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 runs in one partition. Its per-series prefixes are cut out as
18//! [`FusedSeries`] nodes of their own so they keep their scan partitions: `cut_as_segment` decides
19//! what is cut, [`cut_segments`] rewrites the tree into one segment per cut, and [`segment_tree`]
20//! builds the nodes.
21//!
22//! Output columns are the planner's answer, read through [`OutputTags`], [`FieldNames`] and
23//! [`RootSchema`].
24
25use std::sync::Arc;
26
27use common_query::native_histogram::native_histogram_value_type;
28use common_query::series_frame::raw_series_frame_schema_with_ordering;
29use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit as ArrowTimeUnit};
30use datafusion::common::{DFSchema, DFSchemaRef};
31use datafusion::logical_expr::{Extension, LogicalPlan};
32use datatypes::data_type::DataType as _;
33use datatypes::series::SeriesOrdering;
34use datatypes::series::frame::{FrameContent, FrameLabelMode, SeriesFrameDeclaration};
35use datatypes::series::time::EvalGrid;
36use store_api::region_engine::RawLabelSource;
37
38use crate::extension_plan::{
39    FieldKind, FusedOutputFormat, FusedSeries, FusedSeriesBinding, InputLocality, RawSeriesSource,
40    input_locality, tree_source_fields,
41};
42use crate::native::plan::native_tree_supported;
43use crate::native::plan::{
44    BoundInput, METRIC_NAME, NativeExpr, NativeNode, NativeTree, NativeType, reads_across_series,
45};
46use crate::vector_match::Cardinality;
47
48/// The planner's output tag columns for a node, given each source's tag columns.
49pub type OutputTags = fn(&NativeNode, &[Vec<String>]) -> Option<Vec<String>>;
50
51/// The planner's value column names for the compiled `fields` of a statement's expression.
52pub type FieldNames = fn(&str, &[String]) -> Vec<String>;
53
54/// The planner's row schema for a statement root over `promql`, or `None` when its columns cannot
55/// be named once.
56pub type RootSchema = fn(&str, &NativeTree, &[Vec<String>], &str, FieldKind) -> Option<DFSchemaRef>;
57
58/// Whether `node` evaluates each series on its own, directly over a scan, so one partitioned
59/// execution is one answer.
60pub fn pointwise_operand(node: &NativeNode) -> bool {
61    match &node.expr {
62        NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } => {
63            matches!(input.expr, NativeExpr::Input(_))
64        }
65        NativeExpr::Map { input, .. } | NativeExpr::Timestamp { input } => pointwise_operand(input),
66        NativeExpr::ParameterizedMap {
67            input, parameters, ..
68        } => pointwise_operand(input) && parameters.iter().all(NativeNode::is_data_free),
69        NativeExpr::Binary {
70            left,
71            right,
72            matching,
73        } => {
74            let scalar = |side: &NativeNode| matches!(side.output, NativeType::Scalar(_));
75            matching.cardinality == Cardinality::OneToOne
76                && match (scalar(left), scalar(right)) {
77                    (true, false) => left.is_data_free() && pointwise_operand(right),
78                    (false, true) => right.is_data_free() && pointwise_operand(left),
79                    _ => false,
80                }
81        }
82        NativeExpr::Input(_)
83        | NativeExpr::Scalar(_)
84        | NativeExpr::EvalTime { .. }
85        | NativeExpr::VectorOf { .. }
86        | NativeExpr::ScalarOf { .. }
87        | NativeExpr::ParameterizedTopK { .. }
88        | NativeExpr::ParameterizedHistogram { .. }
89        | NativeExpr::ParameterizedAggregate { .. }
90        | NativeExpr::Aggregate { .. }
91        | NativeExpr::Vector { .. }
92        | NativeExpr::Set { .. }
93        | NativeExpr::Merge { .. }
94        | NativeExpr::Info { .. } => false,
95    }
96}
97
98pub fn independent_scan_pair(root: &NativeNode) -> bool {
99    let (left, right) = match &root.expr {
100        NativeExpr::Binary { left, right, .. } => match (&left.expr, &right.expr) {
101            (NativeExpr::Scalar(_), NativeExpr::Scalar(_)) => return false,
102            (NativeExpr::Scalar(_), _) => return independent_scan_pair(right),
103            (_, NativeExpr::Scalar(_)) => return independent_scan_pair(left),
104            _ => (left, right),
105        },
106        NativeExpr::Map { input, .. } => return independent_scan_pair(input),
107        NativeExpr::Set { left, right, .. } => {
108            return scan_operand(left) && scan_operand(right);
109        }
110        NativeExpr::Info { base, info, .. } => {
111            return pointwise_operand(base) && pointwise_operand(info);
112        }
113        _ => return false,
114    };
115
116    scan_operand(left) && scan_operand(right)
117}
118
119fn scan_operand(node: &NativeNode) -> bool {
120    pointwise_operand(node) || independent_scan_pair(node)
121}
122
123/// Whether `node` answers an evaluated vector, the only thing a segment boundary carries.
124fn exportable(node: &NativeNode) -> bool {
125    node.output
126        .samples()
127        .is_some_and(|schema| schema.eval_grid.is_some())
128}
129
130/// Whether `node` is a window over an evaluated input (a subquery).
131fn evaluated_input_window(node: &NativeNode) -> bool {
132    matches!(&node.expr, NativeExpr::Window { op, .. } if op.input_grid.is_some())
133}
134
135/// Whether the dist analyzer places a segment over `node` below the `MergeScan`.
136///
137/// Mirrors the tree-shape check of the `FusedSeries` arm of `Categorizer::check_extension_plan`
138/// (`src/query/src/dist_plan/commutativity.rs`). A segment left above the merge has no scan the
139/// physical planner can read, so `cut_as_segment` must not cut it.
140pub fn region_local_segment(node: &NativeNode) -> bool {
141    !reads_across_series(node) || pointwise_operand(node) || independent_scan_pair(node)
142}
143
144/// Whether `node` becomes a segment of its own under a parent that must gather.
145///
146/// Local prefixes, global consumers and canonical merges are cut separately, so a prefix keeps its
147/// scan width and every global consumer sees the canonical boundary below it. A pointwise wrapper
148/// of a global consumer is cut as well, so it cannot hide that consumer from recursive lowering.
149fn cut_as_segment(node: &NativeNode, canonical_segmentation: bool) -> bool {
150    // Where the analyzer will not place a subquery window region-locally, the per-series prefix
151    // inside it is cut instead.
152    if evaluated_input_window(node) && !region_local_segment(node) {
153        return false;
154    }
155    // A subquery window answers per series on its own grid, whatever its locality reports.
156    let evaluated_window = evaluated_input_window(node);
157    if !exportable(node)
158        || matches!(node.expr, NativeExpr::Input(_))
159        || (!canonical_segmentation
160            && !evaluated_window
161            && matches!(input_locality(node), InputLocality::SinglePartition))
162    {
163        return false;
164    }
165    if canonical_segmentation && (contains_global_consumer(node) || is_canonical_cut(node)) {
166        return true;
167    }
168    // Data-free subtrees stay with their parent.
169    let mut sources = Vec::new();
170    collect_segment_inputs(node, &mut sources);
171    !sources.is_empty()
172}
173
174/// Whether the merge producer's entire prefix can run on each scan partition independently.
175pub fn canonical_local_prefix(node: &NativeNode) -> bool {
176    match &node.expr {
177        NativeExpr::Input(_) => true,
178        NativeExpr::Instant { input, .. } | NativeExpr::Window { input, .. } => {
179            matches!(input.expr, NativeExpr::Input(_))
180        }
181        NativeExpr::Map { input, .. } | NativeExpr::Timestamp { input } => {
182            canonical_local_prefix(input)
183        }
184        NativeExpr::ParameterizedMap {
185            input, parameters, ..
186        } => canonical_local_prefix(input) && parameters.iter().all(NativeNode::is_data_free),
187        NativeExpr::Binary { left, right, .. } => {
188            (left.is_data_free() && canonical_local_prefix(right))
189                || (right.is_data_free() && canonical_local_prefix(left))
190        }
191        _ => false,
192    }
193}
194
195pub fn contains_canonical_merge(node: &NativeNode) -> bool {
196    node.any(&|node| matches!(node.expr, NativeExpr::Merge { .. }))
197}
198
199pub fn contains_global_consumer(node: &NativeNode) -> bool {
200    node.any(&is_global_consumer)
201}
202
203/// Whole-vector consumers stay global, but are cut out as evaluated segments so a pointwise parent
204/// does not inherit their single-partition placement.
205fn is_global_consumer(node: &NativeNode) -> bool {
206    matches!(
207        node.expr,
208        NativeExpr::Aggregate { .. }
209            | NativeExpr::ParameterizedAggregate { .. }
210            | NativeExpr::Vector { .. }
211    ) && matches!(input_locality(node), InputLocality::SinglePartition)
212}
213
214/// Whether a subtree can be cut without inheriting its parent's global gather: a local prefix, or
215/// a canonical merge that becomes its own routed boundary.
216fn is_canonical_cut(node: &NativeNode) -> bool {
217    matches!(node.expr, NativeExpr::Merge { .. })
218        || !matches!(input_locality(node), InputLocality::SinglePartition)
219        || canonical_local_prefix(node)
220}
221
222/// One segment: its tree rewritten to its own index space, the scans it reads, and the subtrees cut
223/// out of it.
224///
225/// `FusedSeries` requires dense source indices, so a segment numbers its scans first, in the order
226/// it first names them, then its cut subtrees.
227pub struct Segment {
228    pub node: NativeNode,
229    /// Original scan indices, in the order this segment's indices name them.
230    pub sources: Vec<usize>,
231    /// The subtrees cut out of this segment, each still in the original index space.
232    pub cut: Vec<NativeNode>,
233}
234
235/// Collects a segment's scans and cut subtrees, without descending into a cut.
236fn collect_segment(
237    node: &NativeNode,
238    sources: &mut Vec<usize>,
239    cut: &mut Vec<NativeNode>,
240    canonical_segmentation: bool,
241) {
242    match &node.expr {
243        NativeExpr::Input(input) => {
244            if !sources.contains(&input.source_index) {
245                sources.push(input.source_index);
246            }
247        }
248        expr => {
249            for child in expr.children() {
250                if cut_as_segment(child, canonical_segmentation) {
251                    cut.push(child.clone());
252                } else {
253                    collect_segment(child, sources, cut, canonical_segmentation);
254                }
255            }
256        }
257    }
258}
259
260/// Collects every scan input in a selected segment without looking for nested cuts.
261fn collect_segment_inputs(node: &NativeNode, sources: &mut Vec<usize>) {
262    for input in node.inputs() {
263        if !sources.contains(&input.source_index) {
264            sources.push(input.source_index);
265        }
266    }
267}
268
269/// Rewrites every input leaf in a selected segment to its index in the segment's own space.
270fn rewrite_inner_segment(node: &NativeNode, sources: &[usize]) -> NativeNode {
271    let expr = match &node.expr {
272        NativeExpr::Input(input) => NativeExpr::Input(BoundInput {
273            source_index: sources
274                .iter()
275                .position(|&source| source == input.source_index)
276                .expect("the segment collected every scan it reads"),
277            output: input.output.clone(),
278            ordering: input.ordering,
279        }),
280        expr => expr.with_children(
281            expr.children()
282                .into_iter()
283                .map(|child| rewrite_inner_segment(child, sources))
284                .collect(),
285        ),
286    };
287    NativeNode {
288        expr,
289        output: node.output.clone(),
290    }
291}
292
293/// Rewrites a segment's tree so every leaf names its index in the segment's own space.
294fn rewrite_segment(
295    node: &NativeNode,
296    sources: &[usize],
297    cut_base: usize,
298    next_cut: &mut usize,
299    canonical_segmentation: bool,
300) -> NativeNode {
301    let expr = match &node.expr {
302        NativeExpr::Input(input) => NativeExpr::Input(BoundInput {
303            source_index: sources
304                .iter()
305                .position(|&source| source == input.source_index)
306                .expect("the segment collected every scan it reads"),
307            output: input.output.clone(),
308            ordering: input.ordering,
309        }),
310        expr => {
311            let children = expr
312                .children()
313                .into_iter()
314                .map(|child| {
315                    if cut_as_segment(child, canonical_segmentation) {
316                        let index = cut_base + *next_cut;
317                        *next_cut += 1;
318                        NativeNode {
319                            expr: NativeExpr::Input(BoundInput {
320                                source_index: index,
321                                output: child.output.clone(),
322                                ordering: NATIVE_ORDERING,
323                            }),
324                            output: child.output.clone(),
325                        }
326                    } else {
327                        rewrite_segment(child, sources, cut_base, next_cut, canonical_segmentation)
328                    }
329                })
330                .collect::<Vec<_>>();
331            expr.with_children(children)
332        }
333    };
334    NativeNode {
335        expr,
336        output: node.output.clone(),
337    }
338}
339
340/// Splits `node` into one segment and the subtrees cut out of it.
341pub fn cut_segments(node: &NativeNode, canonical_segmentation: bool) -> Segment {
342    let mut sources = Vec::new();
343    let mut cut = Vec::new();
344    collect_segment(node, &mut sources, &mut cut, canonical_segmentation);
345    let cut_base = sources.len();
346    let mut next_cut = 0;
347    let rewritten = rewrite_segment(
348        node,
349        &sources,
350        cut_base,
351        &mut next_cut,
352        canonical_segmentation,
353    );
354    Segment {
355        node: rewritten,
356        sources,
357        cut,
358    }
359}
360
361/// Moves or appends `__name__` to the end of a rows layout's tag list. A scalar root gets no name
362/// column.
363pub fn with_row_name_column(node: &NativeNode, mut tags: Vec<String>) -> Vec<String> {
364    if !matches!(&node.output, NativeType::Samples(_)) {
365        return tags;
366    }
367    if let Some(index) = tags.iter().position(|tag| tag == METRIC_NAME) {
368        tags.remove(index);
369    }
370    tags.push(METRIC_NAME.to_string());
371    tags
372}
373
374/// The ordering trees are compiled against: the weaker of a native scan's `KeyThenTime` and a
375/// two-phase scan's `Contiguous`, since the logical planner cannot tell which a statement gets.
376pub const NATIVE_ORDERING: SeriesOrdering = SeriesOrdering::Contiguous;
377
378/// The output schema of a fused node: a non-nullable millisecond time index, one nullable column
379/// of `field_kind` per field, then nullable `Utf8` tags. Value columns are named by the caller's
380/// [`FieldNames`].
381pub fn fused_output_schema(
382    fields: &[String],
383    tags: &[String],
384    time_index: &str,
385    field_kind: FieldKind,
386) -> datafusion::common::Result<DFSchemaRef> {
387    let field_type = match field_kind {
388        FieldKind::Float => ArrowDataType::Float64,
389        FieldKind::Histogram => native_histogram_value_type().as_arrow_type(),
390    };
391    let mut columns = Vec::with_capacity(fields.len() + tags.len() + 1);
392    // Marked as the existing planner marks it, for `RANGE` queries and schema conversion.
393    columns.push((
394        None,
395        Arc::new(
396            Field::new(
397                time_index,
398                ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
399                false,
400            )
401            .with_metadata(std::collections::HashMap::from([(
402                datatypes::schema::TIME_INDEX_KEY.to_string(),
403                "true".to_string(),
404            )])),
405        ),
406    ));
407    for name in fields {
408        columns.push((None, Arc::new(Field::new(name, field_type.clone(), true))));
409    }
410    for name in tags {
411        let mut field = Field::new(name, ArrowDataType::Utf8, true);
412        // Tells the response layer each row carries its own name.
413        if name == METRIC_NAME {
414            field = field.with_metadata(datatypes::schema::metric_name_field_metadata());
415        }
416        columns.push((None, Arc::new(field)));
417    }
418
419    let metadata = std::collections::HashMap::from([(
420        datatypes::schema::VERSION_KEY.to_string(),
421        datatypes::schema::Schema::INITIAL_VERSION.to_string(),
422    )]);
423    Ok(Arc::new(DFSchema::new_with_metadata(columns, metadata)?))
424}
425
426/// The grid a `FusedSeries` publishes on: its root's grid, which inside a subquery is the
427/// subquery's grid, or `statement_grid` for a root without one.
428fn fused_publish_grid(root: &NativeNode, statement_grid: &Arc<EvalGrid>) -> Arc<EvalGrid> {
429    root.output
430        .grid()
431        .map_or_else(|| Arc::clone(statement_grid), Arc::clone)
432}
433
434/// Lowers a tree whose root is a canonical merge into a producer and a canonical router, and
435/// returns the plan with the tags its frames carry.
436///
437/// - The producer runs the merge on every scan partition, so a same-partition collision fails
438///   there, and exports one series per label set as a frame.
439/// - The router is `SeriesRepartitionExec`'s canonical routing: it publishes a label set once every
440///   producer contributed it or ended, and reports a second piece holding a taken position.
441///
442/// `format` is what the caller reads: rows for a statement root, frames otherwise. `None` when the
443/// boundary cannot be built, so the caller keeps its plan.
444#[allow(clippy::too_many_arguments)]
445pub fn canonical_boundary_stages(
446    promql: Arc<str>,
447    tree: &NativeTree,
448    children: &[LogicalPlan],
449    source_tags: &[Vec<String>],
450    grid: &Arc<EvalGrid>,
451    time_index: &str,
452    tags: &[String],
453    metric: &Option<Arc<str>>,
454    format: FusedOutputFormat,
455    root_kind: FieldKind,
456    output_tags_of: OutputTags,
457    field_names: FieldNames,
458) -> Option<(LogicalPlan, Vec<String>)> {
459    let NativeExpr::Merge { input } = &tree.root().expr else {
460        return None;
461    };
462    if !canonical_local_prefix(input) {
463        return None;
464    }
465    let NativeType::Samples(schema) = &tree.root().output else {
466        return None;
467    };
468    schema.eval_grid.as_ref()?;
469    let fields = schema
470        .fields
471        .iter()
472        .map(|field| field.name.to_string())
473        .collect::<Vec<_>>();
474    let output_tags = output_tags_of(tree.root(), source_tags)?;
475    let row_tags = with_row_name_column(tree.root(), output_tags.clone());
476    // A column-name collision declines, so the caller keeps its plan.
477    let value_names = field_names(&promql, &fields);
478    let output_schema = fused_output_schema(&value_names, &row_tags, time_index, root_kind).ok()?;
479
480    let producer = FusedSeries::try_new_canonical_producer(
481        Arc::clone(&promql),
482        tree.clone(),
483        FusedSeriesBinding {
484            grid: Arc::clone(grid),
485            time_index: time_index.to_string(),
486            tags: tags.to_vec(),
487            metric_name: metric.clone(),
488        },
489        children.to_vec(),
490    )
491    .ok()?;
492    let producer = LogicalPlan::Extension(Extension {
493        node: Arc::new(producer),
494    });
495
496    // A consumer above reads the routed frames as an ordinary evaluated input; the statement root
497    // converts them to rows.
498    if format == FusedOutputFormat::SeriesFrame {
499        return Some((producer, output_tags));
500    }
501    let evaluated = NativeType::Samples(Arc::clone(schema));
502    let consumer_tree = NativeTree::try_new(NativeNode {
503        expr: NativeExpr::Input(BoundInput {
504            source_index: 0,
505            output: evaluated.clone(),
506            ordering: NATIVE_ORDERING,
507        }),
508        output: evaluated,
509    })
510    .ok()?;
511    // A frame names each series' own metric, so the binding names one only when a tag column does.
512    let consumer_metric = if output_tags.iter().any(|tag| tag == METRIC_NAME) {
513        metric.clone()
514    } else {
515        None
516    };
517    let consumer = FusedSeries::try_new_with_format(
518        Arc::clone(&promql),
519        consumer_tree,
520        FusedSeriesBinding {
521            grid: Arc::clone(grid),
522            time_index: time_index.to_string(),
523            tags: output_tags.clone(),
524            metric_name: consumer_metric,
525        },
526        vec![producer],
527        output_schema,
528        FusedOutputFormat::PlainRows,
529    )
530    .ok()?;
531    Some((
532        LogicalPlan::Extension(Extension {
533            node: Arc::new(consumer),
534        }),
535        output_tags,
536    ))
537}
538
539fn is_raw_series_source(plan: &LogicalPlan) -> bool {
540    match plan {
541        LogicalPlan::Extension(extension) => extension.node.as_any().is::<RawSeriesSource>(),
542        _ => false,
543    }
544}
545
546/// Whether `plan` is a discovered selector's [`RawSeriesSource`], or the `Union` of several. It is
547/// used as is: wrapping it in another source is refused by the physical planner.
548fn is_sourced_plan(plan: &LogicalPlan) -> bool {
549    matches!(plan, LogicalPlan::Union(_)) || is_raw_series_source(plan)
550}
551
552fn find_input_node(node: &NativeNode, source_index: usize) -> Option<&BoundInput> {
553    node.inputs()
554        .into_iter()
555        .find(|input| input.source_index == source_index)
556}
557
558/// Whether `plan` is the typed empty input of a discovered selector that matched no table: an
559/// `EmptyRelation` declaring the raw explicit-label frame.
560pub fn is_empty_discovered_input(plan: &LogicalPlan) -> bool {
561    let LogicalPlan::EmptyRelation(relation) = plan else {
562        return false;
563    };
564    if relation.produce_one_row {
565        return false;
566    }
567    let Ok(declaration) = SeriesFrameDeclaration::parse(relation.schema.as_arrow()) else {
568        return false;
569    };
570    if declaration.content() != FrameContent::Raw
571        || declaration.labels() != FrameLabelMode::Explicit
572    {
573        return false;
574    }
575    let Ok(frame) = raw_series_frame_schema_with_ordering(
576        declaration.series(),
577        &RawLabelSource::Explicit,
578        NATIVE_ORDERING,
579    ) else {
580        return false;
581    };
582    relation.schema.as_arrow() == frame.as_ref()
583}
584
585#[allow(clippy::too_many_arguments, clippy::type_complexity)]
586fn build_evaluated_segment(
587    promql: Arc<str>,
588    node: &NativeNode,
589    children: &[LogicalPlan],
590    source_tags: &[Vec<String>],
591    source_ids: &[Option<usize>],
592    per_source: &[(Option<Arc<str>>, String, Vec<String>)],
593    grid: &Arc<EvalGrid>,
594    time_index: &str,
595    root_kind: FieldKind,
596    output_tags_of: OutputTags,
597    field_names: FieldNames,
598) -> Option<(LogicalPlan, Vec<String>)> {
599    let mut sources = Vec::new();
600    collect_segment_inputs(node, &mut sources);
601    if sources.is_empty() {
602        return None;
603    }
604    let mut inputs = Vec::with_capacity(sources.len());
605    let mut local_tags = Vec::with_capacity(sources.len());
606    let tree = NativeTree::try_new(rewrite_inner_segment(node, &sources)).ok()?;
607    let source_fields = tree_source_fields(&tree).ok()?;
608    for (local_index, &index) in sources.iter().enumerate() {
609        let child = children.get(index)?.clone();
610        let input = find_input_node(node, index)?;
611        if input
612            .output
613            .samples()
614            .is_some_and(|schema| schema.eval_grid.is_some())
615            || is_sourced_plan(&child)
616            || is_empty_discovered_input(&child)
617        {
618            inputs.push(child);
619            local_tags.push(source_tags.get(index)?.clone());
620        } else {
621            let original_index = *source_ids.get(index)?.as_ref()?;
622            let (Some((Some(metric), _, tags)), Some(fields)) = (
623                per_source.get(original_index),
624                source_fields.get(local_index),
625            ) else {
626                return None;
627            };
628            inputs.push(LogicalPlan::Extension(Extension {
629                node: Arc::new(
630                    RawSeriesSource::try_new(
631                        Arc::clone(metric),
632                        tags.clone(),
633                        fields.clone(),
634                        child,
635                    )
636                    .ok()?,
637                ),
638            }));
639            local_tags.push(tags.clone());
640        }
641    }
642    if matches!(tree.root().expr, NativeExpr::Merge { .. }) {
643        let (plan, tags) = canonical_boundary_stages(
644            Arc::clone(&promql),
645            &tree,
646            &inputs,
647            &local_tags,
648            grid,
649            time_index,
650            &[],
651            &None,
652            FusedOutputFormat::SeriesFrame,
653            root_kind,
654            output_tags_of,
655            field_names,
656        )?;
657        return Some((plan, tags));
658    }
659    let output_tags = output_tags_of(tree.root(), &local_tags)?;
660    if !native_tree_supported(&tree) {
661        return None;
662    }
663    let frame = FusedSeries::series_frame_schema(&tree).ok()?;
664    let frame = DFSchema::try_from(frame.as_ref().clone()).ok()?;
665    let publish_grid = fused_publish_grid(tree.root(), grid);
666    let plan = FusedSeries::try_new_with_format(
667        Arc::from("segment"),
668        tree,
669        FusedSeriesBinding {
670            grid: publish_grid,
671            time_index: time_index.to_string(),
672            tags: output_tags.clone(),
673            metric_name: None,
674        },
675        inputs,
676        Arc::new(frame),
677        FusedOutputFormat::SeriesFrame,
678    )
679    .ok()?;
680    Some((
681        LogicalPlan::Extension(Extension {
682            node: Arc::new(plan),
683        }),
684        output_tags,
685    ))
686}
687
688/// Builds one segment's plan from a subtree without cutting again, and returns it with its output
689/// tags. `None` when any part cannot be built.
690#[allow(clippy::type_complexity)]
691fn build_inner_segment(
692    node: &NativeNode,
693    bare_scans: &[LogicalPlan],
694    per_source: &[(Option<Arc<str>>, String, Vec<String>)],
695    grid: &Arc<EvalGrid>,
696    output_tags_of: OutputTags,
697) -> Option<(LogicalPlan, Vec<String>)> {
698    let mut sources = Vec::new();
699    collect_segment_inputs(node, &mut sources);
700    if sources.is_empty() {
701        return None;
702    }
703    let scans = sources
704        .iter()
705        .map(|&index| bare_scans.get(index).cloned())
706        .collect::<Option<Vec<_>>>()?;
707    let source_tags = sources
708        .iter()
709        .map(|&index| per_source.get(index).map(|(_, _, tags)| tags.clone()))
710        .collect::<Option<Vec<_>>>()?;
711    let tree = NativeTree::try_new(rewrite_inner_segment(node, &sources)).ok()?;
712    let output_tags = output_tags_of(tree.root(), &source_tags)?;
713    let segment_grid = fused_publish_grid(tree.root(), grid);
714    let (inputs, metric, time_index, tags) = if let [index] = sources.as_slice() {
715        let (metric, time_index, tags) = per_source.get(*index)?;
716        (scans, metric.clone(), time_index.clone(), tags.clone())
717    } else {
718        // One binding cannot describe several sources, so each child gets its own
719        // explicit-label source.
720        let source_fields = tree_source_fields(&tree).ok()?;
721        let mut children = Vec::with_capacity(sources.len());
722        for (local_index, &source_index) in sources.iter().enumerate() {
723            let scan = scans.get(local_index)?;
724            if is_sourced_plan(scan) {
725                children.push(scan.clone());
726                continue;
727            }
728            let (Some((Some(metric), _, source_tags)), Some(fields)) =
729                (per_source.get(source_index), source_fields.get(local_index))
730            else {
731                return None;
732            };
733            children.push(LogicalPlan::Extension(Extension {
734                node: Arc::new(
735                    RawSeriesSource::try_new(
736                        Arc::clone(metric),
737                        source_tags.clone(),
738                        fields.clone(),
739                        scan.clone(),
740                    )
741                    .ok()?,
742                ),
743            }));
744        }
745        let time_index = per_source.get(*sources.first()?)?.1.clone();
746        (children, None, time_index, output_tags.clone())
747    };
748    if !native_tree_supported(&tree) {
749        return None;
750    }
751    let frame = FusedSeries::series_frame_schema(&tree).ok()?;
752    let frame = DFSchema::try_from(frame.as_ref().clone()).ok()?;
753    let plan = FusedSeries::try_new_with_format(
754        Arc::from("segment"),
755        tree,
756        FusedSeriesBinding {
757            grid: segment_grid,
758            time_index: time_index.clone(),
759            tags: tags.clone(),
760            metric_name: metric.clone(),
761        },
762        inputs,
763        Arc::new(frame),
764        FusedOutputFormat::SeriesFrame,
765    )
766    .ok()?;
767    Some((
768        LogicalPlan::Extension(Extension {
769            node: Arc::new(plan),
770        }),
771        output_tags,
772    ))
773}
774
775/// Plans `tree` as several segments, or `None` when there is nothing to cut or a segment cannot be
776/// built; the caller then keeps the unsegmented plan.
777///
778/// Nested segments publish frames for their parents; only the statement root publishes rows, named
779/// through [`FieldNames`] and [`RootSchema`].
780#[allow(clippy::too_many_arguments, clippy::type_complexity)]
781pub fn segment_tree(
782    promql: Arc<str>,
783    tree: &NativeTree,
784    children: &[LogicalPlan],
785    source_tags: &[Vec<String>],
786    bare_scans: &[LogicalPlan],
787    per_source: &[(Option<Arc<str>>, String, Vec<String>)],
788    grid: &Arc<EvalGrid>,
789    time_index: &str,
790    tags: &[String],
791    metric: &Option<Arc<str>>,
792    format: FusedOutputFormat,
793    canonical_segmentation: bool,
794    root_kind: FieldKind,
795    remote_raw_boundary: bool,
796    output_tags_of: OutputTags,
797    field_names: FieldNames,
798    root_schema: RootSchema,
799) -> Option<LogicalPlan> {
800    // A subquery window root may read across series even where `input_locality` reports a local
801    // tree, so it is attempted too; `cut_as_segment` admits each cut.
802    if !matches!(input_locality(tree.root()), InputLocality::SinglePartition)
803        && !evaluated_input_window(tree.root())
804    {
805        return None;
806    }
807    let mut current_tree = tree.clone();
808    let mut current_children = children.to_vec();
809    let mut current_tags = source_tags.to_vec();
810    let mut current_source_ids = (0..children.len()).map(Some).collect::<Vec<_>>();
811    let mut first_iteration = true;
812    let mut changed = false;
813    loop {
814        if !matches!(
815            input_locality(current_tree.root()),
816            InputLocality::SinglePartition
817        ) && !evaluated_input_window(current_tree.root())
818        {
819            break;
820        }
821        let segment = cut_segments(current_tree.root(), canonical_segmentation);
822        if segment.cut.is_empty() {
823            break;
824        }
825        let mut inputs = Vec::with_capacity(segment.sources.len() + segment.cut.len());
826        let mut child_tags = Vec::with_capacity(inputs.capacity());
827        for &index in &segment.sources {
828            let child = current_children.get(index)?;
829            inputs.push(child.clone());
830            child_tags.push(current_tags.get(index).cloned().unwrap_or_default());
831        }
832        let mut child_source_ids = segment
833            .sources
834            .iter()
835            .map(|&index| current_source_ids.get(index).copied().flatten())
836            .collect::<Vec<_>>();
837        for cut in &segment.cut {
838            // A cut wrapping a global consumer is segmented recursively, so its inner canonical
839            // boundary stays below the consumer.
840            let canonical = matches!(cut.expr, NativeExpr::Merge { .. });
841            let built = if first_iteration && contains_global_consumer(cut) {
842                let cut_tree = NativeTree::try_new(cut.clone()).ok()?;
843                let plan = segment_tree(
844                    Arc::clone(&promql),
845                    &cut_tree,
846                    &current_children,
847                    &current_tags,
848                    bare_scans,
849                    per_source,
850                    grid,
851                    time_index,
852                    tags,
853                    metric,
854                    FusedOutputFormat::SeriesFrame,
855                    canonical_segmentation,
856                    root_kind,
857                    remote_raw_boundary,
858                    output_tags_of,
859                    field_names,
860                    root_schema,
861                );
862                match plan {
863                    Some(plan) => {
864                        let cut_tags = output_tags_of(cut, &current_tags)?;
865                        Some((plan, cut_tags))
866                    }
867                    None => None,
868                }
869            } else if first_iteration && !canonical && !remote_raw_boundary {
870                build_inner_segment(cut, bare_scans, per_source, grid, output_tags_of)
871            } else {
872                None
873            };
874            if built.is_none() && contains_global_consumer(cut) {
875                return None;
876            }
877            // Otherwise the cut is built over the frames this loop has already published.
878            let built = built.or_else(|| {
879                build_evaluated_segment(
880                    Arc::clone(&promql),
881                    cut,
882                    &current_children,
883                    &current_tags,
884                    &current_source_ids,
885                    per_source,
886                    grid,
887                    time_index,
888                    root_kind,
889                    output_tags_of,
890                    field_names,
891                )
892            });
893            let (plan, cut_tags) = built?;
894            inputs.push(plan);
895            child_tags.push(cut_tags);
896            child_source_ids.push(None);
897        }
898        let parent = NativeTree::try_new(segment.node).ok()?;
899        first_iteration = false;
900        current_tree = parent;
901        current_children = inputs;
902        current_tags = child_tags;
903        current_source_ids = child_source_ids;
904        changed = true;
905    }
906    if !changed {
907        return None;
908    }
909    let parent = current_tree;
910    let mut inputs = current_children;
911    let mut child_tags = current_tags;
912    // A merge at this segment's root still needs its own boundary.
913    if let NativeExpr::Merge { input } = &parent.root().expr {
914        let source_fields = tree_source_fields(&parent).ok();
915        for index in 0..inputs.len() {
916            let bound = find_input_node(input, index)?;
917            if bound
918                .output
919                .samples()
920                .is_some_and(|schema| schema.eval_grid.is_none())
921                && !is_raw_series_source(&inputs[index])
922            {
923                let source_index = current_source_ids.get(index).copied().flatten()?;
924                let (Some((Some(source_metric), _, source_tags)), Some(fields)) = (
925                    per_source.get(source_index),
926                    source_fields.as_ref().and_then(|fields| fields.get(index)),
927                ) else {
928                    return None;
929                };
930                let Ok(source) = RawSeriesSource::try_new(
931                    Arc::clone(source_metric),
932                    source_tags.clone(),
933                    fields.clone(),
934                    inputs[index].clone(),
935                ) else {
936                    return None;
937                };
938                inputs[index] = LogicalPlan::Extension(Extension {
939                    node: Arc::new(source),
940                });
941                child_tags[index] = source_tags.clone();
942            }
943        }
944        return canonical_boundary_stages(
945            Arc::clone(&promql),
946            &parent,
947            &inputs,
948            &child_tags,
949            grid,
950            time_index,
951            tags,
952            metric,
953            format,
954            root_kind,
955            output_tags_of,
956            field_names,
957        )
958        .map(|(plan, _)| plan);
959    }
960    // Physical planning cannot fall back, so refuse here what the runtime would refuse.
961    if !native_tree_supported(&parent) {
962        return None;
963    }
964    let output_schema = match format {
965        FusedOutputFormat::PlainRows => {
966            root_schema(&promql, &parent, &child_tags, time_index, root_kind)?
967        }
968        FusedOutputFormat::SeriesFrame => {
969            let Ok(frame) = FusedSeries::series_frame_schema(&parent) else {
970                return None;
971            };
972            let Ok(schema) = DFSchema::try_from(frame.as_ref().clone()) else {
973                return None;
974            };
975            Arc::new(schema)
976        }
977    };
978    // A recursive segment keeps its own source's metric; its parent's would relabel both inputs.
979    let segment_binding = |source_ids: &[Option<usize>]| -> (Option<Arc<str>>, String) {
980        let mut sources = source_ids.iter().flatten().copied();
981        let Some(source) = sources.next() else {
982            return (metric.clone(), time_index.to_string());
983        };
984        if sources.next().is_some() {
985            return (None, time_index.to_string());
986        }
987        per_source.get(source).map_or_else(
988            || (metric.clone(), time_index.to_string()),
989            |(metric, time, _)| (metric.clone(), time.clone()),
990        )
991    };
992    let (segment_metric, segment_time_index) = segment_binding(&current_source_ids);
993    // Recursion reaches a cut inside a subquery window with the statement's grid, not the
994    // subquery's, so the root's own grid is bound.
995    let publish_grid = fused_publish_grid(parent.root(), grid);
996    let Ok(plan) = FusedSeries::try_new_with_format(
997        Arc::clone(&promql),
998        parent,
999        FusedSeriesBinding {
1000            grid: publish_grid,
1001            time_index: segment_time_index,
1002            tags: tags.to_vec(),
1003            metric_name: segment_metric,
1004        },
1005        inputs,
1006        output_schema,
1007        format,
1008    ) else {
1009        return None;
1010    };
1011    Some(LogicalPlan::Extension(Extension {
1012        node: Arc::new(plan),
1013    }))
1014}
1015
1016#[cfg(test)]
1017mod tests {
1018    use std::sync::Arc;
1019
1020    use datatypes::series::SeriesOrdering;
1021    use datatypes::series::samples::{FieldSpec, SeriesSchema};
1022    use datatypes::series::time::{EvalGrid, GridSpec};
1023
1024    use super::*;
1025    use crate::map::MathOp;
1026    use crate::native::plan::{
1027        AggregateKind, AggregateStage, BoundAggregate, BoundInput, BoundInstant, BoundMap,
1028        Grouping, InstantValue, MapOp,
1029    };
1030
1031    fn grid() -> Arc<EvalGrid> {
1032        Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1, 4).unwrap()).unwrap())
1033    }
1034
1035    fn evaluated(grid: &Arc<EvalGrid>) -> NativeType {
1036        NativeType::Samples(Arc::new(SeriesSchema {
1037            fields: vec![FieldSpec {
1038                name: Arc::from("value"),
1039            }]
1040            .into(),
1041            eval_grid: Some(Arc::clone(grid)),
1042        }))
1043    }
1044
1045    fn map_over(inner: NativeNode) -> NativeNode {
1046        let output = inner
1047            .output
1048            .grid()
1049            .expect("a map reads an evaluated vector")
1050            .clone();
1051        NativeNode {
1052            expr: NativeExpr::Map {
1053                input: Box::new(inner),
1054                op: BoundMap {
1055                    ops: vec![MapOp::Math(MathOp::Abs)].into(),
1056                },
1057            },
1058            output: evaluated(&output),
1059        }
1060    }
1061
1062    fn selection(inner: NativeNode, output: NativeType) -> NativeNode {
1063        let grid = output
1064            .grid()
1065            .expect("a selection answers on a grid")
1066            .clone();
1067        NativeNode {
1068            expr: NativeExpr::Instant {
1069                input: Box::new(inner),
1070                op: BoundInstant {
1071                    lookback_ms: 300_000,
1072                    offset_ms: 0,
1073                    at_ms: None,
1074                    value: InstantValue::Sample,
1075                    output_grid: grid,
1076                },
1077            },
1078            output,
1079        }
1080    }
1081
1082    #[test]
1083    fn a_fold_that_reads_its_parameter_is_a_global_consumer() {
1084        let grid = grid();
1085        let output = evaluated(&grid);
1086        let source = NativeNode {
1087            expr: NativeExpr::Input(BoundInput {
1088                output: output.clone(),
1089                source_index: 0,
1090                ordering: SeriesOrdering::Contiguous,
1091            }),
1092            output: output.clone(),
1093        };
1094        let fold = NativeNode {
1095            expr: NativeExpr::ParameterizedAggregate {
1096                input: Box::new(selection(source.clone(), output.clone())),
1097                op: BoundAggregate {
1098                    kind: AggregateKind::Quantile { quantile: 0.0 },
1099                    group: Grouping::By(Arc::from([])),
1100                    stage: AggregateStage::Complete,
1101                    field_kind: FieldKind::Float,
1102                },
1103                parameter: Box::new(NativeNode {
1104                    expr: NativeExpr::EvalTime { date: None },
1105                    output: NativeType::Scalar(Arc::clone(&grid)),
1106                }),
1107            },
1108            output: output.clone(),
1109        };
1110        assert!(
1111            contains_global_consumer(&fold),
1112            "a fold that reads its `φ` per point reads the whole vector"
1113        );
1114        assert!(
1115            contains_global_consumer(&map_over(fold)),
1116            "a pointwise parent must not hide the fold's gather"
1117        );
1118        assert!(
1119            !contains_global_consumer(&map_over(selection(source, output))),
1120            "a selection is not a whole-vector consumer"
1121        );
1122    }
1123}