Skip to main content

query/optimizer/
series_frame_output.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
15use std::sync::Arc;
16
17use datafusion::config::ConfigOptions;
18use datafusion::physical_optimizer::PhysicalOptimizerRule;
19use datafusion::physical_plan::ExecutionPlan;
20use datafusion_common::{DataFusionError, Result as DfResult};
21use datatypes::series::frame::{FrameContent, FrameLabelMode, SeriesFrameDeclaration};
22use promql::extension_plan::{RawSeriesSourceExec, SeriesRepartitionExec};
23
24/// Ensures a multi-partition series-frame *root* is emitted through one output partition.
25///
26/// The client receives one stream. Some multi-partition frame roots need identities merged across
27/// partitions; region per-series scans do not, because their scan contract assigns each identity to
28/// one partition.
29///
30/// The view is the root of a query-engine execution, which in a distributed statement is one
31/// region's own root as well: a region answers its part of the statement through the same engine,
32/// so the same coalescing would otherwise apply to the frames it hands upstream.
33///
34/// This rule normalizes the plan's root and nothing else. A single-partition root is left alone:
35/// one producer's finality is the whole answer when that producer is the entire output, and the
36/// router's job is reconciling several producers rather than raw content as such. Frame edges
37/// below the root stay the responsibility of the operator that builds them - `FusedSeries` inserts
38/// its own owner where a consumer needs one - so this is not a guard against every frame-shaped
39/// subplan an arbitrary caller might execute directly.
40#[derive(Debug, Default)]
41pub struct SeriesFrameOutput;
42
43impl PhysicalOptimizerRule for SeriesFrameOutput {
44    fn optimize(
45        &self,
46        plan: Arc<dyn ExecutionPlan>,
47        _config: &ConfigOptions,
48    ) -> DfResult<Arc<dyn ExecutionPlan>> {
49        let schema = plan.schema();
50        if !schema
51            .metadata()
52            .keys()
53            .any(|key| key.starts_with("greptime.series."))
54        {
55            return Ok(plan);
56        }
57
58        let declaration = SeriesFrameDeclaration::parse(schema.as_ref()).map_err(|error| {
59            DataFusionError::Plan(format!("invalid series frame declaration: {error}"))
60        })?;
61        if plan.properties().output_partitioning().partition_count() <= 1 {
62            return Ok(plan);
63        }
64        // A raw frame reaches the client through the same single stream, and ordinary batch
65        // coalescing cannot produce it: a chunk's `is_last` closes only its own producer, so
66        // coalescing would hand over several partial series under one identity. The router needs
67        // explicit labels to check that one key has one binding; a key-only frame therefore stays
68        // rejected rather than silently coalesced.
69        //
70        // Ordinary multi-partition roots need their identities merged, but a root whose producer
71        // declared that each identity lives in one partition does not: its chain is the identity.
72        if declaration.content() == FrameContent::Raw
73            && declaration.labels() != FrameLabelMode::Explicit
74        {
75            return Err(DataFusionError::Plan(
76                "a multi-partition raw series frame needs explicit labels to be merged into one \
77                 output stream"
78                    .into(),
79            ));
80        }
81
82        let completion = plan
83            .downcast_ref::<RawSeriesSourceExec>()
84            .is_some_and(RawSeriesSourceExec::is_per_series_scan)
85            || plan.downcast_ref::<SeriesRepartitionExec>().is_some()
86            || plan
87                .downcast_ref::<promql::extension_plan::FusedSeriesExec>()
88                .is_some_and(|fused| fused.has_partition_disjoint_identities());
89        if completion {
90            Ok(Arc::new(SeriesRepartitionExec::try_new_complete_disjoint(
91                plan, 1,
92            )?))
93        } else {
94            Ok(Arc::new(SeriesRepartitionExec::try_new(plan, 1)?))
95        }
96    }
97
98    fn name(&self) -> &str {
99        "SeriesFrameOutput"
100    }
101
102    fn schema_check(&self) -> bool {
103        true
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use api::v1::SemanticType;
110    use common_error::ext::BoxedError;
111    use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream};
112    use datafusion::arrow::datatypes::Schema;
113    use datafusion::arrow::record_batch::RecordBatch;
114    use datafusion::common::DFSchema;
115    use datafusion::datasource::memory::MemorySourceConfig;
116    use datafusion::datasource::source::DataSourceExec;
117    use datafusion::logical_expr::{EmptyRelation, LogicalPlan};
118    use datafusion::physical_optimizer::ensure_coop::EnsureCooperative;
119    use datafusion::physical_plan::PhysicalExpr;
120    use datafusion::physical_plan::coop::CooperativeExec;
121    use datafusion::physical_plan::display::{DisplayAs, DisplayFormatType};
122    use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
123    use datatypes::data_type::ConcreteDataType;
124    use datatypes::schema::{ColumnSchema, SchemaRef};
125    use datatypes::series::SeriesOrdering;
126    use datatypes::series::frame::raw_series_frame_schema;
127    use datatypes::series::samples::{FieldSpec, SeriesSchema};
128    use datatypes::series::time::{EvalGrid, GridSpec};
129    use promql::extension_plan::{
130        FusedOutputFormat, FusedSeries, FusedSeriesBinding, RawSeriesSource, SeriesRouting,
131    };
132    use promql::native::plan::{
133        BoundInput, BoundInstant, BoundWindow, InstantValue, NativeExpr, NativeNode, NativeTree,
134        NativeType,
135    };
136    use promql::range_eval::{RangeFunction, RangeWindow};
137    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
138    use store_api::region_engine::{
139        BoundTag, PrepareRequest, QueryScanContext, RawLabelSource, RegionScanner,
140        ScannerProperties,
141    };
142    use store_api::storage::{RegionId, ScanRequest};
143    use table::table::scan::RegionScanExec;
144
145    use super::*;
146
147    fn series_schema() -> Arc<SeriesSchema> {
148        Arc::new(SeriesSchema {
149            fields: Arc::from([FieldSpec {
150                name: Arc::from("value"),
151            }]),
152            eval_grid: None,
153        })
154    }
155
156    fn raw_frame_schema() -> Arc<Schema> {
157        raw_series_frame_schema(&series_schema(), FrameLabelMode::Explicit)
158            .expect("a raw frame declares its layout")
159    }
160
161    /// A plan declaring `partitions` empty explicit-label raw-frame partitions.
162    fn raw_plan(partitions: usize) -> Arc<dyn ExecutionPlan> {
163        let schema = raw_frame_schema();
164        let batch = RecordBatch::new_empty(Arc::clone(&schema));
165        let batches = (0..partitions)
166            .map(|_| vec![batch.clone()])
167            .collect::<Vec<_>>();
168        let source = MemorySourceConfig::try_new(&batches, schema, None)
169            .expect("the fixture batches match the frame schema");
170        Arc::new(DataSourceExec::new(Arc::new(source)))
171    }
172
173    fn optimized(plan: Arc<dyn ExecutionPlan>) -> DfResult<Arc<dyn ExecutionPlan>> {
174        SeriesFrameOutput.optimize(plan, &ConfigOptions::default())
175    }
176
177    /// The region layout the raw-series fixtures scan: the tag `host`, the time index and one field.
178    fn region_metadata() -> RegionMetadataRef {
179        let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
180        builder
181            .push_column_metadata(ColumnMetadata {
182                column_schema: ColumnSchema::new(
183                    "host",
184                    ConcreteDataType::string_datatype(),
185                    false,
186                ),
187                semantic_type: SemanticType::Tag,
188                column_id: 1,
189            })
190            .push_column_metadata(ColumnMetadata {
191                column_schema: ColumnSchema::new(
192                    "ts",
193                    ConcreteDataType::timestamp_millisecond_datatype(),
194                    false,
195                )
196                .with_time_index(true),
197                semantic_type: SemanticType::Timestamp,
198                column_id: 2,
199            })
200            .push_column_metadata(ColumnMetadata {
201                column_schema: ColumnSchema::new(
202                    "value",
203                    ConcreteDataType::float64_datatype(),
204                    true,
205                ),
206                semantic_type: SemanticType::Field,
207                column_id: 3,
208            })
209            .primary_key(vec![1]);
210        Arc::new(builder.build().expect("the fixture metadata is valid"))
211    }
212
213    /// The label binding a per-series scan of [`region_metadata`] publishes: every key column is
214    /// bound, so one identity lives in one scan partition.
215    fn per_series_labels() -> RawLabelSource {
216        RawLabelSource::PrimaryKey {
217            metric_name: Arc::from("cpu"),
218            physical_metadata: region_metadata(),
219            logical_tags: Arc::from([BoundTag {
220                column_id: 1,
221                name: Arc::from("host"),
222            }]),
223        }
224    }
225
226    /// The region's scanner, answering the raw-series path the planner selects.
227    #[derive(Debug)]
228    struct RawSeriesScanner {
229        metadata: RegionMetadataRef,
230        properties: ScannerProperties,
231    }
232
233    impl DisplayAs for RawSeriesScanner {
234        fn fmt_as(
235            &self,
236            _format: DisplayFormatType,
237            f: &mut std::fmt::Formatter<'_>,
238        ) -> std::fmt::Result {
239            write!(f, "RawSeriesScanner")
240        }
241    }
242
243    impl RegionScanner for RawSeriesScanner {
244        fn name(&self) -> &str {
245            "RawSeriesScanner"
246        }
247
248        fn properties(&self) -> &ScannerProperties {
249            &self.properties
250        }
251
252        fn schema(&self) -> SchemaRef {
253            Arc::clone(&self.metadata.schema)
254        }
255
256        fn metadata(&self) -> RegionMetadataRef {
257            Arc::clone(&self.metadata)
258        }
259
260        fn prepare(&mut self, request: PrepareRequest) -> std::result::Result<(), BoxedError> {
261            self.properties.prepare(request);
262            Ok(())
263        }
264
265        fn scan_partition(
266            &self,
267            _ctx: &QueryScanContext,
268            _metrics: &ExecutionPlanMetricsSet,
269            _partition: usize,
270        ) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
271            Ok(Box::pin(EmptyRecordBatchStream::new(Arc::clone(
272                &self.metadata.schema,
273            ))))
274        }
275
276        fn raw_series_schema(
277            &self,
278            _label_source: &RawLabelSource,
279        ) -> std::result::Result<Option<Arc<SeriesSchema>>, BoxedError> {
280            Ok(Some(series_schema()))
281        }
282
283        fn has_predicate_without_region(&self) -> bool {
284            true
285        }
286
287        fn add_dyn_filter_to_predicate(
288            &mut self,
289            filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
290        ) -> Vec<bool> {
291            vec![false; filter_exprs.len()]
292        }
293
294        fn set_logical_region(&mut self, logical_region: bool) {
295            self.properties.set_logical_region(logical_region);
296        }
297
298        fn set_query_load_region_id(&mut self, region_id: RegionId) {
299            self.properties.set_query_load_region_id(region_id);
300        }
301    }
302
303    /// A region's native raw-series leaf over `partitions` scan partitions.
304    fn series_scan(partitions: usize) -> Arc<dyn ExecutionPlan> {
305        let scanner = RawSeriesScanner {
306            metadata: region_metadata(),
307            properties: ScannerProperties::new(vec![vec![]; partitions], false, 0),
308        };
309        let scan = Arc::new(
310            RegionScanExec::new(Box::new(scanner), ScanRequest::default(), None)
311                .expect("the fixture scanner scans"),
312        );
313        scan.try_to_series_scan(per_series_labels())
314            .expect("the fixture binding is legal")
315            .expect("the fixture scanner answers raw series")
316    }
317
318    /// A [`RawSeriesSourceExec`] root over `child`, as the region planner builds one.
319    fn raw_source_root(child: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {
320        RawSeriesSource::try_new(
321            Arc::from("cpu"),
322            vec!["host".to_string()],
323            vec!["value".to_string()],
324            LogicalPlan::EmptyRelation(EmptyRelation {
325                produce_one_row: false,
326                schema: Arc::new(
327                    DFSchema::try_from(raw_frame_schema()).expect("the frame is a legal schema"),
328                ),
329            }),
330        )
331        .expect("the source binds one metric")
332        .to_per_series_execution_plan(child)
333        .expect("the child is a raw frame of these fields")
334    }
335
336    /// A fused root running `rate(x[5m])` over `input`, as bound by `labels`.
337    ///
338    /// The window drops the metric name, which is what makes the binding below it decide whether the
339    /// drop keeps two stored series apart.
340    fn fused_rate_root_over(
341        input: Arc<dyn ExecutionPlan>,
342        labels: RawLabelSource,
343    ) -> Arc<dyn ExecutionPlan> {
344        let grid = Arc::new(
345            EvalGrid::try_new(GridSpec::try_new(0, 1_000, 2).expect("the grid is valid"))
346                .expect("the grid is materialized"),
347        );
348        let raw = NativeType::Samples(series_schema());
349        let evaluated = NativeType::Samples(Arc::new(SeriesSchema {
350            fields: series_schema().fields.clone(),
351            eval_grid: Some(Arc::clone(&grid)),
352        }));
353        let tree = NativeTree::try_new(NativeNode {
354            expr: NativeExpr::Window {
355                input: Box::new(NativeNode {
356                    expr: NativeExpr::Input(BoundInput {
357                        source_index: 0,
358                        output: raw.clone(),
359                        ordering: SeriesOrdering::Contiguous,
360                    }),
361                    output: raw,
362                }),
363                op: BoundWindow {
364                    function: RangeFunction::Rate,
365                    window: RangeWindow {
366                        range_ms: 5_000,
367                        offset_ms: 0,
368                        anchor_ms: None,
369                        modifier: None,
370                    },
371                    input_grid: None,
372                    output_grid: Arc::clone(&grid),
373                },
374            },
375            output: evaluated,
376        })
377        .expect("the tree is legal");
378        let output_schema = Arc::new(
379            DFSchema::try_from(
380                FusedSeries::series_frame_schema(&tree).expect("the tree declares a frame"),
381            )
382            .expect("the frame is a legal schema"),
383        );
384        let fused = FusedSeries::try_new_with_format(
385            Arc::from("rate(x[5m])"),
386            tree,
387            FusedSeriesBinding {
388                grid,
389                metric_name: Some(Arc::from("cpu")),
390                time_index: "time".to_string(),
391                tags: vec!["host".to_string()],
392            },
393            vec![LogicalPlan::EmptyRelation(EmptyRelation {
394                produce_one_row: false,
395                schema: Arc::new(
396                    DFSchema::try_from(raw_frame_schema()).expect("the frame is a legal schema"),
397                ),
398            })],
399            output_schema,
400            FusedOutputFormat::SeriesFrame,
401        )
402        .expect("the fused node is planned");
403        fused
404            .to_execution_plan(vec![(input, labels, SeriesOrdering::Contiguous)])
405            .expect("the fused node is physical")
406    }
407
408    /// A fused root running one sample selection over `input`, as bound by `labels`.
409    ///
410    /// The input must be a contiguous raw frame, which both [`series_scan`] and [`raw_plan`] are.
411    fn fused_root_over(
412        input: Arc<dyn ExecutionPlan>,
413        labels: RawLabelSource,
414    ) -> Arc<dyn ExecutionPlan> {
415        let grid = Arc::new(
416            EvalGrid::try_new(GridSpec::try_new(0, 1_000, 2).expect("the grid is valid"))
417                .expect("the grid is materialized"),
418        );
419        let raw = NativeType::Samples(series_schema());
420        let evaluated = NativeType::Samples(Arc::new(SeriesSchema {
421            fields: series_schema().fields.clone(),
422            eval_grid: Some(Arc::clone(&grid)),
423        }));
424        let tree = NativeTree::try_new(NativeNode {
425            expr: NativeExpr::Instant {
426                input: Box::new(NativeNode {
427                    expr: NativeExpr::Input(BoundInput {
428                        source_index: 0,
429                        output: raw.clone(),
430                        ordering: SeriesOrdering::Contiguous,
431                    }),
432                    output: raw,
433                }),
434                op: BoundInstant {
435                    lookback_ms: 0,
436                    offset_ms: 0,
437                    at_ms: None,
438                    value: InstantValue::Sample,
439                    output_grid: Arc::clone(&grid),
440                },
441            },
442            output: evaluated,
443        })
444        .expect("the tree is legal");
445        let output_schema = Arc::new(
446            DFSchema::try_from(
447                FusedSeries::series_frame_schema(&tree).expect("the tree declares a frame"),
448            )
449            .expect("the frame is a legal schema"),
450        );
451        let fused = FusedSeries::try_new_with_format(
452            Arc::from("cpu"),
453            tree,
454            FusedSeriesBinding {
455                grid,
456                metric_name: Some(Arc::from("cpu")),
457                time_index: "time".to_string(),
458                tags: vec!["host".to_string()],
459            },
460            vec![LogicalPlan::EmptyRelation(EmptyRelation {
461                produce_one_row: false,
462                schema: Arc::new(
463                    DFSchema::try_from(raw_frame_schema()).expect("the frame is a legal schema"),
464                ),
465            })],
466            output_schema,
467            FusedOutputFormat::SeriesFrame,
468        )
469        .expect("the fused node is planned");
470        fused
471            .to_execution_plan(vec![(input, labels, SeriesOrdering::Contiguous)])
472            .expect("the fused node is physical")
473    }
474
475    /// A fused root running one sample selection over one per-series scan.
476    fn fused_root(partitions: usize) -> Arc<dyn ExecutionPlan> {
477        fused_root_over(series_scan(partitions), per_series_labels())
478    }
479
480    #[test]
481    fn an_unmarked_raw_root_selects_merge_inputs_router() {
482        let exec = optimized(raw_plan(3)).unwrap();
483        let router = exec.downcast_ref::<SeriesRepartitionExec>().unwrap();
484        assert_eq!(
485            promql::extension_plan::IdentityCompletion::MergeInputs,
486            router.identity_completion()
487        );
488    }
489
490    #[test]
491    fn a_multi_partition_raw_root_is_routed_into_one_output() {
492        let plan = raw_plan(3);
493        assert_eq!(3, plan.properties().output_partitioning().partition_count());
494
495        let exec = optimized(plan).expect("an explicit-label raw root is supported");
496        assert_eq!(
497            1,
498            exec.properties().output_partitioning().partition_count(),
499            "the client sees one raw stream"
500        );
501        let router = exec
502            .downcast_ref::<SeriesRepartitionExec>()
503            .expect("the exit is the shared router");
504        assert_eq!(
505            promql::extension_plan::IdentityCompletion::MergeInputs,
506            router.identity_completion(),
507            "unproven memory roots use conservative merging"
508        );
509        assert_eq!(
510            &SeriesRouting::RawPrimaryKey,
511            router.routing_policy(),
512            "raw identities meet at their complete primary key"
513        );
514        assert_eq!(
515            raw_frame_schema(),
516            exec.schema(),
517            "the frame schema is kept"
518        );
519    }
520
521    #[test]
522    fn a_repartition_root_selects_complete_disjoint_router() {
523        let source: Arc<dyn ExecutionPlan> =
524            Arc::new(SeriesRepartitionExec::try_new(raw_plan(3), 2).unwrap());
525        let exec = optimized(source).unwrap();
526        let router = exec.downcast_ref::<SeriesRepartitionExec>().unwrap();
527        assert_eq!(
528            promql::extension_plan::IdentityCompletion::CompleteDisjoint,
529            router.identity_completion()
530        );
531    }
532
533    #[test]
534    fn a_per_series_raw_root_selects_complete_disjoint_router() {
535        let root = raw_source_root(series_scan(2));
536        assert!(
537            root.downcast_ref::<RawSeriesSourceExec>()
538                .expect("the root is the region's raw source")
539                .is_per_series_scan(),
540            "the fixture root is the per-series case"
541        );
542        assert_eq!(2, root.properties().output_partitioning().partition_count());
543
544        let exec = optimized(root).unwrap();
545        let router = exec
546            .downcast_ref::<SeriesRepartitionExec>()
547            .expect("the root is routed");
548        assert_eq!(
549            promql::extension_plan::IdentityCompletion::CompleteDisjoint,
550            router.identity_completion(),
551            "a per-series scan owns each identity in one partition"
552        );
553    }
554
555    /// `EnsureCooperative` runs before this rule and rebuilds the raw source over a wrapped scan.
556    #[test]
557    fn a_per_series_raw_root_stays_complete_disjoint_behind_ensure_cooperative() {
558        let root = EnsureCooperative::new()
559            .optimize(raw_source_root(series_scan(2)), &ConfigOptions::default())
560            .unwrap();
561        assert!(
562            root.children()[0].is::<CooperativeExec>(),
563            "the fixture scan is wrapped the way the default rules leave it"
564        );
565
566        let exec = optimized(root).unwrap();
567        let router = exec
568            .downcast_ref::<SeriesRepartitionExec>()
569            .expect("the root is routed");
570        assert_eq!(
571            promql::extension_plan::IdentityCompletion::CompleteDisjoint,
572            router.identity_completion()
573        );
574    }
575
576    #[test]
577    fn a_cooperative_scan_keeps_the_per_series_raw_root_on_complete_disjoint() {
578        let root = raw_source_root(series_scan(2));
579        // The physical optimizer wraps the scan leaf, so the raw source is rebuilt over a child that
580        // is no longer the scan itself.
581        let root = EnsureCooperative::new()
582            .optimize(root, &ConfigOptions::default())
583            .expect("the plan is optimized");
584        assert!(
585            root.downcast_ref::<RawSeriesSourceExec>()
586                .expect("the root is still the region's raw source")
587                .is_per_series_scan(),
588            "a cooperative wrapper moves the scan, not the series it answers"
589        );
590
591        let exec = optimized(root).unwrap();
592        let router = exec
593            .downcast_ref::<SeriesRepartitionExec>()
594            .expect("the root is routed");
595        assert_eq!(
596            promql::extension_plan::IdentityCompletion::CompleteDisjoint,
597            router.identity_completion(),
598            "the scan's per-partition ownership survives the wrapper"
599        );
600    }
601
602    #[test]
603    fn a_raw_source_root_without_per_series_provenance_selects_merge_inputs_router() {
604        let root = raw_source_root(raw_plan(2));
605        assert!(
606            !root
607                .downcast_ref::<RawSeriesSourceExec>()
608                .expect("the root is the region's raw source")
609                .is_per_series_scan(),
610            "the fixture root is a raw source over something that is not a per-series scan"
611        );
612
613        let exec = optimized(root).unwrap();
614        let router = exec
615            .downcast_ref::<SeriesRepartitionExec>()
616            .expect("the root is routed");
617        assert_eq!(
618            promql::extension_plan::IdentityCompletion::MergeInputs,
619            router.identity_completion(),
620            "the node alone proves nothing about where a scan keeps its identities"
621        );
622    }
623
624    #[test]
625    fn a_fused_root_with_disjoint_identities_selects_complete_disjoint_router() {
626        let root = fused_root(2);
627        assert!(
628            root.downcast_ref::<promql::extension_plan::FusedSeriesExec>()
629                .expect("the root is the fused node")
630                .has_partition_disjoint_identities(),
631            "the fixture root is the fused case"
632        );
633        assert_eq!(2, root.properties().output_partitioning().partition_count());
634
635        let exec = optimized(root).unwrap();
636        let router = exec
637            .downcast_ref::<SeriesRepartitionExec>()
638            .expect("the root is routed");
639        assert_eq!(
640            promql::extension_plan::IdentityCompletion::CompleteDisjoint,
641            router.identity_completion(),
642            "a fused chain over a per-series scan owns each identity in one partition"
643        );
644    }
645
646    #[test]
647    fn a_fused_rate_root_over_a_per_series_scan_selects_complete_disjoint_router() {
648        let root = fused_rate_root_over(series_scan(2), per_series_labels());
649        assert!(
650            root.downcast_ref::<promql::extension_plan::FusedSeriesExec>()
651                .expect("the root is the fused node")
652                .has_partition_disjoint_identities(),
653            "rate drops the metric name, and the binding below it names one metric and keys its \
654             series by `host`, which the drop leaves in place"
655        );
656        assert_eq!(2, root.properties().output_partitioning().partition_count());
657
658        let exec = optimized(root).unwrap();
659        let router = exec
660            .downcast_ref::<SeriesRepartitionExec>()
661            .expect("the root is routed");
662        assert_eq!(
663            promql::extension_plan::IdentityCompletion::CompleteDisjoint,
664            router.identity_completion(),
665            "a name-dropping window over a single bound metric still owns each identity in one \
666             partition"
667        );
668    }
669
670    #[test]
671    fn a_fused_rate_root_over_an_explicit_source_selects_merge_inputs_router() {
672        let root = fused_rate_root_over(raw_plan(2), RawLabelSource::Explicit);
673        assert!(
674            !root
675                .downcast_ref::<promql::extension_plan::FusedSeriesExec>()
676                .expect("the root is the fused node")
677                .has_partition_disjoint_identities(),
678            "an explicit-label source states no bound key, so the name rate drops is still part of \
679             what tells two series apart"
680        );
681
682        let exec = optimized(root).unwrap();
683        let router = exec
684            .downcast_ref::<SeriesRepartitionExec>()
685            .expect("the root is routed");
686        assert_eq!(
687            promql::extension_plan::IdentityCompletion::MergeInputs,
688            router.identity_completion(),
689            "an unproven source merges its inputs"
690        );
691    }
692
693    #[test]
694    fn a_fused_root_without_disjoint_identities_selects_merge_inputs_router() {
695        let root = fused_root_over(raw_plan(2), RawLabelSource::Explicit);
696        assert!(
697            !root
698                .downcast_ref::<promql::extension_plan::FusedSeriesExec>()
699                .expect("the root is the fused node")
700                .has_partition_disjoint_identities(),
701            "explicit labels say nothing about where a source keeps its identities"
702        );
703        assert_eq!(2, root.properties().output_partitioning().partition_count());
704
705        let exec = optimized(root).unwrap();
706        let router = exec
707            .downcast_ref::<SeriesRepartitionExec>()
708            .expect("the root is routed");
709        assert_eq!(
710            promql::extension_plan::IdentityCompletion::MergeInputs,
711            router.identity_completion(),
712            "a fused node without proven identity placement merges its inputs"
713        );
714    }
715
716    #[test]
717    fn a_single_partition_raw_root_is_left_alone() {
718        let plan = raw_plan(1);
719        let exec = optimized(Arc::clone(&plan)).expect("nothing to normalize");
720        assert!(
721            Arc::ptr_eq(&plan, &exec),
722            "one producer is already the whole answer"
723        );
724    }
725
726    #[test]
727    fn the_rule_does_not_wrap_its_own_output_again() {
728        let routed = optimized(raw_plan(3)).unwrap();
729        let again = optimized(Arc::clone(&routed)).unwrap();
730        assert!(
731            Arc::ptr_eq(&routed, &again),
732            "the exit declares one partition"
733        );
734    }
735
736    #[test]
737    fn a_plan_without_a_frame_declaration_is_untouched() {
738        let schema = Arc::new(Schema::empty());
739        let batch = RecordBatch::new_empty(Arc::clone(&schema));
740        let source =
741            MemorySourceConfig::try_new(&[vec![batch.clone()], vec![batch]], schema, None).unwrap();
742        let plan: Arc<dyn ExecutionPlan> = Arc::new(DataSourceExec::new(Arc::new(source)));
743        let exec = optimized(Arc::clone(&plan)).expect("unrelated plans pass through");
744        assert!(Arc::ptr_eq(&plan, &exec));
745    }
746}