Skip to main content

promql/native/
segment.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//! Segmenting a native tree, so each per-series prefix runs where its input is read.
16//!
17//! A tree that reads across series answers one partition and gathers whatever it reads. Its
18//! per-series prefixes do not need that gather, so each is cut out as a [`FusedSeries`] node of its
19//! own and keeps the partitions it was scanned with: `cut_as_segment` decides what can be cut,
20//! [`cut_segments`] rewrites the tree into one segment per cut, and [`segment_tree`] builds the
21//! nodes, recursing into a cut that wraps a whole-vector consumer.
22//!
23//! Everything here reads the bound tree alone. The columns a node publishes are the planner's
24//! answer, so the builders ask for them through [`OutputTags`], [`FieldNames`] and [`RootSchema`]
25//! instead of deriving them a second time.
26
27use std::sync::Arc;
28
29use common_query::native_histogram::native_histogram_value_type;
30use common_query::series_frame::raw_series_frame_schema_with_ordering;
31use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit as ArrowTimeUnit};
32use datafusion::common::{DFSchema, DFSchemaRef};
33use datafusion::logical_expr::{Extension, LogicalPlan};
34use datatypes::data_type::DataType as _;
35use datatypes::series::SeriesOrdering;
36use datatypes::series::frame::{FrameContent, FrameLabelMode, SeriesFrameDeclaration};
37use datatypes::series::time::EvalGrid;
38use store_api::region_engine::RawLabelSource;
39
40use crate::extension_plan::{
41    FieldKind, FusedOutputFormat, FusedSeries, FusedSeriesBinding, InputLocality, RawSeriesSource,
42    input_locality, tree_source_fields,
43};
44use crate::native::plan::native_tree_supported;
45use crate::native::plan::{
46    BoundInput, METRIC_NAME, NativeExpr, NativeNode, NativeTree, NativeType, reads_across_series,
47};
48use crate::vector_match::Cardinality;
49
50/// Derives the output tag columns a node publishes, from the tag columns each source declares.
51///
52/// The planner that owns the result layout names those columns with its own walk over the tree. A
53/// segment only reads that answer - it never renames a column - so it asks through this leaf
54/// rather than deriving the columns a second time.
55pub type OutputTags = fn(&NativeNode, &[Vec<String>]) -> Option<Vec<String>>;
56
57/// Derives the value column names a statement's expression gives the compiled `fields`.
58///
59/// Like [`OutputTags`], this is the planner's answer: a segment publishes the values its tree
60/// computes under the names the statement gave them, so the builders ask through this leaf instead
61/// of publishing the compiler's own field names. The tree alone does not carry the statement's
62/// expression, which is why the expression text is an input rather than something derived here.
63pub type FieldNames = fn(&str, &[String]) -> Vec<String>;
64
65/// The row schema a statement root publishes for `promql`, or `None` when its columns cannot be
66/// named once.
67///
68/// Like [`OutputTags`], this is the caller's answer: a segment that publishes rows publishes
69/// exactly the columns the planner would have published for the same statement.
70pub type RootSchema = fn(&str, &NativeTree, &[Vec<String>], &str, FieldKind) -> Option<DFSchemaRef>;
71
72/// Whether `node` reads samples point-wise, so that one partitioned execution is one answer.
73///
74/// A node's output type is not checked here: [`NativeNode::validate`] already refuses a selection,
75/// a map or a binary operation whose operands are not evaluated vectors, so every branch below is
76/// one that produces values rather than raw samples.
77pub fn pointwise_operand(node: &NativeNode) -> bool {
78    match &node.expr {
79        // A selection reads the raw samples below it; anything else below it is a value computed
80        // from a whole series, not a scan.
81        NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } => {
82            matches!(input.expr, NativeExpr::Input(_))
83        }
84        NativeExpr::Map { input, .. } | NativeExpr::Timestamp { input } => pointwise_operand(input),
85        // A parameter that reads no data has the same value in every execution.
86        NativeExpr::ParameterizedMap {
87            input, parameters, ..
88        } => pointwise_operand(input) && parameters.iter().all(NativeNode::is_data_free),
89        // A scalar that reads no data is broadcast over the vector side's positions. Two vectors
90        // are a match between two series sets, which is the shape this route cannot split.
91        NativeExpr::Binary {
92            left,
93            right,
94            matching,
95        } => {
96            let scalar = |side: &NativeNode| matches!(side.output, NativeType::Scalar(_));
97            matching.cardinality == Cardinality::OneToOne
98                && match (scalar(left), scalar(right)) {
99                    (true, false) => left.is_data_free() && pointwise_operand(right),
100                    (false, true) => right.is_data_free() && pointwise_operand(left),
101                    _ => false,
102                }
103        }
104        // An aggregate folds a group, a vector operation reads the whole vector, and a bare input or
105        // scalar is not a per-series evaluation. A parameterized topk or histogram reads the whole
106        // vector, `scalar()` answers from it, and a per-point `φ` is read beside the fold over the
107        // whole group.
108        NativeExpr::Input(_)
109        | NativeExpr::Scalar(_)
110        | NativeExpr::EvalTime { .. }
111        | NativeExpr::VectorOf { .. }
112        | NativeExpr::ScalarOf { .. }
113        | NativeExpr::ParameterizedTopK { .. }
114        | NativeExpr::ParameterizedHistogram { .. }
115        | NativeExpr::ParameterizedAggregate { .. }
116        | NativeExpr::Aggregate { .. }
117        | NativeExpr::Vector { .. }
118        | NativeExpr::Set { .. }
119        | NativeExpr::Merge { .. }
120        | NativeExpr::Info { .. } => false,
121    }
122}
123
124pub fn independent_scan_pair(root: &NativeNode) -> bool {
125    let (left, right) = match &root.expr {
126        NativeExpr::Binary { left, right, .. } => match (&left.expr, &right.expr) {
127            (NativeExpr::Scalar(_), NativeExpr::Scalar(_)) => return false,
128            (NativeExpr::Scalar(_), _) => return independent_scan_pair(right),
129            (_, NativeExpr::Scalar(_)) => return independent_scan_pair(left),
130            _ => (left, right),
131        },
132        NativeExpr::Map { input, .. } => return independent_scan_pair(input),
133        NativeExpr::Set { left, right, .. } => {
134            return scan_operand(left) && scan_operand(right);
135        }
136        NativeExpr::Info { base, info, .. } => {
137            return pointwise_operand(base) && pointwise_operand(info);
138        }
139        _ => return false,
140    };
141
142    scan_operand(left) && scan_operand(right)
143}
144
145fn scan_operand(node: &NativeNode) -> bool {
146    pointwise_operand(node) || independent_scan_pair(node)
147}
148
149/// Whether a segment can hand `node`'s values to another segment.
150///
151/// A boundary carries an evaluated series frame: values addressed on a grid, under the labels of
152/// the series they belong to. A scalar is broadcast rather than carried, aggregate state is
153/// internal, and raw samples are what a scan produces - none of them is a frame, so a subtree
154/// producing one stays inside the segment that reads it.
155fn exportable(node: &NativeNode) -> bool {
156    node.output
157        .samples()
158        .is_some_and(|schema| schema.eval_grid.is_some())
159}
160
161/// Whether `node` is a window over an evaluated input - the shape a subquery over anything but a
162/// bare selection compiles to.
163fn evaluated_input_window(node: &NativeNode) -> bool {
164    matches!(&node.expr, NativeExpr::Window { op, .. } if op.input_grid.is_some())
165}
166
167/// Whether the dist analyzer places a segment over `node` region-locally.
168///
169/// A segment is a `FusedSeries` node the analyzer has to move below the `MergeScan` for the physical
170/// planner to read the scans it names. The `FusedSeries` arm of `Categorizer::check_extension_plan`
171/// (`src/query/src/dist_plan/commutativity.rs`) is what decides that, from the bound tree alone: a
172/// root that [`reads_across_series`] is `NonCommutative` unless it is a per-series evaluation or the
173/// `Partial` half of a split fold. A segment it refuses stays above the merge, where the physical
174/// planner finds neither a region scan nor an explicit-label frame below it, so the statement fails
175/// while being planned instead of keeping the plan it had. Segmentation therefore asks that question
176/// before it cuts, and `cut_as_segment` declines the nodes this refuses.
177pub fn region_local_segment(node: &NativeNode) -> bool {
178    !reads_across_series(node) || pointwise_operand(node) || independent_scan_pair(node)
179}
180
181/// Whether `node` becomes a segment of its own under a parent that must gather.
182///
183/// Cut local prefixes, global consumers and canonical merges separately so the prefix keeps its
184/// scan width, and every global consumer sees the canonical boundary below it. A pointwise wrapper
185/// of a global consumer is cut as well, so it cannot hide that consumer from recursive lowering.
186fn cut_as_segment(node: &NativeNode, canonical_segmentation: bool) -> bool {
187    // A window over an evaluated input answers per series on its own grid, so its own shape says
188    // nothing about where a segment over it can go: it drops the metric name, so two of the series
189    // it answers can end under one label set, and the dist analyzer reads it as cross-series
190    // ([`region_local_segment`]). Cutting one where the analyzer will not place it leaves a
191    // `FusedSeries` above the `MergeScan` that the physical planner cannot build, so the segment is
192    // only taken where the analyzer places it region-locally; otherwise the per-series prefix
193    // inside the window is cut instead, and where there is none the statement keeps the plan it had.
194    if evaluated_input_window(node) && !region_local_segment(node) {
195        return false;
196    }
197    // A window over an evaluated input is answered per series on its own grid, so it is not the
198    // global gather a raw window's locality reports.
199    let evaluated_window = evaluated_input_window(node);
200    if !exportable(node)
201        || matches!(node.expr, NativeExpr::Input(_))
202        || (!canonical_segmentation
203            && !evaluated_window
204            && matches!(input_locality(node), InputLocality::SinglePartition))
205    {
206        return false;
207    }
208    if canonical_segmentation && (contains_global_consumer(node) || is_canonical_cut(node)) {
209        return true;
210    }
211    // A segment builder needs an input, so data-free subtrees stay with their parent.
212    let mut sources = Vec::new();
213    collect_segment_inputs(node, &mut sources);
214    !sources.is_empty()
215}
216
217/// Whether the merge producer's entire prefix can run on each scan partition independently.
218pub fn canonical_local_prefix(node: &NativeNode) -> bool {
219    match &node.expr {
220        NativeExpr::Input(_) => true,
221        NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } => {
222            matches!(input.expr, NativeExpr::Input(_))
223        }
224        NativeExpr::Map { input, .. } | NativeExpr::Timestamp { input } => {
225            canonical_local_prefix(input)
226        }
227        NativeExpr::ParameterizedMap {
228            input, parameters, ..
229        } => canonical_local_prefix(input) && parameters.iter().all(NativeNode::is_data_free),
230        NativeExpr::Binary { left, right, .. } => {
231            (left.is_data_free() && canonical_local_prefix(right))
232                || (right.is_data_free() && canonical_local_prefix(left))
233        }
234        _ => false,
235    }
236}
237
238pub fn contains_canonical_merge(node: &NativeNode) -> bool {
239    node.any(&|node| matches!(node.expr, NativeExpr::Merge { .. }))
240}
241
242pub fn contains_global_consumer(node: &NativeNode) -> bool {
243    node.any(&is_global_consumer)
244}
245
246/// Whole-vector consumers remain global, but can be cut out as evaluated segments so a pointwise
247/// parent does not inherit their single-partition placement.
248///
249/// A per-point `φ` does not make the fold it reads any less of a whole-vector consumer: a
250/// `quantile` answers from every series of its group whichever node its argument comes from, so the
251/// parameterized variant is admitted here exactly as the bound one is. Leaving it out would read a
252/// fold that requires one partition as a node that does not, and the cut below it would be chosen
253/// as though its parent could run per partition.
254fn is_global_consumer(node: &NativeNode) -> bool {
255    matches!(
256        node.expr,
257        NativeExpr::Aggregate { .. }
258            | NativeExpr::ParameterizedAggregate { .. }
259            | NativeExpr::Vector { .. }
260    ) && matches!(input_locality(node), InputLocality::SinglePartition)
261}
262
263/// Whether a subtree can be cut without inheriting its parent's global gather.
264///
265/// A local prefix stays on its source partitions. A canonical merge becomes its own routed
266/// boundary, and a parent reads the assembled frames rather than gathering the scan.
267fn is_canonical_cut(node: &NativeNode) -> bool {
268    matches!(node.expr, NativeExpr::Merge { .. })
269        || !matches!(input_locality(node), InputLocality::SinglePartition)
270        || canonical_local_prefix(node)
271}
272
273/// One segment: its tree rewritten to read only its own inputs, the scans it reads, and the
274/// subtrees cut out of it.
275///
276/// A segment has one index space of its own - the scans it reads first, in the order it first names
277/// them, then the subtrees cut out of it - because `FusedSeries` requires its source indices to be
278/// dense over its children.
279pub struct Segment {
280    pub node: NativeNode,
281    /// Original scan indices, in the order this segment's indices name them.
282    pub sources: Vec<usize>,
283    /// The subtrees cut out of this segment, each still in the original index space.
284    pub cut: Vec<NativeNode>,
285}
286
287/// Collects a segment's scans and cut subtrees, without descending into a cut.
288fn collect_segment(
289    node: &NativeNode,
290    sources: &mut Vec<usize>,
291    cut: &mut Vec<NativeNode>,
292    canonical_segmentation: bool,
293) {
294    match &node.expr {
295        NativeExpr::Input(input) => {
296            if !sources.contains(&input.source_index) {
297                sources.push(input.source_index);
298            }
299        }
300        expr => {
301            for child in expr.children() {
302                if cut_as_segment(child, canonical_segmentation) {
303                    cut.push(child.clone());
304                } else {
305                    collect_segment(child, sources, cut, canonical_segmentation);
306                }
307            }
308        }
309    }
310}
311
312/// Collects every scan input in a selected segment without looking for nested cuts.
313fn collect_segment_inputs(node: &NativeNode, sources: &mut Vec<usize>) {
314    for input in node.inputs() {
315        if !sources.contains(&input.source_index) {
316            sources.push(input.source_index);
317        }
318    }
319}
320
321/// Rewrites every input leaf in a selected segment to its index in the segment's own space.
322fn rewrite_inner_segment(node: &NativeNode, sources: &[usize]) -> NativeNode {
323    let expr = match &node.expr {
324        NativeExpr::Input(input) => NativeExpr::Input(BoundInput {
325            source_index: sources
326                .iter()
327                .position(|&source| source == input.source_index)
328                .expect("the segment collected every scan it reads"),
329            output: input.output.clone(),
330            ordering: input.ordering,
331        }),
332        expr => expr.with_children(
333            expr.children()
334                .into_iter()
335                .map(|child| rewrite_inner_segment(child, sources))
336                .collect(),
337        ),
338    };
339    NativeNode {
340        expr,
341        output: node.output.clone(),
342    }
343}
344
345/// Rewrites a segment's tree so every leaf names its index in the segment's own space.
346fn rewrite_segment(
347    node: &NativeNode,
348    sources: &[usize],
349    cut_base: usize,
350    next_cut: &mut usize,
351    canonical_segmentation: bool,
352) -> NativeNode {
353    let expr = match &node.expr {
354        NativeExpr::Input(input) => NativeExpr::Input(BoundInput {
355            source_index: sources
356                .iter()
357                .position(|&source| source == input.source_index)
358                .expect("the segment collected every scan it reads"),
359            output: input.output.clone(),
360            ordering: input.ordering,
361        }),
362        expr => {
363            let children = expr
364                .children()
365                .into_iter()
366                .map(|child| {
367                    if cut_as_segment(child, canonical_segmentation) {
368                        let index = cut_base + *next_cut;
369                        *next_cut += 1;
370                        NativeNode {
371                            expr: NativeExpr::Input(BoundInput {
372                                source_index: index,
373                                output: child.output.clone(),
374                                ordering: NATIVE_ORDERING,
375                            }),
376                            output: child.output.clone(),
377                        }
378                    } else {
379                        rewrite_segment(child, sources, cut_base, next_cut, canonical_segmentation)
380                    }
381                })
382                .collect::<Vec<_>>();
383            expr.with_children(children)
384        }
385    };
386    NativeNode {
387        expr,
388        output: node.output.clone(),
389    }
390}
391
392/// Splits `node` into one segment and the subtrees cut out of it.
393pub fn cut_segments(node: &NativeNode, canonical_segmentation: bool) -> Segment {
394    let mut sources = Vec::new();
395    let mut cut = Vec::new();
396    collect_segment(node, &mut sources, &mut cut, canonical_segmentation);
397    let cut_base = sources.len();
398    let mut next_cut = 0;
399    let rewritten = rewrite_segment(
400        node,
401        &sources,
402        cut_base,
403        &mut next_cut,
404        canonical_segmentation,
405    );
406    Segment {
407        node: rewritten,
408        sources,
409        cut,
410    }
411}
412
413/// Appends the per-row name column to a rows layout's tag list.
414///
415/// A scalar root declares no name column: it publishes one value and no series, so the row it
416/// answers has no name to report. The column is appended, so the layout keeps its order - the time
417/// index, then the value fields, then the tags - and a label set that already reports the name keeps
418/// the one column it has.
419pub fn with_row_name_column(node: &NativeNode, mut tags: Vec<String>) -> Vec<String> {
420    if !matches!(&node.output, NativeType::Samples(_)) {
421        return tags;
422    }
423    // A layout can already report the name: a set operation takes it from its sides, a discovered
424    // source sorts its tags for the union, and a statement reading more than one metric-bound input
425    // declares the name each of those inputs reports. None of them leaves that column last - `or`
426    // keeps the left operand's order and only appends the right side's unseen tags, and sorting puts
427    // the name wherever its bytes fall - so the existing one is removed and appended instead: every
428    // rows layout then answers one order, the time index, the value fields, the labels, and the name
429    // last.
430    if let Some(index) = tags.iter().position(|tag| tag == METRIC_NAME) {
431        tags.remove(index);
432    }
433    tags.push(METRIC_NAME.to_string());
434    tags
435}
436
437/// The ordering this route compiles its trees against: the weakest both scanners provide.
438///
439/// A native scan declares `KeyThenTime` and a two-phase scan `Contiguous`, and the logical planner
440/// cannot read which one a statement will get. `Contiguous` is the weaker of the two - every
441/// series' samples contiguous, the series themselves unordered - and a native evaluation only
442/// refuses `Interleaved`, so a tree compiled against this ordering runs on either scanner.
443pub const NATIVE_ORDERING: SeriesOrdering = SeriesOrdering::Contiguous;
444
445/// The columns a [`FusedSeries`] node produces.
446///
447/// With `experimental_native_promql` enabled, a value column is named by the caller's [`FieldNames`]
448/// answer for the statement's expression, not legacy planner expression text. Legacy headers in
449/// `tests/cases/**` are unaffected because the native route is opt-in and off by default.
450///
451/// The shape is the one the existing unary pipeline consumes — the time index, then the series
452/// fields, then the tags — and each column is declared the way the node's own conversion reads it
453/// back:
454/// the time column is a non-nullable millisecond timestamp with no timezone, because every
455/// evaluated chunk is addressed on the statement's grid and carries one; a field is a nullable
456/// `Float64`, because a grid point inside the statement's interval can have no sample; and a tag is
457/// a nullable `Utf8`, because a range function drops the metric name and a series can be missing a
458/// label entirely.
459/// The output schema of a fused node: its time index, one column per field, then its tags.
460///
461/// `field_kind` says what a field column carries. The physical conversion reads the same kind off
462/// this schema and dispatches on it, so the schema and the batch it describes cannot disagree.
463pub fn fused_output_schema(
464    fields: &[String],
465    tags: &[String],
466    time_index: &str,
467    field_kind: FieldKind,
468) -> datafusion::common::Result<DFSchemaRef> {
469    let field_type = match field_kind {
470        FieldKind::Float => ArrowDataType::Float64,
471        FieldKind::Histogram => native_histogram_value_type().as_arrow_type(),
472    };
473    let mut columns = Vec::with_capacity(fields.len() + tags.len() + 1);
474    // The time index is marked as one, the way the existing planner's plans mark the table's own
475    // time index: what a plan publishes is a result either way, and a reader of the marker - a
476    // `RANGE` query over the plan, a schema converted back to GreptimeDB's - has to see the same
477    // column on both routes.
478    columns.push((
479        None,
480        Arc::new(
481            Field::new(
482                time_index,
483                ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
484                false,
485            )
486            .with_metadata(std::collections::HashMap::from([(
487                datatypes::schema::TIME_INDEX_KEY.to_string(),
488                "true".to_string(),
489            )])),
490        ),
491    ));
492    for name in fields {
493        columns.push((None, Arc::new(Field::new(name, field_type.clone(), true))));
494    }
495    for name in tags {
496        let mut field = Field::new(name, ArrowDataType::Utf8, true);
497        // The runtime answers `__name__` from the metric name of the series it reports, so a tag
498        // column of that name is the name of each row rather than one name for the whole result.
499        // Declaring it keeps the response layer from naming every row after the statement.
500        if name == METRIC_NAME {
501            field = field.with_metadata(datatypes::schema::metric_name_field_metadata());
502        }
503        columns.push((None, Arc::new(field)));
504    }
505
506    // GreptimeDB's schemas carry their version, and a result schema is no different: a schema
507    // read back from this plan is one, exactly as the existing planner's answer for the same
508    // statement is.
509    let metadata = std::collections::HashMap::from([(
510        datatypes::schema::VERSION_KEY.to_string(),
511        datatypes::schema::Schema::INITIAL_VERSION.to_string(),
512    )]);
513    Ok(Arc::new(DFSchema::new_with_metadata(columns, metadata)?))
514}
515
516/// The grid one `FusedSeries` publishes on: the grid its root declares it produces, or the
517/// statement's grid when the root declares none.
518///
519/// A root that produces one value per grid point says which grid that is, and that declared grid is
520/// the one its consumer reads it on: a window over an evaluated input - a subquery - produces on the
521/// window's own output grid, and a non-window root inside such a window, like the `Map` an
522/// expression of a subquery compiles to, produces on the subquery's grid rather than on the
523/// statement's. A statement root declares the statement's grid, so the two agree there. A root with
524/// no declared grid - raw samples - is read where it was scanned and keeps the caller's grid.
525/// Every lowering path binds the effective grid (the subquery's child grid for a matrix root, the
526/// statement's grid otherwise), so a window root answers that same grid here.
527fn fused_publish_grid(root: &NativeNode, statement_grid: &Arc<EvalGrid>) -> Arc<EvalGrid> {
528    root.output
529        .grid()
530        .map_or_else(|| Arc::clone(statement_grid), Arc::clone)
531}
532
533/// Lowers a tree whose root is a canonical merge into a producer and a canonical router.
534///
535/// The tree says the statement answers one series per canonical label set; what it cannot say is
536/// where the pieces of one set are, because a rewrite created them after the scan split the rows.
537/// So the pieces have to meet before the answer is written, and there are only two honest ways to
538/// make them meet: read every partition in one execution, or route each label set to one owner. The
539/// first takes the caller's parallelism away for the whole query; this is the second.
540///
541/// Two stages come out of it, and each has one job:
542///
543/// - the **producer** runs the tree's root merge on every scan partition. Its merge collects the
544///   pieces that partition holds - which is what makes a same-partition collision an error here,
545///   before anything is routed - and it exports one series per label set as a series frame. It is
546///   explicitly partition-local: the same node without that distinction would gather its inputs and
547///   answer everything in one execution.
548/// - the **router** is `SeriesRepartitionExec`'s canonical routing, which collects the pieces of one
549///   label set from *every* input partition. It is the conservative router - a label set is
550///   published only once every producer contributed it or ended - because a producer promises one
551///   series per set *per partition*, not that each set lives in one partition. A second piece of one
552///   set that holds a position another piece already holds is the same error, reported while that
553///   label set is assembled, and each output of the router then holds whole label sets: one series
554///   per set, complementary points joined.
555///
556/// `None` when the boundary cannot be built, so the caller keeps the plan it would have chosen.
557/// The stages of a canonical boundary over `tree`, and the columns its frames carry.
558///
559/// `format` says what the caller above reads: a statement root reads the boundary's rows, and
560/// anything else reads the assembled frames as an ordinary evaluated input.
561#[allow(clippy::too_many_arguments)]
562pub fn canonical_boundary_stages(
563    promql: Arc<str>,
564    tree: &NativeTree,
565    children: &[LogicalPlan],
566    source_tags: &[Vec<String>],
567    grid: &Arc<EvalGrid>,
568    time_index: &str,
569    tags: &[String],
570    metric: &Option<Arc<str>>,
571    format: FusedOutputFormat,
572    root_kind: FieldKind,
573    output_tags_of: OutputTags,
574    field_names: FieldNames,
575) -> Option<(LogicalPlan, Vec<String>)> {
576    let NativeExpr::Merge { input } = &tree.root().expr else {
577        return None;
578    };
579    if !canonical_local_prefix(input) {
580        return None;
581    }
582    let NativeType::Samples(schema) = &tree.root().output else {
583        return None;
584    };
585    schema.eval_grid.as_ref()?;
586    let fields = schema
587        .fields
588        .iter()
589        .map(|field| field.name.to_string())
590        .collect::<Vec<_>>();
591    let output_tags = output_tags_of(tree.root(), source_tags)?;
592    // The terminal rows of this boundary report the name of each row they publish, so the schema
593    // declares it exactly as the other rows layouts do. The tags stay the walk's own: they name the
594    // labels the frames carry, and the binding below is built from them.
595    let row_tags = with_row_name_column(tree.root(), output_tags.clone());
596    // The values are named after the expression, as in every other rows layout of this statement.
597    // A schema this boundary cannot declare declines here: the caller's error type is not one this
598    // crate can build, so a name collision is reported by declining rather than as an internal
599    // error, and the caller keeps the plan it would have chosen.
600    let value_names = field_names(&promql, &fields);
601    let output_schema = fused_output_schema(&value_names, &row_tags, time_index, root_kind).ok()?;
602
603    // The producer: the statement's own tree, run per partition, exporting a frame. It runs above
604    // the regions, where its router collects each label set from every region's contribution.
605    let producer = FusedSeries::try_new_canonical_producer(
606        Arc::clone(&promql),
607        tree.clone(),
608        FusedSeriesBinding {
609            grid: Arc::clone(grid),
610            time_index: time_index.to_string(),
611            tags: tags.to_vec(),
612            metric_name: metric.clone(),
613        },
614        children.to_vec(),
615    )
616    .ok()?;
617    let producer = LogicalPlan::Extension(Extension {
618        node: Arc::new(producer),
619    });
620
621    // What reads the router depends on where this boundary sits. A consumer still above it reads
622    // whole label sets, and the router already merged the pieces of one label set into one series,
623    // so that consumer is an ordinary evaluated input of its own and needs no merge. The statement's
624    // root instead publishes rows, which is this boundary's own frame converted as usual.
625    if format == FusedOutputFormat::SeriesFrame {
626        return Some((producer, output_tags));
627    }
628    let evaluated = NativeType::Samples(Arc::clone(schema));
629    let consumer_tree = NativeTree::try_new(NativeNode {
630        expr: NativeExpr::Input(BoundInput {
631            source_index: 0,
632            output: evaluated.clone(),
633            ordering: NATIVE_ORDERING,
634        }),
635        output: evaluated,
636    })
637    .ok()?;
638    // A frame names each series' own metric, so the binding names one only when a tag column does.
639    let consumer_metric = if output_tags.iter().any(|tag| tag == METRIC_NAME) {
640        metric.clone()
641    } else {
642        None
643    };
644    let consumer = FusedSeries::try_new_with_format(
645        Arc::clone(&promql),
646        consumer_tree,
647        FusedSeriesBinding {
648            grid: Arc::clone(grid),
649            time_index: time_index.to_string(),
650            tags: output_tags.clone(),
651            metric_name: consumer_metric,
652        },
653        vec![producer],
654        output_schema,
655        FusedOutputFormat::PlainRows,
656    )
657    .ok()?;
658    Some((
659        LogicalPlan::Extension(Extension {
660            node: Arc::new(consumer),
661        }),
662        output_tags,
663    ))
664}
665
666fn is_raw_series_source(plan: &LogicalPlan) -> bool {
667    match plan {
668        LogicalPlan::Extension(extension) => extension.node.as_any().is::<RawSeriesSource>(),
669        _ => false,
670    }
671}
672
673/// Whether `plan` already answers raw series frames of its own.
674///
675/// A selector naming no metric is prepared as one [`RawSeriesSource`] per discovered metric, or as
676/// the `Union` of them when it discovered several, and each source names the metric it reads. So
677/// such a plan is a frame producer in its own right: a segment hands it to the node it builds
678/// instead of binding it again. Binding it again nests a source in a source, and the physical
679/// planner reads a source's child as the region scan that source binds - a union is no such child
680/// either - so the nested input is refused after the statement has already been committed to this
681/// route.
682fn is_sourced_plan(plan: &LogicalPlan) -> bool {
683    matches!(plan, LogicalPlan::Union(_)) || is_raw_series_source(plan)
684}
685
686fn find_input_node(node: &NativeNode, source_index: usize) -> Option<&BoundInput> {
687    node.inputs()
688        .into_iter()
689        .find(|input| input.source_index == source_index)
690}
691
692/// Whether `plan` is the typed empty input a discovered selector that matched no table gets.
693///
694/// It reads no region and holds no scan, so it is not one of the tables a node's binding is derived
695/// from: two selectors are "of one table" only if the tables they scan are one. The remote
696/// admission gate reads the same shape back, to tell a node with nothing to ship from one that does
697/// read regions, so the declared frame is part of the check: an empty relation that does not
698/// declare the raw explicit-label frame is some other plan, not this input.
699pub fn is_empty_discovered_input(plan: &LogicalPlan) -> bool {
700    let LogicalPlan::EmptyRelation(relation) = plan else {
701        return false;
702    };
703    if relation.produce_one_row {
704        return false;
705    }
706    let Ok(declaration) = SeriesFrameDeclaration::parse(relation.schema.as_arrow()) else {
707        return false;
708    };
709    if declaration.content() != FrameContent::Raw
710        || declaration.labels() != FrameLabelMode::Explicit
711    {
712        return false;
713    }
714    let Ok(frame) = raw_series_frame_schema_with_ordering(
715        declaration.series(),
716        &RawLabelSource::Explicit,
717        NATIVE_ORDERING,
718    ) else {
719        return false;
720    };
721    relation.schema.as_arrow() == frame.as_ref()
722}
723
724#[allow(clippy::too_many_arguments, clippy::type_complexity)]
725fn build_evaluated_segment(
726    promql: Arc<str>,
727    node: &NativeNode,
728    children: &[LogicalPlan],
729    source_tags: &[Vec<String>],
730    source_ids: &[Option<usize>],
731    per_source: &[(Option<Arc<str>>, String, Vec<String>)],
732    grid: &Arc<EvalGrid>,
733    time_index: &str,
734    root_kind: FieldKind,
735    output_tags_of: OutputTags,
736    field_names: FieldNames,
737) -> Option<(LogicalPlan, Vec<String>)> {
738    let mut sources = Vec::new();
739    collect_segment_inputs(node, &mut sources);
740    if sources.is_empty() {
741        return None;
742    }
743    let mut inputs = Vec::with_capacity(sources.len());
744    let mut local_tags = Vec::with_capacity(sources.len());
745    let tree = NativeTree::try_new(rewrite_inner_segment(node, &sources)).ok()?;
746    let source_fields = tree_source_fields(&tree).ok()?;
747    for (local_index, &index) in sources.iter().enumerate() {
748        let child = children.get(index)?.clone();
749        let input = find_input_node(node, index)?;
750        if input
751            .output
752            .samples()
753            .is_some_and(|schema| schema.eval_grid.is_some())
754            // A selector that discovered one metric is prepared as that metric's source, and one that
755            // discovered several as the union of one source per metric; either way it already
756            // declares the frames this segment reads, since it names each metric's source. So there
757            // is nothing to bind it to and nothing to wrap it in, and binding a source in a source
758            // is what the physical planner refuses. See [`is_sourced_plan`].
759            || is_sourced_plan(&child)
760            // The typed empty frame of a selector that matched no table is an input in its own
761            // right: it reads no region and carries no metric, so there is nothing to wrap it in.
762            // A segment over it is still an explicit-label frame with no series.
763            || is_empty_discovered_input(&child)
764        {
765            inputs.push(child);
766            local_tags.push(source_tags.get(index)?.clone());
767        } else {
768            let original_index = *source_ids.get(index)?.as_ref()?;
769            let (Some((Some(metric), _, tags)), Some(fields)) = (
770                per_source.get(original_index),
771                source_fields.get(local_index),
772            ) else {
773                return None;
774            };
775            inputs.push(LogicalPlan::Extension(Extension {
776                node: Arc::new(
777                    RawSeriesSource::try_new(
778                        Arc::clone(metric),
779                        tags.clone(),
780                        fields.clone(),
781                        child,
782                    )
783                    .ok()?,
784                ),
785            }));
786            local_tags.push(tags.clone());
787        }
788    }
789    // A canonical merge is not a segment: it is the middle of a boundary whose two frame nodes and
790    // router are what answer one series per label set across partitions, so it is built as that
791    // boundary and read as a frame.
792    if matches!(tree.root().expr, NativeExpr::Merge { .. }) {
793        let (plan, tags) = canonical_boundary_stages(
794            Arc::clone(&promql),
795            &tree,
796            &inputs,
797            &local_tags,
798            grid,
799            time_index,
800            &[],
801            &None,
802            FusedOutputFormat::SeriesFrame,
803            root_kind,
804            output_tags_of,
805            field_names,
806        )?;
807        return Some((plan, tags));
808    }
809    let output_tags = output_tags_of(tree.root(), &local_tags)?;
810    if !native_tree_supported(&tree) {
811        return None;
812    }
813    let frame = FusedSeries::series_frame_schema(&tree).ok()?;
814    let frame = DFSchema::try_from(frame.as_ref().clone()).ok()?;
815    let publish_grid = fused_publish_grid(tree.root(), grid);
816    let plan = FusedSeries::try_new_with_format(
817        Arc::from("segment"),
818        tree,
819        FusedSeriesBinding {
820            grid: publish_grid,
821            time_index: time_index.to_string(),
822            tags: output_tags.clone(),
823            metric_name: None,
824        },
825        inputs,
826        Arc::new(frame),
827        FusedOutputFormat::SeriesFrame,
828    )
829    .ok()?;
830    Some((
831        LogicalPlan::Extension(Extension {
832            node: Arc::new(plan),
833        }),
834        output_tags,
835    ))
836}
837
838/// Builds one segment's plan from a subtree, binding its scan inputs without cutting again.
839///
840/// Returns the plan and the output columns the segment reports, which its parent names its own
841/// columns by. `None` when any part cannot be built, so the statement keeps the plan it had.
842#[allow(clippy::type_complexity)]
843fn build_inner_segment(
844    node: &NativeNode,
845    bare_scans: &[LogicalPlan],
846    per_source: &[(Option<Arc<str>>, String, Vec<String>)],
847    grid: &Arc<EvalGrid>,
848    output_tags_of: OutputTags,
849) -> Option<(LogicalPlan, Vec<String>)> {
850    let mut sources = Vec::new();
851    collect_segment_inputs(node, &mut sources);
852    if sources.is_empty() {
853        return None;
854    }
855    let scans = sources
856        .iter()
857        .map(|&index| bare_scans.get(index).cloned())
858        .collect::<Option<Vec<_>>>()?;
859    let source_tags = sources
860        .iter()
861        .map(|&index| per_source.get(index).map(|(_, _, tags)| tags.clone()))
862        .collect::<Option<Vec<_>>>()?;
863    let tree = NativeTree::try_new(rewrite_inner_segment(node, &sources)).ok()?;
864    let output_tags = output_tags_of(tree.root(), &source_tags)?;
865    // A segment publishes on the grid its own root declares, which is the grid its parent reads it
866    // on: the segments of a subquery's inner expression are evaluated on the subquery's grid, not on
867    // the statement's, whatever their root computes. The statement's grid is only the fallback for a
868    // root that declares none.
869    let segment_grid = fused_publish_grid(tree.root(), grid);
870    let (inputs, metric, time_index, tags) = if let [index] = sources.as_slice() {
871        let (metric, time_index, tags) = per_source.get(*index)?;
872        (scans, metric.clone(), time_index.clone(), tags.clone())
873    } else {
874        // A binding cannot describe different source identities. Give each child the existing
875        // explicit-label source boundary used for separate metric tables.
876        let source_fields = tree_source_fields(&tree).ok()?;
877        let mut children = Vec::with_capacity(sources.len());
878        for (local_index, &source_index) in sources.iter().enumerate() {
879            let scan = scans.get(local_index)?;
880            // A scan that is already a source - one metric of a discovery, or the union of several -
881            // is the frame producer this segment reads, so it stays as it is; see [`is_sourced_plan`].
882            if is_sourced_plan(scan) {
883                children.push(scan.clone());
884                continue;
885            }
886            let (Some((Some(metric), _, source_tags)), Some(fields)) =
887                (per_source.get(source_index), source_fields.get(local_index))
888            else {
889                return None;
890            };
891            children.push(LogicalPlan::Extension(Extension {
892                node: Arc::new(
893                    RawSeriesSource::try_new(
894                        Arc::clone(metric),
895                        source_tags.clone(),
896                        fields.clone(),
897                        scan.clone(),
898                    )
899                    .ok()?,
900                ),
901            }));
902        }
903        let time_index = per_source.get(*sources.first()?)?.1.clone();
904        (children, None, time_index, output_tags.clone())
905    };
906    if !native_tree_supported(&tree) {
907        return None;
908    }
909    let frame = FusedSeries::series_frame_schema(&tree).ok()?;
910    let frame = DFSchema::try_from(frame.as_ref().clone()).ok()?;
911    let plan = FusedSeries::try_new_with_format(
912        Arc::from("segment"),
913        tree,
914        FusedSeriesBinding {
915            grid: segment_grid,
916            time_index: time_index.clone(),
917            tags: tags.clone(),
918            metric_name: metric.clone(),
919        },
920        inputs,
921        Arc::new(frame),
922        FusedOutputFormat::SeriesFrame,
923    )
924    .ok()?;
925    Some((
926        LogicalPlan::Extension(Extension {
927            node: Arc::new(plan),
928        }),
929        output_tags,
930    ))
931}
932
933/// Plans `tree` as several segments, or `None` when it is one node already.
934///
935/// A tree that reads across series answers one partition and gathers whatever it reads. Its
936/// per-series prefixes do not need that gather, so each becomes a segment of its own and keeps the
937/// partitions it was scanned with. Global consumers and canonical merges are cut in their original
938/// order, and recursive segments publish frames for their parents to consume. Only the statement
939/// root publishes rows, and it does so under the statement's own value names: [`FieldNames`]
940/// answers those, and the rows schema asks [`RootSchema`] for the rest of the layout.
941#[allow(clippy::too_many_arguments, clippy::type_complexity)]
942pub fn segment_tree(
943    promql: Arc<str>,
944    tree: &NativeTree,
945    children: &[LogicalPlan],
946    source_tags: &[Vec<String>],
947    bare_scans: &[LogicalPlan],
948    per_source: &[(Option<Arc<str>>, String, Vec<String>)],
949    grid: &Arc<EvalGrid>,
950    time_index: &str,
951    tags: &[String],
952    metric: &Option<Arc<str>>,
953    format: FusedOutputFormat,
954    canonical_segmentation: bool,
955    root_kind: FieldKind,
956    remote_raw_boundary: bool,
957    output_tags_of: OutputTags,
958    field_names: FieldNames,
959    root_schema: RootSchema,
960) -> Option<LogicalPlan> {
961    // Only a tree the analyzer gathers is worth splitting: its per-series prefixes then run where
962    // their input is read. A window over an evaluated input can need that split even where
963    // [`input_locality`] reports a local tree - it drops the metric name, so [`reads_across_series`]
964    // reads it as cross-series - and the per-series prefix inside it is what keeps the partitions it
965    // scanned. Proceeding only admits the attempt: every cut is admitted by `cut_as_segment`
966    // individually, which is where the analyzer's placement is asked.
967    if !matches!(input_locality(tree.root()), InputLocality::SinglePartition)
968        && !evaluated_input_window(tree.root())
969    {
970        return None;
971    }
972    // A segment boundary has to carry something, and the only thing it can carry is a per-series
973    // prefix: a subtree that answers each series on its own and can be recomputed. A tree with no
974    // such subtree inside it has nothing to cut, and cutting anything else - an aggregate's own
975    // state, a constant - is either impossible or a plain recomputation of the same work in one
976    // more node. Cutting on locality alone would accept one here.
977    //
978    // The window this tree may be rooted at is not one of those consumers, but it is no boundary
979    // either: `cut_as_segment` never cuts one, and what keeps its input's partitions is the
980    // per-series prefix below it, which the cuts below are admitted for.
981    //
982    // A grouping by `__name__` needs no refusal of its own here: `source_tags` is the authority on
983    // which labels an input declares, and the planner declares the metric name of every occurrence of
984    // a statement reading more than one input - so a segment's output tags name the label the grouping
985    // keeps, and two groups differing only by metric are published under their own label sets.
986    let mut current_tree = tree.clone();
987    let mut current_children = children.to_vec();
988    let mut current_tags = source_tags.to_vec();
989    let mut current_source_ids = (0..children.len()).map(Some).collect::<Vec<_>>();
990    let mut first_iteration = true;
991    let mut changed = false;
992    loop {
993        // A tree the analyzer keeps partition-local needs no segment; a window over an evaluated
994        // input is still worth attempting one for, so its per-series prefix keeps its partitions.
995        if !matches!(
996            input_locality(current_tree.root()),
997            InputLocality::SinglePartition
998        ) && !evaluated_input_window(current_tree.root())
999        {
1000            break;
1001        }
1002        let segment = cut_segments(current_tree.root(), canonical_segmentation);
1003        if segment.cut.is_empty() {
1004            break;
1005        }
1006        let mut inputs = Vec::with_capacity(segment.sources.len() + segment.cut.len());
1007        let mut child_tags = Vec::with_capacity(inputs.capacity());
1008        for &index in &segment.sources {
1009            let child = current_children.get(index)?;
1010            inputs.push(child.clone());
1011            child_tags.push(current_tags.get(index).cloned().unwrap_or_default());
1012        }
1013        let mut child_source_ids = segment
1014            .sources
1015            .iter()
1016            .map(|&index| current_source_ids.get(index).copied().flatten())
1017            .collect::<Vec<_>>();
1018        for cut in &segment.cut {
1019            // A cut may wrap a global consumer in a pointwise rewrite or a later merge. Segment
1020            // that subtree first so its inner canonical boundary stays below the consumer. A local
1021            // canonical merge instead goes directly to the boundary builder.
1022            let canonical = matches!(cut.expr, NativeExpr::Merge { .. });
1023            let built = if first_iteration && contains_global_consumer(cut) {
1024                let cut_tree = NativeTree::try_new(cut.clone()).ok()?;
1025                let plan = segment_tree(
1026                    Arc::clone(&promql),
1027                    &cut_tree,
1028                    &current_children,
1029                    &current_tags,
1030                    bare_scans,
1031                    per_source,
1032                    grid,
1033                    time_index,
1034                    tags,
1035                    metric,
1036                    FusedOutputFormat::SeriesFrame,
1037                    canonical_segmentation,
1038                    root_kind,
1039                    remote_raw_boundary,
1040                    output_tags_of,
1041                    field_names,
1042                    root_schema,
1043                );
1044                match plan {
1045                    Some(plan) => {
1046                        let cut_tags = output_tags_of(cut, &current_tags)?;
1047                        Some((plan, cut_tags))
1048                    }
1049                    None => None,
1050                }
1051            } else if first_iteration && !canonical && !remote_raw_boundary {
1052                build_inner_segment(cut, bare_scans, per_source, grid, output_tags_of)
1053            } else {
1054                None
1055            };
1056            if built.is_none() && contains_global_consumer(cut) {
1057                return None;
1058            }
1059            // A cut the first iteration cannot build from the scans is built from the frames this
1060            // loop has already published: the canonical pass inserts a merge under a label rewrite,
1061            // and that boundary - rebuilt here as a producer, a frame and a router - is what answers
1062            // one series per label set across partitions. Which cuts are taken is
1063            // `cut_as_segment`'s decision, and it declines the evaluated-input window the analyzer
1064            // will not place region-locally, so this fallback only ever sees the cuts it admitted.
1065            let built = built.or_else(|| {
1066                build_evaluated_segment(
1067                    Arc::clone(&promql),
1068                    cut,
1069                    &current_children,
1070                    &current_tags,
1071                    &current_source_ids,
1072                    per_source,
1073                    grid,
1074                    time_index,
1075                    root_kind,
1076                    output_tags_of,
1077                    field_names,
1078                )
1079            });
1080            let (plan, cut_tags) = built?;
1081            inputs.push(plan);
1082            child_tags.push(cut_tags);
1083            child_source_ids.push(None);
1084        }
1085        let parent = NativeTree::try_new(segment.node).ok()?;
1086        first_iteration = false;
1087        current_tree = parent;
1088        current_children = inputs;
1089        current_tags = child_tags;
1090        current_source_ids = child_source_ids;
1091        changed = true;
1092    }
1093    if !changed {
1094        return None;
1095    }
1096    let parent = current_tree;
1097    // Segmentation is useful even when the resulting parent is still single-partition: each
1098    // exported per-series subtree remains a separate input and is bound to its own source.
1099    let mut inputs = current_children;
1100    let mut child_tags = current_tags;
1101    // A merge at this segment's root still needs its own boundary. An outer rewrite above a
1102    // recursively cut ranking runs after the ranking, then is canonicalized before its caller.
1103    if let NativeExpr::Merge { input } = &parent.root().expr {
1104        let source_fields = tree_source_fields(&parent).ok();
1105        for index in 0..inputs.len() {
1106            let bound = find_input_node(input, index)?;
1107            if bound
1108                .output
1109                .samples()
1110                .is_some_and(|schema| schema.eval_grid.is_none())
1111                && !is_raw_series_source(&inputs[index])
1112            {
1113                let source_index = current_source_ids.get(index).copied().flatten()?;
1114                let (Some((Some(source_metric), _, source_tags)), Some(fields)) = (
1115                    per_source.get(source_index),
1116                    source_fields.as_ref().and_then(|fields| fields.get(index)),
1117                ) else {
1118                    return None;
1119                };
1120                let Ok(source) = RawSeriesSource::try_new(
1121                    Arc::clone(source_metric),
1122                    source_tags.clone(),
1123                    fields.clone(),
1124                    inputs[index].clone(),
1125                ) else {
1126                    return None;
1127                };
1128                inputs[index] = LogicalPlan::Extension(Extension {
1129                    node: Arc::new(source),
1130                });
1131                child_tags[index] = source_tags.clone();
1132            }
1133        }
1134        return canonical_boundary_stages(
1135            Arc::clone(&promql),
1136            &parent,
1137            &inputs,
1138            &child_tags,
1139            grid,
1140            time_index,
1141            tags,
1142            metric,
1143            format,
1144            root_kind,
1145            output_tags_of,
1146            field_names,
1147        )
1148        .map(|(plan, _)| plan);
1149    }
1150    // Nothing below can fall back once physical planning starts, so every tree this route commits
1151    // to has to be one the runtime executes. A shape the runtime refuses - a grouping by a value
1152    // field, an operation with no kernel - therefore keeps the plan it had.
1153    if !native_tree_supported(&parent) {
1154        return None;
1155    }
1156    let output_schema = match format {
1157        FusedOutputFormat::PlainRows => {
1158            root_schema(&promql, &parent, &child_tags, time_index, root_kind)?
1159        }
1160        FusedOutputFormat::SeriesFrame => {
1161            let Ok(frame) = FusedSeries::series_frame_schema(&parent) else {
1162                return None;
1163            };
1164            let Ok(schema) = DFSchema::try_from(frame.as_ref().clone()) else {
1165                return None;
1166            };
1167            Arc::new(schema)
1168        }
1169    };
1170    // A recursively constructed segment still has its original source binding. Its parent may
1171    // combine another metric; giving the segment that parent's metric would relabel both inputs.
1172    // Direct scan segments keep their established builder and binding unchanged.
1173    let segment_binding = |source_ids: &[Option<usize>]| -> (Option<Arc<str>>, String) {
1174        let mut sources = source_ids.iter().flatten().copied();
1175        let Some(source) = sources.next() else {
1176            return (metric.clone(), time_index.to_string());
1177        };
1178        if sources.next().is_some() {
1179            return (None, time_index.to_string());
1180        }
1181        per_source.get(source).map_or_else(
1182            || (metric.clone(), time_index.to_string()),
1183            |(metric, time, _)| (metric.clone(), time.clone()),
1184        )
1185    };
1186    let (segment_metric, segment_time_index) = segment_binding(&current_source_ids);
1187    // A segment publishes on the grid its root declares, which is the grid its consumer reads it
1188    // on. Segmentation recurses into a cut subtree with the caller's grid, and that subtree can sit
1189    // inside a subquery window: the canonical segmentation of a collapsing rewrite cuts the window's
1190    // input while its caller still holds the statement's grid. Binding the caller's grid here
1191    // rejects such a segment, and the rejection aborts the whole route.
1192    let publish_grid = fused_publish_grid(parent.root(), grid);
1193    let Ok(plan) = FusedSeries::try_new_with_format(
1194        Arc::clone(&promql),
1195        parent,
1196        FusedSeriesBinding {
1197            grid: publish_grid,
1198            time_index: segment_time_index,
1199            tags: tags.to_vec(),
1200            metric_name: segment_metric,
1201        },
1202        inputs,
1203        output_schema,
1204        format,
1205    ) else {
1206        return None;
1207    };
1208    Some(LogicalPlan::Extension(Extension {
1209        node: Arc::new(plan),
1210    }))
1211}
1212
1213#[cfg(test)]
1214mod tests {
1215    use std::sync::Arc;
1216
1217    use datatypes::series::SeriesOrdering;
1218    use datatypes::series::samples::{FieldSpec, SeriesSchema};
1219    use datatypes::series::time::{EvalGrid, GridSpec};
1220
1221    use super::*;
1222    use crate::map::MathOp;
1223    use crate::native::plan::{
1224        AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap,
1225        Grouping, InstantValue, MapOp,
1226    };
1227
1228    fn grid() -> Arc<EvalGrid> {
1229        Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1, 4).unwrap()).unwrap())
1230    }
1231
1232    /// The evaluated layout of the only field these trees carry.
1233    fn evaluated(grid: &Arc<EvalGrid>) -> NativeType {
1234        NativeType::Samples(Arc::new(SeriesSchema {
1235            fields: vec![FieldSpec {
1236                name: Arc::from("value"),
1237            }]
1238            .into(),
1239            eval_grid: Some(Arc::clone(grid)),
1240        }))
1241    }
1242
1243    /// `abs(…)` over `inner`, as a pointwise rewrite above a cut would be.
1244    fn map_over(inner: NativeNode) -> NativeNode {
1245        let output = inner
1246            .output
1247            .grid()
1248            .expect("a map reads an evaluated vector")
1249            .clone();
1250        NativeNode {
1251            expr: NativeExpr::Map {
1252                input: Box::new(inner),
1253                op: BoundMap {
1254                    ops: vec![MapOp::Math(MathOp::Abs)].into(),
1255                },
1256            },
1257            output: evaluated(&output),
1258        }
1259    }
1260
1261    /// `inner` selected at every grid point.
1262    fn selection(inner: NativeNode, output: NativeType) -> NativeNode {
1263        let grid = output
1264            .grid()
1265            .expect("a selection answers on a grid")
1266            .clone();
1267        NativeNode {
1268            expr: NativeExpr::Instant {
1269                input: Box::new(inner),
1270                op: BoundInstant {
1271                    lookback_ms: 300_000,
1272                    offset_ms: 0,
1273                    at_ms: None,
1274                    value: InstantValue::Sample,
1275                    output_grid: grid,
1276                },
1277            },
1278            output,
1279        }
1280    }
1281
1282    /// A fold that reads its argument at every step is a whole-vector consumer.
1283    ///
1284    /// A `quantile` answers from its group's whole sample set wherever its `φ` comes from, so a
1285    /// fold that reads that `φ` per point needs every series of the vector in one place exactly as
1286    /// the fold that binds the number does. [`segment_tree`] asks [`contains_global_consumer`]
1287    /// where a tree may be cut and whether a cut it cannot build has to be declined, and a parent
1288    /// that answers one series at a time -- the `abs` below, as a canonical label rewrite would be
1289    /// -- must not hide the gather under it: read as a per-partition node, the cut beneath would be
1290    /// chosen for a parent that cannot run there.
1291    #[test]
1292    fn a_fold_that_reads_its_parameter_is_a_global_consumer() {
1293        let grid = grid();
1294        let output = evaluated(&grid);
1295        let source = NativeNode {
1296            expr: NativeExpr::Input(BoundInput {
1297                output: output.clone(),
1298                source_index: 0,
1299                ordering: SeriesOrdering::Contiguous,
1300            }),
1301            output: output.clone(),
1302        };
1303        let fold = NativeNode {
1304            expr: NativeExpr::ParameterizedAggregate {
1305                input: Box::new(selection(source.clone(), output.clone())),
1306                op: BoundAggregate {
1307                    kind: AggregateKind::Quantile { quantile: 0.0 },
1308                    group: Grouping::By(Arc::from([])),
1309                    stage: AggregateStage::Complete,
1310                    field_kind: FieldKind::Float,
1311                },
1312                parameter: Box::new(NativeNode {
1313                    expr: NativeExpr::EvalTime { date: None },
1314                    output: NativeType::Scalar(Arc::clone(&grid)),
1315                }),
1316            },
1317            output: output.clone(),
1318        };
1319        assert!(
1320            contains_global_consumer(&fold),
1321            "a fold that reads its `φ` per point reads the whole vector"
1322        );
1323        assert!(
1324            contains_global_consumer(&map_over(fold)),
1325            "a pointwise parent must not hide the fold's gather"
1326        );
1327        // The predicate is about that fold and not about every subtree: a pointwise rewrite of a
1328        // selection answers each series on its own, so it stays cuttable where it stands.
1329        assert!(
1330            !contains_global_consumer(&map_over(selection(source, output))),
1331            "a selection is not a whole-vector consumer"
1332        );
1333    }
1334}