Skip to main content

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