Skip to main content

promql/native/
split.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//! Where a native aggregate is split so two planes can run it.
16//!
17//! A `Complete` aggregate folds every contribution to a group, which is only correct when one
18//! execution reads all of them. A raw-series scan hands its partitions to separate executions, so the
19//! aggregate is split instead: the per-series prefix of the tree runs below the aggregate in the
20//! partitions that read series, that aggregate becomes a `Partial` one exporting the state each
21//! partition folded, and everything above it runs over the merged series.
22//!
23//! The split is structural. The innermost aggregate of the tree is replaced by an input node at its
24//! own output - that is where state enters - and the nodes above it become the suffix. What cannot be
25//! split correctly is refused with [`DataFusionError::NotImplemented`], which the planner reads as
26//! "plan this query the existing way".
27
28use std::sync::Arc;
29
30use datafusion::error::{DataFusionError, Result as DfResult};
31use datatypes::series::SeriesOrdering;
32use datatypes::series::samples::{FieldSpec, SeriesSchema};
33
34use crate::map::MathOp;
35use crate::native::plan::{
36    AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, BoundInput, BoundVectorOp,
37    Grouping, MapOp, NativeExpr, NativeNode, NativeTree, NativeType, aggregate_state_binding,
38};
39
40pub(crate) struct Split {
41    /// The per-series tree below the cut aggregate, which the producer runs.
42    prefix: NativeNode,
43    /// The tree above it, starting at the input the merged values enter at.
44    suffix: NativeNode,
45    /// The aggregate that was cut out.
46    op: BoundAggregate,
47    /// What that aggregate produces: the layout the exported state is indexed by.
48    schema: Arc<SeriesSchema>,
49    /// The suffix reads whole histograms rather than individual groups.
50    histogram: bool,
51    /// The suffix rewrites at least one label of the histogram routing key.
52    label_rewrite: bool,
53}
54
55/// Whether every histogram-routing key of this aggregate is necessarily empty.
56pub(crate) fn histogram_group_is_single(group: &Grouping) -> bool {
57    matches!(group, Grouping::By(labels) if labels.iter().all(|label| {
58        crate::histogram_eval::HISTOGRAM_ROUTING_EXCLUDED_LABELS.contains(&label.as_ref())
59    }))
60}
61
62/// Splits the innermost aggregate out of `node`.
63///
64/// `Ok(None)` is a subtree holding no aggregate. Point-wise operations can run where their groups
65/// are owned. Histogram functions can also run there when the state router co-locates every bucket
66/// and every histogram whose output labels collide. A label rewrite may change that key, so it is
67/// only admitted alongside a partitioned histogram when it cannot change a label in the cut's
68/// routing key. A single-owner histogram needs no such restriction. A histogram parameter is
69/// answered above the cut, so it has to read no series: one that does would be silently replaced by
70/// the merged values. `topk`, a second aggregate and vector-vector matching still need a whole-vector
71/// boundary.
72///
73/// An instant selection or a window over raw samples above the cut cannot be applied to the merged
74/// values under the tree's current binding: the cut output is evaluated, whereas these nodes consume
75/// raw samples. A subquery window instead reads an evaluated input, so it is admitted when its
76/// declared grid equals its direct input's grid.
77pub(crate) fn split(
78    node: &NativeNode,
79    fields: &[FieldSpec],
80    time_index: &str,
81) -> DfResult<Option<Split>> {
82    match &node.expr {
83        NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => Ok(None),
84        NativeExpr::Map { input, op } => {
85            let Some(mut inner) = split(input, fields, time_index)? else {
86                return Ok(None);
87            };
88            let changes_key = op.ops.iter().any(|op| {
89                let MapOp::Label(rewrite) = op else {
90                    return false;
91                };
92                let destination = rewrite.destination();
93                !crate::histogram_eval::HISTOGRAM_ROUTING_EXCLUDED_LABELS.contains(&destination)
94                    && match &inner.op.group {
95                        Grouping::By(labels) => {
96                            labels.iter().any(|label| label.as_ref() == destination)
97                        }
98                        Grouping::Without(labels) => {
99                            !labels.iter().any(|label| label.as_ref() == destination)
100                        }
101                    }
102            });
103            if changes_key && inner.histogram && !histogram_group_is_single(&inner.op.group) {
104                return Err(declined(
105                    "a routing-label rewrite around a partitioned histogram",
106                ));
107            }
108            inner.label_rewrite |= changes_key;
109            inner.suffix = NativeNode {
110                expr: NativeExpr::Map {
111                    input: Box::new(inner.suffix),
112                    op: op.clone(),
113                },
114                output: node.output.clone(),
115            };
116            Ok(Some(inner))
117        }
118        NativeExpr::Aggregate { input, op } => {
119            check_cut(op, fields, time_index)?;
120            match split(input, fields, time_index)? {
121                // A second aggregate above the cut folds the merged values of every group, which
122                // no partition owns on its own: it would have to be replanned as its own
123                // `Partial`/`Final` pair above the first one's result.
124                Some(_) => Err(declined("an aggregate above a split aggregate")),
125                None => {
126                    admit_prefix(input)?;
127                    let NativeType::Samples(schema) = &node.output else {
128                        return Err(declined("an aggregate that produces no values"));
129                    };
130                    if schema.eval_grid.is_none() {
131                        return Err(declined("an aggregate that produces no values"));
132                    }
133                    Ok(Some(Split {
134                        prefix: (**input).clone(),
135                        // The merged values enter the suffix as the aggregate's own output: the same
136                        // binding and the same value, which is what the tree validates, at source
137                        // `0` of the suffix's own execution - a source index is local to one
138                        // execution, so the suffix names its one input rather than inheriting the
139                        // prefix's.
140                        suffix: NativeNode {
141                            expr: NativeExpr::Input(BoundInput {
142                                source_index: 0,
143                                output: node.output.clone(),
144                                ordering: SeriesOrdering::Contiguous,
145                            }),
146                            output: node.output.clone(),
147                        },
148                        op: op.clone(),
149                        schema: Arc::clone(schema),
150                        histogram: false,
151                        label_rewrite: false,
152                    }))
153                }
154            }
155        }
156        NativeExpr::Vector {
157            input,
158            op: BoundVectorOp::Histogram(function),
159        } => {
160            let Some(mut inner) = split(input, fields, time_index)? else {
161                return Ok(None);
162            };
163            // Two histogram calls may drop different labels at successive levels (in particular,
164            // a native histogram retains `le`), so the first call's partition key is not enough.
165            if inner.histogram {
166                return Err(declined("nested histograms above a split aggregate"));
167            }
168            if inner.label_rewrite && !histogram_group_is_single(&inner.op.group) {
169                return Err(declined(
170                    "a routing-label rewrite around a partitioned histogram",
171                ));
172            }
173            inner.histogram = true;
174            inner.suffix = NativeNode {
175                expr: NativeExpr::Vector {
176                    input: Box::new(inner.suffix),
177                    op: BoundVectorOp::Histogram(*function),
178                },
179                output: node.output.clone(),
180            };
181            Ok(Some(inner))
182        }
183        // The same histogram operation with a parameter evaluated at every grid point instead of
184        // bound as a constant. The parameter is a per-point scalar - an expression of `time()` and
185        // literals - so it reads no series and means the same thing above the merged values, and
186        // the suffix carries it unchanged.
187        NativeExpr::ParameterizedHistogram {
188            input,
189            op,
190            parameters,
191        } => {
192            let Some(mut inner) = split(input, fields, time_index)? else {
193                return Ok(None);
194            };
195            // The same two refusals as the literal form: successive calls may drop different labels,
196            // so only the first call's partition key is known, and a rewrite may change that key.
197            if inner.histogram {
198                return Err(declined("nested histograms above a split aggregate"));
199            }
200            if inner.label_rewrite && !histogram_group_is_single(&inner.op.group) {
201                return Err(declined(
202                    "a routing-label rewrite around a partitioned histogram",
203                ));
204            }
205            // A parameter is answered at its own grid point rather than from the merged values, so
206            // one that reads the series the prefix reads has no source above the cut: applying it
207            // there would silently answer it from the merged state instead.
208            if parameters
209                .iter()
210                .any(|parameter| !suffix_carries(parameter))
211            {
212                return Err(declined(
213                    "a histogram parameter that reads the series the split reads",
214                ));
215            }
216            inner.histogram = true;
217            inner.suffix = NativeNode {
218                expr: NativeExpr::ParameterizedHistogram {
219                    input: Box::new(inner.suffix),
220                    op: op.clone(),
221                    parameters: parameters.clone(),
222                },
223                output: node.output.clone(),
224            };
225            Ok(Some(inner))
226        }
227        // TopK ranks the whole vector, not one histogram or aggregation group at a time.
228        NativeExpr::Vector {
229            op: BoundVectorOp::TopK { .. },
230            ..
231        } => Err(declined("a whole-vector operation above a split aggregate")),
232        // A per-point `φ` does not make the fold splittable: `check_cut` declines every `quantile`,
233        // whose state is its group's samples however its argument is read. A `ParameterizedAggregate`
234        // is only ever that fold, so there is nothing here to admit.
235        NativeExpr::ParameterizedAggregate { .. } => Err(declined("a `quantile` aggregate")),
236        // A canonical merge answers one series per canonical label set from every piece of that set,
237        // and the pieces of one set are not in one partition: a label rewrite created them after the
238        // scan split the rows. A split keeps that merge in the prefix, where it sees one partition's
239        // pieces - so two colliding series that landed in different partitions are each collected
240        // apart, the state router folds their partial states, and the statement answers a value
241        // where Prometheus reports `vector cannot contain metrics with the same labelset`.
242        //
243        // The merge therefore has to stay above every partition, and the tree keeps the plan the
244        // lowering gives a collected subtree: the merge is the boundary (`canonical_boundary_stages`
245        // builds its producer and the canonical router collects one label set from every partition),
246        // and the fold above it reads the whole series that boundary assembled. Refusing the split
247        // here is what sends the statement there instead of answering it per partition.
248        NativeExpr::Merge { .. } => Err(declined("an aggregate split across a canonical merge")),
249        // A window whose input is already evaluated - a subquery - applies to the merged values the
250        // suffix reads, provided it evaluates on a grid. The declared grid and the input's grid are
251        // already required to be the same one when the window is bound, so the cut's grid need not be
252        // that grid: a window between them may already have re-gridded the values. A raw-sample
253        // window cannot sit above the cut.
254        NativeExpr::Window { input, op } => {
255            let Some(mut inner) = split(input, fields, time_index)? else {
256                return Ok(None);
257            };
258            let input_grid = input
259                .output
260                .samples()
261                .and_then(|schema| schema.eval_grid.as_ref());
262            if input_grid.is_none() {
263                return Err(declined("a window over raw samples above an aggregate"));
264            }
265            inner.suffix = NativeNode {
266                expr: NativeExpr::Window {
267                    input: Box::new(inner.suffix),
268                    op: op.clone(),
269                },
270                output: node.output.clone(),
271            };
272            Ok(Some(inner))
273        }
274        // These read values the merged state does not answer: an instant selection or window reads
275        // raw samples, `scalar`/`vector` answers one value or one series instead of the vector, and a
276        // parameterized map reads the whole vector at a point. `ParameterizedTopK` declines here
277        // exactly like the literal `topk` above does: a per-point `k` ranks the whole vector just as
278        // a bound one does, so it needs the same whole-vector boundary. Admitting the one and
279        // refusing the other would be an inconsistency rather than a capability.
280        NativeExpr::Instant { input, .. }
281        | NativeExpr::Timestamp { input }
282        | NativeExpr::Vector { input, .. }
283        | NativeExpr::VectorOf { input }
284        | NativeExpr::ScalarOf { input }
285        | NativeExpr::ParameterizedMap { input, .. }
286        | NativeExpr::ParameterizedTopK { input, .. } => match split(input, fields, time_index)? {
287            Some(_) => Err(declined(
288                "an aggregate under an operation that reads evaluated values",
289            )),
290            None => Ok(None),
291        },
292        NativeExpr::Binary {
293            left,
294            right,
295            matching,
296        } => {
297            // Each side is split once, and at most one of them may hold the innermost aggregate: two
298            // would be two cuts, which this node cannot merge.
299            let (left_split, right_split) = (
300                split(left, fields, time_index)?,
301                split(right, fields, time_index)?,
302            );
303            // A constant operand is broadcast over whatever the other side answers, so applying the
304            // same operation to the merged values is the operation the query wrote. Any other sibling
305            // would have to be matched with those values by label, which nothing below this node
306            // gathers.
307            let (mut inner, constant_on_the_left) = match (left_split, right_split) {
308                (None, None) => return Ok(None),
309                (Some(inner), None) if matches!(right.expr, NativeExpr::Scalar(_)) => {
310                    (inner, false)
311                }
312                (None, Some(inner)) if matches!(left.expr, NativeExpr::Scalar(_)) => (inner, true),
313                _ => {
314                    return Err(declined(
315                        "an aggregate under a binary operation without a constant on the other side",
316                    ));
317                }
318            };
319            // The cut side's own suffix takes the place of the aggregate, on the side the query wrote
320            // it: a non-commutative operator means what that order says, and the matching and the
321            // output are the ones the compiler bound.
322            let (left, right) = if constant_on_the_left {
323                ((**left).clone(), inner.suffix)
324            } else {
325                (inner.suffix, (**right).clone())
326            };
327            inner.suffix = NativeNode {
328                expr: NativeExpr::Binary {
329                    left: Box::new(left),
330                    right: Box::new(right),
331                    matching: matching.clone(),
332                },
333                output: node.output.clone(),
334            };
335            Ok(Some(inner))
336        }
337        // A set operation keeps samples by whether their match group is present on the other side,
338        // which the merged values of one side cannot answer.
339        NativeExpr::Set { left, right, .. } => {
340            match (
341                split(left, fields, time_index)?,
342                split(right, fields, time_index)?,
343            ) {
344                (None, None) => Ok(None),
345                _ => Err(declined("an aggregate under a set operation")),
346            }
347        }
348        // The suffix above a split aggregate reads the merged state alone, so it has no source for
349        // the info series.
350        NativeExpr::Info { base, info, .. } => {
351            match (
352                split(base, fields, time_index)?,
353                split(info, fields, time_index)?,
354            ) {
355                (None, None) => Ok(None),
356                _ => Err(declined("an aggregate under info")),
357            }
358        }
359    }
360}
361
362/// The field names of the raw series the prefix reads, in source order.
363///
364/// Read off the tree's own raw input node, which is the one authority on what the prefix is
365/// compiled against: the root is already evaluated on the statement's grid, so its fields are the
366/// statement's value columns rather than the raw ones a `by(...)` clause would name. The prefix is
367/// one series at a time and the tree reads exactly one source, so the first raw input answers for
368/// all of them.
369pub(crate) fn prefix_fields(tree: &NativeTree) -> DfResult<Vec<FieldSpec>> {
370    tree.root()
371        .inputs()
372        .into_iter()
373        .find_map(|input| {
374            input
375                .output
376                .samples()
377                .filter(|schema| schema.eval_grid.is_none())
378                .map(|schema| schema.fields.to_vec())
379        })
380        .ok_or_else(|| declined("a tree that reads no raw series"))
381}
382
383/// Refuses an aggregate whose state the split cannot carry, and one grouped by a value field.
384///
385/// Only the eight fixed-width accumulators are carried: a quantile's state is the group's samples, and
386/// a non-`Complete` stage is a state or a merge rather than an answer. A `by(...)` naming a value field
387/// or the time index cannot be kept either - the state rows are indexed by field and by grid point,
388/// so a group that varies with either is not a group - while a label the input does not have is
389/// simply absent, exactly as it is in the existing planner.
390pub(crate) fn check_cut(
391    op: &BoundAggregate,
392    fields: &[FieldSpec],
393    time_index: &str,
394) -> DfResult<()> {
395    if op.stage != AggregateStage::Complete {
396        return Err(declined("an aggregate that is not `Complete`"));
397    }
398    if matches!(op.kind, AggregateKind::Quantile { .. }) {
399        return Err(declined("a `quantile` aggregate"));
400    }
401    if let Grouping::By(labels) = &op.group
402        && labels.iter().any(|label| {
403            label.as_ref() == time_index
404                || fields
405                    .iter()
406                    .any(|field| field.name.as_ref() == label.as_ref())
407        })
408    {
409        return Err(declined("an aggregate grouped by a value field"));
410    }
411    Ok(())
412}
413
414/// Checks that the per-series prefix is a tree one partition can evaluate on its own.
415///
416/// The producer runs one execution per partition and folds exactly the series that partition's scan
417/// returned, so the prefix has to answer one series from one series' samples: maps are point-wise, a
418/// binary operation with a constant side applies that constant to each series its other side answers,
419/// and a window or an instant selection reads the raw input itself. A raw input means no evaluation
420/// grid - a tree whose input is already evaluated is a subquery's, which one partition cannot evaluate.
421///
422/// A `clamp` whose maximum is below its minimum answers no value at all, so the fold would see a group
423/// with no sample of that field rather than the query the reader wrote.
424pub(crate) fn admit_prefix(root: &NativeNode) -> DfResult<()> {
425    let mut node = root;
426    loop {
427        match &node.expr {
428            NativeExpr::Map { input, op } => {
429                for map_op in op.ops.iter() {
430                    if let MapOp::Math(MathOp::Clamp { min, max }) = map_op
431                        && max < min
432                    {
433                        return Err(declined("a `clamp` whose maximum is below its minimum"));
434                    }
435                }
436                node = input;
437            }
438            // Only a constant side is broadcast: it reaches each series the other side answers, so
439            // that side is the one the fold runs. Two constants answer one value per grid point and
440            // read no series, and two vectors are a label match over the whole vector, which is not
441            // what either half of the split produces.
442            NativeExpr::Binary { left, right, .. } => {
443                node = match (&left.expr, &right.expr) {
444                    (NativeExpr::Scalar(_), NativeExpr::Scalar(_)) => {
445                        return Err(declined("a per-series prefix of two constants"));
446                    }
447                    (NativeExpr::Scalar(_), _) => &**right,
448                    (_, NativeExpr::Scalar(_)) => &**left,
449                    (_, _) => {
450                        return Err(declined(
451                            "a per-series prefix that matches two vectors by label",
452                        ));
453                    }
454                };
455            }
456            // A canonical merge is a `merge_same_labelset` over the pieces one scan returned, so it
457            // reads across series even inside one partition: a prefix holding one cannot promise
458            // one series per label set, which is why the split refuses it above as well.
459            NativeExpr::Merge { .. } => {
460                return Err(declined("a per-series prefix that collects a label set"));
461            }
462            _ => break,
463        }
464    }
465    let raw = |node: &NativeNode| match &node.expr {
466        NativeExpr::Input(input) => input
467            .output
468            .samples()
469            .is_some_and(|schema| schema.eval_grid.is_none()),
470        _ => false,
471    };
472    match &node.expr {
473        NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } if raw(input) => {
474            Ok(())
475        }
476        _ => Err(declined(
477            "a per-series prefix that is not one series at a time",
478        )),
479    }
480}
481
482pub(crate) fn declined(reason: &str) -> DataFusionError {
483    DataFusionError::NotImplemented(format!(
484        "the native aggregate split does not carry {reason}"
485    ))
486}
487
488/// A split aggregate as the two trees that run it, and the state they exchange between them.
489///
490/// The prefix runs where the series are read and ends at a `Partial` aggregate exporting the state
491/// each partition folded. The suffix runs where every partition's state has arrived and starts at a
492/// `Final` aggregate consuming it, so nothing above the cut sees a partial contribution.
493pub struct SplitTrees {
494    /// The prefix, with the cut aggregate bound over it as `Partial`; it answers aggregate state.
495    pub partial: NativeTree,
496    /// The `Final` aggregate over that state, and everything the split moved above the cut.
497    pub final_tree: NativeTree,
498}
499
500impl Split {
501    /// Binds this split as the two trees that run it.
502    ///
503    /// `Ok(None)` is an aggregate whose kernel keeps no mergeable state, which cannot cross a
504    /// partition boundary at all.
505    pub fn into_trees(self) -> DfResult<Option<SplitTrees>> {
506        let Self {
507            prefix,
508            suffix,
509            op,
510            schema,
511            histogram: _,
512            label_rewrite: _,
513        } = self;
514        let Some((kind, components)) = aggregate_state_binding(op.kind, op.field_kind) else {
515            return Ok(None);
516        };
517        let Some(grid) = schema.eval_grid.clone() else {
518            return Err(DataFusionError::Internal(
519                "a split aggregate has no evaluation grid".into(),
520            ));
521        };
522        let state = Arc::new(AggregateStateSchema {
523            group: op.group.clone(),
524            kind,
525            components: components.into(),
526            accumulators: schema.fields.clone(),
527            grid,
528        });
529        let partial = NativeTree::try_new(NativeNode {
530            expr: NativeExpr::Aggregate {
531                input: Box::new(prefix),
532                op: BoundAggregate {
533                    stage: AggregateStage::Partial,
534                    ..op.clone()
535                },
536            },
537            output: NativeType::AggregateState(Arc::clone(&state)),
538        })?;
539        let merged = NativeNode {
540            expr: NativeExpr::Aggregate {
541                input: Box::new(NativeNode {
542                    expr: NativeExpr::Input(BoundInput {
543                        source_index: 0,
544                        output: NativeType::AggregateState(Arc::clone(&state)),
545                        ordering: SeriesOrdering::Contiguous,
546                    }),
547                    output: NativeType::AggregateState(Arc::clone(&state)),
548                }),
549                op: BoundAggregate {
550                    stage: AggregateStage::Final,
551                    ..op
552                },
553            },
554            output: NativeType::Samples(Arc::clone(&schema)),
555        };
556        let root = enter_suffix(suffix, &merged)?;
557        Ok(Some(SplitTrees {
558            partial,
559            final_tree: NativeTree::try_new(root)?,
560        }))
561    }
562}
563
564/// Puts `merged` at the cut and returns the suffix above it.
565///
566/// A suffix is the spine of point-wise maps, constant-sided binaries, evaluated-input windows and at
567/// most one histogram operation between the cut and the root, with scalar constants and the
568/// evaluation time preserved. Other whole-vector operations are refused by `split`.
569fn enter_suffix(node: NativeNode, merged: &NativeNode) -> DfResult<NativeNode> {
570    let NativeNode { expr, output } = node;
571    let rejected = || {
572        DataFusionError::Internal("the split suffix holds an operation it does not build".into())
573    };
574    let expr = match expr {
575        NativeExpr::Input(_) => return Ok(merged.clone()),
576        // A constant carries no state: the suffix keeps it as it is, beside the merged values. The
577        // evaluation time is such a constant - it answers the grid's own timestamps, and the suffix
578        // runs on the statement's grid, so it answers the same per-point value there.
579        NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {
580            return Ok(NativeNode { expr, output });
581        }
582        // A subquery window above the cut is rebuilt over the merged values, on its own grid.
583        NativeExpr::Window { input, op } => NativeExpr::Window {
584            input: Box::new(enter_suffix(*input, merged)?),
585            op,
586        },
587        NativeExpr::Map { input, op } => NativeExpr::Map {
588            input: Box::new(enter_suffix(*input, merged)?),
589            op,
590        },
591        NativeExpr::Vector {
592            input,
593            op: op @ BoundVectorOp::Histogram(_),
594        } => NativeExpr::Vector {
595            input: Box::new(enter_suffix(*input, merged)?),
596            op,
597        },
598        // The parameters are per-point scalars that read no series - `split` refuses the split
599        // otherwise - so they mean the same above the merged values and are handed over untouched
600        // while only the input is rebuilt.
601        NativeExpr::ParameterizedHistogram {
602            input,
603            op,
604            parameters,
605        } => NativeExpr::ParameterizedHistogram {
606            input: Box::new(enter_suffix(*input, merged)?),
607            op,
608            parameters,
609        },
610        NativeExpr::Binary {
611            left,
612            right,
613            matching,
614        } => NativeExpr::Binary {
615            left: Box::new(enter_suffix(*left, merged)?),
616            right: Box::new(enter_suffix(*right, merged)?),
617            matching,
618        },
619        _ => return Err(rejected()),
620    };
621    Ok(NativeNode { expr, output })
622}
623
624/// Whether [`enter_suffix`] rebuilds this subtree without reading `merged`.
625///
626/// This is the question the histogram arm of [`split`] asks of every parameter before it is carried
627/// above the cut: a parameter that `enter_suffix` rebuilds from constants alone means the same thing
628/// there, and one that reads the series has no source above the cut. Keeping the answer exactly the
629/// set of shapes `enter_suffix` builds is what keeps a misplaced tree a decline rather than an
630/// `Internal` error: a subtree that claims to carry but does not would reach `rejected()`.
631fn suffix_carries(node: &NativeNode) -> bool {
632    match &node.expr {
633        // Constants: they answer their own values on the statement's grid.
634        NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => true,
635        // Point-wise spines over something that carries: the map and the histogram application
636        // reach each series the way they are rebuilt.
637        NativeExpr::Map { input, .. }
638        | NativeExpr::Vector {
639            input,
640            op: BoundVectorOp::Histogram(_),
641        } => suffix_carries(input),
642        // A binary operation carries when both sides do: a constant broadcast over a constant is
643        // still a constant.
644        NativeExpr::Binary { left, right, .. } => suffix_carries(left) && suffix_carries(right),
645        // Everything else reads a source: the cut's own values (`Input`), the whole vector at a
646        // point (`ScalarOf`, a vector operation), or the series a parameter reads.
647        _ => false,
648    }
649}