diff --git a/src/promql/src/evaluated.rs b/src/promql/src/evaluated.rs index ff2a4a59751..74dad674817 100644 --- a/src/promql/src/evaluated.rs +++ b/src/promql/src/evaluated.rs @@ -52,12 +52,12 @@ impl EvaluatedChunk { Ok(Self { series, is_last }) } - /// The absolute grid range this chunk decided. + /// The absolute grid range this chunk holds rows for. /// - /// Ranges of one series never go backwards and never overlap; together with + /// Ranges of one series never go backwards and never overlap, and they need not be adjacent: + /// the positions between two chunks hold no value. Together with /// [`EvaluatedChunk::is_last`] they say how far the series has been evaluated. An empty range is - /// meaningful: it reports that the chunk closed the series without deciding anything past what - /// was already handed out. + /// meaningful: it reports that the chunk closed the series without holding a row of its own. pub fn range(&self) -> &GridRange { match &self.series.time { TimeAxis::Grid(range) => range, diff --git a/src/promql/src/grid_series.rs b/src/promql/src/grid_series.rs index 881f800110e..f35fa5f4c2e 100644 --- a/src/promql/src/grid_series.rs +++ b/src/promql/src/grid_series.rs @@ -60,8 +60,11 @@ pub struct GridSeriesBuilder { indices: Vec, /// One row per retained row, per field; empty when nothing is buffered. fields: Vec, - /// The buffered rows finalized into shared buffers, with the runs still to hand out. - finished: Option, + /// Batches of finalized rows still to hand out, oldest first. + /// + /// A batch keeps its own buffers because a run's offset indexes the buffers it was finalized + /// with: merging two batches' runs under one `fields` would cut them at the wrong place. + finished: VecDeque, } /// Retained rows turned into field buffers a run can be sliced out of. @@ -113,7 +116,7 @@ impl GridSeriesBuilder { next: 0, indices: Vec::new(), fields: Vec::new(), - finished: None, + finished: VecDeque::new(), }) } @@ -190,8 +193,8 @@ impl GridSeriesBuilder { !self.indices.is_empty() || self .finished - .as_ref() - .is_some_and(|finished| !finished.runs.is_empty()) + .iter() + .any(|finished| !finished.runs.is_empty()) } /// Starts the series the following pushes belong to. @@ -211,7 +214,7 @@ impl GridSeriesBuilder { self.next = 0; self.indices.clear(); self.fields.clear(); - self.finished = None; + self.finished.clear(); } /// Hands out the next run of positions holding a value, or `None` when none is left. @@ -223,18 +226,23 @@ impl GridSeriesBuilder { pub fn take_run(&mut self, metric: MetricName) -> Result> { let exhausted = self .finished - .as_ref() + .front() .is_none_or(|finished| finished.runs.is_empty()); if exhausted && !self.indices.is_empty() { self.finalize()?; } - let Some(finished) = self.finished.as_mut() else { + // The oldest batch is the one whose runs come first on the grid. + let Some(finished) = self.finished.front_mut() else { return Ok(None); }; let Some(run) = finished.runs.pop_front() else { return Ok(None); }; - Self::cut(&self.schema, &self.grid, &metric, &finished.fields, &run).map(Some) + let cut = Self::cut(&self.schema, &self.grid, &metric, &finished.fields, &run)?; + if self.finished.front().is_some_and(|f| f.runs.is_empty()) { + self.finished.pop_front(); + } + Ok(Some(cut)) } /// Returns every piece the pushed rows make up and resets the builder for the next series. @@ -242,22 +250,25 @@ impl GridSeriesBuilder { /// One piece per maximal run of consecutive positions holding a value; an empty vector when /// no pushed row held one. pub fn finish(&mut self, metric: MetricName) -> Result> { + // Rows pushed since the last finalization become one more batch; every batch is cut + // against its own buffers, so the pieces an earlier `take_run` left behind reach the + // caller too. if !self.indices.is_empty() { self.finalize()?; } self.next = 0; - let Some(finished) = self.finished.take() else { - return Ok(Vec::new()); - }; - let mut pieces = Vec::with_capacity(finished.runs.len()); - for run in finished.runs { - pieces.push(Self::cut( - &self.schema, - &self.grid, - &metric, - &finished.fields, - &run, - )?); + let mut pieces = Vec::new(); + // Batches in the order they were pushed, each cut against its own buffers. + for finished in std::mem::take(&mut self.finished) { + for run in finished.runs { + pieces.push(Self::cut( + &self.schema, + &self.grid, + &metric, + &finished.fields, + &run, + )?); + } } Ok(pieces) } @@ -282,7 +293,7 @@ impl GridSeriesBuilder { let fields = SeriesFields::try_from_vec(samples).map_err(external)?; let runs = runs_of(&self.indices); self.indices.clear(); - self.finished = Some(Finished { fields, runs }); + self.finished.push_back(Finished { fields, runs }); Ok(()) } diff --git a/src/promql/src/grid_series/tests.rs b/src/promql/src/grid_series/tests.rs index 8186603e0ec..c93fed599af 100644 --- a/src/promql/src/grid_series/tests.rs +++ b/src/promql/src/grid_series/tests.rs @@ -335,3 +335,41 @@ fn one_builder_serves_several_series() { assert!(second.iter().all(|piece| piece.metric == metric(1))); assert!(!builder.has_pending()); } + +/// Mixing `take_run` with more pushes and then `finish` keeps every piece: `finish` hands out what +/// the earlier `take_run` left behind before cutting the rows pushed since. +#[test] +fn finish_keeps_the_pieces_an_earlier_take_left_behind() { + let mut builder = GridSeriesBuilder::try_new(grid_schema(1, 20)).unwrap(); + builder.push(0, &[Some(1.0)]).unwrap(); + builder.push(5, &[Some(2.0)]).unwrap(); + builder.push(9, &[Some(3.0)]).unwrap(); + + let taken = builder.take_run(metric(0)).unwrap().expect("a piece"); + assert_eq!(piece_ranges(&[taken]), vec![(0, 1)]); + + // More rows after a piece was taken: they finalize into their own buffers, so the pieces still + // queued from the first batch must not be dropped on the way. + builder.push(15, &[Some(4.0)]).unwrap(); + let rest = builder.finish(metric(0)).unwrap(); + assert_eq!( + piece_ranges(&rest), + vec![(5, 1), (9, 1), (15, 1)], + "finish dropped the pieces an earlier take_run left pending" + ); + // The values, not only the ranges: each piece is cut from the buffer its own rows went into, + // so a piece cut from the wrong batch would carry another position's value. + let values: Vec = rest + .iter() + .map(|piece| match piece.fields.as_slice()[0].dense() { + Some(DenseSamplesRef::Float(values)) => values.value(0), + _ => panic!("expected float samples"), + }) + .collect(); + assert_eq!( + values, + vec![2.0, 3.0, 4.0], + "a piece carries the wrong batch's value" + ); + assert!(!builder.has_pending()); +} diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index 750c8b84e16..d75768b1a3c 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -592,6 +592,14 @@ impl RangeEvaluator { "evaluated series does not match the input schema".into(), )); } + // A run of no positions carries no sample and decides nothing, so it is not input: the + // closing chunk of a series that produced nothing travels as an `EvaluatedChunk` to the + // operators, not as a run pushed here. Reading its last timestamp would panic. + if range.is_empty() { + return Err(DataFusionError::Execution( + "evaluated range input holds no position".into(), + )); + } let last_ts = range.timestamps()[range.len() - 1]; match &mut self.series { None => { diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index 2420143d34f..9c1792d2f99 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -2930,3 +2930,27 @@ fn evaluated_histograms_drop_counter_reset_hints() { SampleRef::Float(resets) if resets == 0.0 )); } + +/// A run holding no position is refused rather than panicking: it carries no sample and decides +/// nothing, so it is not input to a window. +#[test] +fn an_empty_run_is_refused_not_indexed() { + // A closing chunk of a series that produced nothing: a grid range of no positions. + let time = GridRange::try_new(grid(0, 1, 4), 0, 0).unwrap(); + let fields = SeriesFields::try_from_vec(vec![Samples::from_float(Float64Array::from(Vec::< + f64, + >::new( + )))]) + .unwrap(); + let empty = Series::try_new( + &SeriesSchema { + fields: raw_schema(1).fields.clone(), + eval_grid: Some(grid(0, 1, 4)), + }, + metric(0), + TimeAxis::Grid(time), + fields, + ) + .unwrap(); + execution_error(probe_evaluator(1, grid(0, 10, 4), one_ms()).push_series(&empty, true)); +}