Skip to main content

promql/native/
plan.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 bound tree a native PromQL evaluation compiles to.
16//!
17//! A query is compiled into [`NativeTree`]: [`NativeNode`]s whose operations are already bound to
18//! kernels, fields and grids. Nothing in this module interprets a function name, resolves a label
19//! or picks a column at run time; those decisions are made before the tree exists, so the hot
20//! path only feeds batches to kernels it was handed.
21//!
22//! The tree is also the unit of legality. [`NativeNode::validate`] checks the contract every
23//! operation states about its input, which is what lets a new combination of supported operations
24//! be an ordinary tree instead of another hand-written shape.
25//!
26//! What the tree cannot express yet is deliberate for this stage: [`NativeExpr::Scalar`] holds a
27//! constant, so `time()` and `scalar(v)` have no node. The legality below is therefore about the
28//! operations that exist, not about PromQL's whole surface.
29
30use std::hash::Hash;
31use std::sync::Arc;
32
33use datafusion::arrow::datatypes::DataType;
34use datafusion::error::{DataFusionError, Result};
35use datatypes::series::aggregate_state::{AggregateStateKind, StateComponent};
36use datatypes::series::samples::{FieldSpec, SeriesSchema};
37use datatypes::series::time::EvalGrid;
38use datatypes::series::{SeriesLabels, SeriesOrdering};
39
40use common_query::native_histogram::native_histogram_arrow_type;
41
42use crate::extension_plan::FieldKind;
43use crate::histogram_eval::{HistogramFunction, NativeHistogramFunction};
44use crate::info::InfoSelector;
45use crate::map::MathOp;
46use crate::map_label::LabelRewrite;
47use crate::map_time::DateFunction;
48use crate::range_eval::{RangeFunction, RangeWindow, fold_offset, predict_linear_instants};
49use crate::select::SortOrder;
50use crate::vector_match::{
51    BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp,
52};
53
54/// The bucket-bound label a classic histogram's series carry, which the histogram function folds and
55/// its result does not report.
56const LE_LABEL: &str = "le";
57
58/// The label a metric name is stored under, which a scan binds beside its tag columns rather than
59/// among them.
60pub(crate) const METRIC_NAME: &str = "__name__";
61
62/// Metadata labels the runtime removes from histogram result label sets.
63const PROMQL_METADATA_LABELS: [&str; 3] = ["__name__", "__type__", "__unit__"];
64
65/// A conservative set of reportable label names for `node`.
66///
67/// `source_tags` is indexed by each leaf's `source_index`. The canonical pass supplies runtime
68/// label names, including `__name__` for named scans; the planner supplies declared tag columns
69/// to derive output columns. The result need not describe the labels of any individual series:
70/// `or` includes a nullable `__name__` column even when both operands drop their names. Math
71/// operations remove only `__name__` here, while their runtime also removes `__type__` and
72/// `__unit__`.
73///
74/// They follow Prometheus' result labels: a one-to-one match keeps the left side's labels, narrowed
75/// by `on` or `ignoring`; `and` and `unless` keep the left side's series and `or` adds the right
76/// side's; `info` adds the data labels of the info table; an operation with a scalar or a function
77/// of each value keeps its operand's; a scalar and `vector(s)` have none; `count_values` keeps its
78/// grouping and the label it writes; a fill that answers a missing many-side sample files the one
79/// side's matching labels, so they join the set, while a grouped `include` label joins them only when
80/// the one side carries it or the matching keeps it in the key a fill reads. A label rewrite writes
81/// its destination, and a destination that names the metric name writes that name.
82///
83/// A node that reports a value of its own drops the name where its kernel does - `timestamp`, a
84/// range function whose result is computed (`rate`, `increase`, ...), a math or histogram map,
85/// `histogram_quantile`, every non-filtering binary - so a name rewrite below one of them cannot
86/// make the name reappear above it.
87///
88/// `None` for a node whose labels this walk does not derive - a `count_values` whose destination is
89/// empty, or an input whose source has no entry. `None` proves nothing: the canonical pass treats
90/// it as "may alias" rather than as "distinct", and the planner keeps the statement off the native
91/// route.
92pub fn fused_output_tags(node: &NativeNode, source_tags: &[Vec<String>]) -> Option<Vec<String>> {
93    match &node.expr {
94        NativeExpr::Input(input) => source_tags.get(input.source_index).cloned(),
95        NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } | NativeExpr::VectorOf { .. } => {
96            Some(Vec::new())
97        }
98        // These report a value of their own rather than the sample they read, and the runtime drops
99        // the name for each of them. `source_tags` is the authority on what an input carries, so a
100        // discovery input arrives carrying `__name__` and these arms are what decides it does not
101        // survive.
102        NativeExpr::Instant { input, op } => {
103            let tags = fused_output_tags(input, source_tags)?;
104            Some(match op.value {
105                InstantValue::Timestamp => without_metadata_labels(tags),
106                InstantValue::Sample | InstantValue::InfoTimestamp => tags,
107            })
108        }
109        NativeExpr::Window { input, op } => {
110            let tags = fused_output_tags(input, source_tags)?;
111            Some(if op.function.drops_metric_name() {
112                without_metadata_labels(tags)
113            } else {
114                tags
115            })
116        }
117        NativeExpr::Timestamp { input } => Some(without_metadata_labels(fused_output_tags(
118            input,
119            source_tags,
120        )?)),
121        // A label rewrite changes the label set itself: `label_replace` adds its destination label
122        // and an empty replacement removes it, so the input's labels are not the output's. A math or
123        // histogram kernel drops the metric name where it runs, and the ops apply in written order,
124        // so what follows a rewrite sees the set the rewrite left.
125        NativeExpr::Map { input, op } => {
126            let mut tags = fused_output_tags(input, source_tags)?;
127            for operation in op.ops.iter() {
128                match operation {
129                    MapOp::Label(rewrite) => {
130                        let destination = rewrite.destination();
131                        if tags.iter().any(|tag| tag == destination) {
132                            // The input carries the label, so the rewrite changes its value - and an
133                            // empty replacement may remove it, which the column still represents.
134                            tags.retain(|tag| tag != destination);
135                            tags.push(destination.to_string());
136                        } else if rewrite.writes_value() {
137                            // A fresh destination is a label the output only carries when the
138                            // rewrite can write a value; a delete-only rewrite of a label no input
139                            // carried publishes nothing.
140                            tags.push(destination.to_string());
141                        }
142                    }
143                    MapOp::Math(_) | MapOp::Histogram(_) => tags = without_metadata_labels(tags),
144                }
145            }
146            Some(tags)
147        }
148        // Its parameters are scalars, which carry no labels; the map computes a value of its own
149        // with the input, and its kernel drops the metric name.
150        NativeExpr::ParameterizedMap { input, .. } => Some(without_metadata_labels(
151            fused_output_tags(input, source_tags)?,
152        )),
153        // `scalar()` reports one value and no labels, like the scalar it produces.
154        NativeExpr::ScalarOf { .. } => Some(Vec::new()),
155        // Its parameter is a scalar, which carries no labels, and ranking keeps each selected
156        // series' own labels.
157        NativeExpr::ParameterizedTopK { input, .. } => fused_output_tags(input, source_tags),
158        // A parameterized histogram function folds the bucket series that share the other labels
159        // into one series and drops `le` along with the metadata labels, exactly as its bound
160        // counterpart does. Its parameters are scalars and carry no labels.
161        NativeExpr::ParameterizedHistogram { input, .. } => {
162            let mut tags = fused_output_tags(input, source_tags)?;
163            tags.retain(|tag| tag != LE_LABEL && !PROMQL_METADATA_LABELS.contains(&tag.as_str()));
164            Some(tags)
165        }
166        // An aggregate reports the grouping labels its input carries: `by(...)` keeps exactly the
167        // ones it names, and `without(...)` keeps the rest and drops the metric name, as Prometheus
168        // does. A grouping by `__name__` keeps the name where the input reports one - which is
169        // `source_tags`'s answer, not the schema's: a named input declares it when the statement
170        // reads more than one, so the groups two metrics form stay apart, and a statement reading
171        // one leaves the column to the rows layout's appended name, which is what `sum by
172        // (__name__)` over one metric reports.
173        NativeExpr::Aggregate { input, op } => grouped_output_tags(input, op, source_tags),
174        // Its parameter is a scalar, which carries no labels, so a fold that reads it per point
175        // reports the same columns as the one that binds its `φ`.
176        NativeExpr::ParameterizedAggregate { input, op, .. } => {
177            grouped_output_tags(input, op, source_tags)
178        }
179        // Selecting some of the input's series keeps each one's own labels, and `count_values`
180        // keeps its grouping's; `histogram` folds bucket series into one histogram, so it does not
181        // report the input's set.
182        NativeExpr::Vector { input, op } => match op {
183            BoundVectorOp::TopK { .. }
184            | BoundVectorOp::LimitK { .. }
185            | BoundVectorOp::LimitRatio { .. }
186            | BoundVectorOp::Sort(_) => fused_output_tags(input, source_tags),
187            // `absent` reports the labels its own matchers name, not the input's set and not the
188            // table's columns: it answers one series carrying exactly those, so a label the input
189            // does not carry is still a label of the result.
190            BoundVectorOp::Absent { labels } => Some(
191                labels
192                    .tags()
193                    .iter()
194                    .map(|label| label.name.to_string())
195                    .collect(),
196            ),
197            // `count_values` writes the value it counts into its own label and then keeps its
198            // grouping: `by(...)` keeps the labels named plus that destination, `without(...)`
199            // keeps the rest minus the labels named and the metric name. What the node reports is
200            // therefore the grouping applied to the labels its input carries, with the destination
201            // among them - not the input's set, and not the scan's, since the grouping narrows both.
202            //
203            // The destination is a label the node creates, so a rewrite of it above this node is a
204            // rewrite of an existing label. A destination naming the metric name writes the name
205            // the node groups by, which is the one label its result carries. This walk derives the
206            // labels; it does not decide which groupings the kernel accepts, and those refusals stay
207            // where they are.
208            BoundVectorOp::CountValues { label, group } if !label.is_empty() => {
209                let mut tags = fused_output_tags(input, source_tags)?;
210                if !tags.contains(&label.to_string()) {
211                    tags.push(label.to_string());
212                }
213                Some(match group {
214                    Grouping::By(names) => {
215                        let mut output = tags
216                            .into_iter()
217                            .filter(|tag| names.iter().any(|name| name.as_ref() == tag))
218                            .collect::<Vec<_>>();
219                        // `by` keeps the label the node writes whether the input carried it or not.
220                        if !output.contains(&label.to_string()) {
221                            output.push(label.to_string());
222                        }
223                        output
224                    }
225                    Grouping::Without(names) => tags
226                        .into_iter()
227                        .filter(|tag| {
228                            tag != METRIC_NAME && !names.iter().any(|name| name.as_ref() == tag)
229                        })
230                        .collect(),
231                })
232            }
233            BoundVectorOp::CountValues { .. } => None,
234            // A classic histogram function folds the bucket series that share the other labels into
235            // one series and drops `le`, along with the metadata labels the runtime does not put on
236            // its result. What it keeps is everything else its input carried.
237            BoundVectorOp::Histogram(_) => {
238                let mut tags = fused_output_tags(input, source_tags)?;
239                tags.retain(|tag| {
240                    tag != LE_LABEL && !PROMQL_METADATA_LABELS.contains(&tag.as_str())
241                });
242                Some(tags)
243            }
244        },
245        NativeExpr::Merge { input } => fused_output_tags(input, source_tags),
246        NativeExpr::Binary {
247            left,
248            right,
249            matching,
250        } => {
251            let keeps_name = keeps_metric_name(matching);
252            let scalar_side = matches!(&left.output, NativeType::Scalar(_))
253                || matches!(&right.output, NativeType::Scalar(_));
254            let tags = match (&left.output, &right.output) {
255                (NativeType::Scalar(_), _) => fused_output_tags(right, source_tags)?,
256                (_, NativeType::Scalar(_)) => fused_output_tags(left, source_tags)?,
257                _ => {
258                    let kept = |tags: Vec<String>| -> Vec<String> {
259                        match &matching.labels {
260                            MatchingLabels::On(names) => tags
261                                .into_iter()
262                                .filter(|tag| {
263                                    names.iter().any(|name| name.as_ref() == tag.as_str())
264                                })
265                                .collect(),
266                            MatchingLabels::Ignoring(names) => tags
267                                .into_iter()
268                                .filter(|tag| {
269                                    !names.iter().any(|name| name.as_ref() == tag.as_str())
270                                })
271                                .collect(),
272                        }
273                    };
274                    let left_tags = fused_output_tags(left, source_tags)?;
275                    let right_tags = fused_output_tags(right, source_tags)?;
276                    // One-to-one matching narrows the left side's labels with `on`/`ignoring`.
277                    // A group retains the many side's labels and copies the named labels from the one
278                    // side: `group_left(container)` keeps the left labels and adds `container` from
279                    // the right.
280                    let mut tags = match &matching.cardinality {
281                        Cardinality::OneToOne => kept(left_tags.clone()),
282                        Cardinality::ManyToOne(_) => left_tags.clone(),
283                        Cardinality::OneToMany(_) => right_tags.clone(),
284                    };
285                    // `result_metric` drops the metadata labels before it matches or copies an
286                    // included label, so an arithmetic result starts without the name. An include can
287                    // still put it back from the one side, which is why the final rule below does not
288                    // run on this branch.
289                    if !keeps_name {
290                        tags.retain(|tag| tag != METRIC_NAME);
291                    }
292                    let (includes, include_tags): (&[Arc<str>], &Vec<String>) =
293                        match &matching.cardinality {
294                            Cardinality::OneToOne => (&[], &left_tags),
295                            Cardinality::ManyToOne(labels) => (labels, &right_tags),
296                            Cardinality::OneToMany(labels) => (labels, &left_tags),
297                        };
298                    for tag in include_tags {
299                        if includes.iter().any(|label| label.as_ref() == tag.as_str())
300                            && !tags.contains(tag)
301                        {
302                            tags.push(tag.clone());
303                        }
304                    }
305                    // A grouped result carries an include label only when a row can give it one.
306                    // `result_metric` removes the label from the many side's labels unless the one side
307                    // has it, so a paired row and a row filed from a one-side series take it from the
308                    // one series, which is what the loop above declares. A row filed from a many-side
309                    // series takes it from that series' match key instead, so it carries the label only
310                    // when the matching keeps the label in the key. Everything else the many side
311                    // carries is the base above, so a label neither of those can provide has to leave
312                    // the set: nothing would ever fill its column.
313                    if !includes.is_empty() {
314                        let many_rows_filled = match &matching.cardinality {
315                            // `group_right` puts the one side on the left, so the fills trade places:
316                            // `fill_left` is the one that answers a missing one-side sample there.
317                            Cardinality::OneToMany(_) => matching.fill.lhs,
318                            Cardinality::ManyToOne(_) | Cardinality::OneToOne => matching.fill.rhs,
319                        }
320                        .is_some();
321                        let in_match_key = |label: &str| match &matching.labels {
322                            MatchingLabels::On(names) => {
323                                names.iter().any(|name| name.as_ref() == label)
324                            }
325                            // A match key is built from a series' tags, which never hold the metric name.
326                            MatchingLabels::Ignoring(names) => {
327                                label != "__name__"
328                                    && !names.iter().any(|name| name.as_ref() == label)
329                            }
330                        };
331                        tags.retain(|tag| {
332                            !includes.iter().any(|label| label.as_ref() == tag.as_str())
333                                || include_tags.contains(tag)
334                                || (many_rows_filled && in_match_key(tag))
335                        });
336                    }
337                    // A fill answers a missing sample from the series of the other side, and the kernel
338                    // files that row at the label set the series it has gives it
339                    // (`vector_match::binary_field`): a many-side series keeps all of its labels, which
340                    // `tags` already holds, while a one-side series keeps only its matching labels plus
341                    // the group labels the modifier names, which the loop above adds. So what a fill can
342                    // add here is the one side's matching labels, and only a fill that can file a
343                    // one-side row has any to add: one where the many side is the missing side. Which
344                    // fill that is follows the kernel, which trades the two for `group_right`, whose one
345                    // side is the left - there it is `fill_right` that leaves the many side missing.
346                    let (one_tags, fills_many_side) = match &matching.cardinality {
347                        Cardinality::OneToMany(_) => (&left_tags, matching.fill.rhs),
348                        Cardinality::ManyToOne(_) | Cardinality::OneToOne => {
349                            (&right_tags, matching.fill.lhs)
350                        }
351                    };
352                    // A filled row keeps only the one side's matching labels, so the name can reach
353                    // it only through an `on` key that names the metric name, and only while the
354                    // operation reports its samples' names.
355                    let fill_carries_name = keeps_name
356                        && matches!(&matching.labels, MatchingLabels::On(names)
357                            if names.iter().any(|name| name.as_ref() == METRIC_NAME));
358                    if fills_many_side.is_some() {
359                        for tag in kept(one_tags.clone()) {
360                            if tag == METRIC_NAME && !fill_carries_name {
361                                continue;
362                            }
363                            if !tags.contains(&tag) {
364                                tags.push(tag);
365                            }
366                        }
367                    }
368                    tags
369                }
370            };
371            Some(if scalar_side && !keeps_name {
372                without_metadata_labels(tags)
373            } else {
374                tags
375            })
376        }
377        NativeExpr::Set { left, right, op } => {
378            let mut tags = fused_output_tags(left, source_tags)?;
379            if op.op == SetOp::Or {
380                for tag in fused_output_tags(right, source_tags)? {
381                    if !tags.contains(&tag) {
382                        tags.push(tag);
383                    }
384                }
385                // `or` reports the series of both sides, and each row keeps the name of the side it
386                // came from, so the name is a label of the result even when neither source declares
387                // it as a tag column. A side whose kernel dropped the name leaves the column empty.
388                if !tags.iter().any(|tag| tag == METRIC_NAME) {
389                    tags.push(METRIC_NAME.to_string());
390                }
391            }
392            Some(tags)
393        }
394        // A base series keeps its labels and takes the data labels of its info series: the ones the
395        // selector names, or all of them when it names none.
396        NativeExpr::Info {
397            base,
398            info,
399            selector,
400        } => {
401            let mut tags = fused_output_tags(base, source_tags)?;
402            for tag in fused_output_tags(info, source_tags)? {
403                let copied = selector.data_labels.is_empty()
404                    || selector
405                        .data_labels
406                        .iter()
407                        .any(|label| label.as_ref() == tag.as_str());
408                if copied && !tags.contains(&tag) {
409                    tags.push(tag);
410                }
411            }
412            Some(tags)
413        }
414    }
415}
416
417/// The labels an aggregate reports: the ones its grouping keeps among those its input carries.
418///
419/// `by(...)` keeps exactly the labels it names, and `without(...)` keeps the rest and drops the
420/// metric name, as Prometheus does. A grouping by `__name__` keeps the name where the input reports
421/// one; a named scan only reports it among the runtime labels, so the aggregate keeps it there and
422/// publishes no column for it, which is what `sum by (__name__)` over one metric reports.
423///
424/// Both the fold that binds its argument and the one that reads it per point answer this way: what
425/// decides the columns is the grouping, not where the aggregate's one argument comes from.
426fn grouped_output_tags(
427    input: &NativeNode,
428    op: &BoundAggregate,
429    source_tags: &[Vec<String>],
430) -> Option<Vec<String>> {
431    let input_tags = fused_output_tags(input, source_tags)?;
432    Some(match &op.group {
433        Grouping::By(kept) => input_tags
434            .into_iter()
435            .filter(|tag| kept.iter().any(|name| name.as_ref() == tag.as_str()))
436            .collect(),
437        Grouping::Without(dropped) => input_tags
438            .into_iter()
439            .filter(|tag| {
440                tag != METRIC_NAME && !dropped.iter().any(|name| name.as_ref() == tag.as_str())
441            })
442            .collect(),
443    })
444}
445
446/// Whether a binary operation reports the samples of the side it keeps, name included.
447///
448/// A filtering comparison reports those samples, so the name survives it. Every other binary
449/// operation computes new values, and `bool` reports the comparison's own outcome rather than
450/// either operand's samples, so both drop the name.
451fn keeps_metric_name(matching: &BinaryMatching) -> bool {
452    matching.op.is_comparison() && !matching.return_bool
453}
454
455/// The labels a node reports after the metadata labels are dropped, which is what a kernel that
456/// computes a value of its own does to the samples it reports.
457///
458/// The runtime drops all of [`PROMQL_METADATA_LABELS`] here, not the name alone: a name-dropping
459/// window and `timestamp` both go through `drop_metric_name`, and both end with
460/// `remove_all(&METADATA_LABELS)` - an empty value leaves with them too. Deriving only the name
461/// would leave `__type__` and `__unit__` in a label set the runtime no longer reports them in, and
462/// a drop above such a node would then be collected for labels that are already gone.
463fn without_metadata_labels(tags: Vec<String>) -> Vec<String> {
464    tags.into_iter()
465        .filter(|tag| !PROMQL_METADATA_LABELS.contains(&tag.as_str()))
466        .collect()
467}
468
469/// What one node produces.
470///
471/// A sample type with an evaluation grid is an evaluated series: one value per grid point. Without
472/// a grid it is raw samples carrying their own timestamps. A scalar is one value per grid point
473/// and no labels. Intermediate aggregate state is a different type altogether, so an operation
474/// that cannot consume it is rejected by type rather than by convention.
475#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
476pub enum NativeType {
477    /// Samples, evaluated when the schema carries a grid and raw otherwise.
478    Samples(Arc<SeriesSchema>),
479    /// One value per grid point and no labels, which binary operations broadcast.
480    ///
481    /// PromQL scalars vary with the evaluation time (`time()`, `scalar(v)`), so this carries the
482    /// grid it is evaluated on. Its value carrier is a series without labels, but its type is
483    /// what keeps a broadcast from becoming label matching.
484    Scalar(Arc<EvalGrid>),
485    /// Intermediate aggregate state, not a query value.
486    AggregateState(Arc<AggregateStateSchema>),
487}
488
489impl NativeType {
490    /// The schema of a sample type, or `None` for a scalar or aggregate state.
491    pub fn samples(&self) -> Option<&Arc<SeriesSchema>> {
492        match self {
493            Self::Samples(schema) => Some(schema),
494            Self::Scalar(_) | Self::AggregateState(_) => None,
495        }
496    }
497
498    /// The grid this type is evaluated on, or `None` when it holds raw samples or state.
499    ///
500    /// A scalar is evaluated on its grid like a vector, which is what lets a binary operation
501    /// line it up with a vector point by point; only raw samples and state have no positions.
502    pub fn grid(&self) -> Option<&Arc<EvalGrid>> {
503        match self {
504            Self::Samples(schema) => schema.eval_grid.as_ref(),
505            Self::Scalar(grid) => Some(grid),
506            Self::AggregateState(_) => None,
507        }
508    }
509
510    /// What this type is, for a rejection that has to say what a consumer was handed.
511    fn describe(&self) -> &'static str {
512        match self {
513            Self::Samples(schema) if schema.eval_grid.is_some() => "an evaluated vector",
514            Self::Samples(_) => "raw samples",
515            Self::Scalar(_) => "a scalar",
516            Self::AggregateState(_) => "aggregate state",
517        }
518    }
519
520    /// Whether `self` binds the same thing as `other`: the same samples or the same state.
521    ///
522    /// Bindings compare their semantic content, not process-local allocation identity. Scalars are
523    /// produced by a node and never handed to one by a source, so they never match.
524    fn same_binding(&self, other: &NativeType) -> bool {
525        match (self, other) {
526            (Self::Samples(mine), Self::Samples(theirs)) => **mine == **theirs,
527            (Self::AggregateState(mine), Self::AggregateState(theirs)) => **mine == **theirs,
528            _ => false,
529        }
530    }
531}
532
533/// The [`FieldKind`] every referenced field of a scan carries, or `None` when they disagree or one
534/// is a type this route does not answer.
535///
536/// The route declares one output column per field, so a statement whose selectors carry different
537/// kinds has no column to declare them in and keeps the existing plan. `Float64` and the canonical
538/// native histogram struct are the two kinds this route answers.
539pub fn uniform_field_kind<'a>(
540    kinds: impl IntoIterator<Item = Option<&'a DataType>>,
541) -> Option<FieldKind> {
542    let mut answer = None;
543    for kind in kinds {
544        let this = match kind? {
545            DataType::Float64 => FieldKind::Float,
546            data_type if data_type == &native_histogram_arrow_type() => FieldKind::Histogram,
547            _ => return None,
548        };
549        match answer {
550            None => answer = Some(this),
551            Some(seen) if seen == this => {}
552            Some(_) => return None,
553        }
554    }
555    answer
556}
557
558/// The output kind of a binary operation over two evaluated vectors, including fill pairs.
559pub fn binary_output_field_kind(
560    left: FieldKind,
561    right: FieldKind,
562    op: BinaryOp,
563    return_bool: bool,
564    fill: FillValues,
565) -> Option<FieldKind> {
566    if return_bool {
567        return Some(FieldKind::Float);
568    }
569    match op {
570        BinaryOp::Add
571        | BinaryOp::Sub
572        | BinaryOp::Mul
573        | BinaryOp::Div
574        | BinaryOp::Mod
575        | BinaryOp::Pow
576        | BinaryOp::Atan2 => {
577            // An unsupported pair emits no sample, not a float. Fill values are floats, so one
578            // field can be produced by the real pair and by either enabled synthetic pair.
579            let payload_kind = |left, right| match (left, op, right) {
580                (FieldKind::Float, _, FieldKind::Float) => Some(FieldKind::Float),
581                (FieldKind::Histogram, BinaryOp::Add | BinaryOp::Sub, FieldKind::Histogram)
582                | (FieldKind::Histogram, BinaryOp::Mul | BinaryOp::Div, FieldKind::Float)
583                | (FieldKind::Float, BinaryOp::Mul, FieldKind::Histogram) => {
584                    Some(FieldKind::Histogram)
585                }
586                _ => None,
587            };
588            let candidates = [
589                payload_kind(left, right),
590                fill.rhs.and_then(|_| payload_kind(left, FieldKind::Float)),
591                fill.lhs.and_then(|_| payload_kind(FieldKind::Float, right)),
592            ];
593            let mut kind = None;
594            for candidate in candidates.into_iter().flatten() {
595                if kind.is_some_and(|existing| existing != candidate) {
596                    return None;
597                }
598                kind = Some(candidate);
599            }
600            // With no possible samples, retain the legacy float layout for an empty result.
601            Some(kind.unwrap_or(FieldKind::Float))
602        }
603        // A comparison over one kind answers that kind's samples, which is what keeps a histogram
604        // column a histogram. A comparison over two kinds answers no sample at all: the kernel
605        // reports every mixed pair - `(Float, Histogram)` and `(Histogram, Float)` included - as
606        // unsupported and skips it without counting a match (`vector_match::elem_binop`), so the
607        // column is the same empty float layout arithmetic keeps for a pair that can emit nothing.
608        _ if left == right => Some(left),
609        _ => Some(FieldKind::Float),
610    }
611}
612
613impl NativeNode {
614    /// The kind this node's output field carries, given the kind its sources carry.
615    ///
616    /// `None` means this walk cannot name it: either the caller has no kind for the statement's
617    /// sources and this tree reads one, or the shape's samples are ones the model does not describe.
618    /// Both keep the existing plan rather than declaring a column the first batch might not fill.
619    pub fn output_field_kind(&self, input: Option<FieldKind>) -> Option<FieldKind> {
620        let kind_of = |node: &NativeNode| node.output_field_kind(input);
621        match &self.expr {
622            NativeExpr::Input(_) => input,
623            // A tree that reads no source answers floats: a constant, the evaluation time, `vector()`
624            // over one of them, and a date function of the evaluation time. None of them carries a
625            // sample kind of its own, so none of them needs the source kind either.
626            NativeExpr::Scalar(_)
627            | NativeExpr::EvalTime { .. }
628            | NativeExpr::VectorOf { .. }
629            | NativeExpr::Timestamp { .. } => Some(FieldKind::Float),
630            // The window functions that answer with a histogram are the ones the range kernel says
631            // yield one; every other range function reduces its window to a float.
632            NativeExpr::Window { input, op } => {
633                let inner = kind_of(input)?;
634                (!op.function.yields_histograms())
635                    .then_some(FieldKind::Float)
636                    .or(Some(inner))
637            }
638            // An instant selection reads one sample of the field, so it keeps the kind; the two
639            // timestamp forms replace the sample with a float of its own time.
640            NativeExpr::Instant { input, op } => match op.value {
641                InstantValue::Sample => kind_of(input),
642                InstantValue::Timestamp | InstantValue::InfoTimestamp => Some(FieldKind::Float),
643            },
644            // `histogram_count` and the other native-histogram readers answer with one float per
645            // sample; the map kernels that keep the samples keep their kind as well.
646            NativeExpr::Map { input, op } => {
647                let mut kind = kind_of(input)?;
648                for op in op.ops.iter() {
649                    kind = match op {
650                        // The native-histogram readers answer one float per sample.
651                        MapOp::Histogram(_) => FieldKind::Float,
652                        // A label rewrite writes labels only, so the samples it passes on are the
653                        // ones it was given, kind included.
654                        MapOp::Label(_) => kind,
655                        // No math function keeps a histogram, so a histogram reaching one is a
656                        // shape this walk does not name rather than a silent float.
657                        MapOp::Math(_) if kind == FieldKind::Histogram => return None,
658                        MapOp::Math(_) => FieldKind::Float,
659                    };
660                }
661                Some(kind)
662            }
663            // A constant beside a vector is broadcast over it, so the operation answers with the
664            // vector's own samples: a histogram times a float is still a histogram. Two vectors
665            // use the arithmetic result's kind, including any samples emitted by fill, and an
666            // empty float field only when no possible pairing can emit a sample.
667            NativeExpr::Binary {
668                left,
669                right,
670                matching,
671            } => {
672                // `bool` makes a comparison answer 1 or 0 whatever its operands hold, which is
673                // what the kernel does before it looks at the kinds.
674                if matching.return_bool {
675                    return Some(FieldKind::Float);
676                }
677                match (&left.expr, &right.expr) {
678                    (NativeExpr::Scalar(_), NativeExpr::Scalar(_)) => Some(FieldKind::Float),
679                    (NativeExpr::Scalar(_), _) => kind_of(right),
680                    (_, NativeExpr::Scalar(_)) => kind_of(left),
681                    (_, _) => {
682                        let left_kind = kind_of(left)?;
683                        let right_kind = kind_of(right)?;
684                        binary_output_field_kind(
685                            left_kind,
686                            right_kind,
687                            matching.op,
688                            false,
689                            matching.fill,
690                        )
691                    }
692                }
693            }
694            // A canonical merge collects pieces of one label set: it assembles the samples it was
695            // given and never converts them, so the field keeps the kind it had.
696            NativeExpr::Merge { input } => kind_of(input),
697            // A set operation keeps the payloads it selects - `and` and `unless` keep the left
698            // samples, `or` keeps the left's and the right's unmatched ones - so a pair of
699            // different kinds would answer a field carrying both. This route declares one type per
700            // field, so it names the answer only when both sides agree. That is this planner's
701            // condition for a uniformly typed column, not a rule Prometheus states.
702            NativeExpr::Set { left, right, .. } => {
703                let left_kind = kind_of(left)?;
704                (left_kind == kind_of(right)?).then_some(left_kind)
705            }
706            // `scalar()` answers one float per grid point, whatever its input holds.
707            NativeExpr::ScalarOf { .. } => Some(FieldKind::Float),
708            // A ranking hands on the series it selected, so the field keeps the kind it read; its
709            // parameter is a scalar, which carries no samples of its own.
710            NativeExpr::ParameterizedTopK { input, .. } => kind_of(input),
711            // `histogram_quantile` and `histogram_fraction` reduce a histogram to one float per
712            // sample whatever their arguments are, constant or per point.
713            NativeExpr::ParameterizedHistogram { .. } => Some(FieldKind::Float),
714            // An aggregate answers the kind its own state carries: `count`/`group` answer a count
715            // or a `1` whatever the samples they counted, `min`/`max`/`stddev`/`stdvar`/`quantile`
716            // fold the float samples and skip the histogram ones, and `sum`/`avg` answer the
717            // payload they folded - a native histogram when their binding is a histogram state, a
718            // float otherwise. Naming it here is what lets `sum(count_over_time(h[5m]))` - a float
719            // built from histograms - declare a float column, and `sum(h)` declare a histogram one.
720            NativeExpr::Aggregate { op, .. } => Some(aggregate_output_kind(op)),
721            // A per-point parameter decides the `φ` the fold reads, not the layout it answers, so
722            // the kind is the one the same aggregate's state carries.
723            NativeExpr::ParameterizedAggregate { op, .. } => Some(aggregate_output_kind(op)),
724            // A whole-vector operation either hands on the series it selected - a ranking keeps the
725            // ones it ranked, `limit_ratio` the ones its hash kept, and `sort` the same series in
726            // another order - so the field keeps the kind it read, which is the rule the
727            // per-point `k` form above already states for the same `TopK`. The other three compute
728            // the value: `absent` writes `1.0` where the input held nothing, `histogram_quantile`
729            // and `histogram_fraction` reduce a classic histogram to one float, and `count_values`
730            // counts samples as floats.
731            NativeExpr::Vector { input, op } => Some(match op {
732                BoundVectorOp::TopK { .. }
733                | BoundVectorOp::LimitK { .. }
734                | BoundVectorOp::LimitRatio { .. }
735                | BoundVectorOp::Sort(_) => kind_of(input)?,
736                BoundVectorOp::Absent { .. }
737                | BoundVectorOp::Histogram(_)
738                | BoundVectorOp::CountValues { .. } => FieldKind::Float,
739            }),
740            // `info` answers the base series' own samples with the info series' data labels added,
741            // so the field is the base's field: natively it never reads the info series' values as
742            // the answer (`info` is selected as a timestamp, `InstantValue::InfoTimestamp`).
743            NativeExpr::Info { base, .. } => kind_of(base),
744            // A parameterized map is a math function over its input - `round` and the three
745            // `clamp`s - and math skips native histogram samples rather than converting them
746            // (`map::map_math`), so the field shape is unchanged and keeps the input's kind. The
747            // two scalar functions, `max_of` and `min_of`, take a scalar input, whose kind is a
748            // float whether or not the source carries histograms.
749            NativeExpr::ParameterizedMap { input, .. } => kind_of(input),
750        }
751    }
752}
753
754/// The kind an aggregate's own output column carries.
755///
756/// It follows the state the aggregate keeps rather than the samples it read, because the two can
757/// differ in both directions: `count` over a histogram answers a float, and so does every aggregate
758/// that skips histogram samples, while `sum`/`avg` over a histogram answer the histogram they folded.
759pub fn aggregate_output_kind(op: &BoundAggregate) -> FieldKind {
760    match aggregate_state_binding(op.kind, op.field_kind) {
761        Some((kind, _)) if kind.is_histogram() => FieldKind::Histogram,
762        _ => FieldKind::Float,
763    }
764}
765
766/// The layout of intermediate aggregate state.
767///
768/// State is indexed by `(group labels, absolute grid index)`, so it carries the grid it was
769/// accumulated on. It is not a query value and does not pretend to be one.
770#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
771pub struct AggregateStateSchema {
772    /// How the groups its rows are indexed by are identified.
773    pub group: Grouping,
774    /// Aggregate whose partial accumulator this state carries.
775    pub kind: AggregateStateKind,
776    /// Ordered accumulator components, shared with the kernel layout.
777    pub components: Arc<[StateComponent]>,
778    /// The accumulator columns, one per aggregated field.
779    pub accumulators: Arc<[FieldSpec]>,
780    /// The grid the state is indexed on.
781    pub grid: Arc<EvalGrid>,
782}
783
784/// Returns the state type implied by an aggregate over an input of `field_kind`, if that state can
785/// be merged across a partition boundary.
786///
787/// Two families share this table. A numeric input keeps the components the accumulator kernel
788/// declares, and the component list comes from that kernel rather than a second mapping, so changing
789/// a kernel's state fields changes the native binding in lockstep. A native-histogram input binds
790/// the histogram state of the same aggregate: it carries the payload and the compensation that
791/// belongs to it, plus the evidence a merge of two partitions has to report. A quantile has no
792/// partial kernel at all, whatever it reads.
793pub fn aggregate_state_binding(
794    kind: AggregateKind,
795    field_kind: FieldKind,
796) -> Option<(AggregateStateKind, Vec<StateComponent>)> {
797    if field_kind == FieldKind::Histogram {
798        let state_kind = match kind {
799            AggregateKind::Sum => AggregateStateKind::HistogramSum,
800            AggregateKind::Avg => AggregateStateKind::HistogramAvg,
801            // Every other aggregate folds a float answer out of the samples it reads - a count is a
802            // count whatever it counted, and the extreme and deviation kinds skip a histogram
803            // sample - so a histogram input keeps their numeric state.
804            _ => return float_state_binding(kind),
805        };
806        // The layout is the kind's own canonical list, which is the list its frame accepts.
807        return Some((state_kind, state_kind.components().to_vec()));
808    }
809    float_state_binding(kind)
810}
811
812/// The numeric state one aggregate keeps, from the components its kernel declares.
813fn float_state_binding(kind: AggregateKind) -> Option<(AggregateStateKind, Vec<StateComponent>)> {
814    use crate::aggregate::{AggregateOp, StateField};
815
816    let (state_kind, op) = match kind {
817        AggregateKind::Sum => (AggregateStateKind::Sum, AggregateOp::Sum),
818        AggregateKind::Count => (AggregateStateKind::Count, AggregateOp::Count),
819        AggregateKind::Avg => (AggregateStateKind::Avg, AggregateOp::Avg),
820        AggregateKind::Min => (AggregateStateKind::Min, AggregateOp::Min),
821        AggregateKind::Max => (AggregateStateKind::Max, AggregateOp::Max),
822        AggregateKind::Group => (AggregateStateKind::Group, AggregateOp::Group),
823        AggregateKind::Stddev => (AggregateStateKind::Stddev, AggregateOp::Stddev),
824        AggregateKind::Stdvar => (AggregateStateKind::Stdvar, AggregateOp::Stdvar),
825        AggregateKind::Quantile { .. } => return None,
826    };
827    let components = op
828        .state_fields()
829        .iter()
830        .map(|field| match field {
831            StateField::Value => StateComponent::Value,
832            StateField::Mean => StateComponent::Mean,
833            StateField::Compensation => StateComponent::Compensation,
834            StateField::Count => StateComponent::Count,
835            StateField::IncrementalMean => StateComponent::IncrementalMean,
836        })
837        .collect();
838    Some((state_kind, components))
839}
840
841/// A scan or exchange boundary bound as a node input.
842///
843/// The binding records what the input was created for: the output a consumer type-checks against,
844/// and the ordering it guarantees. An instant selection and a window both read the ordering,
845/// rejecting an interleaved input; no other consumer reads it yet.
846#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
847pub struct BoundInput {
848    /// Child index in the DataFusion plan. The compiler initially assigns selector-occurrence
849    /// indices; the caller maps them to child indices when constructing the plan.
850    ///
851    /// Multiple logical inputs may reference the same child after plan collapse. This is not a
852    /// runtime `InputId` or an identity for an input leaf.
853    pub source_index: usize,
854    /// What the input produces: raw samples from a scan, or state from an exchange boundary.
855    pub output: NativeType,
856    /// The ordering the input guarantees.
857    pub ordering: SeriesOrdering,
858}
859
860/// A constant scalar bound for broadcast or a statement root.
861///
862/// A scalar that varies per grid point is the same [`NativeType::Scalar`] as this constant: what
863/// keeps a binary operation from label-matching it is its type, not its constness. The varying
864/// ones are [`NativeExpr::EvalTime`] and a binary operation between scalars.
865#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
866pub struct BoundScalar {
867    /// The constant value.
868    pub value: f64,
869}
870
871/// An instant selection: the last sample at or before each grid point, within a lookback.
872#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
873pub struct BoundInstant {
874    /// How far back a sample may lie before it counts as stale.
875    pub lookback_ms: i64,
876    /// Selector offset; positive reads earlier samples.
877    pub offset_ms: i64,
878    /// Anchored selection instant; samples are selected at this time for every grid point.
879    pub at_ms: Option<i64>,
880    /// What the selection reports for the sample it selects.
881    pub value: InstantValue,
882    /// The grid the selection produces values on.
883    pub output_grid: Arc<EvalGrid>,
884}
885
886/// What an instant selection reports at a grid point for the sample it selected there.
887#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
888pub enum InstantValue {
889    /// The sample itself.
890    Sample,
891    /// `timestamp(x)`: the sample's own time in seconds, without the metric name.
892    Timestamp,
893    /// The info series `info()` reads: the sample's own time in milliseconds, under all of its
894    /// labels, as Prometheus' `evalSeries` records it for `info`.
895    InfoTimestamp,
896}
897
898/// A window function over raw samples or over an evaluated input.
899///
900/// The input and output grids are bound separately: a subquery evaluates its inner expression on
901/// its own grid and consumes the result directly, without resampling it onto the outer grid.
902#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
903pub struct BoundWindow {
904    /// The function this node runs.
905    pub function: RangeFunction,
906    /// The window length, offset and anchor.
907    pub window: RangeWindow,
908    /// The grid the input is evaluated on, or `None` when the input is raw samples.
909    pub input_grid: Option<Arc<EvalGrid>>,
910    /// The grid this node produces values on.
911    pub output_grid: Arc<EvalGrid>,
912}
913
914/// A chain of point-wise operations applied to a whole evaluated value.
915#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
916pub struct BoundMap {
917    /// The operations, applied in order.
918    pub ops: Arc<[MapOp]>,
919}
920
921/// A math function whose scalar parameters are bound as nodes, because at least one of them varies
922/// per grid point; Prometheus reads each parameter at every step. With constant parameters the same
923/// function is a [`MathOp`] in a [`BoundMap`].
924///
925/// Every function here reads one parameter per point except `max_of` and `min_of`, which are
926/// functions of two scalars: their input is the one scalar the call wrote first and their one
927/// parameter is the other. [`Self::takes_a_scalar_input`] says which shape a function has, so the
928/// node's input and output are checked against the function it carries rather than against a
929/// convention the functions no longer all share.
930#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
931pub enum ParameterizedOp {
932    /// `round(v, to_nearest)`.
933    Round,
934    /// `clamp(v, min, max)`.
935    Clamp,
936    /// `clamp_min(v, min)`.
937    ClampMin,
938    /// `clamp_max(v, max)`.
939    ClampMax,
940    /// `max_of(a, b)`: the larger of two scalars.
941    MaxOf,
942    /// `min_of(a, b)`: the smaller of two scalars.
943    MinOf,
944}
945
946impl ParameterizedOp {
947    /// How many parameters the function reads after its input.
948    pub fn arity(self) -> usize {
949        match self {
950            Self::Clamp => 2,
951            Self::Round | Self::ClampMin | Self::ClampMax | Self::MaxOf | Self::MinOf => 1,
952        }
953    }
954
955    /// Whether the function's input is a scalar, which is what a function of two scalars has.
956    ///
957    /// A parameterized map otherwise maps a vector's fields onto the same fields; `max_of` and
958    /// `min_of` answer one scalar from one, so their input carries a scalar's single unlabelled
959    /// field and their answer is a scalar on that field's grid.
960    pub fn takes_a_scalar_input(self) -> bool {
961        matches!(self, Self::MaxOf | Self::MinOf)
962    }
963}
964
965/// One operation of a map, applied to each series on its own: math over its float values, a
966/// function of its native histograms, or a change of its labels. Each can give two series one label
967/// set, which is why all live in a map.
968#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
969pub enum MapOp {
970    Math(MathOp),
971    Histogram(NativeHistogramFunction),
972    Label(Arc<LabelRewrite>),
973}
974
975/// Which aggregate a node computes.
976///
977/// Every kind here folds a group's values into one value per grid point. The aggregates that
978/// instead select some of the input's series (`topk`, `bottomk`, `limitk`, `limit_ratio`) or write
979/// one output label per distinct value (`count_values`) are a different shape and have no variant,
980/// so a node cannot claim to compute one of them.
981///
982/// A kind may be bound before its kernel exists: whether the tree can run is
983/// [`NativeTree::try_new`]'s and the runtime's question, not this enum's.
984///
985/// `Eq` is missing because [`AggregateKind::Quantile`] carries an `f64`, as
986/// [`RangeFunction::QuantileOverTime`] does.
987///
988/// [`RangeFunction::QuantileOverTime`]: crate::range_eval::RangeFunction::QuantileOverTime
989#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
990pub enum AggregateKind {
991    /// `sum`: the total of each group's values at each grid point.
992    Sum,
993    /// `avg`: the mean of each group's values at each grid point.
994    Avg,
995    /// `count`: how many values each group has at each grid point.
996    Count,
997    /// `min`: the smallest of each group's values at each grid point.
998    Min,
999    /// `max`: the largest of each group's values at each grid point.
1000    Max,
1001    /// `group`: `1` where a group has any value at a grid point.
1002    Group,
1003    /// `stddev`: the standard deviation of each group's values at each grid point.
1004    Stddev,
1005    /// `stdvar`: the variance of each group's values at each grid point.
1006    Stdvar,
1007    /// `quantile`: the φ-quantile of each group's values at each grid point, as written.
1008    Quantile {
1009        /// The φ the query wrote, which `0` to `1` does not bound: Prometheus reads a negative φ as
1010        /// `-Infinity` and one above `1` as `+Infinity`.
1011        quantile: f64,
1012    },
1013}
1014
1015/// Where an aggregate sits in the execution, which decides whether its output is a query value.
1016#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
1017pub enum AggregateStage {
1018    /// Every contribution to each group lies within this execution, so the output is complete.
1019    Complete,
1020    /// Only this execution's contributions were seen, so the output is state for a later merge.
1021    Partial,
1022    /// The state was collected from every contributing execution, so the output is complete.
1023    Final,
1024}
1025
1026/// How an aggregate's groups are identified, in the binding's own terms.
1027///
1028/// The kernel already takes both shapes ([`aggregate::Grouping`]), and the two are not
1029/// interchangeable: `by(job)` keeps `job` and drops everything else, while `without(job)` keeps
1030/// every other label and drops `job` too. A list of group labels can only spell the first, so a
1031/// `without` written that way would group a query by labels it meant to remove.
1032///
1033/// [`aggregate::Grouping`]: crate::aggregate::Grouping
1034#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
1035pub enum Grouping {
1036    /// The labels a group is identified by; every other label is dropped.
1037    By(Arc<[Arc<str>]>),
1038    /// The labels a group is not identified by; these are dropped, and so is `__name__`.
1039    Without(Arc<[Arc<str>]>),
1040}
1041
1042/// An aggregate bound to its kind, grouping and stage.
1043#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
1044pub struct BoundAggregate {
1045    /// Which aggregate to compute.
1046    pub kind: AggregateKind,
1047    /// How its groups are identified.
1048    pub group: Grouping,
1049    /// Where this aggregate sits in the execution.
1050    pub stage: AggregateStage,
1051    /// The kind the aggregate's direct input answers with, decided where this node was bound.
1052    ///
1053    /// It is what its state carries: a `sum` or `avg` over native histograms keeps histogram state,
1054    /// while the same aggregate over floats keeps numeric components. It is decided from the input's
1055    /// own output kind rather than from the source, because an operator between the two can change
1056    /// it -- `sum(count_over_time(h[5m]))` aggregates a float built from histograms.
1057    pub field_kind: FieldKind,
1058}
1059
1060/// An operator over the whole input vector at each grid point: one that keeps some of the input's
1061/// samples with their series' labels and values, orders the series, reports where none is present,
1062/// reads a classic histogram from its bucket series, or counts the samples sharing a value.
1063///
1064/// Its constants are bound here, as a window's are: a `k` or a ratio only known at run time has no
1065/// field.
1066#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
1067pub enum BoundVectorOp {
1068    /// `topk` (`top`) or `bottomk`: the `k` largest or smallest values of each group.
1069    TopK { k: f64, top: bool, group: Grouping },
1070    /// `limitk`: the first `k` series of each group that hold a sample, in input order.
1071    LimitK { k: f64, group: Grouping },
1072    /// `limit_ratio`: the series whose label hash falls in the ratio; it keeps whole series, so it
1073    /// has no grouping.
1074    LimitRatio { ratio: f64 },
1075    /// `sort`, `sort_desc`, `sort_by_label` and `sort_by_label_desc`: the input's series in another
1076    /// order, which only an instant result shows. `sort` and `sort_desc` also drop histogram
1077    /// samples, in a range result too.
1078    Sort(SortOrder),
1079    /// `absent`: `1` under `labels` at every point where the input holds no sample. The labels are
1080    /// what the compiler derives from the argument's matchers.
1081    Absent { labels: SeriesLabels },
1082    /// `histogram_quantile` or `histogram_fraction`: each classic histogram is read from the bucket
1083    /// series that share its labels, so this too reads the whole vector at a point.
1084    Histogram(HistogramFunction),
1085    /// `count_values(label, v)`: how many samples of each group share a value, under a label set
1086    /// per value. It writes a label per distinct value, which an aggregate's fixed groups cannot.
1087    CountValues { label: Arc<str>, group: Grouping },
1088}
1089
1090/// A set operator and the labels its two vectors are matched by.
1091///
1092/// It has no cardinality, `bool` or fill: PromQL matches a set operator many-to-many and refuses
1093/// the other modifiers on it.
1094#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
1095pub struct BoundSetOp {
1096    /// `and`, `or` or `unless`.
1097    pub op: SetOp,
1098    /// The labels a sample's match group is read from on either side.
1099    pub labels: MatchingLabels,
1100}
1101
1102/// What a node computes. Every variant holds a bound operation, never a name to resolve.
1103///
1104/// The variants are numbered by their position, and postcard writes that number, so these indices
1105/// are a wire contract: a version 3 [`crate::extension_plan::FusedSeries`] envelope carries the
1106/// whole [`NativeTree`] rather than a prefix of it, and a variant inserted anywhere but the end
1107/// renames every variant after it for a reader of an earlier build. New variants are therefore
1108/// appended after `Info`, and `native_expr_variant_indices_are_a_wire_contract` in the tests below
1109/// pins the numbers.
1110#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)]
1111pub enum NativeExpr {
1112    /// A scan or an exchange boundary.
1113    Input(BoundInput),
1114    /// A constant scalar, evaluated on the statement's grid.
1115    Scalar(BoundScalar),
1116    /// The evaluation time of each grid point, as `time()` reads it in seconds, or a date function
1117    /// of it, as a date function called without an argument reads it.
1118    ///
1119    /// A date function is bound here rather than over `time()`: Prometheus reads the calendar from
1120    /// the evaluation timestamp truncated to whole seconds, which the float `time()` does not carry
1121    /// exactly for every timestamp.
1122    EvalTime { date: Option<DateFunction> },
1123    /// `vector(s)`: the scalar as one series without labels.
1124    VectorOf { input: Box<NativeNode> },
1125    /// An instant selection over its input.
1126    Instant {
1127        input: Box<NativeNode>,
1128        op: BoundInstant,
1129    },
1130    /// Canonicalizes evaluated fragments that share a label set.
1131    Merge { input: Box<NativeNode> },
1132    /// A window function over its input.
1133    Window {
1134        input: Box<NativeNode>,
1135        op: BoundWindow,
1136    },
1137    /// Point-wise operations over its input.
1138    Map {
1139        input: Box<NativeNode>,
1140        op: BoundMap,
1141    },
1142    /// A point-wise math function over its input whose parameters are scalar nodes, in argument
1143    /// order.
1144    ///
1145    /// The input is the evaluated vector the function maps, or -- for `max_of` and `min_of`, which
1146    /// are functions of two scalars -- the scalar the call wrote first, which the node answers as
1147    /// one scalar on the same grid. A constant input has no chunk of its own and is read off its
1148    /// binding, as a constant parameter is.
1149    ParameterizedMap {
1150        input: Box<NativeNode>,
1151        op: ParameterizedOp,
1152        parameters: Vec<NativeNode>,
1153    },
1154    /// The timestamp of an evaluated input, in seconds.
1155    Timestamp { input: Box<NativeNode> },
1156    /// An aggregate over its input.
1157    Aggregate {
1158        input: Box<NativeNode>,
1159        op: BoundAggregate,
1160    },
1161    /// An operation over the whole input vector at each grid point.
1162    Vector {
1163        input: Box<NativeNode>,
1164        op: BoundVectorOp,
1165    },
1166    /// A binary operation between two inputs, with its matching rules.
1167    ///
1168    /// Scalar operands are broadcast, so `matching` only applies to vector–vector operations.
1169    Binary {
1170        left: Box<NativeNode>,
1171        right: Box<NativeNode>,
1172        matching: BinaryMatching,
1173    },
1174    /// A set operation between two vectors, which keeps samples of either side as they are.
1175    Set {
1176        left: Box<NativeNode>,
1177        right: Box<NativeNode>,
1178        op: BoundSetOp,
1179    },
1180    /// `info(base, {selector})`: the series of `base` with the data labels of the info series that
1181    /// share their identifying labels. `info` is the instant selection of those info series, whose
1182    /// values are the times of the samples it selected ([`InstantValue::InfoTimestamp`]).
1183    Info {
1184        base: Box<NativeNode>,
1185        info: Box<NativeNode>,
1186        selector: InfoSelector,
1187    },
1188    /// `scalar(v)`: at each grid point, the sole sample value or NaN when the vector has zero or
1189    /// more than one sample.
1190    ScalarOf { input: Box<NativeNode> },
1191    /// `topk`/`bottomk` whose `k` is evaluated at every grid point instead of bound as a constant.
1192    ///
1193    /// `op` is still the `TopK` the constant path binds; its `k` is unused here, because the value
1194    /// this node selects with is the parameter's, read once per point.
1195    ParameterizedTopK {
1196        input: Box<NativeNode>,
1197        op: BoundVectorOp,
1198        parameter: Box<NativeNode>,
1199    },
1200    /// A classic histogram vector operation whose arguments vary on the output grid.
1201    ParameterizedHistogram {
1202        input: Box<NativeNode>,
1203        op: BoundVectorOp,
1204        parameters: Vec<NativeNode>,
1205    },
1206    /// An aggregate whose argument is read at every grid point instead of bound as a constant:
1207    /// `quantile(<φ per point>, v)`.
1208    ///
1209    /// `op` is still the `Quantile` the constant path binds; its `φ` is unused here, because the
1210    /// value this node folds with is the parameter's, read once per point -- exactly as
1211    /// [`Self::ParameterizedTopK`] ignores the `k` its own binding carries. What the fold keeps is
1212    /// its group's sample set either way, so a parameter read per point changes what is folded, not
1213    /// how.
1214    ParameterizedAggregate {
1215        input: Box<NativeNode>,
1216        op: BoundAggregate,
1217        parameter: Box<NativeNode>,
1218    },
1219}
1220
1221/// One node of a bound tree.
1222#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)]
1223pub struct NativeNode {
1224    /// What this node computes, including its bound operands.
1225    pub expr: NativeExpr,
1226    /// What this node produces.
1227    pub output: NativeType,
1228}
1229
1230impl NativeExpr {
1231    /// The subtrees this expression reads, in the order the node evaluates them.
1232    pub fn children(&self) -> Vec<&NativeNode> {
1233        match self {
1234            NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {
1235                Vec::new()
1236            }
1237            NativeExpr::VectorOf { input }
1238            | NativeExpr::Instant { input, .. }
1239            | NativeExpr::Merge { input }
1240            | NativeExpr::Window { input, .. }
1241            | NativeExpr::Map { input, .. }
1242            | NativeExpr::Timestamp { input }
1243            | NativeExpr::Aggregate { input, .. }
1244            | NativeExpr::Vector { input, .. }
1245            | NativeExpr::ScalarOf { input } => vec![input],
1246            NativeExpr::ParameterizedMap {
1247                input, parameters, ..
1248            }
1249            | NativeExpr::ParameterizedHistogram {
1250                input, parameters, ..
1251            } => std::iter::once(input.as_ref())
1252                .chain(parameters.iter())
1253                .collect(),
1254            NativeExpr::ParameterizedTopK {
1255                input, parameter, ..
1256            }
1257            | NativeExpr::ParameterizedAggregate {
1258                input, parameter, ..
1259            } => vec![input, parameter],
1260            NativeExpr::Binary { left, right, .. } | NativeExpr::Set { left, right, .. } => {
1261                vec![left, right]
1262            }
1263            NativeExpr::Info { base, info, .. } => vec![base, info],
1264        }
1265    }
1266
1267    /// This expression with its children replaced, in the order [`Self::children`] reports them.
1268    ///
1269    /// Panics when `children` holds fewer nodes than the expression reads.
1270    pub fn with_children(&self, children: Vec<NativeNode>) -> NativeExpr {
1271        let mut children = children.into_iter();
1272        let mut next = || children.next().expect("one replacement per child");
1273        match self {
1274            NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {
1275                self.clone()
1276            }
1277            NativeExpr::VectorOf { .. } => NativeExpr::VectorOf {
1278                input: Box::new(next()),
1279            },
1280            NativeExpr::Instant { op, .. } => NativeExpr::Instant {
1281                input: Box::new(next()),
1282                op: op.clone(),
1283            },
1284            NativeExpr::Merge { .. } => NativeExpr::Merge {
1285                input: Box::new(next()),
1286            },
1287            NativeExpr::Window { op, .. } => NativeExpr::Window {
1288                input: Box::new(next()),
1289                op: op.clone(),
1290            },
1291            NativeExpr::Map { op, .. } => NativeExpr::Map {
1292                input: Box::new(next()),
1293                op: op.clone(),
1294            },
1295            NativeExpr::ParameterizedMap { op, parameters, .. } => NativeExpr::ParameterizedMap {
1296                input: Box::new(next()),
1297                op: *op,
1298                parameters: (0..parameters.len()).map(|_| next()).collect(),
1299            },
1300            NativeExpr::ScalarOf { .. } => NativeExpr::ScalarOf {
1301                input: Box::new(next()),
1302            },
1303            NativeExpr::ParameterizedTopK { op, .. } => NativeExpr::ParameterizedTopK {
1304                input: Box::new(next()),
1305                op: op.clone(),
1306                parameter: Box::new(next()),
1307            },
1308            NativeExpr::ParameterizedAggregate { op, .. } => NativeExpr::ParameterizedAggregate {
1309                input: Box::new(next()),
1310                op: op.clone(),
1311                parameter: Box::new(next()),
1312            },
1313            NativeExpr::ParameterizedHistogram { op, parameters, .. } => {
1314                NativeExpr::ParameterizedHistogram {
1315                    input: Box::new(next()),
1316                    op: op.clone(),
1317                    parameters: (0..parameters.len()).map(|_| next()).collect(),
1318                }
1319            }
1320            NativeExpr::Timestamp { .. } => NativeExpr::Timestamp {
1321                input: Box::new(next()),
1322            },
1323            NativeExpr::Aggregate { op, .. } => NativeExpr::Aggregate {
1324                input: Box::new(next()),
1325                op: op.clone(),
1326            },
1327            NativeExpr::Vector { op, .. } => NativeExpr::Vector {
1328                input: Box::new(next()),
1329                op: op.clone(),
1330            },
1331            NativeExpr::Binary { matching, .. } => NativeExpr::Binary {
1332                left: Box::new(next()),
1333                right: Box::new(next()),
1334                matching: matching.clone(),
1335            },
1336            NativeExpr::Set { op, .. } => NativeExpr::Set {
1337                left: Box::new(next()),
1338                right: Box::new(next()),
1339                op: op.clone(),
1340            },
1341            NativeExpr::Info { selector, .. } => NativeExpr::Info {
1342                base: Box::new(next()),
1343                info: Box::new(next()),
1344                selector: selector.clone(),
1345            },
1346        }
1347    }
1348}
1349
1350impl NativeNode {
1351    /// Whether `predicate` holds for this node or any node below it.
1352    pub fn any(&self, predicate: &impl Fn(&NativeNode) -> bool) -> bool {
1353        predicate(self)
1354            || self
1355                .expr
1356                .children()
1357                .into_iter()
1358                .any(|child| child.any(predicate))
1359    }
1360
1361    /// The input leaves below this node, in the order the tree evaluates them. A source that two
1362    /// leaves read is listed once per leaf.
1363    pub fn inputs(&self) -> Vec<&BoundInput> {
1364        fn collect<'a>(node: &'a NativeNode, inputs: &mut Vec<&'a BoundInput>) {
1365            if let NativeExpr::Input(input) = &node.expr {
1366                inputs.push(input);
1367            }
1368            for child in node.expr.children() {
1369                collect(child, inputs);
1370            }
1371        }
1372        let mut inputs = Vec::new();
1373        collect(self, &mut inputs);
1374        inputs
1375    }
1376
1377    /// Whether this node reads no data at all: a constant, the evaluation time, or an operation
1378    /// between them. Every execution computes the same value for it.
1379    pub fn is_data_free(&self) -> bool {
1380        match &self.expr {
1381            NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => true,
1382            NativeExpr::Binary { left, right, .. } => left.is_data_free() && right.is_data_free(),
1383            NativeExpr::VectorOf { input } => input.is_data_free(),
1384            _ => false,
1385        }
1386    }
1387}
1388
1389/// Whether this tree can hand over two series that share one canonical label set.
1390///
1391/// A canonical label set is the identity a [`NativeExpr::Merge`] groups by: the metric name plus the
1392/// ordinary labels, which is exactly what [`SeriesLabels`] holds. One scan partition holds one
1393/// series per such set - a stored series is one identity, and the scan splits rows by storage key
1394/// rather than by label set - so only a computation that *writes* an existing label, or drops one,
1395/// can turn two of those identities into one. A `label_replace` or a `label_join` writes one, and it
1396/// may name the very label that told its input's series apart; a range function that drops the
1397/// metric name, and `timestamp` in either of its forms, drop one.
1398///
1399/// The rewrite is judged by the labels it writes and the ones its input carries, which is why the
1400/// caller supplies what it knows about each source's tags, indexed by the `source_index` the leaves
1401/// were bound to: a destination that names no ordinary label of the input writes a fresh one, and a
1402/// fresh ordinary label cannot make two series equal. That is the difference between
1403/// `label_replace(x, "dst", "$1", "host", "(.*)")` - which no merge has to collect - and
1404/// `label_replace(x, "host", "same", "host", ".*")`, which folds every series of `x` into one label
1405/// set.
1406///
1407/// A source's entry is its complete runtime label set, so `__name__` is one of its labels whenever
1408/// its series carry a name - a scan bound to one metric names every series from its binding. That is
1409/// what makes `label_replace(x, "__name__", "same", "__name__", ".*")` a rewrite of an existing
1410/// label: two metrics whose ordinary labels are equal can be told apart by name alone, and rewriting
1411/// that name folds them into one identity. A name write is collected even when the derived set no
1412/// longer carries `__name__` - after `abs`, a `timestamp` or a range function dropped it - because
1413/// the scan below those kernels can still hold several metrics whose ordinary labels are equal, and
1414/// writing one name puts them under one identity; the walk has no proof that the input reads a
1415/// single metric, so the conservative answer is the one that collects.
1416///
1417/// Everything else either keeps the set it read or answers a set of its own:
1418///
1419/// - A map of math drops the metadata labels, and so do a histogram map, a parameterized map, an
1420///   arithmetic or `bool` scalar broadcast, a range function that computes its result and a
1421///   `timestamp` in either of its forms. Such a node is judged by the labels it and its input
1422///   report ([`metadata_labels_keep_series_apart`]): a source bound to one metric names every series
1423///   it hands over, so the name the drop removes told none of them apart, and a source that may hand
1424///   over several is collected. A key column that holds `NULL` in one series and `''` in another is
1425///   *not* part of that proof - see the doc comment of the function - so a drop whose labels prove
1426///   it is never collected for the storage keys alone.
1427/// - An `Aggregate` answers its groups, a `Vector` that folds series answers its result sets, and a
1428///   `Binary` that reads whole vectors files its rows by the label set a sample *ends* under and
1429///   refuses two values of a field at one point. A `Set` does the same, and `info` merges the
1430///   results that share a label set. Each answers one series per set it names.
1431/// - A `Window` that drops the metadata labels, and the two timestamps, claim one of their own: the
1432///   name is part of the identity a merge groups by, so two series that shared every other label are
1433///   one label set from there on - unless the labels tell them apart by the same rule the kernels
1434///   above are judged by.
1435/// - A [`Merge`](NativeExpr::Merge) at or below a drop answers nothing for it
1436///   ([`canonical_below`](crate::native::plan::canonical_below)): a merge hands over one series per
1437///   canonical label set, but the labels that tell two of its series apart still have to prove the
1438///   drop. A chain of drops over one metric is therefore collected once per collision the labels do
1439///   not prove, and not at all when they do.
1440/// - A node that hands its input's series over unchanged - a selection, a name-keeping window,
1441///   `topk` and its ranking siblings - passes the answer on: an alias below it is still an alias
1442///   above it.
1443///
1444/// This is the fact [`merge_label_rewrites`](crate::native::canonicalize::merge_label_rewrites)
1445/// inserts a `Merge` for: a consumer that reads a whole label set cannot answer from pieces, and this
1446/// says where pieces of one set can exist at all. A `Merge` is the collection itself, so it answers
1447/// `false` - which is what makes the pass idempotent.
1448pub fn duplicates_canonical_labels(
1449    node: &NativeNode,
1450    source_tags: &[Vec<String>],
1451    source_metrics: &[Option<Arc<str>>],
1452) -> bool {
1453    match &node.expr {
1454        NativeExpr::Input(_)
1455        | NativeExpr::Scalar(_)
1456        | NativeExpr::EvalTime { .. }
1457        | NativeExpr::VectorOf { .. } => false,
1458        // The collection itself: one series per label set comes out of it.
1459        NativeExpr::Merge { .. } => false,
1460        // These hand each series over as they read it, so what aliases below them still aliases --
1461        // except `timestamp`, which reports a sample's own time under the metadata labels dropped
1462        // and is therefore a source of duplicates in its own right unless the labels prove that
1463        // drop injective ([`metadata_labels_keep_series_apart`]).
1464        NativeExpr::Instant { input, op } => {
1465            (op.value == InstantValue::Timestamp
1466                && !metadata_labels_keep_series_apart(input, source_tags, source_metrics))
1467                || duplicates_canonical_labels(input, source_tags, source_metrics)
1468        }
1469        // A window that drops the metadata labels can fold two series that agreed on every other
1470        // label into one set, so it is a source of duplicates whether or not its input was one -
1471        // unless the labels below it provably tell those series apart still.
1472        NativeExpr::Window { input, op } => {
1473            (op.function.drops_metric_name()
1474                && !metadata_labels_keep_series_apart(input, source_tags, source_metrics))
1475                || duplicates_canonical_labels(input, source_tags, source_metrics)
1476        }
1477        // `timestamp` always drops the metadata labels, so two series it reads can become one set -
1478        // unless the labels below it are all bound to one metric, which is what proves that the name
1479        // it removes told none of those series apart.
1480        NativeExpr::Timestamp { input } => {
1481            !metadata_labels_keep_series_apart(input, source_tags, source_metrics)
1482                || duplicates_canonical_labels(input, source_tags, source_metrics)
1483        }
1484        // A parameterized map is a math kernel - `round`, `clamp` - and drops the metadata labels as
1485        // a math map does, so it answers for the same reason. Its parameter is a scalar and carries
1486        // no labels of the input's.
1487        NativeExpr::ParameterizedMap { input, .. } => {
1488            !metadata_labels_keep_series_apart(input, source_tags, source_metrics)
1489                || duplicates_canonical_labels(input, source_tags, source_metrics)
1490        }
1491        NativeExpr::ParameterizedTopK { input, .. } => {
1492            duplicates_canonical_labels(input, source_tags, source_metrics)
1493        }
1494        // `scalar()` answers one value, which names no label set at all.
1495        NativeExpr::ScalarOf { .. } => false,
1496        // The histogram functions fold the bucket series of one histogram into one series, so two
1497        // pieces of one label set cannot survive them.
1498        NativeExpr::ParameterizedHistogram { .. } => false,
1499        // A rewrite writes a caller-chosen destination label, so two series can end under one set -
1500        // but only if that label was one of the input's, because writing a label no series carries
1501        // leaves every series' identity distinct. `map_writes_existing_label` is that question, and
1502        // an input whose labels this walk cannot derive is collected rather than trusted. Even a
1503        // whole-vector consumer can emit distinct series whose labels a later rewrite makes equal.
1504        // A math or histogram kernel in the same map drops the metadata labels, which is a source of
1505        // duplicates of its own unless the labels tell its input's series apart - see the doc
1506        // comment above.
1507        NativeExpr::Map { input, op } => {
1508            (op.ops
1509                .iter()
1510                .any(|operation| matches!(operation, MapOp::Math(_) | MapOp::Histogram(_)))
1511                && !metadata_labels_keep_series_apart(input, source_tags, source_metrics))
1512                || map_writes_existing_label(input, op, source_tags).unwrap_or(true)
1513                || duplicates_canonical_labels(input, source_tags, source_metrics)
1514        }
1515        // A fold answers one series per group, which is one label set per group.
1516        NativeExpr::Aggregate { .. } | NativeExpr::ParameterizedAggregate { .. } => false,
1517        NativeExpr::Vector { input, op } => match op {
1518            // These keep and order the series they read, so they alias exactly as their input does.
1519            BoundVectorOp::TopK { .. }
1520            | BoundVectorOp::LimitK { .. }
1521            | BoundVectorOp::LimitRatio { .. }
1522            | BoundVectorOp::Sort(_) => {
1523                duplicates_canonical_labels(input, source_tags, source_metrics)
1524            }
1525            // `absent` reports one series, `count_values` one per distinct value, and the histogram
1526            // functions fold the bucket series of one histogram into one series.
1527            BoundVectorOp::Absent { .. }
1528            | BoundVectorOp::Histogram(_)
1529            | BoundVectorOp::CountValues { .. } => false,
1530        },
1531        NativeExpr::Binary {
1532            left,
1533            right,
1534            matching,
1535        } => {
1536            let vector = |side: &NativeNode| side.output.samples().is_some();
1537            match (vector(left), vector(right)) {
1538                // Two vectors are matched by label, and the kernel files its rows by the label set a
1539                // sample ends under, refusing two values of one field at one point.
1540                (true, true) => false,
1541                // A broadcast reaches each series of its vector side as it is, one series of the
1542                // vector side per output series. An arithmetic one and one that reports a `bool`
1543                // drop the metadata labels, which is a source of duplicates of its own unless the
1544                // labels tell its series apart; a filtering comparison keeps the set it read.
1545                (true, false) | (false, true) => {
1546                    let carried = if vector(left) { left } else { right };
1547                    let drops_metadata = !matching.op.is_comparison() || matching.return_bool;
1548                    (drops_metadata
1549                        && !metadata_labels_keep_series_apart(carried, source_tags, source_metrics))
1550                        || duplicates_canonical_labels(carried, source_tags, source_metrics)
1551                }
1552                // Two scalars name no label set at all.
1553                (false, false) => false,
1554            }
1555        }
1556        // A set operation keeps each side's samples and files them by result label set, refusing two
1557        // values of one field at one point.
1558        NativeExpr::Set { .. } => false,
1559        // `info` indexes the info side by identifying labels and merges the results that share a
1560        // label set.
1561        NativeExpr::Info { .. } => false,
1562    }
1563}
1564
1565/// Whether `op`, applied to `input`'s series, writes a label those series already carry.
1566///
1567/// The walk is over the ops in written order, starting from the labels the input reports. A
1568/// destination the input already carries can fold two series into one; a fresh destination cannot.
1569/// A `__name__` destination is always treated as carried, even when the derived set has lost it: a
1570/// kernel such as `abs`, `timestamp` or a range function drops the name, but the scan below it can
1571/// still hold several metrics whose ordinary labels are equal, and writing one name puts those
1572/// identities under one label set. Nothing here proves the input reads a single metric, so the
1573/// conservative answer is the one that collects.
1574///
1575/// `None` when the input's label set is not derivable, which is treated as "it may carry the
1576/// destination" by the caller: an unknown set proves nothing, so the conservative answer is the one
1577/// that collects.
1578fn map_writes_existing_label(
1579    input: &NativeNode,
1580    op: &crate::native::plan::BoundMap,
1581    source_tags: &[Vec<String>],
1582) -> Option<bool> {
1583    let mut tags = fused_output_tags(input, source_tags)?;
1584    let mut existing = false;
1585    for operation in op.ops.iter() {
1586        if let MapOp::Label(rewrite) = operation {
1587            let destination = rewrite.destination();
1588            if destination == METRIC_NAME || tags.iter().any(|tag| tag == destination) {
1589                existing = true;
1590            }
1591            // A label the input did not carry is one the rewrite publishes only when it can write a
1592            // value; a delete-only rewrite adds nothing a later op could read as carried.
1593            if rewrite.writes_value() && !tags.iter().any(|tag| tag == destination) {
1594                tags.push(destination.to_string());
1595            }
1596        }
1597    }
1598    Some(existing)
1599}
1600
1601/// Whether the metadata labels a rewrite drops are the only ones telling `node`'s series apart.
1602///
1603/// A range function that computes its result and `timestamp` in either of its forms drop
1604/// [`PROMQL_METADATA_LABELS`] - the metric name, `__type__` and `__unit__` - and a consumer above
1605/// them that reads a whole label set has to establish those series cannot collide once the three are
1606/// gone. Two series of one input collide only if they differed in one of the three alone,
1607/// so the drop is injective - and nothing has to be collected - when neither can tell two of them
1608/// apart:
1609///
1610/// - The name: a source bound to one metric names every series it hands over, so the name is the
1611///   same for all of them and removing it merges nothing (see [`single_metric_name`]). A source that
1612///   may hand over several - one selector that discovered several metrics, or a caller that cannot
1613///   tell - is not proved, and the conservative answer is the one that collects.
1614/// - `__type__` and `__unit__`: both are removed along with the name, and neither is a label this
1615///   walk can prove constant across a source's series. They are ordinary labels when a source
1616///   carries them as tags or a rewrite writes them, and two series that agree on everything else are
1617///   one label set once they are gone. Their presence anywhere in `node`'s output is therefore
1618///   enough to withhold the proof.
1619///
1620/// A node whose own kernel answers one series per label set - a fold, a match between two vectors, a
1621/// set operation, `info`, `count_values` - has already told those series apart, so a drop above it is
1622/// proved whatever metrics it reads ([`answers_one_series_per_label_set`]).
1623///
1624/// A node whose labels already lost the name - `abs`, a name-dropping window below it - has no name
1625/// of its own left to remove, and what its surviving labels tell apart is then only as good as the
1626/// metrics below it: a drop that happened on the way there removed a name without asking this walk,
1627/// so the proof asks instead that every source it reads is bound to the same one metric
1628/// ([`single_source_metric`]). Over a selector that discovered several metrics that drop folds them
1629/// together, and the answer is the one that collects.
1630///
1631/// `false` when the walk cannot derive `node`'s labels at all, because an unknown set proves nothing.
1632///
1633/// This is the whole of the drop's proof: every arm of [`duplicates_canonical_labels`] that decides
1634/// whether a collection is needed asks it, and so does [`unifies_its_own_contributions`] at run
1635/// time, so the two cannot disagree about a merge.
1636///
1637/// What it does not answer is a key column that holds `NULL` in one series and `''` in another, both
1638/// of which decode to no label once the empty value is dropped with the name. That pair is
1639/// deliberately outside the proof: it is a property of a nullable tag column rather than of the
1640/// labels, and every tag column of a metric-engine table is nullable, so collecting a drop for it
1641/// puts a canonical merge - and the fragmenting boundary that merge carries - over every statement
1642/// whose kernel drops the metadata labels, including the ones whose labels prove the drop injective.
1643/// The fact is still read from the resolved table
1644/// ([`keys_survive_metadata_drop`](crate::extension_plan::keys_survive_metadata_drop)) and the
1645/// statements whose labels prove the drop while that pair does not are still counted
1646/// ([`leaves_a_drop_to_the_storage_keys`]), so what the pair can hide stays observable even though
1647/// nothing is collected for it.
1648fn metadata_labels_keep_series_apart(
1649    node: &NativeNode,
1650    source_tags: &[Vec<String>],
1651    source_metrics: &[Option<Arc<str>>],
1652) -> bool {
1653    let Some(tags) = fused_output_tags(node, source_tags) else {
1654        return false;
1655    };
1656    if tags
1657        .iter()
1658        .any(|tag| tag == "__type__" || tag == "__unit__")
1659    {
1660        return false;
1661    }
1662    if !tags.iter().any(|tag| tag == METRIC_NAME) {
1663        // A node whose own kernel already answers one series per label set told those series apart
1664        // itself, so the drop above it removes a name no two of them were told apart by: `1 - a / b`
1665        // matches the two metrics and refuses two values of one field at one point, and the broadcast
1666        // above that match only drops a name the match no longer carries. Nothing is collected for
1667        // such a consumer, whatever metrics it reads.
1668        if answers_one_series_per_label_set(node) {
1669            return true;
1670        }
1671        // Otherwise no name is left to lose, so what the surviving labels tell apart is decided by
1672        // the sources below: every one of them reading the same single metric is what says a name
1673        // dropped on the way here could not have folded two metrics together either. `abs` and a
1674        // name-dropping window both drop the name without asking, so without that fact nothing
1675        // below is proved.
1676        return single_source_metric(node, source_metrics).is_some();
1677    }
1678    single_metric_name(node, source_metrics).is_some()
1679}
1680
1681/// Whether `node` answers one series per label set by construction.
1682///
1683/// These are the nodes whose own kernel files or folds its rows by the label set a sample ends
1684/// under, so two of the series it answers are distinct label sets whatever its inputs held: a fold
1685/// answers one series per group, a match between two vectors and a set operation file their rows by
1686/// the result label set and refuse two values of one field at one point, `info` merges the results
1687/// that share a label set, and the functions that build one series out of many - `absent`,
1688/// `count_values` and the histogram functions - answer a set of their own.
1689///
1690/// A metadata drop above one of them therefore cannot fold two of its series by removing the name:
1691/// the identity that told them apart is the label set the kernel filed them under, and that set is
1692/// what the drop is handed.
1693///
1694/// A [`NativeExpr::Merge`] is deliberately not one of them. It answers one series per *canonical*
1695/// label set, and that set includes the name: a merge keeps `a{job="x"}` and `b{job="x"}` apart, so a
1696/// drop above it that removes the name does fold those two, and it is collected
1697/// (`a_merge_below_a_drop_does_not_answer_the_metadata_labels`).
1698fn answers_one_series_per_label_set(node: &NativeNode) -> bool {
1699    match &node.expr {
1700        NativeExpr::Aggregate { .. }
1701        | NativeExpr::Set { .. }
1702        | NativeExpr::Info { .. }
1703        | NativeExpr::ParameterizedHistogram { .. } => true,
1704        // A match between two vectors is the one `Binary` shape that files its rows by the result
1705        // label set; a node with a scalar on one side reaches each series of its vector side as it
1706        // is, which tells nothing apart on its own.
1707        NativeExpr::Binary { left, right, .. } => {
1708            left.output.samples().is_some() && right.output.samples().is_some()
1709        }
1710        NativeExpr::Vector { op, .. } => matches!(
1711            op,
1712            BoundVectorOp::Absent { .. }
1713                | BoundVectorOp::Histogram(_)
1714                | BoundVectorOp::CountValues { .. }
1715        ),
1716        _ => false,
1717    }
1718}
1719
1720/// Whether a [`NativeExpr::Merge`] collects the series `node` hands over, at it or below it.
1721///
1722/// A merge holds one series per canonical label set, so the series above one are not stored series
1723/// any more: a merge with nothing to merge hands its input's pieces through, and one that does
1724/// merge keeps the first piece's labels and drops the pieces it folded, so what comes out is unique
1725/// under the label set Prometheus compares (`label_set` in `grid_series`) - the one that treats an
1726/// empty label value as no label. Two pieces that came out of one merge are therefore distinct under
1727/// that comparison even though their rows may still spell an empty value, which is what makes a
1728/// second drop above the merge unable to fold them by removing an empty value. What it does not make
1729/// impossible is the rest of such a drop: a merge keeps two series that differ in `__name__`,
1730/// `__type__` or `__unit__`, and removing those is exactly what a metadata drop does.
1731///
1732/// Only the children that carry samples are searched: a parameter is a scalar or a vector of
1733/// constants, and a merge below one reads series this node's own samples did not come from.
1734fn canonical_below(node: &NativeNode) -> bool {
1735    matches!(node.expr, NativeExpr::Merge { .. })
1736        || node
1737            .expr
1738            .children()
1739            .into_iter()
1740            .filter(|child| matches!(child.output, NativeType::Samples(_)))
1741            .any(canonical_below)
1742}
1743
1744/// Whether `node` drops [`PROMQL_METADATA_LABELS`] on its own over series whose labels are proved to
1745/// tell apart and whose keys are not.
1746///
1747/// This is what the pair the proof leaves outside costs, stated rather than collected: the labels
1748/// prove the drop ([`metadata_labels_keep_series_apart`]), nothing at or below it has collected
1749/// already ([`canonical_below`]), and the scan's primary key holds a column that can spell `NULL` in
1750/// one series and `''` in another. Those two decode to an absent and to an empty label, and the drop
1751/// normalizes them into one - the case a collection used to be inserted for and that a name-dropping
1752/// kernel over a metric-engine table, whose tag columns are all nullable, paid a merge for. The
1753/// collection is gone (see [`metadata_labels_keep_series_apart`]) and this is the count that keeps
1754/// the statements it would have covered observable.
1755///
1756/// Every node that drops the metadata labels on its own counts: a map of math, a histogram map, a
1757/// parameterized map and an arithmetic or `bool` scalar broadcast, and the three that rewrite a
1758/// sample's own value - a name-dropping range function, `timestamp(x)` and a `timestamp` over an
1759/// evaluated input.
1760fn drops_metadata_labels_over_one_metric(
1761    node: &NativeNode,
1762    source_tags: &[Vec<String>],
1763    source_metrics: &[Option<Arc<str>>],
1764    keys_survive: bool,
1765) -> bool {
1766    // The statement is counted exactly when the labels prove the drop and the key columns are the
1767    // only thing left that does not: nothing at or below it has collected already
1768    // ([`canonical_below`]), and the resolved table's keys can spell the `NULL`/`''` pair - which is
1769    // the fact this count exists to surface now that nothing is collected for it.
1770    let decided_by_the_keys = |carried: &NativeNode| {
1771        !keys_survive
1772            && metadata_labels_keep_series_apart(carried, source_tags, source_metrics)
1773            && !canonical_below(carried)
1774    };
1775    let dropped = match &node.expr {
1776        NativeExpr::Instant { input, op } => {
1777            op.value == InstantValue::Timestamp && decided_by_the_keys(input)
1778        }
1779        NativeExpr::Timestamp { input } => decided_by_the_keys(input),
1780        NativeExpr::Window { input, op } => {
1781            op.function.drops_metric_name() && decided_by_the_keys(input)
1782        }
1783        NativeExpr::ParameterizedMap { input, .. } => decided_by_the_keys(input),
1784        NativeExpr::Map { input, op } => {
1785            op.ops
1786                .iter()
1787                .any(|operation| matches!(operation, MapOp::Math(_) | MapOp::Histogram(_)))
1788                && decided_by_the_keys(input)
1789        }
1790        // A broadcast reaches each series of its vector side as it is; an arithmetic one and one
1791        // that reports a `bool` drop the metadata labels, a filtering comparison keeps them.
1792        NativeExpr::Binary {
1793            left,
1794            right,
1795            matching,
1796        } => {
1797            let carried = match (
1798                left.output.samples().is_some(),
1799                right.output.samples().is_some(),
1800            ) {
1801                (true, false) => Some(left.as_ref()),
1802                (false, true) => Some(right.as_ref()),
1803                _ => None,
1804            };
1805            carried.is_some_and(|carried| {
1806                (!matching.op.is_comparison() || matching.return_bool)
1807                    && decided_by_the_keys(carried)
1808            })
1809        }
1810        _ => false,
1811    };
1812    dropped
1813        || node.expr.children().into_iter().any(|child| {
1814            drops_metadata_labels_over_one_metric(child, source_tags, source_metrics, keys_survive)
1815        })
1816}
1817
1818/// Whether `tree` holds a node that drops the metadata labels over series whose labels are proved to
1819/// tell apart and whose keys are not (see [`drops_metadata_labels_over_one_metric`]).
1820///
1821/// A statement this answers `true` for is one whose drop the labels prove while the scan below it
1822/// keys its series by a column that can hold `NULL` in one series and `''` in another
1823/// (`keys_survive` is `false`, and the caller states that fact from the resolved table). Nothing is
1824/// collected for that pair - the labels are the whole of the proof - so this is the count that keeps
1825/// the statements it leaves unproved observable, and the caller reports it as the reason its
1826/// label-set check does not cover them.
1827pub fn leaves_a_drop_to_the_storage_keys(
1828    tree: &NativeTree,
1829    source_tags: &[Vec<String>],
1830    source_metrics: &[Option<Arc<str>>],
1831    keys_survive: bool,
1832) -> bool {
1833    drops_metadata_labels_over_one_metric(tree.root(), source_tags, source_metrics, keys_survive)
1834}
1835
1836/// The one metric every source `node` reads is bound to, or `None` when they are not all one.
1837///
1838/// This is the facts-free question about the leaves alone: a node can drop the metric name on the
1839/// way (a math map, a range function) whatever its sources hold, so what the surviving labels tell
1840/// apart is only as good as the set of metrics below them.
1841fn single_source_metric(
1842    node: &NativeNode,
1843    source_metrics: &[Option<Arc<str>>],
1844) -> Option<Arc<str>> {
1845    let mut pending = vec![node];
1846    let mut metric: Option<&Arc<str>> = None;
1847    while let Some(node) = pending.pop() {
1848        match &node.expr {
1849            // A source that may hand over several metrics proves nothing about their names.
1850            NativeExpr::Input(input) => {
1851                let bound = source_metrics.get(input.source_index)?.as_ref()?;
1852                match metric {
1853                    None => metric = Some(bound),
1854                    Some(seen) if seen == bound => {}
1855                    Some(_) => return None,
1856                }
1857            }
1858            NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {}
1859            NativeExpr::Instant { input, .. }
1860            | NativeExpr::Window { input, .. }
1861            | NativeExpr::Map { input, .. }
1862            | NativeExpr::Timestamp { input }
1863            | NativeExpr::VectorOf { input }
1864            | NativeExpr::Merge { input }
1865            | NativeExpr::Aggregate { input, .. }
1866            | NativeExpr::Vector { input, .. }
1867            | NativeExpr::ScalarOf { input } => pending.push(input),
1868            NativeExpr::ParameterizedMap {
1869                input, parameters, ..
1870            }
1871            | NativeExpr::ParameterizedHistogram {
1872                input, parameters, ..
1873            } => {
1874                pending.push(input);
1875                pending.extend(parameters.iter());
1876            }
1877            NativeExpr::ParameterizedTopK {
1878                input, parameter, ..
1879            } => {
1880                pending.push(input);
1881                pending.push(parameter);
1882            }
1883            // A fold reads its group's values and the series its argument is answered from, so both
1884            // halves are sources this question is asked of.
1885            NativeExpr::ParameterizedAggregate {
1886                input, parameter, ..
1887            } => {
1888                pending.push(input);
1889                pending.push(parameter);
1890            }
1891            NativeExpr::Binary { left, right, .. }
1892            | NativeExpr::Set { left, right, .. }
1893            | NativeExpr::Info {
1894                base: left,
1895                info: right,
1896                ..
1897            } => {
1898                pending.push(left);
1899                pending.push(right);
1900            }
1901        }
1902    }
1903    metric.cloned()
1904}
1905
1906/// The one metric every series `node` hands over is named, or `None` when this walk cannot say.
1907///
1908/// Only the nodes that hand their input's label set on unchanged can carry a name: every kernel that
1909/// reports a value of its own drops it, so a name above one of those is one a rewrite wrote. What is
1910/// left is the boundary the leaves are bound to - where `source_metrics` answers, indexed by the
1911/// `source_index` the leaf reads - and the nodes that pass a set through.
1912fn single_metric_name(node: &NativeNode, source_metrics: &[Option<Arc<str>>]) -> Option<Arc<str>> {
1913    match &node.expr {
1914        NativeExpr::Input(input) => source_metrics.get(input.source_index).cloned().flatten(),
1915        // These report the label set they read rather than one of their own, so the name is their
1916        // input's. A map that computes a value or writes a name is not one of them.
1917        NativeExpr::Merge { input }
1918        | NativeExpr::ParameterizedTopK { input, .. }
1919        | NativeExpr::Vector {
1920            input,
1921            op:
1922                BoundVectorOp::TopK { .. }
1923                | BoundVectorOp::LimitK { .. }
1924                | BoundVectorOp::LimitRatio { .. }
1925                | BoundVectorOp::Sort(_),
1926        } => single_metric_name(input, source_metrics),
1927        NativeExpr::Instant { input, op } if op.value != InstantValue::Timestamp => {
1928            single_metric_name(input, source_metrics)
1929        }
1930        NativeExpr::Window { input, op } if !op.function.drops_metric_name() => {
1931            single_metric_name(input, source_metrics)
1932        }
1933        NativeExpr::Map { input, op }
1934            if op.ops.iter().all(|operation| {
1935                matches!(
1936                    operation,
1937                    MapOp::Label(rewrite) if rewrite.destination() != METRIC_NAME
1938                )
1939            }) =>
1940        {
1941            single_metric_name(input, source_metrics)
1942        }
1943        // A kernel that reports a value of its own drops the name, and a fold, a set operation, an
1944        // `info` lookup and a rewrite writing the name answer a set this walk does not follow.
1945        _ => None,
1946    }
1947}
1948
1949/// Whether `node` reads the whole input vector at a point rather than one series at a time.
1950///
1951/// An `Aggregate` folds every series of its group, whether its argument is bound or read per point,
1952/// a `Binary` and a `Set` pair two vectors' series by label, an `Info` looks the info series of each
1953/// series up by its identifying labels, and a `Vector` operation (`sort`, `absent`, `topk`, `limitk`,
1954/// `histogram_quantile`, ...) reorders or reads the whole vector at a grid point.
1955///
1956/// `Merge` answers one series per label set, and the label sets it answers span every input series:
1957/// two of them can collapse into the one it emits. It is therefore whole-vector too, which is why it
1958/// also cannot be moved below a boundary that holds only part of a metric. Everything else - an
1959/// input, a scalar, a selection, a window, a map, and a binary operation with a constant on one
1960/// side, whose broadcast reaches each series the other side answers - answers one series from one
1961/// series' rows.
1962///
1963/// Both a region-side placement and the native route's admission ask this, and they must agree: a
1964/// tree admitted here but refused there becomes a node the physical layer cannot build, and one
1965/// refused here but admitted there would be pushed to a region that holds part of the metric.
1966///
1967/// The walk asks the facts-free form of [`unifies_its_own_contributions`]: a placement reads a tree
1968/// without the binding that says which metric each of its inputs reads, and every reader of this
1969/// answer - the admission below, the region-side classification and the locality of a built node -
1970/// asks it of the same tree, so the conservative answer is the one that keeps them agreeing.
1971pub fn reads_across_series(node: &NativeNode) -> bool {
1972    match &node.expr {
1973        NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => false,
1974        NativeExpr::Window { input, .. } => {
1975            matches!(unifies_its_own_contributions(input, &[], &[]), Some(false))
1976                || reads_across_series(input)
1977        }
1978        NativeExpr::Instant { input, .. }
1979        | NativeExpr::VectorOf { input }
1980        | NativeExpr::Map { input, .. }
1981        | NativeExpr::Timestamp { input } => reads_across_series(input),
1982        // A parameterized operation reads its parameters too, and one of them can read across series
1983        // as well: `clamp_min(b, scalar(a))` bounds each series of `b` by a value that only exists
1984        // once the whole of `a` is gathered, so the node reads across series wherever its parameter
1985        // does.
1986        NativeExpr::ParameterizedMap {
1987            input, parameters, ..
1988        } => reads_across_series(input) || parameters.iter().any(reads_across_series),
1989        // `scalar()` needs the whole vector: which series carries the one value at a point decides
1990        // the answer, so the node reads across series.
1991        NativeExpr::ScalarOf { .. } => true,
1992        NativeExpr::Binary { left, right, .. } => {
1993            let scalar = |side: &NativeNode| matches!(side.output, NativeType::Scalar(_));
1994            if scalar(left) || scalar(right) {
1995                reads_across_series(left) || reads_across_series(right)
1996            } else {
1997                // Two vectors are matched by label, which pairs series of the whole vector.
1998                true
1999            }
2000        }
2001        // A parameterized operation reads its parameter too, and a `k` that changes per point
2002        // decides which series survive.
2003        NativeExpr::ParameterizedTopK { .. } | NativeExpr::ParameterizedHistogram { .. } => true,
2004        NativeExpr::Aggregate { .. }
2005        | NativeExpr::ParameterizedAggregate { .. }
2006        | NativeExpr::Vector { .. }
2007        | NativeExpr::Set { .. }
2008        | NativeExpr::Info { .. }
2009        | NativeExpr::Merge { .. } => true,
2010    }
2011}
2012
2013/// Whether `node` is a supported child of a [`NativeExpr::Merge`], and the evaluated vector it hands
2014/// over.
2015///
2016/// A merge receives fragments and groups them by canonical label set, combining the ones a label set
2017/// shares by grid position; it names neither the tree nor the operator that produced a fragment. What
2018/// it reads is therefore the whole of its requirement: samples evaluated on one grid in one field
2019/// layout, which is an evaluated vector and nothing else. This is that type check and no more, so no
2020/// node kind is refused for what it computes: a scan's samples, a window's rate, an aggregate's fold
2021/// and a binary operation's match all hand over the same thing, and which one of them did says
2022/// nothing about whether the fragments merge.
2023///
2024/// The collection does rely on the shape of the stream - a series arrives whole, its chunks
2025/// contiguous and its last one marked as closing it - and every node that answers an evaluated vector
2026/// keeps it. A window, a map, an instant selection, a timestamp and a scalar broadcast hand their
2027/// input's closing on, and an aggregate, a vector operation, a binary or set operation and a merge
2028/// itself close each series they answer, because each decides a whole series at once. There is hence
2029/// no operator above a merge that could break the collection, and none has to be listed here; the
2030/// collector checks the shape chunk by chunk before it keeps a fragment, which is where a stream that
2031/// broke it is refused.
2032fn merge_shape_supported(node: &NativeNode) -> Option<(&Arc<SeriesSchema>, &Arc<EvalGrid>)> {
2033    evaluated_vector(&node.output)
2034}
2035
2036/// A bound evaluation tree.
2037///
2038/// The tree itself carries no run-time state: every execution builds its own, so one compiled plan
2039/// can serve every partition.
2040#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)]
2041pub struct NativeTree {
2042    root: NativeNode,
2043}
2044
2045impl NativeTree {
2046    /// Creates a tree over `root`, checking that every node's contract holds.
2047    ///
2048    /// A structurally inconsistent tree is a compiler defect.
2049    pub fn try_new(root: NativeNode) -> Result<Self> {
2050        root.validate()?;
2051        Ok(Self { root })
2052    }
2053
2054    /// The root node.
2055    pub fn root(&self) -> &NativeNode {
2056        &self.root
2057    }
2058}
2059
2060impl<'de> serde::Deserialize<'de> for NativeNode {
2061    fn deserialize<D: serde::Deserializer<'de>>(
2062        deserializer: D,
2063    ) -> std::result::Result<Self, D::Error> {
2064        #[derive(serde::Deserialize)]
2065        struct Wire {
2066            expr: NativeExpr,
2067            output: NativeType,
2068        }
2069        let wire = Wire::deserialize(deserializer)?;
2070        Ok(Self {
2071            expr: wire.expr,
2072            output: wire.output,
2073        })
2074    }
2075}
2076
2077impl<'de> serde::Deserialize<'de> for NativeTree {
2078    fn deserialize<D: serde::Deserializer<'de>>(
2079        deserializer: D,
2080    ) -> std::result::Result<Self, D::Error> {
2081        #[derive(serde::Deserialize)]
2082        struct Wire {
2083            root: NativeNode,
2084        }
2085        let wire = Wire::deserialize(deserializer)?;
2086        wire.root.validate().map_err(serde::de::Error::custom)?;
2087        Ok(Self { root: wire.root })
2088    }
2089}
2090
2091/// Whether the native runtime executes `tree`, answered from the tree itself.
2092///
2093/// This is the question the native route asks before it commits a statement: a tree the runtime
2094/// refuses has to keep the plan it had, because a refusal raised during physical planning cannot
2095/// fall back. It used to be answered by building a
2096/// [`NativeExecutionState`](crate::native::execute::NativeExecutionState) over the tree and
2097/// dropping it, which allocates a runtime node per node per partition only to throw it away. Every
2098/// term of the answer is bound on the tree, so the answer is read from the tree instead.
2099///
2100/// # What is refused
2101///
2102/// This lists what `RuntimeNode::build` (and the root check in
2103/// `NativeExecutionState::try_new`) refuses, less what [`NativeNode::validate`] has already
2104/// refused: a `NativeTree` exists only through [`NativeTree::try_new`] or `Deserialize`, and both
2105/// validate, so a compiled tree's per-node type contracts hold by the time this runs. What is left
2106/// is the shape of the nodes, and the arithmetic each of them leaves to the runtime:
2107///
2108/// - a root that answers raw samples, which has no positions to answer on;
2109/// - an input leaf whose series chunks may interleave, which no consumer of a leaf can order;
2110/// - `scalar()` over a vector carrying more than one field;
2111/// - a binary node that is neither a vector–vector operation nor a broadcast the runtime performs:
2112///   two constant operands (no series to carry the result), a scalar broadcast carrying
2113///   vector-matching modifiers, or `bool` on an arithmetic operator, which has no `bool` form;
2114/// - a `quantile` aggregate at any stage but `Complete`, which would need a partial state it does
2115///   not keep (`validate` refuses one for the same reason; this arm keeps the predicate and the
2116///   runtime agreeing on it);
2117/// - an aggregate below `Final` whose `by` names a value field, which would fold series the
2118///   existing plan keeps apart;
2119/// - `topk`, `bottomk`, `limitk`, `sort` and `sort_desc` over a vector carrying more than one
2120///   field, whose series have no one value to rank;
2121/// - a `topk`, `bottomk`, `limitk` or `count_values` grouping that names a value field, and a
2122///   `count_values` label that is empty;
2123/// - a window whose `anchored` or `smoothed` modifier reads evaluated input, names a function its
2124///   kernel does not correct, or carries a negative lookback;
2125/// - a window whose timestamps do not fit: the fold offset an `@` anchor turns into, or the one
2126///   `predict_linear` adds to a point of the grid, where the sum leaves `i64`. Not a shape, but it
2127///   is decided by the grid and the window alone, so this is where it is decided (see
2128///   `window_instants_fit`).
2129///
2130/// # What `NativeExecutionState::try_new` still decides
2131///
2132/// Not every refusal is decided by the tree, and the ones below stay where the runtime builds:
2133///
2134/// - a reservation the memory pool refuses, which no tree carries. Every site that admits a tree
2135///   ran the trial build over an
2136///   [`UnboundedMemoryPool`](datafusion::execution::memory_pool::UnboundedMemoryPool), which
2137///   refuses nothing, and none of them builds a runtime any more, so this is not a refusal
2138///   admission can meet at any site;
2139/// - a tree a test assembled directly, whose nodes disagree about their types, which
2140///   [`NativeNode::validate`] rejects for every compiled one.
2141pub fn native_tree_supported(tree: &NativeTree) -> bool {
2142    // A constant root and a state root are answers the state produces itself; a root of raw
2143    // samples is not one, because raw samples carry their own timestamps instead of positions.
2144    let root_supported = match &tree.root().output {
2145        NativeType::Scalar(_) | NativeType::AggregateState(_) => true,
2146        NativeType::Samples(schema) => schema.eval_grid.is_some(),
2147    };
2148    root_supported && native_node_supported(tree.root())
2149}
2150
2151/// Whether `node` and every input below it is a shape the runtime builds.
2152fn native_node_supported(node: &NativeNode) -> bool {
2153    stacker::maybe_grow(VALIDATE_STACK_RED_ZONE, VALIDATE_STACK_GROWTH, || {
2154        native_node_supported_within_stack(node)
2155    })
2156}
2157
2158/// [`native_node_supported`] one tree level down.
2159///
2160/// Every arm reads this node's own shape and recurses into exactly the inputs its variant holds,
2161/// so a new [`NativeExpr`] variant does not compile until it is classified here.
2162fn native_node_supported_within_stack(node: &NativeNode) -> bool {
2163    match &node.expr {
2164        NativeExpr::Input(bound) => bound.ordering != SeriesOrdering::Interleaved,
2165        NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => true,
2166        NativeExpr::VectorOf { input } | NativeExpr::Instant { input, .. } => {
2167            native_node_supported(input)
2168        }
2169        NativeExpr::Merge { input } | NativeExpr::Map { input, .. } => native_node_supported(input),
2170        NativeExpr::Timestamp { input } => native_node_supported(input),
2171        NativeExpr::Window { input, op } => {
2172            native_node_supported(input)
2173                && window_modifier_supported(input, op)
2174                && window_instants_fit(op)
2175        }
2176        NativeExpr::ParameterizedMap {
2177            input, parameters, ..
2178        } => native_node_supported(input) && parameters.iter().all(native_node_supported),
2179        NativeExpr::ParameterizedHistogram {
2180            input, parameters, ..
2181        } => native_node_supported(input) && parameters.iter().all(native_node_supported),
2182        NativeExpr::Aggregate { input, op } => {
2183            native_node_supported(input) && aggregate_supported(node, input, op)
2184        }
2185        // A per-point argument does not change which fold runs, only where its `φ` comes from: the
2186        // same aggregate checks apply, and the parameter is a subtree like any other. That it is a
2187        // scalar on this fold's grid is a type contract `validate` already refuses.
2188        NativeExpr::ParameterizedAggregate {
2189            input,
2190            op,
2191            parameter,
2192        } => {
2193            native_node_supported(input)
2194                && native_node_supported(parameter)
2195                // A literal hands over no chunk, so the fold could never read a value from it:
2196                // `validate` refuses one, and a tree this predicate admits must be one it does not.
2197                && !matches!(parameter.expr, NativeExpr::Scalar(_))
2198                && aggregate_supported(node, input, op)
2199        }
2200        NativeExpr::Vector { input, op } => {
2201            native_node_supported(input)
2202                && node
2203                    .output
2204                    .samples()
2205                    .is_some_and(|schema| vector_op_supported(schema, op))
2206        }
2207        NativeExpr::ParameterizedTopK {
2208            input,
2209            op,
2210            parameter,
2211        } => {
2212            native_node_supported(input)
2213                && native_node_supported(parameter)
2214                // A per-point `k` ranks the same series as the constant one, one value per series.
2215                && node.output.samples().is_some_and(|schema| {
2216                    schema.fields.len() == 1 && vector_op_supported(schema, op)
2217                })
2218        }
2219        NativeExpr::ScalarOf { input } => {
2220            native_node_supported(input)
2221                // `scalar()` answers the sole value of a vector, so a vector of several fields has
2222                // more than one value to answer with.
2223                && input
2224                    .output
2225                    .samples()
2226                    .is_some_and(|schema| schema.fields.len() == 1)
2227        }
2228        NativeExpr::Binary {
2229            left,
2230            right,
2231            matching,
2232        } => {
2233            native_node_supported(left)
2234                && native_node_supported(right)
2235                && binary_supported(left, right, matching)
2236        }
2237        NativeExpr::Set { left, right, .. } => {
2238            native_node_supported(left) && native_node_supported(right)
2239        }
2240        NativeExpr::Info { base, info, .. } => {
2241            native_node_supported(base) && native_node_supported(info)
2242        }
2243    }
2244}
2245
2246/// Whether a binary node over `left` and `right` is a shape the runtime builds.
2247///
2248/// Two evaluated vectors are matched by `matching`, which the kernel takes as it is bound. Every
2249/// other pair is a broadcast over one scalar side, and a broadcast has no labels to match and no
2250/// series to pair: two constants leave no series to carry the result, a modifier a vector match
2251/// would use has no meaning over a scalar, and arithmetic has no `bool` form.
2252fn binary_supported(left: &NativeNode, right: &NativeNode, matching: &BinaryMatching) -> bool {
2253    let evaluated = |node: &NativeNode| {
2254        node.output
2255            .samples()
2256            .is_some_and(|schema| schema.eval_grid.is_some())
2257    };
2258    if evaluated(left) && evaluated(right) {
2259        return true;
2260    }
2261    let literal = |node: &NativeNode| matches!(&node.expr, NativeExpr::Scalar(_));
2262    let broadcastable = match (&left.output, &right.output) {
2263        (NativeType::Samples(vector), NativeType::Scalar(_))
2264        | (NativeType::Scalar(_), NativeType::Samples(vector)) => vector.eval_grid.is_some(),
2265        (NativeType::Scalar(_), NativeType::Scalar(_)) => !(literal(left) && literal(right)),
2266        _ => false,
2267    };
2268    broadcastable
2269        && matching.labels == MatchingLabels::Ignoring(Vec::new())
2270        && matching.cardinality == Cardinality::OneToOne
2271        && matching.fill == FillValues::default()
2272        && !(!matching.op.is_comparison() && matching.return_bool)
2273}
2274
2275/// Whether the runtime folds `op` over `input` with the layout `node` declares.
2276///
2277/// A `Complete` or `Partial` node folds values into groups it keys by series labels only, while
2278/// `Final` merges state that was already grouped, which is why only the folding stages are checked
2279/// against the schema.
2280fn aggregate_supported(node: &NativeNode, input: &NativeNode, op: &BoundAggregate) -> bool {
2281    match op.kind {
2282        AggregateKind::Sum
2283        | AggregateKind::Count
2284        | AggregateKind::Avg
2285        | AggregateKind::Min
2286        | AggregateKind::Max
2287        | AggregateKind::Group
2288        | AggregateKind::Stddev
2289        | AggregateKind::Stdvar => {}
2290        AggregateKind::Quantile { .. } => {
2291            // A quantile is one `Complete` fold over its group's whole input: it keeps no state,
2292            // so `validate` refuses a `Partial` or `Final` one and there is nothing to merge. The
2293            // runtime answers the `Complete` stage, which is the only shape compiled.
2294            if op.stage != AggregateStage::Complete {
2295                return false;
2296            }
2297        }
2298    }
2299    if op.stage == AggregateStage::Final {
2300        return true;
2301    }
2302    node.output
2303        .samples()
2304        .or_else(|| input.output.samples())
2305        .is_some_and(|schema| grouping_supported(schema, &op.group))
2306}
2307
2308/// Whether `op` is an operation the vector kernel runs over a vector of `schema`.
2309fn vector_op_supported(schema: &SeriesSchema, op: &BoundVectorOp) -> bool {
2310    // These five rank or order one value per series, so a vector whose samples carry several
2311    // fields has no one value to rank.
2312    let one_field = matches!(
2313        op,
2314        BoundVectorOp::TopK { .. }
2315            | BoundVectorOp::LimitK { .. }
2316            | BoundVectorOp::Sort(SortOrder::Asc | SortOrder::Desc)
2317    );
2318    if one_field && schema.fields.len() != 1 {
2319        return false;
2320    }
2321    match op {
2322        BoundVectorOp::TopK { group, .. } | BoundVectorOp::LimitK { group, .. } => {
2323            grouping_supported(schema, group)
2324        }
2325        BoundVectorOp::CountValues { label, group } => {
2326            let names = group_names(group);
2327            crate::aggregate::validate_count_values(
2328                schema,
2329                label.as_ref(),
2330                kernel_grouping(group, &names),
2331            )
2332            .is_ok()
2333        }
2334        BoundVectorOp::LimitRatio { .. }
2335        | BoundVectorOp::Sort(_)
2336        | BoundVectorOp::Absent { .. }
2337        | BoundVectorOp::Histogram(_) => true,
2338    }
2339}
2340
2341/// Whether the kernel folds `schema`'s series the way `group` asks.
2342///
2343/// The kernel validates its grouping by the schema alone: the group is a set of series labels, and
2344/// a `by` naming one of the schema's fields would group by a value that varies between samples.
2345/// This is the check `FloatAggregator::try_new_budgeted` and `VectorRuntime::try_new` run, spelled
2346/// once so a reader of either name finds the same rule.
2347fn grouping_supported(schema: &SeriesSchema, group: &Grouping) -> bool {
2348    let names = group_names(group);
2349    crate::aggregate::validate_vector_grouping(schema, kernel_grouping(group, &names)).is_ok()
2350}
2351
2352/// The labels `group` names, which is what the kernel's grouping is built over.
2353fn group_names(group: &Grouping) -> Vec<&str> {
2354    match group {
2355        Grouping::By(names) | Grouping::Without(names) => names.iter().map(AsRef::as_ref).collect(),
2356    }
2357}
2358
2359/// `group` spelled with the kernel's own [`Grouping`](crate::aggregate::Grouping), over the labels
2360/// [`group_names`] reports for it: `by` and `without` are not interchangeable to the kernel.
2361fn kernel_grouping<'a>(group: &Grouping, names: &'a [&'a str]) -> crate::aggregate::Grouping<'a> {
2362    match group {
2363        Grouping::By(_) => crate::aggregate::Grouping::By(names),
2364        Grouping::Without(_) => crate::aggregate::Grouping::Without(names),
2365    }
2366}
2367
2368/// Whether the runtime evaluates `op` over `input`, with or without a range modifier.
2369///
2370/// An `anchored` or `smoothed` window reads samples around the window to pin its boundary values,
2371/// which only a raw sample stream can offer and only a kernel that corrects its boundaries reads.
2372/// That is one rule, not two: [`check_modifier`](crate::range_eval::check_modifier) states it for
2373/// [`RangeEvaluator::try_new`](crate::range_eval::RangeEvaluator::try_new), and it is asked here
2374/// over the schema the tree binds, so a modifier a runtime refuses is one admission declines.
2375fn window_modifier_supported(input: &NativeNode, op: &BoundWindow) -> bool {
2376    // Without a modifier there is nothing for the rule to decide.
2377    let Some(modifier) = op.window.modifier else {
2378        return true;
2379    };
2380    input.output.samples().is_some_and(|schema| {
2381        crate::range_eval::check_modifier(schema, modifier, op.function).is_ok()
2382    })
2383}
2384
2385/// Whether the runtime can compute the timestamps `op` reads.
2386///
2387/// Unlike the window itself, which a point of the grid opens alone, these timestamps are sums of
2388/// the window's own parts: an `@` anchor becomes an offset from the grid's first point, and
2389/// `predict_linear` adds that offset to the first and last point of the grid. Every term of either
2390/// sum is bound on the node, but a sum of two that fit can still leave `i64`, and the runtime
2391/// refuses the window when one does. Asking [`fold_offset`] and [`predict_linear_instants`] here
2392/// rather than repeating their arithmetic keeps the two verdicts the same one: a query whose only
2393/// refusal is this one keeps the plan it had instead of failing while the runtime is built.
2394fn window_instants_fit(op: &BoundWindow) -> bool {
2395    let grid = op.output_grid.spec();
2396    let Ok(fold_offset) = fold_offset(grid, op.window) else {
2397        return false;
2398    };
2399    match op.function {
2400        // Only `predict_linear` reads the instant it reports; every other function reads the
2401        // window it opens, which the grid alone decides.
2402        RangeFunction::PredictLinear(_) => predict_linear_instants(grid, fold_offset).is_ok(),
2403        _ => true,
2404    }
2405}
2406
2407/// Stack one [`NativeNode::validate`] level needs below it before the check grows its stack.
2408///
2409/// The check recurses once per tree level, and a debug build's frame for one level is large:
2410/// measured on an 80-term chain, the whole check needed about 1.9 MiB, which overflows the 2 MiB
2411/// stack a test thread has. There is no depth limit on the trees this route compiles, so the check
2412/// grows its stack on demand rather than relying on the caller's.
2413const VALIDATE_STACK_RED_ZONE: usize = 256 * 1024;
2414
2415/// Stack a growth adds when the reserve above is spent. It holds several levels of the same check.
2416const VALIDATE_STACK_GROWTH: usize = 4 * 1024 * 1024;
2417
2418impl NativeNode {
2419    /// Checks this node and its inputs against the contract of its operation.
2420    pub fn validate(&self) -> Result<()> {
2421        stacker::maybe_grow(VALIDATE_STACK_RED_ZONE, VALIDATE_STACK_GROWTH, || {
2422            self.validate_within_stack()
2423        })
2424    }
2425
2426    fn validate_within_stack(&self) -> Result<()> {
2427        match &self.expr {
2428            NativeExpr::Input(input) => {
2429                // An input node's output is exactly the binding it was bound to: a scan hands over
2430                // the samples it was created for, and an exchange boundary the state.
2431                if !self.output.same_binding(&input.output) {
2432                    return Err(invalid(
2433                        "an input node's output is not the binding it was bound to",
2434                    ));
2435                }
2436            }
2437            NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {
2438                if !matches!(self.output, NativeType::Scalar(_)) {
2439                    return Err(invalid("a scalar node does not produce a scalar"));
2440                }
2441            }
2442            NativeExpr::ScalarOf { input } => {
2443                input.validate()?;
2444                let Some((_, input_grid)) = evaluated_vector(&input.output) else {
2445                    return Err(invalid("scalar() consumes an evaluated vector"));
2446                };
2447                let NativeType::Scalar(output_grid) = &self.output else {
2448                    return Err(invalid("scalar() does not produce a scalar"));
2449                };
2450                if output_grid.spec() != input_grid.spec() {
2451                    return Err(invalid("scalar() output is not on its input's grid"));
2452                }
2453            }
2454            NativeExpr::VectorOf { input } => {
2455                input.validate()?;
2456                let NativeType::Scalar(input_grid) = &input.output else {
2457                    return Err(invalid("vector() consumes a scalar"));
2458                };
2459                ensure_samples(&self.output, "vector()")?;
2460                if !self.output.samples().is_some_and(|s| s.fields.len() == 1) {
2461                    return Err(invalid("vector() produces one field"));
2462                }
2463                // The scalar is materialized on the grid it is evaluated on, so an output on another
2464                // grid would address positions the scalar does not have.
2465                ensure_grid(&self.output, input_grid, "vector()")?;
2466            }
2467            NativeExpr::Instant { input, op } => {
2468                input.validate()?;
2469                // An instant selection reads raw samples and stamps them onto its own grid: an
2470                // evaluated vector is already stamped, and a scalar has no timestamps at all.
2471                match &input.output {
2472                    NativeType::Samples(schema) if schema.eval_grid.is_none() => {}
2473                    NativeType::Samples(_) => {
2474                        return Err(invalid("an instant selection reads evaluated values"));
2475                    }
2476                    other => {
2477                        return Err(invalid(&format!(
2478                            "an instant selection consumes raw samples, not {}",
2479                            other.describe()
2480                        )));
2481                    }
2482                }
2483                ensure_not_interleaved(input)?;
2484                ensure_samples(&self.output, "an instant selection")?;
2485                // A selection is one source row per grid point: `select_instants` picks row
2486                // indices and every field is taken at them, so it carries one value per input
2487                // field.
2488                ensure_same_fields(&input.output, &self.output, "an instant selection")?;
2489                ensure_grid(&self.output, &op.output_grid, "an instant selection")?;
2490            }
2491            NativeExpr::Merge { input } => {
2492                input.validate()?;
2493                // A merge canonicalizes evaluated fragments, so an evaluated vector is the whole of
2494                // what it needs of its input: [`merge_shape_supported`] is that check, and its
2495                // documentation says why no shape of tree above those fragments matters.
2496                let Some((_input_schema, input_grid)) = merge_shape_supported(input) else {
2497                    return Err(invalid(&format!(
2498                        "a merge consumes an evaluated vector, not {}",
2499                        input.output.describe()
2500                    )));
2501                };
2502                ensure_samples(&self.output, "a merge")?;
2503                ensure_same_fields(&input.output, &self.output, "a merge")?;
2504                ensure_grid(&self.output, input_grid, "a merge")?;
2505            }
2506            NativeExpr::Window { input, op } => {
2507                input.validate()?;
2508                // A window reads a range of samples per grid point, so it consumes samples: state
2509                // is not a sample stream and a scalar has no timestamps.
2510                let NativeType::Samples(schema) = &input.output else {
2511                    return Err(invalid(&format!(
2512                        "a window consumes samples, not {}",
2513                        input.output.describe()
2514                    )));
2515                };
2516                // A range that is not positive reads nothing at every grid point.
2517                if op.window.range_ms <= 0 {
2518                    return Err(invalid(
2519                        "a window reads an empty range: its range must be positive",
2520                    ));
2521                }
2522                ensure_not_interleaved(input)?;
2523                // What is checked here and just below is that the declared input grid equals the
2524                // input's grid, and that the output grid matches the declared one. That the grid
2525                // covers the window's read range
2526                // `(out.start - offset - range, out.end - offset]` is not checked here: only a
2527                // subquery feeds an evaluated input to a window, and deriving that coverage is the
2528                // compiler's, which builds the subquery's child grid to span it.
2529                match (op.input_grid.as_ref(), schema.eval_grid.as_ref()) {
2530                    (None, None) => {}
2531                    (Some(bound), Some(actual)) if bound.spec() == actual.spec() => {}
2532                    _ => {
2533                        return Err(invalid(
2534                            "a window's declared input grid is not the input's grid",
2535                        ));
2536                    }
2537                }
2538                ensure_samples(&self.output, "a window")?;
2539                ensure_same_fields(&input.output, &self.output, "a window")?;
2540                ensure_grid(&self.output, &op.output_grid, "a window")?;
2541            }
2542            NativeExpr::Map { input, op } => {
2543                input.validate()?;
2544                // A map is point-wise over an evaluated vector: raw samples have no shared
2545                // positions to be point-wise over, and a scalar is not a vector.
2546                let Some((_, input_grid)) = evaluated_vector(&input.output) else {
2547                    return Err(invalid(&format!(
2548                        "a map consumes an evaluated vector, not {}",
2549                        input.output.describe()
2550                    )));
2551                };
2552                if op.ops.is_empty() {
2553                    return Err(invalid("a map holds no operation"));
2554                }
2555                ensure_samples(&self.output, "a map")?;
2556                ensure_same_fields(&input.output, &self.output, "a map")?;
2557                ensure_grid(&self.output, input_grid, "a map")?;
2558            }
2559            NativeExpr::ParameterizedMap {
2560                input,
2561                op,
2562                parameters,
2563            } => {
2564                input.validate()?;
2565                // `max_of` and `min_of` are functions of two scalars, so their input is the first
2566                // of the two rather than a vector's fields; every other function here maps an
2567                // evaluated vector and answers one of the same shape.
2568                let input_grid = if op.takes_a_scalar_input() {
2569                    let NativeType::Scalar(input_grid) = &input.output else {
2570                        return Err(invalid(&format!(
2571                            "{op:?} consumes a scalar, not {}",
2572                            input.output.describe()
2573                        )));
2574                    };
2575                    Arc::clone(input_grid)
2576                } else {
2577                    let Some((_, input_grid)) = evaluated_vector(&input.output) else {
2578                        return Err(invalid(&format!(
2579                            "a map consumes an evaluated vector, not {}",
2580                            input.output.describe()
2581                        )));
2582                    };
2583                    Arc::clone(input_grid)
2584                };
2585                if parameters.len() != op.arity() {
2586                    return Err(invalid(&format!(
2587                        "{op:?} reads {} parameter(s), but {} are bound",
2588                        op.arity(),
2589                        parameters.len()
2590                    )));
2591                }
2592                for parameter in parameters {
2593                    parameter.validate()?;
2594                    if !matches!(&parameter.output, NativeType::Scalar(grid) if grid.spec() == input_grid.spec())
2595                    {
2596                        return Err(invalid(
2597                            "a map parameter is not a scalar on its input's grid",
2598                        ));
2599                    }
2600                }
2601                if op.takes_a_scalar_input() {
2602                    if !matches!(&self.output, NativeType::Scalar(grid) if grid.spec() == input_grid.spec())
2603                    {
2604                        return Err(invalid(
2605                            "a map over a scalar does not answer a scalar on its input's grid",
2606                        ));
2607                    }
2608                } else {
2609                    ensure_samples(&self.output, "a parameterized map")?;
2610                    ensure_same_fields(&input.output, &self.output, "a parameterized map")?;
2611                    ensure_grid(&self.output, &input_grid, "a parameterized map")?;
2612                }
2613            }
2614            NativeExpr::ParameterizedTopK {
2615                input,
2616                op,
2617                parameter,
2618            } => {
2619                input.validate()?;
2620                parameter.validate()?;
2621                if !matches!(op, BoundVectorOp::TopK { .. }) {
2622                    return Err(invalid("a parameterized topk operation is not TopK"));
2623                }
2624                let Some((_, output_grid)) = evaluated_vector(&self.output) else {
2625                    return Err(invalid(
2626                        "a parameterized topk does not produce an evaluated vector",
2627                    ));
2628                };
2629                if !matches!(&parameter.output, NativeType::Scalar(grid) if grid.spec() == output_grid.spec())
2630                {
2631                    return Err(invalid(
2632                        "a topk parameter is not a scalar on its output grid",
2633                    ));
2634                }
2635                let Some((_, input_grid)) = evaluated_vector(&input.output) else {
2636                    return Err(invalid("a parameterized topk consumes a non-vector"));
2637                };
2638                ensure_same_fields(&input.output, &self.output, "a vector operation")?;
2639                ensure_grid(&input.output, input_grid, "a vector operation")?;
2640                ensure_grid(&self.output, input_grid, "a vector operation")?;
2641            }
2642            NativeExpr::ParameterizedHistogram {
2643                input,
2644                op,
2645                parameters,
2646            } => {
2647                input.validate()?;
2648                if !matches!(op, BoundVectorOp::Histogram(_)) {
2649                    return Err(invalid(
2650                        "a parameterized histogram operation is not Histogram",
2651                    ));
2652                }
2653                let expected = match op {
2654                    BoundVectorOp::Histogram(HistogramFunction::Quantile(_)) => 1,
2655                    BoundVectorOp::Histogram(HistogramFunction::Fraction { .. }) => 2,
2656                    _ => {
2657                        return Err(invalid(
2658                            "parameterized histogram operation is not Histogram",
2659                        ));
2660                    }
2661                };
2662                if parameters.len() != expected {
2663                    return Err(invalid("parameterized histogram has the wrong arity"));
2664                }
2665                let Some((_, input_grid)) = evaluated_vector(&input.output) else {
2666                    return Err(invalid("a parameterized histogram consumes a non-vector"));
2667                };
2668                for parameter in parameters {
2669                    parameter.validate()?;
2670                    if !matches!(&parameter.output, NativeType::Scalar(grid) if grid.spec() == input_grid.spec())
2671                    {
2672                        return Err(invalid(
2673                            "a histogram parameter is not a scalar on its input grid",
2674                        ));
2675                    }
2676                }
2677                ensure_same_fields(&input.output, &self.output, "a vector operation")?;
2678                ensure_grid(&self.output, input_grid, "a vector operation")?;
2679            }
2680            NativeExpr::Vector { input, .. } => {
2681                input.validate()?;
2682                // A vector operation keeps the input's fields and grid, so it consumes and produces
2683                // the same evaluated vector.
2684                let Some((_, input_grid)) = evaluated_vector(&input.output) else {
2685                    return Err(invalid(&format!(
2686                        "a vector operation consumes an evaluated vector, not {}",
2687                        input.output.describe()
2688                    )));
2689                };
2690                ensure_samples(&self.output, "a vector operation")?;
2691                ensure_same_fields(&input.output, &self.output, "a vector operation")?;
2692                ensure_grid(&self.output, input_grid, "a vector operation")?;
2693            }
2694            NativeExpr::Timestamp { input } => {
2695                input.validate()?;
2696                let Some((_, input_grid)) = evaluated_vector(&input.output) else {
2697                    return Err(invalid("timestamp consumes an evaluated vector"));
2698                };
2699                ensure_samples(&self.output, "timestamp")?;
2700                ensure_same_fields(&input.output, &self.output, "timestamp")?;
2701                ensure_grid(&self.output, input_grid, "timestamp")?;
2702            }
2703            NativeExpr::Aggregate { input, op } => {
2704                input.validate()?;
2705                // A stage's contract is a pair of types, not only what it produces: `Partial`
2706                // turns a vector into state and `Final` turns state back into a vector, so state
2707                // never sits where a value is expected and a value never sits where state is.
2708                match op.stage {
2709                    AggregateStage::Complete => {
2710                        // Every contribution lies within this execution: vector in, vector out,
2711                        // both on the input's grid, one value per input field.
2712                        let Some((_, input_grid)) = evaluated_vector(&input.output) else {
2713                            return Err(invalid(&format!(
2714                                "a complete aggregate consumes an evaluated vector, not {}",
2715                                input.output.describe()
2716                            )));
2717                        };
2718                        ensure_samples(&self.output, "a complete aggregate")?;
2719                        ensure_same_fields(&input.output, &self.output, "a complete aggregate")?;
2720                        ensure_grid(&self.output, input_grid, "a complete aggregate")?;
2721                    }
2722                    AggregateStage::Partial => {
2723                        // Only this execution's contributions were seen, so the output is state
2724                        // for a later merge: on the input's grid, grouped the same way, one
2725                        // accumulator per input field.
2726                        let Some((input_schema, input_grid)) = evaluated_vector(&input.output)
2727                        else {
2728                            return Err(invalid(&format!(
2729                                "a partial aggregate consumes an evaluated vector, not {}",
2730                                input.output.describe()
2731                            )));
2732                        };
2733                        let NativeType::AggregateState(state) = &self.output else {
2734                            return Err(invalid(&format!(
2735                                "a partial aggregate produces aggregate state, not {}",
2736                                self.output.describe()
2737                            )));
2738                        };
2739                        ensure_field_count(
2740                            state.accumulators.len(),
2741                            input_schema.fields.len(),
2742                            "a partial aggregate",
2743                        )?;
2744                        let Some((expected_kind, expected_components)) =
2745                            aggregate_state_binding(op.kind, op.field_kind)
2746                        else {
2747                            return Err(DataFusionError::NotImplemented(format!(
2748                                "aggregate state is not defined for {:?}",
2749                                op.kind
2750                            )));
2751                        };
2752                        if state.kind != expected_kind
2753                            || state.components.as_ref() != expected_components
2754                        {
2755                            return Err(DataFusionError::NotImplemented(format!(
2756                                "partial {:?} aggregate requires state kind {:?} with components {:?}, found {:?} with {:?}",
2757                                op.kind,
2758                                expected_kind,
2759                                expected_components,
2760                                state.kind,
2761                                state.components
2762                            )));
2763                        }
2764                        if state.grid.spec() != input_grid.spec() {
2765                            return Err(invalid(
2766                                "aggregate state is indexed on a grid the input does not produce",
2767                            ));
2768                        }
2769                        if state.group != op.group {
2770                            return Err(invalid(
2771                                "aggregate state groups differ from the binding: state built for \
2772                                 one `by` or `without` cannot be merged into another",
2773                            ));
2774                        }
2775                    }
2776                    AggregateStage::Final => {
2777                        // The state was collected from every contributing execution, so the
2778                        // output is the complete value on the grid that state is indexed on.
2779                        let NativeType::AggregateState(state) = &input.output else {
2780                            return Err(invalid(&format!(
2781                                "a final aggregate consumes aggregate state, not {}",
2782                                input.output.describe()
2783                            )));
2784                        };
2785                        let Some((expected_kind, expected_components)) =
2786                            aggregate_state_binding(op.kind, op.field_kind)
2787                        else {
2788                            return Err(DataFusionError::NotImplemented(format!(
2789                                "aggregate state is not defined for {:?}",
2790                                op.kind
2791                            )));
2792                        };
2793                        if state.kind != expected_kind
2794                            || state.components.as_ref() != expected_components
2795                        {
2796                            return Err(DataFusionError::NotImplemented(format!(
2797                                "final {:?} aggregate requires state kind {:?} with components {:?}, found {:?} with {:?}",
2798                                op.kind,
2799                                expected_kind,
2800                                expected_components,
2801                                state.kind,
2802                                state.components
2803                            )));
2804                        }
2805                        if state.group != op.group {
2806                            return Err(invalid(
2807                                "aggregate state groups differ from the binding: state built for \
2808                                 one `by` or `without` cannot be merged into another",
2809                            ));
2810                        }
2811                        let output = ensure_samples(&self.output, "a final aggregate")?;
2812                        // The merged value carries one value per accumulator the state holds.
2813                        ensure_field_count(
2814                            output.fields.len(),
2815                            state.accumulators.len(),
2816                            "a final aggregate",
2817                        )?;
2818                        ensure_grid(&self.output, &state.grid, "a final aggregate")?;
2819                    }
2820                }
2821            }
2822            NativeExpr::ParameterizedAggregate {
2823                input,
2824                op,
2825                parameter,
2826            } => {
2827                input.validate()?;
2828                parameter.validate()?;
2829                // The parameter is read off the chunk its node hands over, once per grid point, so
2830                // it has to be a scalar the node answers a series for -- `scalar()`, `time()` and
2831                // the like all do. A literal has no chunk of its own: its value is on the binding
2832                // of a node that carries it, and a fold that never receives one would run to the
2833                // end of its input and fail instead of folding. A query that writes a constant gets
2834                // the constant path, which binds the number on the fold itself; a tree that reaches
2835                // here with one was not built by the compiler, so it is refused before it runs.
2836                if matches!(parameter.expr, NativeExpr::Scalar(_)) {
2837                    return Err(invalid(
2838                        "a parameterized aggregate reads a parameter node that hands over a \
2839                         scalar series, not a literal",
2840                    ));
2841                }
2842                // Only a `quantile` takes an argument a query reads per point: it is the one
2843                // aggregate whose argument is a value rather than a name, and every other kind
2844                // binds its parameter into its own op (or is not an aggregate at all).
2845                if !matches!(op.kind, AggregateKind::Quantile { .. }) {
2846                    return Err(invalid(
2847                        "a parameterized aggregate that is not a `quantile`",
2848                    ));
2849                }
2850                // A quantile answers from its group's whole sample set, so it keeps no state: the
2851                // stage that reads a parameter is the one that folds, exactly as for the bound `φ`.
2852                if op.stage != AggregateStage::Complete {
2853                    return Err(invalid(
2854                        "a parameterized aggregate at a stage other than `Complete`",
2855                    ));
2856                }
2857                // The parameter is read at every point the fold answers, one value per point and no
2858                // labels, so it is a scalar on the grid the answer is stamped on.
2859                let Some((_, output_grid)) = evaluated_vector(&self.output) else {
2860                    return Err(invalid(
2861                        "a parameterized aggregate does not produce an evaluated vector",
2862                    ));
2863                };
2864                if !matches!(&parameter.output, NativeType::Scalar(grid) if grid.spec() == output_grid.spec())
2865                {
2866                    return Err(invalid(
2867                        "an aggregate parameter is not a scalar on its output grid",
2868                    ));
2869                }
2870                let Some((_, input_grid)) = evaluated_vector(&input.output) else {
2871                    return Err(invalid(&format!(
2872                        "a complete aggregate consumes an evaluated vector, not {}",
2873                        input.output.describe()
2874                    )));
2875                };
2876                ensure_same_fields(
2877                    &input.output,
2878                    &self.output,
2879                    "a parameterized complete aggregate",
2880                )?;
2881                ensure_grid(
2882                    &self.output,
2883                    input_grid,
2884                    "a parameterized complete aggregate",
2885                )?;
2886            }
2887            NativeExpr::Binary { left, right, .. } => {
2888                left.validate()?;
2889                right.validate()?;
2890                // A binary operation is point-wise, so both sides are evaluated on the statement's
2891                // grid: state has no positions at all, and raw samples carry their own timestamps
2892                // instead of positions on a shared grid.
2893                let Some(left_grid) = left.output.grid() else {
2894                    return Err(invalid(&format!(
2895                        "a binary operation consumes evaluated values, not {} on its left",
2896                        left.output.describe()
2897                    )));
2898                };
2899                let Some(right_grid) = right.output.grid() else {
2900                    return Err(invalid(&format!(
2901                        "a binary operation consumes evaluated values, not {} on its right",
2902                        right.output.describe()
2903                    )));
2904                };
2905                if left_grid.spec() != right_grid.spec() {
2906                    return Err(invalid("a binary operation aligns two different grids"));
2907                }
2908                match (&left.output, &right.output) {
2909                    // Two scalars make a scalar: there is nothing to match and nothing to keep.
2910                    (NativeType::Scalar(_), NativeType::Scalar(_)) => {
2911                        if !matches!(&self.output, NativeType::Scalar(grid) if grid.spec() == left_grid.spec())
2912                        {
2913                            return Err(invalid(
2914                                "two scalars do not produce a scalar on the statement's grid",
2915                            ));
2916                        }
2917                    }
2918                    // A scalar side carries no labels and no fields, so the operation is a
2919                    // broadcast on the statement's grid and `matching` is not consulted. A scalar
2920                    // has no fields of its own, so the broadcast keeps the vector side's fields.
2921                    (NativeType::Scalar(_), NativeType::Samples(vector))
2922                    | (NativeType::Samples(vector), NativeType::Scalar(_)) => {
2923                        let Some(output) = self.output.samples() else {
2924                            return Err(invalid(&format!(
2925                                "a scalar broadcast produces the vector side's samples, not {}",
2926                                self.output.describe()
2927                            )));
2928                        };
2929                        ensure_grid(&self.output, left_grid, "a scalar broadcast")?;
2930                        if output.fields.len() != vector.fields.len() {
2931                            return Err(invalid(
2932                                "a scalar broadcast does not produce the vector side's fields",
2933                            ));
2934                        }
2935                    }
2936                    // Two vectors are matched by `matching` on the grid they share, and the match
2937                    // pairs fields by position, so it keeps the shorter side's fields.
2938                    (NativeType::Samples(left_vector), NativeType::Samples(right_vector)) => {
2939                        let Some(output) = self.output.samples() else {
2940                            return Err(invalid(&format!(
2941                                "a binary operation over two vectors produces samples, not {}",
2942                                self.output.describe()
2943                            )));
2944                        };
2945                        ensure_field_count(
2946                            output.fields.len(),
2947                            left_vector.fields.len().min(right_vector.fields.len()),
2948                            "a binary operation over two vectors",
2949                        )?;
2950                        ensure_grid(&self.output, left_grid, "a binary operation")?;
2951                    }
2952                    // State has no grid, so the grid checks above return for either side before
2953                    // this match and these two arms cannot be reached at run time. They are
2954                    // spelled out because `NativeType` names `AggregateState` and the match has to
2955                    // cover the pair; the message says so rather than pretending a value arrived.
2956                    (NativeType::AggregateState(_), _) | (_, NativeType::AggregateState(_)) => {
2957                        return Err(invalid(
2958                            "a binary operation reached aggregate state, which has no grid: the \
2959                             grid check above should have rejected it",
2960                        ));
2961                    }
2962                }
2963            }
2964            NativeExpr::Set { left, right, .. } => {
2965                left.validate()?;
2966                right.validate()?;
2967                // A set operation keeps samples of whole vectors on the grid both share: a scalar
2968                // has no labels to match, and PromQL refuses it on either side.
2969                let Some((left_schema, left_grid)) = evaluated_vector(&left.output) else {
2970                    return Err(invalid(&format!(
2971                        "a set operation consumes evaluated vectors, not {} on its left",
2972                        left.output.describe()
2973                    )));
2974                };
2975                let Some((right_schema, right_grid)) = evaluated_vector(&right.output) else {
2976                    return Err(invalid(&format!(
2977                        "a set operation consumes evaluated vectors, not {} on its right",
2978                        right.output.describe()
2979                    )));
2980                };
2981                if left_grid.spec() != right_grid.spec() {
2982                    return Err(invalid("a set operation aligns two different grids"));
2983                }
2984                // `or` hands the right side's samples on under the left side's fields, so the
2985                // kernel pairs every field by position and refuses sides of different counts.
2986                if left_schema.fields.len() != right_schema.fields.len() {
2987                    return Err(invalid(&format!(
2988                        "a set operation pairs fields by position, and its sides carry {} and {}",
2989                        left_schema.fields.len(),
2990                        right_schema.fields.len()
2991                    )));
2992                }
2993                ensure_samples(&self.output, "a set operation")?;
2994                ensure_same_fields(&left.output, &self.output, "a set operation")?;
2995                ensure_grid(&self.output, left_grid, "a set operation")?;
2996            }
2997            NativeExpr::Info { base, info, .. } => {
2998                base.validate()?;
2999                info.validate()?;
3000                let Some((_, base_grid)) = evaluated_vector(&base.output) else {
3001                    return Err(invalid(&format!(
3002                        "info consumes an evaluated vector, not {}",
3003                        base.output.describe()
3004                    )));
3005                };
3006                // The kernel reads the info side's values as sample times, which only an instant
3007                // selection that reports them produces. A canonical merge above that selection only
3008                // collects the pieces of one label set into one series, so it hands the times on
3009                // unchanged and the check looks through it. Nothing else is looked through: an
3010                // evaluated value vector is not a set of sample times, and reading one as times
3011                // would compare a sample's value against another's.
3012                let mut source = info.as_ref();
3013                while let NativeExpr::Merge { input } = &source.expr {
3014                    source = input;
3015                }
3016                let NativeExpr::Instant { op, .. } = &source.expr else {
3017                    return Err(invalid(
3018                        "info reads its info series from an instant selection",
3019                    ));
3020                };
3021                if op.value != InstantValue::InfoTimestamp {
3022                    return Err(invalid(
3023                        "info reads the sample times of its info series, not their values",
3024                    ));
3025                }
3026                let Some((info_schema, info_grid)) = evaluated_vector(&info.output) else {
3027                    return Err(invalid("info's info series are not an evaluated vector"));
3028                };
3029                if info_schema.fields.len() != 1 {
3030                    return Err(invalid(&format!(
3031                        "info reads one sample time per info series, and its info series carry {} \
3032                         fields",
3033                        info_schema.fields.len()
3034                    )));
3035                }
3036                if base_grid.spec() != info_grid.spec() {
3037                    return Err(invalid("info aligns two different grids"));
3038                }
3039                ensure_samples(&self.output, "info")?;
3040                ensure_same_fields(&base.output, &self.output, "info")?;
3041                ensure_grid(&self.output, base_grid, "info")?;
3042            }
3043        }
3044        Ok(())
3045    }
3046}
3047
3048/// Whether a binary operation drops the metric name when one side is a scalar broadcast.
3049///
3050/// `BroadcastRuntime::drops_labels` in [`execute`](crate::native::execute) is the rule the runtime
3051/// applies: arithmetic and a `bool` comparison answer a series under the metric name dropped, and a
3052/// filtering comparison keeps the label set it read.
3053fn broadcast_drops_labels(matching: &BinaryMatching) -> bool {
3054    !matching.op.is_comparison() || matching.return_bool
3055}
3056
3057/// Whether `node` hands over one logical series per canonical label set, or several.
3058///
3059/// This is the rule the runtime collectors use to decide whether a consumer above `node` has to
3060/// collect what `node` emits. `RuntimeNode::build` in [`execute`](crate::native::execute) and the
3061/// Window and `limitk` collectors share this predicate so their decisions cannot disagree.
3062///
3063/// Three answers, because what a consumer may do about a contribution carries two facts and a
3064/// boundary answers neither:
3065///
3066/// - `Some(true)`: the output is one series per canonical label set, established here, so a
3067///   consumer that needs one unified series already has it and collects nothing.
3068/// - `Some(false)`: the output may hold several series of one label set, and this node *says so*,
3069///   so a consumer that needs one unified series collects them through `MergeInput`. A
3070///   [`NativeExpr::Merge`] above such a node would make it stream an already-merged series and
3071///   turn that collection off.
3072/// - `None`: the output may hold several, and this node says nothing: it has neither a proof to
3073///   offer nor a report to make. Only a boundary ([`NativeExpr::Input`]) answers this, and a node
3074///   that hands its input's series back unchanged passes the answer on. Runtime collectors leave
3075///   this case alone because they collect only when the answer is `Some(false)`.
3076///
3077/// The collection condition is `matches!(answer, Some(false))`: the Window `MergeInput` collector
3078/// at runtime and the `limitk` collector both ask this predicate of their input.
3079///
3080/// `source_tags` and `source_metrics` are the same facts
3081/// [`duplicates_canonical_labels`] judges a whole label set by, indexed the same way: a node that
3082/// drops the metadata labels reports fragments only when
3083/// [`metadata_labels_keep_series_apart`] cannot prove the labels tell its series apart. That is the
3084/// whole of the drop's proof, so this predicate and the canonical pass cannot disagree about a drop:
3085/// a `NULL`/`''` pair in one key column is outside it for both, and the statements the pair leaves
3086/// unproved are counted by [`leaves_a_drop_to_the_storage_keys`] rather than collected.
3087///
3088/// This predicate is only ever asked of a node by the consumer directly above it - the `Window`
3089/// `MergeInput` collector and the `limitk` one, both in [`execute`](crate::native::execute) - and
3090/// that is exactly where the canonical pass puts its [`NativeExpr::Merge`] when a collection is
3091/// needed: it collects the input of a `Window`, an `Aggregate`, a `Vector`, a `Map`, a
3092/// `ParameterizedMap` and each side of a `Binary`/`Set`/`Info`
3093/// ([`merge_label_rewrites`](crate::native::canonicalize::merge_label_rewrites)). The collector
3094/// then reads the merge's `Some(true)` - a merge *is* the collection - so the weaker answer this
3095/// function gives about the node beneath it is never the one acted on. Where the pass left the tree
3096/// alone, the proof held, and the answer asked here is the same one. A caller without these facts
3097/// (placement, which reads a tree without a binding) passes empty slices and gets the conservative
3098/// answer.
3099#[allow(clippy::match_same_arms)] // Keep each expression's contribution guarantee explicit.
3100pub fn unifies_its_own_contributions(
3101    node: &NativeNode,
3102    source_tags: &[Vec<String>],
3103    source_metrics: &[Option<Arc<str>>],
3104) -> Option<bool> {
3105    match &node.expr {
3106        // A boundary hands over the pieces some upstream execution produced: what it holds is one
3107        // storage series at a time for a scan and one partition's fragments of a label set for an
3108        // exchange, and nothing in the tree can tell which series those fragments belong to. A
3109        // merge binds samples evaluated on a grid rather than proving the pieces are one series
3110        // per label set, so a proof is not this function's to give: it answers `None`. Runtime
3111        // collectors gather only when this node reports fragments with `Some(false)`.
3112        NativeExpr::Input(_) => None,
3113        // A constant holds no label set at all, so it has nothing that could arrive twice.
3114        NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } | NativeExpr::VectorOf { .. } => {
3115            Some(true)
3116        }
3117        // A selection reads raw samples - `validate` refuses an evaluated input - and raw samples
3118        // arrive one whole storage series at a time, so it answers one series per series it read,
3119        // under the label set it read. `timestamp(x)` is the exception: it reports the sample's own
3120        // time under the metric name dropped, which can give two series one label set.
3121        NativeExpr::Instant { input, op } => {
3122            if op.value == InstantValue::Timestamp {
3123                // `timestamp` drops the metadata labels, so what it emits aliases unless the drop
3124                // provably tells its series apart. The labels half is asked here; the keys half is
3125                // what the pass collects with, above this node - see this function's docs.
3126                Some(metadata_labels_keep_series_apart(
3127                    input,
3128                    source_tags,
3129                    source_metrics,
3130                ))
3131            } else {
3132                Some(true)
3133            }
3134        }
3135        // The merge is the collection: whatever its input handed over, it groups the fragments by
3136        // canonical label set and emits one series per set, so what it emits shares none.
3137        NativeExpr::Merge { .. } => Some(true),
3138        // A window answers three ways, and what the function does to labels decides the first:
3139        //
3140        // - the function drops the metric name, so what it emits can coincide with another series'
3141        //   label set whatever its input held: `Some(false)` (this is a real report, and the case
3142        //   `Map`, `Timestamp` and a label-dropping broadcast are in);
3143        // - the function keeps the metric name, and the child answers one series per label set -
3144        //   `Some(true)` - or reports fragments the window's `MergeInput` collects - `Some(false)`.
3145        //   Either way the window emits one series per label set and answers `Some(true)`: an
3146        //   already-unified child keeps that property through the labels the window retains, and
3147        //   fragments are collected before the window folds them;
3148        // - the function keeps the metric name, but the child is a boundary - `None`. The window
3149        //   folds each contribution on its own, so what it emits does alias its input's fragments,
3150        //   and `Some(false)` is exact.
3151        NativeExpr::Window { input, op } => {
3152            let child = unifies_its_own_contributions(input, source_tags, source_metrics);
3153            if child.is_none() {
3154                // A boundary hands the pieces of one series over one at a time, and the window folds
3155                // them without ever seeing the whole series: what it emits aliases whatever the
3156                // labels say.
3157                Some(false)
3158            } else if op.function.drops_metric_name() {
3159                // The function drops the metadata labels, so the window answers `Some(true)` exactly
3160                // when the labels say the drop tells its input's series apart. The keys half is the
3161                // pass's to ask: where it fails, the pass has already put its merge above this
3162                // window and the collector reads that merge's answer - see this function's docs.
3163                Some(metadata_labels_keep_series_apart(
3164                    input,
3165                    source_tags,
3166                    source_metrics,
3167                ))
3168            } else {
3169                Some(true)
3170            }
3171        }
3172        // A map can rewrite labels, so two series can end under one label set: what it hands out is
3173        // not one series per set until a canonical merge has collected the set.
3174        NativeExpr::Map { .. } | NativeExpr::ParameterizedMap { .. } => Some(false),
3175        // `topk` hands back the series it read with their labels, so the input's answer is its own -
3176        // exactly as for the bound operation.
3177        NativeExpr::ParameterizedTopK { input, .. } => {
3178            unifies_its_own_contributions(input, source_tags, source_metrics)
3179        }
3180        // A histogram function groups its rows by label set itself, so it emits one series per set.
3181        NativeExpr::ParameterizedHistogram { .. } => Some(true),
3182        // `scalar()` answers one value per point, which is not several series.
3183        NativeExpr::ScalarOf { .. } => Some(true),
3184        // A timestamp reports a position under the metadata labels dropped, and the labels half
3185        // asked here is answered for the same reason the `timestamp` selection's is: the keys half
3186        // is the one the pass turns into a merge above this node - see this function's docs.
3187        NativeExpr::Timestamp { input } => Some(metadata_labels_keep_series_apart(
3188            input,
3189            source_tags,
3190            source_metrics,
3191        )),
3192        NativeExpr::Binary {
3193            left,
3194            right,
3195            matching,
3196        } => {
3197            if evaluated_vector(&left.output).is_some() && evaluated_vector(&right.output).is_some()
3198            {
3199                // Two vectors are matched by the kernel, which files its rows by the label set a
3200                // sample ends under and emits one series per set.
3201                Some(true)
3202            } else if broadcast_drops_labels(matching) {
3203                // A broadcast whose operation drops the metric name can give two series of its
3204                // vector side one label set.
3205                Some(false)
3206            } else {
3207                // A filtering comparison keeps the label set it read, so the side that carries
3208                // series answers for this node. Which side that is follows the rule the runtime's
3209                // broadcast matches on: an evaluated vector carries them, and with two scalars the
3210                // carrier is the side that is not a bound constant (`broadcast_runtime`'s
3211                // `literal(left).is_none()`), which is what the second test below reads.
3212                //
3213                // The two selection rules agree wherever it is observable: every scalar node kind
3214                // answers `Some(true)` (`Scalar`, `EvalTime`, `VectorOf`), so a scalar-scalar pair
3215                // answers `Some(true)` whichever side is named and a consumer collects nothing
3216                // either way. The constant check is still what keeps the two readers describing
3217                // the same node rather than coinciding by accident.
3218                let carries_series = |node: &NativeNode| {
3219                    if node.output.samples().is_some() {
3220                        return true;
3221                    }
3222                    !matches!(node.expr, NativeExpr::Scalar(BoundScalar { .. }))
3223                };
3224                let vector = if carries_series(left) { left } else { right };
3225                unifies_its_own_contributions(vector, source_tags, source_metrics)
3226            }
3227        }
3228        // A set operation keeps each side's samples and files them by label set, one series per
3229        // set.
3230        NativeExpr::Set { .. } => Some(true),
3231        // `info` indexes the info side by identifying labels and merges the results that share a
3232        // label set.
3233        NativeExpr::Info { .. } => Some(true),
3234        // A finished aggregate emits one series per group, and two groups are two label sets.
3235        // `Partial` state is not a series at all, which is not several either. A per-point parameter
3236        // does not change that: the labels a group is filed under are its grouping's.
3237        NativeExpr::Aggregate { .. } | NativeExpr::ParameterizedAggregate { .. } => Some(true),
3238        // `topk`, `limit_ratio` and `sort` hand back the series they read with their labels, so the
3239        // input's answer is theirs. The four that read the whole vector - `limitk`, `absent`,
3240        // `histogram_*` and `count_values` - emit one series per label set: `limitk` counts series
3241        // in input order, so its input carries the merge the runtime performs when that input reports fragments, and the other three group their rows
3242        // by label set themselves.
3243        NativeExpr::Vector { input, op } => {
3244            let whole = matches!(
3245                op,
3246                BoundVectorOp::LimitK { .. }
3247                    | BoundVectorOp::Absent { .. }
3248                    | BoundVectorOp::Histogram(_)
3249                    | BoundVectorOp::CountValues { .. }
3250            );
3251            if whole {
3252                Some(true)
3253            } else {
3254                unifies_its_own_contributions(input, source_tags, source_metrics)
3255            }
3256        }
3257    }
3258}
3259
3260/// The schema and grid of an evaluated vector, or `None` when `ty` is raw samples, a scalar or
3261/// state.
3262///
3263/// An operation over values needs both halves: that its input is samples at all, which rules out
3264/// a scalar, and that those samples are stamped onto a grid, which rules out raw samples. The
3265/// schema comes back with the grid because a consumer that needs the grid also declares a field
3266/// layout for the fields the schema carries.
3267fn evaluated_vector(ty: &NativeType) -> Option<(&Arc<SeriesSchema>, &Arc<EvalGrid>)> {
3268    let schema = ty.samples().filter(|schema| schema.eval_grid.is_some())?;
3269    Some((schema, schema.eval_grid.as_ref()?))
3270}
3271
3272/// Checks that a node declares the field layout its input produces.
3273///
3274/// A window, a map, an instant selection and a complete aggregate all report one value per input
3275/// field, so they keep the layout of their input. A node that declares a different number of
3276/// fields than it consumes describes a computation this model has no meaning for, and letting it
3277/// through would only surface at run time as a field count mismatch against a schema the tree was
3278/// supposed to have validated.
3279fn ensure_same_fields(input: &NativeType, output: &NativeType, what: &str) -> Result<()> {
3280    let (NativeType::Samples(input), NativeType::Samples(output)) = (input, output) else {
3281        return Ok(());
3282    };
3283    ensure_field_count(output.fields.len(), input.fields.len(), what)
3284}
3285
3286/// Checks that a node declares `declared` fields where its input provides `expected`.
3287///
3288/// Some nodes compute their layout instead of keeping their input's: a final aggregate produces one
3289/// value per accumulator the state holds, and a vector-vector binary operation produces one field
3290/// per matched pair, which is the shorter side's count. Both are checked against the count the
3291/// kernel produces, so the message names the node and both numbers.
3292fn ensure_field_count(declared: usize, expected: usize, what: &str) -> Result<()> {
3293    if declared != expected {
3294        return Err(invalid(&format!(
3295            "{what} declares {declared} field(s) but its input provides {expected}"
3296        )));
3297    }
3298    Ok(())
3299}
3300
3301/// Checks that `ty` produces samples and returns them.
3302fn ensure_samples<'a>(ty: &'a NativeType, what: &str) -> Result<&'a Arc<SeriesSchema>> {
3303    ty.samples()
3304        .ok_or_else(|| invalid(&format!("{what} does not produce samples")))
3305}
3306
3307/// Checks that `ty` is evaluated on the grid `expected` describes.
3308///
3309/// The comparison is by [`EvalGrid::spec`], not by allocation: that is the rule the kernels apply
3310/// (`vector_match::same_grid`), so a compiler that allocates one grid per window but binds equal
3311/// specs produces a tree the kernel runs correctly.
3312fn ensure_grid(ty: &NativeType, expected: &Arc<EvalGrid>, what: &str) -> Result<()> {
3313    match ty.grid() {
3314        Some(actual) if actual.spec() == expected.spec() => Ok(()),
3315        Some(_) => Err(invalid(&format!(
3316            "{what} declares a grid its output does not carry"
3317        ))),
3318        None => Err(invalid(&format!("{what} produces values without a grid"))),
3319    }
3320}
3321
3322/// Checks that `input`, when it is a [`NativeExpr::Input`], does not declare interleaved series.
3323///
3324/// A native evaluation reads one series to its last chunk before the next: a range evaluator folds
3325/// a series completely before it starts another, and an instant selection's consumer collects one
3326/// series' chunks into one buffer. Neither can be handed chunks of different series that
3327/// interleave, which is the one rule both consumers state. Only an input node carries an ordering,
3328/// so only there is there one to check.
3329fn ensure_not_interleaved(input: &NativeNode) -> Result<()> {
3330    if let NativeExpr::Input(binding) = &input.expr
3331        && binding.ordering == SeriesOrdering::Interleaved
3332    {
3333        return Err(invalid(
3334            "a native evaluation reads one series to its last chunk before the next, so \
3335             interleaved chunks cannot be fed to it",
3336        ));
3337    }
3338    Ok(())
3339}
3340
3341fn invalid(reason: &str) -> DataFusionError {
3342    // A rejected tree is a compiler defect, not a query error: the compiler only builds a node
3343    // after deciding that this combination is supported. `Internal` keeps that meaning on the wire
3344    // instead of reporting a mistake in the client's statement, which `Plan` would.
3345    DataFusionError::Internal(reason.to_string())
3346}
3347
3348// Tests for native plan validation and execution contracts.
3349#[cfg(test)]
3350pub(crate) mod tests;
3351
3352impl PartialEq for BoundScalar {
3353    fn eq(&self, o: &Self) -> bool {
3354        self.value.to_bits() == o.value.to_bits()
3355    }
3356}
3357impl Eq for BoundScalar {}
3358impl std::hash::Hash for BoundScalar {
3359    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
3360        self.value.to_bits().hash(h);
3361    }
3362}
3363impl PartialEq for AggregateKind {
3364    fn eq(&self, o: &Self) -> bool {
3365        match (self, o) {
3366            (Self::Quantile { quantile: a }, Self::Quantile { quantile: b }) => {
3367                a.to_bits() == b.to_bits()
3368            }
3369            (Self::Sum, Self::Sum)
3370            | (Self::Avg, Self::Avg)
3371            | (Self::Count, Self::Count)
3372            | (Self::Min, Self::Min)
3373            | (Self::Max, Self::Max)
3374            | (Self::Group, Self::Group)
3375            | (Self::Stddev, Self::Stddev)
3376            | (Self::Stdvar, Self::Stdvar) => true,
3377            _ => false,
3378        }
3379    }
3380}
3381impl Eq for AggregateKind {}
3382impl std::hash::Hash for AggregateKind {
3383    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
3384        std::mem::discriminant(self).hash(h);
3385        if let Self::Quantile { quantile } = self {
3386            quantile.to_bits().hash(h);
3387        }
3388    }
3389}
3390
3391impl PartialEq for BoundVectorOp {
3392    fn eq(&self, o: &Self) -> bool {
3393        match (self, o) {
3394            (
3395                Self::TopK {
3396                    k: a,
3397                    top: b,
3398                    group: c,
3399                },
3400                Self::TopK {
3401                    k: x,
3402                    top: y,
3403                    group: z,
3404                },
3405            ) => a.to_bits() == x.to_bits() && b == y && c == z,
3406            (Self::LimitK { k: a, group: b }, Self::LimitK { k: x, group: y }) => {
3407                a.to_bits() == x.to_bits() && b == y
3408            }
3409            (Self::LimitRatio { ratio: a }, Self::LimitRatio { ratio: b }) => {
3410                a.to_bits() == b.to_bits()
3411            }
3412            (Self::Sort(a), Self::Sort(b)) => a == b,
3413            (Self::Absent { labels: a }, Self::Absent { labels: b }) => a == b,
3414            (Self::Histogram(a), Self::Histogram(b)) => a == b,
3415            (
3416                Self::CountValues { label: a, group: b },
3417                Self::CountValues { label: x, group: y },
3418            ) => a == x && b == y,
3419            _ => false,
3420        }
3421    }
3422}
3423impl std::hash::Hash for BoundVectorOp {
3424    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
3425        match self {
3426            Self::TopK { k, top, group } => {
3427                0u8.hash(h);
3428                k.to_bits().hash(h);
3429                top.hash(h);
3430                group.hash(h)
3431            }
3432            Self::LimitK { k, group } => {
3433                1u8.hash(h);
3434                k.to_bits().hash(h);
3435                group.hash(h)
3436            }
3437            Self::LimitRatio { ratio } => {
3438                2u8.hash(h);
3439                ratio.to_bits().hash(h)
3440            }
3441            Self::Sort(x) => {
3442                3u8.hash(h);
3443                x.hash(h)
3444            }
3445            Self::Absent { labels } => {
3446                4u8.hash(h);
3447                labels.hash(h)
3448            }
3449            Self::Histogram(x) => {
3450                5u8.hash(h);
3451                x.hash(h)
3452            }
3453            Self::CountValues { label, group } => {
3454                6u8.hash(h);
3455                label.hash(h);
3456                group.hash(h)
3457            }
3458        }
3459    }
3460}
3461impl Eq for BoundVectorOp {}