mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 13:44:03 +00:00
perf(promql): consume evaluated series chunk by chunk
`RangeEvaluator::push_evaluated` takes the next chunk of one evaluated series instead of one whole series, so an evaluator can sit downstream of another one: the first chunk opens the series with its labels, each later one continues exactly where the previous ended, and the one marked `is_last` closes it. The first chunk may begin at any position of the input grid. A producer that trims its output to the rows holding a value starts at its first such row; the positions before it carry no sample rather than a missing one, so reporting them as decided is correct and a window over them can never gain a sample. `SeriesState` grows an `input_end`: a chunk's range indexes the *input* grid while `cursor` and `completed` index the *output* grid, and the two differ exactly when the input is itself evaluated. `map::map_chunk` applies a map chain to a chunk and always keeps the input chunk's decided range and its `is_last`; a chain that yields no value still reports the positions it settled. A chain without kernels is the identity on the whole chunk, labels included: every chunk of one series has to agree on them. Signed-off-by: discord9 <discord9@users.noreply.github.com> Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
@@ -37,7 +37,9 @@ use datatypes::series::samples::{
|
||||
};
|
||||
use datatypes::series::time::{GridRange, TimeAxis};
|
||||
|
||||
use crate::evaluated::EvaluatedChunk;
|
||||
use crate::functions::Round;
|
||||
use crate::grid_series::{GridSeriesBuilder, METADATA_LABELS};
|
||||
|
||||
/// Float math supported by the evaluated-series kernel.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -132,6 +134,115 @@ pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Op
|
||||
Ok(Some(output))
|
||||
}
|
||||
|
||||
/// Applies the map kernels `ops` to one evaluated chunk, in order.
|
||||
///
|
||||
/// The returned chunk always covers the input chunk's decided range and keeps its `is_last`; a
|
||||
/// chain that maps every value away delivers missing values, not a shorter range. A kernel
|
||||
/// dropping values is a property of the values, not of how far evaluation has progressed, so the
|
||||
/// positions the chunk decided still travel with it and its consumer still advances. Trimming the
|
||||
/// result to the rows holding a value, as the output does, is a separate stage.
|
||||
///
|
||||
/// At least one kernel rewrites the labels as [`map_math`] does, so with one the metadata labels
|
||||
/// are dropped even from a chunk without any value to map. A chain without kernels maps nothing,
|
||||
/// so it is the identity on the whole chunk and returns its labels unchanged: a consumer of the
|
||||
/// series reads the chunks of one series as one series only while they agree on them. Raw time
|
||||
/// axes are rejected.
|
||||
pub fn map_chunk(
|
||||
schema: &SeriesSchema,
|
||||
chunk: &EvaluatedChunk,
|
||||
ops: &[MathOp],
|
||||
) -> Result<EvaluatedChunk> {
|
||||
let TimeAxis::Grid(range) = &chunk.series.time else {
|
||||
return Err(DataFusionError::Execution(
|
||||
"Map math requires an evaluated grid time axis".into(),
|
||||
));
|
||||
};
|
||||
if ops.is_empty() {
|
||||
// No kernel maps anything, so the chunk is already its own result. Returning it before the
|
||||
// labels are rewritten keeps the whole chunk -- labels, range and end -- exactly as it came
|
||||
// in, which a consumer of the series requires: every chunk of one series has to carry the
|
||||
// same labels, and a chain without kernels must not relabel the zero-length chunk that
|
||||
// closes a series differently from the chunk before it.
|
||||
return EvaluatedChunk::try_new(chunk.series.clone(), chunk.is_last);
|
||||
}
|
||||
let mut metric = chunk.series.metric.clone();
|
||||
metric.remove_all(&METADATA_LABELS);
|
||||
if range.is_empty() {
|
||||
// Nothing left to map, but the labels of the series are still rewritten.
|
||||
let mut series = chunk.series.clone();
|
||||
series.metric = metric;
|
||||
return EvaluatedChunk::try_new(series, chunk.is_last);
|
||||
}
|
||||
// Each kernel maps the result of the previous one. A kernel that maps every value away ends
|
||||
// the chain: there is no value left for the next one to map.
|
||||
let mut mapped = Some(chunk.series.clone());
|
||||
for op in ops {
|
||||
let Some(series) = mapped.take() else {
|
||||
break;
|
||||
};
|
||||
mapped = map_math(schema, &series, *op)?;
|
||||
}
|
||||
if let Some(mapped) = &mapped
|
||||
&& let TimeAxis::Grid(mapped_range) = &mapped.time
|
||||
&& mapped_range == range
|
||||
{
|
||||
// The chain did not move the ends of the series, so it is already the chunk.
|
||||
return EvaluatedChunk::try_new(mapped.clone(), chunk.is_last);
|
||||
}
|
||||
|
||||
// The chain trimmed rows off one or both ends, or dropped every value. Place its rows back at
|
||||
// the offset they kept and hold the span open to the input chunk's ends.
|
||||
let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
|
||||
builder.cover_from(range.start())?;
|
||||
if let Some(mapped) = &mapped {
|
||||
let TimeAxis::Grid(mapped_range) = &mapped.time else {
|
||||
return Err(DataFusionError::Execution(
|
||||
"Map math requires an evaluated grid time axis".into(),
|
||||
));
|
||||
};
|
||||
let offset = mapped_range
|
||||
.start()
|
||||
.checked_sub(range.start())
|
||||
.ok_or_else(|| {
|
||||
DataFusionError::Execution(format!(
|
||||
"mapped series begins at {} before its input chunk at {}",
|
||||
mapped_range.start(),
|
||||
range.start()
|
||||
))
|
||||
})?;
|
||||
// One cursor per field, for the reason `map_math` advances iterators rather than calling
|
||||
// `sample(row)`.
|
||||
let mut cursors = mapped
|
||||
.fields
|
||||
.iter()
|
||||
.map(|samples| samples.iter())
|
||||
.collect::<Vec<_>>();
|
||||
let mut values = vec![None; mapped.fields.len()];
|
||||
for row in 0..mapped_range.len() {
|
||||
for (value, cursor) in values.iter_mut().zip(cursors.iter_mut()) {
|
||||
*value = match cursor.next() {
|
||||
// A mapped field holds no histogram, so anything else stays missing.
|
||||
Some(SampleRef::Float(value)) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
builder.push(range.start() + offset + row, &values)?;
|
||||
}
|
||||
}
|
||||
builder.cover_through(range.start() + range.len())?;
|
||||
// `cover_from` opens the span for every non-empty range, and the empty one returned above, so
|
||||
// the builder always hands back the series it spans. Refuse to report a shorter range than the
|
||||
// chunk decided rather than take a wrong answer here should that ever stop holding.
|
||||
let Some(series) = builder.finish(metric)? else {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"mapped chunk lost the positions {}..{} it decided",
|
||||
range.start(),
|
||||
range.start() + range.len()
|
||||
)));
|
||||
};
|
||||
EvaluatedChunk::try_new(series, chunk.is_last)
|
||||
}
|
||||
|
||||
/// Negates every float field and drops the metric name, like Prometheus' unary minus.
|
||||
///
|
||||
/// Shares the evaluated-grid, missingness, unsupported-type and same-labelset contract of
|
||||
|
||||
@@ -260,10 +260,15 @@ fn flush_batch(
|
||||
}
|
||||
|
||||
struct SeriesState {
|
||||
/// `None` for evaluated input, which arrives as one complete series.
|
||||
/// `None` for evaluated input, which is identified by its labels instead of a primary key.
|
||||
primary_key: Option<Buffer>,
|
||||
metric: MetricName,
|
||||
last_ts: i64,
|
||||
/// Grid index after the last input position consumed. The chunks of one evaluated series tile
|
||||
/// the input grid, so this is where the next one has to start. Unlike `completed`, it counts
|
||||
/// positions of the *input* grid, which is a different grid whenever the input is itself
|
||||
/// evaluated.
|
||||
input_end: usize,
|
||||
/// Next grid index to evaluate.
|
||||
cursor: usize,
|
||||
/// Grid index after the last position the evaluator has decided, whether it holds a value or
|
||||
@@ -567,39 +572,97 @@ impl RangeEvaluator {
|
||||
self.close_series()
|
||||
}
|
||||
|
||||
/// Evaluates one complete evaluated series, such as the inner result of a subquery: the
|
||||
/// value at each grid point is a sample at that time. Stale markers are kept as values,
|
||||
/// Consumes the next chunk of one evaluated series, such as the inner result of a subquery:
|
||||
/// the value at each grid point is a sample at that time. Stale markers are kept as values,
|
||||
/// since the input is computed.
|
||||
///
|
||||
/// The input arrives complete, so its result is one closing chunk.
|
||||
pub fn push_series(&mut self, series: &Series) -> Result<Option<EvaluatedChunk>> {
|
||||
let TimeAxis::Grid(range) = &series.time else {
|
||||
/// The first chunk opens the series with its labels, each later one starts exactly where the
|
||||
/// previous one ended, and the one marked `is_last` closes it. The first chunk may begin at any
|
||||
/// position of the input grid: a producer that trims its output starts at its first row
|
||||
/// holding a value, and the positions before it carry no sample rather than a missing one.
|
||||
///
|
||||
/// A chunk reports the positions it decided, whether they hold a value or not, so a position
|
||||
/// an inner evaluation settled without a result crosses this layer too; as on the raw path,
|
||||
/// what became final is handed out and the closing chunk always is. An empty chunk decides
|
||||
/// nothing and is only legal as that closing chunk.
|
||||
///
|
||||
/// The evaluator must not be reused after an error.
|
||||
pub fn push_evaluated(&mut self, chunk: &EvaluatedChunk) -> Result<Option<EvaluatedChunk>> {
|
||||
if self.input_grid.is_none() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"evaluated range input must be a grid series".into(),
|
||||
"evaluated chunk pushed to an evaluator of raw series".into(),
|
||||
));
|
||||
}
|
||||
let TimeAxis::Grid(range) = &chunk.series.time else {
|
||||
return Err(DataFusionError::Execution(
|
||||
"an evaluated chunk must be addressed on a grid".into(),
|
||||
));
|
||||
};
|
||||
if self.input_grid != Some(range.grid().spec())
|
||||
|| series.fields.len() != self.fields.len()
|
||||
|| series.fields.iter().any(|field| field.len() != range.len())
|
||||
|| chunk.series.fields.len() != self.fields.len()
|
||||
|| chunk
|
||||
.series
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| field.len() != range.len())
|
||||
{
|
||||
return Err(DataFusionError::Execution(
|
||||
"evaluated series does not match the input schema".into(),
|
||||
"evaluated chunk does not match the input schema".into(),
|
||||
));
|
||||
}
|
||||
if self.series.is_some() {
|
||||
return Err(DataFusionError::Execution(
|
||||
"evaluated series pushed inside a raw series".into(),
|
||||
));
|
||||
if range.is_empty() && !chunk.is_last {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"empty evaluated chunk at {} that does not close its series",
|
||||
range.start()
|
||||
)));
|
||||
}
|
||||
// Every chunk after the first has to continue exactly where the previous one ended, so the
|
||||
// positions of one series never repeat or leave a gap. The first chunk is not constrained:
|
||||
// a producer that trims its output to the rows holding a value begins at its first such
|
||||
// row, and the positions before it carry no sample rather than a missing one. Reporting
|
||||
// them as decided is still correct, because no input ever arrives there, so a window over
|
||||
// them can never gain a sample.
|
||||
if let Some(state) = &self.series
|
||||
&& range.start() != state.input_end
|
||||
{
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated chunks are out of order: {} does not continue from {}",
|
||||
range.start(),
|
||||
state.input_end
|
||||
)));
|
||||
}
|
||||
if let Some(state) = &self.series {
|
||||
if state.metric != chunk.series.metric {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"evaluated series label set changed before its last chunk: {:?} after {:?}",
|
||||
chunk.series.metric, state.metric
|
||||
)));
|
||||
}
|
||||
} else {
|
||||
self.series = Some(SeriesState {
|
||||
primary_key: None,
|
||||
metric: chunk.series.metric.clone(),
|
||||
last_ts: 0,
|
||||
input_end: 0,
|
||||
cursor: 0,
|
||||
completed: 0,
|
||||
emitted_end: 0,
|
||||
});
|
||||
}
|
||||
self.ingest(&range.timestamps(), &chunk.series.fields, false)?;
|
||||
// Advanced only now: `ingest` may fail on a sample it cannot shift or convert.
|
||||
self.series
|
||||
.as_mut()
|
||||
.expect("opened at the entry of this push")
|
||||
.input_end = range.start() + range.len();
|
||||
if !chunk.is_last {
|
||||
// `ready` is in the shifted sample domain, so it is the last grid timestamp this
|
||||
// chunk carries plus the offset its samples were shifted by: every point up to there
|
||||
// can no longer gain a sample.
|
||||
let last = range.grid().timestamps()[range.start() + range.len() - 1];
|
||||
self.evaluate(Some(i128::from(last) + i128::from(self.window.offset_ms)))?;
|
||||
return self.emit(false);
|
||||
}
|
||||
self.series = Some(SeriesState {
|
||||
primary_key: None,
|
||||
metric: series.metric.clone(),
|
||||
last_ts: 0,
|
||||
cursor: 0,
|
||||
completed: 0,
|
||||
emitted_end: 0,
|
||||
});
|
||||
self.ingest(&range.timestamps(), &series.fields, false)?;
|
||||
self.close_series()
|
||||
}
|
||||
|
||||
@@ -703,6 +766,7 @@ impl RangeEvaluator {
|
||||
primary_key: Some(chunk.primary_key.clone()),
|
||||
metric,
|
||||
last_ts: time[time.len() - 1],
|
||||
input_end: 0,
|
||||
cursor: 0,
|
||||
completed: 0,
|
||||
emitted_end: 0,
|
||||
|
||||
Reference in New Issue
Block a user