Skip to main content

promql/native/
execute.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//! Running a bound tree, node by node.
16//!
17//! Each execution owns a recursive runtime tree; the compiled [`NativeTree`] stays immutable, so
18//! one tree builds independent executions. A caller registers the tree's per-node metric handles
19//! into its own metrics set once, before the execution starts.
20
21use std::collections::{HashSet, VecDeque};
22use std::sync::Arc;
23
24use common_query::promql_annotations::PromqlAnnotationCollector;
25use datafusion::error::{DataFusionError, Result};
26use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation};
27use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
28use datatypes::arrow::array::{Array, ArrowPrimitiveType, Float64Array, PrimitiveArray};
29use datatypes::arrow::buffer::{Buffer, ScalarBuffer};
30use datatypes::series::histogram::HistogramView;
31use datatypes::series::raw::{RawSeriesChunk, RawTimestamps};
32use datatypes::series::samples::{
33    DenseSamplesRef, FieldSpec, RowCursor, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
34};
35use datatypes::series::time::{EvalGrid, GridRange, GridSpan, GridSpec, TimeAxis};
36use datatypes::series::{SeriesLabels, SeriesOrdering};
37
38use crate::aggregate;
39use crate::grid_series::{
40    GridSample, GridSeriesBuilder, fields_bytes, merge_same_labelset, owned, series_bytes,
41    table_bytes,
42};
43use crate::histogram_eval::float_histogram::FloatHistogram;
44use crate::histogram_eval::{
45    HistogramFunction, HistogramParameters, evaluate_histograms_with_annotations,
46    map_native_histogram,
47};
48use crate::info::{InfoSelector, info_with_reservation};
49use crate::instant_eval::{
50    info_sample_times, instant_candidate_span, select_instant_at, select_instants,
51    timestamp_of_evaluated, timestamp_of_selection,
52};
53use crate::map::{
54    ArithmeticOp, Comparison, ComparisonOp, ParameterizedMath, ScalarOperand, ScalarSeriesOperand,
55    drop_metric_name, is_float_series, map_arithmetic_literal, map_arithmetic_series,
56    map_compare_literal, map_compare_series, map_math, map_math_with_parameters,
57};
58use crate::map_time::{self, DateFunction};
59use crate::native::aggregate::{AggregateOutput, AggregateRuntime};
60use crate::native::batch::EvaluatedChunk;
61use crate::native::metrics::NodeMetrics;
62use crate::native::plan::{
63    BoundInstant, BoundScalar, BoundSetOp, BoundVectorOp, Grouping, InstantValue, MapOp,
64    NativeExpr, NativeNode, NativeTree, NativeType, ParameterizedOp, unifies_its_own_contributions,
65};
66use crate::native::state::{StateChunk, state_bytes};
67use crate::range_eval::RangeEvaluator;
68use crate::select::{self, SortOrder};
69use crate::vector_match::{
70    BinaryKind, BinaryMatching, Cardinality, DuplicateEvidence, FillValues, MatchingLabels,
71    binary_vectors_with_reservation, set_vectors_with_reservation, validate_binary_operand,
72};
73
74#[cfg(test)]
75mod tests;
76
77/// A chunk on an internal edge.
78enum NativeChunk {
79    /// Raw source samples, with their own timestamps.
80    Raw(RawSeriesChunk),
81    /// Evaluated values, addressed on their absolute grid positions.
82    Evaluated(EvaluatedChunk),
83    /// Partial aggregate state, addressed on its group's absolute grid positions.
84    AggregateState(StateChunk),
85}
86
87impl NativeChunk {
88    /// The positions this chunk carries: decided grid positions, or raw timestamps.
89    fn positions(&self) -> usize {
90        match self {
91            Self::Raw(chunk) => chunk.time.len(),
92            Self::Evaluated(chunk) => chunk.series.time.len(),
93            Self::AggregateState(StateChunk::Series { series, .. }) => {
94                series.iter().map(|s| s.time.len()).sum()
95            }
96            Self::AggregateState(StateChunk::Row(row)) => row.time.len(),
97        }
98    }
99
100    /// The chunk kind, for error messages.
101    fn describe(&self) -> &'static str {
102        match self {
103            Self::Raw(_) => "raw samples",
104            Self::Evaluated(_) => "an evaluated chunk",
105            Self::AggregateState(_) => "aggregate state",
106        }
107    }
108
109    /// Whether this chunk closes its source series (not its label set, which two source series
110    /// can share).
111    fn is_last(&self) -> bool {
112        match self {
113            Self::Raw(chunk) => chunk.is_last,
114            Self::Evaluated(chunk) => chunk.is_last,
115            // The producer is done with these groups; a `Final` still closes a group only when
116            // its whole input ends.
117            Self::AggregateState(_) => true,
118        }
119    }
120
121    /// An estimate of the bytes this chunk holds; shared buffers and tables are counted in full
122    /// for every chunk.
123    fn bytes(&self) -> usize {
124        match self {
125            Self::Raw(chunk) => raw_bytes(chunk),
126            Self::Evaluated(chunk) => evaluated_bytes(chunk),
127            Self::AggregateState(chunk) => state_bytes(chunk),
128        }
129    }
130}
131
132/// The bytes a raw chunk holds: its identity, its timestamps and the Arrow buffers behind its
133/// fields.
134pub(crate) fn raw_bytes(chunk: &RawSeriesChunk) -> usize {
135    std::mem::size_of::<RawSeriesChunk>()
136        .saturating_add(buffer_bytes(&chunk.primary_key))
137        .saturating_add(chunk.metric.as_ref().map_or(0, metric_bytes))
138        .saturating_add(buffer_bytes(chunk.time.as_buffer().inner()))
139        .saturating_add(fields_bytes(&chunk.fields))
140}
141
142/// The bytes an evaluated chunk holds: its struct and the Arrow buffers behind its fields, but not
143/// the shared grid.
144pub(super) fn evaluated_bytes(chunk: &EvaluatedChunk) -> usize {
145    std::mem::size_of::<EvaluatedChunk>().saturating_add(fields_bytes(&chunk.series.fields))
146}
147
148/// [`series_bytes`] without the sample buffers and without the `Series` struct: its axis, segment
149/// descriptors and labels. For a retainer that bills buffers through [`unbilled_sample_buffers`]
150/// and counts the struct in its own container.
151pub(crate) fn chunk_bytes_beside_samples(series: &Series) -> usize {
152    series_bytes(series)
153        .saturating_sub(fields_bytes(&series.fields))
154        .saturating_sub(std::mem::size_of::<Series>())
155}
156
157/// The bytes one chunk retained by a binary operand holds: [`chunk_bytes_beside_samples`] plus the
158/// `Series` struct plus the rows its sample slices cover, so a series split into many slices of one
159/// buffer is not billed that buffer per chunk. Histogram tables are excluded; the operand bills
160/// each once through [`unbilled_tables`].
161pub(crate) fn operand_chunk_bytes(series: &Series) -> usize {
162    chunk_bytes_beside_samples(series)
163        .saturating_add(std::mem::size_of::<Series>())
164        .saturating_add(sample_slice_bytes(&series.fields))
165}
166
167/// The dense segments of every field of one chunk. A merged field has several, and asking it for a
168/// single dense view answers `None`.
169pub(crate) fn field_segments(fields: &SeriesFields) -> impl Iterator<Item = &Samples> + '_ {
170    fields.iter().flat_map(|field| field.segments())
171}
172
173/// The bytes the sample slices of one series cover, by rows: floats per value, histograms per
174/// index.
175fn sample_slice_bytes(fields: &SeriesFields) -> usize {
176    field_segments(fields)
177        .map(|segment| match segment.dense() {
178            Some(DenseSamplesRef::Float(values)) => {
179                values.len().saturating_mul(std::mem::size_of::<f64>())
180            }
181            Some(DenseSamplesRef::Histogram(histograms)) => histograms
182                .indices()
183                .len()
184                .saturating_mul(std::mem::size_of::<u32>()),
185            Some(DenseSamplesRef::Mixed(mixed)) => mixed
186                .floats()
187                .len()
188                .saturating_mul(std::mem::size_of::<f64>())
189                .saturating_add(
190                    mixed
191                        .histograms()
192                        .indices()
193                        .len()
194                        .saturating_mul(std::mem::size_of::<u32>()),
195                ),
196            // `segments` hands out dense segments only, so a nested chunk never reaches here.
197            None => 0,
198        })
199        .fold(0usize, usize::saturating_add)
200}
201
202/// The Arrow allocations (values and validity bitmaps) `series`' samples live in that neither
203/// `billed` nor this chunk has already listed, with their bytes: full capacity plus one identity
204/// slot each. A retained slice keeps its whole allocation resident, so it is billed in full, once.
205///
206/// The identity is [`Buffer::data_ptr`], shared by every slice of one allocation; it stays unique
207/// while remembered because the retained chunk keeps the allocation alive. The caller adds the
208/// returned identities to `billed` after retaining the chunk.
209pub(crate) fn unbilled_sample_buffers(
210    series: &Series,
211    billed: &HashSet<usize>,
212) -> (Vec<usize>, usize) {
213    let mut fresh: Vec<usize> = Vec::new();
214    let mut bytes = 0usize;
215    for field in series.fields.iter() {
216        for segment in field.segments() {
217            match segment.dense() {
218                Some(DenseSamplesRef::Float(values)) => {
219                    unbilled_array_buffers(values, &mut fresh, billed, &mut bytes)
220                }
221                Some(DenseSamplesRef::Histogram(histograms)) => {
222                    unbilled_array_buffers(histograms.indices(), &mut fresh, billed, &mut bytes)
223                }
224                Some(DenseSamplesRef::Mixed(mixed)) => {
225                    unbilled_array_buffers(mixed.floats(), &mut fresh, billed, &mut bytes);
226                    unbilled_array_buffers(
227                        mixed.histograms().indices(),
228                        &mut fresh,
229                        billed,
230                        &mut bytes,
231                    );
232                }
233                // `segments` hands out dense segments only, so a nested chunk never reaches here.
234                None => {}
235            }
236        }
237    }
238    (fresh, bytes)
239}
240
241/// [`unbilled_buffer`] for a sample array's values and validity bitmap.
242fn unbilled_array_buffers<T: ArrowPrimitiveType>(
243    values: &PrimitiveArray<T>,
244    fresh: &mut Vec<usize>,
245    billed: &HashSet<usize>,
246    bytes: &mut usize,
247) {
248    unbilled_buffer(values.values().inner(), fresh, billed, bytes);
249    if let Some(nulls) = values.nulls() {
250        unbilled_buffer(nulls.buffer(), fresh, billed, bytes);
251    }
252}
253
254/// Adds the allocation `buffer` is a slice of to `fresh` and `bytes`, once.
255fn unbilled_buffer(
256    buffer: &Buffer,
257    fresh: &mut Vec<usize>,
258    billed: &HashSet<usize>,
259    bytes: &mut usize,
260) {
261    let held = buffer_bytes(buffer);
262    if held == 0 {
263        return;
264    }
265    let identity = buffer.data_ptr().as_ptr() as usize;
266    if billed.contains(&identity) || fresh.contains(&identity) {
267        return;
268    }
269    fresh.push(identity);
270    *bytes = bytes
271        .saturating_add(held)
272        .saturating_add(std::mem::size_of::<usize>());
273}
274
275/// The histogram tables `series` references that neither `billed` nor this chunk has already
276/// listed, with their [`table_bytes`] plus one identity slot each. The identity is the `Arc`'s
277/// address, unique while the retained chunk keeps the table alive. The caller adds the identities
278/// to `billed` after retaining the chunk.
279pub(crate) fn unbilled_tables(series: &Series, billed: &HashSet<usize>) -> (Vec<usize>, usize) {
280    let mut fresh: Vec<usize> = Vec::new();
281    let mut bytes = 0usize;
282    for field in series.fields.iter() {
283        for segment in field.segments() {
284            let table = match segment.dense() {
285                Some(DenseSamplesRef::Histogram(histograms)) => histograms.batch(),
286                Some(DenseSamplesRef::Mixed(mixed)) => mixed.histograms().batch(),
287                _ => continue,
288            };
289            let identity = Arc::as_ptr(table) as usize;
290            if billed.contains(&identity) || fresh.contains(&identity) {
291                continue;
292            }
293            fresh.push(identity);
294            bytes = bytes
295                .saturating_add(table_bytes(table))
296                .saturating_add(std::mem::size_of::<usize>());
297        }
298    }
299    (fresh, bytes)
300}
301
302/// A rough workspace estimate for merging fragments that hold `rows` rows between them. Values
303/// and histogram tables stay shared with the fragments and are not counted.
304pub(crate) fn merge_workspace_bytes(rows: usize, fragments: usize, fields: usize) -> usize {
305    let sorted_rows = rows.saturating_mul(
306        std::mem::size_of::<(usize, usize, usize)>() + std::mem::size_of::<usize>(),
307    );
308    let readers = fragments.saturating_mul(
309        fields.saturating_mul(std::mem::size_of::<Samples>() + 4 * std::mem::size_of::<usize>()),
310    );
311    // Run and field descriptors for rows alternating between fragments or gaps.
312    let merged_field_per_row =
313        2 * std::mem::size_of::<Samples>() + 3 * std::mem::size_of::<usize>();
314    let merged_fields = rows
315        .saturating_mul(fields)
316        .saturating_mul(merged_field_per_row);
317    let output = fragments.saturating_mul(
318        std::mem::size_of::<Series>() + fields.saturating_mul(std::mem::size_of::<Samples>()),
319    );
320    sorted_rows
321        .saturating_add(readers)
322        .saturating_add(merged_fields)
323        .saturating_add(output)
324}
325
326/// The bytes of the whole allocation `buffer` is a slice of: the capacity is what a slice keeps
327/// alive.
328fn buffer_bytes(buffer: &Buffer) -> usize {
329    buffer.capacity().max(buffer.len())
330}
331
332/// Which of an execution's inputs a caller's chunk belongs to: the leaf's position counted left to
333/// right. Meaningful only within one tree.
334#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
335pub struct InputId(usize);
336
337impl InputId {
338    /// The input at `index`, counted left to right.
339    pub fn new(index: usize) -> Self {
340        Self(index)
341    }
342
343    /// The position this id names.
344    pub fn index(self) -> usize {
345        self.0
346    }
347}
348
349/// The series whose first chunk this buffer received and whose closing chunk it has not seen.
350struct OpenSeries {
351    metric: SeriesLabels,
352    last_position: Option<usize>,
353}
354
355/// The input a [`RuntimeOp::Window`] or a [`RuntimeOp::Merge`] collects until its input ends, then
356/// merges into one series per label set ([`crate::grid_series::merge_same_labelset`]).
357///
358/// The per-series contract is checked here because the merge would sort a stream that broke it into
359/// a plausible answer.
360struct MergeInput {
361    schema: Arc<SeriesSchema>,
362    /// In arrival order.
363    fragments: Vec<Series>,
364    /// An estimate of the fragments plus the merge workspace.
365    bytes: usize,
366    /// The series the next chunk must continue, if the last chunk did not close it.
367    open: Option<OpenSeries>,
368}
369
370impl MergeInput {
371    fn new(schema: Arc<SeriesSchema>) -> Self {
372        Self {
373            schema,
374            fragments: Vec::new(),
375            bytes: 0,
376            open: None,
377        }
378    }
379
380    /// Checks one chunk against the series contract and tracks the open series: it must match the
381    /// input grid and schema, continue the open series' labels, and move strictly forward. A chunk
382    /// with `is_last` closes the series whether or not it holds rows.
383    fn check(&mut self, series: &Series, is_last: bool) -> Result<()> {
384        let on_grid = match (&self.schema.eval_grid, series.time.grid()) {
385            (Some(input), Some(grid)) => input.spec() == grid.spec(),
386            _ => false,
387        };
388        if !on_grid
389            || series.fields.len() != self.schema.fields.len()
390            || series
391                .fields
392                .iter()
393                .any(|field| field.len() != series.time.len())
394        {
395            return Err(DataFusionError::Execution(
396                "merge input does not match its input schema".to_string(),
397            ));
398        }
399        let (first, last) = (series.time.first_position(), series.time.last_position());
400        if !is_last && first.is_none() {
401            return Err(DataFusionError::Execution(
402                "merge input has no position before the last run of its series".to_string(),
403            ));
404        }
405        if let Some(open) = &self.open
406            && open.metric != series.metric
407        {
408            return Err(DataFusionError::Execution(
409                "merge input changed identity before its last run".to_string(),
410            ));
411        }
412        if let Some(previous) = self.open.as_ref().and_then(|open| open.last_position)
413            && let Some(first) = first
414            && first <= previous
415        {
416            return Err(DataFusionError::Execution(format!(
417                "merge input runs are not increasing: {first} after {previous}"
418            )));
419        }
420        self.open = if is_last {
421            None
422        } else {
423            Some(OpenSeries {
424                metric: series.metric.clone(),
425                last_position: last,
426            })
427        };
428        Ok(())
429    }
430
431    /// The workspace merging the fragments needs; see [`merge_workspace_bytes`].
432    fn workspace_bytes(&self) -> usize {
433        let rows: usize = self
434            .fragments
435            .iter()
436            .map(|fragment| fragment.time.len())
437            .sum();
438        merge_workspace_bytes(rows, self.fragments.len(), self.schema.fields.len())
439    }
440}
441
442/// A node's metric handles and its memory reservation in the query's pool.
443pub(super) struct NodeBuffer {
444    metrics: Arc<NodeMetrics>,
445    reservation: MemoryReservation,
446    /// The bytes reserved for this node's grid timestamps, kept across every resize;
447    /// `None` until [`NodeBuffer::reserve_grid`] reserves them.
448    grid: Option<usize>,
449}
450
451impl NodeBuffer {
452    /// Registers a reservation with `pool`, labelled `name` (e.g. `native.window at root.left`) in
453    /// errors and pool reports.
454    pub(super) fn new(
455        name: impl Into<String>,
456        metrics: Arc<NodeMetrics>,
457        pool: &Arc<dyn MemoryPool>,
458    ) -> Self {
459        let consumer = MemoryConsumer::new(name.into());
460        Self {
461            metrics,
462            reservation: consumer.register(pool),
463            grid: None,
464        }
465    }
466
467    /// Reserves `grid`'s timestamps before this node first reads them, once per node. An
468    /// [`EvalGrid`] materializes them lazily and keeps them for the plan's lifetime, so the node
469    /// that triggers materialization keeps the reservation; a grid already materialized was charged
470    /// by whoever did it. The `grid` record also short-circuits: a collecting window reserves on
471    /// every chunk long before it materializes the grid at flush.
472    pub(super) fn reserve_grid(&mut self, grid: &EvalGrid) -> Result<()> {
473        if self.grid.is_some() || grid.is_materialized() {
474            return Ok(());
475        }
476        let len = usize::try_from(grid.spec().len).map_err(|_| {
477            DataFusionError::Execution("grid length does not fit memory size".to_string())
478        })?;
479        let bytes = len.checked_mul(std::mem::size_of::<i64>()).ok_or_else(|| {
480            DataFusionError::Execution("grid timestamp size overflow".to_string())
481        })?;
482        self.grow(bytes)?;
483        self.grid = Some(bytes);
484        Ok(())
485    }
486
487    /// Reserves `bytes` beside what this node already holds.
488    pub(super) fn grow(&mut self, bytes: usize) -> Result<()> {
489        self.reservation.try_grow(bytes)?;
490        self.record();
491        Ok(())
492    }
493
494    /// Sets the reservation to `bytes` plus the grid timestamps reserved by [`Self::reserve_grid`].
495    pub(super) fn resize(&mut self, bytes: usize) -> Result<()> {
496        self.reservation
497            .try_resize(bytes.saturating_add(self.grid.unwrap_or(0)))?;
498        self.record();
499        Ok(())
500    }
501
502    /// Gives `bytes` of what this node holds back to the pool.
503    fn shrink(&mut self, bytes: usize) -> Result<()> {
504        self.reservation.try_shrink(bytes)?;
505        self.record();
506        Ok(())
507    }
508
509    /// Splits `bytes` off into a separate reservation; the pool total is unchanged.
510    fn transfer(&mut self, bytes: usize) -> Result<MemoryReservation> {
511        // Only an accounting drift gets here; `split` would panic.
512        if bytes > self.reservation.size() {
513            return Err(DataFusionError::Internal(format!(
514                "a queued chunk holds {bytes} bytes, more than the {} its node reserves",
515                self.reservation.size()
516            )));
517        }
518        let reservation = self.reservation.split(bytes);
519        self.record();
520        Ok(reservation)
521    }
522
523    /// Reports what this node now reserves.
524    fn record(&self) {
525        self.metrics.record_reserved_bytes(self.reservation.size());
526    }
527}
528
529impl Drop for NodeBuffer {
530    fn drop(&mut self) {
531        self.reservation.free();
532        self.record();
533    }
534}
535
536/// The bytes a metric name holds: its name and each tag's name and value, one row per label.
537fn metric_bytes(metric: &SeriesLabels) -> usize {
538    metric.name().map_or(0, |name| name.len())
539        + std::mem::size_of_val(metric.tags())
540        + metric
541            .tags()
542            .iter()
543            .map(|tag| tag.name.len() + tag.value.len())
544            .sum::<usize>()
545}
546
547/// What a map node applies.
548struct MapRuntime {
549    ops: Arc<[MapOp]>,
550    /// The output schema, which the input is checked against.
551    schema: Arc<SeriesSchema>,
552}
553
554/// An instant selection. [`select_instants`] takes a complete source axis, so this buffers each
555/// series until its last chunk and emits one chunk for it.
556struct InstantRuntime {
557    selection: BoundInstant,
558    /// The input's fields on the selection's output grid.
559    schema: Arc<SeriesSchema>,
560    output: GridSeriesBuilder,
561    /// The chunks of the open series; empty while none is open.
562    chunks: Vec<RawSeriesChunk>,
563    /// The bytes `chunks` hold.
564    held: usize,
565}
566
567impl InstantRuntime {
568    fn try_new(input: &SeriesSchema, op: &BoundInstant) -> Result<Self> {
569        let schema = Arc::new(SeriesSchema {
570            fields: Arc::clone(&input.fields),
571            eval_grid: Some(Arc::clone(&op.output_grid)),
572        });
573        Ok(Self {
574            selection: op.clone(),
575            output: GridSeriesBuilder::try_new(Arc::clone(&schema))?,
576            schema,
577            chunks: Vec::new(),
578            held: 0,
579        })
580    }
581
582    fn buffered_bytes(&self) -> usize {
583        self.held
584    }
585
586    /// An upper bound on what gathering the series `closing` ends allocates beside the buffered
587    /// chunks: the concatenated axis and segment descriptors, the [`select_instants`] output, and
588    /// the builder's rows doubled for `Vec` growth. A histogram field is charged its largest row
589    /// per selected point, since every point can select the same row.
590    fn gather_bytes(&self, closing: &RawSeriesChunk) -> usize {
591        let points = self.selected_points(closing);
592        let chunks = self.chunks.len().saturating_add(1);
593        let rows = self
594            .chunks
595            .iter()
596            .chain(std::iter::once(closing))
597            .map(|chunk| chunk.time.len())
598            .fold(0usize, usize::saturating_add);
599        let fields = self.schema.fields.len();
600        let descriptor = std::mem::size_of::<Samples>();
601        let segments = self
602            .chunks
603            .iter()
604            .chain(std::iter::once(closing))
605            .flat_map(|chunk| chunk.fields.as_slice())
606            .map(|field| field.segments().len())
607            .fold(0usize, usize::saturating_add);
608        let axis = rows.saturating_mul(std::mem::size_of::<i64>());
609        let layout = chunks
610            .saturating_mul(fields)
611            .saturating_mul(descriptor)
612            .saturating_add(segments.saturating_mul(3).saturating_mul(descriptor))
613            .saturating_add(fields.saturating_mul(std::mem::size_of::<Vec<Samples>>()));
614        let selection =
615            points.saturating_mul(std::mem::size_of::<u64>() + std::mem::size_of::<i64>());
616        let mut rows_of_points = points.saturating_mul(
617            std::mem::size_of::<usize>() + fields.saturating_mul(std::mem::size_of::<f64>() + 1),
618        );
619        for largest in self.largest_histograms(closing).iter().flatten() {
620            rows_of_points = rows_of_points.saturating_add(
621                points.saturating_mul(std::mem::size_of::<Option<u32>>().saturating_add(*largest)),
622            );
623        }
624        let row = fields.saturating_mul(
625            std::mem::size_of::<Option<GridSample>>() + std::mem::size_of::<RowCursor<'_>>(),
626        );
627        axis.saturating_add(layout)
628            .saturating_add(selection)
629            .saturating_add(row)
630            .saturating_add(rows_of_points.saturating_mul(2))
631    }
632
633    /// The candidate grid points [`select_instants`] can decide for the buffered series, clipped to
634    /// the series' span unless an `@` modifier pins the selection.
635    fn selected_points(&self, closing: &RawSeriesChunk) -> usize {
636        let spec = self.selection.output_grid.spec();
637        if self.selection.at_ms.is_some() {
638            return usize::try_from(spec.len).unwrap_or(usize::MAX);
639        }
640        // The selection refuses these itself, before it can decide anything.
641        if spec.step_ms <= 0 || self.selection.lookback_ms < 0 {
642            return 0;
643        }
644        let query_end = grid_end_ms(spec);
645        if query_end < spec.start_ms {
646            return 0;
647        }
648        let series = || self.chunks.iter().chain(std::iter::once(closing));
649        let endpoints = series()
650            .find_map(|chunk| chunk.time.as_buffer().first().copied())
651            .zip(
652                series()
653                    .rev()
654                    .find_map(|chunk| chunk.time.as_buffer().last().copied()),
655            );
656        let span = instant_candidate_span(
657            endpoints,
658            spec.start_ms..=query_end,
659            spec.step_ms,
660            self.selection.lookback_ms,
661            self.selection.offset_ms,
662        );
663        usize::try_from(span.count).unwrap_or(usize::MAX)
664    }
665
666    /// The largest histogram row of each field, `None` for a float field.
667    fn largest_histograms(&self, closing: &RawSeriesChunk) -> Vec<Option<usize>> {
668        let mut largest = vec![None; self.schema.fields.len()];
669        for chunk in self.chunks.iter().chain(std::iter::once(closing)) {
670            for (slot, field) in largest.iter_mut().zip(chunk.fields.as_slice()) {
671                if let Some(bytes) = histogram_row_bytes(field) {
672                    *slot = Some(slot.unwrap_or(0).max(bytes));
673                }
674            }
675        }
676        largest
677    }
678
679    /// Buffers one chunk of the open series and gathers it on its last chunk; `None` while the
680    /// series is open.
681    fn push(&mut self, chunk: RawSeriesChunk) -> Result<Option<EvaluatedChunk>> {
682        if let Some(open) = self.chunks.first()
683            && (open.primary_key.as_slice() != chunk.primary_key.as_slice()
684                || open.metric != chunk.metric)
685        {
686            return Err(series_changed());
687        }
688        let closing = chunk.is_last;
689        self.held = self.held.saturating_add(raw_bytes(&chunk));
690        self.chunks.push(chunk);
691        if !closing {
692            return Ok(None);
693        }
694        self.gather().map(Some)
695    }
696
697    /// Selects the instants of the buffered series and frees the buffer.
698    fn gather(&mut self) -> Result<EvaluatedChunk> {
699        let chunk = self.select()?;
700        self.chunks.clear();
701        self.chunks.shrink_to_fit();
702        self.held = 0;
703        Ok(chunk)
704    }
705
706    /// The last sample at or before each grid point of the buffered series, as one chunk.
707    fn select(&mut self) -> Result<EvaluatedChunk> {
708        let Some(first) = self.chunks.first() else {
709            return Err(DataFusionError::Execution(
710                "the instant selection holds no series to select".to_string(),
711            ));
712        };
713        let metric = first.metric.clone().ok_or_else(no_labels)?;
714        let time = buffered_time(&self.chunks)?;
715        let fields = buffered_fields(&self.chunks, self.schema.fields.len())?;
716        let grid = Arc::clone(&self.selection.output_grid);
717        let spec = grid.spec();
718        if let Some(at_ms) = self.selection.at_ms {
719            let timestamp_window = if self.selection.value == InstantValue::Timestamp
720                && self.selection.lookback_ms >= 0
721            {
722                let anchor = at_ms as i128;
723                let shifted = anchor - self.selection.offset_ms as i128;
724                let lower = anchor.max(shifted) - self.selection.lookback_ms as i128;
725                let upper = anchor.min(shifted);
726                if lower > upper || (lower == upper && self.selection.lookback_ms != 0) {
727                    None
728                } else {
729                    let effective_lookback = i64::try_from(upper - lower).ok();
730                    effective_lookback.and_then(|lookback| {
731                        i64::try_from(upper).ok().map(|upper| (upper, lookback))
732                    })
733                }
734            } else {
735                Some((at_ms, self.selection.lookback_ms))
736            };
737            let Some((selection_at, selection_lookback)) = timestamp_window else {
738                let metric = drop_metric_name(&metric)?;
739                return no_row_chunk(&self.schema, metric);
740            };
741            let Some(index) = select_instant_at(
742                &time,
743                &fields,
744                selection_at,
745                selection_lookback,
746                if self.selection.value == InstantValue::Timestamp {
747                    0
748                } else {
749                    self.selection.offset_ms
750                },
751            )?
752            else {
753                return no_row_chunk(&self.schema, self.output_metric(&metric)?);
754            };
755            let grid_len = usize::try_from(spec.len).unwrap_or(usize::MAX);
756            if self.selection.value != InstantValue::Sample {
757                let indices = vec![index; grid_len];
758                let timestamps = grid
759                    .timestamps()
760                    .map_err(crate::grid_series::external)?
761                    .to_vec();
762                return self.project(&metric, &time, &fields, &indices, &timestamps);
763            }
764            self.output.begin_series();
765            let mut cursors: Vec<RowCursor<'_>> = fields.iter().map(Samples::cursor).collect();
766            let mut row = Vec::with_capacity(fields.len());
767            for cursor in &mut cursors {
768                row.push(owned(
769                    cursor
770                        .at(index as usize)
771                        .ok_or_else(|| missing_row(index as usize))?,
772                )?);
773            }
774            for position in 0..grid_len {
775                self.output.push_samples(position, &row)?;
776            }
777            return match self.output.finish(metric.clone())? {
778                Some(series) => EvaluatedChunk::try_new(series, true),
779                None => no_row_chunk(&self.schema, metric),
780            };
781        }
782        let (indices, timestamps) = select_instants(
783            &time,
784            &fields,
785            spec.start_ms..=grid_end_ms(spec),
786            spec.step_ms,
787            self.selection.lookback_ms,
788            self.selection.offset_ms,
789        )?;
790        if self.selection.value != InstantValue::Sample {
791            return self.project(&metric, &time, &fields, &indices, &timestamps);
792        }
793        self.output.begin_series();
794        let mut cursors: Vec<RowCursor<'_>> = fields.iter().map(Samples::cursor).collect();
795        // `GridSample` is not `Clone`, so the row is filled slot by slot rather than from one
796        // value.
797        let mut row: Vec<Option<GridSample>> = (0..fields.len()).map(|_| None).collect();
798        let mut read: Option<usize> = None;
799        for (index, timestamp) in indices.iter().zip(&timestamps) {
800            let index = *index as usize;
801            let position = grid_position(&grid, *timestamp)?;
802            // Consecutive grid points can select the same source row.
803            if read != Some(index) {
804                for (slot, cursor) in row.iter_mut().zip(&mut cursors) {
805                    let sample = cursor.at(index).ok_or_else(|| missing_row(index))?;
806                    *slot = owned(sample)?;
807                }
808                read = Some(index);
809            }
810            // The builder drops a position where every field is empty.
811            self.output.push_samples(position, &row)?;
812        }
813        match self.output.finish(metric.clone())? {
814            Some(series) => EvaluatedChunk::try_new(series, true),
815            None => no_row_chunk(&self.schema, metric),
816        }
817    }
818
819    /// The labels this selection reports a series under: `timestamp(x)` drops the metric name.
820    fn output_metric(&self, metric: &SeriesLabels) -> Result<SeriesLabels> {
821        match self.selection.value {
822            InstantValue::Timestamp => drop_metric_name(metric),
823            InstantValue::Sample | InstantValue::InfoTimestamp => Ok(metric.clone()),
824        }
825    }
826
827    /// The selected sample times, for `timestamp()` and `info` selections.
828    fn project(
829        &self,
830        metric: &SeriesLabels,
831        time: &RawTimestamps,
832        fields: &SeriesFields,
833        indices: &[u64],
834        timestamps: &[i64],
835    ) -> Result<EvaluatedChunk> {
836        let projected = match self.selection.value {
837            InstantValue::Timestamp => {
838                timestamp_of_selection(&self.schema, metric, time, fields, indices, timestamps)?
839            }
840            InstantValue::InfoTimestamp => {
841                info_sample_times(&self.schema, metric, time, fields, indices, timestamps)?
842            }
843            InstantValue::Sample => {
844                return Err(DataFusionError::Internal(
845                    "an instant selection of samples has no sample times to project".to_string(),
846                ));
847            }
848        };
849        match projected {
850            Some(series) => EvaluatedChunk::try_new(series, true),
851            None => no_row_chunk(&self.schema, self.output_metric(metric)?),
852        }
853    }
854}
855
856/// An input a node reads whole before it computes (a binary operand, or the input of a vector
857/// operation). Chunks are assembled into one series per logical series once the input ends.
858#[derive(Default)]
859struct RetainedInput {
860    /// The open series and the position after its last row. A label set may close and start again
861    /// (as two logical series); starting another series while one is open is an error.
862    open: Option<(SeriesLabels, usize)>,
863    /// In arrival order.
864    series: Vec<Series>,
865    /// The exclusive chunk index at which each logical series closed.
866    ends: Vec<usize>,
867    /// Addresses of histogram tables already billed; see [`unbilled_tables`].
868    tables: HashSet<usize>,
869    /// The bytes `series`, `ends` and the billed tables hold.
870    held: usize,
871}
872
873impl RetainedInput {
874    /// The bytes `chunk` would add; the same figure [`Self::enqueue`] adds, so it can be reserved
875    /// first.
876    fn pending(&self, chunk: &EvaluatedChunk) -> usize {
877        let end = if chunk.is_last {
878            std::mem::size_of::<usize>()
879        } else {
880            0
881        };
882        let (_, tables) = unbilled_tables(&chunk.series, &self.tables);
883        tables
884            .saturating_add(operand_chunk_bytes(&chunk.series))
885            .saturating_add(end)
886    }
887
888    /// Retains one chunk, refusing one that starts another series while one is open or goes back
889    /// inside the open one.
890    fn retain(&mut self, chunk: EvaluatedChunk, reader: Reader) -> Result<()> {
891        let (first, last) = (
892            chunk.series.time.first_position(),
893            chunk.series.time.last_position(),
894        );
895        let metric = chunk.series.metric.clone();
896        let end = self.open.as_ref().map_or(0, |(_, end)| *end);
897        if let Some((open, _)) = &self.open
898            && *open != metric
899        {
900            let (owner, input) = (reader.owner(), reader.input());
901            return Err(DataFusionError::Execution(format!(
902                "{owner} reads whole series, and {input} handed over {metric:?} before {open:?} \
903                 ended"
904            )));
905        }
906        if let Some(first) = first
907            && first < end
908        {
909            let (owner, input) = (reader.owner(), reader.input());
910            return Err(DataFusionError::Execution(format!(
911                "{owner} was handed chunks of {metric:?} by {input} that do not continue each \
912                 other: one starts at position {first}, after the series already reached {end}"
913            )));
914        }
915        self.open = (!chunk.is_last).then(|| (metric, last.map_or(end, |last| last + 1)));
916        self.enqueue(chunk);
917        Ok(())
918    }
919
920    /// Refuses an input that ended with a series still open.
921    fn ensure_closed(&self, reader: Reader) -> Result<()> {
922        match &self.open {
923            Some((metric, _)) => Err(DataFusionError::Execution(format!(
924                "the input of {} ended before the last chunk of a series: {} handed over \
925                 {metric:?} without the chunk that closes it",
926                reader.owner(),
927                reader.input()
928            ))),
929            None => Ok(()),
930        }
931    }
932
933    /// Retains one chunk and adds the [`Self::pending`] figure to `held`.
934    fn enqueue(&mut self, chunk: EvaluatedChunk) {
935        let closing = chunk.is_last;
936        let (tables, bytes) = unbilled_tables(&chunk.series, &self.tables);
937        self.held = self
938            .held
939            .saturating_add(if closing {
940                std::mem::size_of::<usize>()
941            } else {
942                0
943            })
944            .saturating_add(operand_chunk_bytes(&chunk.series))
945            .saturating_add(bytes);
946        self.tables.extend(tables);
947        self.series.push(chunk.series);
948        if closing {
949            self.ends.push(self.series.len());
950        }
951    }
952
953    /// The chunk ranges of the logical series this operand closed, in arrival order.
954    fn boundaries(&self) -> impl Iterator<Item = std::ops::Range<usize>> + '_ {
955        self.ends.iter().scan(0, |start, &end| {
956            let range = *start..end;
957            *start = end;
958            Some(range)
959        })
960    }
961
962    /// The metadata assembling this operand's chunks into logical series allocates; samples are
963    /// shared, not copied. Per series: the entry and field list; per chunk and field: one
964    /// descriptor; per segment: three descriptors (flatten copy, `Arc<[Samples]>` slot, vector
965    /// doubling); per run: the collected span plus [`TimeAxis::from_grid_spans`]'s copies.
966    fn assembly_bytes(&self, schema: &SeriesSchema) -> Option<usize> {
967        let samples = std::mem::size_of::<Samples>();
968        let grids = std::mem::size_of::<GridSpan>();
969        let width = schema.fields.len();
970        let mut bytes = 0usize;
971        for boundary in self.boundaries() {
972            let chunks = &self.series[boundary];
973            let mut runs = 0usize;
974            let mut segments = 0usize;
975            for chunk in chunks {
976                runs = runs.checked_add(chunk.time.runs().count())?;
977                for field in chunk.fields.iter() {
978                    segments = segments.checked_add(field.segments().len())?;
979                }
980            }
981            // `+ width`: a field with no segment still builds one empty `Samples`.
982            let descriptors = chunks
983                .len()
984                .checked_mul(width)?
985                .checked_add(segments.checked_mul(3)?.checked_add(width)?)?;
986            let axis = runs.checked_mul(
987                grids
988                    .checked_mul(2)?
989                    .checked_add(std::mem::size_of::<usize>())?,
990            )?;
991            bytes = bytes
992                .checked_add(std::mem::size_of::<Series>())?
993                .checked_add(width.checked_mul(samples)?)?
994                .checked_add(descriptors.checked_mul(samples)?)?
995                .checked_add(axis)?;
996        }
997        Some(bytes)
998    }
999
1000    /// The logical series this operand closed, each as one series on `schema`'s grid. Fields are
1001    /// chained segment descriptors sharing the retained buffers; reserve [`Self::assembly_bytes`]
1002    /// first.
1003    fn assemble(&self, schema: &SeriesSchema, reader: Reader) -> Result<Vec<Series>> {
1004        let grid = schema.eval_grid.clone().ok_or_else(|| {
1005            let (owner, input) = (reader.owner(), reader.input());
1006            DataFusionError::Execution(format!(
1007                "{owner} assembles {input} on an evaluation grid, and its schema names none"
1008            ))
1009        })?;
1010        let mut assembled = Vec::with_capacity(self.ends.len());
1011        for boundary in self.boundaries() {
1012            let chunks = &self.series[boundary];
1013            let metric = chunks
1014                .first()
1015                .map(|chunk| chunk.metric.clone())
1016                .ok_or_else(|| {
1017                    let (owner, input) = (reader.owner(), reader.input());
1018                    DataFusionError::Execution(format!(
1019                        "{owner} closed a logical series of {input} without a chunk to assemble"
1020                    ))
1021                })?;
1022            let runs = chunks
1023                .iter()
1024                .map(|chunk| chunk.time.runs().count())
1025                .fold(0usize, usize::saturating_add);
1026            let mut spans = Vec::with_capacity(runs);
1027            for chunk in chunks {
1028                for run in chunk.time.runs() {
1029                    spans.push(GridSpan::new(run.position, run.len));
1030                }
1031            }
1032            let mut fields = Vec::with_capacity(schema.fields.len());
1033            for index in 0..schema.fields.len() {
1034                let mut segments = Vec::with_capacity(chunks.len());
1035                for chunk in chunks {
1036                    let field = chunk.fields.get(index).ok_or_else(|| {
1037                        let (owner, input) = (reader.owner(), reader.input());
1038                        DataFusionError::Execution(format!(
1039                            "{owner} cannot assemble {input}: a chunk of it carries {} fields, not \
1040                             {}",
1041                            chunk.fields.len(),
1042                            schema.fields.len()
1043                        ))
1044                    })?;
1045                    segments.push(field.clone());
1046                }
1047                fields.push(Samples::try_from_chunks(segments).map_err(series_error)?);
1048            }
1049            let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?;
1050            let time = TimeAxis::from_grid_spans(grid.clone(), spans).map_err(series_error)?;
1051            assembled.push(Series::try_new(schema, metric, time, fields).map_err(series_error)?);
1052        }
1053        Ok(assembled)
1054    }
1055
1056    /// Drops the retained chunks, giving back what they hold.
1057    fn release(&mut self) {
1058        self.open = None;
1059        self.series.clear();
1060        self.series.shrink_to_fit();
1061        self.ends.clear();
1062        self.ends.shrink_to_fit();
1063        self.tables.clear();
1064        self.tables.shrink_to_fit();
1065        self.held = 0;
1066    }
1067}
1068
1069/// A binary, set or `info` node: retains both operands until they end, then assembles their logical
1070/// series and runs the kernel once.
1071struct BinaryRuntime {
1072    node_index: usize,
1073    /// Evidence shared with the other output partitions of this fused-series execution.
1074    evidence: Option<Arc<DuplicateEvidence>>,
1075    /// The query's collector for dropped histogram sample pairs, when requested.
1076    annotations: Option<PromqlAnnotationCollector>,
1077    kernel: PairKernel,
1078    /// Left then right; each chunk is checked against its operand's schema.
1079    schemas: [Arc<SeriesSchema>; 2],
1080    operands: [RetainedInput; 2],
1081    /// Whether the kernel has run; it runs once, since it drops the operands.
1082    computed: bool,
1083}
1084
1085/// The kernel a [`BinaryRuntime`] runs over its two assembled operands.
1086enum PairKernel {
1087    /// An arithmetic or comparison operation between matched series.
1088    Binary(Arc<BinaryMatching>),
1089    /// `and`, `or` or `unless`, which keeps samples of either side as they are.
1090    Set(BoundSetOp),
1091    /// `info`, whose left operand is the base and right operand the info series' sample times.
1092    Info(InfoSelector),
1093}
1094
1095impl PairKernel {
1096    /// The node name used in errors.
1097    fn node(&self) -> &'static str {
1098        match self {
1099            Self::Binary(_) => "the binary node",
1100            Self::Set(_) => "the set node",
1101            Self::Info(_) => "the info node",
1102        }
1103    }
1104}
1105
1106fn side_name(index: usize) -> &'static str {
1107    match index {
1108        0 => "left",
1109        _ => "right",
1110    }
1111}
1112
1113/// The owner of a [`RetainedInput`], named in its errors.
1114#[derive(Clone, Copy)]
1115enum Reader {
1116    Operand { side: usize, node: &'static str },
1117    Vector,
1118}
1119
1120impl Reader {
1121    fn owner(self) -> String {
1122        match self {
1123            Self::Operand { node, .. } => node.to_string(),
1124            Self::Vector => "the vector operation".to_string(),
1125        }
1126    }
1127
1128    fn input(self) -> String {
1129        match self {
1130            Self::Operand { side, .. } => format!("its {} operand", side_name(side)),
1131            Self::Vector => "its input".to_string(),
1132        }
1133    }
1134}
1135
1136impl BinaryRuntime {
1137    /// This node's evidence slot for a field.
1138    fn slot(&self, field: usize) -> (usize, usize) {
1139        (self.node_index, field)
1140    }
1141
1142    fn new(
1143        kernel: PairKernel,
1144        schemas: [Arc<SeriesSchema>; 2],
1145        node_index: usize,
1146        evidence: Option<Arc<DuplicateEvidence>>,
1147    ) -> Self {
1148        Self {
1149            node_index,
1150            evidence,
1151            annotations: None,
1152            kernel,
1153            schemas,
1154            operands: [RetainedInput::default(), RetainedInput::default()],
1155            computed: false,
1156        }
1157    }
1158
1159    fn reader(&self, side: usize) -> Reader {
1160        Reader::Operand {
1161            side,
1162            node: self.kernel.node(),
1163        }
1164    }
1165
1166    fn retained_bytes(&self) -> usize {
1167        self.operands
1168            .iter()
1169            .map(|operand| operand.held)
1170            .fold(0usize, usize::saturating_add)
1171    }
1172
1173    fn assembly_bytes(&self) -> Option<usize> {
1174        let [left, right] = &self.operands;
1175        let [left_schema, right_schema] = &self.schemas;
1176        left.assembly_bytes(left_schema)?
1177            .checked_add(right.assembly_bytes(right_schema)?)
1178    }
1179
1180    fn assemble(&self) -> Result<[Vec<Series>; 2]> {
1181        let [left, right] = &self.operands;
1182        let [left_schema, right_schema] = &self.schemas;
1183        Ok([
1184            left.assemble(left_schema, self.reader(0))?,
1185            right.assemble(right_schema, self.reader(1))?,
1186        ])
1187    }
1188
1189    /// The bytes the chunk of `side` would add to that operand; see [`RetainedInput::pending`].
1190    fn pending(&self, side: usize, chunk: &EvaluatedChunk) -> Result<usize> {
1191        self.operands
1192            .get(side)
1193            .map(|operand| operand.pending(chunk))
1194            .ok_or_else(invalid_binary_operand)
1195    }
1196
1197    /// Refuses an operand that ended with a series still open.
1198    fn closed(&self) -> Result<()> {
1199        for (side, operand) in self.operands.iter().enumerate() {
1200            operand.ensure_closed(self.reader(side))?;
1201        }
1202        Ok(())
1203    }
1204
1205    /// Retains one chunk of the operand at `side`, after the kernel's own operand check. The bound
1206    /// tree is no proof of what a chunk carries: `Series` fields are public, so a struct-literal
1207    /// chunk can carry another field count or fewer samples than its axis places rows.
1208    fn retain(&mut self, side: usize, chunk: EvaluatedChunk) -> Result<()> {
1209        let Some(schema) = self.schemas.get(side) else {
1210            return Err(invalid_binary_operand());
1211        };
1212        validate_binary_operand(schema.as_ref(), std::slice::from_ref(&chunk.series)).map_err(
1213            |error| {
1214                DataFusionError::Execution(format!(
1215                    "{} rejected its {} operand: {error}",
1216                    self.kernel.node(),
1217                    side_name(side)
1218                ))
1219            },
1220        )?;
1221        let reader = self.reader(side);
1222        let Some(operand) = self.operands.get_mut(side) else {
1223            return Err(invalid_binary_operand());
1224        };
1225        operand.retain(chunk, reader)
1226    }
1227
1228    /// Runs the kernel over both assembled operands, or returns `None` if it already ran.
1229    ///
1230    /// Chunks are assembled into logical series first; otherwise every chunk would be a separate
1231    /// match candidate. The reservation covers retained chunks, assembly and the kernel's reported
1232    /// workspace, then the output until the caller queues it.
1233    fn compute(&mut self, buffer: &mut NodeBuffer) -> Result<Option<Vec<Series>>> {
1234        if self.computed {
1235            return Ok(None);
1236        }
1237        self.closed()?;
1238        let [left_schema, right_schema] = &self.schemas;
1239        let retained = self.retained_bytes();
1240        let node = self.kernel.node();
1241        let assembly = self
1242            .assembly_bytes()
1243            .ok_or_else(|| reservation_overflow(node))?;
1244        buffer.grow(assembly)?;
1245        let assembled = match self.assemble() {
1246            Ok(assembled) => assembled,
1247            Err(error) => {
1248                buffer.resize(retained)?;
1249                return Err(error);
1250            }
1251        };
1252        let [left, right] = &assembled;
1253        let metrics = Arc::clone(&buffer.metrics);
1254        let output = {
1255            let _timer = metrics.timer();
1256            let mut reserve = |workspace: usize| {
1257                let bytes = retained
1258                    .checked_add(assembly)
1259                    .and_then(|held| held.checked_add(workspace))
1260                    .ok_or_else(|| reservation_overflow(node))?;
1261                buffer.resize(bytes)
1262            };
1263            match &self.kernel {
1264                PairKernel::Binary(matching) => {
1265                    let evidence = self.evidence.as_deref();
1266                    binary_vectors_with_reservation(
1267                        matching,
1268                        left_schema,
1269                        left,
1270                        right_schema,
1271                        right,
1272                        evidence.map(|evidence| crate::vector_match::NodeEvidence {
1273                            node: self.slot(0).0,
1274                            evidence,
1275                        }),
1276                        self.annotations.as_ref(),
1277                        &mut reserve,
1278                    )
1279                }
1280                PairKernel::Set(set) => set_vectors_with_reservation(
1281                    set.op,
1282                    &set.labels,
1283                    left_schema,
1284                    left,
1285                    right_schema,
1286                    right,
1287                    &mut reserve,
1288                ),
1289                PairKernel::Info(selector) => {
1290                    info_with_reservation(left_schema, left, right, selector, &mut reserve)
1291                }
1292            }
1293        };
1294        let output = output?;
1295        drop(assembled);
1296        for operand in &mut self.operands {
1297            operand.release();
1298        }
1299        self.computed = true;
1300        Ok(Some(output))
1301    }
1302}
1303
1304/// A vector operation (`topk`, `limitk`, ...): its answer at a point depends on every series there,
1305/// so it retains the whole input and runs the kernel once.
1306struct VectorRuntime {
1307    op: BoundVectorOp,
1308    /// Shared by input and output.
1309    schema: Arc<SeriesSchema>,
1310    input: RetainedInput,
1311    /// Whether pieces of one label set are merged before the kernel; `limitk` needs it when its
1312    /// input can split a label set.
1313    merge_input: bool,
1314    computed: bool,
1315    annotations: Option<PromqlAnnotationCollector>,
1316    /// The per-point k of a parameterized topk/bottomk, in grid position order.
1317    parameter: Option<Vec<Option<f64>>>,
1318    /// The bytes charged for the parameter values.
1319    parameter_bytes: usize,
1320}
1321
1322impl VectorRuntime {
1323    /// Validates the operation's grouping against `schema`.
1324    fn try_new(op: BoundVectorOp, schema: Arc<SeriesSchema>) -> Result<Self> {
1325        // These operations group by labels only; a `by` naming a value field would wrongly merge
1326        // groups.
1327        let bound_grouping = match &op {
1328            BoundVectorOp::TopK { group, .. }
1329            | BoundVectorOp::LimitK { group, .. }
1330            | BoundVectorOp::CountValues { group, .. } => Some(group),
1331            _ => None,
1332        };
1333        if let Some(group) = bound_grouping {
1334            let names = group.names();
1335            let grouping = group.kernel(&names);
1336            match &op {
1337                BoundVectorOp::CountValues { label, .. } => {
1338                    aggregate::validate_count_values(&schema, label, grouping)?
1339                }
1340                _ => aggregate::validate_vector_grouping(&schema, grouping)?,
1341            }
1342        }
1343        Ok(Self {
1344            op,
1345            schema,
1346            input: RetainedInput::default(),
1347            merge_input: false,
1348            computed: false,
1349            annotations: None,
1350            parameter: None,
1351            parameter_bytes: 0,
1352        })
1353    }
1354
1355    /// Runs the kernel over the whole input, or returns `None` if it already ran. The kernels do
1356    /// not report allocations, so their workspace is estimated by [`vector_workspace_bytes`].
1357    fn compute(&mut self, buffer: &mut NodeBuffer) -> Result<Option<Vec<Series>>> {
1358        self.compute_with_histogram_parameters(buffer, &[])
1359    }
1360
1361    fn compute_with_histogram_parameters(
1362        &mut self,
1363        buffer: &mut NodeBuffer,
1364        parameters: &[&[Option<f64>]],
1365    ) -> Result<Option<Vec<Series>>> {
1366        if self.computed {
1367            return Ok(None);
1368        }
1369        self.input.ensure_closed(Reader::Vector)?;
1370        let retained = self.input.held.saturating_add(self.parameter_bytes);
1371        let assembly = self
1372            .input
1373            .assembly_bytes(&self.schema)
1374            .ok_or_else(vector_overflow)?;
1375        buffer.grow(assembly)?;
1376        let assembled = match self.input.assemble(&self.schema, Reader::Vector) {
1377            Ok(assembled) => assembled,
1378            Err(error) => {
1379                buffer.resize(retained)?;
1380                return Err(error);
1381            }
1382        };
1383        // `limitk` keeps series in input order, as Prometheus does; pieces of one label set are one
1384        // series there, so they are merged first.
1385        let assembled = if self.merge_input {
1386            let rows = assembled.iter().map(|series| series.time.len()).sum();
1387            buffer.grow(merge_workspace_bytes(
1388                rows,
1389                assembled.len(),
1390                self.schema.fields.len(),
1391            ))?;
1392            merge_same_labelset(&self.schema, assembled)?
1393        } else {
1394            assembled
1395        };
1396        if !parameters.is_empty() && !matches!(self.op, BoundVectorOp::Histogram(_)) {
1397            return Err(DataFusionError::Internal(
1398                "histogram parameters supplied to non-histogram op".into(),
1399            ));
1400        }
1401        let assembled = if !parameters.is_empty() {
1402            let rows = assembled.iter().map(|series| series.time.len()).sum();
1403            buffer.grow(merge_workspace_bytes(
1404                rows,
1405                assembled.len(),
1406                self.schema.fields.len(),
1407            ))?;
1408            merge_same_labelset(&self.schema, assembled)?
1409        } else {
1410            assembled
1411        };
1412        if !parameters.is_empty() {
1413            let grid = self
1414                .schema
1415                .eval_grid
1416                .as_ref()
1417                .ok_or_else(|| DataFusionError::Internal("histogram grid missing".into()))?;
1418            if parameters
1419                .iter()
1420                .any(|values| values.len() != grid.spec().len as usize)
1421            {
1422                return Err(DataFusionError::Internal(
1423                    "histogram parameter length differs from its grid".into(),
1424                ));
1425            }
1426        }
1427        if self.parameter.is_some() && !matches!(self.op, BoundVectorOp::TopK { .. }) {
1428            return Err(DataFusionError::Internal(
1429                "only topk accepts a per-point k".into(),
1430            ));
1431        }
1432        if let Some(values) = self.parameter.as_ref() {
1433            let grid = self
1434                .schema
1435                .eval_grid
1436                .as_ref()
1437                .ok_or_else(|| DataFusionError::Internal("topk grid missing".into()))?;
1438            if values.len() != grid.spec().len as usize {
1439                return Err(DataFusionError::Internal(
1440                    "topk parameter length differs from its grid".into(),
1441                ));
1442            }
1443        }
1444        buffer.grow(vector_workspace_bytes(&self.op, &self.schema, &assembled))?;
1445        let metrics = Arc::clone(&buffer.metrics);
1446        let output = {
1447            let _timer = metrics.timer();
1448            if parameters.is_empty() {
1449                vector_series_with_k(
1450                    &self.op,
1451                    &self.schema,
1452                    &assembled,
1453                    self.parameter.as_deref(),
1454                    self.annotations.as_ref(),
1455                )?
1456            } else {
1457                let function = match self.op {
1458                    BoundVectorOp::Histogram(function) => function,
1459                    _ => {
1460                        return Err(DataFusionError::Internal(
1461                            "parameterized histogram op mismatch".into(),
1462                        ));
1463                    }
1464                };
1465                let histogram_parameters = match function {
1466                    HistogramFunction::Quantile(_) => HistogramParameters {
1467                        quantile: Some(parameters[0]),
1468                        lower: None,
1469                        upper: None,
1470                    },
1471                    HistogramFunction::Fraction { .. } => HistogramParameters {
1472                        quantile: None,
1473                        lower: Some(parameters[0]),
1474                        upper: Some(parameters[1]),
1475                    },
1476                };
1477                evaluate_histograms_with_annotations(
1478                    function,
1479                    &self.schema,
1480                    &assembled,
1481                    Some(histogram_parameters),
1482                    self.annotations.as_ref(),
1483                )?
1484            }
1485        };
1486        self.input.release();
1487        self.computed = true;
1488        Ok(Some(output))
1489    }
1490}
1491
1492/// The error for a vector operation whose reservation does not fit an address space.
1493fn vector_overflow() -> DataFusionError {
1494    DataFusionError::Execution(
1495        "the input of the vector operation does not fit one address space: the bytes it would \
1496         reserve overflow"
1497            .to_string(),
1498    )
1499}
1500
1501fn vector_series_with_k(
1502    op: &BoundVectorOp,
1503    schema: &Arc<SeriesSchema>,
1504    series: &[Series],
1505    values: Option<&[Option<f64>]>,
1506    collector: Option<&PromqlAnnotationCollector>,
1507) -> Result<Vec<Series>> {
1508    let grouping = |group: &Grouping| match group {
1509        Grouping::By(labels) => select::Grouping::By(labels.to_vec()),
1510        Grouping::Without(labels) => select::Grouping::Without(labels.to_vec()),
1511    };
1512    match op {
1513        BoundVectorOp::TopK { k, top, group } => {
1514            if let Some(values) = values {
1515                let grid = schema.eval_grid.as_ref().ok_or_else(|| {
1516                    DataFusionError::Internal("topk output has no evaluation grid".into())
1517                })?;
1518                if values.len() != grid.spec().len as usize {
1519                    return Err(DataFusionError::Internal(
1520                        "topk parameter length differs from its grid".into(),
1521                    ));
1522                }
1523                select::topk_at(
1524                    // No sample selects nothing, as Prometheus does for an empty parameter; a NaN
1525                    // sample is still an error (`select::validate_topk_parameters`).
1526                    |point| match values[point] {
1527                        Some(k) => select::k_param(k, series.len()),
1528                        None => Ok(None),
1529                    },
1530                    *top,
1531                    &grouping(group),
1532                    schema,
1533                    series,
1534                )
1535            } else {
1536                select::topk(*k, *top, &grouping(group), schema, series)
1537            }
1538        }
1539        BoundVectorOp::LimitK { k, group } => select::limitk(*k, &grouping(group), schema, series),
1540        BoundVectorOp::LimitRatio { ratio } => select::limit_ratio(*ratio, schema, series),
1541        BoundVectorOp::Sort(order) => select::sort_instant(order, schema, series.to_vec()),
1542        // The kernel takes one native histogram series per label set, so pieces of one label set
1543        // are merged first.
1544        BoundVectorOp::Histogram(function) => evaluate_histograms_with_annotations(
1545            *function,
1546            schema,
1547            &merge_same_labelset(schema, series.to_vec())?,
1548            None,
1549            collector,
1550        ),
1551        BoundVectorOp::CountValues { label, group } => {
1552            let names = group.names();
1553            aggregate::count_values(schema, series, label, group.kernel(&names))
1554        }
1555        BoundVectorOp::Absent { labels } => Ok(select::absent(schema, series, labels.clone())?
1556            .into_iter()
1557            .collect()),
1558    }
1559}
1560
1561/// A rough estimate of what the vector operation `op` allocates over `series`, beside the input it
1562/// reads: ranking candidates and copied histograms, sort keys and float rebuilds, `absent`'s
1563/// per-point flags, `count_values`' per-sample groups, and the histogram functions' merge and
1564/// per-row buckets.
1565fn vector_workspace_bytes(op: &BoundVectorOp, schema: &SeriesSchema, series: &[Series]) -> usize {
1566    let fields = schema.fields.len();
1567    match op {
1568        BoundVectorOp::Sort(order) => {
1569            let rebuilds = matches!(order, SortOrder::Asc | SortOrder::Desc);
1570            return series.iter().fold(0usize, |total, item| {
1571                let floats = if rebuilds
1572                    && item
1573                        .fields
1574                        .iter()
1575                        .any(|field| histogram_row_bytes(field).is_some())
1576                {
1577                    item.time.len().saturating_mul(std::mem::size_of::<f64>())
1578                } else {
1579                    0
1580                };
1581                total
1582                    .saturating_add(std::mem::size_of::<(f64, Series)>())
1583                    .saturating_add(floats)
1584            });
1585        }
1586        BoundVectorOp::Absent { .. } => {
1587            let points = schema.eval_grid.as_ref().map_or(0, |grid| {
1588                usize::try_from(grid.spec().len).unwrap_or(usize::MAX)
1589            });
1590            return points.saturating_mul(fields.saturating_mul(1 + std::mem::size_of::<f64>()));
1591        }
1592        BoundVectorOp::Histogram(_) => {
1593            let rows: usize = series.iter().map(|item| item.time.len()).sum();
1594            let label = std::mem::size_of::<(Arc<str>, Arc<str>)>();
1595            let row = std::mem::size_of::<(f64, f64)>() + fields * std::mem::size_of::<f64>();
1596            let per_series = std::mem::size_of::<(f64, &Series)>()
1597                + fields * std::mem::size_of::<RowCursor<'_>>();
1598            return series.iter().fold(
1599                merge_workspace_bytes(rows, series.len(), fields),
1600                |total, item| {
1601                    total
1602                        .saturating_add(per_series)
1603                        .saturating_add((item.metric.tags().len() + 1).saturating_mul(label))
1604                        .saturating_add(item.time.len().saturating_mul(row))
1605                },
1606            );
1607        }
1608        BoundVectorOp::CountValues { .. } => {
1609            let label = std::mem::size_of::<(Arc<str>, Arc<str>)>();
1610            // A 17-digit value with sign, point and exponent. Large magnitudes formatted in full
1611            // can be longer.
1612            let value = 24;
1613            let group = std::mem::size_of::<Vec<f64>>()
1614                + fields * std::mem::size_of::<f64>()
1615                + std::mem::size_of::<Series>()
1616                + fields * std::mem::size_of::<Samples>();
1617            return series.iter().fold(0usize, |total, item| {
1618                let labels = 2 * (item.metric.tags().len() + 2) * label + value;
1619                let samples = item.time.len().saturating_mul(fields);
1620                total.saturating_add(samples.saturating_mul(group + labels))
1621            });
1622        }
1623        BoundVectorOp::TopK { .. }
1624        | BoundVectorOp::LimitK { .. }
1625        | BoundVectorOp::LimitRatio { .. } => {}
1626    }
1627    let row = std::mem::size_of::<(usize, usize)>()
1628        + std::mem::size_of::<(usize, usize, f64)>()
1629        + fields * std::mem::size_of::<f64>();
1630    let per_series = 2 * std::mem::size_of::<usize>()
1631        + std::mem::size_of::<Vec<(usize, usize)>>()
1632        + std::mem::size_of::<RowCursor<'_>>()
1633        + std::mem::size_of::<Series>()
1634        + fields * std::mem::size_of::<Samples>();
1635    let label = std::mem::size_of::<(Arc<str>, Arc<str>)>();
1636    series.iter().fold(0usize, |total, item| {
1637        let rows = item.time.len();
1638        let labels = item.metric.tags().len() + 1;
1639        let histograms = item
1640            .fields
1641            .iter()
1642            .filter_map(histogram_row_bytes)
1643            .fold(0usize, |bytes, widest| {
1644                bytes.saturating_add(widest.saturating_mul(rows))
1645            });
1646        total
1647            .saturating_add(rows.saturating_mul(row))
1648            .saturating_add(per_series)
1649            .saturating_add(labels.saturating_mul(label))
1650            .saturating_add(histograms)
1651    })
1652}
1653
1654/// The operation a scalar broadcast applies, with the side the constant sits on already resolved.
1655#[derive(Clone, Copy, Debug)]
1656enum BroadcastOp {
1657    Arithmetic(ArithmeticOp),
1658    Compare(Comparison),
1659}
1660
1661/// The scalar side of a broadcast.
1662enum BroadcastScalar {
1663    Literal(ScalarOperand),
1664    /// A per-point scalar, read whole before any vector chunk is answered.
1665    Dynamic {
1666        /// Whether the scalar is the left operand.
1667        left: bool,
1668        value: Option<Series>,
1669    },
1670}
1671
1672/// A binary node with one scalar operand. Unlike [`BinaryRuntime`] it applies to each vector chunk
1673/// as it arrives and retains nothing.
1674struct BroadcastRuntime {
1675    scalar: BroadcastScalar,
1676    /// Whether the vector is the left operand.
1677    vector_left: bool,
1678    op: BroadcastOp,
1679    /// The vector side's schema; the kernel checks each chunk against it.
1680    sample_schema: Arc<SeriesSchema>,
1681    /// The bytes charged for a [`BroadcastScalar::Dynamic`] value.
1682    scalar_bytes: usize,
1683    annotations: Option<PromqlAnnotationCollector>,
1684}
1685
1686/// A map with scalar parameters (`round`, `clamp`, `max_of`, ...), holding each parameter once it
1687/// arrives.
1688struct ParameterizedMapRuntime {
1689    op: ParameterizedOp,
1690    schema: Arc<SeriesSchema>,
1691    /// A constant input (as in `max_of(0, time())`), which its node does not hand over as a chunk,
1692    /// and whether its one chunk has been built.
1693    input_literal: Option<f64>,
1694    input_produced: bool,
1695    /// Constant parameters, which their nodes do not hand over as chunks.
1696    literals: Vec<Option<f64>>,
1697    /// Each parameter's unlabelled series, in argument order.
1698    values: Vec<Option<Series>>,
1699    /// The bytes charged for `values` and for the constant input's chunk.
1700    parameter_bytes: usize,
1701}
1702
1703impl ParameterizedMapRuntime {
1704    fn ready(&self) -> bool {
1705        self.values.iter().all(Option::is_some)
1706    }
1707
1708    /// Applies the function to one chunk with each parameter read at each point.
1709    fn apply(&self, chunk: &EvaluatedChunk) -> Result<Option<Series>> {
1710        let value = |index: usize| {
1711            self.values
1712                .get(index)
1713                .and_then(Option::as_ref)
1714                .ok_or_else(|| {
1715                    DataFusionError::Execution(
1716                        "the map was applied before its parameters arrived".to_string(),
1717                    )
1718                })
1719        };
1720        let function = match self.op {
1721            ParameterizedOp::Round => ParameterizedMath::Round {
1722                to_nearest: value(0)?,
1723            },
1724            ParameterizedOp::Clamp => ParameterizedMath::Clamp {
1725                min: value(0)?,
1726                max: value(1)?,
1727            },
1728            ParameterizedOp::ClampMin => ParameterizedMath::ClampMin { min: value(0)? },
1729            ParameterizedOp::ClampMax => ParameterizedMath::ClampMax { max: value(0)? },
1730            ParameterizedOp::MaxOf => ParameterizedMath::MaxOf { other: value(0)? },
1731            ParameterizedOp::MinOf => ParameterizedMath::MinOf { other: value(0)? },
1732        };
1733        map_math_with_parameters(&self.schema, &chunk.series, function)
1734    }
1735}
1736
1737impl BroadcastRuntime {
1738    /// Whether the scalar varies per point and has not arrived yet.
1739    fn awaits_scalar(&self) -> bool {
1740        matches!(self.scalar, BroadcastScalar::Dynamic { value: None, .. })
1741    }
1742
1743    /// Whether the operation drops the metric name (arithmetic and `bool` comparisons). Two input
1744    /// series can then share one label set; a [`NativeExpr::Merge`] above handles that.
1745    fn drops_labels(&self) -> bool {
1746        match self.op {
1747            BroadcastOp::Arithmetic(_) | BroadcastOp::Compare(Comparison::Bool(_)) => true,
1748            BroadcastOp::Compare(Comparison::Filter(_)) => false,
1749        }
1750    }
1751
1752    /// Reports histogram samples dropped by an operation with no histogram form, as Prometheus
1753    /// does instead of failing.
1754    fn record_dropped_histograms(&self, dropped_histogram: bool, op: impl std::fmt::Display) {
1755        if dropped_histogram && let Some(collector) = &self.annotations {
1756            collector.record_info(format!(
1757                "{op}: dropped native histogram samples because this binary operation is not supported for native histograms"
1758            ));
1759        }
1760    }
1761
1762    /// The label set `metric` becomes under this operation.
1763    fn output_metric(&self, metric: &SeriesLabels) -> Result<SeriesLabels> {
1764        if self.drops_labels() {
1765            drop_metric_name(metric)
1766        } else {
1767            Ok(metric.clone())
1768        }
1769    }
1770
1771    /// Applies the operation to one vector chunk. `None` means every position was emptied and the
1772    /// chunk does not close its series; a closing chunk always yields a series, possibly with no
1773    /// rows, so the close reaches the consumer.
1774    fn apply(&self, chunk: &EvaluatedChunk) -> Result<Option<Series>> {
1775        let output = match &self.scalar {
1776            BroadcastScalar::Literal(operand) => match self.op {
1777                BroadcastOp::Arithmetic(op) => {
1778                    let (output, dropped_histogram) =
1779                        map_arithmetic_literal(&self.sample_schema, &chunk.series, op, *operand)?;
1780                    self.record_dropped_histograms(dropped_histogram, op);
1781                    Some(output)
1782                }
1783                BroadcastOp::Compare(comparison) => {
1784                    let (output, dropped_histogram) = map_compare_literal(
1785                        &self.sample_schema,
1786                        &chunk.series,
1787                        comparison,
1788                        *operand,
1789                    )?;
1790                    self.record_dropped_histograms(dropped_histogram, comparison);
1791                    output
1792                }
1793            },
1794            BroadcastScalar::Dynamic { left, value } => {
1795                let value = value.as_ref().ok_or_else(|| {
1796                    DataFusionError::Execution(
1797                        "the binary node broadcast a scalar that has not arrived".to_string(),
1798                    )
1799                })?;
1800                let operand = if *left {
1801                    ScalarSeriesOperand::Left(value)
1802                } else {
1803                    ScalarSeriesOperand::Right(value)
1804                };
1805                match self.op {
1806                    BroadcastOp::Arithmetic(op) => {
1807                        if !is_float_series(&chunk.series) {
1808                            return Err(DataFusionError::NotImplemented(
1809                                "dynamic scalar arithmetic does not support histogram or mixed samples"
1810                                    .into(),
1811                            ));
1812                        }
1813                        map_arithmetic_series(&self.sample_schema, &chunk.series, op, operand)?
1814                    }
1815                    BroadcastOp::Compare(comparison) => {
1816                        let (output, dropped_histogram) = map_compare_series(
1817                            &self.sample_schema,
1818                            &chunk.series,
1819                            comparison,
1820                            operand,
1821                        )?;
1822                        self.record_dropped_histograms(dropped_histogram, comparison);
1823                        output
1824                    }
1825                }
1826            }
1827        };
1828        match output {
1829            Some(output) => Ok(Some(output)),
1830            None if chunk.is_last => {
1831                let metric = self.output_metric(&chunk.series.metric)?;
1832                no_row_series(&self.sample_schema, &chunk.series, metric).map(Some)
1833            }
1834            None => Ok(None),
1835        }
1836    }
1837}
1838
1839/// The buffered chunks as the one source axis they make up.
1840fn buffered_time(chunks: &[RawSeriesChunk]) -> Result<RawTimestamps> {
1841    let len = chunks.iter().map(|chunk| chunk.time.len()).sum();
1842    let mut timestamps: Vec<i64> = Vec::with_capacity(len);
1843    for chunk in chunks {
1844        timestamps.extend_from_slice(chunk.time.as_buffer());
1845    }
1846    RawTimestamps::try_new(ScalarBuffer::from(timestamps)).map_err(series_error)
1847}
1848
1849/// The buffered chunks' fields, each chaining its chunks' samples without copying.
1850fn buffered_fields(chunks: &[RawSeriesChunk], fields: usize) -> Result<SeriesFields> {
1851    let mut per_field: Vec<Vec<Samples>> = vec![Vec::with_capacity(chunks.len()); fields];
1852    for chunk in chunks {
1853        for (field, slot) in chunk.fields.iter().zip(&mut per_field) {
1854            slot.push(field.clone());
1855        }
1856    }
1857    let fields = per_field
1858        .into_iter()
1859        .map(|chunks| Samples::try_from_chunks(chunks).map_err(series_error))
1860        .collect::<Result<Vec<_>>>()?;
1861    SeriesFields::try_from_vec(fields).map_err(series_error)
1862}
1863
1864/// The bytes of the field's largest histogram row in the builder's table, `None` for a float
1865/// field.
1866fn histogram_row_bytes(field: &Samples) -> Option<usize> {
1867    let holds_histograms = field.segments().iter().any(|segment| {
1868        matches!(
1869            segment.dense(),
1870            Some(DenseSamplesRef::Histogram(_) | DenseSamplesRef::Mixed(_))
1871        )
1872    });
1873    if !holds_histograms {
1874        return None;
1875    }
1876    Some(
1877        field
1878            .iter()
1879            .filter_map(|sample| match sample {
1880                SampleRef::Histogram(view) => Some(histogram_bytes(&view)),
1881                _ => None,
1882            })
1883            .fold(0, usize::max),
1884    )
1885}
1886
1887/// The bytes the histogram table holds for one row of `view`: its scalar columns, the offset each
1888/// bucket list pays for it, and the values those lists hold.
1889fn histogram_bytes(view: &HistogramView<'_>) -> usize {
1890    let custom = view
1891        .custom_values
1892        .len()
1893        .saturating_mul(std::mem::size_of::<f64>());
1894    let sides = [view.positive, view.negative]
1895        .iter()
1896        .map(|side| {
1897            side.span_offsets
1898                .len()
1899                .saturating_mul(2)
1900                .saturating_mul(std::mem::size_of::<i32>())
1901                .saturating_add(
1902                    side.buckets
1903                        .len()
1904                        .saturating_mul(std::mem::size_of::<f64>()),
1905                )
1906        })
1907        .fold(0usize, usize::saturating_add);
1908    HISTOGRAM_ROW_HEADER_BYTES
1909        .saturating_add(custom)
1910        .saturating_add(sides)
1911}
1912
1913/// The bytes a histogram table row takes before its bucket lists: the schema, zero threshold, sum,
1914/// count, zero count, reset hint and start timestamp, the narrow columns counted at the width of
1915/// the widest, and one offset per list column -- custom bounds, two span columns and one bucket
1916/// column per side.
1917const HISTOGRAM_ROW_HEADER_BYTES: usize =
1918    7 * std::mem::size_of::<i64>() + 7 * std::mem::size_of::<u32>();
1919
1920/// The last (inclusive) timestamp of `spec`. [`GridSpec::try_new`] guarantees it fits `i64`.
1921fn grid_end_ms(spec: GridSpec) -> i64 {
1922    (i128::from(spec.start_ms) + i128::from(spec.step_ms) * (i128::from(spec.len) - 1)) as i64
1923}
1924
1925/// The grid position of `timestamp`. A timestamp off the grid is an internal disagreement, so it
1926/// is an error rather than skipped.
1927fn grid_position(grid: &EvalGrid, timestamp: i64) -> Result<usize> {
1928    let spec = grid.spec();
1929    // Fast `i64` path per point; overflow or an off-grid timestamp falls through to `i128`.
1930    if spec.step_ms > 0
1931        && let Some(offset) = timestamp.checked_sub(spec.start_ms)
1932        && offset >= 0
1933    {
1934        let (position, remainder) = (offset / spec.step_ms, offset % spec.step_ms);
1935        if remainder == 0 && (position as u64) < spec.len {
1936            return Ok(position as usize);
1937        }
1938    }
1939    let offset = i128::from(timestamp) - i128::from(spec.start_ms);
1940    let step = i128::from(spec.step_ms);
1941    let position = offset.div_euclid(step);
1942    if offset.rem_euclid(step) != 0 || position < 0 || position >= i128::from(spec.len) {
1943        return Err(DataFusionError::Execution(format!(
1944            "the instant selection reported the timestamp {timestamp}ms, which is not a point of \
1945             its grid {spec:?}"
1946        )));
1947    }
1948    Ok(position as usize)
1949}
1950
1951/// Checks that an evaluated series lies on the grid its consumer is bound to.
1952fn ensure_grid(grid: Option<&EvalGrid>, time: &TimeAxis) -> Result<()> {
1953    if grid.is_none_or(|grid| {
1954        time.grid()
1955            .is_none_or(|actual| actual.spec() != grid.spec())
1956    }) {
1957        return Err(DataFusionError::Execution(
1958            "vector() input does not match its evaluation grid".to_string(),
1959        ));
1960    }
1961    Ok(())
1962}
1963
1964/// The layout of a scalar's value carrier: one field on `grid`.
1965fn scalar_schema(grid: Arc<EvalGrid>) -> SeriesSchema {
1966    SeriesSchema {
1967        fields: Arc::from([FieldSpec {
1968            name: "value".into(),
1969        }]),
1970        eval_grid: Some(grid),
1971    }
1972}
1973
1974/// The bytes one value per point of `grid` takes in a chunk of its own, reserved before it exists.
1975fn grid_chunk_bytes(grid: &EvalGrid) -> Result<usize> {
1976    let len = usize::try_from(grid.spec().len).map_err(|_| {
1977        DataFusionError::Execution("scalar grid length does not fit memory size".into())
1978    })?;
1979    std::mem::size_of::<EvaluatedChunk>()
1980        .checked_add(std::mem::size_of::<Float64Array>())
1981        .and_then(|bytes| {
1982            len.checked_mul(std::mem::size_of::<f64>())
1983                .and_then(|values| bytes.checked_add(values))
1984        })
1985        .ok_or_else(|| DataFusionError::Execution("scalar allocation size overflow".into()))
1986}
1987
1988/// An upper bound of what a chain of map operations allocates over `series`. Each operation's
1989/// output lives until the next one is written, so the bound is the largest sum of two consecutive
1990/// workspaces. Sizing every operation from `series` relies on each one writing floats only, at no
1991/// more rows than it read.
1992fn map_workspace_bytes(ops: &[MapOp], series: &Series) -> Result<usize> {
1993    let (mut previous, mut bound) = (0usize, 0usize);
1994    let mut first = true;
1995    for op in ops {
1996        let workspace = match op {
1997            MapOp::Label(_) => continue,
1998            MapOp::Math(_) if !first || is_float_series(series) => mapped_workspace_bytes(series)?,
1999            _ if first => built_series_workspace_bytes(series)?,
2000            _ => built_workspace_bytes(series.time.len(), series.time.len(), series.fields.len())?,
2001        };
2002        let live = previous
2003            .checked_add(workspace)
2004            .ok_or_else(|| workspace_overflow(series.time.len(), series.fields.len()))?;
2005        bound = bound.max(live);
2006        previous = workspace;
2007        first = false;
2008    }
2009    Ok(bound)
2010}
2011
2012/// An upper bound of what a kernel that maps each dense segment of `series` into a new array of
2013/// equal length allocates. A histogram row is charged at the field's largest payload, plus a buffer
2014/// header and 64-byte alignment per segment.
2015fn mapped_workspace_bytes(series: &Series) -> Result<usize> {
2016    let segments = series
2017        .fields
2018        .iter()
2019        .map(|field| field.segments().len())
2020        .fold(0usize, usize::saturating_add);
2021    let bound = || {
2022        let mut bytes = assembly_bytes(series.fields.len(), segments, &series.metric)?;
2023        for field in series.fields.iter() {
2024            let row = histogram_row_bytes(field).map_or(std::mem::size_of::<f64>(), |histogram| {
2025                histogram.max(std::mem::size_of::<f64>())
2026            });
2027            for segment in field.segments() {
2028                bytes = segment
2029                    .len()
2030                    .checked_mul(row)?
2031                    .checked_add(64 + BUFFER_HEADER_BYTES)?
2032                    .checked_add(bytes)?;
2033            }
2034        }
2035        Some(bytes)
2036    };
2037    bound().ok_or_else(|| workspace_overflow(series.time.len(), series.fields.len()))
2038}
2039
2040/// An upper bound of what a kernel that pushes a subset of the rows of `series` into a
2041/// [`GridSeriesBuilder`] allocates: [`built_workspace_bytes`] over the series' rows and runs, and
2042/// the result's assembly ([`assembly_bytes`]), one segment per field.
2043fn built_series_workspace_bytes(series: &Series) -> Result<usize> {
2044    let fields = series.fields.len();
2045    let rows = built_workspace_bytes(series.time.len(), series.time.runs().count(), fields)?;
2046    assembly_bytes(fields, fields, &series.metric)
2047        .and_then(|assembly| assembly.checked_add(rows))
2048        .ok_or_else(|| workspace_overflow(series.time.len(), fields))
2049}
2050
2051/// The bytes a result of `fields` fields over `segments` segments is assembled from, beside its
2052/// values: the descriptor lists (a growing list holds at most `2 * n + 4` entries) and the label
2053/// set rebuilt from `metric`.
2054fn assembly_bytes(fields: usize, segments: usize, metric: &SeriesLabels) -> Option<usize> {
2055    let descriptors = segments
2056        .checked_mul(6)?
2057        .checked_add(fields.checked_mul(16)?)?
2058        .checked_add(8)?
2059        .checked_mul(std::mem::size_of::<Samples>())?;
2060    descriptors
2061        .checked_add(std::mem::size_of_val(metric.tags()))?
2062        .checked_add(BUFFER_HEADER_BYTES + std::mem::size_of::<Series>())
2063}
2064
2065/// An allowance for the shared header an Arrow buffer or a label list is allocated behind.
2066const BUFFER_HEADER_BYTES: usize = 64;
2067
2068/// An upper bound of the bytes a [`GridSeriesBuilder`] allocates for a result of `fields` float
2069/// fields whose positions are a subset of `rows` positions in `runs` runs.
2070///
2071/// Keeping `kept` rows in `split` runs costs `2 * kept + 4` entries per growing column plus a span
2072/// per run. Dropping a position splits at most one run, so `split <= min(kept, runs + rows - kept)`
2073/// and the maximum is at one end of that range. Pass `runs = rows` when the result's positions are
2074/// not a subset of the input's.
2075fn built_workspace_bytes(rows: usize, runs: usize, fields: usize) -> Result<usize> {
2076    let cost = |kept: usize, split: usize| {
2077        let capacity = kept.checked_mul(2)?.checked_add(4)?;
2078        let indices = capacity.checked_mul(std::mem::size_of::<usize>())?;
2079        let validity = kept.div_ceil(8).checked_mul(2)?.checked_add(64)?;
2080        let field = capacity
2081            .checked_mul(std::mem::size_of::<f64>())?
2082            .checked_add(validity)?;
2083        let spans = split
2084            .checked_mul(2 * std::mem::size_of::<GridSpan>() + 2 * std::mem::size_of::<usize>())?;
2085        fields
2086            .checked_mul(field)?
2087            .checked_add(indices)?
2088            .checked_add(spans)
2089    };
2090    let runs = runs.min(rows);
2091    let fragmented = rows.checked_add(runs).map(|total| total.div_ceil(2));
2092    fragmented
2093        .and_then(|fragmented| Some(cost(rows, runs)?.max(cost(fragmented, fragmented)?)))
2094        .ok_or_else(|| workspace_overflow(rows, fields))
2095}
2096
2097fn workspace_overflow(rows: usize, fields: usize) -> DataFusionError {
2098    DataFusionError::Execution(format!(
2099        "the workspace for {rows} rows of {fields} fields does not fit one address space"
2100    ))
2101}
2102
2103/// An upper bound of what `window`'s next push allocates for its output rows, given the input's
2104/// last sample time `last_ts` and whether it closes the series.
2105///
2106/// Rows come from [`RangeEvaluator::output_rows_bound`], each possibly its own run. A
2107/// histogram-valued function adds an index and a doubled table row per field and row, sized by the
2108/// widest histogram retained or incoming; a result combining disjoint layouts can exceed that and
2109/// is not bounded.
2110fn window_workspace_bytes(
2111    window: &RangeEvaluator,
2112    last_ts: Option<i64>,
2113    last: bool,
2114    fields: &SeriesFields,
2115    metric: &SeriesLabels,
2116) -> Result<usize> {
2117    let rows = window.output_rows_bound(last_ts, last);
2118    let width = window.output_schema().fields.len();
2119    let floats = assembly_bytes(width, width, metric)
2120        .ok_or_else(|| workspace_overflow(rows, width))?
2121        .checked_add(built_workspace_bytes(rows, rows, width)?)
2122        .ok_or_else(|| workspace_overflow(rows, width))?;
2123    if !window.yields_histograms() {
2124        return Ok(floats);
2125    }
2126    let retained = window
2127        .widest_retained_histogram()
2128        .map(|heap| heap.saturating_add(HISTOGRAM_ROW_HEADER_BYTES));
2129    let incoming = fields.iter().filter_map(histogram_row_bytes).max();
2130    let Some(widest) = retained.max(incoming) else {
2131        return Ok(floats);
2132    };
2133    let histograms = || {
2134        let row = widest
2135            .checked_mul(2)?
2136            .checked_add(2 * std::mem::size_of::<Option<u32>>() + std::mem::size_of::<u32>() + 1)?;
2137        let in_flight = widest.checked_add(std::mem::size_of::<FloatHistogram>())?;
2138        rows.checked_mul(row)?
2139            .checked_add(in_flight)?
2140            .checked_mul(width)?
2141            .checked_add(floats)
2142    };
2143    histograms().ok_or_else(|| {
2144        DataFusionError::Execution(format!(
2145            "the histogram workspace for {rows} rows of {width} fields does not fit one address \
2146             space"
2147        ))
2148    })
2149}
2150
2151/// The time of the last sample a chunk carries, on its own timeline.
2152fn last_sample_ms(chunk: &NativeChunk) -> Result<Option<i64>> {
2153    match chunk {
2154        NativeChunk::Raw(chunk) => Ok(chunk.time.as_buffer().last().copied()),
2155        NativeChunk::Evaluated(chunk) => Ok(last_series_ms(&chunk.series)),
2156        NativeChunk::AggregateState(_) => Err(DataFusionError::Execution(
2157            "an aggregate state chunk reached a node that reads values or samples".to_string(),
2158        )),
2159    }
2160}
2161
2162/// The time of the last row `series` carries.
2163fn last_series_ms(series: &Series) -> Option<i64> {
2164    let row = series.time.len().checked_sub(1)?;
2165    series.time.timestamp(row)
2166}
2167
2168/// One unlabelled constant value per statement grid point, closed on its only chunk.
2169fn scalar_chunk(grid: Arc<EvalGrid>, value: f64) -> Result<EvaluatedChunk> {
2170    scalar_chunk_on(&scalar_schema(Arc::clone(&grid)), grid, value)
2171}
2172
2173/// [`scalar_chunk`] under `schema`, which names the one field.
2174fn scalar_chunk_on(
2175    schema: &SeriesSchema,
2176    grid: Arc<EvalGrid>,
2177    value: f64,
2178) -> Result<EvaluatedChunk> {
2179    let len = grid.spec().len as usize;
2180    let time = GridRange::try_new(grid, 0, len).map_err(series_error)?;
2181    let values = Float64Array::from(vec![value; len]);
2182    let fields = SeriesFields::one(Samples::from_float(values));
2183    let metric = SeriesLabels::try_new(None, Vec::new()).map_err(series_error)?;
2184    let series =
2185        Series::try_new(schema, metric, TimeAxis::Grid(time), fields).map_err(series_error)?;
2186    EvaluatedChunk::try_new(series, true)
2187}
2188
2189/// A closing chunk carrying `metric` and no rows.
2190fn no_row_chunk(schema: &SeriesSchema, metric: SeriesLabels) -> Result<EvaluatedChunk> {
2191    let grid = schema.eval_grid.clone().ok_or_else(|| {
2192        DataFusionError::Execution(
2193            "an instant selection produces an evaluated chunk, which is addressed on a grid"
2194                .to_string(),
2195        )
2196    })?;
2197    let empty = Samples::from_float(Float64Array::from(Vec::<f64>::new()));
2198    let fields =
2199        SeriesFields::try_from_vec(vec![empty; schema.fields.len()]).map_err(series_error)?;
2200    let time = GridRange::try_new(grid, 0, 0).map_err(series_error)?;
2201    let series =
2202        Series::try_new(schema, metric, TimeAxis::Grid(time), fields).map_err(series_error)?;
2203    EvaluatedChunk::try_new(series, true)
2204}
2205
2206/// The edge from a [`RuntimeNode`] to a child; names the child's metrics.
2207#[derive(Clone, Copy)]
2208enum ChildRole {
2209    Input,
2210    Left,
2211    Right,
2212    Parameter,
2213    IndexedParameter(usize),
2214}
2215
2216impl ChildRole {
2217    fn metric_name(self, parent: &str) -> String {
2218        match self {
2219            ChildRole::Input => format!("{parent}.input"),
2220            ChildRole::Left => format!("{parent}.left"),
2221            ChildRole::Right => format!("{parent}.right"),
2222            ChildRole::Parameter => format!("{parent}.parameter"),
2223            ChildRole::IndexedParameter(index) => format!("{parent}.parameter{index}"),
2224        }
2225    }
2226}
2227
2228/// A runtime operator and its directly owned children and metrics.
2229struct RuntimeNode {
2230    metrics: Arc<NodeMetrics>,
2231    op: RuntimeOp,
2232}
2233
2234// Each payload precedes its NodeState, so it drops before that node's reservation.
2235enum RuntimeOp {
2236    Input(InputId),
2237    Scalar,
2238    ScalarOf {
2239        input: Box<RuntimeNode>,
2240        input_schema: Arc<SeriesSchema>,
2241        grid: Arc<EvalGrid>,
2242        retained: RetainedInput,
2243        produced: bool,
2244        state: NodeState,
2245    },
2246    /// The evaluation time or a date function of it, produced once as one closed chunk.
2247    EvalTime {
2248        grid: Arc<EvalGrid>,
2249        date: Option<DateFunction>,
2250        produced: bool,
2251        state: NodeState,
2252    },
2253    /// A scalar handed on as a vector. A constant input has no chunk of its own, so its value is
2254    /// produced here, once.
2255    VectorOf {
2256        input: Box<RuntimeNode>,
2257        literal: Option<f64>,
2258        produced: bool,
2259        schema: Arc<SeriesSchema>,
2260        state: NodeState,
2261    },
2262    Instant {
2263        input: Box<RuntimeNode>,
2264        instant: InstantRuntime,
2265        state: NodeState,
2266    },
2267    Merge {
2268        input: Box<RuntimeNode>,
2269        merge: Option<MergeInput>,
2270        state: NodeState,
2271    },
2272    Window {
2273        input: Box<RuntimeNode>,
2274        // `None` once `finish_windows` has consumed the evaluator.
2275        window: Option<RangeEvaluator>,
2276        merge: Option<MergeInput>,
2277        state: NodeState,
2278    },
2279    Map {
2280        input: Box<RuntimeNode>,
2281        map: MapRuntime,
2282        state: NodeState,
2283    },
2284    ParameterizedMap {
2285        input: Box<RuntimeNode>,
2286        parameters: Vec<RuntimeNode>,
2287        map: ParameterizedMapRuntime,
2288        state: NodeState,
2289    },
2290    Timestamp {
2291        input: Box<RuntimeNode>,
2292        schema: Arc<SeriesSchema>,
2293        state: NodeState,
2294    },
2295    Binary {
2296        left: Box<RuntimeNode>,
2297        right: Box<RuntimeNode>,
2298        binary: BinaryRuntime,
2299        state: NodeState,
2300    },
2301    Broadcast {
2302        left: Box<RuntimeNode>,
2303        right: Box<RuntimeNode>,
2304        broadcast: BroadcastRuntime,
2305        state: NodeState,
2306    },
2307    Aggregate {
2308        input: Box<RuntimeNode>,
2309        aggregate: AggregateRuntime,
2310        state: NodeState,
2311    },
2312    Vector {
2313        input: Box<RuntimeNode>,
2314        vector: VectorRuntime,
2315        state: NodeState,
2316    },
2317    ParameterizedTopK {
2318        input: Box<RuntimeNode>,
2319        // Taken and dropped after its scalar values are installed.
2320        parameter: Option<Box<RuntimeNode>>,
2321        vector: VectorRuntime,
2322        state: NodeState,
2323    },
2324    ParameterizedAggregate {
2325        input: Box<RuntimeNode>,
2326        // Taken and dropped once the fold holds the series it answers with.
2327        parameter: Option<Box<RuntimeNode>>,
2328        aggregate: AggregateRuntime,
2329        state: NodeState,
2330    },
2331    ParameterizedHistogram {
2332        input: Box<RuntimeNode>,
2333        // Each parameter is taken and dropped after its scalar values are installed.
2334        parameters: Vec<Option<RuntimeNode>>,
2335        literals: Vec<Option<f64>>,
2336        vector: VectorRuntime,
2337        values: Vec<Option<Vec<Option<f64>>>>,
2338        parameter_bytes: Vec<usize>,
2339        state: NodeState,
2340    },
2341}
2342
2343/// State shared by the stateful operators. The queue precedes the buffer so it drops before its
2344/// reservation.
2345struct NodeState {
2346    queued: VecDeque<(NativeChunk, usize)>,
2347    queued_tables: usize,
2348    buffer: NodeBuffer,
2349}
2350
2351/// The kind of chunk an input leaf is bound to, and so the only kind it accepts.
2352#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2353enum LeafKind {
2354    Raw,
2355    Evaluated,
2356    AggregateState,
2357}
2358
2359impl LeafKind {
2360    fn of(output: &NativeType) -> Result<Self> {
2361        match output {
2362            NativeType::Samples(schema) if schema.eval_grid.is_some() => Ok(Self::Evaluated),
2363            NativeType::Samples(_) => Ok(Self::Raw),
2364            NativeType::AggregateState(_) => Ok(Self::AggregateState),
2365            NativeType::Scalar(_) => Err(DataFusionError::Execution(
2366                "an input leaf cannot be bound to a scalar".to_string(),
2367            )),
2368        }
2369    }
2370
2371    fn describe(self) -> &'static str {
2372        match self {
2373            Self::Raw => "raw samples",
2374            Self::Evaluated => "an evaluated series",
2375            Self::AggregateState => "aggregate state",
2376        }
2377    }
2378
2379    fn accepts(self, chunk: &NativeChunk) -> bool {
2380        matches!(
2381            (self, chunk),
2382            (Self::Raw, NativeChunk::Raw(_))
2383                | (Self::Evaluated, NativeChunk::Evaluated(_))
2384                | (Self::AggregateState, NativeChunk::AggregateState(_))
2385        )
2386    }
2387}
2388
2389/// The caller-owned state of one input leaf.
2390struct InputSlot {
2391    source_index: usize,
2392    kind: LeafKind,
2393    /// Whether the series whose chunk this leaf most recently handed over is still open.
2394    open_source_series: bool,
2395    /// Whether the series whose chunk the caller most recently queued here is still open. Tracked
2396    /// separately from handovers because a node waiting on a parameter can leave a chunk queued at
2397    /// the end of a run.
2398    open_queued_series: bool,
2399    state: NodeState,
2400}
2401
2402impl InputSlot {
2403    /// Whether an input the caller ended here left a series open, handed over or still queued.
2404    fn ends_open(&self) -> bool {
2405        self.open_source_series || self.open_queued_series
2406    }
2407}
2408
2409/// State for one execution of a bound tree. The live tree and input slots are dropped together
2410/// when the executor finishes or fails; the public state remains available for inspection.
2411pub struct NativeExecutionState {
2412    live: Option<LiveExecution>,
2413}
2414
2415struct LiveExecution {
2416    root: RuntimeNode,
2417    inputs: Vec<InputSlot>,
2418    /// A constant root waiting for its only pull; operand scalars remain chunkless.
2419    scalar_root: Option<(Arc<EvalGrid>, f64, NodeState)>,
2420}
2421
2422impl NodeState {
2423    /// Adds the node name to `error`: an `Execution` message gets it as a prefix and stays
2424    /// `Execution`; any other variant is wrapped in `Context`.
2425    fn context(&self, error: DataFusionError) -> DataFusionError {
2426        let name = self.buffer.reservation.consumer().name();
2427        match error {
2428            DataFusionError::Execution(message) => {
2429                DataFusionError::Execution(format!("{name}: {message}"))
2430            }
2431            other => DataFusionError::Context(name.to_string(), Box::new(other)),
2432        }
2433    }
2434
2435    pub(super) fn new(
2436        name: impl Into<String>,
2437        metrics: Arc<NodeMetrics>,
2438        pool: &Arc<dyn MemoryPool>,
2439    ) -> Self {
2440        let name = name.into();
2441        Self {
2442            queued: VecDeque::new(),
2443            queued_tables: 0,
2444            buffer: NodeBuffer::new(name, metrics, pool),
2445        }
2446    }
2447}
2448
2449/// Remaining stack below which [`RuntimeNode::build`] and [`RuntimeNode::pull`] grow it. Both
2450/// recurse once per tree level with large debug-build frames (about 140 KiB and 80 KiB, measured on
2451/// a 100-term chain), and the tree has no depth limit, so an 8 MiB worker stack can overflow.
2452const NATIVE_STACK_RED_ZONE: usize = 512 * 1024;
2453
2454/// Stack added per growth; holds several levels.
2455const NATIVE_STACK_GROWTH: usize = 4 * 1024 * 1024;
2456
2457impl RuntimeNode {
2458    /// Builds the runtime node for `node` and, recursively, for its inputs, growing the stack as it
2459    /// descends.
2460    fn build(
2461        node: &NativeNode,
2462        pool: &Arc<dyn MemoryPool>,
2463        inputs: &mut Vec<InputSlot>,
2464        binary_before: &mut usize,
2465        location: String,
2466        duplicate_evidence: Option<Arc<DuplicateEvidence>>,
2467        sources: &SourceFacts,
2468    ) -> Result<Self> {
2469        stacker::maybe_grow(NATIVE_STACK_RED_ZONE, NATIVE_STACK_GROWTH, || {
2470            Self::build_within_stack(
2471                node,
2472                pool,
2473                inputs,
2474                binary_before,
2475                location,
2476                duplicate_evidence,
2477                sources,
2478            )
2479        })
2480    }
2481
2482    fn build_within_stack(
2483        node: &NativeNode,
2484        pool: &Arc<dyn MemoryPool>,
2485        inputs: &mut Vec<InputSlot>,
2486        binary_before: &mut usize,
2487        location: String,
2488        duplicate_evidence: Option<Arc<DuplicateEvidence>>,
2489        sources: &SourceFacts,
2490    ) -> Result<Self> {
2491        let metrics = Arc::new(NodeMetrics::default());
2492        let op = match &node.expr {
2493            NativeExpr::Input(bound) => {
2494                if bound.ordering == SeriesOrdering::Interleaved {
2495                    return Err(DataFusionError::NotImplemented(format!(
2496                        "the native runtime does not accept {:?} input ordering",
2497                        bound.ordering
2498                    )));
2499                }
2500                let id = InputId(inputs.len());
2501                inputs.push(InputSlot {
2502                    source_index: bound.source_index,
2503                    kind: LeafKind::of(&node.output)?,
2504                    open_source_series: false,
2505                    open_queued_series: false,
2506                    state: NodeState::new(
2507                        format!(
2508                            "native.input at {location} (source_index={})",
2509                            bound.source_index
2510                        ),
2511                        Arc::clone(&metrics),
2512                        pool,
2513                    ),
2514                });
2515                RuntimeOp::Input(id)
2516            }
2517            NativeExpr::Scalar(_) => RuntimeOp::Scalar,
2518            NativeExpr::ScalarOf { input } => {
2519                let input_schema = input.output.samples().cloned().ok_or_else(|| {
2520                    DataFusionError::Execution("scalar() consumes non-sample input".to_string())
2521                })?;
2522                if input_schema.fields.len() != 1 {
2523                    return Err(DataFusionError::NotImplemented(
2524                        "the native runtime does not execute multi-field scalar()".into(),
2525                    ));
2526                }
2527                let grid = input_schema.eval_grid.clone().ok_or_else(|| {
2528                    DataFusionError::Execution("scalar() consumes raw samples".to_string())
2529                })?;
2530                let child = Self::build(
2531                    input,
2532                    pool,
2533                    inputs,
2534                    binary_before,
2535                    format!("{location}.input"),
2536                    duplicate_evidence.clone(),
2537                    sources,
2538                )?;
2539                RuntimeOp::ScalarOf {
2540                    input: Box::new(child),
2541                    input_schema,
2542                    grid,
2543                    retained: RetainedInput::default(),
2544                    produced: false,
2545                    state: NodeState::new(
2546                        format!("native.scalar_of at {location}"),
2547                        Arc::clone(&metrics),
2548                        pool,
2549                    ),
2550                }
2551            }
2552            NativeExpr::EvalTime { date } => {
2553                let NativeType::Scalar(grid) = &node.output else {
2554                    return Err(DataFusionError::Execution(
2555                        "the evaluation time does not produce a scalar".to_string(),
2556                    ));
2557                };
2558                RuntimeOp::EvalTime {
2559                    grid: Arc::clone(grid),
2560                    date: *date,
2561                    produced: false,
2562                    state: NodeState::new(
2563                        format!("native.time at {location}"),
2564                        Arc::clone(&metrics),
2565                        pool,
2566                    ),
2567                }
2568            }
2569            NativeExpr::VectorOf { input } => {
2570                let schema = node.output.samples().cloned().ok_or_else(|| {
2571                    DataFusionError::Execution("vector() does not produce samples".to_string())
2572                })?;
2573                let literal = match &input.expr {
2574                    NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
2575                    _ => None,
2576                };
2577                let child = Self::build(
2578                    input,
2579                    pool,
2580                    inputs,
2581                    binary_before,
2582                    format!("{location}.input"),
2583                    duplicate_evidence.clone(),
2584                    sources,
2585                )?;
2586                RuntimeOp::VectorOf {
2587                    input: Box::new(child),
2588                    literal,
2589                    produced: false,
2590                    schema,
2591                    state: NodeState::new(
2592                        format!("native.vector_of at {location}"),
2593                        Arc::clone(&metrics),
2594                        pool,
2595                    ),
2596                }
2597            }
2598            NativeExpr::Instant { input, op } => {
2599                let child = Self::build(
2600                    input,
2601                    pool,
2602                    inputs,
2603                    binary_before,
2604                    format!("{location}.input"),
2605                    duplicate_evidence.clone(),
2606                    sources,
2607                )?;
2608                let input_schema = input.output.samples().cloned().ok_or_else(|| {
2609                    DataFusionError::Execution(
2610                        "instant selection consumes non-sample input".to_string(),
2611                    )
2612                })?;
2613                RuntimeOp::Instant {
2614                    input: Box::new(child),
2615                    instant: InstantRuntime::try_new(&input_schema, op)?,
2616                    state: {
2617                        NodeState::new(
2618                            format!("native.instant at {location}"),
2619                            Arc::clone(&metrics),
2620                            pool,
2621                        )
2622                    },
2623                }
2624            }
2625            NativeExpr::Merge { input } => {
2626                let child = Self::build(
2627                    input,
2628                    pool,
2629                    inputs,
2630                    binary_before,
2631                    format!("{location}.input"),
2632                    duplicate_evidence.clone(),
2633                    sources,
2634                )?;
2635                let schema = node.output.samples().cloned().ok_or_else(|| {
2636                    DataFusionError::Execution("merge does not produce samples".to_string())
2637                })?;
2638                let state = NodeState::new(
2639                    format!("native.merge at {location}"),
2640                    Arc::clone(&metrics),
2641                    pool,
2642                );
2643                RuntimeOp::Merge {
2644                    input: Box::new(child),
2645                    merge: Some(MergeInput::new(schema)),
2646                    state,
2647                }
2648            }
2649            NativeExpr::Window { input, op } => {
2650                let child = Self::build(
2651                    input,
2652                    pool,
2653                    inputs,
2654                    binary_before,
2655                    format!("{location}.input"),
2656                    duplicate_evidence.clone(),
2657                    sources,
2658                )?;
2659                let input_schema = input.output.samples().cloned().ok_or_else(|| {
2660                    DataFusionError::Execution("window consumes non-sample input".to_string())
2661                })?;
2662                // Collect and merge fragments only when the input cannot prove its series keep
2663                // distinct label sets: the same check the canonical pass uses to place merges.
2664                let unification =
2665                    unifies_its_own_contributions(input, &sources.tags, &sources.metrics);
2666                let merge = matches!(unification, Some(false))
2667                    .then(|| MergeInput::new(Arc::clone(&input_schema)));
2668                let state = NodeState::new(
2669                    format!("native.window at {location}"),
2670                    Arc::clone(&metrics),
2671                    pool,
2672                );
2673                RuntimeOp::Window {
2674                    input: Box::new(child),
2675                    window: Some(RangeEvaluator::try_new(
2676                        &input_schema,
2677                        Arc::clone(&op.output_grid),
2678                        op.window,
2679                        op.function,
2680                    )?),
2681                    merge,
2682                    state,
2683                }
2684            }
2685            NativeExpr::Map { input, op } => {
2686                let child = Self::build(
2687                    input,
2688                    pool,
2689                    inputs,
2690                    binary_before,
2691                    format!("{location}.input"),
2692                    duplicate_evidence.clone(),
2693                    sources,
2694                )?;
2695                let schema = node.output.samples().cloned().ok_or_else(|| {
2696                    DataFusionError::Execution("map does not produce samples".to_string())
2697                })?;
2698                let state = NodeState::new(
2699                    format!("native.map at {location}"),
2700                    Arc::clone(&metrics),
2701                    pool,
2702                );
2703                RuntimeOp::Map {
2704                    input: Box::new(child),
2705                    map: MapRuntime {
2706                        ops: Arc::clone(&op.ops),
2707                        schema,
2708                    },
2709                    state,
2710                }
2711            }
2712            NativeExpr::ParameterizedMap {
2713                input,
2714                op,
2715                parameters,
2716            } => {
2717                let child = Self::build(
2718                    input,
2719                    pool,
2720                    inputs,
2721                    binary_before,
2722                    format!("{location}.input"),
2723                    duplicate_evidence.clone(),
2724                    sources,
2725                )?;
2726                let schema = match &node.output {
2727                    NativeType::Samples(schema) => Arc::clone(schema),
2728                    NativeType::Scalar(grid) => Arc::new(scalar_schema(Arc::clone(grid))),
2729                    NativeType::AggregateState(_) => {
2730                        return Err(DataFusionError::Execution(
2731                            "map does not produce samples or a scalar, but aggregate state"
2732                                .to_string(),
2733                        ));
2734                    }
2735                };
2736                let literals = parameters
2737                    .iter()
2738                    .map(|parameter| match &parameter.expr {
2739                        NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
2740                        _ => None,
2741                    })
2742                    .collect();
2743                let input_literal = match &input.expr {
2744                    NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
2745                    _ => None,
2746                };
2747                let nodes = parameters
2748                    .iter()
2749                    .enumerate()
2750                    .map(|(index, parameter)| {
2751                        Self::build(
2752                            parameter,
2753                            pool,
2754                            inputs,
2755                            binary_before,
2756                            format!("{location}.parameter{index}"),
2757                            duplicate_evidence.clone(),
2758                            sources,
2759                        )
2760                    })
2761                    .collect::<Result<Vec<_>>>()?;
2762                let state = NodeState::new(
2763                    format!("native.map at {location}"),
2764                    Arc::clone(&metrics),
2765                    pool,
2766                );
2767                RuntimeOp::ParameterizedMap {
2768                    input: Box::new(child),
2769                    parameters: nodes,
2770                    map: ParameterizedMapRuntime {
2771                        op: *op,
2772                        schema,
2773                        input_literal,
2774                        input_produced: false,
2775                        literals,
2776                        values: vec![None; parameters.len()],
2777                        parameter_bytes: 0,
2778                    },
2779                    state,
2780                }
2781            }
2782            NativeExpr::Timestamp { input } => {
2783                let child = Self::build(
2784                    input,
2785                    pool,
2786                    inputs,
2787                    binary_before,
2788                    format!("{location}.input"),
2789                    duplicate_evidence.clone(),
2790                    sources,
2791                )?;
2792                let schema = node.output.samples().cloned().ok_or_else(|| {
2793                    DataFusionError::Execution("timestamp does not produce samples".to_string())
2794                })?;
2795                let state = NodeState::new(
2796                    format!("native.timestamp at {location}"),
2797                    Arc::clone(&metrics),
2798                    pool,
2799                );
2800                RuntimeOp::Timestamp {
2801                    input: Box::new(child),
2802                    schema,
2803                    state,
2804                }
2805            }
2806            NativeExpr::Binary {
2807                left,
2808                right,
2809                matching,
2810            } => {
2811                let left_schema = left.output.samples();
2812                let right_schema = right.output.samples();
2813                let (binary, broadcast) = match (left_schema, right_schema) {
2814                    (Some(left_schema), Some(right_schema))
2815                        if left_schema.eval_grid.is_some() && right_schema.eval_grid.is_some() =>
2816                    {
2817                        let node_index = *binary_before;
2818                        *binary_before += 1;
2819                        (
2820                            Some(BinaryRuntime::new(
2821                                PairKernel::Binary(Arc::new(matching.clone())),
2822                                [Arc::clone(left_schema), Arc::clone(right_schema)],
2823                                node_index,
2824                                duplicate_evidence.clone(),
2825                            )),
2826                            None,
2827                        )
2828                    }
2829                    _ => (None, Some(broadcast_runtime(left, right, matching)?)),
2830                };
2831                let left_node = Self::build(
2832                    left,
2833                    pool,
2834                    inputs,
2835                    binary_before,
2836                    format!("{location}.left"),
2837                    duplicate_evidence.clone(),
2838                    sources,
2839                )?;
2840                let right_node = Self::build(
2841                    right,
2842                    pool,
2843                    inputs,
2844                    binary_before,
2845                    format!("{location}.right"),
2846                    duplicate_evidence.clone(),
2847                    sources,
2848                )?;
2849                match (binary, broadcast) {
2850                    (Some(binary), None) => RuntimeOp::Binary {
2851                        left: Box::new(left_node),
2852                        right: Box::new(right_node),
2853                        binary,
2854                        state: NodeState::new(
2855                            format!("native.binary at {location}"),
2856                            Arc::clone(&metrics),
2857                            pool,
2858                        ),
2859                    },
2860                    (None, Some(broadcast)) => {
2861                        let state = NodeState::new(
2862                            format!("native.binary at {location}"),
2863                            Arc::clone(&metrics),
2864                            pool,
2865                        );
2866                        RuntimeOp::Broadcast {
2867                            left: Box::new(left_node),
2868                            right: Box::new(right_node),
2869                            broadcast,
2870                            state,
2871                        }
2872                    }
2873                    _ => {
2874                        return Err(DataFusionError::Internal(
2875                            "binary runtime build selected conflicting operation modes".to_string(),
2876                        ));
2877                    }
2878                }
2879            }
2880            NativeExpr::Set { left, right, op } => {
2881                let (Some(left_schema), Some(right_schema)) =
2882                    (left.output.samples(), right.output.samples())
2883                else {
2884                    return Err(DataFusionError::Execution(
2885                        "a set operation consumes two vectors".to_string(),
2886                    ));
2887                };
2888                let node_index = *binary_before;
2889                *binary_before += 1;
2890                let set = BinaryRuntime::new(
2891                    PairKernel::Set(op.clone()),
2892                    [Arc::clone(left_schema), Arc::clone(right_schema)],
2893                    node_index,
2894                    duplicate_evidence.clone(),
2895                );
2896                let left_node = Self::build(
2897                    left,
2898                    pool,
2899                    inputs,
2900                    binary_before,
2901                    format!("{location}.left"),
2902                    duplicate_evidence.clone(),
2903                    sources,
2904                )?;
2905                let right_node = Self::build(
2906                    right,
2907                    pool,
2908                    inputs,
2909                    binary_before,
2910                    format!("{location}.right"),
2911                    duplicate_evidence.clone(),
2912                    sources,
2913                )?;
2914                RuntimeOp::Binary {
2915                    left: Box::new(left_node),
2916                    right: Box::new(right_node),
2917                    binary: set,
2918                    state: NodeState::new(
2919                        format!("native.set at {location}"),
2920                        Arc::clone(&metrics),
2921                        pool,
2922                    ),
2923                }
2924            }
2925            NativeExpr::Info {
2926                base,
2927                info,
2928                selector,
2929            } => {
2930                let (Some(base_schema), Some(info_schema)) =
2931                    (base.output.samples(), info.output.samples())
2932                else {
2933                    return Err(DataFusionError::Execution(
2934                        "info consumes two vectors".to_string(),
2935                    ));
2936                };
2937                let node_index = *binary_before;
2938                *binary_before += 1;
2939                let runtime = BinaryRuntime::new(
2940                    PairKernel::Info(selector.clone()),
2941                    [Arc::clone(base_schema), Arc::clone(info_schema)],
2942                    node_index,
2943                    duplicate_evidence.clone(),
2944                );
2945                let base_node = Self::build(
2946                    base,
2947                    pool,
2948                    inputs,
2949                    binary_before,
2950                    format!("{location}.base"),
2951                    duplicate_evidence.clone(),
2952                    sources,
2953                )?;
2954                let info_node = Self::build(
2955                    info,
2956                    pool,
2957                    inputs,
2958                    binary_before,
2959                    format!("{location}.info"),
2960                    duplicate_evidence.clone(),
2961                    sources,
2962                )?;
2963                RuntimeOp::Binary {
2964                    left: Box::new(base_node),
2965                    right: Box::new(info_node),
2966                    binary: runtime,
2967                    state: NodeState::new(
2968                        format!("native.info at {location}"),
2969                        Arc::clone(&metrics),
2970                        pool,
2971                    ),
2972                }
2973            }
2974            NativeExpr::Aggregate { input, op } => {
2975                let schema = node
2976                    .output
2977                    .samples()
2978                    .or_else(|| input.output.samples())
2979                    .cloned()
2980                    .ok_or_else(|| {
2981                        DataFusionError::Execution("aggregate does not produce samples".to_string())
2982                    })?;
2983                let mut state = NodeState::new(
2984                    format!("native.aggregate at {location}"),
2985                    Arc::clone(&metrics),
2986                    pool,
2987                );
2988                let aggregate = AggregateRuntime::new(op.clone(), schema, &mut state.buffer)?;
2989                let child = Self::build(
2990                    input,
2991                    pool,
2992                    inputs,
2993                    binary_before,
2994                    format!("{location}.input"),
2995                    duplicate_evidence.clone(),
2996                    sources,
2997                )?;
2998                RuntimeOp::Aggregate {
2999                    input: Box::new(child),
3000                    aggregate,
3001                    state,
3002                }
3003            }
3004            NativeExpr::ParameterizedAggregate {
3005                input,
3006                op,
3007                parameter,
3008            } => {
3009                let schema = node
3010                    .output
3011                    .samples()
3012                    .or_else(|| input.output.samples())
3013                    .cloned()
3014                    .ok_or_else(|| {
3015                        DataFusionError::Execution(
3016                            "a parameterized aggregate does not produce samples".into(),
3017                        )
3018                    })?;
3019                let mut state = NodeState::new(
3020                    format!("native.aggregate at {location}"),
3021                    Arc::clone(&metrics),
3022                    pool,
3023                );
3024                let aggregate =
3025                    AggregateRuntime::new_parameterized(op.clone(), schema, &mut state.buffer)?;
3026                let child = Self::build(
3027                    input,
3028                    pool,
3029                    inputs,
3030                    binary_before,
3031                    format!("{location}.input"),
3032                    duplicate_evidence.clone(),
3033                    sources,
3034                )?;
3035                // Input before parameter: the order the selector walk binds the two sources in.
3036                let parameter = Self::build(
3037                    parameter,
3038                    pool,
3039                    inputs,
3040                    binary_before,
3041                    format!("{location}.parameter"),
3042                    duplicate_evidence.clone(),
3043                    sources,
3044                )?;
3045                RuntimeOp::ParameterizedAggregate {
3046                    input: Box::new(child),
3047                    parameter: Some(Box::new(parameter)),
3048                    aggregate,
3049                    state,
3050                }
3051            }
3052            NativeExpr::ParameterizedTopK {
3053                input,
3054                op,
3055                parameter,
3056            } => {
3057                let schema = node.output.samples().cloned().ok_or_else(|| {
3058                    DataFusionError::Execution("parameterized topk does not produce samples".into())
3059                })?;
3060                let one_field = schema.fields.len() == 1;
3061                if !one_field {
3062                    return Err(DataFusionError::NotImplemented(
3063                        "the native runtime does not execute multi-field vector operations".into(),
3064                    ));
3065                }
3066                let vector = VectorRuntime::try_new(op.clone(), schema)?;
3067                let child = Self::build(
3068                    input,
3069                    pool,
3070                    inputs,
3071                    binary_before,
3072                    format!("{location}.input"),
3073                    duplicate_evidence.clone(),
3074                    sources,
3075                )?;
3076                let parameter = Self::build(
3077                    parameter,
3078                    pool,
3079                    inputs,
3080                    binary_before,
3081                    format!("{location}.parameter"),
3082                    duplicate_evidence.clone(),
3083                    sources,
3084                )?;
3085                let state = NodeState::new(
3086                    format!("native.vector at {location}"),
3087                    Arc::clone(&metrics),
3088                    pool,
3089                );
3090                RuntimeOp::ParameterizedTopK {
3091                    input: Box::new(child),
3092                    parameter: Some(Box::new(parameter)),
3093                    vector,
3094                    state,
3095                }
3096            }
3097            NativeExpr::ParameterizedHistogram {
3098                input,
3099                op,
3100                parameters,
3101            } => {
3102                if !matches!(op, BoundVectorOp::Histogram(_)) {
3103                    return Err(DataFusionError::Internal(
3104                        "parameterized histogram has non-histogram op".into(),
3105                    ));
3106                }
3107                if parameters.len()
3108                    != match op {
3109                        BoundVectorOp::Histogram(HistogramFunction::Quantile(_)) => 1,
3110                        BoundVectorOp::Histogram(HistogramFunction::Fraction { .. }) => 2,
3111                        _ => 0,
3112                    }
3113                {
3114                    return Err(DataFusionError::Internal(
3115                        "parameterized histogram has the wrong arity".into(),
3116                    ));
3117                }
3118                let literals = parameters
3119                    .iter()
3120                    .map(|parameter| match &parameter.expr {
3121                        NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
3122                        _ => None,
3123                    })
3124                    .collect();
3125                let schema = node.output.samples().cloned().ok_or_else(|| {
3126                    DataFusionError::Execution(
3127                        "parameterized histogram does not produce samples".into(),
3128                    )
3129                })?;
3130                let vector = VectorRuntime::try_new(op.clone(), schema)?;
3131                let child = Self::build(
3132                    input,
3133                    pool,
3134                    inputs,
3135                    binary_before,
3136                    format!("{location}.input"),
3137                    duplicate_evidence.clone(),
3138                    sources,
3139                )?;
3140                let mut built = Vec::with_capacity(parameters.len());
3141                for (index, parameter) in parameters.iter().enumerate() {
3142                    let runtime = Self::build(
3143                        parameter,
3144                        pool,
3145                        inputs,
3146                        binary_before,
3147                        format!("{location}.parameter{index}"),
3148                        duplicate_evidence.clone(),
3149                        sources,
3150                    )?;
3151                    built.push(Some(runtime));
3152                }
3153                RuntimeOp::ParameterizedHistogram {
3154                    input: Box::new(child),
3155                    parameter_bytes: vec![0; built.len()],
3156                    values: vec![None; built.len()],
3157                    parameters: built,
3158                    literals,
3159                    vector,
3160                    state: NodeState::new(
3161                        format!("native.vector at {location}"),
3162                        Arc::clone(&metrics),
3163                        pool,
3164                    ),
3165                }
3166            }
3167            NativeExpr::Vector { input, op } => {
3168                let schema = node.output.samples().cloned().ok_or_else(|| {
3169                    DataFusionError::Execution(
3170                        "vector operation does not produce samples".to_string(),
3171                    )
3172                })?;
3173                let one_field = matches!(
3174                    op,
3175                    BoundVectorOp::TopK { .. }
3176                        | BoundVectorOp::LimitK { .. }
3177                        | BoundVectorOp::Sort(SortOrder::Asc | SortOrder::Desc)
3178                );
3179                if one_field && schema.fields.len() != 1 {
3180                    return Err(DataFusionError::NotImplemented(
3181                        "the native runtime does not execute multi-field vector operations"
3182                            .to_string(),
3183                    ));
3184                }
3185                let mut vector = VectorRuntime::try_new(op.clone(), schema)?;
3186                let child = Self::build(
3187                    input,
3188                    pool,
3189                    inputs,
3190                    binary_before,
3191                    format!("{location}.input"),
3192                    duplicate_evidence.clone(),
3193                    sources,
3194                )?;
3195                let limitk = matches!(op, BoundVectorOp::LimitK { .. });
3196                if limitk
3197                    && matches!(
3198                        unifies_its_own_contributions(input, &sources.tags, &sources.metrics),
3199                        Some(false)
3200                    )
3201                {
3202                    vector.merge_input = true;
3203                }
3204                RuntimeOp::Vector {
3205                    input: Box::new(child),
3206                    vector,
3207                    state: NodeState::new(
3208                        format!("native.vector at {location}"),
3209                        Arc::clone(&metrics),
3210                        pool,
3211                    ),
3212                }
3213            }
3214        };
3215        Ok(Self { metrics, op })
3216    }
3217
3218    /// The node's direct children, each with the role its metrics are named by. `children_mut`
3219    /// yields the same nodes in the same order.
3220    fn children(&self) -> impl Iterator<Item = (ChildRole, &RuntimeNode)> {
3221        let mut operands: [Option<(ChildRole, &RuntimeNode)>; 2] = [None, None];
3222        let mut parameter: Option<&RuntimeNode> = None;
3223        let mut map_parameters: &[RuntimeNode] = &[];
3224        let mut histogram_parameters: &[Option<RuntimeNode>] = &[];
3225        match &self.op {
3226            RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => {}
3227            RuntimeOp::ScalarOf { input, .. }
3228            | RuntimeOp::VectorOf { input, .. }
3229            | RuntimeOp::Instant { input, .. }
3230            | RuntimeOp::Merge { input, .. }
3231            | RuntimeOp::Window { input, .. }
3232            | RuntimeOp::Map { input, .. }
3233            | RuntimeOp::Timestamp { input, .. }
3234            | RuntimeOp::Aggregate { input, .. }
3235            | RuntimeOp::Vector { input, .. } => operands[0] = Some((ChildRole::Input, input)),
3236            RuntimeOp::ParameterizedMap {
3237                input, parameters, ..
3238            } => {
3239                operands[0] = Some((ChildRole::Input, input));
3240                map_parameters = parameters;
3241            }
3242            RuntimeOp::ParameterizedTopK {
3243                input,
3244                parameter: topk_or_quantile,
3245                ..
3246            }
3247            | RuntimeOp::ParameterizedAggregate {
3248                input,
3249                parameter: topk_or_quantile,
3250                ..
3251            } => {
3252                operands[0] = Some((ChildRole::Input, input));
3253                parameter = topk_or_quantile.as_deref();
3254            }
3255            RuntimeOp::ParameterizedHistogram {
3256                input, parameters, ..
3257            } => {
3258                operands[0] = Some((ChildRole::Input, input));
3259                histogram_parameters = parameters;
3260            }
3261            RuntimeOp::Binary { left, right, .. } | RuntimeOp::Broadcast { left, right, .. } => {
3262                operands = [
3263                    Some((ChildRole::Left, left)),
3264                    Some((ChildRole::Right, right)),
3265                ];
3266            }
3267        }
3268        // Only one of the two lists is non-empty. A histogram parameter keeps its slot index after
3269        // the earlier ones are released.
3270        let indexed = map_parameters.iter().enumerate();
3271        let unreleased = histogram_parameters
3272            .iter()
3273            .enumerate()
3274            .filter_map(|(index, parameter)| parameter.as_ref().map(|node| (index, node)));
3275        operands
3276            .into_iter()
3277            .flatten()
3278            .chain(parameter.map(|node| (ChildRole::Parameter, node)))
3279            .chain(
3280                indexed
3281                    .chain(unreleased)
3282                    .map(|(index, node)| (ChildRole::IndexedParameter(index), node)),
3283            )
3284    }
3285
3286    fn children_mut(&mut self) -> impl Iterator<Item = &mut RuntimeNode> {
3287        let mut operands: [Option<&mut RuntimeNode>; 2] = [None, None];
3288        let mut parameter: Option<&mut RuntimeNode> = None;
3289        let mut map_parameters: &mut [RuntimeNode] = &mut [];
3290        let mut histogram_parameters: &mut [Option<RuntimeNode>] = &mut [];
3291        match &mut self.op {
3292            RuntimeOp::Input(_) | RuntimeOp::Scalar | RuntimeOp::EvalTime { .. } => {}
3293            RuntimeOp::ScalarOf { input, .. }
3294            | RuntimeOp::VectorOf { input, .. }
3295            | RuntimeOp::Instant { input, .. }
3296            | RuntimeOp::Merge { input, .. }
3297            | RuntimeOp::Window { input, .. }
3298            | RuntimeOp::Map { input, .. }
3299            | RuntimeOp::Timestamp { input, .. }
3300            | RuntimeOp::Aggregate { input, .. }
3301            | RuntimeOp::Vector { input, .. } => operands[0] = Some(input),
3302            RuntimeOp::ParameterizedMap {
3303                input, parameters, ..
3304            } => {
3305                operands[0] = Some(input);
3306                map_parameters = parameters;
3307            }
3308            RuntimeOp::ParameterizedTopK {
3309                input,
3310                parameter: topk_or_quantile,
3311                ..
3312            }
3313            | RuntimeOp::ParameterizedAggregate {
3314                input,
3315                parameter: topk_or_quantile,
3316                ..
3317            } => {
3318                operands[0] = Some(input);
3319                parameter = topk_or_quantile.as_deref_mut();
3320            }
3321            RuntimeOp::ParameterizedHistogram {
3322                input, parameters, ..
3323            } => {
3324                operands[0] = Some(input);
3325                histogram_parameters = parameters;
3326            }
3327            RuntimeOp::Binary { left, right, .. } | RuntimeOp::Broadcast { left, right, .. } => {
3328                operands = [Some(left), Some(right)];
3329            }
3330        }
3331        operands
3332            .into_iter()
3333            .flatten()
3334            .chain(parameter)
3335            .chain(map_parameters.iter_mut())
3336            .chain(histogram_parameters.iter_mut().flatten())
3337    }
3338
3339    fn state(&self) -> Option<&NodeState> {
3340        match &self.op {
3341            RuntimeOp::Input(_) | RuntimeOp::Scalar => None,
3342            RuntimeOp::ScalarOf { state, .. }
3343            | RuntimeOp::EvalTime { state, .. }
3344            | RuntimeOp::VectorOf { state, .. }
3345            | RuntimeOp::Instant { state, .. }
3346            | RuntimeOp::Merge { state, .. }
3347            | RuntimeOp::Window { state, .. }
3348            | RuntimeOp::Map { state, .. }
3349            | RuntimeOp::ParameterizedMap { state, .. }
3350            | RuntimeOp::Timestamp { state, .. }
3351            | RuntimeOp::Binary { state, .. }
3352            | RuntimeOp::Broadcast { state, .. }
3353            | RuntimeOp::Aggregate { state, .. }
3354            | RuntimeOp::Vector { state, .. }
3355            | RuntimeOp::ParameterizedTopK { state, .. }
3356            | RuntimeOp::ParameterizedAggregate { state, .. }
3357            | RuntimeOp::ParameterizedHistogram { state, .. } => Some(state),
3358        }
3359    }
3360
3361    fn register_metrics(&self, name: &str, set: &ExecutionPlanMetricsSet, partition: usize) {
3362        self.metrics.register(name, set, partition);
3363        for (role, child) in self.children() {
3364            child.register_metrics(&role.metric_name(name), set, partition);
3365        }
3366    }
3367
3368    fn reserved_bytes(&self) -> usize {
3369        let own = self
3370            .state()
3371            .map_or(0, |state| state.buffer.reservation.size());
3372        self.children().fold(own, |total, (_, child)| {
3373            total.saturating_add(child.reserved_bytes())
3374        })
3375    }
3376}
3377
3378impl RuntimeNode {
3379    fn set_annotations(&mut self, collector: PromqlAnnotationCollector) {
3380        match &mut self.op {
3381            RuntimeOp::Window { window, .. } => {
3382                if let Some(window) = window {
3383                    window.set_annotations(Some(collector.clone()));
3384                }
3385            }
3386            RuntimeOp::Binary { binary, .. } => binary.annotations = Some(collector.clone()),
3387            RuntimeOp::Broadcast { broadcast, .. } => {
3388                broadcast.annotations = Some(collector.clone())
3389            }
3390            RuntimeOp::Aggregate { aggregate, .. }
3391            | RuntimeOp::ParameterizedAggregate { aggregate, .. } => {
3392                aggregate.set_annotations(collector.clone())
3393            }
3394            RuntimeOp::Vector { vector, .. }
3395            | RuntimeOp::ParameterizedTopK { vector, .. }
3396            | RuntimeOp::ParameterizedHistogram { vector, .. } => {
3397                vector.annotations = Some(collector.clone())
3398            }
3399            RuntimeOp::Input(_)
3400            | RuntimeOp::Scalar
3401            | RuntimeOp::ScalarOf { .. }
3402            | RuntimeOp::EvalTime { .. }
3403            | RuntimeOp::VectorOf { .. }
3404            | RuntimeOp::Instant { .. }
3405            | RuntimeOp::Merge { .. }
3406            | RuntimeOp::Map { .. }
3407            | RuntimeOp::ParameterizedMap { .. }
3408            | RuntimeOp::Timestamp { .. } => {}
3409        }
3410        for child in self.children_mut() {
3411            child.set_annotations(collector.clone());
3412        }
3413    }
3414
3415    /// Pulls this node's next chunk, pulling its children as needed. `inputs_finished` says no
3416    /// more source chunks will arrive, so a node that needs its whole input can tell "nothing more"
3417    /// from "nothing yet". Grows the stack as it recurses ([`NATIVE_STACK_RED_ZONE`]).
3418    fn pull(
3419        &mut self,
3420        inputs: &mut [InputSlot],
3421        inputs_finished: bool,
3422    ) -> Result<Option<NativeChunk>> {
3423        stacker::maybe_grow(NATIVE_STACK_RED_ZONE, NATIVE_STACK_GROWTH, || {
3424            self.pull_within_stack(inputs, inputs_finished)
3425        })
3426    }
3427
3428    fn pull_within_stack(
3429        &mut self,
3430        inputs: &mut [InputSlot],
3431        inputs_finished: bool,
3432    ) -> Result<Option<NativeChunk>> {
3433        match &mut self.op {
3434            RuntimeOp::Input(id) => {
3435                let input = *id;
3436                let count = inputs.len();
3437                let slot = inputs
3438                    .get_mut(input.index())
3439                    .ok_or_else(|| no_input(count, input))?;
3440                slot.pop_source()
3441            }
3442            // A constant has no chunk: consumers read the value off their own binding.
3443            RuntimeOp::Scalar => Ok(None),
3444            RuntimeOp::ScalarOf {
3445                input,
3446                input_schema,
3447                grid,
3448                retained,
3449                produced,
3450                state,
3451            } => {
3452                while let Some(chunk) = input.pull(inputs, inputs_finished)? {
3453                    let NativeChunk::Evaluated(chunk) = chunk else {
3454                        return Err(DataFusionError::Execution(
3455                            "scalar() consumes evaluated chunks, not raw samples".into(),
3456                        ));
3457                    };
3458                    validate_binary_operand(input_schema, std::slice::from_ref(&chunk.series))
3459                        .map_err(|error| {
3460                            DataFusionError::Execution(format!(
3461                                "scalar() rejected its input: {error}"
3462                            ))
3463                        })?;
3464                    let pending = retained.pending(&chunk);
3465                    state.buffer.grow(pending).map_err(|e| state.context(e))?;
3466                    retained
3467                        .retain(chunk, Reader::Vector)
3468                        .map_err(|e| state.context(e))?;
3469                    state
3470                        .buffer
3471                        .resize(retained.held)
3472                        .map_err(|e| state.context(e))?;
3473                }
3474                if !inputs_finished || !input.settled(inputs) {
3475                    return Ok(None);
3476                }
3477                if !*produced {
3478                    let len = grid.spec().len as usize;
3479                    let bytes = grid_chunk_bytes(grid).map_err(|e| state.context(e))?;
3480                    // The kernel's per-point sample counts.
3481                    let counts_bytes = len.saturating_mul(std::mem::size_of::<u8>());
3482                    let assembly = retained
3483                        .assembly_bytes(input_schema)
3484                        .ok_or_else(vector_overflow)?;
3485                    state
3486                        .buffer
3487                        .grow(assembly.saturating_add(bytes).saturating_add(counts_bytes))
3488                        .map_err(|e| state.context(e))?;
3489                    let assembled = retained
3490                        .assemble(input_schema, Reader::Vector)
3491                        .map_err(|e| state.context(e))?;
3492                    retained.release();
3493                    // As Prometheus' `funcScalar`: NaN where a point does not hold exactly one
3494                    // float sample; histogram samples are ignored.
3495                    let answer =
3496                        select::scalar(input_schema, &assembled).map_err(|e| state.context(e))?;
3497                    drop(assembled);
3498                    state.buffer.resize(bytes).map_err(|e| state.context(e))?;
3499                    let schema = scalar_schema(Arc::clone(grid));
3500                    let series =
3501                        Series::try_new(&schema, answer.metric, answer.time, answer.fields)
3502                            .map_err(series_error)?;
3503                    state.queued.push_back((
3504                        NativeChunk::Evaluated(EvaluatedChunk::try_new(series, true)?),
3505                        bytes,
3506                    ));
3507                    *produced = true;
3508                }
3509                state.pop_queued(evaluated_values)
3510            }
3511            RuntimeOp::EvalTime {
3512                grid,
3513                date,
3514                produced,
3515                state,
3516            } => {
3517                if !std::mem::replace(produced, true) {
3518                    // `time()` and the date functions materialize the grid's timestamps.
3519                    state
3520                        .buffer
3521                        .reserve_grid(grid)
3522                        .map_err(|error| state.context(error))?;
3523                    let schema = scalar_schema(Arc::clone(grid));
3524                    state
3525                        .produce(grid, || match date {
3526                            None => map_time::time(&schema),
3527                            Some(date) => map_time::date_of_eval_time(*date, &schema),
3528                        })
3529                        .map_err(|error| state.context(error))?;
3530                }
3531                state.pop_queued(evaluated_values)
3532            }
3533            RuntimeOp::VectorOf {
3534                input,
3535                literal,
3536                produced,
3537                schema,
3538                state,
3539            } => {
3540                if let Some(value) = literal {
3541                    if !std::mem::replace(produced, true) {
3542                        let grid = schema.eval_grid.clone().ok_or_else(|| {
3543                            DataFusionError::Execution(
3544                                "vector() produces values without a grid".to_string(),
3545                            )
3546                        })?;
3547                        state
3548                            .produce(&grid, || {
3549                                Ok(scalar_chunk_on(schema, Arc::clone(&grid), *value)?.series)
3550                            })
3551                            .map_err(|error| state.context(error))?;
3552                    }
3553                    return state.pop_queued(evaluated_values);
3554                }
3555                // A scalar is already one unlabelled series; only the schema changes.
3556                let Some(chunk) = input.pull(inputs, inputs_finished)? else {
3557                    return Ok(None);
3558                };
3559                let NativeChunk::Evaluated(EvaluatedChunk { series, is_last }) = chunk else {
3560                    return Err(DataFusionError::Execution(
3561                        "vector() consumes an evaluated scalar, not raw samples".to_string(),
3562                    ));
3563                };
3564                ensure_grid(schema.eval_grid.as_deref(), &series.time)?;
3565                let series = Series::try_new(schema, series.metric, series.time, series.fields)
3566                    .map_err(series_error)?;
3567                Ok(Some(NativeChunk::Evaluated(EvaluatedChunk::try_new(
3568                    series, is_last,
3569                )?)))
3570            }
3571            RuntimeOp::Instant {
3572                input,
3573                instant,
3574                state,
3575            } => {
3576                let selection = instant;
3577                // Only a series' closing chunk yields output, so keep pulling until one does.
3578                loop {
3579                    let Some(chunk) = input.pull(inputs, inputs_finished)? else {
3580                        return Ok(None);
3581                    };
3582                    if let Some(output) = state
3583                        .instant(selection, chunk)
3584                        .map_err(|error| state.context(error))?
3585                    {
3586                        return Ok(Some(NativeChunk::Evaluated(output)));
3587                    }
3588                }
3589            }
3590            RuntimeOp::Merge {
3591                input,
3592                merge,
3593                state,
3594            } => {
3595                if let Some(chunk) = state.take_output()? {
3596                    return Ok(Some(chunk));
3597                }
3598                while let Some(chunk) = input.pull(inputs, inputs_finished)? {
3599                    let NativeChunk::Evaluated(chunk) = chunk else {
3600                        return Err(DataFusionError::Execution(
3601                            "merge consumes evaluated samples, not raw samples".into(),
3602                        ));
3603                    };
3604                    state.collect_merge(
3605                        merge.as_mut().ok_or_else(|| {
3606                            DataFusionError::Execution("merge buffer was released".into())
3607                        })?,
3608                        chunk,
3609                    )?;
3610                }
3611                Ok(None)
3612            }
3613            RuntimeOp::Window {
3614                input,
3615                window,
3616                merge,
3617                state,
3618            } => {
3619                // Chunks queued by a flush of collected input go first.
3620                if let Some(chunk) = state.take_output().map_err(|error| state.context(error))? {
3621                    return Ok(Some(chunk));
3622                }
3623                let Some(evaluator) = window.as_mut() else {
3624                    return Err(no_window());
3625                };
3626                // A chunk that decides no point yields nothing; keep pulling.
3627                loop {
3628                    let Some(chunk) = input.pull(inputs, inputs_finished)? else {
3629                        return Ok(None);
3630                    };
3631                    if let Some(output) = state
3632                        .window(evaluator, merge, chunk)
3633                        .map_err(|error| state.context(error))?
3634                    {
3635                        return Ok(Some(NativeChunk::Evaluated(output)));
3636                    }
3637                }
3638            }
3639            RuntimeOp::Map { input, map, state } => {
3640                let operation = map;
3641                // A chunk the operation empties entirely yields nothing; keep pulling.
3642                loop {
3643                    let Some(chunk) = input.pull(inputs, inputs_finished)? else {
3644                        return Ok(None);
3645                    };
3646                    let NativeChunk::Evaluated(chunk) = chunk else {
3647                        return Err(DataFusionError::Execution(
3648                            "the map node consumes an evaluated chunk, not raw samples".to_string(),
3649                        ));
3650                    };
3651                    if let Some(output) = state
3652                        .map(operation, chunk)
3653                        .map_err(|error| state.context(error))?
3654                    {
3655                        return Ok(Some(NativeChunk::Evaluated(output)));
3656                    }
3657                }
3658            }
3659            RuntimeOp::ParameterizedMap {
3660                input,
3661                parameters,
3662                map,
3663                state,
3664            } => {
3665                let operation = map;
3666                // Read every parameter whole first; a constant one is built from its binding.
3667                for (index, parameter) in parameters.iter_mut().enumerate() {
3668                    let slot = &mut operation.values[index];
3669                    if slot.is_some() {
3670                        continue;
3671                    }
3672                    if let Some(value) = operation.literals[index] {
3673                        let grid = operation.schema.eval_grid.clone().ok_or_else(|| {
3674                            DataFusionError::Execution(
3675                                "a map produces values without a grid".to_string(),
3676                            )
3677                        })?;
3678                        state
3679                            .hold_constant(&mut operation.parameter_bytes, slot, grid, value)
3680                            .map_err(|error| state.context(error))?;
3681                        continue;
3682                    }
3683                    while let Some(chunk) = parameter.pull(inputs, inputs_finished)? {
3684                        state
3685                            .hold_scalar(&mut operation.parameter_bytes, slot, chunk)
3686                            .map_err(|error| state.context(error))?;
3687                    }
3688                }
3689                if !operation.ready() {
3690                    // A parameter like `scalar(selector)` answers only after its input ends.
3691                    if !inputs_finished
3692                        || !parameters.iter().all(|parameter| parameter.settled(inputs))
3693                    {
3694                        return Ok(None);
3695                    }
3696                    return Err(DataFusionError::Execution(
3697                        "a map parameter did not hand over its value".to_string(),
3698                    ));
3699                }
3700                // A constant input has no chunk of its own; build it on the map's grid.
3701                if let Some(value) = operation.input_literal
3702                    && !std::mem::replace(&mut operation.input_produced, true)
3703                {
3704                    let grid = operation.schema.eval_grid.clone().ok_or_else(|| {
3705                        DataFusionError::Execution(
3706                            "a map produces values without a grid".to_string(),
3707                        )
3708                    })?;
3709                    let mut slot = None;
3710                    state
3711                        .hold_constant(&mut operation.parameter_bytes, &mut slot, grid, value)
3712                        .map_err(|error| state.context(error))?;
3713                    let series = slot.expect("the constant input was just built");
3714                    let chunk = EvaluatedChunk::try_new(series, true)
3715                        .map_err(|error| state.context(error))?;
3716                    return state
3717                        .parameterized_map(operation, chunk)
3718                        .map_err(|error| state.context(error))
3719                        .map(|output| output.map(NativeChunk::Evaluated));
3720                }
3721                loop {
3722                    let chunk = match input.pull(inputs, inputs_finished)? {
3723                        Some(NativeChunk::Evaluated(chunk)) => chunk,
3724                        Some(NativeChunk::Raw(_)) => {
3725                            return Err(DataFusionError::Execution(
3726                                "the map node consumes an evaluated chunk, not raw samples"
3727                                    .to_string(),
3728                            ));
3729                        }
3730                        Some(NativeChunk::AggregateState(_)) => {
3731                            return Err(DataFusionError::Execution(
3732                                "an aggregate state chunk reached a node that reads values or samples"
3733                                    .to_string(),
3734                            ));
3735                        }
3736                        None => return Ok(None),
3737                    };
3738                    if let Some(output) = state
3739                        .parameterized_map(operation, chunk)
3740                        .map_err(|error| state.context(error))?
3741                    {
3742                        return Ok(Some(NativeChunk::Evaluated(output)));
3743                    }
3744                }
3745            }
3746            RuntimeOp::Timestamp {
3747                input,
3748                schema,
3749                state,
3750            } => loop {
3751                let Some(chunk) = input.pull(inputs, inputs_finished)? else {
3752                    return Ok(None);
3753                };
3754                let NativeChunk::Evaluated(chunk) = chunk else {
3755                    return Err(DataFusionError::Execution(
3756                        "timestamp consumes evaluated samples, not raw samples".into(),
3757                    ));
3758                };
3759                if let Some(output) = state
3760                    .timestamp(schema, chunk)
3761                    .map_err(|error| state.context(error))?
3762                {
3763                    return Ok(Some(NativeChunk::Evaluated(output)));
3764                }
3765            },
3766            RuntimeOp::Binary {
3767                left,
3768                right,
3769                binary,
3770                state,
3771            } => {
3772                let operation = binary;
3773                // Retain everything both operands hand over; nothing is decided until both are
3774                // whole.
3775                while let Some(chunk) = left.pull(inputs, inputs_finished)? {
3776                    state
3777                        .retain_binary(operation, 0, chunk)
3778                        .map_err(|error| state.context(error))?;
3779                }
3780                while let Some(chunk) = right.pull(inputs, inputs_finished)? {
3781                    state
3782                        .retain_binary(operation, 1, chunk)
3783                        .map_err(|error| state.context(error))?;
3784                }
3785                // An empty pull is not the end: a collecting window below may not have flushed.
3786                if !inputs_finished || !left.settled(inputs) || !right.settled(inputs) {
3787                    return Ok(None);
3788                }
3789                state
3790                    .compute_binary(operation)
3791                    .map_err(|error| state.context(error))?;
3792                state.pop_queued(evaluated_values)
3793            }
3794            RuntimeOp::Broadcast {
3795                left,
3796                right,
3797                broadcast,
3798                state,
3799            } => {
3800                let operation = broadcast;
3801                // A dynamic scalar is read whole first; then each vector chunk is mapped as it
3802                // arrives.
3803                let (vector, scalar) = if operation.vector_left {
3804                    (&mut **left, &mut **right)
3805                } else {
3806                    (&mut **right, &mut **left)
3807                };
3808                if let BroadcastScalar::Dynamic { value, .. } = &mut operation.scalar
3809                    && value.is_none()
3810                {
3811                    while let Some(chunk) = scalar.pull(inputs, inputs_finished)? {
3812                        state
3813                            .hold_scalar(&mut operation.scalar_bytes, value, chunk)
3814                            .map_err(|error| state.context(error))?;
3815                    }
3816                }
3817                if operation.awaits_scalar() {
3818                    if !inputs_finished || !scalar.settled(inputs) {
3819                        return Ok(None);
3820                    }
3821                    return Err(DataFusionError::Execution(
3822                        "a broadcast scalar did not hand over its value".to_string(),
3823                    ));
3824                }
3825                // A chunk the operation empties entirely yields nothing; keep pulling.
3826                loop {
3827                    let Some(chunk) = vector.pull(inputs, inputs_finished)? else {
3828                        return Ok(None);
3829                    };
3830                    if let Some(output) = state
3831                        .broadcast(operation, chunk)
3832                        .map_err(|error| state.context(error))?
3833                    {
3834                        return Ok(Some(NativeChunk::Evaluated(output)));
3835                    }
3836                }
3837            }
3838            RuntimeOp::Aggregate {
3839                input,
3840                aggregate,
3841                state,
3842            } => {
3843                let fold = aggregate;
3844                // Nothing is answered before the input ends.
3845                while let Some(chunk) = input.pull(inputs, inputs_finished)? {
3846                    state
3847                        .retain_aggregate(fold, chunk)
3848                        .map_err(|error| state.context(error))?;
3849                }
3850                if !inputs_finished || !input.settled(inputs) {
3851                    return Ok(None);
3852                }
3853                state
3854                    .compute_aggregate(fold)
3855                    .map_err(|error| state.context(error))?;
3856                state.pop_queued(evaluated_values)
3857            }
3858            RuntimeOp::ParameterizedAggregate {
3859                input,
3860                parameter,
3861                aggregate,
3862                state,
3863            } => {
3864                let fold = aggregate;
3865                // φ is read whole before the fold can answer.
3866                if let Some(parameter_node) = parameter.as_mut() {
3867                    let mut slot = None;
3868                    let mut held = 0usize;
3869                    while let Some(chunk) = parameter_node.pull(inputs, inputs_finished)? {
3870                        state
3871                            .hold_scalar(&mut held, &mut slot, chunk)
3872                            .map_err(|error| state.context(error))?;
3873                    }
3874                    let series = {
3875                        // While φ is pending, drain the input into the fold anyway: the source
3876                        // queue bills each queued slice for its whole allocation, while the fold
3877                        // bills a shared allocation once.
3878                        if !parameter_node.settled(inputs) {
3879                            while let Some(chunk) = input.pull(inputs, inputs_finished)? {
3880                                state
3881                                    .retain_aggregate(fold, chunk)
3882                                    .map_err(|error| state.context(error))?;
3883                            }
3884                            return Ok(None);
3885                        }
3886                        slot.ok_or_else(|| {
3887                            DataFusionError::Execution(
3888                                "the quantile parameter produced no scalar".into(),
3889                            )
3890                        })?
3891                    };
3892                    fold.hold_parameter(series, &mut state.buffer)
3893                        .map_err(|error| state.context(error))?;
3894                    // Run the evaluators' truncation check now: `unclosed` cannot reach this
3895                    // subtree once it is dropped.
3896                    parameter_node.finish_windows()?;
3897                    *parameter = None;
3898                }
3899                while let Some(chunk) = input.pull(inputs, inputs_finished)? {
3900                    state
3901                        .retain_aggregate(fold, chunk)
3902                        .map_err(|error| state.context(error))?;
3903                }
3904                if !inputs_finished || !input.settled(inputs) {
3905                    return Ok(None);
3906                }
3907                state
3908                    .compute_aggregate(fold)
3909                    .map_err(|error| state.context(error))?;
3910                state.pop_queued(evaluated_values)
3911            }
3912            RuntimeOp::ParameterizedTopK {
3913                input,
3914                parameter,
3915                vector,
3916                state,
3917            } => {
3918                let operation = vector;
3919                if operation.parameter.is_none() {
3920                    let mut slot = None;
3921                    let parameter_node = parameter.as_mut().ok_or_else(|| {
3922                        DataFusionError::Internal("topk parameter already consumed".into())
3923                    })?;
3924                    while let Some(chunk) = parameter_node.pull(inputs, inputs_finished)? {
3925                        state
3926                            .hold_scalar(&mut operation.parameter_bytes, &mut slot, chunk)
3927                            .map_err(|error| state.context(error))?;
3928                    }
3929                    let series = {
3930                        if !parameter_node.settled(inputs) {
3931                            return Ok(None);
3932                        }
3933                        slot.ok_or_else(|| {
3934                            DataFusionError::Execution("topk parameter produced no scalar".into())
3935                        })?
3936                    };
3937                    let grid = operation
3938                        .schema
3939                        .eval_grid
3940                        .as_ref()
3941                        .ok_or_else(|| DataFusionError::Internal("topk grid missing".into()))?;
3942                    let len = grid.spec().len as usize;
3943                    if series.time.len() != len {
3944                        return Err(DataFusionError::Execution(
3945                            "topk parameter does not cover its grid".into(),
3946                        ));
3947                    }
3948                    let bytes = len.saturating_mul(std::mem::size_of::<Option<f64>>());
3949                    state
3950                        .buffer
3951                        .grow(bytes)
3952                        .map_err(|error| state.context(error))?;
3953                    let mut values = Vec::with_capacity(len);
3954                    {
3955                        let mut cursor = series.fields.as_slice()[0].cursor();
3956                        for row in 0..len {
3957                            values.push(match cursor.at(row) {
3958                                Some(SampleRef::Float(value)) => Some(value),
3959                                _ => None,
3960                            });
3961                        }
3962                    }
3963                    select::validate_topk_parameters(&values)
3964                        .map_err(|error| state.context(error))?;
3965                    operation.parameter = Some(values);
3966                    drop(series);
3967                    operation.parameter_bytes = bytes;
3968                    state
3969                        .settle_vector(operation)
3970                        .map_err(|error| state.context(error))?;
3971                    // Run the evaluators' truncation check now: `unclosed` cannot reach this
3972                    // subtree once it is dropped.
3973                    parameter_node.finish_windows()?;
3974                    *parameter = None;
3975                }
3976                while let Some(chunk) = input.pull(inputs, inputs_finished)? {
3977                    state
3978                        .retain_vector(operation, chunk)
3979                        .map_err(|error| state.context(error))?;
3980                }
3981                if !inputs_finished || !input.settled(inputs) {
3982                    return Ok(None);
3983                }
3984                state
3985                    .compute_vector(operation)
3986                    .map_err(|error| state.context(error))?;
3987                state.pop_queued(evaluated_values)
3988            }
3989            RuntimeOp::ParameterizedHistogram {
3990                input,
3991                parameters,
3992                literals,
3993                vector,
3994                values,
3995                parameter_bytes,
3996                state,
3997            } => {
3998                let operation = vector;
3999                for index in 0..parameters.len() {
4000                    if values[index].is_none() {
4001                        let mut slot = None;
4002                        if let Some(value) = literals[index] {
4003                            let grid = operation.schema.eval_grid.clone().ok_or_else(|| {
4004                                DataFusionError::Internal("histogram grid missing".into())
4005                            })?;
4006                            state.hold_constant(
4007                                &mut parameter_bytes[index],
4008                                &mut slot,
4009                                grid,
4010                                value,
4011                            )?;
4012                        } else {
4013                            let parameter = parameters[index].as_mut().ok_or_else(|| {
4014                                DataFusionError::Internal(
4015                                    "histogram parameter already consumed".into(),
4016                                )
4017                            })?;
4018                            while let Some(chunk) = parameter.pull(inputs, inputs_finished)? {
4019                                state.hold_scalar(&mut parameter_bytes[index], &mut slot, chunk)?;
4020                            }
4021                            if !parameter.settled(inputs) {
4022                                return Ok(None);
4023                            }
4024                        }
4025                        let series = slot.ok_or_else(|| {
4026                            DataFusionError::Execution(
4027                                "histogram parameter produced no scalar".into(),
4028                            )
4029                        })?;
4030                        let len = operation
4031                            .schema
4032                            .eval_grid
4033                            .as_ref()
4034                            .ok_or_else(|| {
4035                                DataFusionError::Internal("histogram grid missing".into())
4036                            })?
4037                            .spec()
4038                            .len as usize;
4039                        if series.time.len() != len {
4040                            return Err(DataFusionError::Execution(
4041                                "histogram parameter does not cover its grid".into(),
4042                            ));
4043                        }
4044                        let bytes = len.saturating_mul(std::mem::size_of::<Option<f64>>());
4045                        state.buffer.grow(bytes)?;
4046                        let collected = {
4047                            let mut cursor = series.fields.as_slice()[0].cursor();
4048                            (0..len)
4049                                .map(|row| match cursor.at(row) {
4050                                    Some(SampleRef::Float(v)) => Some(v),
4051                                    _ => None,
4052                                })
4053                                .collect::<Vec<Option<f64>>>()
4054                        };
4055                        values[index] = Some(collected);
4056                        parameter_bytes[index] = bytes;
4057                        drop(series);
4058                        operation.parameter_bytes = parameter_bytes
4059                            .iter()
4060                            .copied()
4061                            .fold(0usize, usize::saturating_add);
4062                        state.settle_vector(operation)?;
4063                        if let Some(parameter) = &mut parameters[index] {
4064                            parameter.finish_windows()?;
4065                        }
4066                        parameters[index] = None;
4067                    }
4068                }
4069                while let Some(chunk) = input.pull(inputs, inputs_finished)? {
4070                    state.retain_vector(operation, chunk)?;
4071                }
4072                if !inputs_finished || !input.settled(inputs) {
4073                    return Ok(None);
4074                }
4075                let collected = values
4076                    .iter()
4077                    .map(|v| {
4078                        v.as_deref().ok_or_else(|| {
4079                            DataFusionError::Internal("histogram parameters not collected".into())
4080                        })
4081                    })
4082                    .collect::<Result<Vec<_>>>()?;
4083                state.compute_histogram(operation, &collected)?;
4084                state.pop_queued(evaluated_values)
4085            }
4086            RuntimeOp::Vector {
4087                input,
4088                vector,
4089                state,
4090            } => {
4091                let operation = vector;
4092                while let Some(chunk) = input.pull(inputs, inputs_finished)? {
4093                    state
4094                        .retain_vector(operation, chunk)
4095                        .map_err(|error| state.context(error))?;
4096                }
4097                if !inputs_finished || !input.settled(inputs) {
4098                    return Ok(None);
4099                }
4100                state
4101                    .compute_vector(operation)
4102                    .map_err(|error| state.context(error))?;
4103                state.pop_queued(evaluated_values)
4104            }
4105        }
4106    }
4107
4108    /// Whether this node has produced everything it ever will. An empty pull does not imply it: a
4109    /// collecting window yields nothing until flushed, and a binary node nothing until both
4110    /// operands are done.
4111    fn settled(&self, inputs: &[InputSlot]) -> bool {
4112        let own = match &self.op {
4113            RuntimeOp::Input(id) => inputs
4114                .get(id.index())
4115                .is_some_and(|slot| slot.state.queued.is_empty()),
4116            RuntimeOp::Scalar => true,
4117            RuntimeOp::EvalTime {
4118                produced, state, ..
4119            } => *produced && state.queued.is_empty(),
4120            RuntimeOp::ScalarOf {
4121                produced,
4122                retained,
4123                state,
4124                ..
4125            } => *produced && state.queued.is_empty() && retained.held == 0,
4126            RuntimeOp::VectorOf {
4127                literal,
4128                produced,
4129                state,
4130                ..
4131            } => state.queued.is_empty() && (*produced || literal.is_none()),
4132            // A collecting window still holding its merge input owes output.
4133            RuntimeOp::Window { merge, state, .. } | RuntimeOp::Merge { merge, state, .. } => {
4134                state.queued.is_empty() && merge.is_none()
4135            }
4136            // Settled children are not enough: a whole-input kernel must also have run.
4137            RuntimeOp::Aggregate {
4138                aggregate, state, ..
4139            }
4140            | RuntimeOp::ParameterizedAggregate {
4141                aggregate, state, ..
4142            } => state.queued.is_empty() && aggregate.computed,
4143            RuntimeOp::Vector { vector, state, .. }
4144            | RuntimeOp::ParameterizedTopK { vector, state, .. }
4145            | RuntimeOp::ParameterizedHistogram { vector, state, .. } => {
4146                state.queued.is_empty() && vector.computed
4147            }
4148            // What one side of a vector match answers at a point depends on the other side.
4149            RuntimeOp::Binary { binary, state, .. } => state.queued.is_empty() && binary.computed,
4150            RuntimeOp::Instant { state, .. }
4151            | RuntimeOp::Map { state, .. }
4152            | RuntimeOp::ParameterizedMap { state, .. }
4153            | RuntimeOp::Timestamp { state, .. }
4154            | RuntimeOp::Broadcast { state, .. } => state.queued.is_empty(),
4155        };
4156        own && self.children().all(|(_, child)| child.settled(inputs))
4157    }
4158
4159    /// Flushes every collecting window and merge whose input has settled, deepest first, so an
4160    /// outer one never merges input still held below it. Returns whether anything was flushed.
4161    fn flush_ready_merges(&mut self, inputs: &[InputSlot]) -> Result<bool> {
4162        let mut flushed = false;
4163        for child in self.children_mut() {
4164            flushed |= child.flush_ready_merges(inputs)?;
4165        }
4166        match &mut self.op {
4167            RuntimeOp::Merge {
4168                input,
4169                merge,
4170                state,
4171            } if merge.is_some() && input.settled(inputs) => {
4172                state.flush_canonical_merge(merge)?;
4173                flushed = true;
4174            }
4175            RuntimeOp::Window {
4176                input,
4177                window,
4178                merge,
4179                state,
4180            } if merge.is_some() && input.settled(inputs) => {
4181                let Some(evaluator) = window.as_mut() else {
4182                    return Err(no_window());
4183                };
4184                state
4185                    .flush_merge(evaluator, merge)
4186                    .map_err(|error| state.context(error))?;
4187                flushed = true;
4188            }
4189            _ => {}
4190        }
4191        Ok(flushed)
4192    }
4193
4194    /// Whether any window still holds collected input that has not been merged.
4195    fn any_merge_pending(&self) -> bool {
4196        matches!(
4197            &self.op,
4198            RuntimeOp::Window { merge: Some(_), .. } | RuntimeOp::Merge { merge: Some(_), .. }
4199        ) || self.children().any(|(_, child)| child.any_merge_pending())
4200    }
4201
4202    /// Refuses input that ended with a series still open, in every node that retains whole series;
4203    /// otherwise half a series would be read as a complete one.
4204    fn unclosed(&self) -> Result<()> {
4205        match &self.op {
4206            RuntimeOp::ScalarOf {
4207                retained, state, ..
4208            } => retained
4209                .ensure_closed(Reader::Vector)
4210                .map_err(|error| state.context(error))?,
4211            RuntimeOp::Vector { vector, state, .. }
4212            | RuntimeOp::ParameterizedTopK { vector, state, .. }
4213            | RuntimeOp::ParameterizedHistogram { vector, state, .. } => vector
4214                .input
4215                .ensure_closed(Reader::Vector)
4216                .map_err(|error| state.context(error))?,
4217            RuntimeOp::Binary { binary, state, .. } => {
4218                binary.closed().map_err(|error| state.context(error))?
4219            }
4220            // A fold's retained input does not track open series.
4221            RuntimeOp::Aggregate { .. } | RuntimeOp::ParameterizedAggregate { .. } => {}
4222            RuntimeOp::Input(_)
4223            | RuntimeOp::Scalar
4224            | RuntimeOp::EvalTime { .. }
4225            | RuntimeOp::VectorOf { .. }
4226            | RuntimeOp::Instant { .. }
4227            | RuntimeOp::Merge { .. }
4228            | RuntimeOp::Window { .. }
4229            | RuntimeOp::Map { .. }
4230            | RuntimeOp::ParameterizedMap { .. }
4231            | RuntimeOp::Timestamp { .. }
4232            | RuntimeOp::Broadcast { .. } => {}
4233        }
4234        self.children().try_for_each(|(_, child)| child.unclosed())
4235    }
4236
4237    /// Finishes every window evaluator still present in this subtree. All are finished even after
4238    /// one fails, so none keeps its bytes; the first error is returned.
4239    fn finish_windows(&mut self) -> Result<()> {
4240        let children = self
4241            .children_mut()
4242            .map(RuntimeNode::finish_windows)
4243            .fold(Ok(()), Result::and);
4244        let own = match &mut self.op {
4245            RuntimeOp::Window { window, state, .. } => window
4246                .take()
4247                .map_or(Ok(()), |evaluator| {
4248                    state.buffer.reserve_grid(evaluator.grid())?;
4249                    RangeEvaluator::finish(evaluator)
4250                })
4251                .map_err(|error| state.context(error)),
4252            _ => Ok(()),
4253        };
4254        children.and(own)
4255    }
4256}
4257
4258/// Input label sets and metric names used to decide when series must be merged.
4259#[derive(Clone, Debug, Default)]
4260pub struct SourceFacts {
4261    /// The complete label set of each input, indexed by leaf `source_index`.
4262    tags: Vec<Vec<String>>,
4263    /// The one metric each input is bound to, indexed the same way; `None` when it may have
4264    /// several.
4265    metrics: Vec<Option<Arc<str>>>,
4266}
4267
4268impl SourceFacts {
4269    /// No facts; every decision stays conservative.
4270    pub fn none() -> Self {
4271        Self::default()
4272    }
4273
4274    /// The same tags and metric for each of `sources` inputs, for a statement reading one table.
4275    /// With `metric = None` nothing can be proven.
4276    pub fn uniform(tags: Vec<String>, metric: Option<Arc<str>>, sources: usize) -> Self {
4277        Self {
4278            tags: vec![tags; sources],
4279            metrics: vec![metric; sources],
4280        }
4281    }
4282}
4283
4284impl NativeExecutionState {
4285    pub fn try_new(
4286        tree: &NativeTree,
4287        pool: Arc<dyn MemoryPool>,
4288        duplicate_evidence: Option<Arc<DuplicateEvidence>>,
4289    ) -> Result<Self> {
4290        Self::try_new_with_sources(tree, pool, duplicate_evidence, &SourceFacts::none())
4291    }
4292
4293    /// Builds the execution over `tree`. `sources` must not prove more than the canonical pass
4294    /// assumed when it placed its merges; [`SourceFacts::none`] is always safe.
4295    pub fn try_new_with_sources(
4296        tree: &NativeTree,
4297        pool: Arc<dyn MemoryPool>,
4298        duplicate_evidence: Option<Arc<DuplicateEvidence>>,
4299        sources: &SourceFacts,
4300    ) -> Result<Self> {
4301        let mut inputs = Vec::new();
4302        let mut binary_before = 0usize;
4303        let root = RuntimeNode::build(
4304            tree.root(),
4305            &pool,
4306            &mut inputs,
4307            &mut binary_before,
4308            "root".to_string(),
4309            duplicate_evidence.clone(),
4310            sources,
4311        )?;
4312        let scalar_root = match (&tree.root().expr, &tree.root().output) {
4313            (NativeExpr::Scalar(BoundScalar { value }), NativeType::Scalar(grid)) => Some((
4314                Arc::clone(grid),
4315                *value,
4316                NodeState::new(
4317                    "native.scalar at root".to_string(),
4318                    Arc::clone(&root.metrics),
4319                    &pool,
4320                ),
4321            )),
4322            _ => None,
4323        };
4324        match &tree.root().output {
4325            NativeType::Scalar(_) => {}
4326            NativeType::Samples(schema) if schema.eval_grid.is_some() => {}
4327            NativeType::Samples(_) => {
4328                return Err(DataFusionError::Execution(
4329                    "native runtime root produces raw samples".to_string(),
4330                ));
4331            }
4332            // A `Partial` aggregate root; read through `NativeExecutor::next_state`.
4333            NativeType::AggregateState(_) => {}
4334        }
4335        Ok(Self {
4336            live: Some(LiveExecution {
4337                root,
4338                inputs,
4339                scalar_root,
4340            }),
4341        })
4342    }
4343
4344    pub fn set_annotations(&mut self, collector: Option<PromqlAnnotationCollector>) {
4345        if let (Some(live), Some(collector)) = (&mut self.live, collector) {
4346            live.root.set_annotations(collector);
4347        }
4348    }
4349
4350    /// Registers every node's metric handles with `set`. Call once, before the execution starts.
4351    pub(crate) fn register_metrics(&self, set: &ExecutionPlanMetricsSet, partition: usize) {
4352        if let Some(live) = &self.live {
4353            live.root.register_metrics("root", set, partition);
4354        }
4355    }
4356
4357    /// Returns the runtime input slots bound to `source_index`.
4358    pub fn input_ids(&self, source_index: usize) -> impl Iterator<Item = InputId> + '_ {
4359        self.live
4360            .iter()
4361            .flat_map(|live| live.inputs.iter())
4362            .enumerate()
4363            .filter(move |(_, slot)| slot.source_index == source_index)
4364            .map(|(index, _)| InputId::new(index))
4365    }
4366
4367    pub fn reserved_bytes(&self) -> usize {
4368        self.live.as_ref().map_or(0, |live| {
4369            live.inputs
4370                .iter()
4371                .map(|slot| slot.state.buffer.reservation.size())
4372                .fold(0usize, usize::saturating_add)
4373                .saturating_add(live.root.reserved_bytes())
4374                .saturating_add(
4375                    live.scalar_root
4376                        .as_ref()
4377                        .map_or(0, |(_, _, state)| state.buffer.reservation.size()),
4378                )
4379        })
4380    }
4381}
4382
4383impl LiveExecution {
4384    /// Pulls the root's next chunk; a constant root is produced here on its first pull.
4385    fn pull(&mut self, inputs_finished: bool) -> Result<Option<NativeChunk>> {
4386        if let Some((grid, value, mut state)) = self.scalar_root.take() {
4387            let bytes = grid_chunk_bytes(&grid).map_err(|error| state.context(error))?;
4388            state
4389                .buffer
4390                .grow(bytes)
4391                .map_err(|error| state.context(error))?;
4392            let chunk = scalar_chunk(grid, value).map_err(|error| state.context(error))?;
4393            state.buffer.metrics.record_completed_series(1);
4394            state
4395                .queued
4396                .push_back((NativeChunk::Evaluated(chunk), bytes));
4397            return state.pop_queued(evaluated_values);
4398        }
4399        self.root.pull(&mut self.inputs, inputs_finished)
4400    }
4401
4402    /// Refuses an input left with an open series. Input slots are checked first, so the error names
4403    /// the input rather than a node that retained it.
4404    fn unclosed(&self) -> Result<()> {
4405        if let Some(index) = self.inputs.iter().position(InputSlot::ends_open) {
4406            let slot = &self.inputs[index];
4407            return Err(slot.state.context(truncated_input(InputId::new(index))));
4408        }
4409        self.root.unclosed()
4410    }
4411
4412    fn flush_ready_merges(&mut self) -> Result<bool> {
4413        self.root.flush_ready_merges(&self.inputs)
4414    }
4415
4416    fn any_merge_pending(&self) -> bool {
4417        self.root.any_merge_pending()
4418    }
4419
4420    /// Finishes every window before dropping the live tree and its reservations.
4421    fn close(mut self) -> Result<()> {
4422        self.root.finish_windows()
4423    }
4424}
4425
4426impl NodeState {
4427    /// Queues a source chunk, reserving its [`NativeChunk::bytes`] first so a refused chunk leaves
4428    /// nothing behind.
4429    fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> {
4430        let positions = chunk.positions();
4431        let bytes = chunk.bytes();
4432        self.buffer.grow(bytes)?;
4433        self.queued.push_back((chunk, bytes));
4434        self.buffer.metrics.record_input(1, positions);
4435        Ok(())
4436    }
4437
4438    /// Hands over the next queued chunk and releases its charge, recording output metrics; `values`
4439    /// counts the chunk's values (positions for a source, valid values for a result). A state
4440    /// chunk takes its charge with it. [`Self::take_output`] is the metric-free variant used for
4441    /// flushed window and merge output.
4442    fn pop_queued(&mut self, values: fn(&NativeChunk) -> usize) -> Result<Option<NativeChunk>> {
4443        let Some((mut chunk, bytes)) = self.queued.pop_front() else {
4444            return Ok(None);
4445        };
4446        // The consumer keeps a state chunk across polls, so its charge moves with it.
4447        let moved = match &mut chunk {
4448            NativeChunk::AggregateState(StateChunk::Series { reservation, .. }) => {
4449                debug_assert!(
4450                    reservation.is_none(),
4451                    "a handed-over state chunk was charged to a queue twice"
4452                );
4453                let transferred = self.buffer.transfer(bytes)?;
4454                let moved = transferred.size();
4455                *reservation = Some(transferred);
4456                moved
4457            }
4458            _ => 0,
4459        };
4460        let metrics = Arc::clone(&self.buffer.metrics);
4461        {
4462            let _timer = metrics.timer();
4463            self.buffer.shrink(bytes - moved)?;
4464            self.release_queued_tables()?;
4465        }
4466        metrics.record_output(1, values(&chunk));
4467        // Raw timestamps are not grid points.
4468        if let NativeChunk::Evaluated(chunk) = &chunk {
4469            metrics.record_grid_points(chunk.series.time.len());
4470        }
4471        Ok(Some(chunk))
4472    }
4473
4474    /// Maps one evaluated chunk, keeping its closing. `None` means every position was emptied and
4475    /// the chunk does not close its series.
4476    fn map(&mut self, map: &MapRuntime, chunk: EvaluatedChunk) -> Result<Option<EvaluatedChunk>> {
4477        let (positions, closing) = (chunk.series.time.len(), chunk.is_last);
4478        let workspace = map_workspace_bytes(&map.ops, &chunk.series)?;
4479        self.buffer.grow(evaluated_bytes(&chunk))?;
4480        self.buffer.grow(workspace)?;
4481        let metrics = Arc::clone(&self.buffer.metrics);
4482        let outcome = {
4483            let _timer = metrics.timer();
4484            map_chunk(&map.schema, &chunk, &map.ops, &mut |bytes| {
4485                self.buffer.grow(bytes)
4486            })
4487        };
4488        metrics.record_input(1, positions);
4489        if closing {
4490            metrics.record_completed_series(1);
4491        }
4492        // On failure give back the chunk and workspace now, not when the stopped executor drops.
4493        let output = match outcome {
4494            Ok(output) => output,
4495            Err(error) => {
4496                self.buffer.resize(0)?;
4497                return Err(error);
4498            }
4499        };
4500        if let Some(output) = &output {
4501            metrics.record_grid_points(output.series.time.len());
4502            metrics.record_output(1, valid_values(output));
4503        }
4504        self.buffer.resize(0)?;
4505        Ok(output)
4506    }
4507
4508    /// Maps one evaluated chunk with its parameters read per point. `None` means no point kept a
4509    /// value and the chunk does not close its series.
4510    fn parameterized_map(
4511        &mut self,
4512        map: &ParameterizedMapRuntime,
4513        chunk: EvaluatedChunk,
4514    ) -> Result<Option<EvaluatedChunk>> {
4515        let (positions, closing) = (chunk.series.time.len(), chunk.is_last);
4516        let workspace = built_series_workspace_bytes(&chunk.series)?;
4517        self.buffer.grow(evaluated_bytes(&chunk))?;
4518        self.buffer.grow(workspace)?;
4519        let metrics = Arc::clone(&self.buffer.metrics);
4520        let outcome = {
4521            let _timer = metrics.timer();
4522            map.apply(&chunk)
4523        };
4524        metrics.record_input(1, positions);
4525        if closing {
4526            metrics.record_completed_series(1);
4527        }
4528        let outcome = match outcome {
4529            Ok(outcome) => outcome,
4530            Err(error) => {
4531                self.buffer.resize(map.parameter_bytes)?;
4532                return Err(error);
4533            }
4534        };
4535        let output = match outcome {
4536            Some(series) => Some(EvaluatedChunk::try_new(series, closing)?),
4537            // A closing chunk is always handed over so the close reaches the consumer.
4538            None if closing => {
4539                let metric = drop_metric_name(&chunk.series.metric)?;
4540                let empty = no_row_series(&map.schema, &chunk.series, metric)?;
4541                Some(EvaluatedChunk::try_new(empty, true)?)
4542            }
4543            None => None,
4544        };
4545        if let Some(output) = &output {
4546            metrics.record_grid_points(output.series.time.len());
4547            metrics.record_output(1, valid_values(output));
4548        }
4549        self.buffer.resize(map.parameter_bytes)?;
4550        Ok(output)
4551    }
4552
4553    /// Projects evaluation timestamps from one evaluated chunk, preserving its closing.
4554    fn timestamp(
4555        &mut self,
4556        schema: &Arc<SeriesSchema>,
4557        chunk: EvaluatedChunk,
4558    ) -> Result<Option<EvaluatedChunk>> {
4559        let positions = chunk.series.time.len();
4560        let closing = chunk.is_last;
4561        // The kernel materializes the grid's timestamps.
4562        if let Some(grid) = schema.eval_grid.as_deref() {
4563            self.buffer.reserve_grid(grid)?;
4564        }
4565        let workspace = built_series_workspace_bytes(&chunk.series)?;
4566        self.buffer.grow(evaluated_bytes(&chunk))?;
4567        self.buffer.grow(workspace)?;
4568        let labels = drop_metric_name(&chunk.series.metric)?;
4569        let metrics = Arc::clone(&self.buffer.metrics);
4570        let result = {
4571            let _timer = metrics.timer();
4572            timestamp_of_evaluated(schema, &chunk.series)
4573        };
4574        metrics.record_input(1, positions);
4575        if closing {
4576            metrics.record_completed_series(1);
4577        }
4578        let result = match result {
4579            Ok(result) => result,
4580            Err(error) => {
4581                self.buffer.resize(0)?;
4582                return Err(error);
4583            }
4584        };
4585        let output = match result {
4586            Some(series) => Some(EvaluatedChunk::try_new(series, closing)?),
4587            None if closing => Some(no_row_chunk(schema, labels)?),
4588            None => None,
4589        };
4590        if let Some(output) = &output {
4591            metrics.record_grid_points(output.series.time.len());
4592            metrics.record_output(1, valid_values(output));
4593        }
4594        self.buffer.resize(0)?;
4595        Ok(output)
4596    }
4597
4598    /// Applies the broadcast to one vector chunk without retaining it; see
4599    /// [`BroadcastRuntime::apply`].
4600    fn broadcast(
4601        &mut self,
4602        broadcast: &BroadcastRuntime,
4603        chunk: NativeChunk,
4604    ) -> Result<Option<EvaluatedChunk>> {
4605        let NativeChunk::Evaluated(chunk) = chunk else {
4606            return Err(DataFusionError::Execution(
4607                "the binary node broadcasts over an evaluated vector, not raw samples".to_string(),
4608            ));
4609        };
4610        let (positions, closing) = (chunk.series.time.len(), chunk.is_last);
4611        // Literal arithmetic maps segments; everything else builds a subset of rows.
4612        let workspace = match (&broadcast.scalar, broadcast.op) {
4613            (BroadcastScalar::Literal(_), BroadcastOp::Arithmetic(_)) => {
4614                mapped_workspace_bytes(&chunk.series)?
4615            }
4616            _ => built_series_workspace_bytes(&chunk.series)?,
4617        };
4618        self.buffer.grow(evaluated_bytes(&chunk))?;
4619        self.buffer.grow(workspace)?;
4620        let metrics = Arc::clone(&self.buffer.metrics);
4621        let outcome = {
4622            let _timer = metrics.timer();
4623            broadcast.apply(&chunk)
4624        };
4625        metrics.record_input(1, positions);
4626        if closing {
4627            metrics.record_completed_series(1);
4628        }
4629        let output = match outcome {
4630            Ok(output) => output,
4631            Err(error) => {
4632                self.buffer.resize(broadcast.scalar_bytes)?;
4633                return Err(error);
4634            }
4635        };
4636        let output = match output {
4637            Some(series) => Some(EvaluatedChunk::try_new(series, closing)?),
4638            None => None,
4639        };
4640        if let Some(output) = &output {
4641            metrics.record_grid_points(output.series.time.len());
4642            metrics.record_output(1, valid_values(output));
4643        }
4644        self.buffer.resize(broadcast.scalar_bytes)?;
4645        Ok(output)
4646    }
4647
4648    /// Keeps a dynamic scalar operand's single closed chunk in `slot`, adding its bytes to `held`.
4649    fn hold_scalar(
4650        &mut self,
4651        held: &mut usize,
4652        slot: &mut Option<Series>,
4653        chunk: NativeChunk,
4654    ) -> Result<()> {
4655        let NativeChunk::Evaluated(EvaluatedChunk { series, is_last }) = chunk else {
4656            return Err(DataFusionError::Execution(
4657                "a scalar operand is an evaluated series, not raw samples".to_string(),
4658            ));
4659        };
4660        if slot.is_some() || !is_last {
4661            return Err(DataFusionError::Execution(
4662                "a scalar operand hands over exactly one closed chunk".to_string(),
4663            ));
4664        }
4665        let bytes = series_bytes(&series);
4666        self.buffer.grow(bytes)?;
4667        *held = held.saturating_add(bytes);
4668        *slot = Some(series);
4669        Ok(())
4670    }
4671
4672    /// Builds a constant's series on `grid` into `slot`, reserving it first.
4673    fn hold_constant(
4674        &mut self,
4675        held: &mut usize,
4676        slot: &mut Option<Series>,
4677        grid: Arc<EvalGrid>,
4678        value: f64,
4679    ) -> Result<()> {
4680        let bytes = grid_chunk_bytes(&grid)?;
4681        self.buffer.grow(bytes)?;
4682        *held = held.saturating_add(bytes);
4683        *slot = Some(scalar_chunk(grid, value)?.series);
4684        Ok(())
4685    }
4686
4687    /// Builds and queues the single closed chunk of a node with no input, reserving it first.
4688    fn produce(&mut self, grid: &EvalGrid, series: impl FnOnce() -> Result<Series>) -> Result<()> {
4689        let bytes = grid_chunk_bytes(grid)?;
4690        self.buffer.grow(bytes)?;
4691        let chunk = EvaluatedChunk::try_new(series()?, true)?;
4692        self.buffer.metrics.record_completed_series(1);
4693        self.queued
4694            .push_back((NativeChunk::Evaluated(chunk), bytes));
4695        Ok(())
4696    }
4697
4698    /// Feeds one chunk to this node's window. A collecting window only retains it until its input
4699    /// ends; any other window evaluates it now.
4700    fn window(
4701        &mut self,
4702        window: &mut RangeEvaluator,
4703        merge: &mut Option<MergeInput>,
4704        chunk: NativeChunk,
4705    ) -> Result<Option<EvaluatedChunk>> {
4706        self.buffer.reserve_grid(window.grid())?;
4707        if let Some(merge) = merge.as_mut() {
4708            let NativeChunk::Evaluated(chunk) = chunk else {
4709                return Err(DataFusionError::Execution(
4710                    "the window collects evaluated fragments, but it was handed raw samples"
4711                        .to_string(),
4712                ));
4713            };
4714            return self.collect(merge, window, chunk);
4715        }
4716        let (positions, closing) = (chunk.positions(), chunk.is_last());
4717        let (fields, metric) = match &chunk {
4718            NativeChunk::Raw(chunk) => (&chunk.fields, chunk.metric.as_ref()),
4719            NativeChunk::Evaluated(chunk) => (&chunk.series.fields, Some(&chunk.series.metric)),
4720            NativeChunk::AggregateState(_) => {
4721                return Err(DataFusionError::Execution(
4722                    "an aggregate state chunk reached a node that reads values or samples"
4723                        .to_string(),
4724                ));
4725            }
4726        };
4727        let workspace = match metric {
4728            Some(metric) => {
4729                window_workspace_bytes(window, last_sample_ms(&chunk)?, closing, fields, metric)?
4730            }
4731            // The evaluator refuses a raw chunk without labels before it writes a row.
4732            None => 0,
4733        };
4734        self.buffer.grow(chunk.bytes())?;
4735        self.buffer.grow(workspace)?;
4736        let metrics = Arc::clone(&self.buffer.metrics);
4737        let outcome = {
4738            let _timer = metrics.timer();
4739            match &chunk {
4740                NativeChunk::Raw(chunk) => window.push(chunk),
4741                NativeChunk::Evaluated(chunk) => window.push_series(&chunk.series, chunk.is_last),
4742                NativeChunk::AggregateState(_) => {
4743                    return Err(DataFusionError::Execution(
4744                        "an aggregate state chunk reached a node that reads values or samples"
4745                            .to_string(),
4746                    ));
4747                }
4748            }
4749        };
4750        metrics.record_input(1, positions);
4751        if closing {
4752            // Counted on input: a window that decided nothing still closed the series.
4753            metrics.record_completed_series(1);
4754        }
4755        let output = match outcome {
4756            Ok(output) => output,
4757            Err(error) => {
4758                self.buffer.resize(window.retained_bytes())?;
4759                return Err(error);
4760            }
4761        };
4762        if let Some(output) = &output {
4763            metrics.record_grid_points(output.series.time.len());
4764            metrics.record_output(1, valid_values(output));
4765        }
4766        // Settle on what the evaluator retains, not on a per-chunk sum.
4767        self.buffer.resize(window.retained_bytes())?;
4768        Ok(output)
4769    }
4770
4771    /// Retains one operand chunk, reserving it first so a refused chunk leaves the operand
4772    /// unchanged.
4773    fn retain_binary(
4774        &mut self,
4775        binary: &mut BinaryRuntime,
4776        side: usize,
4777        chunk: NativeChunk,
4778    ) -> Result<()> {
4779        let NativeChunk::Evaluated(chunk) = chunk else {
4780            return Err(DataFusionError::Execution(format!(
4781                "{} consumes evaluated chunks, not raw samples",
4782                binary.kernel.node()
4783            )));
4784        };
4785        let pending = binary.pending(side, &chunk)?;
4786        let positions = chunk.series.time.len();
4787        self.buffer.grow(pending)?;
4788        let metrics = Arc::clone(&self.buffer.metrics);
4789        {
4790            let _timer = metrics.timer();
4791            binary.retain(side, chunk)?;
4792            let retained = binary.retained_bytes();
4793            self.buffer.resize(retained)?;
4794        }
4795        metrics.record_input(1, positions);
4796        Ok(())
4797    }
4798
4799    /// Runs this node's binary kernel and queues the chunks it produced.
4800    fn compute_binary(&mut self, binary: &mut BinaryRuntime) -> Result<()> {
4801        let output = binary.compute(&mut self.buffer)?;
4802        // A kernel that already ran has moved its result into the queue, which the handover below
4803        // charges for: leaving the reservation alone here is what keeps a queued result covered.
4804        let Some(output) = output else {
4805            return Ok(());
4806        };
4807        self.queue_results(output, false, 0)
4808    }
4809
4810    /// Settles a vector node's reservation on its retained input plus its parameter values.
4811    fn settle_vector(&mut self, vector: &VectorRuntime) -> Result<()> {
4812        let held = vector.input.held.saturating_add(vector.parameter_bytes);
4813        self.buffer.resize(held)
4814    }
4815
4816    /// Retains one chunk of a vector node's input, reserving it first.
4817    fn retain_vector(&mut self, vector: &mut VectorRuntime, chunk: NativeChunk) -> Result<()> {
4818        let NativeChunk::Evaluated(chunk) = chunk else {
4819            return Err(DataFusionError::Execution(
4820                "the vector operation consumes evaluated chunks, not raw samples".to_string(),
4821            ));
4822        };
4823        validate_binary_operand(vector.schema.as_ref(), std::slice::from_ref(&chunk.series))
4824            .map_err(|error| {
4825                DataFusionError::Execution(format!(
4826                    "the vector operation rejected its input: {error}"
4827                ))
4828            })?;
4829        let pending = vector.input.pending(&chunk);
4830        let positions = chunk.series.time.len();
4831        self.buffer.grow(pending)?;
4832        let metrics = Arc::clone(&self.buffer.metrics);
4833        {
4834            let _timer = metrics.timer();
4835            vector.input.retain(chunk, Reader::Vector)?;
4836            self.settle_vector(vector)?;
4837        }
4838        metrics.record_input(1, positions);
4839        Ok(())
4840    }
4841
4842    /// Runs the histogram kernel with its per-point parameters and queues its output.
4843    fn compute_histogram(
4844        &mut self,
4845        vector: &mut VectorRuntime,
4846        parameters: &[&[Option<f64>]],
4847    ) -> Result<()> {
4848        let output = vector.compute_with_histogram_parameters(&mut self.buffer, parameters)?;
4849        if let Some(output) = output {
4850            self.queue_results(output, false, vector.parameter_bytes)?;
4851        }
4852        Ok(())
4853    }
4854
4855    fn compute_vector(&mut self, vector: &mut VectorRuntime) -> Result<()> {
4856        let shares_input = matches!(vector.op, BoundVectorOp::Sort(_));
4857        let output = vector.compute(&mut self.buffer)?;
4858        let Some(output) = output else {
4859            return Ok(());
4860        };
4861        self.queue_results(output, shares_input, vector.parameter_bytes)
4862    }
4863
4864    /// Queues a whole-input kernel's output, one closed chunk per series, and settles the
4865    /// reservation on the queue plus `beside` (e.g. parameter values). With `shares_input` (a sort
4866    /// returns its input) each series is measured by [`operand_chunk_bytes`] and its tables billed
4867    /// once.
4868    fn queue_results(
4869        &mut self,
4870        output: Vec<Series>,
4871        shares_input: bool,
4872        beside: usize,
4873    ) -> Result<()> {
4874        let mut tables = HashSet::new();
4875        let mut closed = 0usize;
4876        for series in output {
4877            let bytes = if shares_input {
4878                let (fresh, table_bytes) = unbilled_tables(&series, &tables);
4879                tables.extend(fresh);
4880                self.queued_tables = self.queued_tables.saturating_add(table_bytes);
4881                operand_chunk_bytes(&series)
4882            } else {
4883                series_bytes(&series)
4884            };
4885            let chunk = NativeChunk::Evaluated(EvaluatedChunk::try_new(series, true)?);
4886            self.queued.push_back((chunk, bytes));
4887            closed += 1;
4888        }
4889        self.buffer.metrics.record_completed_series(closed);
4890        let queued = self
4891            .queued
4892            .iter()
4893            .fold(self.queued_tables, |total, (_, bytes)| {
4894                total.saturating_add(*bytes)
4895            });
4896        self.buffer.resize(queued.saturating_add(beside))
4897    }
4898
4899    /// Folds one value or state chunk into this node's aggregate, reserving it first.
4900    fn retain_aggregate(
4901        &mut self,
4902        aggregate: &mut AggregateRuntime,
4903        chunk: NativeChunk,
4904    ) -> Result<()> {
4905        if let NativeChunk::AggregateState(chunk) = chunk {
4906            let pending = aggregate.pending_state(&chunk);
4907            let positions = match &chunk {
4908                StateChunk::Series { series, .. } => {
4909                    series.iter().map(|series| series.time.len()).sum()
4910                }
4911                StateChunk::Row(row) => row.time.len(),
4912            };
4913            self.buffer.grow(pending)?;
4914            let metrics = Arc::clone(&self.buffer.metrics);
4915            {
4916                let _timer = metrics.timer();
4917                aggregate.accumulate_state(chunk, &mut self.buffer, pending)?;
4918            }
4919            metrics.record_input(1, positions);
4920            return Ok(());
4921        }
4922        let NativeChunk::Evaluated(chunk) = chunk else {
4923            return Err(DataFusionError::Execution(
4924                "the aggregate consumes evaluated chunks, not raw samples".to_string(),
4925            ));
4926        };
4927        let pending = aggregate.pending(&chunk);
4928        let positions = chunk.series.time.len();
4929        self.buffer.grow(pending)?;
4930        let metrics = Arc::clone(&self.buffer.metrics);
4931        {
4932            let _timer = metrics.timer();
4933            aggregate.accumulate(chunk, &mut self.buffer, pending)?;
4934        }
4935        metrics.record_input(1, positions);
4936        Ok(())
4937    }
4938
4939    /// Finishes this node's fold and queues one closed chunk per group, or one state chunk for a
4940    /// `Partial`. The queue's capacity is reserved before it grows.
4941    fn compute_aggregate(&mut self, aggregate: &mut AggregateRuntime) -> Result<()> {
4942        let metrics = Arc::clone(&self.buffer.metrics);
4943        let _timer = metrics.timer();
4944        let groups = aggregate.groups();
4945        let queue_capacity = self.queued.capacity();
4946        let queue_target = self.queued.len().saturating_add(groups);
4947        let queue_growth = queue_target
4948            .saturating_sub(queue_capacity)
4949            .saturating_mul(std::mem::size_of::<(NativeChunk, usize)>());
4950        self.buffer.grow(queue_growth)?;
4951        if groups > 0 {
4952            self.queued.try_reserve_exact(groups).map_err(|error| {
4953                DataFusionError::Execution(format!(
4954                    "cannot reserve aggregate output queue: {error}"
4955                ))
4956            })?;
4957        }
4958        let queue_bytes = queue_target
4959            .max(queue_capacity)
4960            .saturating_mul(std::mem::size_of::<(NativeChunk, usize)>());
4961        let output = aggregate.compute(&mut self.buffer, queue_bytes)?;
4962        let Some(output) = output else {
4963            return Ok(());
4964        };
4965        let mut closed = 0usize;
4966        match output {
4967            AggregateOutput::Samples(series) => {
4968                for series in series {
4969                    let bytes = series_bytes(&series);
4970                    let chunk = NativeChunk::Evaluated(EvaluatedChunk::try_new(series, true)?);
4971                    self.queued.push_back((chunk, bytes));
4972                    closed += 1;
4973                }
4974            }
4975            AggregateOutput::State(chunk) => {
4976                let StateChunk::Series { series, .. } = &chunk else {
4977                    return Err(DataFusionError::Internal(
4978                        "Partial aggregate produced row state".into(),
4979                    ));
4980                };
4981                closed = series.len();
4982                let bytes = state_bytes(&chunk);
4983                self.queued
4984                    .push_back((NativeChunk::AggregateState(chunk), bytes));
4985            }
4986        }
4987        self.buffer.metrics.record_completed_series(closed);
4988        let queued_bytes = self
4989            .queued
4990            .iter()
4991            .fold(0usize, |total, (_, bytes)| total.saturating_add(*bytes));
4992        let queue_backing = self
4993            .queued
4994            .capacity()
4995            .saturating_mul(std::mem::size_of::<(NativeChunk, usize)>());
4996        self.buffer
4997            .resize(queued_bytes.saturating_add(queue_backing))
4998    }
4999
5000    /// Feeds one chunk to this node's instant selection. `None` means the series has not ended yet.
5001    fn instant(
5002        &mut self,
5003        instant: &mut InstantRuntime,
5004        chunk: NativeChunk,
5005    ) -> Result<Option<EvaluatedChunk>> {
5006        let NativeChunk::Raw(chunk) = chunk else {
5007            return Err(DataFusionError::Execution(
5008                "the instant selection consumes raw samples, not an evaluated chunk".to_string(),
5009            ));
5010        };
5011        let (positions, closing) = (chunk.time.len(), chunk.is_last);
5012        // A timestamp selection materializes the grid's timestamps.
5013        if instant.selection.value != InstantValue::Sample {
5014            self.buffer.reserve_grid(&instant.selection.output_grid)?;
5015        }
5016        self.buffer.grow(raw_bytes(&chunk))?;
5017        // The closing chunk triggers the gather; reserve its workspace up front.
5018        let scratch = if closing {
5019            instant.gather_bytes(&chunk)
5020        } else {
5021            0
5022        };
5023        self.buffer.grow(scratch)?;
5024        let metrics = Arc::clone(&self.buffer.metrics);
5025        let outcome = {
5026            let _timer = metrics.timer();
5027            instant.push(chunk)
5028        };
5029        metrics.record_input(1, positions);
5030        if closing {
5031            metrics.record_completed_series(1);
5032        }
5033        let output = match outcome {
5034            Ok(output) => output,
5035            Err(error) => {
5036                self.settle_buffered(instant)?;
5037                return Err(error);
5038            }
5039        };
5040        if let Some(output) = &output {
5041            metrics.record_grid_points(output.series.time.len());
5042            metrics.record_output(1, valid_values(output));
5043        }
5044        self.settle_buffered(instant)?;
5045        Ok(output)
5046    }
5047
5048    /// Sets this node's reservation to the chunks of the series it is still gathering.
5049    fn settle_buffered(&mut self, instant: &InstantRuntime) -> Result<()> {
5050        self.buffer.resize(instant.buffered_bytes())
5051    }
5052
5053    /// Validates and retains one fragment for a later merge.
5054    fn collect_merge(&mut self, merge: &mut MergeInput, chunk: EvaluatedChunk) -> Result<()> {
5055        let EvaluatedChunk { series, is_last } = chunk;
5056        merge.check(&series, is_last)?;
5057        let bytes = series_bytes(&series);
5058        self.buffer.grow(bytes)?;
5059        merge.bytes = merge.bytes.saturating_add(bytes);
5060        merge.fragments.push(series);
5061        self.buffer
5062            .metrics
5063            .record_input(1, merge.fragments.last().map_or(0, |s| s.time.len()));
5064        if is_last {
5065            self.buffer.metrics.record_completed_series(1);
5066        }
5067        Ok(())
5068    }
5069
5070    /// Merges all collected fragments by label set and queues the result.
5071    fn flush_canonical_merge(&mut self, merge: &mut Option<MergeInput>) -> Result<()> {
5072        let Some(merge) = merge.take() else {
5073            return Ok(());
5074        };
5075        if merge.fragments.is_empty() {
5076            return self.buffer.shrink(merge.bytes);
5077        }
5078        let workspace = merge.workspace_bytes();
5079        self.buffer.grow(workspace)?;
5080        let held = merge.bytes.saturating_add(workspace);
5081        let merged = merge_same_labelset(&merge.schema, merge.fragments)?;
5082        for series in merged {
5083            let chunk = EvaluatedChunk::try_new(series, true)?;
5084            self.buffer
5085                .metrics
5086                .record_grid_points(chunk.series.time.len());
5087            self.buffer.metrics.record_output(1, valid_values(&chunk));
5088            let bytes = series_bytes(&chunk.series);
5089            self.buffer.grow(bytes)?;
5090            self.queued
5091                .push_back((NativeChunk::Evaluated(chunk), bytes));
5092        }
5093        self.buffer.shrink(held)
5094    }
5095
5096    /// Collects one fragment of a collecting window's input; nothing is evaluated until the flush.
5097    fn collect(
5098        &mut self,
5099        merge: &mut MergeInput,
5100        window: &RangeEvaluator,
5101        chunk: EvaluatedChunk,
5102    ) -> Result<Option<EvaluatedChunk>> {
5103        self.collect_merge(merge, chunk)?;
5104        let retained = window.retained_bytes();
5105        self.buffer.resize(retained.saturating_add(merge.bytes))?;
5106        Ok(None)
5107    }
5108
5109    /// Merges this window's collected input and evaluates each merged series as one closed series.
5110    /// `merge` is taken first, so a failed merge is not retried.
5111    fn flush_merge(
5112        &mut self,
5113        window: &mut RangeEvaluator,
5114        merge: &mut Option<MergeInput>,
5115    ) -> Result<()> {
5116        let Some(merge) = merge.take() else {
5117            return Ok(());
5118        };
5119        if merge.fragments.is_empty() {
5120            return self.buffer.shrink(merge.bytes);
5121        }
5122        self.buffer.reserve_grid(window.grid())?;
5123        let workspace = merge.workspace_bytes();
5124        let held = merge.bytes.saturating_add(workspace);
5125        let schema = Arc::clone(&merge.schema);
5126        self.buffer.grow(workspace)?;
5127        // Already-queued output stays charged through every resize below.
5128        let mut queued_bytes = self
5129            .queued
5130            .iter()
5131            .fold(self.queued_tables, |total, (_, bytes)| {
5132                total.saturating_add(*bytes)
5133            });
5134        // Merged series slice the fragments' segments, so the fragments' charge covers them.
5135        let merged = merge_same_labelset(&schema, merge.fragments)?;
5136        for series in merged {
5137            let workspace = window_workspace_bytes(
5138                window,
5139                last_series_ms(&series),
5140                true,
5141                &series.fields,
5142                &series.metric,
5143            )?;
5144            self.buffer.grow(workspace)?;
5145            let output = {
5146                let metrics = Arc::clone(&self.buffer.metrics);
5147                let _timer = metrics.timer();
5148                window.push_series(&series, true)?
5149            };
5150            let Some(output) = output else {
5151                self.buffer.shrink(workspace)?;
5152                continue;
5153            };
5154            self.buffer
5155                .metrics
5156                .record_grid_points(output.series.time.len());
5157            self.buffer.metrics.record_output(1, valid_values(&output));
5158            let retained = window.retained_bytes();
5159            self.buffer
5160                .resize(retained.saturating_add(held).saturating_add(queued_bytes))?;
5161            let bytes = evaluated_bytes(&output);
5162            self.enqueue_output(output)?;
5163            queued_bytes = queued_bytes.saturating_add(bytes);
5164        }
5165        self.buffer.shrink(held)
5166    }
5167
5168    /// Queues one output computed while flushing, charged until [`Self::take_output`] hands it
5169    /// over.
5170    fn enqueue_output(&mut self, chunk: EvaluatedChunk) -> Result<()> {
5171        let bytes = evaluated_bytes(&chunk);
5172        self.buffer.grow(bytes)?;
5173        self.queued
5174            .push_back((NativeChunk::Evaluated(chunk), bytes));
5175        Ok(())
5176    }
5177
5178    /// Hands over the next queued chunk without recording metrics (the flush already did).
5179    fn take_output(&mut self) -> Result<Option<NativeChunk>> {
5180        let Some((chunk, bytes)) = self.queued.pop_front() else {
5181            return Ok(None);
5182        };
5183        self.buffer.shrink(bytes)?;
5184        self.release_queued_tables()?;
5185        Ok(Some(chunk))
5186    }
5187
5188    /// Gives back the shared tables' charge once no queued result references them.
5189    fn release_queued_tables(&mut self) -> Result<()> {
5190        if self.queued.is_empty() && self.queued_tables > 0 {
5191            self.buffer
5192                .shrink(std::mem::take(&mut self.queued_tables))?;
5193        }
5194        Ok(())
5195    }
5196}
5197
5198impl InputSlot {
5199    /// Queues one source chunk at this input, refusing a chunk of another [`LeafKind`].
5200    fn enqueue(&mut self, chunk: NativeChunk) -> Result<()> {
5201        if !self.kind.accepts(&chunk) {
5202            return Err(self.state.context(DataFusionError::Execution(format!(
5203                "the native source is bound to {}, but {} was queued at it",
5204                self.kind.describe(),
5205                chunk.describe(),
5206            ))));
5207        }
5208        // Updated only after the pool admits the chunk.
5209        let closing = chunk.is_last();
5210        self.state
5211            .enqueue(chunk)
5212            .map_err(|error| self.state.context(error))?;
5213        self.open_queued_series = !closing;
5214        Ok(())
5215    }
5216
5217    /// Hands over the next queued source chunk and updates [`Self::open_source_series`].
5218    fn pop_source(&mut self) -> Result<Option<NativeChunk>> {
5219        let Some(chunk) = self.state.pop_queued(NativeChunk::positions)? else {
5220            return Ok(None);
5221        };
5222        self.open_source_series = !chunk.is_last();
5223        if chunk.is_last() {
5224            self.state.buffer.metrics.record_completed_series(1);
5225        }
5226        Ok(Some(chunk))
5227    }
5228}
5229
5230/// Drives one execution of a bound tree: the caller pushes source chunks, pulls output, and ends
5231/// the input with [`Self::end_of_input`] or [`Self::finish`]. Streaming nodes (windows, maps,
5232/// broadcasts) answer as input arrives; collecting windows and whole-input nodes answer only after
5233/// the input ends.
5234pub struct NativeExecutor {
5235    state: NativeExecutionState,
5236    phase: Phase,
5237    /// Passed down every pull; set by `next_output` once the input has ended, the tree has gone
5238    /// quiet, and no series is left open. Until then whole-input nodes only retain.
5239    inputs_finished: bool,
5240    /// Whether the caller ended the input. After it, an empty pull advances the ending stages in
5241    /// `next_output` instead of returning `None`.
5242    ended: bool,
5243}
5244
5245/// Whether the execution can still produce chunks.
5246#[derive(Clone, Debug, PartialEq, Eq)]
5247enum Phase {
5248    Running,
5249    /// The input ended and every node closed.
5250    Finished,
5251    /// Stopped after an error; evaluators must not be reused.
5252    Failed(String),
5253}
5254
5255impl NativeExecutor {
5256    pub fn new(state: NativeExecutionState) -> Self {
5257        Self {
5258            state,
5259            phase: Phase::Running,
5260            inputs_finished: false,
5261            ended: false,
5262        }
5263    }
5264
5265    pub fn state(&self) -> &NativeExecutionState {
5266        &self.state
5267    }
5268
5269    fn live(&self) -> Result<&LiveExecution> {
5270        self.state.live.as_ref().ok_or_else(no_live_execution)
5271    }
5272
5273    fn live_mut(&mut self) -> Result<&mut LiveExecution> {
5274        self.state.live.as_mut().ok_or_else(no_live_execution)
5275    }
5276
5277    /// Queues one raw source chunk at `input`. An unknown id or a chunk kind the leaf is not bound
5278    /// to is an error and stops the execution.
5279    pub fn push_raw(&mut self, input: InputId, chunk: RawSeriesChunk) -> Result<()> {
5280        self.push_source(input, NativeChunk::Raw(chunk))
5281    }
5282
5283    /// Queues one evaluated source chunk at the input `input` names.
5284    pub fn push_evaluated(&mut self, input: InputId, chunk: EvaluatedChunk) -> Result<()> {
5285        self.push_source(input, NativeChunk::Evaluated(chunk))
5286    }
5287
5288    /// Queues one aggregate-state chunk at the input `input` names; only a state leaf accepts it.
5289    pub(crate) fn push_state(&mut self, input: InputId, chunk: StateChunk) -> Result<()> {
5290        self.push_source(input, NativeChunk::AggregateState(chunk))
5291    }
5292
5293    /// The next chunk the root produces, or `None` when nothing is ready yet (or, after the input
5294    /// ended, when the execution has finished). A chunk's `is_last` closes one input series, not
5295    /// its label set; see [`crate::native::batch`].
5296    pub fn next_chunk(&mut self) -> Result<Option<EvaluatedChunk>> {
5297        match self.next_output()? {
5298            Some(NativeChunk::Evaluated(chunk)) => Ok(Some(chunk)),
5299            Some(NativeChunk::Raw(_)) => {
5300                let error = DataFusionError::Execution(
5301                    "the native runtime produces evaluated chunks, but its root produced raw \
5302                     samples"
5303                        .to_string(),
5304                );
5305                self.stop(&error);
5306                Err(error)
5307            }
5308            Some(NativeChunk::AggregateState(_)) => {
5309                let error = DataFusionError::Execution(
5310                    "the native runtime produces evaluated chunks, but its root produced \
5311                     aggregate state"
5312                        .to_string(),
5313                );
5314                self.stop(&error);
5315                Err(error)
5316            }
5317            None => Ok(None),
5318        }
5319    }
5320
5321    /// Like [`Self::next_chunk`], for a tree whose root is a `Partial` aggregate.
5322    pub(crate) fn next_state(&mut self) -> Result<Option<StateChunk>> {
5323        match self.next_output()? {
5324            Some(NativeChunk::AggregateState(chunk)) => Ok(Some(chunk)),
5325            Some(other) => {
5326                let error = DataFusionError::Execution(format!(
5327                    "the native runtime produces aggregate state, but its root produced {}",
5328                    other.describe()
5329                ));
5330                self.stop(&error);
5331                Err(error)
5332            }
5333            None => Ok(None),
5334        }
5335    }
5336
5337    /// The next chunk the root produces, of any kind. After the input ended, an empty pull runs the
5338    /// next ending stage: the open-series check, then merge flushes, then closing the tree.
5339    fn next_output(&mut self) -> Result<Option<NativeChunk>> {
5340        self.check_running()?;
5341        loop {
5342            let inputs_finished = self.inputs_finished;
5343            match self.live_mut()?.pull(inputs_finished) {
5344                Ok(Some(chunk)) => return Ok(Some(chunk)),
5345                Ok(None) => {}
5346                Err(error) => {
5347                    self.stop(&error);
5348                    return Err(error);
5349                }
5350            }
5351            if !self.ended {
5352                return Ok(None);
5353            }
5354            if !self.inputs_finished {
5355                // Refuse a series the caller never closed before any whole-input node computes.
5356                if let Err(error) = self.live()?.unclosed() {
5357                    self.stop(&error);
5358                    return Err(error);
5359                }
5360                self.inputs_finished = true;
5361                continue;
5362            }
5363            match self.live_mut()?.flush_ready_merges() {
5364                Ok(true) => continue,
5365                Ok(false) => {}
5366                Err(error) => {
5367                    self.stop(&error);
5368                    return Err(error);
5369                }
5370            }
5371            if self.live()?.any_merge_pending() {
5372                continue;
5373            }
5374            // Closing the tree frees every reservation.
5375            let live = self.state.live.take().ok_or_else(no_live_execution)?;
5376            return match live.close() {
5377                Ok(()) => {
5378                    self.phase = Phase::Finished;
5379                    Ok(None)
5380                }
5381                Err(error) => {
5382                    self.stop(&error);
5383                    Err(error)
5384                }
5385            };
5386        }
5387    }
5388
5389    /// Ends the input; later pulls run the ending stages. Errors if called twice.
5390    pub fn end_of_input(&mut self) -> Result<()> {
5391        if self.ended {
5392            return Err(DataFusionError::Execution(
5393                "the native execution already ended its input".to_string(),
5394            ));
5395        }
5396        self.ended = true;
5397        Ok(())
5398    }
5399
5400    /// [`Self::end_of_input`] followed by pulling every remaining chunk.
5401    pub fn finish(&mut self) -> Result<Vec<EvaluatedChunk>> {
5402        self.end_of_input()?;
5403        self.drain()
5404    }
5405
5406    fn drain(&mut self) -> Result<Vec<EvaluatedChunk>> {
5407        let mut drained = Vec::new();
5408        loop {
5409            match self.next_chunk() {
5410                Ok(Some(chunk)) => drained.push(chunk),
5411                Ok(None) => return Ok(drained),
5412                Err(error) => return Err(error),
5413            }
5414        }
5415    }
5416
5417    /// Queues a source chunk at the input leaf `input` names.
5418    fn push_source(&mut self, input: InputId, chunk: NativeChunk) -> Result<()> {
5419        self.check_running()?;
5420        if self.ended {
5421            return Err(DataFusionError::Execution(
5422                "the native execution already ended its input, so no chunk can be queued at it"
5423                    .to_string(),
5424            ));
5425        }
5426        let result = self.queue_source(input, chunk);
5427        if let Err(error) = &result {
5428            self.stop(error);
5429        }
5430        result
5431    }
5432
5433    fn queue_source(&mut self, input: InputId, chunk: NativeChunk) -> Result<()> {
5434        let live = self.live_mut()?;
5435        let count = live.inputs.len();
5436        let slot = live
5437            .inputs
5438            .get_mut(input.index())
5439            .ok_or_else(|| no_input(count, input))?;
5440        slot.enqueue(chunk)
5441    }
5442
5443    /// Refuses to continue an execution that finished or stopped.
5444    fn check_running(&self) -> Result<()> {
5445        match &self.phase {
5446            Phase::Running => Ok(()),
5447            Phase::Finished => Err(DataFusionError::Execution(
5448                "the native execution already finished".to_string(),
5449            )),
5450            Phase::Failed(reason) => Err(DataFusionError::Execution(format!(
5451                "the native execution stopped after an earlier error: {reason}"
5452            ))),
5453        }
5454    }
5455
5456    /// Stops the execution for good, dropping the live tree and every reservation.
5457    fn stop(&mut self, error: &DataFusionError) {
5458        self.state.live = None;
5459        self.phase = Phase::Failed(error.to_string());
5460    }
5461}
5462
5463/// Maps one chunk with `ops`, keeping its closing. `None` means every position was emptied and
5464/// the chunk does not close its series; a closing chunk is always returned, possibly with no rows.
5465/// `admit` reserves the bytes a label rewrite writes before it runs.
5466fn map_chunk(
5467    schema: &Arc<SeriesSchema>,
5468    chunk: &EvaluatedChunk,
5469    ops: &[MapOp],
5470    admit: &mut dyn FnMut(usize) -> Result<()>,
5471) -> Result<Option<EvaluatedChunk>> {
5472    let mut series = chunk.series.clone();
5473    for (index, op) in ops.iter().enumerate() {
5474        let mapped = match op {
5475            MapOp::Label(rewrite) => {
5476                admit(rewrite.written_bytes(&series.metric))?;
5477                rewrite.apply(&mut series.metric)?;
5478                continue;
5479            }
5480            MapOp::Math(math) => map_math(schema, &series, *math)?,
5481            MapOp::Histogram(function) => map_native_histogram(*function, schema, &series)?,
5482        };
5483        if let Some(mapped) = mapped {
5484            series = mapped;
5485            continue;
5486        }
5487        if !chunk.is_last {
5488            return Ok(None);
5489        }
5490        // The empty closing chunk still carries the labels the remaining ops would produce.
5491        let mut metric = series.metric.clone();
5492        for op in &ops[index..] {
5493            match op {
5494                MapOp::Label(rewrite) => {
5495                    admit(rewrite.written_bytes(&metric))?;
5496                    rewrite.apply(&mut metric)?;
5497                }
5498                MapOp::Math(_) => metric = drop_metric_name(&metric)?,
5499                // `simpleHistogramFunc` drops only the name, not the type and unit.
5500                MapOp::Histogram(_) => metric.remove("__name__"),
5501            }
5502        }
5503        let empty = no_row_series(schema, &series, metric)?;
5504        return EvaluatedChunk::try_new(empty, true).map(Some);
5505    }
5506    EvaluatedChunk::try_new(series, chunk.is_last).map(Some)
5507}
5508
5509/// A series carrying `metric` and no rows, placed after `series`' last position.
5510fn no_row_series(schema: &SeriesSchema, series: &Series, metric: SeriesLabels) -> Result<Series> {
5511    let grid = series.time.grid().ok_or_else(|| {
5512        DataFusionError::Execution("a mapped chunk must be addressed on a grid".to_string())
5513    })?;
5514    let fields = (0..schema.fields.len())
5515        .map(|_| Samples::from_float(Float64Array::from(Vec::<f64>::new())))
5516        .collect();
5517    let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?;
5518    let at = series.time.last_position().map_or(0, |last| last + 1);
5519    let time = GridRange::try_new(Arc::clone(grid), at, 0).map_err(series_error)?;
5520    Series::try_new(schema, metric, TimeAxis::Grid(time), fields).map_err(series_error)
5521}
5522
5523/// The valid values a chunk holds: one per valid field sample.
5524fn valid_values(chunk: &EvaluatedChunk) -> usize {
5525    chunk
5526        .series
5527        .fields
5528        .iter()
5529        .map(|field| {
5530            field
5531                .iter()
5532                .filter(|sample| !matches!(sample, SampleRef::Missing))
5533                .count()
5534        })
5535        .sum()
5536}
5537
5538/// The output-values metric for a chunk: valid values, or positions for raw and state chunks.
5539fn evaluated_values(chunk: &NativeChunk) -> usize {
5540    match chunk {
5541        NativeChunk::Evaluated(chunk) => valid_values(chunk),
5542        NativeChunk::Raw(chunk) => chunk.time.len(),
5543        NativeChunk::AggregateState(StateChunk::Series { series, .. }) => {
5544            series.iter().map(|series| series.time.len()).sum()
5545        }
5546        NativeChunk::AggregateState(StateChunk::Row(row)) => row.time.len(),
5547    }
5548}
5549
5550/// The error for a chunk of another series arriving while one is being selected.
5551fn series_changed() -> DataFusionError {
5552    DataFusionError::Execution(
5553        "the instant selection combines one series into one axis, and a chunk of another series \
5554         arrived before the first one ended"
5555            .to_string(),
5556    )
5557}
5558
5559/// The error for a series an instant selection has no labels to report it under.
5560fn no_labels() -> DataFusionError {
5561    DataFusionError::Execution(
5562        "the instant selection requires materialized series labels".to_string(),
5563    )
5564}
5565
5566/// The error for a source row the selection named but the series does not hold.
5567fn missing_row(index: usize) -> DataFusionError {
5568    DataFusionError::Execution(format!(
5569        "the instant selection selected the source row {index}, which the series it read does not \
5570         hold"
5571    ))
5572}
5573
5574/// The error for an input that ended without the chunk closing its series.
5575fn truncated_input(input: InputId) -> DataFusionError {
5576    DataFusionError::Execution(format!(
5577        "the input at routing slot {} ended before the last chunk of a series: the last chunk it \
5578         handed over did not say `is_last`",
5579        input.index()
5580    ))
5581}
5582
5583/// The error for a chunk routed to an input the execution does not have.
5584fn no_input(inputs: usize, input: InputId) -> DataFusionError {
5585    DataFusionError::Execution(format!(
5586        "the native execution has {inputs} inputs, and no input {} was queued at",
5587        input.index()
5588    ))
5589}
5590
5591/// A binary operation was asked to read an operand other than its two inputs.
5592fn invalid_binary_operand() -> DataFusionError {
5593    DataFusionError::Internal("invalid binary operand index".to_string())
5594}
5595
5596fn no_live_execution() -> DataFusionError {
5597    DataFusionError::Internal("the running native execution has no state".to_string())
5598}
5599
5600/// The error for a node asked to evaluate a window without its evaluator.
5601fn no_window() -> DataFusionError {
5602    DataFusionError::Execution("the node holds no window evaluator".to_string())
5603}
5604
5605/// The error for a vector-scalar operation carrying vector-matching modifiers.
5606fn matched_scalar() -> DataFusionError {
5607    DataFusionError::NotImplemented(
5608        "the native runtime does not execute a scalar broadcast whose constant carries matching \
5609         modifiers: a constant has no labels to match, so the operation this Binary describes is \
5610         not the one it would compute"
5611            .to_string(),
5612    )
5613}
5614
5615/// The error for a binary node whose operands are neither two evaluated vectors nor a vector and a
5616/// scalar; `operands` describes what arrived.
5617fn unsupported_binary(operands: &str) -> DataFusionError {
5618    DataFusionError::NotImplemented(format!(
5619        "the native runtime does not execute this Binary node: it reads {operands}, and this \
5620         runtime reads two evaluated vectors or one evaluated vector and one constant"
5621    ))
5622}
5623
5624/// The broadcast runtime of a binary node with a scalar operand: over the vector, or for two
5625/// scalars over the varying one. A constant is read from its node's binding; a dynamic scalar
5626/// from its node's chunk.
5627fn broadcast_runtime(
5628    left: &NativeNode,
5629    right: &NativeNode,
5630    matching: &BinaryMatching,
5631) -> Result<BroadcastRuntime> {
5632    let literal = |node: &NativeNode| match &node.expr {
5633        NativeExpr::Scalar(BoundScalar { value }) => Some(*value),
5634        _ => None,
5635    };
5636    let (vector_left, sample_schema) = match (&left.output, &right.output) {
5637        (NativeType::Samples(vector), NativeType::Scalar(_)) if vector.eval_grid.is_some() => {
5638            (true, Arc::clone(vector))
5639        }
5640        (NativeType::Scalar(_), NativeType::Samples(vector)) if vector.eval_grid.is_some() => {
5641            (false, Arc::clone(vector))
5642        }
5643        (NativeType::Scalar(grid), NativeType::Scalar(_)) => {
5644            // The compiler folds two constants; an unfolded pair has no series to carry the result.
5645            if literal(left).is_some() && literal(right).is_some() {
5646                return Err(unsupported_binary(
5647                    "two constants, which broadcast over no vector",
5648                ));
5649            }
5650            (
5651                literal(left).is_none(),
5652                Arc::new(scalar_schema(Arc::clone(grid))),
5653            )
5654        }
5655        (_, _) => {
5656            return Err(unsupported_binary(
5657                "an operand that is neither evaluated samples nor a scalar, which no validated \
5658                 tree binds as a binary operand",
5659            ));
5660        }
5661    };
5662    let scalar_side = if vector_left { right } else { left };
5663    let scalar = match literal(scalar_side) {
5664        Some(value) if vector_left => BroadcastScalar::Literal(ScalarOperand::Right(value)),
5665        Some(value) => BroadcastScalar::Literal(ScalarOperand::Left(value)),
5666        None => BroadcastScalar::Dynamic {
5667            left: !vector_left,
5668            value: None,
5669        },
5670    };
5671    // A scalar has no labels; matching modifiers here would describe a different operation.
5672    if matching.labels != MatchingLabels::Ignoring(Vec::new())
5673        || matching.cardinality != Cardinality::OneToOne
5674        || matching.fill != FillValues::default()
5675    {
5676        return Err(matched_scalar());
5677    }
5678    Ok(BroadcastRuntime {
5679        scalar,
5680        vector_left,
5681        op: broadcast_op(matching)?,
5682        sample_schema,
5683        scalar_bytes: 0,
5684        annotations: None,
5685    })
5686}
5687
5688/// The operation a binary node's `matching` describes; `bool` on arithmetic is refused.
5689fn broadcast_op(matching: &BinaryMatching) -> Result<BroadcastOp> {
5690    let arithmetic = |op: ArithmeticOp| {
5691        if matching.return_bool {
5692            Err(DataFusionError::Execution(
5693                "the binary node carries `bool` on an arithmetic operator, which has no bool form"
5694                    .to_string(),
5695            ))
5696        } else {
5697            Ok(BroadcastOp::Arithmetic(op))
5698        }
5699    };
5700    let comparison = |op: ComparisonOp| {
5701        if matching.return_bool {
5702            Ok(BroadcastOp::Compare(Comparison::Bool(op)))
5703        } else {
5704            Ok(BroadcastOp::Compare(Comparison::Filter(op)))
5705        }
5706    };
5707    match matching.op.kind() {
5708        BinaryKind::Arithmetic(op) => arithmetic(op),
5709        BinaryKind::Comparison(op) => comparison(op),
5710    }
5711}
5712
5713/// The error for a reservation that overflows `usize`.
5714fn reservation_overflow(node: &str) -> DataFusionError {
5715    DataFusionError::Execution(format!(
5716        "the operands and the kernel's workspace of {node} do not fit one address space: the bytes \
5717         it would reserve overflow"
5718    ))
5719}
5720
5721fn series_error(error: datatypes::error::Error) -> DataFusionError {
5722    DataFusionError::External(Box::new(error))
5723}