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