Skip to main content

query/dist_plan/
planner.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//! [ExtensionPlanner] implementation for distributed planner
16
17use std::sync::Arc;
18
19use ahash::HashMap;
20use arrow_schema::SortOptions;
21use async_trait::async_trait;
22use catalog::CatalogManagerRef;
23use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
24use common_telemetry::debug;
25use datafusion::catalog::Session;
26use datafusion::common::Result;
27use datafusion::datasource::DefaultTableSource;
28use datafusion::execution::context::SessionState;
29use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
30use datafusion::physical_plan::ExecutionPlan;
31use datafusion::physical_planner::{ExtensionPlanner, PhysicalPlanner};
32use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion, TreeNodeVisitor};
33use datafusion_common::{DataFusionError, TableReference};
34use datafusion_expr::{Extension, LogicalPlan, UserDefinedLogicalNode};
35use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr};
36use datatypes::prelude::ConcreteDataType;
37use datatypes::value::Value;
38use partition::expr::{Operand, PartitionExpr, RestrictedOp};
39use partition::function::IcebergHash;
40use partition::manager::{
41    PartitionInfo, PartitionRuleManagerRef, create_partitions_from_region_routes,
42};
43use session::context::QueryContext;
44use snafu::{OptionExt, ResultExt};
45use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME};
46use store_api::storage::{RegionId, TableId};
47use table::TableRef;
48use table::metadata::{TableInfo, TableType};
49use table::table::adapter::DfTableProviderAdapter;
50use table::table_name::TableName;
51
52use crate::dist_plan::PredicateExtractor;
53use crate::dist_plan::merge_scan::{MergeScanExec, MergeScanLogicalPlan};
54use crate::dist_plan::merge_sort::{MergeSortExec, MergeSortLogicalPlan};
55use crate::dist_plan::region_pruner::{ConstraintPruner, partition_comparison_matches};
56use crate::error::{CatalogSnafu, PartitionRuleManagerSnafu, TableNotFoundSnafu};
57use crate::optimizer::expr_depth;
58use crate::region_query::RegionQueryHandlerRef;
59
60/// Planner for converting merge sort logical plan to physical plan.
61///
62/// `MergeSortExec` always represents the distributed merge stage. It declares
63/// the required input ordering to DataFusion, so `EnforceSorting` inserts a
64/// `SortExec` below it when the input `MergeScanExec` cannot preserve per-region
65/// ordering, for example when one output partition may merge multiple region
66/// streams.
67pub struct MergeSortExtensionPlanner {}
68
69impl MergeSortExtensionPlanner {
70    fn ordering(
71        planner: &dyn PhysicalPlanner,
72        session: &dyn Session,
73        planning_ctx: &PhysicalPlanningContext,
74        merge_sort: &MergeSortLogicalPlan,
75    ) -> Result<LexOrdering> {
76        let ordering = merge_sort
77            .expr
78            .iter()
79            .map(|sort_expr| {
80                let physical_expr = planner.create_physical_expr(
81                    &sort_expr.expr,
82                    merge_sort.input.schema(),
83                    session,
84                    planning_ctx,
85                )?;
86                Ok(PhysicalSortExpr::new(
87                    physical_expr,
88                    SortOptions {
89                        descending: !sort_expr.asc,
90                        nulls_first: sort_expr.nulls_first,
91                    },
92                ))
93            })
94            .collect::<Result<Vec<_>>>()?;
95
96        LexOrdering::new(ordering).ok_or_else(|| {
97            DataFusionError::Internal(
98                "Expect MergeSort to have non-empty sort expressions".to_string(),
99            )
100        })
101    }
102}
103
104#[async_trait]
105impl ExtensionPlanner for MergeSortExtensionPlanner {
106    async fn plan_extension(
107        &self,
108        planner: &dyn PhysicalPlanner,
109        node: &dyn UserDefinedLogicalNode,
110        _logical_inputs: &[&LogicalPlan],
111        physical_inputs: &[Arc<dyn ExecutionPlan>],
112        session: &dyn Session,
113        planning_ctx: &PhysicalPlanningContext,
114    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
115        if let Some(merge_sort) = node.as_any().downcast_ref::<MergeSortLogicalPlan>() {
116            if let LogicalPlan::Extension(ext) = &merge_sort.input.as_ref()
117                && ext
118                    .node
119                    .as_any()
120                    .downcast_ref::<MergeScanLogicalPlan>()
121                    .is_some()
122            {
123                let input = physical_inputs.first().cloned().ok_or_else(|| {
124                    DataFusionError::Internal(
125                        "Expect MergeSort to have one physical input".to_string(),
126                    )
127                })?;
128                if input.downcast_ref::<MergeScanExec>().is_none() {
129                    return Err(DataFusionError::Internal(format!(
130                        "Expect MergeSort's input is a MergeScanExec, found {:?}",
131                        physical_inputs
132                    )));
133                }
134
135                let ordering = Self::ordering(planner, session, planning_ctx, merge_sort)?;
136                Ok(Some(Arc::new(MergeSortExec::new(
137                    ordering,
138                    input,
139                    merge_sort.fetch,
140                ))))
141            } else {
142                Ok(None)
143            }
144        } else {
145            Ok(None)
146        }
147    }
148}
149
150pub struct DistExtensionPlanner {
151    catalog_manager: CatalogManagerRef,
152    partition_rule_manager: PartitionRuleManagerRef,
153    region_query_handler: RegionQueryHandlerRef,
154    enable_per_region_metrics: bool,
155}
156
157impl DistExtensionPlanner {
158    pub fn new(
159        catalog_manager: CatalogManagerRef,
160        partition_rule_manager: PartitionRuleManagerRef,
161        region_query_handler: RegionQueryHandlerRef,
162        enable_per_region_metrics: bool,
163    ) -> Self {
164        Self {
165            catalog_manager,
166            partition_rule_manager,
167            region_query_handler,
168            enable_per_region_metrics,
169        }
170    }
171}
172
173#[async_trait]
174impl ExtensionPlanner for DistExtensionPlanner {
175    async fn plan_extension(
176        &self,
177        planner: &dyn PhysicalPlanner,
178        node: &dyn UserDefinedLogicalNode,
179        _logical_inputs: &[&LogicalPlan],
180        _physical_inputs: &[Arc<dyn ExecutionPlan>],
181        session: &dyn Session,
182        _planning_ctx: &PhysicalPlanningContext,
183    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
184        let Some(merge_scan) = node.as_any().downcast_ref::<MergeScanLogicalPlan>() else {
185            return Ok(None);
186        };
187
188        let input_plan = merge_scan.input();
189        let fallback = |logical_plan| async move {
190            let optimized_plan = self.optimize_input_logical_plan(session, logical_plan)?;
191            planner
192                .create_physical_plan(&optimized_plan, session)
193                .await
194                .map(Some)
195        };
196
197        if merge_scan.is_placeholder() {
198            // ignore placeholder
199            return fallback(input_plan).await;
200        }
201
202        let optimized_plan = input_plan;
203        let direct_raw = matches!(input_plan, LogicalPlan::Extension(extension)
204            if extension.node.as_any().is::<promql::extension_plan::RawSeriesSource>());
205        let Some(table_name) = Self::extract_full_table_name(input_plan)? else {
206            if direct_raw {
207                return Err(DataFusionError::Plan(
208                    "raw series source has no region route table".into(),
209                ));
210            }
211            // no relation found in input plan, going to execute them locally
212            return fallback(optimized_plan).await;
213        };
214
215        let (regions, series_disjoint) = match self.get_regions(&table_name, input_plan).await {
216            Ok(regions) => regions,
217            Err(error) if direct_raw => {
218                return Err(error);
219            }
220            // Existing non-raw plans may still execute locally when no peers are found.
221            Err(_) => return fallback(optimized_plan).await,
222        };
223
224        // TODO(ruihang): generate different execution plans for different variant merge operation
225        let schema = merge_scan.schema().as_arrow();
226        let session_state = session
227            .as_any()
228            .downcast_ref::<SessionState>()
229            .ok_or_else(|| {
230                DataFusionError::Internal(
231                    "MergeScan requires a SessionState for physical planning".to_string(),
232                )
233            })?;
234        let query_ctx = session_state
235            .config()
236            .get_extension()
237            .unwrap_or_else(QueryContext::arc);
238        // A source that merges label sets does so above this merge scan, where every region's
239        // answer arrives; a region running that merge too would buffer its whole answer and
240        // resolve a shared timestamp from its own share of the keys.
241        let label_set_source = match input_plan {
242            LogicalPlan::Extension(extension) => extension
243                .node
244                .as_any()
245                .downcast_ref::<promql::extension_plan::RawSeriesSource>()
246                .filter(|source| source.merges_label_sets()),
247            _ => None,
248        };
249        let region_plan = match label_set_source {
250            Some(source) => LogicalPlan::Extension(Extension {
251                node: Arc::new(source.for_regions()),
252            }),
253            None => input_plan.clone(),
254        };
255        let merge_scan_plan = MergeScanExec::new(
256            session_state,
257            table_name,
258            regions,
259            region_plan,
260            schema,
261            self.region_query_handler.clone(),
262            query_ctx,
263            session.config().target_partitions(),
264            merge_scan.remote_dyn_filter_producer_id(),
265            self.enable_per_region_metrics,
266        )?
267        .with_raw_series_disjoint(series_disjoint)?;
268        let merge_scan_plan = Arc::new(merge_scan_plan) as Arc<dyn ExecutionPlan>;
269        match label_set_source {
270            Some(source) => source.merged_by_label_set(merge_scan_plan).map(Some),
271            None => Ok(Some(merge_scan_plan)),
272        }
273    }
274}
275
276impl DistExtensionPlanner {
277    /// Extract fully resolved table name from logical plan
278    fn extract_full_table_name(plan: &LogicalPlan) -> Result<Option<TableName>> {
279        let mut extractor = TableScanExtractor::default();
280        let _ = plan.visit(&mut extractor)?;
281        Ok(extractor.table_name)
282    }
283
284    /// Selects the regions of the ordinary distributed plan.
285    async fn get_regions(
286        &self,
287        table_name: &TableName,
288        logical_plan: &LogicalPlan,
289    ) -> Result<(Vec<RegionId>, bool)> {
290        let mut extractor = TableScanExtractor::default();
291        let _ = logical_plan.visit(&mut extractor)?;
292        // Resolving by name again could bind an authorized scan to a replacement table.
293        let captured_table = extractor.captured_table;
294        let table = match &captured_table {
295            Some(table) => table.clone(),
296            None => self
297                .catalog_manager
298                .table(
299                    &table_name.catalog_name,
300                    &table_name.schema_name,
301                    &table_name.table_name,
302                    None,
303                )
304                .await
305                .context(CatalogSnafu)?
306                .with_context(|| TableNotFoundSnafu {
307                    table: table_name.to_string(),
308                })?,
309        };
310
311        let table_info = table.table_info();
312        let (physical_table_id, physical_table_route) = self
313            .partition_rule_manager
314            .find_physical_table_route_with_id(table_info.table_id())
315            .await
316            .context(PartitionRuleManagerSnafu)?;
317        let all_regions = physical_table_route
318            .region_routes
319            .iter()
320            .map(|r| RegionId::new(table_info.table_id(), r.region.id.region_number()))
321            .collect::<Vec<_>>();
322        let logical_partition_columns = partition_column_types(&table_info);
323        let partition_columns = logical_partition_columns
324            .iter()
325            .map(|(name, _)| name.clone())
326            .collect::<Vec<_>>();
327        debug!(
328            "DistExtensionPlanner: loaded table partition metadata, table: {}, table_id: {}, partition_key_indices: {:?}, partition_columns: {:?}, all_regions: {:?}",
329            table_name,
330            table_info.table_id(),
331            table_info.meta.partition_key_indices,
332            partition_columns,
333            all_regions,
334        );
335        let partitioned_by_table_id = physical_table_id != table_info.table_id()
336            && table_info.meta.engine == METRIC_ENGINE_NAME
337            && table.partition_rules().is_some_and(|rules| {
338                rules
339                    .extra_phy_cols_not_in_logical_table
340                    .iter()
341                    .any(|name| name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME)
342            });
343        let regions = 'pruning: {
344            let partition_expressions = if partition_columns.is_empty() {
345                Vec::new()
346            } else {
347                PredicateExtractor::extract_partition_expressions(logical_plan, &partition_columns)
348                    .unwrap_or_else(|err| {
349                        debug!(
350                            "Failed to extract partition predicates for table {table_name}: {err}"
351                        );
352                        Vec::new()
353                    })
354            };
355
356            if partition_expressions.is_empty()
357                && (!partitioned_by_table_id || all_regions.len() == 1)
358            {
359                break 'pruning all_regions;
360            }
361            let partitions = match create_partitions_from_region_routes(
362                table_info.table_id(),
363                &physical_table_route.region_routes,
364            ) {
365                Ok(partitions) => partitions,
366                Err(err) => {
367                    debug!("Failed to load partitions for table {table_name}: {err}");
368                    break 'pruning all_regions;
369                }
370            };
371
372            let (mut regions, partitions) = if partitioned_by_table_id {
373                let Some(candidates) =
374                    simplify_metric_partitions(table_info.table_id(), partitions)
375                else {
376                    debug!("Could not simplify partition rules for table {table_name}");
377                    break 'pruning all_regions;
378                };
379                candidates
380            } else {
381                (Vec::new(), partitions)
382            };
383
384            // Repartition publishes new bounds before staging regions serve them. If any route is
385            // staging, skip hash inference for the whole table. This checks only the planning-time
386            // layout: MergeScanExec sends the selected IDs without a partition version.
387            let scan_equalities = if partition_expressions.is_empty()
388                || physical_table_route
389                    .region_routes
390                    .iter()
391                    .any(|route| route.is_leader_staging())
392            {
393                Vec::new()
394            } else {
395                PredicateExtractor::extract_scan_equalities(logical_plan, &partition_columns)
396            };
397
398            // Rules that simplify to true impose no constraints on the SQL predicates.
399            // Send only the residual rules to the constraint pruner.
400            if !partitions.is_empty()
401                && !partition_expressions.is_empty()
402                && let Some(column_types) = self
403                    .partition_column_types_for_pruning(
404                        table_name,
405                        table_info.as_ref(),
406                        physical_table_id,
407                        partition_expressions.iter().chain(&scan_equalities),
408                    )
409                    .await
410            {
411                match ConstraintPruner::prune_regions_with_scan_equalities(
412                    &partition_expressions,
413                    &partitions,
414                    column_types,
415                    &scan_equalities,
416                ) {
417                    Ok(pruned) => regions.extend(pruned),
418                    Err(err) => {
419                        debug!("Failed to prune partitions for table {table_name}: {err}");
420                        regions.extend(partitions.iter().map(|partition| partition.id));
421                    }
422                }
423            } else {
424                regions.extend(partitions.iter().map(|partition| partition.id));
425            }
426
427            debug!(
428                "Region pruning for table {table_name}: {} -> {} regions",
429                all_regions.len(),
430                regions.len()
431            );
432            regions
433        };
434
435        // A selected region is trivially disjoint. For several regions the proof must
436        // use the captured scan and the physical route's table metadata, not a logical
437        // metric table's possibly incomplete partition columns.
438        let series_disjoint = if regions.len() <= 1 {
439            true
440        } else if captured_table.is_none() {
441            false
442        } else {
443            let physical_info = if physical_table_id == table_info.table_id() {
444                Some(table_info.clone())
445            } else {
446                self.catalog_manager
447                    .table_info_by_id(physical_table_id)
448                    .await
449                    .ok()
450                    .flatten()
451            };
452            physical_info.is_some_and(|info| {
453                physical_regions_disjoint(&info, &physical_table_route.region_routes, &regions)
454            })
455        };
456        Ok((regions, series_disjoint))
457    }
458
459    /// Resolves the partition-column types that are safe to use for region pruning.
460    ///
461    /// A logical metric table may not contain every physical partition column, either for backward
462    /// compatibility or because its physical table was repartitioned after the logical table was
463    /// created. Predicate extraction must remain bounded by the logical schema, while pruning
464    /// needs the physical datatypes to evaluate route expressions. Any lookup failure or
465    /// logical/physical datatype mismatch returns `None`, preserving the current candidate regions.
466    async fn partition_column_types_for_pruning<'a>(
467        &self,
468        table_name: &TableName,
469        logical_table_info: &TableInfo,
470        physical_table_id: u32,
471        partition_expressions: impl Iterator<Item = &'a PartitionExpr>,
472    ) -> Option<HashMap<String, ConcreteDataType>> {
473        let physical_partition_columns = if physical_table_id == logical_table_info.table_id() {
474            partition_column_types(logical_table_info)
475        } else {
476            match self
477                .catalog_manager
478                .table_info_by_id(physical_table_id)
479                .await
480            {
481                Ok(Some(physical_table_info)) => {
482                    partition_column_types(physical_table_info.as_ref())
483                }
484                Ok(None) => {
485                    debug!(
486                        "DistExtensionPlanner: physical table info not found for table {} (id: {})",
487                        table_name, physical_table_id
488                    );
489                    return None;
490                }
491                Err(err) => {
492                    debug!(
493                        "DistExtensionPlanner: failed to load physical table info for table {} (id: {}): {}",
494                        table_name, physical_table_id, err
495                    );
496                    return None;
497                }
498            }
499        };
500        let physical_column_types = physical_partition_columns
501            .into_iter()
502            .collect::<HashMap<_, _>>();
503        let logical_column_types = partition_column_types(logical_table_info)
504            .into_iter()
505            .collect::<HashMap<_, _>>();
506        let mut predicate_column_names = std::collections::HashSet::new();
507        for expression in partition_expressions {
508            expression.collect_column_names(&mut predicate_column_names);
509        }
510        if predicate_column_names
511            .iter()
512            .any(|name| logical_column_types.get(name) != physical_column_types.get(name))
513        {
514            debug!(
515                "DistExtensionPlanner: logical and physical partition metadata mismatch for table {} (physical id: {})",
516                table_name, physical_table_id
517            );
518            return None;
519        }
520
521        Some(physical_column_types)
522    }
523
524    /// Input logical plan is analyzed. Thus only call logical optimizer to optimize it.
525    fn optimize_input_logical_plan(
526        &self,
527        session: &dyn Session,
528        plan: &LogicalPlan,
529    ) -> Result<LogicalPlan> {
530        expr_depth::validate_plan(plan)?;
531        let session_state = session
532            .as_any()
533            .downcast_ref::<SessionState>()
534            .ok_or_else(|| {
535                DataFusionError::Internal(
536                    "MergeScan requires a SessionState for logical optimization".to_string(),
537                )
538            })?;
539
540        session_state
541            .optimizer()
542            .optimize(plan.clone(), session_state, |_, _| {})
543    }
544}
545
546enum SimplifiedPartitionExpr {
547    Constant(bool),
548    Residual(PartitionExpr),
549}
550
551/// Returns unconditional regions and regions with residual partition rules.
552/// Incomplete or inconsistent routing rules leave the original route in use.
553fn simplify_metric_partitions(
554    table_id: TableId,
555    partitions: Vec<PartitionInfo>,
556) -> Option<(Vec<RegionId>, Vec<PartitionInfo>)> {
557    let table_id = Value::UInt32(table_id);
558    let hash = IcebergHash::evaluate_value(&table_id).ok()?;
559    let mut unconditional = Vec::new();
560    let mut residual = Vec::new();
561    for PartitionInfo { id, partition_expr } in partitions {
562        match simplify_metric_partition_expr(partition_expr?, &table_id, &hash)? {
563            SimplifiedPartitionExpr::Constant(false) => {}
564            SimplifiedPartitionExpr::Constant(true) => unconditional.push(id),
565            SimplifiedPartitionExpr::Residual(expr) => residual.push(PartitionInfo {
566                id,
567                partition_expr: Some(expr),
568            }),
569        }
570    }
571    // A complete set of physical rules covers every logical table ID.
572    if unconditional.is_empty() && residual.is_empty() {
573        return None;
574    }
575    Some((unconditional, residual))
576}
577
578fn simplify_metric_partition_expr(
579    expr: PartitionExpr,
580    table_id: &Value,
581    hash: &Value,
582) -> Option<SimplifiedPartitionExpr> {
583    use SimplifiedPartitionExpr::{Constant, Residual};
584
585    // Route deserialization canonicalizes comparisons to dimension op literal.
586    match (expr.op, *expr.lhs, *expr.rhs) {
587        (op @ (RestrictedOp::And | RestrictedOp::Or), Operand::Expr(lhs), Operand::Expr(rhs)) => {
588            let lhs = simplify_metric_partition_expr(lhs, table_id, hash)?;
589            let rhs = simplify_metric_partition_expr(rhs, table_id, hash)?;
590            let absorbing = op == RestrictedOp::Or;
591            match (lhs, rhs) {
592                (Constant(lhs), Constant(rhs)) => {
593                    Some(Constant(if absorbing { lhs || rhs } else { lhs && rhs }))
594                }
595                (Constant(value), residual) | (residual, Constant(value)) => {
596                    Some(if value == absorbing {
597                        Constant(value)
598                    } else {
599                        residual
600                    })
601                }
602                (Residual(lhs), Residual(rhs)) => Some(Residual(PartitionExpr {
603                    lhs: Box::new(Operand::Expr(lhs)),
604                    op,
605                    rhs: Box::new(Operand::Expr(rhs)),
606                })),
607            }
608        }
609        (RestrictedOp::And | RestrictedOp::Or, _, _) => None,
610        (op, dimension @ (Operand::Column(_) | Operand::IcebergHash(_)), Operand::Value(bound)) => {
611            let known = match &dimension {
612                Operand::Column(name) if name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME => table_id,
613                Operand::IcebergHash(function)
614                    if function.column() == DATA_SCHEMA_TABLE_ID_COLUMN_NAME =>
615                {
616                    hash
617                }
618                _ => return Some(Residual(PartitionExpr::new(dimension, op, bound.into()))),
619            };
620
621            // DDL types the bound to the dimension. Partition routing orders NULL
622            // before non-NULL values. A mismatched bound cannot safely be folded.
623            if !matches!(bound, Value::Null) && known.data_type() != bound.data_type() {
624                return None;
625            }
626            let matches = partition_comparison_matches(&op, known.cmp(&bound))?;
627            Some(Constant(matches))
628        }
629        _ => None,
630    }
631}
632
633/// Prove that every physical routing column belongs to the complete raw primary key.
634/// Unknown indices, missing route expressions, or route columns not represented in physical
635/// partition metadata cannot establish disjointness. Reserved-looking names have no special status.
636fn physical_regions_disjoint(
637    table_info: &TableInfo,
638    routes: &[common_meta::rpc::router::RegionRoute],
639    regions: &[RegionId],
640) -> bool {
641    let columns = table_info.meta.schema.column_schemas();
642    let partition_keys = &table_info.meta.partition_key_indices;
643    // Routing by any nonempty subset of the complete key keeps equal complete keys together.
644    // The reverse inclusion is not required: (host, rack) partitioned by host is disjoint.
645    if partition_keys.is_empty()
646        || table_info.meta.primary_key_indices.is_empty()
647        || partition_keys.iter().any(|index| {
648            columns.get(*index).is_none_or(|column| {
649                column.is_time_index() || !table_info.meta.primary_key_indices.contains(index)
650            })
651        })
652        || table_info
653            .meta
654            .primary_key_indices
655            .iter()
656            .any(|index| columns.get(*index).is_none())
657    {
658        return false;
659    }
660    let partition_names = partition_keys
661        .iter()
662        .map(|index| columns[*index].name.as_str())
663        .collect::<std::collections::HashSet<_>>();
664    for region in regions {
665        let mut matching = routes
666            .iter()
667            .filter(|route| route.region.id.region_number() == region.region_number());
668        let Some(route) = matching.next() else {
669            return false;
670        };
671        if matching.next().is_some() {
672            return false;
673        }
674        let Ok(Some(expression)) = PartitionExpr::from_json_str(&route.region.partition_expr())
675        else {
676            return false;
677        };
678        let mut names = std::collections::HashSet::new();
679        expression.collect_column_names(&mut names);
680        if names.is_empty()
681            || names
682                .iter()
683                .any(|name| !partition_names.contains(name.as_str()))
684        {
685            return false;
686        }
687    }
688    true
689}
690
691fn partition_column_types(table_info: &TableInfo) -> Vec<(String, ConcreteDataType)> {
692    table_info
693        .meta
694        .partition_columns()
695        .map(|column| (column.name.clone(), column.data_type.clone()))
696        .collect()
697}
698
699/// Extract the scan name and captured table identity from a logical plan.
700#[derive(Default)]
701struct TableScanExtractor {
702    pub table_name: Option<TableName>,
703    captured_table: Option<TableRef>,
704}
705
706impl TreeNodeVisitor<'_> for TableScanExtractor {
707    type Node = LogicalPlan;
708
709    fn f_down(&mut self, node: &Self::Node) -> Result<TreeNodeRecursion> {
710        match node {
711            LogicalPlan::TableScan(scan) => {
712                if let Some(source) = scan.source.downcast_ref::<DefaultTableSource>()
713                    && let Some(provider) = source
714                        .table_provider
715                        .downcast_ref::<DfTableProviderAdapter>()
716                {
717                    if provider.table().table_type() == TableType::Base {
718                        self.captured_table = Some(provider.table());
719                        let info = provider.table().table_info();
720                        self.table_name = Some(TableName::new(
721                            info.catalog_name.clone(),
722                            info.schema_name.clone(),
723                            info.name.clone(),
724                        ));
725                    }
726                    return Ok(TreeNodeRecursion::Stop);
727                }
728                match &scan.table_name {
729                    TableReference::Full {
730                        catalog,
731                        schema,
732                        table,
733                    } => {
734                        self.table_name = Some(TableName::new(
735                            catalog.to_string(),
736                            schema.to_string(),
737                            table.to_string(),
738                        ));
739                        Ok(TreeNodeRecursion::Stop)
740                    }
741                    // TODO(ruihang): Maybe the following two cases should not be valid
742                    TableReference::Partial { schema, table } => {
743                        self.table_name = Some(TableName::new(
744                            DEFAULT_CATALOG_NAME.to_string(),
745                            schema.to_string(),
746                            table.to_string(),
747                        ));
748                        Ok(TreeNodeRecursion::Stop)
749                    }
750                    TableReference::Bare { table } => {
751                        self.table_name = Some(TableName::new(
752                            DEFAULT_CATALOG_NAME.to_string(),
753                            DEFAULT_SCHEMA_NAME.to_string(),
754                            table.to_string(),
755                        ));
756                        Ok(TreeNodeRecursion::Stop)
757                    }
758                }
759            }
760            _ => Ok(TreeNodeRecursion::Continue),
761        }
762    }
763}
764
765#[cfg(test)]
766mod tests {
767    use std::collections::HashMap;
768    use std::sync::Arc;
769
770    use api::v1::region::{RemoteDynFilterUnregister, RemoteDynFilterUpdate};
771    use async_trait::async_trait;
772    use catalog::memory::MemoryCatalogManager;
773    use catalog::{CatalogManagerRef, RegisterTableRequest};
774    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
775    use common_meta::cache::new_table_route_cache;
776    use common_meta::key::TableMetadataManager;
777    use common_meta::key::table_route::TableRouteValue;
778    use common_meta::kv_backend::memory::MemoryKvBackend;
779    use common_meta::rpc::router::{Region, RegionRoute};
780    use common_query::request::QueryRequest;
781    use common_recordbatch::SendableRecordBatchStream;
782    use datafusion::datasource::DefaultTableSource;
783    use datafusion_expr::{LogicalPlan, LogicalPlanBuilder, col as df_col, lit};
784    use datatypes::prelude::ConcreteDataType;
785    use datatypes::schema::{ColumnSchema, Schema};
786    use datatypes::value::Value;
787    use moka::future::CacheBuilder;
788    use partition::cache::new_partition_info_cache;
789    use partition::expr::{Operand, PartitionExpr, RestrictedOp, col as partition_col};
790    use partition::function::IcebergHash;
791    use partition::manager::PartitionRuleManager;
792    use session::ReadPreference;
793    use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME;
794    use store_api::storage::RegionId;
795    use table::dist_table::DistTable;
796    use table::metadata::{TableInfo, TableInfoBuilder, TableMeta, TableType};
797    use table::table::PartitionRules;
798    use table::table::adapter::DfTableProviderAdapter;
799    use table::table_name::TableName;
800    use table::test_util::EmptyTable;
801
802    use super::{DistExtensionPlanner, physical_regions_disjoint};
803    use crate::region_query::{RegionQueryHandler, RegionQueryTarget};
804
805    const LOGICAL_TABLE_ID: u32 = 1024;
806    const PHYSICAL_TABLE_ID: u32 = 2048;
807
808    struct UnusedRegionQueryHandler;
809
810    #[async_trait]
811    impl RegionQueryHandler for UnusedRegionQueryHandler {
812        async fn select_target(
813            &self,
814            _read_preference: ReadPreference,
815            _region_id: RegionId,
816        ) -> crate::error::Result<RegionQueryTarget> {
817            unreachable!("get_regions does not select region query targets")
818        }
819
820        async fn do_get(
821            &self,
822            _target: &RegionQueryTarget,
823            _request: QueryRequest,
824        ) -> crate::error::Result<SendableRecordBatchStream> {
825            unreachable!("get_regions does not query regions")
826        }
827
828        async fn handle_remote_dyn_filter_update(
829            &self,
830            _target: &RegionQueryTarget,
831            _query_id: String,
832            _update: RemoteDynFilterUpdate,
833        ) -> crate::error::Result<()> {
834            unreachable!("get_regions does not update dynamic filters")
835        }
836
837        async fn handle_remote_dyn_filter_unregister(
838            &self,
839            _target: &RegionQueryTarget,
840            _query_id: String,
841            _unregister: RemoteDynFilterUnregister,
842        ) -> crate::error::Result<()> {
843            unreachable!("get_regions does not unregister dynamic filters")
844        }
845    }
846
847    fn table_info(
848        table_id: u32,
849        name: &str,
850        columns: &[&str],
851        partition_keys: Vec<usize>,
852    ) -> TableInfo {
853        let schema = Arc::new(Schema::new(
854            columns
855                .iter()
856                .map(|name| {
857                    if *name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME {
858                        ColumnSchema::new(*name, ConcreteDataType::uint32_datatype(), false)
859                    } else {
860                        ColumnSchema::new(*name, ConcreteDataType::string_datatype(), true)
861                    }
862                })
863                .collect(),
864        ));
865        let meta = TableMeta {
866            schema,
867            primary_key_indices: vec![],
868            value_indices: vec![],
869            engine: "metric".to_string(),
870            next_column_id: columns.len() as u32,
871            options: Default::default(),
872            created_on: Default::default(),
873            updated_on: Default::default(),
874            partition_key_indices: partition_keys,
875            column_ids: (0..columns.len() as u32).collect(),
876        };
877        TableInfoBuilder::default()
878            .table_id(table_id)
879            .table_version(0)
880            .name(name.to_string())
881            .catalog_name(DEFAULT_CATALOG_NAME.to_string())
882            .schema_name(DEFAULT_SCHEMA_NAME.to_string())
883            .desc(None)
884            .table_type(TableType::Base)
885            .meta(meta)
886            .build()
887            .unwrap()
888    }
889
890    fn region_route(region_number: u32, expression: Option<PartitionExpr>) -> RegionRoute {
891        RegionRoute {
892            region: Region {
893                id: RegionId::new(PHYSICAL_TABLE_ID, region_number),
894                partition_expr: expression
895                    .map(|expression| expression.as_json_str().unwrap())
896                    .unwrap_or_default(),
897                ..Default::default()
898            },
899            ..Default::default()
900        }
901    }
902
903    async fn planner_and_plan(
904        physical_partition_keys: Vec<usize>,
905        expressions: Vec<Option<PartitionExpr>>,
906    ) -> (DistExtensionPlanner, LogicalPlan, TableName) {
907        let routes = expressions
908            .into_iter()
909            .enumerate()
910            .map(|(index, expression)| region_route(index as u32 + 1, expression))
911            .collect();
912        planner_and_plan_for_routes(physical_partition_keys, routes).await
913    }
914
915    async fn planner_and_plan_for_routes(
916        physical_partition_keys: Vec<usize>,
917        routes: Vec<RegionRoute>,
918    ) -> (DistExtensionPlanner, LogicalPlan, TableName) {
919        let logical_info = table_info(LOGICAL_TABLE_ID, "logical", &["host"], vec![0]);
920        let physical_info = table_info(
921            PHYSICAL_TABLE_ID,
922            "physical",
923            &["host", "rack", DATA_SCHEMA_TABLE_ID_COLUMN_NAME],
924            physical_partition_keys,
925        );
926        let hidden_columns: Vec<_> = physical_info
927            .meta
928            .partition_column_names()
929            .filter(|name| {
930                logical_info
931                    .meta
932                    .schema
933                    .column_index_by_name(name)
934                    .is_none()
935            })
936            .cloned()
937            .collect();
938        let partition_rules = (!hidden_columns.is_empty()).then_some(PartitionRules {
939            extra_phy_cols_not_in_logical_table: hidden_columns,
940        });
941        let logical_table =
942            DistTable::table_partitioned(Arc::new(logical_info.clone()), partition_rules);
943        let physical_table = EmptyTable::from_table_info(&physical_info);
944        let catalog_manager = MemoryCatalogManager::with_default_setup();
945        for table in [&logical_table, &physical_table] {
946            let info = table.table_info();
947            catalog_manager
948                .register_table_sync(RegisterTableRequest {
949                    catalog: info.catalog_name.clone(),
950                    schema: info.schema_name.clone(),
951                    table_name: info.name.clone(),
952                    table_id: info.table_id(),
953                    table: table.clone(),
954                })
955                .unwrap();
956        }
957
958        let backend = Arc::new(MemoryKvBackend::default());
959        let metadata_manager = TableMetadataManager::new(backend.clone());
960        metadata_manager
961            .create_table_metadata(
962                physical_info,
963                TableRouteValue::physical(routes),
964                HashMap::new(),
965            )
966            .await
967            .unwrap();
968        metadata_manager
969            .create_table_metadata(
970                logical_info,
971                TableRouteValue::logical(PHYSICAL_TABLE_ID),
972                HashMap::new(),
973            )
974            .await
975            .unwrap();
976
977        let table_route_cache = Arc::new(new_table_route_cache(
978            "planner-test-routes".to_string(),
979            CacheBuilder::new(16).build(),
980            backend.clone(),
981        ));
982        let partition_info_cache = Arc::new(new_partition_info_cache(
983            "planner-test-partitions".to_string(),
984            CacheBuilder::new(16).build(),
985            table_route_cache.clone(),
986        ));
987        let partition_rule_manager = Arc::new(PartitionRuleManager::new(
988            backend,
989            table_route_cache,
990            partition_info_cache,
991        ));
992        let (resolved_physical_id, physical_route) = partition_rule_manager
993            .find_physical_table_route_with_id(PHYSICAL_TABLE_ID)
994            .await
995            .unwrap();
996        assert_eq!(PHYSICAL_TABLE_ID, resolved_physical_id);
997        let (resolved_logical_id, logical_route) = partition_rule_manager
998            .find_physical_table_route_with_id(LOGICAL_TABLE_ID)
999            .await
1000            .unwrap();
1001        assert_eq!(PHYSICAL_TABLE_ID, resolved_logical_id);
1002        assert_eq!(physical_route.region_routes, logical_route.region_routes);
1003        let catalog_manager: CatalogManagerRef = catalog_manager;
1004        let planner = DistExtensionPlanner::new(
1005            catalog_manager,
1006            partition_rule_manager,
1007            Arc::new(UnusedRegionQueryHandler),
1008            false,
1009        );
1010        let table_source = Arc::new(DefaultTableSource::new(Arc::new(
1011            DfTableProviderAdapter::new(logical_table),
1012        )));
1013        let plan = LogicalPlanBuilder::scan_with_filters("logical", table_source, None, vec![])
1014            .unwrap()
1015            .filter(df_col("host").eq(lit("a")))
1016            .unwrap()
1017            .build()
1018            .unwrap();
1019        (
1020            planner,
1021            plan,
1022            TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "logical"),
1023        )
1024    }
1025
1026    fn physical_partition_expressions() -> Vec<Option<PartitionExpr>> {
1027        vec![
1028            Some(partition_col("host").lt(Value::String("m".into()))),
1029            Some(
1030                partition_col("host")
1031                    .gt_eq(Value::String("m".into()))
1032                    .and(partition_col("rack").lt(Value::String("n".into()))),
1033            ),
1034            Some(
1035                partition_col("host")
1036                    .gt_eq(Value::String("m".into()))
1037                    .and(partition_col("rack").gt_eq(Value::String("n".into()))),
1038            ),
1039        ]
1040    }
1041
1042    #[tokio::test]
1043    async fn region_routing_uses_captured_table() {
1044        let (mut planner, plan, table_name) = planner_and_plan(vec![0], vec![None]).await;
1045        planner.catalog_manager = MemoryCatalogManager::with_default_setup();
1046        let (regions, _) = planner.get_regions(&table_name, &plan).await.unwrap();
1047        assert_eq!(vec![RegionId::new(LOGICAL_TABLE_ID, 1)], regions);
1048    }
1049
1050    #[tokio::test]
1051    async fn logical_table_pruning_uses_physical_partition_datatypes() {
1052        let (planner, plan, table_name) =
1053            planner_and_plan(vec![0, 1], physical_partition_expressions()).await;
1054
1055        let (regions, _) = planner.get_regions(&table_name, &plan).await.unwrap();
1056        assert_eq!(vec![RegionId::new(LOGICAL_TABLE_ID, 1)], regions);
1057    }
1058
1059    fn hash_partition_routes() -> Vec<RegionRoute> {
1060        let hash = Operand::IcebergHash(IcebergHash::new("host"));
1061        vec![
1062            region_route(1, Some(hash.clone().lt(Value::Int32(0)))),
1063            region_route(
1064                2,
1065                Some(
1066                    hash.clone()
1067                        .gt_eq(Value::Int32(0))
1068                        .and(hash.clone().lt(Value::Int32(1_073_741_824))),
1069                ),
1070            ),
1071            region_route(3, Some(hash.gt_eq(Value::Int32(1_073_741_824)))),
1072        ]
1073    }
1074
1075    #[tokio::test]
1076    async fn hash_pruning_requires_a_scan_local_equality() {
1077        let (planner, plan, table_name) =
1078            planner_and_plan_for_routes(vec![0], hash_partition_routes()).await;
1079        let (mut regions, _) = planner.get_regions(&table_name, &plan).await.unwrap();
1080        regions.sort();
1081        assert_eq!(
1082            regions,
1083            vec![
1084                RegionId::new(LOGICAL_TABLE_ID, 1),
1085                RegionId::new(LOGICAL_TABLE_ID, 2)
1086            ]
1087        );
1088
1089        let scan = plan.inputs()[0];
1090        let host_eq = df_col("host").eq(lit("a"));
1091        let with_or = LogicalPlanBuilder::from(scan.clone())
1092            .filter(host_eq.clone().or(df_col("host").lt(lit("z"))))
1093            .unwrap()
1094            .build()
1095            .unwrap();
1096        let after_limit = LogicalPlanBuilder::from(scan.clone())
1097            .limit(0, Some(1))
1098            .unwrap()
1099            .filter(host_eq)
1100            .unwrap()
1101            .build()
1102            .unwrap();
1103        for plan in [with_or, after_limit] {
1104            let (regions, _) = planner.get_regions(&table_name, &plan).await.unwrap();
1105            assert_all_logical_regions(regions);
1106        }
1107    }
1108
1109    #[tokio::test]
1110    async fn hash_pruning_keeps_regions_while_new_bounds_are_staging() {
1111        let mut routes = hash_partition_routes();
1112        routes[2].set_leader_staging();
1113        let (planner, plan, table_name) = planner_and_plan_for_routes(vec![0], routes).await;
1114        let (regions, _) = planner.get_regions(&table_name, &plan).await.unwrap();
1115        assert_all_logical_regions(regions);
1116    }
1117
1118    #[tokio::test]
1119    async fn missing_physical_partition_datatype_falls_back_to_all_logical_regions() {
1120        let (planner, plan, table_name) =
1121            planner_and_plan(vec![0], physical_partition_expressions()).await;
1122
1123        let (regions, _) = planner.get_regions(&table_name, &plan).await.unwrap();
1124        assert_all_logical_regions(regions);
1125    }
1126
1127    #[tokio::test]
1128    async fn missing_route_partition_expression_falls_back_to_all_logical_regions() {
1129        let mut expressions = physical_partition_expressions();
1130        expressions[1] = None;
1131        let (planner, plan, table_name) = planner_and_plan(vec![0, 1], expressions).await;
1132
1133        let (regions, _) = planner.get_regions(&table_name, &plan).await.unwrap();
1134        assert_all_logical_regions(regions);
1135    }
1136
1137    #[tokio::test]
1138    async fn unfiltered_tag_partitioned_scan_keeps_all_regions() {
1139        // The captured table still describes tag partitioning, even if a newer
1140        // route already contains rules for __table_id.
1141        let id = partition_col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
1142        let bound = Value::UInt32(LOGICAL_TABLE_ID);
1143        for tag_keys in [vec![0], vec![0, 1]] {
1144            let rules = vec![
1145                Some(id.clone().lt(bound.clone())),
1146                Some(id.clone().gt_eq(bound.clone())),
1147            ];
1148            let (planner, plan, table) = planner_and_plan(tag_keys, rules).await;
1149            let (regions, _) = planner.get_regions(&table, plan.inputs()[0]).await.unwrap();
1150            assert_eq!(
1151                regions,
1152                vec![
1153                    RegionId::new(LOGICAL_TABLE_ID, 1),
1154                    RegionId::new(LOGICAL_TABLE_ID, 2)
1155                ]
1156            );
1157        }
1158    }
1159
1160    #[tokio::test]
1161    async fn prunes_raw_and_hashed_table_id_without_sql_predicates() {
1162        let id = Value::UInt32(LOGICAL_TABLE_ID);
1163        let hash = IcebergHash::evaluate_value(&id).unwrap();
1164        for (dimension, bound) in [
1165            (partition_col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME), id),
1166            (
1167                Operand::IcebergHash(IcebergHash::new(DATA_SCHEMA_TABLE_ID_COLUMN_NAME)),
1168                hash,
1169            ),
1170        ] {
1171            let rules = vec![
1172                Some(dimension.clone().lt(bound.clone())),
1173                Some(dimension.gt_eq(bound)),
1174            ];
1175            let (planner, plan, table) = planner_and_plan(vec![2], rules).await;
1176            let (regions, _) = planner.get_regions(&table, plan.inputs()[0]).await.unwrap();
1177            assert_eq!(regions, vec![RegionId::new(LOGICAL_TABLE_ID, 2)]);
1178        }
1179    }
1180
1181    #[tokio::test]
1182    async fn prunes_mixed_table_id_and_host_rules() {
1183        let id = partition_col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
1184        let host = partition_col("host");
1185        let boundary = Value::UInt32(LOGICAL_TABLE_ID);
1186        let rules = vec![
1187            Some(id.clone().lt(boundary.clone())),
1188            Some(
1189                id.clone()
1190                    .gt_eq(boundary.clone())
1191                    .and(host.clone().lt(Value::String("m".into()))),
1192            ),
1193            Some(
1194                id.gt_eq(boundary)
1195                    .and(host.gt_eq(Value::String("m".into()))),
1196            ),
1197        ];
1198        let (mut planner, plan, table) = planner_and_plan(vec![0, 2], rules).await;
1199        let candidates = vec![
1200            RegionId::new(LOGICAL_TABLE_ID, 2),
1201            RegionId::new(LOGICAL_TABLE_ID, 3),
1202        ];
1203        let (regions, _) = planner.get_regions(&table, plan.inputs()[0]).await.unwrap();
1204        assert_eq!(regions, candidates);
1205        let (regions, _) = planner.get_regions(&table, &plan).await.unwrap();
1206        assert_eq!(regions, vec![RegionId::new(LOGICAL_TABLE_ID, 2)]);
1207
1208        planner.catalog_manager = MemoryCatalogManager::with_default_setup();
1209        let (regions, _) = planner.get_regions(&table, &plan).await.unwrap();
1210        assert_eq!(regions, candidates);
1211    }
1212
1213    #[tokio::test]
1214    async fn folds_or_in_table_id_partition_rule() {
1215        let id = partition_col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
1216        let host = partition_col("host");
1217        for (boundary, expected) in [(LOGICAL_TABLE_ID, 2), (LOGICAL_TABLE_ID + 1, 1)] {
1218            let boundary = Value::UInt32(boundary);
1219            let rules = vec![
1220                Some(PartitionExpr::new(
1221                    Operand::Expr(id.clone().lt(boundary.clone())),
1222                    RestrictedOp::Or,
1223                    Operand::Expr(host.clone().gt_eq(Value::String("m".into()))),
1224                )),
1225                Some(
1226                    id.clone()
1227                        .gt_eq(boundary)
1228                        .and(host.clone().lt(Value::String("m".into()))),
1229                ),
1230            ];
1231            let (planner, plan, table) = planner_and_plan(vec![0, 2], rules).await;
1232            let (regions, _) = planner.get_regions(&table, &plan).await.unwrap();
1233            assert_eq!(regions, vec![RegionId::new(LOGICAL_TABLE_ID, expected)]);
1234        }
1235    }
1236
1237    #[tokio::test]
1238    async fn incomplete_table_id_rules_keep_the_full_route() {
1239        let id = partition_col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
1240        for rule in [
1241            None,
1242            Some(id.clone().lt(Value::UInt32(0))),
1243            Some(id.clone().gt_eq(Value::Int64(0))),
1244        ] {
1245            let rules = vec![Some(id.clone().lt(Value::UInt32(LOGICAL_TABLE_ID))), rule];
1246            let (planner, plan, table) = planner_and_plan(vec![2], rules).await;
1247            let (regions, _) = planner.get_regions(&table, plan.inputs()[0]).await.unwrap();
1248            assert_eq!(
1249                regions,
1250                vec![
1251                    RegionId::new(LOGICAL_TABLE_ID, 1),
1252                    RegionId::new(LOGICAL_TABLE_ID, 2)
1253                ]
1254            );
1255        }
1256    }
1257
1258    #[test]
1259    fn disjoint_requires_raw_key_routing_and_valid_unique_routes() {
1260        let regions = vec![
1261            RegionId::new(LOGICAL_TABLE_ID, 1),
1262            RegionId::new(LOGICAL_TABLE_ID, 2),
1263        ];
1264        let routes = vec![
1265            region_route(1, Some(partition_col("host").lt(Value::String("m".into())))),
1266            region_route(
1267                2,
1268                Some(partition_col("host").gt_eq(Value::String("m".into()))),
1269            ),
1270        ];
1271        let mut info = table_info(PHYSICAL_TABLE_ID, "physical", &["host", "rack"], vec![0]);
1272        info.meta.primary_key_indices = vec![0];
1273        assert!(physical_regions_disjoint(&info, &routes, &regions));
1274        info.meta.primary_key_indices = vec![0, 1];
1275        assert!(physical_regions_disjoint(&info, &routes, &regions));
1276        info.meta.partition_key_indices = vec![0, 1];
1277        assert!(physical_regions_disjoint(&info, &routes, &regions));
1278        info.meta.partition_key_indices = vec![0, 2];
1279        assert!(!physical_regions_disjoint(&info, &routes, &regions));
1280        info.meta.partition_key_indices = vec![0];
1281        info.meta.primary_key_indices = vec![0];
1282        let mut duplicate = routes.clone();
1283        duplicate.push(routes[0].clone());
1284        assert!(!physical_regions_disjoint(&info, &duplicate, &regions));
1285        let mut missing = routes.clone();
1286        missing[1] = region_route(2, None);
1287        assert!(!physical_regions_disjoint(&info, &missing, &regions));
1288        let mut unknown = routes.clone();
1289        unknown[1] = region_route(2, Some(partition_col("rack").lt(Value::String("m".into()))));
1290        assert!(!physical_regions_disjoint(&info, &unknown, &regions));
1291        let mut malformed = routes.clone();
1292        malformed[1].region.partition_expr = "{invalid".into();
1293        assert!(!physical_regions_disjoint(&info, &malformed, &regions));
1294        assert!(!physical_regions_disjoint(&info, &routes[..1], &regions));
1295
1296        info.meta.schema = Arc::new(Schema::new(vec![
1297            ColumnSchema::new("host", ConcreteDataType::string_datatype(), false),
1298            ColumnSchema::new(
1299                "timestamp",
1300                ConcreteDataType::timestamp_millisecond_datatype(),
1301                false,
1302            )
1303            .with_time_index(true),
1304        ]));
1305        info.meta.partition_key_indices = vec![0, 1];
1306        info.meta.primary_key_indices = vec![0, 1];
1307        assert!(!physical_regions_disjoint(&info, &routes, &regions));
1308    }
1309
1310    #[tokio::test]
1311    async fn disjoint_proof_uses_physical_not_logical_metadata() {
1312        let (planner, plan, table_name) =
1313            planner_and_plan(vec![0, 1], physical_partition_expressions()).await;
1314        // The host predicate is selective; one selected region is always disjoint.
1315        let (regions, disjoint) = planner.get_regions(&table_name, &plan).await.unwrap();
1316        assert_eq!(regions.len(), 1);
1317        assert!(disjoint);
1318        // With no pruning the fixture's physical metadata has no PK, so it cannot prove
1319        // disjointness even though the logical partition keys name host.
1320        let LogicalPlan::Filter(filter) = plan else {
1321            panic!("expected filter")
1322        };
1323        let (regions, disjoint) = planner
1324            .get_regions(&table_name, &filter.input)
1325            .await
1326            .unwrap();
1327        assert_eq!(regions.len(), 3);
1328        assert!(!disjoint);
1329    }
1330
1331    fn assert_all_logical_regions(mut regions: Vec<RegionId>) {
1332        regions.sort_unstable();
1333        assert_eq!(
1334            vec![
1335                RegionId::new(LOGICAL_TABLE_ID, 1),
1336                RegionId::new(LOGICAL_TABLE_ID, 2),
1337                RegionId::new(LOGICAL_TABLE_ID, 3),
1338            ],
1339            regions
1340        );
1341    }
1342}