feat(promql): evaluate @-anchored range windows

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
Dennis Zhuang
2026-10-17 17:20:46 +08:00
parent 7a3cfca086
commit 7dbcac094a
2 changed files with 198 additions and 30 deletions
+140 -23
View File
@@ -32,14 +32,17 @@ mod tests;
pub use function::RangeFunction;
/// The samples a range selector reads at evaluation time `T`:
/// source timestamps in `(T - offset_ms - range_ms, T - offset_ms]`.
/// The samples a range selector reads at evaluation time `T`: source timestamps in
/// `(E - range_ms, E]`, where `E` is `T - offset_ms`, or `anchor_ms - offset_ms` with `@`.
#[derive(Clone, Copy, Debug)]
pub struct RangeWindow {
/// Positive window length in milliseconds.
pub range_ms: i64,
/// Selector offset in milliseconds; positive reads earlier samples.
pub offset_ms: i64,
/// The resolved `@` timestamp in milliseconds, with `start()` and `end()` already replaced
/// by the statement's start and end.
pub anchor_ms: Option<i64>,
}
/// The valid samples of one field inside one window, in source order.
@@ -63,7 +66,9 @@ pub(crate) type WindowKernel = Box<dyn FnMut(FloatWindow<'_>) -> Option<f64> + S
/// windows can still use are retained.
pub struct RangeEvaluator {
grid: Arc<EvalGrid>,
/// The window with `offset_ms` replaced by the offset samples are shifted by.
window: RangeWindow,
replay: Replay,
kernel: WindowKernel,
output_schema: Arc<SeriesSchema>,
output: GridSeriesBuilder,
@@ -80,6 +85,20 @@ struct SeriesState {
cursor: usize,
}
/// How the windows of an `@`-anchored selector map to the grid.
///
/// Like Prometheus, an anchored selector is read once, as the window of the first grid point
/// with the offset rewritten to `start - (anchor - offset)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Replay {
/// Not anchored: every grid point reads its own window.
PerPoint,
/// The first point's result is reported at every point (step-invariant functions).
Once,
/// The first point's window is evaluated at every point (`predict_linear`).
EveryPoint,
}
#[derive(Default)]
struct FieldSamples {
timestamps: Vec<i64>,
@@ -96,27 +115,36 @@ impl RangeEvaluator {
window: RangeWindow,
function: RangeFunction,
) -> Result<Self> {
if let RangeFunction::PredictLinear(_) = function {
let fold_offset = fold_offset(&grid, window)?;
let step_invariant = !matches!(function, RangeFunction::PredictLinear(_));
if !step_invariant {
let spec = grid.spec();
let last =
i128::from(spec.start_ms) + i128::from(spec.step_ms) * (i128::from(spec.len) - 1);
for eval_ts in [i128::from(spec.start_ms), last] {
if i64::try_from(eval_ts + i128::from(window.offset_ms)).is_err() {
if i64::try_from(eval_ts + i128::from(fold_offset)).is_err() {
return Err(DataFusionError::Plan(format!(
"predict_linear evaluation time {eval_ts} overflows with offset {} ms",
window.offset_ms
"predict_linear evaluation time {eval_ts} overflows with offset {fold_offset} ms"
)));
}
}
}
Self::with_kernel(input, grid, window, function.kernel(window.offset_ms))
Self::with_kernel(
input,
grid,
window,
function.kernel(fold_offset),
step_invariant,
)
}
/// `step_invariant` tells whether an `@`-anchored result holds at every grid point.
pub(crate) fn with_kernel(
input: &SeriesSchema,
grid: Arc<EvalGrid>,
window: RangeWindow,
mut window: RangeWindow,
kernel: WindowKernel,
step_invariant: bool,
) -> Result<Self> {
if input.eval_grid.is_some() {
return Err(DataFusionError::Plan(
@@ -129,6 +157,12 @@ impl RangeEvaluator {
window.range_ms
)));
}
let replay = match (window.anchor_ms, step_invariant) {
(None, _) => Replay::PerPoint,
(Some(_), true) => Replay::Once,
(Some(_), false) => Replay::EveryPoint,
};
window.offset_ms = fold_offset(&grid, window)?;
let output_schema = Arc::new(SeriesSchema {
fields: input.fields.clone(),
eval_grid: Some(grid.clone()),
@@ -136,6 +170,7 @@ impl RangeEvaluator {
Ok(Self {
grid,
window,
replay,
kernel,
output: GridSeriesBuilder::try_new(output_schema.clone())?,
output_schema,
@@ -239,6 +274,11 @@ impl RangeEvaluator {
}
fn ingest(&mut self, chunk: &RawSeriesChunk) -> Result<()> {
let state = self.series.as_ref().expect("checked by check_chunk");
if state.cursor >= self.points_read() {
// Every window that reads samples has been evaluated.
return Ok(());
}
let mut samples: Vec<_> = chunk.fields.iter().map(|field| field.iter()).collect();
for &timestamp in chunk.time.as_buffer().iter() {
self.row.clear();
@@ -282,11 +322,12 @@ impl RangeEvaluator {
/// Evaluates grid points up to `ready` on the evaluation timeline, or all remaining points
/// when `ready` is `None`.
fn evaluate(&mut self, ready: Option<i128>) -> Result<()> {
let points_read = self.points_read();
let state = self.series.as_mut().expect("checked by check_chunk");
let spec = self.grid.spec();
let grid = self.grid.timestamps();
let range = i128::from(self.window.range_ms);
while state.cursor < grid.len() {
while state.cursor < points_read {
let eval_ts = grid[state.cursor];
if ready.is_some_and(|ready| i128::from(eval_ts) > ready) {
break;
@@ -312,22 +353,45 @@ impl RangeEvaluator {
continue;
}
self.row.clear();
for field in &self.fields {
let timestamps = &field.timestamps[field.head..];
let len = timestamps.partition_point(|&timestamp| timestamp <= eval_ts);
self.row.push(if len == 0 {
None
} else {
(self.kernel)(FloatWindow {
timestamps: &timestamps[..len],
values: &field.values[field.head..field.head + len],
match self.replay {
Replay::PerPoint => {
evaluate_row(
&self.fields,
&mut self.kernel,
self.window.range_ms,
eval_ts,
range_ms: self.window.range_ms,
})
});
eval_ts,
&mut self.row,
);
self.output.push(state.cursor, &self.row)?;
}
Replay::Once => {
evaluate_row(
&self.fields,
&mut self.kernel,
self.window.range_ms,
eval_ts,
eval_ts,
&mut self.row,
);
for index in 0..grid.len() {
self.output.push(index, &self.row)?;
}
}
Replay::EveryPoint => {
for (index, &point) in grid.iter().enumerate() {
evaluate_row(
&self.fields,
&mut self.kernel,
self.window.range_ms,
eval_ts,
point,
&mut self.row,
);
self.output.push(index, &self.row)?;
}
}
}
self.output.push(state.cursor, &self.row)?;
state.cursor += 1;
}
for field in &mut self.fields {
@@ -337,4 +401,57 @@ impl RangeEvaluator {
}
Ok(())
}
/// The number of leading grid points whose windows are read; an anchored selector reads
/// only the first.
fn points_read(&self) -> usize {
match self.replay {
Replay::PerPoint => self.grid.timestamps().len(),
Replay::Once | Replay::EveryPoint => 1,
}
}
}
/// Fills `row` with the kernel results over each field's window ending at `window_end`,
/// evaluated at `eval_ts`.
fn evaluate_row(
fields: &[FieldSamples],
kernel: &mut WindowKernel,
range_ms: i64,
window_end: i64,
eval_ts: i64,
row: &mut Vec<Option<f64>>,
) {
row.clear();
for field in fields {
let timestamps = &field.timestamps[field.head..];
let len = timestamps.partition_point(|&timestamp| timestamp <= window_end);
row.push(if len == 0 {
None
} else {
kernel(FloatWindow {
timestamps: &timestamps[..len],
values: &field.values[field.head..field.head + len],
eval_ts,
range_ms,
})
});
}
}
/// 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: &EvalGrid, window: RangeWindow) -> Result<i64> {
let Some(anchor) = window.anchor_ms else {
return Ok(window.offset_ms);
};
anchor
.checked_sub(window.offset_ms)
.and_then(|end| grid.spec().start_ms.checked_sub(end))
.ok_or_else(|| {
DataFusionError::Plan(format!(
"@ {anchor} ms with offset {} ms is out of range",
window.offset_ms
))
})
}
+58 -7
View File
@@ -98,7 +98,7 @@ fn metric(host: u64) -> MetricName {
fn probe_evaluator(fields: usize, grid: Arc<EvalGrid>, window: RangeWindow) -> RangeEvaluator {
let kernel: WindowKernel = Box::new(probe);
RangeEvaluator::with_kernel(&raw_schema(fields), grid, window, kernel).unwrap()
RangeEvaluator::with_kernel(&raw_schema(fields), grid, window, kernel, true).unwrap()
}
/// Builds a chunk whose timestamp and value arrays are slices at a nonzero offset.
@@ -210,19 +210,37 @@ fn reference_windows(
.flatten()
.any(|value| value.to_bits() == PROMETHEUS_STALE_NAN_BITS)
})
.map(|(timestamp, values)| (timestamp + window.offset_ms, values.clone()))
.map(|(timestamp, values)| (timestamp + fold_offset(grid, window), values.clone()))
.collect();
let windows = windows_of(&kept, grid, window);
(kept, windows)
}
/// The offset samples are shifted by: with `@`, Prometheus rewrites the offset so that the
/// anchored window is the window of the first evaluation point.
fn fold_offset(grid: &EvalGrid, window: RangeWindow) -> i64 {
match window.anchor_ms {
Some(anchor) => grid.spec().start_ms - (anchor - window.offset_ms),
None => window.offset_ms,
}
}
/// The end of the window each grid point reads, on the evaluation timeline.
fn window_end(grid: &EvalGrid, window: RangeWindow, eval_ts: i64) -> i64 {
match window.anchor_ms {
Some(_) => grid.spec().start_ms,
None => eval_ts,
}
}
/// Rows of `rows`, already on the evaluation timeline, inside each grid point's window.
fn windows_of(rows: &[Row], grid: &EvalGrid, window: RangeWindow) -> Vec<Range<usize>> {
grid.timestamps()
.iter()
.map(|&eval_ts| {
let end = window_end(grid, window, eval_ts);
let inside: Vec<_> = (0..rows.len())
.filter(|&row| rows[row].0 > eval_ts - window.range_ms && rows[row].0 <= eval_ts)
.filter(|&row| rows[row].0 > end - window.range_ms && rows[row].0 <= end)
.collect();
inside
.first()
@@ -248,7 +266,7 @@ fn reference(rows: &[Row], grid: &EvalGrid, window: RangeWindow, fields: usize)
probe(FloatWindow {
timestamps: &timestamps,
values: &values,
eval_ts,
eval_ts: window_end(grid, window, eval_ts),
range_ms: window.range_ms,
})
.unwrap()
@@ -339,8 +357,13 @@ fn udf_reference(
};
match function {
RangeFunction::Rate | RangeFunction::Increase | RangeFunction::Delta => {
// An anchored call is evaluated once, at the start, then replayed.
args.push(ColumnarValue::Array(Arc::new(
TimestampMillisecondArray::new(grid.timestamps().clone(), None),
TimestampMillisecondArray::from_iter_values(
grid.timestamps()
.iter()
.map(|&eval_ts| window_end(grid, window, eval_ts)),
),
)));
args.push(ColumnarValue::Array(Arc::new(Int64Array::from(vec![
window.range_ms,
@@ -356,7 +379,7 @@ fn udf_reference(
TimestampMillisecondArray::from_iter_values(
grid.timestamps()
.iter()
.map(|eval_ts| eval_ts + window.offset_ms),
.map(|eval_ts| eval_ts + fold_offset(grid, window)),
),
)));
}
@@ -409,11 +432,15 @@ fn random_window(rng: &mut StdRng) -> (Arc<EvalGrid>, RangeWindow) {
0 => 0,
_ => rng.random_range(-20_000..20_000),
};
let anchor_ms = rng
.random_bool(0.25)
.then(|| rng.random_range(-40_000..60_000));
(
grid,
RangeWindow {
range_ms,
offset_ms,
anchor_ms,
},
)
}
@@ -518,10 +545,11 @@ fn overlapping_window_spans_chunks() {
let window = RangeWindow {
range_ms: 15,
offset_ms: 0,
anchor_ms: None,
};
let kernel: WindowKernel = Box::new(sum);
let mut evaluator =
RangeEvaluator::with_kernel(&raw_schema(1), grid(10, 10, 3), window, kernel).unwrap();
RangeEvaluator::with_kernel(&raw_schema(1), grid(10, 10, 3), window, kernel, true).unwrap();
let first = chunk(&[(5, vec![Some(1.0)]), (12, vec![Some(2.0)])], 1, 0, false);
let second = chunk(&[(18, vec![Some(4.0)]), (25, vec![Some(8.0)])], 1, 0, true);
assert!(evaluator.push(&first).unwrap().is_none());
@@ -536,6 +564,7 @@ fn empty_input_and_series_without_results() {
let window = RangeWindow {
range_ms: 10,
offset_ms: 0,
anchor_ms: None,
};
probe_evaluator(1, grid(0, 10, 4), window).finish().unwrap();
@@ -552,6 +581,7 @@ fn rejects_invalid_parameters() {
let zero_range = RangeWindow {
range_ms: 0,
offset_ms: 0,
anchor_ms: None,
};
assert!(matches!(
RangeEvaluator::try_new(
@@ -568,6 +598,7 @@ fn rejects_invalid_parameters() {
let window = RangeWindow {
range_ms: 10,
offset_ms: 0,
anchor_ms: None,
};
assert!(matches!(
RangeEvaluator::try_new(&evaluated, grid(0, 10, 4), window, RangeFunction::Rate),
@@ -577,6 +608,7 @@ fn rejects_invalid_parameters() {
let far_offset = RangeWindow {
range_ms: 10,
offset_ms: i64::MAX - 20,
anchor_ms: None,
};
assert!(matches!(
RangeEvaluator::try_new(
@@ -587,6 +619,21 @@ fn rejects_invalid_parameters() {
),
Err(DataFusionError::Plan(_))
));
let unrepresentable_anchor = RangeWindow {
range_ms: 10,
offset_ms: 1,
anchor_ms: Some(i64::MIN),
};
assert!(matches!(
RangeEvaluator::try_new(
&raw_schema(1),
grid(0, 10, 4),
unrepresentable_anchor,
RangeFunction::Rate
),
Err(DataFusionError::Plan(_))
));
}
fn execution_error<T: std::fmt::Debug>(result: Result<T, DataFusionError>) {
@@ -601,6 +648,7 @@ fn rejects_invalid_chunk_sequences() {
let window = RangeWindow {
range_ms: 10,
offset_ms: 0,
anchor_ms: None,
};
let new = || probe_evaluator(1, grid(0, 10, 4), window);
let row = |timestamp| (timestamp, vec![Some(1.0)]);
@@ -638,6 +686,7 @@ fn offset_overflow_fails_unless_the_sample_is_stale() {
let window = RangeWindow {
range_ms: 10,
offset_ms: 10,
anchor_ms: None,
};
let late = i64::MAX - 5;
let mut evaluator = probe_evaluator(1, grid(0, 10, 4), window);
@@ -682,6 +731,7 @@ fn rejects_histogram_samples() {
let window = RangeWindow {
range_ms: 10,
offset_ms: 0,
anchor_ms: None,
};
assert!(matches!(
probe_evaluator(1, grid(0, 10, 4), window).push(&piece),
@@ -694,6 +744,7 @@ fn retains_only_samples_later_windows_need() {
let window = RangeWindow {
range_ms: 50,
offset_ms: 0,
anchor_ms: None,
};
let mut evaluator = probe_evaluator(1, grid(0, 10, 1_000), window);
let rows: Vec<Row> = (0..10_000).map(|i| (i, vec![Some(1.0)])).collect();