Skip to main content

promql/native/
aggregate.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//! The run-time state of an aggregate node.
16//!
17//! An aggregate folds a whole vector into one series per group, so its node is the one that cannot
18//! answer as its input arrives: a group's value at a grid point is the fold of every value every
19//! member of the group has there, and the last member to arrive is the one that decides it. What the
20//! node keeps between chunks is therefore the fold's states and nothing else -- a chunk is folded as
21//! it arrives and dropped -- and it produces once, when the input ends.
22//!
23//! That is also why this runtime cannot tell an incomplete group from a complete one: it folds what
24//! it is handed. A [`AggregateStage::Complete`] aggregate is correct only if every contribution to
25//! each group lies within the streams this execution reads, which is the physical plan's job -- the
26//! caller that schedules scans and exchanges guarantees it, and a plan that ran a `Complete`
27//! aggregate once per partition and then combined the answers would be combining values that were
28//! each missing the other partitions' contributions. The stages that exist for that shape are
29//! [`AggregateStage::Partial`] and [`AggregateStage::Final`], which carry kernel accumulator
30//! state between executions.
31//!
32//! `quantile` is the one aggregate here that is not a fold of each point's values. Its answer is the
33//! φ-quantile of the group's whole sample set at that point, so there is no fixed-width accumulator
34//! that answers it, and no state that combines two partitions' quantiles into the quantile of their
35//! union. What the node keeps instead is its input: every series it was handed, until the input
36//! ends, when [`crate::aggregate::aggregate_quantile`] answers from all of it at once. That is also
37//! why `quantile` exists only as [`AggregateStage::Complete`] here, and why a plan that would have
38//! to fold it per partition has to keep the previous route instead of splitting it.
39//!
40//! There is no spill either: a `quantile` keeps the whole input of every group, at once, until the
41//! last chunk arrives, so what it holds is not bounded by the number of groups the way a fixed-width
42//! accumulator's is -- it is bounded by the pool. Each chunk is admitted before it is kept and the
43//! reservation settles on the input retained so far ([`AggregateRuntime::accumulate`]), so a
44//! statement whose groups' samples do not fit the pool is refused rather than served from disk, and
45//! a caller that needs an answer in bounded memory needs a wider pool rather than a wider node.
46//! Everything else in this runtime trades memory for the width of a point: a fold's state per group
47//! and point, this one's whole input.
48
49use std::collections::HashSet;
50use std::sync::Arc;
51
52use common_query::promql_annotations::PromqlAnnotationCollector;
53use datafusion::error::{DataFusionError, Result};
54use datatypes::series::SeriesLabels;
55use datatypes::series::samples::{FieldSpec, Series, SeriesSchema};
56use datatypes::series::time::{EvalGrid, GridRange, TimeAxis, union_positions};
57
58use crate::aggregate::{
59    AggregateOp, FloatAggregator, FloatMerger, Grouping, HistogramEvidence, HistogramSamples,
60    aggregate_quantile, histogram_samples, validate_aggregate_series,
61};
62use crate::evaluated::EvaluatedChunk;
63use crate::grid_series::{GridSeriesBuilder, series_bytes};
64use crate::map::{constant_series, validate_grid_series};
65use crate::native::execute::{
66    NodeBuffer, chunk_bytes_beside_samples, evaluated_bytes, unbilled_sample_buffers,
67    unbilled_tables,
68};
69use crate::native::plan::{
70    AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, Grouping as BoundGrouping,
71    aggregate_state_binding,
72};
73use crate::native::state::{
74    StateChunk, state_bytes, state_chunk_from_partial, state_row_from_frame_row,
75};
76
77/// The output shape produced by an aggregate stage.
78pub(crate) enum AggregateOutput {
79    Samples(Vec<Series>),
80    State(StateChunk),
81}
82
83/// What a `Complete` aggregate keeps while its input arrives.
84///
85/// The eight point-wise aggregates fold each grid point's values into fixed-width state; `quantile`
86/// keeps the samples themselves, because the φ-quantile of a group is not a value its members' values
87/// fold to.
88#[derive(Clone, Copy)]
89enum Fold {
90    /// One fixed-width accumulator per point and field.
91    Pointwise(AggregateOp),
92    /// The whole input, kept until it ends.
93    Quantile,
94}
95
96/// The input a `quantile` aggregate keeps, until it has all of it.
97///
98/// The members are the series the node was handed, in the order they arrived: that order is the order
99/// [`aggregate_quantile`] folds a group's members in, and a series delivered in several chunks
100/// contributes at each position it holds, so the pieces of one series answer what the whole series
101/// would have. Nothing here is grouped: the kernel groups, and it groups the same way for a chunk as
102/// for a series of its own.
103struct QuantileInput {
104    /// The φ the query wrote, when the query wrote it: a fold that bound its argument folds with
105    /// this one number at every point. The kernel reads it as Prometheus does, so a value outside
106    /// `[0, 1]` answers `-Infinity` or `+Infinity` rather than being refused here. `None` for a fold
107    /// whose φ is read per point, which is what `parameter` holds instead.
108    quantile: Option<f64>,
109    /// The φ read per point, when the query left it to the statement's own evaluation: the one
110    /// unlabelled scalar series the node held from its parameter child, on this node's grid.
111    ///
112    /// It is kept beside the retained input because the kernel reads it per point, exactly as the
113    /// parameter a bound φ is turned into is read: `q` with no sample at a point leaves the point
114    /// unanswered, as it does for the built one.
115    parameter: Option<Series>,
116    /// One entry per series this node was handed.
117    series: Vec<Series>,
118    /// The histogram tables the retained chunks index into, by the address of the allocation behind
119    /// their `Arc`.
120    ///
121    /// A table is one allocation however many chunks of a series index into it, so it is billed once
122    /// -- by the first chunk that references it -- exactly as a binary operand bills the tables of
123    /// the chunks it retains. That is what keeps a series delivered in a thousand chunks from costing
124    /// a thousand tables, and what keeps a table from costing nothing: the per-chunk figure leaves
125    /// its tables out ([`chunk_bytes_beside_samples`]), so a table in neither this set nor a
126    /// reservation is a table nothing covers.
127    tables: HashSet<usize>,
128    /// The Arrow allocations the retained chunks' samples live in, by the address of the allocation
129    /// behind their `Buffer`.
130    ///
131    /// The chunks of one Arrow batch are the same story as its tables one level down, and the same
132    /// answer: what a retainer keeps is the allocation its slices point into, and one allocation is
133    /// one however many chunks slice it, so it is billed once -- by the first chunk that references
134    /// it ([`unbilled_sample_buffers`]) -- rather than once per chunk. That is what keeps a series
135    /// handed over as a thousand slices of one buffer from costing that buffer a thousand times. A
136    /// chunk that holds a small slice of a large allocation is charged the allocation, because the
137    /// allocation is what stays resident; its rows would be the smaller and wrong figure.
138    buffers: HashSet<usize>,
139    /// The bytes the retained chunks hold, folded in as they arrive.
140    ///
141    /// Each chunk is measured once, by what it holds on its own ([`chunk_bytes_beside_samples`]):
142    /// its axis, its descriptors and its labels, beside the allocations it is the first to reference
143    /// -- the Arrow buffers its samples live in and the histogram tables they index into, each
144    /// billed once as [`unbilled_sample_buffers`] and [`unbilled_tables`] report them. Neither the
145    /// allocation those samples are slices of nor the struct that carries the chunk is part of the
146    /// figure: the first is billed as the allocation it is and not as the rows a chunk holds of it,
147    /// and the second is the slot the vector holds the chunk in. [`Self::bytes`] adds that vector
148    /// from the capacity it holds, which is why the struct is not counted here as well.
149    held: usize,
150}
151
152impl QuantileInput {
153    /// The bytes this input holds: the chunks it retained and the vector that carries them.
154    ///
155    /// The retained figure is [`Self::held`], which is folded in chunk by chunk, and the vector is
156    /// counted by the capacity it really holds -- the capacity `retain_quantile` reserved before it
157    /// grew -- so this is what the node has to reserve rather than a second estimate of it.
158    ///
159    /// The two do not overlap. A chunk's `Series` is carried inside one slot of that vector, so
160    /// `held` counts what the chunk holds beside the struct ([`chunk_bytes_beside_samples`]) and the
161    /// capacity here counts every slot the vector owns, occupied or not. Counting the struct in both
162    /// would charge each occupied slot twice; counting it in neither would leave every slot the
163    /// vector holds uncovered.
164    ///
165    /// The parameter is the third figure: a φ read per point is one series this node holds from the
166    /// moment its parameter child hands it over until the kernel reads it, so it is counted from
167    /// [`series_bytes`] however long it stays. A φ the query bound is not held at all - it is
168    /// rebuilt from the binding's one number when the fold answers.
169    ///
170    /// That series sits inline, in the `Option<Series>` slot of this struct, so the descriptor is
171    /// what `size_of::<Self>()` above already counts: the parameter adds the heap beside it and not
172    /// a second descriptor. [`series_bytes`] measures a series it takes by reference, so it counts
173    /// the struct as well; the subtraction here is what keeps one held series from being billed one
174    /// descriptor twice.
175    fn bytes(&self) -> usize {
176        std::mem::size_of::<Self>()
177            .saturating_add(
178                self.series
179                    .capacity()
180                    .saturating_mul(std::mem::size_of::<Series>()),
181            )
182            .saturating_add(self.parameter.as_ref().map_or(0, |parameter| {
183                series_bytes(parameter).saturating_sub(std::mem::size_of::<Series>())
184            }))
185            .saturating_add(self.held)
186    }
187}
188
189/// One aggregate node's states, from the first chunk it is handed to the series it finishes with.
190pub(crate) struct AggregateRuntime {
191    /// What the node computes, as the tree bound it: the kind it folds by and the stage it reports.
192    op: BoundAggregate,
193    /// The layout its input and output share: the fields every chunk has and the grid they are
194    /// addressed on. A `Complete` aggregate neither adds nor drops a field, and it evaluates on its
195    /// input's grid, so one schema describes both sides.
196    schema: Arc<SeriesSchema>,
197    /// What this node keeps between chunks, as the runtime's own enum, so the chunk check can ask
198    /// what the operation accepts.
199    fold: Fold,
200    /// The query's annotation collector, once the driver installed it. Only an operation that skips
201    /// histogram samples has anything to say, and it says it once.
202    annotations: Option<PromqlAnnotationCollector>,
203    /// The fold. `None` once [`Self::compute`] has taken it, which is also what says the node has
204    /// nothing left to fold into.
205    accumulator: Option<FloatAggregator>,
206    /// The whole input of a `quantile` aggregate. `None` for every other kind, and `None` once the
207    /// kernel has answered from it.
208    retained: Option<QuantileInput>,
209    merger: Option<FloatMerger>,
210    state_schema: Option<Arc<AggregateStateSchema>>,
211    /// Whether the fold has been finished and its series handed over. A node computes once: a second
212    /// pull finds the series it queued rather than a fold that ran again.
213    ///
214    /// The driver reads this to decide whether the node settled: an aggregate answers only once its
215    /// fold has run, so a child with nothing left to hand over is not an answer.
216    pub(crate) computed: bool,
217}
218
219impl AggregateRuntime {
220    /// The PromQL name of the aggregate this node folds, as an annotation names it.
221    fn aggregate_name(&self) -> &'static str {
222        match self.fold {
223            Fold::Pointwise(AggregateOp::Sum) => "sum",
224            Fold::Pointwise(AggregateOp::Count) => "count",
225            Fold::Pointwise(AggregateOp::Avg) => "avg",
226            Fold::Pointwise(AggregateOp::Min) => "min",
227            Fold::Pointwise(AggregateOp::Max) => "max",
228            Fold::Pointwise(AggregateOp::Group) => "group",
229            Fold::Pointwise(AggregateOp::Stddev) => "stddev",
230            Fold::Pointwise(AggregateOp::Stdvar) => "stdvar",
231            Fold::Quantile => "quantile",
232        }
233    }
234
235    /// Gives this node the query's collector, so it can report what it skipped.
236    pub(crate) fn set_annotations(&mut self, collector: PromqlAnnotationCollector) {
237        self.annotations = Some(collector);
238    }
239
240    /// What this node computes, for a rejection that has to say what it refused.
241    ///
242    /// It names the kind this node computes, which distinguishes it from another node in the tree.
243    fn describe(&self) -> String {
244        format!("{:?}", self.op.kind)
245    }
246
247    /// The states of a `Complete` aggregate over `schema`.
248    ///
249    /// A stage other than `Complete` and a kind without a supported kernel are refused here, before a single
250    /// chunk is folded: a node this runtime cannot compute must not start, because a partial answer
251    /// would be one the caller never asked for. The rejection names what was found, so a reader can
252    /// tell a tree this runtime cannot run from one it cannot run correctly.
253    pub(crate) fn new(
254        op: BoundAggregate,
255        schema: Arc<SeriesSchema>,
256        buffer: &mut NodeBuffer,
257    ) -> Result<Self> {
258        let kind = match op.kind {
259            AggregateKind::Sum => AggregateOp::Sum,
260            AggregateKind::Count => AggregateOp::Count,
261            AggregateKind::Avg => AggregateOp::Avg,
262            AggregateKind::Min => AggregateOp::Min,
263            AggregateKind::Max => AggregateOp::Max,
264            AggregateKind::Group => AggregateOp::Group,
265            AggregateKind::Stddev => AggregateOp::Stddev,
266            AggregateKind::Stdvar => AggregateOp::Stdvar,
267            // The one kind with no accumulator: it keeps its input instead, which is a state of its
268            // own and is built by [`Self::new_quantile`]. The φ is the only parameter an aggregate
269            // carries, and the arm that names the kind is the one place it is read.
270            AggregateKind::Quantile { quantile } => {
271                return Self::new_quantile(op, Some(quantile), schema, buffer);
272            }
273        };
274        let (state_kind, state_components) = aggregate_state_binding(op.kind, op.field_kind)
275            .ok_or_else(|| {
276                DataFusionError::NotImplemented("aggregate kind has no mergeable state".into())
277            })?;
278        let state_schema = schema.eval_grid.as_ref().map(|grid| {
279            Arc::new(AggregateStateSchema {
280                group: op.group.clone(),
281                kind: state_kind,
282                components: state_components.into(),
283                accumulators: schema.fields.clone(),
284                grid: grid.clone(),
285            })
286        });
287        if op.stage == AggregateStage::Final {
288            let merger = FloatMerger::try_new(&schema, kind)?;
289            buffer.resize(merger.state_bytes())?;
290            return Ok(Self {
291                op,
292                fold: Fold::Pointwise(kind),
293                annotations: None,
294                schema,
295                accumulator: None,
296                retained: None,
297                merger: Some(merger),
298                state_schema,
299                computed: false,
300            });
301        }
302        let name_count = match &op.group {
303            BoundGrouping::By(labels) | BoundGrouping::Without(labels) => labels.len(),
304        };
305        let name_bytes = name_count.saturating_mul(std::mem::size_of::<&str>());
306        buffer.grow(name_bytes)?;
307        let names: Vec<&str> = match &op.group {
308            BoundGrouping::By(labels) | BoundGrouping::Without(labels) => {
309                labels.iter().map(|label| label.as_ref()).collect()
310            }
311        };
312        let grouping = match &op.group {
313            BoundGrouping::By(_) => Grouping::By(&names),
314            BoundGrouping::Without(_) => Grouping::Without(&names),
315        };
316        let name_bytes = names.len().saturating_mul(std::mem::size_of::<&str>());
317        let initial = FloatAggregator::try_new_budgeted(&schema, kind, grouping, |bytes| {
318            buffer.resize(bytes.saturating_add(name_bytes))
319        })?;
320        drop(names);
321        buffer.resize(initial.state_bytes())?;
322        Ok(Self {
323            op,
324            fold: Fold::Pointwise(kind),
325            annotations: None,
326            schema,
327            accumulator: Some(initial),
328            retained: None,
329            merger: None,
330            state_schema,
331            computed: false,
332        })
333    }
334
335    /// The states of a `Complete` `quantile` aggregate over `schema`, whose φ is `quantile`.
336    ///
337    /// A `quantile` is answered from its group's whole sample set, so a stage that saw only part of
338    /// a group would answer the quantile of a subset of it: the quantile of two partitions'
339    /// quantiles is not the quantile of their union, and there is no state to export or merge
340    /// either. That is a property of the operation and not of this runtime, so what refuses a
341    /// `Partial` or a `Final` one is the tree's own check -- [`aggregate_state_binding`] has no
342    /// binding for a `quantile`, which [`crate::native::plan::NativeNode::validate`] reports, and
343    /// [`crate::native::split`] declines a `quantile` for the same reason -- and this starts the one
344    /// stage that is left.
345    ///
346    /// The same check is what puts the input on a grid: a `Complete` aggregate is validated to
347    /// answer its input's values on its input's grid, and `schema` is the layout the node reports,
348    /// so the grid the kernel reads its parameter on is there before this runs.
349    fn new_quantile(
350        op: BoundAggregate,
351        quantile: Option<f64>,
352        schema: Arc<SeriesSchema>,
353        buffer: &mut NodeBuffer,
354    ) -> Result<Self> {
355        let retained = QuantileInput {
356            quantile,
357            parameter: None,
358            series: Vec::new(),
359            tables: HashSet::new(),
360            buffers: HashSet::new(),
361            held: 0,
362        };
363        buffer.resize(retained.bytes())?;
364        Ok(Self {
365            op,
366            fold: Fold::Quantile,
367            annotations: None,
368            schema,
369            accumulator: None,
370            retained: Some(retained),
371            merger: None,
372            state_schema: None,
373            computed: false,
374        })
375    }
376
377    /// The states of a `Complete` aggregate whose one argument is read at every grid point.
378    ///
379    /// Only `quantile` has such an argument, and its fold keeps no number of its own: the φ arrives
380    /// as a series from the node's parameter child ([`Self::hold_parameter`]), so the binding's
381    /// constant is not read here at all. Everything else about the fold is the bound one's -- the
382    /// stage, the layout, and the sample set it keeps until the input ends -- which is why this is
383    /// [`Self::new_quantile`] with no constant to fall back on rather than a second kind of state.
384    pub(crate) fn new_parameterized(
385        op: BoundAggregate,
386        schema: Arc<SeriesSchema>,
387        buffer: &mut NodeBuffer,
388    ) -> Result<Self> {
389        if !matches!(op.kind, AggregateKind::Quantile { .. }) {
390            return Err(DataFusionError::NotImplemented(format!(
391                "the runtime reads a per-point argument only for `quantile`, not for {:?}",
392                op.kind
393            )));
394        }
395        Self::new_quantile(op, None, schema, buffer)
396    }
397
398    /// Keeps the φ this node reads at every grid point, in the one unlabelled scalar series its
399    /// parameter child handed over.
400    ///
401    /// The series is already reserved: it arrives through the driver's `hold_scalar`, which grows the
402    /// same reservation by [`series_bytes`] before the chunk is kept, exactly as it does for a
403    /// broadcast scalar or a `topk` parameter. Adopting it therefore only settles on what the node
404    /// holds -- which counts it once, from [`QuantileInput::bytes`] -- rather than growing for a
405    /// second allocation that was never made: a pool that holds the handoff must not refuse a
406    /// handoff that allocates nothing.
407    pub(crate) fn hold_parameter(
408        &mut self,
409        parameter: Series,
410        buffer: &mut NodeBuffer,
411    ) -> Result<()> {
412        let Some(retained) = self.retained.as_mut() else {
413            return Err(no_fold(&self.describe()));
414        };
415        if retained.parameter.is_some() {
416            return Err(DataFusionError::Execution(
417                "a `quantile` aggregate reads one parameter, and it already holds one".into(),
418            ));
419        }
420        retained.parameter = Some(parameter);
421        buffer.resize(retained.bytes())
422    }
423
424    /// What consuming `chunk` reserves while it is consumed.
425    ///
426    /// A point-wise fold drops the chunk at the end of the call and keeps only its states, so the
427    /// charge is the chunk's own bytes -- the figure [`evaluated_bytes`] reports, which is one pass
428    /// over the chunk and no state between chunks -- and not the `operand_chunk_bytes` figure a
429    /// binary operand keeps, which exists because such an operand holds a series for the whole
430    /// execution and so must count the slices of one buffer instead of the buffer once per chunk.
431    ///
432    /// A `quantile` keeps the chunk instead, and what it holds is not the chunk alone: it is the
433    /// allocations the chunk's samples live in, billed once each, beside the chunk's own descriptors
434    /// ([`Self::retain_quantile`], which is [`chunk_bytes_beside_samples`] plus
435    /// [`unbilled_sample_buffers`] plus [`unbilled_tables`]). That figure is read from the chunk by
436    /// the retainer itself, before it retains it, so nothing is held before it is reserved. Booking
437    /// the chunk again here would reserve the same backing twice -- once for the chunk being handed
438    /// over and once for the allocations it points into -- which is not a safer estimate but a
439    /// refusal of an input whose own figure the pool admits.
440    pub(crate) fn pending(&self, chunk: &EvaluatedChunk) -> usize {
441        match self.fold {
442            Fold::Pointwise(_) => evaluated_bytes(chunk),
443            Fold::Quantile => 0,
444        }
445    }
446
447    /// Folds one chunk into its group.
448    ///
449    /// A chunk that closes its series closes nothing here: a group is not a series, so the last
450    /// contribution of one member says nothing about the group. The fold keeps its states, which is
451    /// what makes a group's answer its whole group's answer once the input ends.
452    ///
453    /// A `quantile` keeps the chunk itself, for the same reason: the answer is the group's sample set,
454    /// so the samples have to survive until the input does.
455    pub(crate) fn accumulate(
456        &mut self,
457        chunk: EvaluatedChunk,
458        buffer: &mut NodeBuffer,
459        pending: usize,
460    ) -> Result<()> {
461        let Fold::Pointwise(kind) = self.fold else {
462            return self.retain_quantile(chunk, buffer);
463        };
464        // `Series` keeps its fields public, so a chunk can be built by struct literal against
465        // another schema; the states are indexed by absolute position on this node's grid, so a
466        // chunk of another field count or another grid would be folded into the wrong places.
467        validate_aggregate_series(&self.schema, &chunk.series, kind)
468            .map_err(|error| folded_chunk(&self.describe(), error))?;
469        if histogram_samples(kind) == HistogramSamples::Ignored
470            && !crate::map::is_float_series(&chunk.series)
471            && let Some(collector) = &self.annotations
472        {
473            // Prometheus reports once that it skipped samples it cannot order or average over; the
474            // fold keeps going on the float samples it can read.
475            collector.record_info(format!(
476                "{}: ignored native histogram samples",
477                self.aggregate_name()
478            ));
479            // The collector keeps the message, so the node has said its piece.
480            self.annotations = None;
481        }
482        let Some(accumulator) = self.accumulator.as_mut() else {
483            return Err(no_fold(&self.describe()));
484        };
485        // Keep the chunk covered while the fold decides whether it needs a new group or block.
486        accumulator.update_budgeted(&chunk.series, |fold_bytes| {
487            buffer.resize(pending.saturating_add(fold_bytes))
488        })?;
489        drop(chunk);
490        buffer.resize(accumulator.state_bytes())
491    }
492
493    /// Keeps one chunk of a `quantile`'s input until the input ends.
494    ///
495    /// The chunk is kept whole rather than folded: the answer is the φ-quantile of the group's sample
496    /// set, and no fixed-width state holds a sample set. What it costs is measured the way a binary
497    /// operand measures the chunks it retains, and for the same reason: what a `quantile` keeps is a
498    /// series for the rest of the execution, so the allocation one buffer its chunks are slices of is
499    /// counted once rather than once per chunk -- and counted at all when the chunk holds a small
500    /// slice of it, because the allocation is what stays resident. It is the chunk's own descriptors
501    /// ([`chunk_bytes_beside_samples`]) beside those allocations: the Arrow buffers its samples live
502    /// in, once each ([`unbilled_sample_buffers`]), and the histogram tables they index into, once
503    /// each ([`unbilled_tables`]). The figure is reserved before the push -- the push is what makes
504    /// the node hold it -- and the reservation then settles on the whole input, which is what this
505    /// node holds between chunks.
506    fn retain_quantile(&mut self, chunk: EvaluatedChunk, buffer: &mut NodeBuffer) -> Result<()> {
507        // A quantile reads float values and skips a histogram sample, so a chunk only has to fit the
508        // schema and the grid -- exactly what the kernel's own input check asks for.
509        validate_grid_series(&self.schema, &chunk.series)
510            .map_err(|error| folded_chunk(&self.describe(), error))?;
511        if !crate::map::is_float_series(&chunk.series)
512            && let Some(collector) = &self.annotations
513        {
514            // Prometheus reports once that it skipped samples it cannot order; the kernel folds the
515            // float samples it can read.
516            collector.record_info(format!(
517                "{}: ignored native histogram samples",
518                self.aggregate_name()
519            ));
520            self.annotations = None;
521        }
522        let Some(retained) = self.retained.as_mut() else {
523            return Err(no_fold(&self.describe()));
524        };
525        // What this chunk adds to what the node holds: the allocations its samples live in and the
526        // histogram tables it is the first chunk to reference -- each billed once, because one
527        // allocation is one however many chunks slice it -- plus the descriptors the chunk keeps.
528        let (buffers, buffer_bytes) = unbilled_sample_buffers(&chunk.series, &retained.buffers);
529        let (tables, table_bytes) = unbilled_tables(&chunk.series, &retained.tables);
530        let bytes = chunk_bytes_beside_samples(&chunk.series)
531            .saturating_add(buffer_bytes)
532            .saturating_add(table_bytes);
533        buffer.grow(bytes)?;
534        // The slot the chunk is about to take, and - when the vector has to grow for it - the
535        // capacity it grows to. `Vec::push` doubles, so booking one slot would let the real
536        // allocation outrun what the pool admitted; the target is booked instead, and the settle
537        // below then reads back the exact capacity the vector holds. The vector's slots are not part
538        // of `held`: [`QuantileInput::bytes`] counts them from that capacity, so booking them here
539        // and folding them there would charge them twice.
540        let needed = retained.series.len().saturating_add(1);
541        if needed > retained.series.capacity() {
542            let target = retained.series.capacity().saturating_mul(2).max(needed);
543            buffer.grow(
544                target
545                    .saturating_sub(retained.series.capacity())
546                    .saturating_mul(std::mem::size_of::<Series>()),
547            )?;
548            retained
549                .series
550                .try_reserve_exact(target.saturating_sub(retained.series.len()))
551                .map_err(|error| {
552                    DataFusionError::Execution(format!(
553                        "cannot retain the `quantile` input: {error}"
554                    ))
555                })?;
556        }
557        retained.series.push(chunk.series);
558        // From here the node keeps those tables and allocations alive itself, so a chunk arriving
559        // later that references one is charged its own descriptors and not the allocation again.
560        retained.tables.extend(tables);
561        retained.buffers.extend(buffers);
562        retained.held = retained.held.saturating_add(bytes);
563        buffer.resize(retained.bytes())
564    }
565
566    /// Merges one state chunk into this final aggregate.
567    ///
568    /// State reaches a `Final` from exactly two places and is merged here, once: a producer in this
569    /// process hands over the groups it folded ([`StateChunk::Series`]), and a region's exported
570    /// frame is decoded into the row it carries ([`StateChunk::Row`], which a merge scan reads
571    /// across processes). Both are read as the rows the merge kernel takes, so there is one merge
572    /// and not one per source; the series form is turned into those rows here, inside the kernel,
573    /// instead of by a caller that would have to know what the kernel eats.
574    pub(crate) fn accumulate_state(
575        &mut self,
576        chunk: StateChunk,
577        buffer: &mut NodeBuffer,
578        pending: usize,
579    ) -> Result<()> {
580        let expected = self.state_schema.as_ref().ok_or_else(|| {
581            DataFusionError::NotImplemented("this runtime does not merge aggregate state".into())
582        })?;
583        // The one conversion this edge performs, and it is here rather than at the API boundary: a
584        // producer hands over the groups it folded, and the kernel merges rows. Each source is
585        // validated once, where its rows are made: the series form by the row layout it is built
586        // against, a decoded row by the checks that layout makes of a group, so the merge below only
587        // merges and a group costs its own encoding.
588        let rows = match chunk {
589            StateChunk::Row(row) => {
590                if row.fields.kind() != expected.kind
591                    || row.fields.components() != expected.components.as_ref()
592                {
593                    return Err(DataFusionError::NotImplemented(
594                        "this runtime does not merge that kind of state".into(),
595                    ));
596                }
597                if row
598                    .time
599                    .grid()
600                    .is_none_or(|grid| grid.spec() != expected.grid.spec())
601                {
602                    return Err(DataFusionError::Execution(
603                        "aggregate state grid mismatch".into(),
604                    ));
605                }
606                if row.fields.len() != self.schema.fields.len() {
607                    return Err(DataFusionError::Execution(
608                        "aggregate state field count mismatch".into(),
609                    ));
610                }
611                vec![row]
612            }
613            StateChunk::Series {
614                series,
615                state_schema: _,
616                reservation: _reservation,
617            } => {
618                // The state layout and the Arrow shape a row is encoded against depend on the chunk,
619                // not on the group, so they are resolved once for all of its groups. The grid is
620                // checked here for the same reason: every row of this chunk lands on the series grid
621                // the layout encodes against, so comparing it once says what a comparison per row
622                // said before.
623                if self.schema.eval_grid.as_ref().map(|grid| grid.spec())
624                    != Some(expected.grid.spec())
625                {
626                    return Err(DataFusionError::Execution(
627                        "aggregate state grid mismatch".into(),
628                    ));
629                }
630                let declared = datatypes::series::aggregate_state::AggregateStateSchema::try_new(
631                    expected.kind,
632                    expected.components.to_vec(),
633                )
634                .map_err(|error| DataFusionError::Execution(error.to_string()))?;
635                let layout =
636                    datatypes::series::frame::StateRowLayout::try_new(&declared, &self.schema)
637                        .map_err(|error| DataFusionError::Execution(error.to_string()))?;
638                let mut rows = Vec::with_capacity(series.len());
639                for group in series {
640                    // A group a `Partial` hands over is whole: it folded the group's contribution of
641                    // its partition, and the merge above joins partitions rather than continuing a
642                    // chain.
643                    let row = layout
644                        .row(group, true)
645                        .map_err(|error| DataFusionError::Execution(error.to_string()))?;
646                    rows.push(state_row_from_frame_row(row, expected)?);
647                }
648                rows
649            }
650        };
651        let description = self.describe();
652        let merger = self.merger.as_mut().ok_or_else(|| no_fold(&description))?;
653        for row in &rows {
654            merger.merge_row(row, |bytes| buffer.resize(pending.saturating_add(bytes)))?;
655        }
656        drop(rows);
657        buffer.resize(merger.state_bytes())
658    }
659
660    /// Transient bytes required to consume a state chunk.
661    pub(crate) fn pending_state(&self, chunk: &StateChunk) -> usize {
662        match chunk {
663            StateChunk::Series { .. } => state_bytes(chunk),
664            StateChunk::Row(row) => crate::native::state::state_row_bytes(row),
665        }
666    }
667
668    /// The number of retained groups, for budgeting the output queue backing storage.
669    ///
670    /// A point-wise fold knows its groups because it keyed them. A `quantile` has not grouped
671    /// anything: the kernel does that when it answers. What it reports here is therefore the number
672    /// of members it retained, which is an upper bound -- every group has at least one member -- and
673    /// only ever sizes a reservation.
674    pub(crate) fn groups(&self) -> usize {
675        if let Some(input) = self.retained.as_ref() {
676            return input.series.len();
677        }
678        self.accumulator.as_ref().map_or(0, FloatAggregator::groups)
679    }
680
681    /// Finishes the fold and returns one series per group, or `None` if the fold already ran.
682    ///
683    /// `None` is what a node reports after it has queued its series: the caller reads them from the
684    /// queue, exactly as it reads the chunks a binary node queued, so a second pull does not finish
685    /// a fold whose states are gone.
686    pub(crate) fn compute(
687        &mut self,
688        buffer: &mut NodeBuffer,
689        queue_bytes: usize,
690    ) -> Result<Option<AggregateOutput>> {
691        if self.computed {
692            return Ok(None);
693        }
694        self.computed = true;
695        if let Some(input) = self.retained.take() {
696            let output = self.finish_quantile(input, buffer, queue_bytes)?;
697            return Ok(Some(AggregateOutput::Samples(output)));
698        }
699        if let Some(accumulator) = self.accumulator.take() {
700            return match self.op.stage {
701                AggregateStage::Complete => {
702                    // What the fold recorded about its inputs is reported here, where this node's
703                    // answer is the whole answer.
704                    let evidence = accumulator.evidence_summary();
705                    let output = accumulator.finish_budgeted(|total| {
706                        buffer.resize(total.saturating_add(queue_bytes))
707                    })?;
708                    let output_vec_bytes = output
709                        .capacity()
710                        .saturating_mul(std::mem::size_of::<Series>());
711                    charge_samples(buffer, &output, output_vec_bytes, queue_bytes)?;
712                    self.report_evidence(evidence);
713                    Ok(Some(AggregateOutput::Samples(output)))
714                }
715                AggregateStage::Partial => {
716                    let state_schema = self
717                        .state_schema
718                        .clone()
719                        .ok_or_else(|| no_fold(&self.describe()))?;
720                    // The fold builds the chunk's own representation, so handing it over costs no
721                    // second copy and no second charge: what was admitted for the groups is what
722                    // the chunk now holds.
723                    //
724                    // What the fold recorded travels in that state instead of being reported here:
725                    // one partition's evidence is a claim about a point the merge has not decided
726                    // yet, and a message cannot be taken back.
727                    let partial = accumulator
728                        .finish_partial_budgeted(|bytes| buffer.resize(bytes + queue_bytes))?;
729                    let chunk = state_chunk_from_partial(partial, state_schema, &self.op)?;
730                    Ok(Some(AggregateOutput::State(chunk)))
731                }
732                AggregateStage::Final => Err(no_fold(&self.describe())),
733            };
734        }
735        if let Some(merger) = self.merger.take() {
736            // The merge saw every partition's state, so this node is where the point's outcome is
737            // final and where its evidence is reported.
738            let evidence = merger.evidence_summary();
739            let output =
740                merger.finish_budgeted(|total| buffer.resize(total.saturating_add(queue_bytes)))?;
741            let output_vec_bytes = output
742                .capacity()
743                .saturating_mul(std::mem::size_of::<Series>());
744            charge_samples(buffer, &output, output_vec_bytes, queue_bytes)?;
745            self.report_evidence(evidence);
746            return Ok(Some(AggregateOutput::Samples(output)));
747        }
748        Err(no_fold(&self.describe()))
749    }
750
751    /// Reports what the fold or merge recorded about its inputs, once, where the answer is final.
752    ///
753    /// Only a `Complete` or a `Final` node reports: a `Partial` node hands its evidence on in the
754    /// state it exports, because a point's outcome is not decided until every partition has been
755    /// merged and a message cannot be withdrawn once it has been collected. The collector is the
756    /// node's own handle, so its children keep theirs.
757    ///
758    /// A poisoned point answers nothing, and the reconciliation its inputs needed is not reported
759    /// for it: the summary already dropped that bit, which is what makes the message set the same
760    /// whichever order the partitions arrived in.
761    fn report_evidence(&mut self, evidence: HistogramEvidence) {
762        if self.op.stage == AggregateStage::Partial {
763            return;
764        }
765        let Some(collector) = self.annotations.take() else {
766            return;
767        };
768        let name = self.aggregate_name();
769        if evidence.incompatible_layout {
770            collector.record_warning(format!(
771                "{name}: incompatible native histogram layouts, the result is removed"
772            ));
773        }
774        if evidence.custom_bounds_reconciled {
775            collector.record_info(format!("{name}: custom buckets reconciled"));
776        }
777        if evidence.counter_reset_collision {
778            collector.record_warning(format!("{name}: contradictory reset hints"));
779        }
780    }
781    /// Answers a `quantile` from the input it kept, and hands the series over.
782    ///
783    /// The kernel reads `q` per point from an unlabelled single-field scalar on the aggregate's own
784    /// grid, and a point that scalar has no value at is a point with no result. Which scalar that is
785    /// depends on what the query wrote: the φ the node held from its parameter child, or -- for a
786    /// number bound on the tree -- one built over the points the input holds, so that every point it
787    /// covers carries it. (A point the held series has no sample at is unanswered, exactly as a
788    /// missing `q` is in the kernel; `scalar(...)`, the shape that produces one per point, answers
789    /// NaN rather than no sample, so a statement whose `foo` holds nothing answers NaN there.)
790    ///
791    /// A built parameter covers the points the input holds and not the window they sit in: the
792    /// kernel reads `q` only where a member has a sample, so a sparse input's parameter is as wide
793    /// as its rows. A parameter over the envelope would instead allocate every position between two
794    /// far-apart points -- a span sized by the statement's range rather than by the data it reads,
795    /// which the pool never admitted. The parameter is booked from the bound its rows give before it
796    /// exists, and settles on its exact figure once it is built. A held parameter is not built here
797    /// and needs no such bound: it was reserved when the node adopted it, which is what
798    /// [`QuantileInput::bytes`] counts ever since.
799    ///
800    /// The reservation covers what is held while the kernel runs -- the input, that parameter, and
801    /// the kernel's workspace -- and then settles on the series the kernel answered, exactly as a
802    /// point-wise fold's finish does. The input is what stops being held when the kernel is done with
803    /// it, so it is dropped before the settle rather than when this call returns: a settle read
804    /// beside a live input would name a set that is never held, and the figure it left behind would
805    /// be the one the next node's admission had to fit into.
806    fn finish_quantile(
807        &self,
808        input: QuantileInput,
809        buffer: &mut NodeBuffer,
810        queue_bytes: usize,
811    ) -> Result<Vec<Series>> {
812        let grid = self.schema.eval_grid.clone().ok_or_else(|| {
813            DataFusionError::Execution(
814                "a `quantile` aggregate needs an evaluated grid to read its parameter on".into(),
815            )
816        })?;
817        // The points the kernel copies the parameter over. A held `φ` covers the grid the statement
818        // evaluated it on, which the input's rows say nothing about: one row of input beside a
819        // `time()` over a million grid points is a million pairs, not one. A built one covers the
820        // points the input holds, and the input's rows bound those.
821        let parameter_points = match &input.parameter {
822            Some(parameter) => parameter.time.len(),
823            None => input.series.iter().map(|series| series.time.len()).sum(),
824        };
825        let workspace = quantile_workspace_bytes(&self.schema, &input, parameter_points);
826        // A built parameter is admitted before it exists, because building it is what makes this
827        // node hold it: the bound is what a parameter over the input's points can take, and the
828        // resize below settles on what it did take. A held one is already counted by
829        // `input.bytes()`, so reserving for it again would charge the same series twice.
830        let built_bound = match (&input.parameter, input.quantile) {
831            (None, Some(_)) => quantile_parameter_bound_bytes(&input),
832            _ => 0,
833        };
834        buffer.resize(
835            input
836                .bytes()
837                .saturating_add(built_bound)
838                .saturating_add(workspace)
839                .saturating_add(queue_bytes),
840        )?;
841        // The φ the kernel reads: the series this node held from its parameter child, or -- when the
842        // query bound the number -- one built over the points the input holds.
843        let mut built = None;
844        if input.parameter.is_none() {
845            let Some(quantile) = input.quantile else {
846                return Err(DataFusionError::Internal(
847                    "a per-point `quantile` parameter was never handed over".into(),
848                ));
849            };
850            let positions = quantile_positions(&input);
851            built = Some(quantile_parameter(&grid, quantile, &positions)?);
852            // The collected positions are what the bound above covered and what this node no longer
853            // holds, so they go before the figure settles.
854            drop(positions);
855        }
856        let parameter = input
857            .parameter
858            .as_ref()
859            .or(built.as_ref())
860            .expect("a parameter is either held or built just above");
861        let held = input
862            .bytes()
863            .saturating_add(if input.parameter.is_some() {
864                0
865            } else {
866                series_bytes(parameter)
867            })
868            .saturating_add(workspace);
869        buffer.resize(held.saturating_add(queue_bytes))?;
870        let names: Vec<&str> = match &self.op.group {
871            BoundGrouping::By(labels) | BoundGrouping::Without(labels) => {
872                labels.iter().map(|label| label.as_ref()).collect()
873            }
874        };
875        let grouping = match &self.op.group {
876            BoundGrouping::By(_) => Grouping::By(&names),
877            BoundGrouping::Without(_) => Grouping::Without(&names),
878        };
879        let output = aggregate_quantile(&self.schema, &input.series, parameter, grouping)
880            .map_err(|error| folded_chunk(&self.describe(), error))?;
881        drop(names);
882        // The parameter's use ends with the kernel call, and a built one is dropped here for the
883        // same reason the input is: the settle below names what the node holds from then on. A
884        // held one goes with the input it is part of.
885        drop(built);
886        // The input is what this node held until the kernel answered, and it is given back before
887        // the reservation settles on the answer: the settle below is what the node holds from then
888        // on, so it must be read from the set that is really alive -- the answer and the queue --
889        // rather than from the answer beside an input this call only drops on its way out. The
890        // kernel's answer holds nothing of the input: the builder copies the samples it keeps.
891        drop(input);
892        let output_vec_bytes = output
893            .capacity()
894            .saturating_mul(std::mem::size_of::<Series>());
895        charge_samples(buffer, &output, output_vec_bytes, queue_bytes)?;
896        Ok(output)
897    }
898}
899
900/// The field the `quantile` parameter is bound under, which the kernel reads as its scalar.
901const QUANTILE_PARAMETER_FIELD: &str = "scalar";
902
903/// The points the retained input holds, once each, in ascending order.
904///
905/// A group's answer is decided at the points at least one of its members holds a sample at, and its
906/// members are drawn from the input, so these are every point the kernel can ask its parameter for.
907/// They are the positions the input's rows sit at -- not the window they span, which two far-apart
908/// points make as wide as the grid.
909fn quantile_positions(input: &QuantileInput) -> Vec<usize> {
910    union_positions(input.series.iter().map(|series| &series.time)).collect()
911}
912
913/// The parameter a `quantile` reads at each point: the φ the query wrote, unlabelled and single
914/// field, at `positions` and nowhere else.
915///
916/// The kernel reads `q` per point and treats a point it has no value at as a point with no result,
917/// so the parameter has to cover exactly the points that can be asked for and may omit every other
918/// one. [`GridSeriesBuilder`] is what makes that cheap: the axis keeps the runs of consecutive
919/// positions rather than a row per position, so two far-apart points cost two rows and two spans
920/// instead of every position between them.
921///
922/// An input holding no point has nothing to decide, which the kernel answers with no output: an
923/// empty scalar over the grid says the same thing and costs nothing.
924fn quantile_parameter(grid: &Arc<EvalGrid>, quantile: f64, positions: &[usize]) -> Result<Series> {
925    let schema = Arc::new(SeriesSchema {
926        fields: Arc::from([FieldSpec {
927            name: QUANTILE_PARAMETER_FIELD.into(),
928        }]),
929        eval_grid: Some(Arc::clone(grid)),
930    });
931    let metric = SeriesLabels::try_new(None, Vec::new())
932        .map_err(|error| DataFusionError::External(Box::new(error)))?;
933    let mut builder = GridSeriesBuilder::try_new(Arc::clone(&schema))?;
934    for position in positions {
935        builder.push(*position, &[Some(quantile)])?;
936    }
937    match builder.finish(metric)? {
938        Some(parameter) => Ok(parameter),
939        None => constant_series(
940            &schema,
941            GridRange::try_new(Arc::clone(grid), 0, 0)
942                .map_err(|error| DataFusionError::External(Box::new(error)))?,
943            quantile,
944        ),
945    }
946}
947
948/// The most a `quantile` parameter over `input` can cost, before it is built.
949///
950/// The parameter holds one value and one position per point it covers, and one span per run of
951/// them; a run is at least one point long, so the input's rows bound all of those. The figure is
952/// what the pool admits ahead of the allocation, and [`series_bytes`] is what it settles on once
953/// the parameter exists: what is admitted is what the parameter really takes, wherever its points
954/// sit on the grid.
955fn quantile_parameter_bound_bytes(input: &QuantileInput) -> usize {
956    let rows: usize = input.series.iter().map(|series| series.time.len()).sum();
957    let per_point = std::mem::size_of::<usize>() // its position, while the points are collected
958        .saturating_add(std::mem::size_of::<f64>()) // the value it carries
959        .saturating_add(2 * std::mem::size_of::<usize>()) // the span of a run of one point
960        .saturating_add(std::mem::size_of::<f64>()); // the array's validity slot for it
961    std::mem::size_of::<Series>()
962        .saturating_add(std::mem::size_of::<TimeAxis>())
963        .saturating_add(rows.saturating_mul(per_point))
964}
965
966/// The bytes the `quantile` kernel needs beside its retained input while it answers.
967///
968/// [`aggregate_quantile`] reports no workspace as it allocates, so this is an estimate reserved once
969/// before it runs, in the same spirit as the whole-vector kernels'. What it covers: the state it
970/// keeps per member (one position list, one heap entry and one cursor per field), its own copy of the
971/// parameter, the temporaries of one grid point (its members' values, the copy the kernel sorts, and
972/// one row of the width it folds), and the rows it builds -- the group being built and the groups it
973/// has already handed over. The row count is the input's own: a group's rows are the points at least
974/// one of its members holds a sample at, so the input's rows bound every group's rows and their sum.
975///
976/// The parameter copy is `parameter_points` pairs and not the input's rows: the kernel reads the
977/// whole parameter into one `(position, φ)` per point it covers before it folds anything, so a dense
978/// `time()` read against one row of input copies every point of the grid, and sizing that copy from
979/// the input's one row would reserve a pair for a million points. What the kernel iterates are the
980/// parameter's own positions -- the points a bound `φ` was built over and the points a held one
981/// covers -- so the caller reports that count rather than this reading the input for it.
982fn quantile_workspace_bytes(
983    schema: &SeriesSchema,
984    input: &QuantileInput,
985    parameter_points: usize,
986) -> usize {
987    let width = schema.fields.len();
988    let members = input.series.len();
989    let rows: usize = input.series.iter().map(|series| series.time.len()).sum();
990    let per_member = std::mem::size_of::<(usize, usize, usize)>()
991        .saturating_add(std::mem::size_of::<usize>())
992        .saturating_add(width.saturating_mul(4 * std::mem::size_of::<usize>()));
993    let per_point = members
994        .saturating_mul(2 * std::mem::size_of::<f64>())
995        .saturating_add(width.saturating_mul(std::mem::size_of::<Option<f64>>()));
996    // One row, charged twice: the builder holds one group at a time and the series it has already
997    // handed over are held beside it.
998    let per_row = 2 * width
999        .saturating_mul(std::mem::size_of::<f64>())
1000        .saturating_add(2 * std::mem::size_of::<usize>())
1001        .saturating_add(1);
1002    // The parameter copy, charged twice for the capacity a growing vector keeps over its length.
1003    let parameter_copy = 2 * parameter_points.saturating_mul(std::mem::size_of::<(usize, f64)>());
1004    members
1005        .saturating_mul(per_member)
1006        .saturating_add(per_point)
1007        .saturating_add(rows.saturating_mul(per_row))
1008        .saturating_add(parameter_copy)
1009        .saturating_add(members.saturating_mul(std::mem::size_of::<Series>()))
1010}
1011
1012/// Charges the series a finished aggregate hands over, plus the queue they enter.
1013///
1014/// The queue's own backing is counted by the caller that appends to it, so what is added here is
1015/// the series themselves and the vector that carries them; the two are charged together because
1016/// the vector outlives the call that built it.
1017fn charge_samples(
1018    buffer: &mut NodeBuffer,
1019    output: &[Series],
1020    output_vec_bytes: usize,
1021    queue_bytes: usize,
1022) -> Result<()> {
1023    let output_bytes = output.iter().fold(0usize, |bytes, series| {
1024        bytes.saturating_add(series_bytes(series))
1025    });
1026    buffer.resize(
1027        output_bytes
1028            .saturating_add(output_vec_bytes)
1029            .saturating_add(queue_bytes),
1030    )
1031}
1032
1033/// The rejection of a chunk that is not the layout this node folds.
1034///
1035/// The fold indexes its states by absolute grid position and by field, so a chunk of another field
1036/// count or another grid would be folded into states that mean something else. `error` is what the
1037/// series check reported, which says which of the two disagreed.
1038/// Wraps the error of a chunk this node cannot fold.
1039///
1040/// Only a chunk that does not fit the schema is the node's own refusal; anything else is the
1041/// kernel saying it does not compute this shape at all -- exporting native histogram state, for
1042/// instance -- and a caller that falls back to another planner on `NotImplemented` still can.
1043/// Wrapping that one in an `Execution` would deny it.
1044fn folded_chunk(aggregate: &str, error: DataFusionError) -> DataFusionError {
1045    match error {
1046        DataFusionError::NotImplemented(_) => error,
1047        error => DataFusionError::Execution(format!(
1048            "the `{aggregate}` aggregate folds chunks bound to its own schema, and this \
1049             one is not: {error}"
1050        )),
1051    }
1052}
1053
1054/// The error for a fold that has already been finished.
1055fn no_fold(aggregate: &str) -> DataFusionError {
1056    DataFusionError::Execution(format!(
1057        "the `{aggregate}` aggregate already finished its fold, so it takes no more input"
1058    ))
1059}
1060
1061#[cfg(test)]
1062mod tests {
1063    use std::sync::Arc;
1064
1065    use common_query::promql_annotations::PromqlAnnotationCollector;
1066    use datatypes::series::samples::{FieldSpec, SeriesSchema};
1067    use datatypes::series::time::{EvalGrid, GridSpec};
1068
1069    use super::*;
1070
1071    fn schema() -> Arc<SeriesSchema> {
1072        Arc::new(SeriesSchema {
1073            fields: vec![FieldSpec {
1074                name: Arc::from("value"),
1075            }]
1076            .into(),
1077            eval_grid: Some(Arc::new(
1078                EvalGrid::try_new(GridSpec::try_new(0, 1, 4).unwrap()).unwrap(),
1079            )),
1080        })
1081    }
1082
1083    fn runtime(stage: AggregateStage) -> AggregateRuntime {
1084        let pool: Arc<dyn datafusion::execution::memory_pool::MemoryPool> =
1085            Arc::new(datafusion::execution::memory_pool::UnboundedMemoryPool::default());
1086        let mut buffer = NodeBuffer::new(
1087            "test aggregate",
1088            Arc::new(crate::native::metrics::NodeMetrics::default()),
1089            &pool,
1090        );
1091        AggregateRuntime::new(
1092            BoundAggregate {
1093                kind: AggregateKind::Sum,
1094                group: BoundGrouping::By(Arc::new([])),
1095                stage,
1096                field_kind: crate::extension_plan::FieldKind::Histogram,
1097            },
1098            schema(),
1099            &mut buffer,
1100        )
1101        .unwrap()
1102    }
1103
1104    /// The φ this node folds is a series over `points` grid points, as `time()` or `scalar()`
1105    /// hands one over.
1106    fn parameter_series(points: usize) -> Series {
1107        let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1, 4).unwrap()).unwrap());
1108        let schema = Arc::new(SeriesSchema {
1109            fields: vec![FieldSpec {
1110                name: Arc::from("scalar"),
1111            }]
1112            .into(),
1113            eval_grid: Some(Arc::clone(&grid)),
1114        });
1115        constant_series(&schema, GridRange::try_new(grid, 0, points).unwrap(), 0.5).unwrap()
1116    }
1117
1118    /// Adopting the parameter transfers the charge it arrived with, and bills it once.
1119    ///
1120    /// The series is grown onto this node's reservation before it is handed over, because it
1121    /// outlives the child that produced it; `hold_scalar` is what does that, and it does it on this
1122    /// node's buffer. Adopting it allocates nothing, so the node settles on what it holds -- the
1123    /// series once, its descriptor counted by the state that holds it inline -- and a pool of
1124    /// exactly that figure admits the handoff. Growing for the same series again would ask for the
1125    /// double of what arrived, and a pool that holds the handoff would refuse it.
1126    #[test]
1127    fn adopting_a_parameter_charges_it_once() {
1128        let parameter = parameter_series(4);
1129        let held = series_bytes(&parameter);
1130        // What the node holds once the series arrived and was grown onto it, and what it holds with
1131        // the same series adopted: the second is the first less the descriptor the state carries
1132        // inline, because a series held in a slot costs the slot and the heap and not the slot
1133        // twice. The pool holds exactly the handoff, so an admission that asks for the series a
1134        // second time has nowhere to put it.
1135        let handoff = std::mem::size_of::<QuantileInput>() + held;
1136        let adopted = handoff - std::mem::size_of::<Series>();
1137        let pool: Arc<dyn datafusion::execution::memory_pool::MemoryPool> = Arc::new(
1138            datafusion::execution::memory_pool::GreedyMemoryPool::new(handoff),
1139        );
1140        let mut buffer = NodeBuffer::new(
1141            "test quantile",
1142            Arc::new(crate::native::metrics::NodeMetrics::default()),
1143            &pool,
1144        );
1145        let mut runtime = AggregateRuntime::new_parameterized(
1146            BoundAggregate {
1147                kind: AggregateKind::Quantile { quantile: 0.0 },
1148                group: BoundGrouping::By(Arc::new([])),
1149                stage: AggregateStage::Complete,
1150                field_kind: crate::extension_plan::FieldKind::Float,
1151            },
1152            schema(),
1153            &mut buffer,
1154        )
1155        .unwrap();
1156        // The handoff the parameter child makes: the series is reserved on this node's buffer
1157        // before it is kept, exactly as `hold_scalar` does for every scalar operand.
1158        buffer.grow(held).unwrap();
1159        runtime
1160            .hold_parameter(parameter, &mut buffer)
1161            .expect("a pool that holds the handoff refused the adoption");
1162        assert_eq!(
1163            pool.reserved(),
1164            adopted,
1165            "the adopted parameter is billed once, descriptor included"
1166        );
1167    }
1168
1169    fn collected(collector: &PromqlAnnotationCollector) -> (Vec<String>, Vec<String>) {
1170        let (mut warnings, mut infos) = (Vec::new(), Vec::new());
1171        collector.append_to(&mut warnings, &mut infos);
1172        (warnings, infos)
1173    }
1174
1175    /// Only the node that finishes the answer reports what the fold recorded, and it says each thing
1176    /// once. A `Partial` node reports nothing: one partition's evidence is a claim about a point the
1177    /// merge has not decided yet, and a message cannot be taken back.
1178    #[test]
1179    fn only_the_finishing_node_reports_histogram_evidence() {
1180        let evidence = HistogramEvidence {
1181            // The summary a poisoned point produces keeps its reconciliation bit out, so this is
1182            // what a merge hands over when a point is removed for its layout.
1183            poisoned: true,
1184            incompatible_layout: true,
1185            custom_bounds_reconciled: false,
1186            counter_reset_seen: true,
1187            not_counter_reset_seen: true,
1188            counter_reset_collision: true,
1189        };
1190        let mut partial = runtime(AggregateStage::Partial);
1191        let collector = PromqlAnnotationCollector::default();
1192        partial.set_annotations(collector.clone());
1193        partial.report_evidence(evidence);
1194        assert_eq!(
1195            collected(&collector),
1196            (Vec::new(), Vec::new()),
1197            "a partial node reports nothing"
1198        );
1199
1200        for stage in [AggregateStage::Complete, AggregateStage::Final] {
1201            let mut finishing = runtime(stage);
1202            let collector = PromqlAnnotationCollector::default();
1203            finishing.set_annotations(collector.clone());
1204            finishing.report_evidence(evidence);
1205            // A second report is not a second message: the node handed its collector on with the
1206            // first one.
1207            finishing.report_evidence(evidence);
1208            let (warnings, infos) = collected(&collector);
1209            assert!(
1210                warnings
1211                    .iter()
1212                    .any(|warning| warning.contains("incompatible native histogram layouts")),
1213                "{stage:?} reported {warnings:?}"
1214            );
1215            assert!(
1216                warnings
1217                    .iter()
1218                    .any(|warning| warning.contains("contradictory reset hints")),
1219                "{stage:?} reported {warnings:?}"
1220            );
1221            assert_eq!(warnings.len(), 2, "{stage:?} reported {warnings:?}");
1222            assert!(infos.is_empty(), "{stage:?} reported {infos:?}");
1223        }
1224    }
1225
1226    /// The two reset-hint bits are OR-ed over every point the fold saw, so between them they say
1227    /// only what the inputs reported -- two groups can each hold one of them. Whether they
1228    /// contradict is a per-point decision, which the summary carries in `counter_reset_collision`,
1229    /// and that bit is what the reporter warns about.
1230    #[test]
1231    fn a_reset_hint_held_by_one_group_each_is_not_a_collision() {
1232        let mut quiet = runtime(AggregateStage::Complete);
1233        let collector = PromqlAnnotationCollector::default();
1234        quiet.set_annotations(collector.clone());
1235        quiet.report_evidence(HistogramEvidence {
1236            counter_reset_seen: true,
1237            not_counter_reset_seen: true,
1238            ..HistogramEvidence::default()
1239        });
1240        assert_eq!(
1241            collected(&collector),
1242            (Vec::new(), Vec::new()),
1243            "two points that each saw one hint contradict nothing"
1244        );
1245
1246        // One point that saw both is the collision, and it is what the message is for.
1247        let mut colliding = runtime(AggregateStage::Complete);
1248        let collector = PromqlAnnotationCollector::default();
1249        colliding.set_annotations(collector.clone());
1250        colliding.report_evidence(HistogramEvidence {
1251            counter_reset_collision: true,
1252            ..HistogramEvidence::default()
1253        });
1254        let (warnings, infos) = collected(&collector);
1255        assert_eq!(warnings.len(), 1, "{warnings:?}");
1256        assert!(
1257            warnings[0].contains("contradictory reset hints"),
1258            "{warnings:?}"
1259        );
1260        assert!(infos.is_empty(), "{infos:?}");
1261    }
1262
1263    /// A reconciled point that answered reports its reconciliation as information, once.
1264    #[test]
1265    fn a_live_point_reports_its_reconciliation() {
1266        let mut runtime = runtime(AggregateStage::Complete);
1267        let collector = PromqlAnnotationCollector::default();
1268        runtime.set_annotations(collector.clone());
1269        runtime.report_evidence(HistogramEvidence {
1270            custom_bounds_reconciled: true,
1271            ..HistogramEvidence::default()
1272        });
1273        let (warnings, infos) = collected(&collector);
1274        assert!(warnings.is_empty(), "{warnings:?}");
1275        assert_eq!(infos.len(), 1, "{infos:?}");
1276        assert!(infos[0].contains("custom buckets reconciled"), "{infos:?}");
1277    }
1278}