diff --git a/src/promql/src/range_eval.rs b/src/promql/src/range_eval.rs index 6ea531043d8..b225f893ca7 100644 --- a/src/promql/src/range_eval.rs +++ b/src/promql/src/range_eval.rs @@ -162,6 +162,11 @@ pub struct RangeEvaluator { /// so a test comparing only output could not tell which one ran. #[cfg(test)] batch_calls: usize, + /// Grid points examined so far to find the end of a decided run in the tail of a round. + /// Test-only: a search and the walk it replaced find the same end, so a test comparing only + /// the pieces could not tell how much of the grid a round touched. + #[cfg(test)] + decided_scans: usize, } /// Windows accumulated for the next batch call: one list per field. @@ -548,6 +553,8 @@ impl RangeEvaluator { pull_budget: usize::MAX, #[cfg(test)] batch_calls: 0, + #[cfg(test)] + decided_scans: 0, }) } @@ -566,6 +573,13 @@ impl RangeEvaluator { self.batch_calls } + /// Grid points examined so far to find the end of a decided run. Test-only: any search finds + /// the same end as the walk it replaced, so only a count can tell the two apart. + #[cfg(test)] + pub(crate) fn decided_scan_count(&self) -> usize { + self.decided_scans + } + /// Schema of the evaluated series: the input fields on the evaluation grid. pub fn output_schema(&self) -> &Arc { &self.output_schema @@ -1238,14 +1252,20 @@ impl RangeEvaluator { let completed = if empty_tail { match self.replay { Replay::PerPoint => { - let mut decided = state.cursor; - if let Some(ready) = ready { - while decided < points_read && i128::from(grid[decided]) <= ready { - decided += 1; + let decided = match ready { + Some(ready) => { + state.cursor + + settled_run( + grid, + state.cursor, + points_read, + ready, + #[cfg(test)] + &mut self.decided_scans, + ) } - } else { - decided = points_read; - } + None => points_read, + }; // A bounded round reports at most its budget of these settled points; the rest // are decided by the pieces that follow. Later rounds start from here either // way, and none of these points can gain a value, so the cursor may skip them. @@ -1358,6 +1378,39 @@ fn zero_budget() -> DataFusionError { DataFusionError::Execution("a pull budget must be positive, got 0".into()) } +/// The number of leading grid points from `start` up to `end` whose timestamp is at or before +/// `bound`: the run of points a round settles without evaluating them. +/// +/// The grid is sorted, so the run ends where a search puts it. Walking to that end instead costs a +/// step per point, and a bounded round would pay the whole distance to the bound on every piece +/// rather than the rows it reports: the piece that follows restarts at the cursor and walks to the +/// same far end again. +fn settled_run( + grid: &[i64], + start: usize, + end: usize, + bound: i128, + #[cfg(test)] scans: &mut usize, +) -> usize { + // An empty span settles nothing, as a walk over it would: the caller's cursor can sit at the + // end of what the input is read for. + let settled = grid.get(start..end).unwrap_or(&[]); + #[cfg(test)] + let mut examined = 0; + let run = settled.partition_point(|×tamp| { + #[cfg(test)] + { + examined += 1; + } + i128::from(timestamp) <= bound + }); + #[cfg(test)] + { + *scans += examined; + } + run +} + /// The offset samples are shifted by: the selector offset, or for `@` the offset that places /// the anchored window at the first grid point. fn fold_offset(grid: GridSpec, window: RangeWindow) -> Result { diff --git a/src/promql/src/range_eval/tests.rs b/src/promql/src/range_eval/tests.rs index 0249c85307a..a3517142c89 100644 --- a/src/promql/src/range_eval/tests.rs +++ b/src/promql/src/range_eval/tests.rs @@ -217,14 +217,6 @@ fn collect_chunks( .collect() } -/// Feeds one whole evaluated series to the chunked entry point as its single closing chunk. -impl RangeEvaluator { - fn push_series(&mut self, series: &Series) -> Result, DataFusionError> { - let chunk = EvaluatedChunk::try_new(series.clone(), true)?; - self.push_evaluated(&chunk) - } -} - /// Folds the chunks of one series back into one series, the way a consumer that keeps every value /// would, and checks the chunk protocol: absolute ranges, never going backwards, all of the same /// series, and one closing chunk last. @@ -1086,6 +1078,64 @@ fn the_pieces_of_one_series_fold_back_to_the_whole_series() { } } +/// A bounded round ends by reporting, one budget at a time, the run of points the input has +/// settled without a value. Finding the end of that run must not walk the distance to the end of +/// the input's bound on every piece: doing so costs about `LEN²/(2 · budget)` comparisons for a +/// tail of `LEN` settled points, and this test fails if that repeating scan comes back. It does +/// not pin a particular search, only that each round's scan stays far below the distance to the +/// bound. +/// +/// A stale marker is what makes the run long and cheap to find: it moves the bound to the last +/// grid point, but it is dropped on the raw path, so every point behind the value at the first one +/// is decided to hold nothing, and no window ever needs a sample again. +#[test] +fn a_bounded_round_does_not_walk_the_settled_tail() { + const BUDGET: usize = 64; + const LEN: usize = 4_096; + let window = RangeWindow { + range_ms: 10, + offset_ms: 0, + anchor_ms: None, + }; + let mut evaluator = probe_evaluator(1, grid(0, 10, LEN as u64), window); + evaluator.set_pull_budget(BUDGET).unwrap(); + let last = 10 * (LEN as i64 - 1); + let rows = chunk( + &[(0, vec![Some(1.0)]), (last, vec![Some(stale())])], + 1, + 0, + false, + ); + + // Every piece with the number of grid points its round examined to find the end of the run. + let mut rounds = Vec::new(); + let mut next = evaluator.push(&rows).unwrap(); + while let Some(piece) = next { + rounds.push(( + piece.range().start(), + piece.range().len(), + evaluator.decided_scan_count(), + )); + next = evaluator.pull(BUDGET).unwrap(); + } + + // The pieces tile the span, so no point is reported twice and none is skipped, and the work of + // no round re-walks the settled tail it already reported past. + let mut end = 0; + let mut examined = 0; + for (index, &(start, len, scanned)) in rounds.iter().enumerate() { + let round = scanned - examined; + examined = scanned; + assert_eq!(start, end, "piece {index} does not continue the span"); + assert!( + round <= 4 * len + 64, + "the round of piece {index} examined {round} grid points to report {len} rows" + ); + end += len; + } + assert_eq!(end, LEN, "the pieces cover every point the input settled"); +} + /// The remaining span of a closed series is handed out by pulling, and the series closes exactly /// once, on the final piece. A second `is_last` would make a consumer close a series twice, and a /// missing one would leave it waiting forever.