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_series` read one whole evaluated series, so an evaluator could not sit downstream of another one: the inner layer only produced its series at the end, and the outer layer then evaluated it in one go. That is the shape a composed `Window -> Map -> Window` chain cannot have, and it is also what forced the inner result to be fully materialized before the outer one started. `push_evaluated(&EvaluatedChunk)` replaces it. A chunk is consumed as it arrives: the first opens the series with its labels, each later one starts 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, because 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 the correct answer 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 an evaluated series. Sharing one counter would have accepted chunks that skip positions. `map::map_chunk` applies a map chain to a chunk and always keeps the input chunk's decided range and its `is_last`. A float map over all-histogram points produces no value at all, and dropping such a chunk would tell the consumer the series had not advanced and, on the closing one, that it had not ended. The map is a property of the values, not of how far evaluation got; trimming to the valued rows stays where it belongs, in the output stage, which still emits no batch for a chunk without a value. `FusedSeriesExec` calls `map_chunk` directly, so `apply_maps` is gone. Signed-off-by: discord9 <discord9@users.noreply.github.com> Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
@@ -81,7 +81,7 @@ use datatypes::series::{MetricName, SeriesOrdering};
|
||||
use futures::Stream;
|
||||
use store_api::region_engine::{RawLabelSource, SendableRawSeriesStream};
|
||||
|
||||
use crate::map::{MathOp, map_math};
|
||||
use crate::map::{MathOp, map_chunk};
|
||||
use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow};
|
||||
use crate::source::materialize_raw_labels;
|
||||
|
||||
@@ -595,25 +595,6 @@ fn describe_map(op: MathOp) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies every map kernel in order and returns the final series.
|
||||
///
|
||||
/// The kernels work on typed [`Series`]; the duplicate-label-set check and the conversion into a
|
||||
/// record batch both need the result of this stage, so no batch is built in between.
|
||||
fn apply_maps(
|
||||
evaluator: &RangeEvaluator,
|
||||
maps: &[MathOp],
|
||||
series: Series,
|
||||
) -> Result<Option<Series>> {
|
||||
let mut series = series;
|
||||
for op in maps {
|
||||
let Some(mapped) = map_math(evaluator.output_schema(), &series, *op)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
series = mapped;
|
||||
}
|
||||
Ok(Some(series))
|
||||
}
|
||||
|
||||
/// Maximum number of raw chunks one `poll_next` call consumes before yielding.
|
||||
///
|
||||
/// A child that is always ready can deliver many short-lived series whose evaluation yields no
|
||||
@@ -952,21 +933,26 @@ impl Stream for FusedSeriesStream {
|
||||
evaluator
|
||||
.push(&chunk)
|
||||
.and_then(|evaluated| match evaluated {
|
||||
Some(evaluated) => apply_maps(evaluator, maps, evaluated.series),
|
||||
// The map chain keeps the chunk's decided range, so a chain that maps
|
||||
// every value away still advances the consumer; `emit` trims it to the
|
||||
// rows holding a value, and a chunk without one produces no batch.
|
||||
Some(evaluated) => {
|
||||
map_chunk(evaluator.output_schema(), &evaluated, maps).map(Some)
|
||||
}
|
||||
None => Ok(None),
|
||||
})
|
||||
};
|
||||
let series = match evaluated {
|
||||
Ok(series) => series,
|
||||
let evaluated = match evaluated {
|
||||
Ok(evaluated) => evaluated,
|
||||
Err(error) => {
|
||||
this.abort();
|
||||
return Poll::Ready(Some(Err(error)));
|
||||
}
|
||||
};
|
||||
let Some(series) = series else {
|
||||
let Some(evaluated) = evaluated else {
|
||||
continue;
|
||||
};
|
||||
return match this.emit(&series) {
|
||||
return match this.emit(&evaluated.series) {
|
||||
Ok(Some(batch)) => Poll::Ready(Some(Ok(batch))),
|
||||
// The chunk settled only positions without a value, so it produces no row and
|
||||
// the loop keeps consuming input.
|
||||
|
||||
@@ -57,10 +57,9 @@ use store_api::region_engine::RawLabelSource;
|
||||
use crate::grid_series::reference::OwnedHistogram;
|
||||
|
||||
use super::{
|
||||
FusedSeriesExec, MAX_CHUNKS_PER_POLL, apply_maps, classify_output, series_to_record_batch,
|
||||
trim_to_values,
|
||||
FusedSeriesExec, MAX_CHUNKS_PER_POLL, classify_output, series_to_record_batch, trim_to_values,
|
||||
};
|
||||
use crate::map::MathOp;
|
||||
use crate::map::{MathOp, map_chunk};
|
||||
use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow};
|
||||
|
||||
const TIME: &str = "time";
|
||||
@@ -354,12 +353,12 @@ impl Case {
|
||||
let Some(evaluated) = evaluator.push(chunk).unwrap() else {
|
||||
continue;
|
||||
};
|
||||
let Some(series) = apply_maps(&evaluator, &self.maps, evaluated.series).unwrap() else {
|
||||
continue;
|
||||
};
|
||||
let evaluated = map_chunk(evaluator.output_schema(), &evaluated, &self.maps).unwrap();
|
||||
// The node trims a chunk to the rows holding a value before emitting it, because the
|
||||
// chunk's span reports decided positions rather than valued ones.
|
||||
let Some(series) = trim_to_values(evaluator.output_schema(), &series).unwrap() else {
|
||||
let Some(series) =
|
||||
trim_to_values(evaluator.output_schema(), &evaluated.series).unwrap()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let batch =
|
||||
|
||||
@@ -28,6 +28,7 @@ use datatypes::series::samples::{
|
||||
};
|
||||
use datatypes::series::time::TimeAxis;
|
||||
|
||||
use crate::evaluated::EvaluatedChunk;
|
||||
use crate::functions::Round;
|
||||
use crate::grid_series::{GridSeriesBuilder, METADATA_LABELS};
|
||||
|
||||
@@ -139,6 +140,104 @@ pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Op
|
||||
builder.finish(metric)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// The labels are rewritten as [`map_math`] does, so the metadata labels are dropped even from a
|
||||
/// chunk without any value to map. 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(),
|
||||
));
|
||||
};
|
||||
let mut metric = chunk.series.metric.clone();
|
||||
metric.remove_all(&METADATA_LABELS);
|
||||
if range.is_empty() {
|
||||
// Nothing 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)
|
||||
}
|
||||
|
||||
/// The float math `op` applies to one value.
|
||||
fn apply(op: MathOp, value: f64) -> f64 {
|
||||
match op {
|
||||
|
||||
@@ -254,10 +254,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
|
||||
@@ -525,39 +530,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()
|
||||
}
|
||||
|
||||
@@ -661,6 +724,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,
|
||||
|
||||
@@ -51,6 +51,7 @@ use crate::grid_series::reference::{
|
||||
};
|
||||
use crate::grid_series::{GridSample, GridSeriesBuilder};
|
||||
use crate::histogram_eval::float_histogram::FloatHistogram;
|
||||
use crate::map::{MathOp, map_chunk};
|
||||
use crate::range_array::RangeArray;
|
||||
use crate::select::{LabelMatcher, MatchOp, absent, absent_labels};
|
||||
|
||||
@@ -1397,6 +1398,7 @@ fn subquery_series_match_references() {
|
||||
let (Some(series), rows) = random_evaluated(&mut rng, &inner, fields, seed) else {
|
||||
continue;
|
||||
};
|
||||
let whole = EvaluatedChunk::try_new(series, true).unwrap();
|
||||
let mut probe = RangeEvaluator::with_kernel(
|
||||
&schema,
|
||||
outer.clone(),
|
||||
@@ -1408,7 +1410,7 @@ fn subquery_series_match_references() {
|
||||
.unwrap();
|
||||
let expected = reference(&rows, &outer, window, fields, false, true);
|
||||
let evaluated = probe
|
||||
.push_series(&series)
|
||||
.push_evaluated(&whole)
|
||||
.unwrap()
|
||||
.expect("the input closes");
|
||||
assert!(evaluated.is_last);
|
||||
@@ -1419,7 +1421,7 @@ fn subquery_series_match_references() {
|
||||
RangeEvaluator::try_new(&schema, outer.clone(), window, function).unwrap();
|
||||
let expected = udf_reference(function, &rows, &outer, window, fields, false);
|
||||
let evaluated = evaluator
|
||||
.push_series(&series)
|
||||
.push_evaluated(&whole)
|
||||
.unwrap()
|
||||
.expect("the input closes");
|
||||
let result = fold_chunks(std::slice::from_ref(&evaluated), evaluator.output_schema());
|
||||
@@ -1471,7 +1473,8 @@ fn rejects_input_of_the_other_kind() {
|
||||
let mut builder = GridSeriesBuilder::try_new(Arc::new(evaluated)).unwrap();
|
||||
builder.push(0, &[Some(1.0)]).unwrap();
|
||||
let series = builder.finish(metric(0)).unwrap().unwrap();
|
||||
execution_error(probe_evaluator(1, grid(0, 10, 4), window).push_series(&series));
|
||||
let chunk = EvaluatedChunk::try_new(series, true).unwrap();
|
||||
execution_error(probe_evaluator(1, grid(0, 10, 4), window).push_evaluated(&chunk));
|
||||
}
|
||||
|
||||
/// The range function a golden fixture names, with its constant arguments.
|
||||
@@ -2211,9 +2214,231 @@ fn evaluated_histograms_drop_counter_reset_hints() {
|
||||
};
|
||||
let mut evaluator =
|
||||
RangeEvaluator::try_new(&schema, grid(10, 10, 1), window, RangeFunction::Resets).unwrap();
|
||||
let result = evaluator.push_series(&series).unwrap().unwrap().series;
|
||||
let chunk = EvaluatedChunk::try_new(series, true).unwrap();
|
||||
let result = evaluator.push_evaluated(&chunk).unwrap().unwrap().series;
|
||||
assert!(matches!(
|
||||
result.fields.as_slice()[0].sample(0),
|
||||
SampleRef::Float(resets) if resets == 0.0
|
||||
));
|
||||
}
|
||||
|
||||
/// An evaluator of evaluated input: `input_grid` is the grid of the inner result it reads, and
|
||||
/// `grid` the grid it reports on.
|
||||
fn evaluated_evaluator(
|
||||
input_grid: Arc<EvalGrid>,
|
||||
grid: Arc<EvalGrid>,
|
||||
window: RangeWindow,
|
||||
) -> RangeEvaluator {
|
||||
let schema = SeriesSchema {
|
||||
fields: raw_schema(1).fields,
|
||||
eval_grid: Some(input_grid),
|
||||
};
|
||||
RangeEvaluator::with_kernel(&schema, grid, window, Box::new(probe), true, true).unwrap()
|
||||
}
|
||||
|
||||
/// The inner layer of the chunked-consumption tests: one raw series on a 10 ms grid, pushed in
|
||||
/// three chunks and evaluated on that same grid.
|
||||
fn inner_layer() -> (RangeEvaluator, Vec<EvaluatedChunk>) {
|
||||
let window = RangeWindow {
|
||||
range_ms: 30,
|
||||
offset_ms: 0,
|
||||
anchor_ms: None,
|
||||
};
|
||||
let mut inner = probe_evaluator(1, grid(0, 10, 8), window);
|
||||
let rows: Vec<Row> = vec![
|
||||
(0, vec![Some(1.0)]),
|
||||
(10, vec![Some(2.0)]),
|
||||
(30, vec![Some(4.0)]),
|
||||
(50, vec![Some(6.0)]),
|
||||
(70, vec![Some(8.0)]),
|
||||
];
|
||||
let pieces = [
|
||||
chunk(&rows[..2], 1, 0, false),
|
||||
chunk(&rows[2..3], 1, 0, false),
|
||||
chunk(&rows[3..], 1, 0, true),
|
||||
];
|
||||
let chunks = collect_chunks(&mut inner, &pieces);
|
||||
(inner, chunks)
|
||||
}
|
||||
|
||||
/// The grid of the outer layer of the chunked-consumption tests: other start, other step, so it
|
||||
/// shares no position with the inner one.
|
||||
fn outer_grid() -> Arc<EvalGrid> {
|
||||
grid(5, 20, 4)
|
||||
}
|
||||
|
||||
/// The window the outer layer of the chunked-consumption tests reads its input with.
|
||||
fn outer_window() -> RangeWindow {
|
||||
RangeWindow {
|
||||
range_ms: 40,
|
||||
offset_ms: 0,
|
||||
anchor_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A chunk whose span is `start..start + values.len()`, every position of it decided.
|
||||
fn values_chunk(
|
||||
schema: &Arc<SeriesSchema>,
|
||||
start: usize,
|
||||
values: &[Option<f64>],
|
||||
is_last: bool,
|
||||
) -> EvaluatedChunk {
|
||||
let mut builder = GridSeriesBuilder::try_new(schema.clone()).unwrap();
|
||||
builder.cover_from(start).unwrap();
|
||||
for (offset, value) in values.iter().enumerate() {
|
||||
builder.push(start + offset, &[*value]).unwrap();
|
||||
}
|
||||
builder.cover_through(start + values.len()).unwrap();
|
||||
let series = builder.finish(metric(0)).unwrap().expect("covered above");
|
||||
EvaluatedChunk::try_new(series, is_last).unwrap()
|
||||
}
|
||||
|
||||
/// Pushing the chunks of one series one at a time must equal pushing the whole series at once:
|
||||
/// the state a later chunk needs (retained samples, resets, decided positions) survives the
|
||||
/// handover. Each layer is on its own grid, so neither can pass by reusing the other's indices.
|
||||
#[test]
|
||||
fn a_series_pushed_in_chunks_matches_the_whole_series() {
|
||||
let (inner, inner_chunks) = inner_layer();
|
||||
let mut chunked = evaluated_evaluator(grid(0, 10, 8), outer_grid(), outer_window());
|
||||
let pushed: Vec<_> = inner_chunks
|
||||
.iter()
|
||||
.filter_map(|piece| chunked.push_evaluated(piece).unwrap())
|
||||
.collect();
|
||||
|
||||
let whole = EvaluatedChunk::try_new(
|
||||
fold_chunks(&inner_chunks, inner.output_schema()).expect("the inner series has values"),
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
let mut at_once = evaluated_evaluator(grid(0, 10, 8), outer_grid(), outer_window());
|
||||
let once: Vec<_> = at_once
|
||||
.push_evaluated(&whole)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
let expected = fold_chunks(&once, at_once.output_schema()).expect("the input closes");
|
||||
let result = fold_chunks(&pushed, chunked.output_schema());
|
||||
assert_series_eq(result.as_ref(), &expand(&expected), &metric(0));
|
||||
}
|
||||
|
||||
/// A chunk is indexed on the grid of the layer that produced it, and that index is absolute:
|
||||
/// reading it on another grid reports positions of that other grid, which only ever increase.
|
||||
#[test]
|
||||
fn a_chunk_indexed_on_the_inner_grid_is_absolute_on_the_outer_one() {
|
||||
let (_, inner_chunks) = inner_layer();
|
||||
let mut outer = evaluated_evaluator(grid(0, 10, 8), outer_grid(), outer_window());
|
||||
let chunks: Vec<_> = inner_chunks
|
||||
.iter()
|
||||
.filter_map(|piece| outer.push_evaluated(piece).unwrap())
|
||||
.collect();
|
||||
|
||||
// Without more than one chunk the monotonicity below would hold for free.
|
||||
assert!(chunks.len() > 1, "{} outer chunks", chunks.len());
|
||||
for chunk in &chunks {
|
||||
assert_eq!(
|
||||
chunk.range().grid().spec(),
|
||||
outer_grid().spec(),
|
||||
"a chunk is addressed on the outer grid"
|
||||
);
|
||||
}
|
||||
let starts: Vec<_> = chunks.iter().map(|chunk| chunk.range().start()).collect();
|
||||
assert!(
|
||||
starts.windows(2).all(|pair| pair[0] < pair[1]),
|
||||
"positions restart or go back: {starts:?}"
|
||||
);
|
||||
let last = chunks.last().expect("checked above");
|
||||
assert_eq!(
|
||||
last.range().start() + last.range().len(),
|
||||
outer_grid().timestamps().len(),
|
||||
"the outer series reached its end"
|
||||
);
|
||||
}
|
||||
|
||||
/// A chunk whose values a float map chain removes keeps its range: the positions were decided, and
|
||||
/// a consumer advances on decided positions, not on the ones that happened to hold a value.
|
||||
#[test]
|
||||
fn a_map_that_removes_every_value_still_delivers_its_range() {
|
||||
// Native histogram points have no float for a float map to produce, so `abs` empties this
|
||||
// chunk without any value having been missing from the input.
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: raw_schema(1).fields,
|
||||
eval_grid: Some(grid(0, 10, 2)),
|
||||
});
|
||||
let reset = "0/0/0/4014000000000000/4014000000000000/1/0_1/4014000000000000///";
|
||||
let histograms = BTreeMap::from([(0, reset.to_string()), (1, reset.to_string())]);
|
||||
let labels = BTreeMap::from([("job".to_string(), "x".to_string())]);
|
||||
let series = mixed_series(&schema, &labels, &BTreeMap::new(), &histograms).unwrap();
|
||||
let chunk = EvaluatedChunk::try_new(series, true).unwrap();
|
||||
|
||||
let mapped = map_chunk(&schema, &chunk, &[MathOp::Abs]).unwrap();
|
||||
assert_eq!((mapped.range().start(), mapped.range().len()), (0, 2));
|
||||
assert!(mapped.is_last);
|
||||
assert!(all_missing(&mapped.series));
|
||||
|
||||
let mut downstream = evaluated_evaluator(grid(0, 10, 2), grid(0, 10, 2), outer_window());
|
||||
let closed = downstream
|
||||
.push_evaluated(&mapped)
|
||||
.unwrap()
|
||||
.expect("the last chunk closes its series");
|
||||
assert!(closed.is_last);
|
||||
assert_eq!(closed.range().start() + closed.range().len(), 2);
|
||||
downstream.finish().expect("the series closed");
|
||||
}
|
||||
|
||||
/// A chunk that starts before the previous one ended is rejected instead of being placed at the
|
||||
/// wrong positions.
|
||||
#[test]
|
||||
fn an_out_of_order_chunk_is_rejected() {
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: raw_schema(1).fields,
|
||||
eval_grid: Some(grid(0, 10, 6)),
|
||||
});
|
||||
let mut outer = evaluated_evaluator(grid(0, 10, 6), outer_grid(), outer_window());
|
||||
let first = values_chunk(&schema, 0, &[Some(1.0), Some(2.0)], false);
|
||||
outer.push_evaluated(&first).unwrap();
|
||||
|
||||
let late = values_chunk(&schema, 3, &[Some(3.0)], true);
|
||||
let error = outer.push_evaluated(&late).unwrap_err();
|
||||
assert!(
|
||||
matches!(&error, DataFusionError::Execution(message)
|
||||
if message.contains("3") && message.contains("2")),
|
||||
"{error:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A series may begin past the first position of its grid, and its consumer must accept it.
|
||||
///
|
||||
/// A producer that trims its output to the rows holding a value starts at the first such row, so
|
||||
/// the positions before it carry no sample at all rather than a missing one. The consumer still
|
||||
/// reports them as decided, and that is the right answer: a window over them can never contain a
|
||||
/// sample, because the input never delivers one there. The first chunk is therefore free to start
|
||||
/// anywhere, and only the later ones have to continue exactly where the previous one ended.
|
||||
#[test]
|
||||
fn a_series_may_begin_past_the_first_position_of_its_grid() {
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: raw_schema(1).fields,
|
||||
eval_grid: Some(grid(0, 10, 4)),
|
||||
});
|
||||
let mut late = evaluated_evaluator(grid(0, 10, 4), outer_grid(), outer_window());
|
||||
let from_one = values_chunk(&schema, 1, &[Some(1.0), Some(2.0), Some(3.0)], true);
|
||||
let accepted = late
|
||||
.push_evaluated(&from_one)
|
||||
.expect("a series may start at any position of its grid")
|
||||
.expect("the closing chunk is always handed out");
|
||||
assert!(accepted.is_last);
|
||||
|
||||
// The same series pushed from position 0 has to agree on every position it covers: the late
|
||||
// start is a property of the input, not a different evaluation.
|
||||
let mut whole = evaluated_evaluator(grid(0, 10, 4), outer_grid(), outer_window());
|
||||
let from_zero = values_chunk(&schema, 0, &[None, Some(1.0), Some(2.0), Some(3.0)], true);
|
||||
let expected = whole
|
||||
.push_evaluated(&from_zero)
|
||||
.expect("a missing first sample is not a late start")
|
||||
.expect("the closing chunk is always handed out");
|
||||
// Both forms settle the same positions: the undelivered prefix is reported as decided, which
|
||||
// is why this compares the dense rows instead of going through the trimming assertion.
|
||||
assert_eq!(accepted.range().start(), 0);
|
||||
assert_eq!(accepted.range().len(), 4);
|
||||
assert_eq!(expand(&accepted.series), expand(&expected.series));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user