promql/range_eval.rs
1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Range-vector window evaluation of raw series onto an evaluation grid.
16
17use std::ops::Range;
18use std::sync::Arc;
19#[cfg(test)]
20use std::sync::atomic::{AtomicU64, Ordering};
21
22use common_query::prometheus::is_prometheus_stale_nan;
23use common_query::promql_annotations::PromqlAnnotationCollector;
24use datafusion::arrow::array::{Array, Float64Array};
25use datafusion::arrow::buffer::Buffer;
26use datafusion::error::{DataFusionError, Result};
27use datatypes::series::SeriesLabels;
28use datatypes::series::histogram::CounterResetHint;
29use datatypes::series::raw::RawSeriesChunk;
30use datatypes::series::samples::{
31 DenseSamplesRef, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
32};
33use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis};
34
35use crate::evaluated::EvaluatedChunk;
36use crate::grid_series::{GridSample, GridSeriesBuilder, METADATA_LABELS, external};
37use crate::histogram_eval::float_histogram::FloatHistogram;
38
39mod function;
40mod histogram;
41#[cfg(test)]
42mod tests;
43
44pub use function::RangeFunction;
45pub(crate) use function::quantile;
46
47/// The samples a range selector reads at evaluation time `T`: source timestamps in
48/// `(E - range_ms, E]`, where `E` is `T - offset_ms`, or `anchor_ms - offset_ms` with `@`. A
49/// modifier widens that: `anchored` also reads the lookback before `E - range_ms`, `smoothed` the
50/// lookback on both sides, and a scan feeding the window has to read that much more.
51#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
52pub struct RangeWindow {
53 /// Positive window length in milliseconds.
54 pub range_ms: i64,
55 /// Selector offset in milliseconds; positive reads earlier samples.
56 pub offset_ms: i64,
57 /// The resolved `@` timestamp in milliseconds, with `start()` and `end()` already replaced
58 /// by the statement's start and end.
59 pub anchor_ms: Option<i64>,
60 /// The experimental `anchored` or `smoothed` selector modifier, which also reads samples
61 /// around the window.
62 pub modifier: Option<RangeModifier>,
63}
64
65/// The experimental range selector modifiers of Prometheus, which read samples beyond the
66/// window to pin its boundary values. Not to be confused with an `@` anchor, which fixes the
67/// window's end.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
69pub enum RangeModifier {
70 /// `anchored`: the window also reads the last sample at or before its start, up to the
71 /// statement's lookback before it, and takes it as the value at the start.
72 Anchored { lookback_ms: i64 },
73 /// `smoothed`: the window also reads samples up to the lookback before its start and after its
74 /// end, and interpolates the values at both boundaries.
75 Smoothed { lookback_ms: i64 },
76}
77
78impl RangeModifier {
79 /// How far before the window start the window also reads.
80 pub(crate) fn before_ms(self) -> i64 {
81 match self {
82 Self::Anchored { lookback_ms } | Self::Smoothed { lookback_ms } => lookback_ms,
83 }
84 }
85
86 /// How far after the window end the window also reads.
87 pub(crate) fn after_ms(self) -> i64 {
88 match self {
89 Self::Anchored { .. } => 0,
90 Self::Smoothed { lookback_ms } => lookback_ms,
91 }
92 }
93
94 pub(crate) fn name(self) -> &'static str {
95 match self {
96 Self::Anchored { .. } => "anchored",
97 Self::Smoothed { .. } => "smoothed",
98 }
99 }
100}
101
102/// The valid samples of one field inside one window, in source order.
103pub(crate) struct FloatWindow<'a> {
104 /// Sample timestamps shifted by the offset onto the evaluation timeline; non-empty.
105 pub timestamps: &'a [i64],
106 pub values: &'a [f64],
107 /// The counter resets this window contains, ascending by sample. Empty for every function
108 /// that does not correct counters and for every window of a series that never reset.
109 pub counter_resets: &'a [CounterReset],
110 /// Evaluation timestamp `T`. `timestamps` lie in `(T - range_ms, T]`, except for an
111 /// `@`-anchored `predict_linear`, which evaluates the first point's window at every `T`, and
112 /// for a range modifier, which widens the window by the lookback as [`RangeWindow`] says.
113 pub eval_ts: i64,
114 pub range_ms: i64,
115}
116
117/// Computes one window result; `None` means the window has no result.
118pub(crate) type WindowKernel = Box<dyn FnMut(FloatWindow<'_>) -> Option<f64> + Send>;
119
120/// The windows of one field at consecutive grid points, as ranges into the field's retained
121/// samples.
122pub(crate) struct FloatWindows<'a> {
123 /// The retained samples, in time order.
124 pub timestamps: &'a [i64],
125 pub values: &'a [f64],
126 /// Counter resets over the retained samples, ascending by position.
127 pub resets: &'a [CounterReset],
128 /// Absolute position of `timestamps[0]`: a reset position is `base` plus a sample index.
129 pub base: u64,
130 /// One range per window, ascending. Each is a half-open index range `[start, end)`; the time
131 /// window it was derived from is left-open, `(T - range_ms, T]`.
132 pub windows: &'a [Range<usize>],
133 /// The evaluation timestamp of each window.
134 pub eval_ts: &'a [i64],
135 pub range_ms: i64,
136}
137
138impl FloatWindows<'_> {
139 /// The resets inside window `index`.
140 ///
141 /// `windows` index the retained arrays as they stand in this batch, not absolutely: each
142 /// span is relative to `timestamps` and `values`, which is why `base` plus a span start is
143 /// the absolute position of the sample the span starts at.
144 pub(crate) fn resets_of(&self, index: usize) -> &[CounterReset] {
145 let span = &self.windows[index];
146 resets_between(
147 self.resets,
148 self.base + span.start as u64,
149 self.base + span.end as u64,
150 )
151 }
152}
153
154/// Computes a batch of one field's windows at once, appending one result per window to `out`.
155pub(crate) type BatchKernel = Box<dyn FnMut(&FloatWindows<'_>, &mut Vec<Option<f64>>) + Send>;
156
157/// Grid points accumulated before a batch kernel call. Sized to keep the per-field span and
158/// column buffers in cache while staying large enough to amortise the call.
159const EVALUATION_BATCH: usize = 512;
160
161/// Evaluates range windows over raw series, one series at a time, handing out its results as they
162/// become final.
163///
164/// Each series is pushed as its chunks in order. A push evaluates the grid points whose windows
165/// the pushed samples complete, and hands them out as one [`EvaluatedChunk`], so a consumer can
166/// stream a long series instead of waiting for its last chunk. One chunk may hold several runs of
167/// positions, separated by stretches holding no value, and the axis names them. The series closes
168/// on a chunk marked `is_last`, which is handed out even when it holds no position.
169///
170/// Fields are evaluated independently over their own valid samples; a row holding a stale
171/// marker in any field is dropped, as the ordinary range selector does. Only the samples later
172/// windows can still use are retained. Native histogram samples need a [`RangeFunction`]; an
173/// evaluator built from a bare kernel rejects them.
174pub struct RangeEvaluator {
175 grid: Arc<EvalGrid>,
176 /// The window with `offset_ms` replaced by the offset samples are shifted by.
177 window: RangeWindow,
178 replay: Replay,
179 kernel: WindowKernel,
180 function: Option<RangeFunction>,
181 annotations: Option<PromqlAnnotationCollector>,
182 output_schema: Arc<SeriesSchema>,
183 output: GridSeriesBuilder,
184 /// The grid of evaluated input series, such as the inner result of a subquery; `None` for
185 /// raw input.
186 input_grid: Option<GridSpec>,
187 series: Option<SeriesState>,
188 fields: Vec<FieldSamples>,
189 row: Vec<Option<GridSample>>,
190 drops_metric_name: bool,
191 /// Raised by the first non-empty window, where Prometheus validates function arguments.
192 window_error: Option<String>,
193 /// Chunks appended by the bulk path, so a test can prove that path is reached rather than
194 /// only that the output is right, which the per-sample path would also produce.
195 #[cfg(test)]
196 bulk_ingests: usize,
197 /// The batch form of `function`, when it has one and the input allows it. Present only for
198 /// `Replay::PerPoint`, whose windows advance with the grid; an anchored selector replays one
199 /// window and gains nothing from batching.
200 batch: Option<BatchKernel>,
201 /// Windows accumulated for the next batch call.
202 pending: PendingBatch,
203 /// Buffers the bulk ingest shifts and compacts a chunk into, kept between chunks so a series
204 /// that needs them does not allocate per push.
205 bulk_scratch: BulkScratch,
206 /// Batch kernel calls made so far. Test-only: both dispatch shapes produce the same output,
207 /// so a test comparing only output could not tell which one ran.
208 #[cfg(test)]
209 batch_calls: usize,
210}
211
212/// The buffers the bulk ingest needs for a chunk whose samples are not retained as they arrive:
213/// the timestamps shifted by the selector offset, and one compacted column per field.
214#[derive(Default)]
215struct BulkScratch {
216 timestamps: Vec<i64>,
217 columns: Vec<Vec<f64>>,
218}
219
220impl BulkScratch {
221 /// The bytes these buffers hold, by capacity.
222 fn bytes(&self) -> usize {
223 self.timestamps.capacity() * std::mem::size_of::<i64>()
224 + self.columns.capacity() * std::mem::size_of::<Vec<f64>>()
225 + self
226 .columns
227 .iter()
228 .map(|column| column.capacity() * std::mem::size_of::<f64>())
229 .sum::<usize>()
230 }
231}
232
233/// Windows accumulated for the next batch call: one list per field.
234struct PendingBatch {
235 /// Grid index of each accumulated point, ascending.
236 ///
237 /// Not assumed contiguous: `evaluate` skips the grid points whose window ends before the
238 /// series has a sample, so a batch can span such a gap and must write each point to its own
239 /// row.
240 indices: Vec<usize>,
241 /// Evaluation timestamp of each accumulated point.
242 eval_ts: Vec<i64>,
243 /// The retained-sample range of each point's window, one list per field.
244 ///
245 /// A span is relative to the retained arrays at the time it was recorded, not an absolute
246 /// index, so [`FieldSamples::advance`] invalidates it: that is why `evaluate` flushes the
247 /// batch before advancing.
248 spans: Vec<Vec<Range<usize>>>,
249 /// One output column per field, written by the batch kernel.
250 columns: Vec<Vec<Option<f64>>>,
251 /// Cursor into each field's retained timestamps; valid across batch flushes, but invalidated
252 /// when `FieldSamples::advance` drains the retained arrays.
253 ends: Vec<usize>,
254 /// Whether each cursor has been positioned by binary search since the last drain.
255 positioned: Vec<bool>,
256}
257
258impl PendingBatch {
259 fn with_fields(fields: usize) -> Self {
260 Self {
261 indices: Vec::new(),
262 eval_ts: Vec::new(),
263 spans: vec![Vec::new(); fields],
264 columns: vec![Vec::new(); fields],
265 ends: vec![0; fields],
266 positioned: vec![false; fields],
267 }
268 }
269
270 fn len(&self) -> usize {
271 self.eval_ts.len()
272 }
273
274 fn is_empty(&self) -> bool {
275 self.eval_ts.is_empty()
276 }
277
278 /// The bytes this batch's own vectors hold, by capacity.
279 fn bytes(&self) -> usize {
280 let spans: usize = self.spans.iter().map(|spans| spans.capacity()).sum();
281 let columns: usize = self.columns.iter().map(|column| column.capacity()).sum();
282 self.indices.capacity() * std::mem::size_of::<usize>()
283 + self.eval_ts.capacity() * std::mem::size_of::<i64>()
284 + spans * std::mem::size_of::<Range<usize>>()
285 + columns * std::mem::size_of::<Option<f64>>()
286 + self.ends.capacity() * std::mem::size_of::<usize>()
287 + self.positioned.capacity() * std::mem::size_of::<bool>()
288 }
289
290 /// Drops the accumulated points, keeping the allocations.
291 fn clear_points(&mut self) {
292 self.indices.clear();
293 self.eval_ts.clear();
294 for spans in &mut self.spans {
295 spans.clear();
296 }
297 }
298
299 fn reset_cursors(&mut self) {
300 self.ends.fill(0);
301 self.positioned.fill(false);
302 }
303}
304
305#[cfg(test)]
306static POSITION_COMPARISONS: AtomicU64 = AtomicU64::new(0);
307
308#[inline]
309fn timestamp_le(timestamp: i64, eval_ts: i64) -> bool {
310 #[cfg(test)]
311 POSITION_COMPARISONS.fetch_add(1, Ordering::Relaxed);
312 timestamp <= eval_ts
313}
314
315/// Records one point for the next batch call: its evaluation timestamp and, per field, the range
316/// of retained samples its window covers.
317fn accumulate(pending: &mut PendingBatch, index: usize, eval_ts: i64, fields: &[FieldSamples]) {
318 debug_assert_eq!(pending.spans.len(), fields.len());
319 pending.indices.push(index);
320 pending.eval_ts.push(eval_ts);
321 for (field_index, (spans, field)) in pending.spans.iter_mut().zip(fields).enumerate() {
322 // Cursors refer to retained arrays, which are unchanged by flushes. `head` only moves
323 // forward; never revisit samples already behind every remaining window.
324 pending.ends[field_index] = pending.ends[field_index].max(field.head);
325 if !pending.positioned[field_index] {
326 pending.ends[field_index] = field.timestamps[field.head..]
327 .partition_point(|×tamp| timestamp_le(timestamp, eval_ts))
328 + field.head;
329 pending.positioned[field_index] = true;
330 } else {
331 while pending.ends[field_index] < field.timestamps.len()
332 && timestamp_le(field.timestamps[pending.ends[field_index]], eval_ts)
333 {
334 pending.ends[field_index] += 1;
335 }
336 }
337 spans.push(field.head..pending.ends[field_index]);
338 }
339}
340
341/// Runs the batch kernel over the accumulated points and appends its columns.
342fn flush_batch(
343 kernel: &mut BatchKernel,
344 pending: &mut PendingBatch,
345 fields: &[FieldSamples],
346 range_ms: i64,
347 row: &mut Vec<Option<GridSample>>,
348 output: &mut GridSeriesBuilder,
349 #[cfg(test)] batch_calls: &mut usize,
350) -> Result<()> {
351 if pending.is_empty() {
352 return Ok(());
353 }
354 // Counted here rather than at the call site, so the number a test reads is by construction
355 // the number of kernel calls that happened.
356 #[cfg(test)]
357 {
358 *batch_calls += 1;
359 }
360 for (index, field) in fields.iter().enumerate() {
361 let batch = FloatWindows {
362 timestamps: &field.timestamps,
363 values: &field.values,
364 resets: &field.resets,
365 base: field.base,
366 windows: &pending.spans[index],
367 eval_ts: &pending.eval_ts,
368 range_ms,
369 };
370 kernel(&batch, &mut pending.columns[index]);
371 }
372 for (offset, &grid_index) in pending.indices.iter().enumerate() {
373 row.clear();
374 for column in &pending.columns {
375 row.push(column[offset].map(GridSample::Float));
376 }
377 output.push_samples(grid_index, row)?;
378 }
379 pending.clear_points();
380 Ok(())
381}
382
383struct SeriesState {
384 /// `None` for evaluated input, which arrives as one complete series.
385 primary_key: Option<Buffer>,
386 metric: SeriesLabels,
387 /// Largest source timestamp retained so far, or `None` while the series holds no sample: a
388 /// closing chunk of a series that never produced a value carries no position to read.
389 last_ts: Option<i64>,
390 /// Next grid index to evaluate.
391 cursor: usize,
392 /// Whether the input, or the evaluated series, has ended. The state stays until the buffered
393 /// rows have been handed out: the closing chunk still needs its metric.
394 closing: bool,
395 /// Grid index after the last position handed out to the consumer.
396 emitted_end: usize,
397}
398
399impl SeriesState {
400 /// The bytes this series' identity holds, which the rows handed out do not cover.
401 fn identity_bytes(&self) -> usize {
402 // A scan slices the primary key out of a decoded buffer, so the bytes the key shows are not
403 // the bytes it keeps: a key of a few bytes pins the allocation it was sliced out of.
404 // Charging the slice length instead would show a handful of bytes for an allocation the
405 // size of a decoded batch. One evaluator holds one series at a time, and an evaluated input
406 // holds no key at all, so there is no second slice of the same allocation to dedupe.
407 let primary_key = self
408 .primary_key
409 .as_ref()
410 .map_or(0, |key| key.capacity().max(key.len()));
411 let metric: usize = self.metric.name().map_or(0, |name| name.len())
412 + self
413 .metric
414 .tags()
415 .iter()
416 .map(|tag| tag.name.len() + tag.value.len())
417 .sum::<usize>();
418 std::mem::size_of::<SeriesState>() + primary_key + metric
419 }
420}
421
422/// How the windows of an `@`-anchored selector map to the grid.
423///
424/// Like Prometheus, an anchored selector is read once, as the window of the first grid point
425/// with the offset rewritten to `start - (anchor - offset)`.
426#[derive(Clone, Copy, Debug, PartialEq, Eq)]
427enum Replay {
428 /// Not anchored: every grid point reads its own window.
429 PerPoint,
430 /// The first point's result is reported at every point (step-invariant functions).
431 Once,
432 /// The first point's window is evaluated at every point (`predict_linear`).
433 EveryPoint,
434}
435
436#[derive(Default)]
437struct FieldSamples {
438 timestamps: Vec<i64>,
439 values: Vec<f64>,
440 /// Samples before `head` are behind every remaining window.
441 head: usize,
442 /// Native histogram samples, kept apart from the floats as Prometheus does.
443 histograms: Vec<(i64, FloatHistogram)>,
444 /// Histograms before `histogram_head` are behind every remaining window; their payloads are
445 /// released by [`advance_histograms`](Self::advance_histograms).
446 histogram_head: usize,
447 /// Estimated payload of the histograms this field still holds: the bucket lists and other
448 /// buffers the samples own, which no `size_of` of a slot shows.
449 ///
450 /// Measured for a histogram when it is admitted and released with it, so a retained sample is
451 /// not walked again on every push. A histogram is never modified once admitted, so the payload
452 /// its release subtracts is the one its admission added. Samples already behind every window
453 /// keep their payload in the figure until the drain releases them.
454 histogram_bytes: usize,
455 /// Sequence number of `values[0]`. Absolute and monotonic across the series this evaluator
456 /// evaluates, so a reset keeps its position when `head` samples are dropped instead of every
457 /// index being renumbered. An empty field holds the number of samples already dropped, which
458 /// keeps positions increasing when the next series starts.
459 base: u64,
460 /// Resets between consecutive retained samples, ascending by position: exactly the ones a
461 /// window over these samples can still contain. Maintained only for the counter-correcting
462 /// functions, and released as the samples they reach back to are dropped.
463 resets: Vec<CounterReset>,
464 /// Whether `resets` is maintained for this field.
465 index_resets: bool,
466}
467
468/// One counter reset: a sample that dropped below the sample before it.
469#[derive(Clone, Copy, Debug)]
470pub(crate) struct CounterReset {
471 /// Position of the later sample, as an absolute sequence number. Its predecessor is
472 /// `position - 1`, so a window holding the samples `[start, end)` contains this reset
473 /// exactly when `start < position < end`.
474 pub position: u64,
475 /// The value the reset adds back: the sample at `position - 1`, which is inside the window
476 /// whenever the reset is.
477 pub previous_value: f64,
478}
479
480/// The resets inside the window over the absolute positions `[start, end)`.
481///
482/// Left-open: a reset at `start` would add back a sample behind the window.
483fn resets_between(resets: &[CounterReset], start: u64, end: u64) -> &[CounterReset] {
484 let first = resets.partition_point(|reset| reset.position <= start);
485 let count = resets[first..].partition_point(|reset| reset.position < end);
486 &resets[first..first + count]
487}
488
489impl FieldSamples {
490 /// The bytes this field's buffers hold, by capacity: the samples, the history behind `head`
491 /// included, plus the estimated payload of the histograms still held.
492 fn bytes(&self) -> usize {
493 self.timestamps.capacity() * std::mem::size_of::<i64>()
494 + self.values.capacity() * std::mem::size_of::<f64>()
495 + self.histograms.capacity() * std::mem::size_of::<(i64, FloatHistogram)>()
496 + self.resets.capacity() * std::mem::size_of::<CounterReset>()
497 + self.histogram_bytes
498 }
499
500 fn new(index_resets: bool) -> Self {
501 Self {
502 index_resets,
503 ..Self::default()
504 }
505 }
506
507 /// Appends one valid sample, recording a counter reset when it dropped below the sample
508 /// before it.
509 ///
510 /// "Before it" means the previous entry of `values`, which leaves native histogram samples
511 /// out. A drop across an intervening histogram is therefore recorded as a reset of two
512 /// samples that are not neighbours. That is unobservable: a window holding both floats also
513 /// holds the histogram between them, so it is a mixed window, whose counter functions report
514 /// nothing; and a window starting after the earlier float excludes a reset on its first
515 /// sample. Should the mixed-window rules ever start reading the float resets, this has to
516 /// compare timestamps instead.
517 fn push(&mut self, timestamp: i64, value: f64) {
518 if self.index_resets
519 && let Some(&previous_value) = self.values.last()
520 && value < previous_value
521 {
522 self.resets.push(CounterReset {
523 position: self.base + self.values.len() as u64,
524 previous_value,
525 });
526 }
527 self.timestamps.push(timestamp);
528 self.values.push(value);
529 }
530
531 /// Appends samples that are all present, in bulk.
532 ///
533 /// Same result as calling [`push`](Self::push) once per sample, including the reset scan,
534 /// which stays per-sample for a field that maintains the index; the two appends become two
535 /// `memcpy`s.
536 fn push_bulk(&mut self, timestamps: &[i64], values: &[f64]) {
537 debug_assert_eq!(timestamps.len(), values.len());
538 if self.index_resets {
539 let start = self.values.len();
540 let mut previous = self.values.last().copied();
541 for (offset, &value) in values.iter().enumerate() {
542 if let Some(previous_value) = previous
543 && value < previous_value
544 {
545 self.resets.push(CounterReset {
546 position: self.base + (start + offset) as u64,
547 previous_value,
548 });
549 }
550 previous = Some(value);
551 }
552 }
553 self.timestamps.extend_from_slice(timestamps);
554 self.values.extend_from_slice(values);
555 }
556
557 /// Drops the samples before `head` and the resets whose predecessor is one of them.
558 fn advance(&mut self) {
559 let head = std::mem::take(&mut self.head);
560 if head == 0 {
561 return;
562 }
563 self.base += head as u64;
564 self.timestamps.drain(..head);
565 self.values.drain(..head);
566 // A reset at `base` would add back the last dropped sample, so it goes with it.
567 let dropped = self
568 .resets
569 .partition_point(|reset| reset.position <= self.base);
570 self.resets.drain(..dropped);
571 }
572
573 /// Drops the histograms before `histogram_head`, releasing the payload they held.
574 ///
575 /// The dropped samples are measured as they go, which costs one measurement per dropped
576 /// histogram in total: the retained ones are never scanned again.
577 fn advance_histograms(&mut self) {
578 let head = std::mem::take(&mut self.histogram_head);
579 if head == 0 {
580 return;
581 }
582 let dropped: usize = self.histograms[..head]
583 .iter()
584 .map(|(_, histogram)| histogram.heap_bytes())
585 .sum();
586 self.histogram_bytes = self.histogram_bytes.saturating_sub(dropped);
587 self.histograms.drain(..head);
588 }
589
590 /// The resets inside the window holding `len` samples from `head`.
591 fn resets_in(&self, len: usize) -> &[CounterReset] {
592 let start = self.base + self.head as u64;
593 resets_between(&self.resets, start, start + len as u64)
594 }
595}
596
597/// The bytes the histograms a row holds box, beyond the slots they sit in.
598///
599/// A slot is an `Option<GridSample>`: a pointer and a tag. A result that is a native histogram
600/// points at a [`FloatHistogram`] on the heap, which owns its bucket lists in turn, and both stay
601/// alive between pushes. Only slots the last evaluated point left in place are counted: a push
602/// clears the row.
603fn boxed_bytes(row: &[Option<GridSample>]) -> usize {
604 row.iter()
605 .flatten()
606 .map(|sample| match sample {
607 GridSample::Histogram(histogram) => {
608 std::mem::size_of::<FloatHistogram>() + histogram.heap_bytes()
609 }
610 GridSample::Float(_) => 0,
611 })
612 .sum()
613}
614
615impl RangeEvaluator {
616 /// Creates an evaluator of `function` for the series of `input` onto `grid`.
617 pub fn try_new(
618 input: &SeriesSchema,
619 grid: Arc<EvalGrid>,
620 window: RangeWindow,
621 function: RangeFunction,
622 ) -> Result<Self> {
623 let mut window_error = None;
624 if let RangeFunction::DoubleExponentialSmoothing { smoothing, trend } = function {
625 // Prometheus rejects factors outside (0, 1); NaN passes its check.
626 window_error = [("smoothing", smoothing), ("trend", trend)]
627 .into_iter()
628 .find(|(_, factor)| *factor <= 0.0 || *factor >= 1.0)
629 .map(|(name, factor)| {
630 format!("invalid {name} factor. Expected: 0 < factor < 1, got: {factor}")
631 });
632 }
633 if let Some(modifier) = window.modifier {
634 check_modifier(input, modifier, function)?;
635 }
636 let fold_offset = fold_offset(grid.spec(), window)?;
637 let step_invariant = !matches!(function, RangeFunction::PredictLinear(_));
638 if !step_invariant {
639 predict_linear_instants(grid.spec(), fold_offset)?;
640 }
641 // A modified window corrects counters over the samples it holds rather than through the
642 // reset index, and has no batch form.
643 let (kernel, index_resets) = match window.modifier {
644 Some(modifier) => (function.modified_kernel(modifier), false),
645 None => (
646 function.kernel(fold_offset),
647 function.indexes_counter_resets(),
648 ),
649 };
650 let mut evaluator =
651 Self::with_kernel(input, grid, window, kernel, step_invariant, index_resets)?;
652 evaluator.drops_metric_name = function.drops_metric_name();
653 evaluator.window_error = window_error;
654 evaluator.function = Some(function);
655 // An anchored selector replays one window at every point, so its windows do not advance
656 // with the grid and a batch would only repeat the same call.
657 if matches!(evaluator.replay, Replay::PerPoint) && window.modifier.is_none() {
658 evaluator.batch = function.batch_kernel();
659 }
660 Ok(evaluator)
661 }
662
663 /// `step_invariant` tells whether an `@`-anchored result holds at every grid point.
664 /// `index_resets` tells whether the kernel corrects counters, which is the only case where
665 /// the per-field reset index is worth maintaining.
666 pub(crate) fn with_kernel(
667 input: &SeriesSchema,
668 grid: Arc<EvalGrid>,
669 mut window: RangeWindow,
670 kernel: WindowKernel,
671 step_invariant: bool,
672 index_resets: bool,
673 ) -> Result<Self> {
674 if window.range_ms <= 0 {
675 return Err(DataFusionError::Plan(format!(
676 "range must be positive, got {} ms",
677 window.range_ms
678 )));
679 }
680 let replay = match (window.anchor_ms, step_invariant) {
681 (None, _) => Replay::PerPoint,
682 (Some(_), true) => Replay::Once,
683 (Some(_), false) => Replay::EveryPoint,
684 };
685 window.offset_ms = fold_offset(grid.spec(), window)?;
686 let output_schema = Arc::new(SeriesSchema {
687 fields: input.fields.clone(),
688 eval_grid: Some(grid.clone()),
689 });
690 Ok(Self {
691 grid,
692 window,
693 replay,
694 kernel,
695 function: None,
696 annotations: None,
697 output: GridSeriesBuilder::try_new(output_schema.clone())?,
698 input_grid: input.eval_grid.as_ref().map(|grid| grid.spec()),
699 output_schema,
700 series: None,
701 fields: input
702 .fields
703 .iter()
704 .map(|_| FieldSamples::new(index_resets))
705 .collect(),
706 row: Vec::with_capacity(input.fields.len()),
707 drops_metric_name: false,
708 window_error: None,
709 #[cfg(test)]
710 bulk_ingests: 0,
711 batch: None,
712 pending: PendingBatch::with_fields(input.fields.len()),
713 bulk_scratch: BulkScratch::default(),
714 #[cfg(test)]
715 batch_calls: 0,
716 })
717 }
718
719 /// The evaluation grid this evaluator decides points of.
720 ///
721 /// Every window ends at a point of it and is read at that point's timestamp, so a caller
722 /// reserving for what the evaluator is about to allocate reserves this grid's timestamps.
723 pub fn grid(&self) -> &Arc<EvalGrid> {
724 &self.grid
725 }
726
727 /// Chunks appended without the per-sample loop. Test-only: both paths produce the same
728 /// output by construction, so a test that only compared output could not tell whether the
729 /// bulk path ran at all.
730 #[cfg(test)]
731 pub(crate) fn bulk_ingest_count(&self) -> usize {
732 self.bulk_ingests
733 }
734
735 /// Batch kernel calls made so far. Test-only: both dispatch shapes produce the same output,
736 /// so a test comparing only output could not tell which one ran.
737 #[cfg(test)]
738 pub(crate) fn batch_call_count(&self) -> usize {
739 self.batch_calls
740 }
741
742 /// Sets the collector used for annotations produced by histogram range evaluation.
743 pub fn set_annotations(&mut self, collector: Option<PromqlAnnotationCollector>) {
744 self.annotations = collector;
745 }
746
747 /// An estimate of the bytes this evaluator keeps between pushes.
748 ///
749 /// Counted by capacity, so it is what the storage holds rather than what it uses: the retained
750 /// samples per field (timestamps, values, the reset index and the native histograms with the
751 /// payload each of them owns), the row a push fills with the histograms it boxes, the identity
752 /// of the open series, the pending batch's own vectors and the buffers the bulk ingest shifts
753 /// and compacts into. Left out are the kernel's scratch buffers, this struct's `Vec` headers
754 /// and the grid, which every chunk addressed on it shares.
755 ///
756 /// The figure is an estimate, not a ledger of every allocation: a histogram's payload is
757 /// measured once when it is admitted and released with it, so neither the retained samples nor
758 /// the transient allocations of a push are walked again.
759 ///
760 /// A push is the only caller that also holds the incoming chunk, and it charges that itself for
761 /// as long as the call runs. The figure must not be per-chunk either: charging every chunk
762 /// consumed would make the charge grow with the chunk count, so a fixed window over a long
763 /// series would read as an allocation failure even though the window holds no more samples.
764 pub(crate) fn retained_bytes(&self) -> usize {
765 let fields: usize = self.fields.iter().map(FieldSamples::bytes).sum();
766 let row = self.row.capacity() * std::mem::size_of::<Option<GridSample>>();
767 fields
768 + row
769 + boxed_bytes(&self.row)
770 + self.series.as_ref().map_or(0, SeriesState::identity_bytes)
771 + self.pending.bytes()
772 + self.bulk_scratch.bytes()
773 }
774
775 /// An upper bound of the rows the next push hands out, for input whose last sample is at
776 /// `last_ts` (`None` when it holds none) and which closes its series when `last`.
777 ///
778 /// A push writes at most one row per point it decides, from the series' cursor -- the first
779 /// point for a series not started yet. Unless the series closes, it decides no point past the
780 /// time the input has reached; and a point holds a row only while its window still reaches the
781 /// latest sample, so the points after that one's window are decided empty. A replayed `@`
782 /// result fills every grid point from the one window it evaluates first.
783 pub(crate) fn output_rows_bound(&self, last_ts: Option<i64>, last: bool) -> usize {
784 let spec = self.grid.spec();
785 let len = usize::try_from(spec.len).unwrap_or(usize::MAX);
786 let state = self.series.as_ref();
787 let Some(latest) = last_ts.or_else(|| state.and_then(|state| state.last_ts)) else {
788 return 0;
789 };
790 let cursor = state.map_or(0, |state| state.cursor);
791 if !matches!(self.replay, Replay::PerPoint) {
792 return if cursor == 0 { len } else { 0 };
793 }
794 // The grid points whose evaluation time is before `bound`.
795 let (start, step) = (i128::from(spec.start_ms), i128::from(spec.step_ms));
796 let points_before = |bound: i128| {
797 let offset = bound - start;
798 if offset <= 0 {
799 return 0;
800 }
801 usize::try_from((offset + step - 1) / step).map_or(len, |points| points.min(len))
802 };
803 let shifted = i128::from(latest) + i128::from(self.window.offset_ms);
804 let before = self
805 .window
806 .modifier
807 .map_or(0, |modifier| i128::from(modifier.before_ms()));
808 let mut end = points_before(shifted + i128::from(self.window.range_ms) + before);
809 if !last && last_ts.is_some() {
810 end = end.min(points_before(shifted + 1));
811 }
812 end.saturating_sub(cursor)
813 }
814
815 /// Whether this evaluator can answer with a native histogram.
816 pub(crate) fn yields_histograms(&self) -> bool {
817 self.function.is_some_and(RangeFunction::yields_histograms)
818 }
819
820 /// The heap bytes of the widest native histogram this evaluator retains, `None` when it
821 /// retains none.
822 pub(crate) fn widest_retained_histogram(&self) -> Option<usize> {
823 self.fields
824 .iter()
825 .flat_map(|field| &field.histograms)
826 .map(|(_, histogram)| histogram.heap_bytes())
827 .max()
828 }
829
830 /// Schema of the evaluated series: the input fields on the evaluation grid.
831 pub fn output_schema(&self) -> &Arc<SeriesSchema> {
832 &self.output_schema
833 }
834
835 /// Consumes the next chunk of the current series, or starts a new series.
836 ///
837 /// Returns every position this chunk decided, in one chunk addressed absolutely on the
838 /// evaluation grid; `None` when it decided no position holding a value. A decided position
839 /// without a result is a row of no chunk, so the positions between two runs of one chunk hold
840 /// no value and cost nothing. One push hands out at most one chunk.
841 ///
842 /// A series always closes exactly once: on the chunk holding its last rows, or on an empty
843 /// chunk after it when nothing is left. The evaluator must not be reused after an error.
844 pub fn push(&mut self, chunk: &RawSeriesChunk) -> Result<Option<EvaluatedChunk>> {
845 if self.input_grid.is_some() {
846 return Err(DataFusionError::Execution(
847 "raw series chunk pushed to an evaluator of evaluated series".into(),
848 ));
849 }
850 self.check_chunk(chunk)?;
851 self.ingest(chunk.time.as_buffer(), &chunk.fields, true)?;
852 let last_ts = chunk.time.as_buffer()[chunk.time.len() - 1];
853 if !chunk.is_last {
854 // Later chunks only hold samples after `last_ts`.
855 self.evaluate(Some(
856 i128::from(last_ts) + i128::from(self.window.offset_ms),
857 ))?;
858 return self.emit();
859 }
860 self.close_series()
861 }
862
863 /// Evaluates one run of an evaluated series, such as the inner result of a subquery: the
864 /// value at each grid point is a sample at that time. Stale markers are kept as values,
865 /// since the input is computed.
866 ///
867 /// `last` says whether this delivery closes its series. A stream hands over the same logical
868 /// series more than once -- a prefix now, its closing chunk later -- and the windows of a later
869 /// delivery read the samples of the earlier ones, so the state a series retains lives on across
870 /// them: only the `last` call ends it. Handing the deliveries over without saying which is last
871 /// would close the series early and lose exactly the samples a window across the boundary
872 /// needs.
873 ///
874 /// One delivery may hold several runs of positions, separated by stretches holding no value;
875 /// they all reach the caller in one chunk, addressed by the axis. A delivery that holds no
876 /// position at all is a legal close when it is `last`, and an error otherwise.
877 pub fn push_series(&mut self, series: &Series, last: bool) -> Result<Option<EvaluatedChunk>> {
878 let time = &series.time;
879 let Some(grid) = time.grid() else {
880 return Err(DataFusionError::Execution(
881 "evaluated range input must be a grid series".into(),
882 ));
883 };
884 if self.input_grid != Some(grid.spec())
885 || series.fields.len() != self.fields.len()
886 || series.fields.iter().any(|field| field.len() != time.len())
887 {
888 return Err(DataFusionError::Execution(
889 "evaluated series does not match the input schema".into(),
890 ));
891 }
892 // The input may skip positions: it is ingested by the positions it carries, and the points
893 // it skips hold no sample, which is exactly what a hole means.
894 let timestamps = time.timestamps().map_err(external)?;
895 let last_ts = timestamps.last().copied();
896 if !last && last_ts.is_none() {
897 // An empty delivery inside a series decides nothing: it is indistinguishable from a
898 // stall, so only the closing `is_last` one is a legal close.
899 return Err(DataFusionError::Execution(
900 "evaluated range input holds no position before its last run".into(),
901 ));
902 }
903 match &mut self.series {
904 None => {
905 self.output.begin_series();
906 self.series = Some(SeriesState {
907 primary_key: None,
908 metric: series.metric.clone(),
909 last_ts,
910 cursor: 0,
911 closing: false,
912 emitted_end: 0,
913 });
914 }
915 Some(state) => {
916 // A run continues its series; the earlier runs' samples stay retained for it.
917 if state.primary_key.is_some() {
918 return Err(DataFusionError::Execution(
919 "evaluated series pushed inside a raw series".into(),
920 ));
921 }
922 if state.closing {
923 return Err(DataFusionError::Execution(
924 "evaluated series pushed after it closed".into(),
925 ));
926 }
927 if state.metric != series.metric {
928 return Err(DataFusionError::Execution(
929 "evaluated series changed identity before its last run".into(),
930 ));
931 }
932 if let Some(last_ts) = last_ts {
933 if let Some(previous) = state.last_ts
934 && timestamps[0] <= previous
935 {
936 return Err(DataFusionError::Execution(format!(
937 "evaluated series runs are not increasing: {} after {previous}",
938 timestamps[0]
939 )));
940 }
941 state.last_ts = Some(last_ts);
942 }
943 }
944 }
945 if let Some(last_ts) = last_ts {
946 self.ingest(×tamps, &series.fields, false)?;
947 if last {
948 return self.close_series();
949 }
950 // Later runs only hold samples after `last_ts`, so every point up to it is decided.
951 // The samples are shifted onto the evaluation timeline by the selector offset, so the
952 // ready point is on that timeline too.
953 self.evaluate(Some(
954 i128::from(last_ts) + i128::from(self.window.offset_ms),
955 ))?;
956 return self.emit();
957 }
958 // A closing chunk holding no position: there is nothing to ingest, but the samples the
959 // earlier deliveries left retained still decide the windows that follow them, so the close
960 // finishes them rather than ending the series on the spot.
961 debug_assert!(last, "an empty chunk that is not last is rejected above");
962 self.close_series()
963 }
964
965 /// Evaluates the rest of the series of the last input chunk and closes it.
966 ///
967 /// The rows still buffered are handed out here as one chunk, and the chunk that sees nothing
968 /// behind it carries `is_last`.
969 fn close_series(&mut self) -> Result<Option<EvaluatedChunk>> {
970 self.evaluate(None)?;
971 self.series
972 .as_mut()
973 .expect("every path that closes a series started one")
974 .closing = true;
975 self.emit()
976 }
977
978 /// Hands out the rows buffered so far as one chunk, and closes the series when nothing is left.
979 ///
980 /// The chunk holds every row decided since the last hand-out, in one go and in one [`Series`]:
981 /// several runs of positions may sit inside it, separated by stretches holding no value, and
982 /// the axis names them. A position decided to hold none costs no row, so it lies between the
983 /// runs rather than inside one. `is_last` closes the series, and a series always closes exactly
984 /// once: on the chunk that carries its last rows, or on an empty chunk after it when no row is
985 /// left.
986 fn emit(&mut self) -> Result<Option<EvaluatedChunk>> {
987 let Some(state) = self.series.as_ref() else {
988 return Ok(None);
989 };
990 let closing = state.closing;
991 let emitted_end = state.emitted_end;
992 let mut metric = state.metric.clone();
993 if self.drops_metric_name {
994 metric.remove_all(&METADATA_LABELS);
995 }
996 let Some(series) = self.output.take_buffered(metric)? else {
997 return if closing {
998 self.empty_chunk(emitted_end)
999 } else {
1000 Ok(None)
1001 };
1002 };
1003 // The builder addresses every position it hands out, so the chunk's bounds come from the
1004 // axis itself: `first_position` is where it starts, and `last_position` where it ends.
1005 let start = series
1006 .time
1007 .first_position()
1008 .expect("the builder addresses every row on the grid");
1009 let end = series.time.last_position().map_or(start, |last| last + 1);
1010 debug_assert!(start >= emitted_end, "a chunk never goes back");
1011 if closing {
1012 // The buffer was drained into this chunk, so nothing of the series is left behind it.
1013 self.series = None;
1014 EvaluatedChunk::try_new(series, true).map(Some)
1015 } else {
1016 self.series
1017 .as_mut()
1018 .expect("checked at the entry of emit")
1019 .emitted_end = end;
1020 EvaluatedChunk::try_new(series, false).map(Some)
1021 }
1022 }
1023
1024 /// A closing chunk without values, addressed after the last position handed out.
1025 fn empty_chunk(&mut self, at: usize) -> Result<Option<EvaluatedChunk>> {
1026 let state = self.series.as_ref().expect("checked by the caller");
1027 let mut metric = state.metric.clone();
1028 if self.drops_metric_name {
1029 metric.remove_all(&METADATA_LABELS);
1030 }
1031 let empty = Samples::from_float(Float64Array::from(Vec::<f64>::new()));
1032 let fields = SeriesFields::try_from_vec(vec![empty; self.output_schema.fields.len()])
1033 .map_err(external)?;
1034 let time = GridRange::try_new(self.grid.clone(), at, 0).map_err(external)?;
1035 let series = Series::try_new(&self.output_schema, metric, TimeAxis::Grid(time), fields)
1036 .map_err(external)?;
1037 self.series = None;
1038 EvaluatedChunk::try_new(series, true).map(Some)
1039 }
1040
1041 /// Checks that the input did not end inside a series, with rows nobody took.
1042 pub fn finish(self) -> Result<()> {
1043 if self.series.is_some() {
1044 return Err(DataFusionError::Execution(
1045 "raw series input ended before the last chunk of a series".into(),
1046 ));
1047 }
1048 Ok(())
1049 }
1050
1051 fn check_chunk(&mut self, chunk: &RawSeriesChunk) -> Result<()> {
1052 let primary_key = Some(chunk.primary_key.as_slice());
1053 let time = chunk.time.as_buffer();
1054 if time.is_empty()
1055 || chunk.fields.len() != self.fields.len()
1056 || chunk.fields.iter().any(|field| field.len() != time.len())
1057 {
1058 return Err(DataFusionError::Execution(format!(
1059 "raw series chunk with {} timestamps and {} fields does not match {} schema fields",
1060 time.len(),
1061 chunk.fields.len(),
1062 self.fields.len()
1063 )));
1064 }
1065 match &mut self.series {
1066 None => {
1067 let metric = chunk.metric.clone().ok_or_else(|| {
1068 DataFusionError::Execution(
1069 "range evaluation requires materialized series labels".into(),
1070 )
1071 })?;
1072 self.output.begin_series();
1073 self.series = Some(SeriesState {
1074 primary_key: Some(chunk.primary_key.clone()),
1075 metric,
1076 last_ts: Some(time[time.len() - 1]),
1077 cursor: 0,
1078 closing: false,
1079 emitted_end: 0,
1080 });
1081 }
1082 Some(state) => {
1083 if state.primary_key.as_ref().map(|key| key.as_slice()) != primary_key
1084 || chunk.metric.as_ref() != Some(&state.metric)
1085 {
1086 return Err(DataFusionError::Execution(
1087 "raw series identity changed before its last chunk".into(),
1088 ));
1089 }
1090 if let Some(last_ts) = state.last_ts
1091 && time[0] <= last_ts
1092 {
1093 return Err(DataFusionError::Execution(format!(
1094 "raw series timestamps are not increasing across chunks: {} after {last_ts}",
1095 time[0]
1096 )));
1097 }
1098 state.last_ts = Some(time[time.len() - 1]);
1099 }
1100 }
1101 Ok(())
1102 }
1103
1104 /// Appends the chunk in bulk when every field is an entirely present float column.
1105 ///
1106 /// Returns `false` when a condition of the per-sample path applies, so the caller can run it.
1107 /// Only the shapes that path alone can read do: a field holding native histogram samples or
1108 /// mixed floats and histograms -- `dense()` reports [`DenseSamplesRef::Mixed`] for the latter,
1109 /// keeping its windows on the histogram path where the mixed-window rules decide the result --
1110 /// and a column with missing samples, which are absent rows rather than values.
1111 ///
1112 /// A selector offset and a stale marker do not: the shift and the rows the marker drops are
1113 /// applied here, over the columns, instead of handing the chunk to the per-sample loop. The
1114 /// search for a marker is one short-circuiting pass, the same pass the loop would have made.
1115 fn ingest_in_bulk(
1116 &mut self,
1117 timestamps: &[i64],
1118 fields: &SeriesFields,
1119 drop_stale: bool,
1120 ) -> Result<bool> {
1121 // Lengths are checked by `check_chunk` for raw input and by `push_series` for evaluated
1122 // input, so only the shape of the columns is decided here.
1123 let mut columns = Vec::with_capacity(fields.len());
1124 for field in fields.iter() {
1125 let Some(DenseSamplesRef::Float(values)) = field.dense() else {
1126 return Ok(false);
1127 };
1128 if values.null_count() != 0 {
1129 return Ok(false);
1130 }
1131 columns.push(values.values().as_ref());
1132 }
1133 // A stale marker drops its whole row, so which rows go is decided before anything is
1134 // retained. A chunk holding none -- the common case -- is judged by one scan that stops at
1135 // the first marker and then leaves the columns as they are.
1136 let stale_rows = if drop_stale
1137 && columns
1138 .iter()
1139 .any(|values| values.iter().any(|value| is_prometheus_stale_nan(*value)))
1140 {
1141 let mut stale = vec![false; timestamps.len()];
1142 for values in &columns {
1143 for (row, dropped) in stale.iter_mut().enumerate() {
1144 *dropped |= is_prometheus_stale_nan(values[row]);
1145 }
1146 }
1147 Some(stale)
1148 } else {
1149 None
1150 };
1151 self.append_float_chunk(timestamps, &columns, stale_rows.as_deref())?;
1152 #[cfg(test)]
1153 {
1154 self.bulk_ingests += 1;
1155 }
1156 Ok(true)
1157 }
1158
1159 /// Retains one chunk of entirely present float columns.
1160 ///
1161 /// `stale` marks the rows a stale marker drops, `None` when the chunk holds none. The retained
1162 /// samples are the chunk's rows less those, on the evaluation timeline: the selector offset
1163 /// shifts them, and only a chunk that needs neither keeps the incoming timestamps as they are.
1164 fn append_float_chunk(
1165 &mut self,
1166 timestamps: &[i64],
1167 columns: &[&[f64]],
1168 stale: Option<&[bool]>,
1169 ) -> Result<()> {
1170 let offset_ms = self.window.offset_ms;
1171 if offset_ms == 0 && stale.is_none() {
1172 // The source timestamps, which `RawTimestamps` already validated as increasing and
1173 // which the frame widened into this array without narrowing: nothing to shift, nothing
1174 // to check, and the two appends become two `memcpy`s.
1175 for (field, values) in self.fields.iter_mut().zip(columns) {
1176 field.push_bulk(timestamps, values);
1177 }
1178 return Ok(());
1179 }
1180 let BulkScratch {
1181 timestamps: mut shifted,
1182 columns: mut compacted,
1183 } = std::mem::take(&mut self.bulk_scratch);
1184 shifted.clear();
1185 shifted.reserve(timestamps.len());
1186 for (row, ×tamp) in timestamps.iter().enumerate() {
1187 if stale.is_some_and(|stale| stale[row]) {
1188 continue;
1189 }
1190 // Like RangeManipulate, any kept sample whose shifted time leaves i64 fails the series,
1191 // whichever path retains it.
1192 let Some(shifted_timestamp) = timestamp.checked_add(offset_ms) else {
1193 self.bulk_scratch = BulkScratch {
1194 timestamps: shifted,
1195 columns: compacted,
1196 };
1197 return Err(DataFusionError::Execution(format!(
1198 "sample timestamp {timestamp} overflows with offset {offset_ms} ms"
1199 )));
1200 };
1201 shifted.push(shifted_timestamp);
1202 }
1203 match stale {
1204 None => {
1205 for (field, values) in self.fields.iter_mut().zip(columns) {
1206 field.push_bulk(&shifted, values);
1207 }
1208 }
1209 Some(stale) => {
1210 compacted.resize_with(columns.len(), Vec::new);
1211 for (retained, values) in compacted.iter_mut().zip(columns) {
1212 retained.clear();
1213 retained.extend(
1214 values
1215 .iter()
1216 .enumerate()
1217 .filter(|(row, _)| !stale[*row])
1218 .map(|(_, &value)| value),
1219 );
1220 }
1221 for (field, values) in self.fields.iter_mut().zip(&compacted) {
1222 field.push_bulk(&shifted, values);
1223 }
1224 }
1225 }
1226 self.bulk_scratch = BulkScratch {
1227 timestamps: shifted,
1228 columns: compacted,
1229 };
1230 Ok(())
1231 }
1232
1233 /// Retains the samples of `fields` at `timestamps`. From `raw` input a row holding a stale
1234 /// marker in any field is dropped; evaluated input keeps it as a value.
1235 fn ingest(&mut self, timestamps: &[i64], fields: &SeriesFields, raw: bool) -> Result<()> {
1236 if self.ingest_in_bulk(timestamps, fields, raw)? {
1237 return Ok(());
1238 }
1239 let mut samples: Vec<_> = fields.iter().map(|field| field.iter()).collect();
1240 let mut row = Vec::with_capacity(samples.len());
1241 for ×tamp in timestamps {
1242 row.clear();
1243 let mut stale = false;
1244 for field in &mut samples {
1245 let sample = field.next().expect("field length checked by the caller");
1246 match &sample {
1247 SampleRef::Missing => {}
1248 SampleRef::Float(value) => stale |= is_prometheus_stale_nan(*value),
1249 SampleRef::Histogram(view) => {
1250 if self.function.is_none() {
1251 return Err(DataFusionError::NotImplemented(
1252 "range evaluation of histogram samples".into(),
1253 ));
1254 }
1255 stale |= is_prometheus_stale_nan(view.sum);
1256 }
1257 }
1258 row.push(sample);
1259 }
1260 if stale && raw {
1261 continue;
1262 }
1263 // Like RangeManipulate, any kept sample whose shifted time leaves i64 fails the series.
1264 let shifted = timestamp
1265 .checked_add(self.window.offset_ms)
1266 .ok_or_else(|| {
1267 DataFusionError::Execution(format!(
1268 "sample timestamp {timestamp} overflows with offset {} ms",
1269 self.window.offset_ms
1270 ))
1271 })?;
1272 // Refused here rather than when a point is evaluated: a smoothed point can be decided
1273 // before the rest of its window arrives, so whether a later histogram is seen would
1274 // depend on how the input is chunked.
1275 if let Some(modifier) = self.window.modifier
1276 && row
1277 .iter()
1278 .any(|sample| matches!(sample, SampleRef::Histogram(_)))
1279 && self.decided_window_reads(shifted)
1280 {
1281 return Err(DataFusionError::NotImplemented(format!(
1282 "the {} range modifier over native histogram samples",
1283 modifier.name()
1284 )));
1285 }
1286 for (field, sample) in self.fields.iter_mut().zip(&row) {
1287 match sample {
1288 SampleRef::Missing => {}
1289 SampleRef::Float(value) => {
1290 field.push(shifted, *value);
1291 }
1292 SampleRef::Histogram(view) => {
1293 let mut h = FloatHistogram::try_from_view(view)?;
1294 // Like Prometheus' `evalSubquery`: an explicit counter reset hint
1295 // describes the sample's raw neighbours, not its evaluated ones.
1296 if !raw && h.reset_hint != CounterResetHint::Gauge {
1297 h.reset_hint = CounterResetHint::Unknown;
1298 }
1299 field.histogram_bytes =
1300 field.histogram_bytes.saturating_add(h.heap_bytes());
1301 field.histograms.push((shifted, h));
1302 }
1303 }
1304 }
1305 }
1306 Ok(())
1307 }
1308
1309 /// Whether a sample at `timestamp` on the evaluation timeline lies in the window of a point
1310 /// this evaluator decides: a window ending at `E` reads `(E - range - before, E + after]`, and
1311 /// only the first point's window is read when the result is replayed.
1312 fn decided_window_reads(&self, timestamp: i64) -> bool {
1313 let (before, after) = self.window.modifier.map_or((0, 0), |modifier| {
1314 (
1315 i128::from(modifier.before_ms()),
1316 i128::from(modifier.after_ms()),
1317 )
1318 });
1319 let spec = self.grid.spec();
1320 let ends = match self.replay {
1321 Replay::PerPoint => i128::from(spec.len),
1322 Replay::Once | Replay::EveryPoint => 1,
1323 };
1324 let (start, step) = (i128::from(spec.start_ms), i128::from(spec.step_ms));
1325 // The window ends that read the sample are those in `[timestamp - after, timestamp +
1326 // range + before)`; the first grid point at or after the lower bound decides.
1327 let lowest = i128::from(timestamp) - after;
1328 let highest = i128::from(timestamp) + i128::from(self.window.range_ms) + before;
1329 let first = if lowest <= start {
1330 0
1331 } else {
1332 (lowest - start + step - 1) / step
1333 };
1334 first < ends && start + first * step < highest
1335 }
1336
1337 /// Evaluates grid points up to `ready` on the evaluation timeline, or all remaining points
1338 /// when `ready` is `None`.
1339 fn evaluate(&mut self, ready: Option<i128>) -> Result<()> {
1340 let points_read = self.points_read();
1341 let state = self.series.as_mut().expect("checked by check_chunk");
1342 let spec = self.grid.spec();
1343 let grid = self.grid.timestamps().map_err(external)?;
1344 // A modifier also reads samples up to the lookback ahead of the window start, so they are
1345 // kept that much longer.
1346 let before = self
1347 .window
1348 .modifier
1349 .map_or(0, |modifier| i128::from(modifier.before_ms()));
1350 // `smoothed` interpolates the window end with the first sample at or after it, which can
1351 // arrive up to the lookback later. A point is decided once every field holds a sample at
1352 // or after it, or once the lookback past it has arrived. The input's last row does not say
1353 // that alone: a stale row is dropped, and a field can hold no value in it.
1354 let ready = match (ready, self.window.modifier) {
1355 (Some(ready), Some(RangeModifier::Smoothed { lookback_ms })) => {
1356 let held = self
1357 .fields
1358 .iter()
1359 .map(|field| {
1360 field
1361 .timestamps
1362 .last()
1363 .map_or(i128::MIN, |&t| i128::from(t))
1364 })
1365 .min()
1366 .unwrap_or(i128::MIN);
1367 Some(held.max(ready - i128::from(lookback_ms)))
1368 }
1369 (ready, _) => ready,
1370 };
1371 let range = i128::from(self.window.range_ms) + before;
1372 let mut empty_tail = false;
1373 while state.cursor < points_read {
1374 let eval_ts = grid[state.cursor];
1375 let lower = i128::from(eval_ts) - range;
1376 let mut earliest = None;
1377 // Later windows start no earlier, so samples behind this one go even when the point
1378 // itself is not ready yet.
1379 for field in &mut self.fields {
1380 field.head += field.timestamps[field.head..]
1381 .partition_point(|×tamp| i128::from(timestamp) <= lower);
1382 field.histogram_head += field.histograms[field.histogram_head..]
1383 .partition_point(|(timestamp, _)| i128::from(*timestamp) <= lower);
1384 let first_histogram = field.histograms.get(field.histogram_head);
1385 for ×tamp in field
1386 .timestamps
1387 .get(field.head)
1388 .into_iter()
1389 .chain(first_histogram.map(|(timestamp, _)| timestamp))
1390 {
1391 earliest = Some(earliest.map_or(timestamp, |min: i64| min.min(timestamp)));
1392 }
1393 }
1394 if ready.is_some_and(|ready| i128::from(eval_ts) > ready) {
1395 break;
1396 }
1397 // No retained sample: every point from here on is decided too. A sample that still
1398 // has to arrive lies beyond the window of every one of them, so none can gain a value.
1399 let Some(earliest) = earliest else {
1400 empty_tail = true;
1401 break;
1402 };
1403 if earliest > eval_ts {
1404 // Skip the points whose windows end before the earliest sample. A smoothed window
1405 // reads past its end, but without a sample at or before its end it has no result,
1406 // as Prometheus returns nothing when the first sample is after the end.
1407 let step = i128::from(spec.step_ms);
1408 let steps = (i128::from(earliest) - i128::from(spec.start_ms) + step - 1) / step;
1409 state.cursor = usize::try_from(steps).map_or(grid.len(), |i| i.min(grid.len()));
1410 continue;
1411 }
1412 if let Some(error) = &self.window_error {
1413 return Err(DataFusionError::Execution(error.clone()));
1414 }
1415
1416 let mut evaluator = RowEvaluator {
1417 fields: &self.fields,
1418 kernel: &mut self.kernel,
1419 function: self.function,
1420 annotations: self.annotations.as_ref(),
1421 range_ms: self.window.range_ms,
1422 offset_ms: self.window.offset_ms,
1423 modifier: self.window.modifier,
1424 };
1425 match self.replay {
1426 Replay::PerPoint => {
1427 // A window holding a native histogram is decided by the mixed-window rules,
1428 // which the batch kernel -- reading floats alone -- cannot reproduce. Flush
1429 // what is pending and decide this point on the per-window path.
1430 //
1431 // Histograms are retained in time order, so the first one still ahead of the
1432 // window head decides: a later one cannot be inside this window if this one
1433 // is not. The check runs only when a batch kernel is set, so a function
1434 // without one never pays for it.
1435 let histogram_window = self.batch.is_some()
1436 && self.fields.iter().any(|field| {
1437 field.histograms.get(field.histogram_head).is_some_and(
1438 |(timestamp, _)| i128::from(*timestamp) <= i128::from(eval_ts),
1439 )
1440 });
1441 if let Some(kernel) = self.batch.as_mut()
1442 && !histogram_window
1443 {
1444 accumulate(&mut self.pending, state.cursor, eval_ts, &self.fields);
1445 if self.pending.len() >= EVALUATION_BATCH {
1446 flush_batch(
1447 kernel,
1448 &mut self.pending,
1449 &self.fields,
1450 self.window.range_ms,
1451 &mut self.row,
1452 &mut self.output,
1453 #[cfg(test)]
1454 &mut self.batch_calls,
1455 )?;
1456 }
1457 state.cursor += 1;
1458 continue;
1459 }
1460 if let Some(kernel) = self.batch.as_mut() {
1461 flush_batch(
1462 kernel,
1463 &mut self.pending,
1464 &self.fields,
1465 self.window.range_ms,
1466 &mut self.row,
1467 &mut self.output,
1468 #[cfg(test)]
1469 &mut self.batch_calls,
1470 )?;
1471 }
1472 evaluator.evaluate(eval_ts, eval_ts, &mut self.row)?;
1473 self.output.push_samples(state.cursor, &self.row)?;
1474 }
1475 Replay::Once => {
1476 evaluator.evaluate(eval_ts, eval_ts, &mut self.row)?;
1477 for index in 0..grid.len() {
1478 self.output.push_samples(index, &self.row)?;
1479 }
1480 }
1481 Replay::EveryPoint => {
1482 for (index, &point) in grid.iter().enumerate() {
1483 evaluator.evaluate(eval_ts, point, &mut self.row)?;
1484 self.output.push_samples(index, &self.row)?;
1485 }
1486 }
1487 }
1488 state.cursor += 1;
1489 }
1490 if let Some(kernel) = self.batch.as_mut() {
1491 flush_batch(
1492 kernel,
1493 &mut self.pending,
1494 &self.fields,
1495 self.window.range_ms,
1496 &mut self.row,
1497 &mut self.output,
1498 #[cfg(test)]
1499 &mut self.batch_calls,
1500 )?;
1501 }
1502 // A point is decided once it has been evaluated, once its window can no longer gain a
1503 // sample, or -- at the end of the series or of what the input has reached -- once no
1504 // retained sample reaches it. The last case is what keeps a long empty stretch cheap: the
1505 // loop stops at the first such point instead of walking the rest of the grid, and none of
1506 // the points behind it can gain a value, so the cursor skips them.
1507 if empty_tail && matches!(self.replay, Replay::PerPoint) {
1508 let mut decided = state.cursor;
1509 if let Some(ready) = ready {
1510 while decided < points_read && i128::from(grid[decided]) <= ready {
1511 decided += 1;
1512 }
1513 } else {
1514 decided = points_read;
1515 }
1516 state.cursor = decided;
1517 }
1518 debug_assert!(
1519 self.pending.is_empty(),
1520 "`evaluate` flushes the batch before `advance` rewrites the retained arrays a \
1521 pending span indexes"
1522 );
1523 let mut drains_samples = false;
1524 for field in &mut self.fields {
1525 // After the last window, samples are still ingested so that the overflow and
1526 // histogram checks do not depend on how the series is chunked, but none are kept.
1527 // An anchored selector can skip past the one point it reads.
1528 if state.cursor >= points_read {
1529 field.head = field.timestamps.len();
1530 field.histogram_head = field.histograms.len();
1531 }
1532 drains_samples |= field.head > 0;
1533 field.advance();
1534 field.advance_histograms();
1535 }
1536 // A drain shifts retained-array indices. Batch flushes do not, so they leave cursors valid.
1537 if drains_samples {
1538 self.pending.reset_cursors();
1539 }
1540 Ok(())
1541 }
1542
1543 /// The number of leading grid points whose windows are read; an anchored selector reads
1544 /// only the first.
1545 fn points_read(&self) -> usize {
1546 match self.replay {
1547 Replay::PerPoint => self.grid.spec().len as usize,
1548 Replay::Once | Replay::EveryPoint => 1,
1549 }
1550 }
1551}
1552
1553/// Computes the result of every field's window at one grid point.
1554struct RowEvaluator<'a> {
1555 fields: &'a [FieldSamples],
1556 kernel: &'a mut WindowKernel,
1557 function: Option<RangeFunction>,
1558 annotations: Option<&'a PromqlAnnotationCollector>,
1559 range_ms: i64,
1560 offset_ms: i64,
1561 modifier: Option<RangeModifier>,
1562}
1563
1564impl RowEvaluator<'_> {
1565 /// Fills `row` with the result over each field's window ending at `window_end`, evaluated
1566 /// at `eval_ts`.
1567 fn evaluate(
1568 &mut self,
1569 window_end: i64,
1570 eval_ts: i64,
1571 row: &mut Vec<Option<GridSample>>,
1572 ) -> Result<()> {
1573 row.clear();
1574 // A smoothed window also reads the samples after its end.
1575 let window_end = window_end + self.modifier.map_or(0, RangeModifier::after_ms);
1576 for field in self.fields {
1577 let timestamps = &field.timestamps[field.head..];
1578 let len = timestamps.partition_point(|×tamp| timestamp <= window_end);
1579 let floats = (len > 0).then(|| FloatWindow {
1580 timestamps: ×tamps[..len],
1581 values: &field.values[field.head..field.head + len],
1582 counter_resets: field.resets_in(len),
1583 eval_ts,
1584 range_ms: self.range_ms,
1585 });
1586 let histograms = &field.histograms[field.histogram_head..];
1587 let histograms = &histograms
1588 [..histograms.partition_point(|(timestamp, _)| *timestamp <= window_end)];
1589 row.push(match self.function {
1590 Some(function) if !histograms.is_empty() => histogram::evaluate(
1591 function,
1592 floats,
1593 histograms,
1594 eval_ts,
1595 self.range_ms,
1596 self.offset_ms,
1597 &mut *self.kernel,
1598 self.annotations,
1599 )?,
1600 _ => floats.and_then(|window| (self.kernel)(window).map(GridSample::Float)),
1601 });
1602 }
1603 Ok(())
1604 }
1605}
1606
1607/// Rejects a modifier on a function Prometheus does not allow it with, as Prometheus rejects the
1608/// query (`AnchoredSafeFunctions`, `SmoothedSafeFunctions`), and on evaluated input, which reads
1609/// no raw samples around its windows.
1610///
1611/// `pub(crate)` because it is a rule about the input's schema and the window alone, so the native
1612/// route's admission predicate (`native_tree_supported`) asks it rather than a second copy of it,
1613/// the way it asks [`fold_offset`].
1614pub(crate) fn check_modifier(
1615 input: &SeriesSchema,
1616 modifier: RangeModifier,
1617 function: RangeFunction,
1618) -> Result<()> {
1619 if input.eval_grid.is_some() {
1620 return Err(DataFusionError::NotImplemented(format!(
1621 "the {} range modifier over evaluated series",
1622 modifier.name()
1623 )));
1624 }
1625 let allowed = match modifier {
1626 RangeModifier::Anchored { .. } => matches!(
1627 function,
1628 RangeFunction::Rate
1629 | RangeFunction::Increase
1630 | RangeFunction::Delta
1631 | RangeFunction::Resets
1632 | RangeFunction::Changes
1633 ),
1634 RangeModifier::Smoothed { .. } => matches!(
1635 function,
1636 RangeFunction::Rate | RangeFunction::Increase | RangeFunction::Delta
1637 ),
1638 };
1639 if !allowed {
1640 let list = match modifier {
1641 RangeModifier::Anchored { .. } => "changes, delta, increase, rate, resets",
1642 RangeModifier::Smoothed { .. } => "delta, increase, rate",
1643 };
1644 return Err(DataFusionError::Plan(format!(
1645 "{} modifier can only be used with: {list} - not with {function:?}",
1646 modifier.name()
1647 )));
1648 }
1649 if modifier.before_ms() < 0 {
1650 return Err(DataFusionError::Plan(format!(
1651 "lookback must not be negative, got {} ms",
1652 modifier.before_ms()
1653 )));
1654 }
1655 Ok(())
1656}
1657
1658/// The offset samples are shifted by: the selector offset, or for `@` the offset that places
1659/// the anchored window at the first grid point.
1660///
1661/// `pub(crate)` because whether it fits is decided from the grid and the window alone, so the
1662/// native route's admission predicate asks the same arithmetic rather than a second copy of it.
1663pub(crate) fn fold_offset(grid: GridSpec, window: RangeWindow) -> Result<i64> {
1664 let Some(anchor) = window.anchor_ms else {
1665 return Ok(window.offset_ms);
1666 };
1667 anchor
1668 .checked_sub(window.offset_ms)
1669 .and_then(|end| grid.start_ms.checked_sub(end))
1670 .ok_or_else(|| {
1671 DataFusionError::Plan(format!(
1672 "@ {anchor} ms with offset {} ms is out of range",
1673 window.offset_ms
1674 ))
1675 })
1676}
1677
1678/// Checks that `predict_linear` can read the instant of every point of `grid` once shifted by
1679/// `fold_offset`.
1680///
1681/// Unlike every other range function, which reads the window a grid point opens alone,
1682/// `predict_linear` reads the instant it reports as well, and reports it shifted by the fold
1683/// offset. The first and the last point are the ones checked: the shift is the same at every point
1684/// and the grid's points are ordered, so what fits at both ends fits between them.
1685///
1686/// The refusal is arithmetic rather than shape, but it is decided by the grid and the window alone,
1687/// which is why the native route's admission predicate reaches it too
1688/// (`native_tree_supported`): a query refused only here has to keep the plan it had instead of
1689/// failing while its runtime is built.
1690pub(crate) fn predict_linear_instants(grid: GridSpec, fold_offset: i64) -> Result<()> {
1691 let last = i128::from(grid.start_ms) + i128::from(grid.step_ms) * (i128::from(grid.len) - 1);
1692 for eval_ts in [i128::from(grid.start_ms), last] {
1693 if i64::try_from(eval_ts + i128::from(fold_offset)).is_err() {
1694 return Err(DataFusionError::Plan(format!(
1695 "predict_linear evaluation time {eval_ts} overflows with offset {fold_offset} ms"
1696 )));
1697 }
1698 }
1699 Ok(())
1700}
1701
1702/// The inner grid of a subquery read by `window` from the outer grid `outer`: the multiples of
1703/// `step_ms` after `start - F - range` up to the last window end, where `F` is the fold offset
1704/// of `window`; with `@`, the only window end is `start - F`. `None` when no multiple falls in
1705/// the windows.
1706pub fn subquery_grid(
1707 outer: GridSpec,
1708 window: RangeWindow,
1709 step_ms: i64,
1710) -> Result<Option<GridSpec>> {
1711 if step_ms <= 0 {
1712 return Err(DataFusionError::Plan(format!(
1713 "subquery step must be positive, got {step_ms} ms"
1714 )));
1715 }
1716 let fold_offset = i128::from(fold_offset(outer, window)?);
1717 let step = i128::from(step_ms);
1718 let start = i128::from(outer.start_ms);
1719 let last_eval = match window.anchor_ms {
1720 Some(_) => start,
1721 None => start + i128::from(outer.step_ms) * (i128::from(outer.len) - 1),
1722 };
1723 let first = ((start - fold_offset - i128::from(window.range_ms)).div_euclid(step) + 1) * step;
1724 let last = last_eval - fold_offset;
1725 if first > last {
1726 return Ok(None);
1727 }
1728 let len = u64::try_from((last - first) / step + 1)
1729 .map_err(|_| DataFusionError::Plan("subquery grid has too many points".into()))?;
1730 let first = i64::try_from(first).map_err(|_| {
1731 DataFusionError::Plan(format!("subquery grid start {first} ms is out of range"))
1732 })?;
1733 GridSpec::try_new(first, step_ms, len)
1734 .map(Some)
1735 .map_err(|error| DataFusionError::External(Box::new(error)))
1736}