diff --git a/src/query/src/dist_plan/planner.rs b/src/query/src/dist_plan/planner.rs index 25ea976094e..8a73a2aec02 100644 --- a/src/query/src/dist_plan/planner.rs +++ b/src/query/src/dist_plan/planner.rs @@ -360,6 +360,20 @@ impl DistExtensionPlanner { (Vec::new(), partitions) }; + // Repartition publishes new bounds before staging regions serve them. If any route is + // staging, skip hash inference for the whole table. This checks only the planning-time + // layout: MergeScanExec sends the selected IDs without a partition version. + let scan_equalities = if partition_expressions.is_empty() + || physical_table_route + .region_routes + .iter() + .any(|route| route.is_leader_staging()) + { + Vec::new() + } else { + PredicateExtractor::extract_scan_equalities(logical_plan, &partition_columns) + }; + // Rules that simplify to true impose no constraints on the SQL predicates. // Send only the residual rules to the constraint pruner. if !partitions.is_empty() @@ -369,14 +383,15 @@ impl DistExtensionPlanner { table_name, table_info.as_ref(), physical_table_id, - &partition_expressions, + partition_expressions.iter().chain(&scan_equalities), ) .await { - match ConstraintPruner::prune_regions( + match ConstraintPruner::prune_regions_with_scan_equalities( &partition_expressions, &partitions, column_types, + &scan_equalities, ) { Ok(pruned) => regions.extend(pruned), Err(err) => { @@ -427,12 +442,12 @@ impl DistExtensionPlanner { /// created. Predicate extraction must remain bounded by the logical schema, while pruning /// needs the physical datatypes to evaluate route expressions. Any lookup failure or /// logical/physical datatype mismatch returns `None`, preserving the current candidate regions. - async fn partition_column_types_for_pruning( + async fn partition_column_types_for_pruning<'a>( &self, table_name: &TableName, logical_table_info: &TableInfo, physical_table_id: u32, - partition_expressions: &[PartitionExpr], + partition_expressions: impl Iterator, ) -> Option> { let physical_partition_columns = if physical_table_id == logical_table_info.table_id() { partition_column_types(logical_table_info) @@ -876,6 +891,18 @@ mod tests { async fn planner_and_plan( physical_partition_keys: Vec, expressions: Vec>, + ) -> (DistExtensionPlanner, LogicalPlan, TableName) { + let routes = expressions + .into_iter() + .enumerate() + .map(|(index, expression)| region_route(index as u32 + 1, expression)) + .collect(); + planner_and_plan_for_routes(physical_partition_keys, routes).await + } + + async fn planner_and_plan_for_routes( + physical_partition_keys: Vec, + routes: Vec, ) -> (DistExtensionPlanner, LogicalPlan, TableName) { let logical_info = table_info(LOGICAL_TABLE_ID, "logical", &["host"], vec![0]); let physical_info = table_info( @@ -918,11 +945,6 @@ mod tests { let backend = Arc::new(MemoryKvBackend::default()); let metadata_manager = TableMetadataManager::new(backend.clone()); - let routes = expressions - .into_iter() - .enumerate() - .map(|(index, expression)| region_route(index as u32 + 1, expression)) - .collect(); metadata_manager .create_table_metadata( physical_info, @@ -1022,6 +1044,65 @@ mod tests { assert_eq!(vec![RegionId::new(LOGICAL_TABLE_ID, 1)], regions); } + fn hash_partition_routes() -> Vec { + let hash = Operand::IcebergHash(IcebergHash::new("host")); + vec![ + region_route(1, Some(hash.clone().lt(Value::Int32(0)))), + region_route( + 2, + Some( + hash.clone() + .gt_eq(Value::Int32(0)) + .and(hash.clone().lt(Value::Int32(1_073_741_824))), + ), + ), + region_route(3, Some(hash.gt_eq(Value::Int32(1_073_741_824)))), + ] + } + + #[tokio::test] + async fn hash_pruning_requires_a_scan_local_equality() { + let (planner, plan, table_name) = + planner_and_plan_for_routes(vec![0], hash_partition_routes()).await; + let (mut regions, _) = planner.get_regions(&table_name, &plan).await.unwrap(); + regions.sort(); + assert_eq!( + regions, + vec![ + RegionId::new(LOGICAL_TABLE_ID, 1), + RegionId::new(LOGICAL_TABLE_ID, 2) + ] + ); + + let scan = plan.inputs()[0]; + let host_eq = df_col("host").eq(lit("a")); + let with_or = LogicalPlanBuilder::from(scan.clone()) + .filter(host_eq.clone().or(df_col("host").lt(lit("z")))) + .unwrap() + .build() + .unwrap(); + let after_limit = LogicalPlanBuilder::from(scan.clone()) + .limit(0, Some(1)) + .unwrap() + .filter(host_eq) + .unwrap() + .build() + .unwrap(); + for plan in [with_or, after_limit] { + let (regions, _) = planner.get_regions(&table_name, &plan).await.unwrap(); + assert_all_logical_regions(regions); + } + } + + #[tokio::test] + async fn hash_pruning_keeps_regions_while_new_bounds_are_staging() { + let mut routes = hash_partition_routes(); + routes[2].set_leader_staging(); + let (planner, plan, table_name) = planner_and_plan_for_routes(vec![0], routes).await; + let (regions, _) = planner.get_regions(&table_name, &plan).await.unwrap(); + assert_all_logical_regions(regions); + } + #[tokio::test] async fn missing_physical_partition_datatype_falls_back_to_all_logical_regions() { let (planner, plan, table_name) = diff --git a/src/query/src/dist_plan/predicate_extractor.rs b/src/query/src/dist_plan/predicate_extractor.rs index 170526d6c89..e5e37e42641 100644 --- a/src/query/src/dist_plan/predicate_extractor.rs +++ b/src/query/src/dist_plan/predicate_extractor.rs @@ -100,6 +100,58 @@ impl PredicateExtractor { Ok(partition_exprs) } + /// Extracts literal equalities that every matching row of a single scan must satisfy. + pub(crate) fn extract_scan_equalities( + plan: &LogicalPlan, + partition_columns: &[String], + ) -> Vec { + Self::scan_filters(plan) + .into_iter() + .flat_map(split_conjunction) + .filter_map(|predicate| { + let Expr::BinaryExpr(binary) = predicate else { + return None; + }; + if binary.op != Operator::Eq { + return None; + } + let expr = DataFusionExprConverter::convert(predicate).ok()?; + let (Operand::Column(column), Operand::Value(_)) = (expr.lhs(), expr.rhs()) else { + return None; + }; + partition_columns.contains(column).then_some(expr) + }) + .collect() + } + + /// Unlike [`Self::collect_filter_expressions`], this drops outer filters across projections + /// and limits: a projection can redefine a column, and a limit selects rows before the filter. + fn scan_filters(mut plan: &LogicalPlan) -> Vec<&Expr> { + let mut predicates = Vec::new(); + loop { + match plan { + LogicalPlan::TableScan(scan) => { + if scan.fetch.is_some() { + predicates.clear(); + } + predicates.extend(&scan.filters); + return predicates; + } + LogicalPlan::Filter(filter) => { + predicates.push(&filter.predicate); + plan = &filter.input; + } + _ => { + predicates.clear(); + let [input] = plan.inputs()[..] else { + return Vec::new(); + }; + plan = input; + } + } + } + } + /// Collect all filter expressions from a logical plan. /// /// Besides explicit [`LogicalPlan::Filter`] nodes, this must also collect diff --git a/src/query/src/dist_plan/region_pruner.rs b/src/query/src/dist_plan/region_pruner.rs index bab2f4896a3..fe14699b015 100644 --- a/src/query/src/dist_plan/region_pruner.rs +++ b/src/query/src/dist_plan/region_pruner.rs @@ -19,7 +19,8 @@ use common_telemetry::debug; use datatypes::prelude::ConcreteDataType; use datatypes::value::{OrderedFloat, Value}; use partition::collider::{AtomicExpr, Collider}; -use partition::expr::{Operand, PartitionExpr}; +use partition::expr::{Operand, PartitionExpr, RestrictedOp}; +use partition::function::IcebergHash; use partition::manager::PartitionInfo; use partition::overlap::atomic_exprs_overlap; use store_api::storage::RegionId; @@ -29,13 +30,29 @@ use crate::error::Result; pub struct ConstraintPruner; impl ConstraintPruner { - /// Prune regions using constraint satisfaction approach + /// Returns candidate Regions using only the supplied partition constraints. /// - /// Takes query expressions and partition info, returns matching region IDs + /// This public entry point does not require scan-local predicates. The distributed planner + /// supplies those separately when inferring constraints on hash dimensions. pub fn prune_regions( query_expressions: &[PartitionExpr], partitions: &[PartitionInfo], column_datatypes: HashMap, + ) -> Result> { + Self::prune_regions_with_scan_equalities( + query_expressions, + partitions, + column_datatypes, + &[], + ) + } + + /// Also prunes hash dimensions using equalities that apply directly to the scan. + pub(crate) fn prune_regions_with_scan_equalities( + query_expressions: &[PartitionExpr], + partitions: &[PartitionInfo], + column_datatypes: HashMap, + scan_equalities: &[PartitionExpr], ) -> Result> { let start = std::time::Instant::now(); let all_regions = partitions @@ -59,9 +76,15 @@ impl ConstraintPruner { return Ok(all_regions); }; - // Create unified collider with both query and partition expressions for consistent normalization + // Normalize the query, derived hash constraints and route bounds together. let mut all_expressions = query_expressions.to_vec(); - all_expressions.extend(all_partition_expressions.iter().cloned()); + all_expressions.extend(Self::iceberg_hash_constraints( + scan_equalities, + &all_partition_expressions, + &column_datatypes, + )); + let partition_expr_offset = all_expressions.len(); + all_expressions.extend(all_partition_expressions); if !Self::normalize_datatype(&mut all_expressions, &column_datatypes) { return Ok(all_regions); } @@ -77,41 +100,120 @@ impl ConstraintPruner { } }; - // Extract query atomic expressions (first N expressions in the collider) - let query_atomics: Vec<&AtomicExpr> = collider - .atomic_exprs - .iter() - .filter(|atomic| atomic.source_expr_index < query_expressions.len()) - .collect(); - - let mut candidate_regions = HashSet::default(); - - for region_atomics in collider - .atomic_exprs - .iter() - .filter(|atomic| atomic.source_expr_index >= query_expressions.len()) - { - if Self::atomic_sets_overlap(&query_atomics, region_atomics) { - let partition_expr_index = - region_atomics.source_expr_index - query_expressions.len(); - candidate_regions.insert(all_regions[partition_expr_index]); - } - } - + let candidate_regions = Self::matching_regions( + &collider.atomic_exprs, + &all_regions, + query_expressions.len(), + partition_expr_offset, + ); debug!( "Constraint pruning (cost {}ms): {} -> {} regions", start.elapsed().as_millis(), partitions.len(), candidate_regions.len() ); - - Ok(candidate_regions.into_iter().collect()) + Ok(candidate_regions) } - fn atomic_sets_overlap(query_atomics: &[&AtomicExpr], partition_atomic: &AtomicExpr) -> bool { - query_atomics + fn matching_regions( + atomics: &[AtomicExpr], + all_regions: &[RegionId], + query_expr_count: usize, + partition_expr_offset: usize, + ) -> Vec { + // In partition::collider, Collider::new visits sources in index order and + // Collider::collide_expr appends each source's OR branches together. Both partition_point + // and chunk_by below rely on that order. + let (filter_atomics, partition_atomics) = atomics.split_at( + atomics.partition_point(|atomic| atomic.source_expr_index < partition_expr_offset), + ); + let (query_atomics, hash_atomics) = filter_atomics.split_at( + filter_atomics.partition_point(|atomic| atomic.source_expr_index < query_expr_count), + ); + // Each scan equality must hold. Its literal and NULL routes are alternatives. + partition_atomics + .chunk_by(Self::same_source_expr) + .filter_map(|route| { + if !Self::atomic_sets_overlap(query_atomics, route) { + return None; + } + let region = all_regions[route[0].source_expr_index - partition_expr_offset]; + // Persisted rules are loaded without checking coverage. Writes in a gap go to + // region 0, so even a fully covered layout may scan one extra region here. + let hash_matches = region.region_number() == 0 + || hash_atomics + .chunk_by(Self::same_source_expr) + .all(|constraint| Self::atomic_sets_overlap(constraint, route)); + hash_matches.then_some(region) + }) + .collect::>() + .into_iter() + .collect() + } + + fn same_source_expr(lhs: &AtomicExpr, rhs: &AtomicExpr) -> bool { + lhs.source_expr_index == rhs.source_expr_index + } + + fn atomic_sets_overlap(lhs: &[AtomicExpr], rhs: &[AtomicExpr]) -> bool { + lhs.iter() + .any(|left| rhs.iter().any(|right| atomic_exprs_overlap(left, right))) + } + + fn iceberg_hash_constraints( + scan_equalities: &[PartitionExpr], + partition_expressions: &[PartitionExpr], + column_datatypes: &HashMap, + ) -> Vec { + if scan_equalities.is_empty() { + return Vec::new(); + } + let mut hash_columns = HashSet::default(); + for expr in partition_expressions { + Self::collect_hash_columns(expr, &mut hash_columns); + } + scan_equalities .iter() - .any(|qa| atomic_exprs_overlap(qa, partition_atomic)) + .filter_map(|expr| { + let (RestrictedOp::Eq, Operand::Column(column), Operand::Value(literal)) = + (expr.op(), expr.lhs(), expr.rhs()) + else { + return None; + }; + let datatype = column_datatypes.get(column)?; + if !hash_columns.contains(column.as_str()) || datatype != &literal.data_type() { + return None; + } + Self::iceberg_hash_constraint(column, literal) + }) + .collect() + } + + fn collect_hash_columns<'a>(expr: &'a PartitionExpr, columns: &mut HashSet<&'a str>) { + for operand in [expr.lhs(), expr.rhs()] { + match operand { + Operand::IcebergHash(hash) => { + columns.insert(hash.column()); + } + Operand::Expr(expr) => Self::collect_hash_columns(expr, columns), + Operand::Column(_) | Operand::Value(_) => {} + } + } + } + + fn iceberg_hash_constraint(column: &str, literal: &Value) -> Option { + if matches!(literal, Value::Null) { + return None; + } + let hash = IcebergHash::evaluate_value(literal).ok()?; + let dimension = Operand::IcebergHash(IcebergHash::new(column)); + // A write can route a missing column as NULL before the region fills its default. + // The current schema cannot rule this out for old writes or in-flight ALTERs. + Some(PartitionExpr::new( + Operand::Expr(dimension.clone().eq(hash)), + RestrictedOp::Or, + Operand::Expr(dimension.eq(Value::Null)), + )) } fn normalize_datatype( @@ -206,10 +308,10 @@ impl ConstraintPruner { true } - // Query predicates never constrain a function dimension, so its values all - // come from partition rules, already typed as the function output. - (Operand::IcebergHash(_), Operand::Value(_)) - | (Operand::Value(_), Operand::IcebergHash(_)) => true, + (Operand::IcebergHash(_), Operand::Value(val)) + | (Operand::Value(val), Operand::IcebergHash(_)) => { + matches!(val, Value::Int32(_) | Value::Null) + } _ => false, } } @@ -219,7 +321,9 @@ impl ConstraintPruner { #[cfg(test)] mod tests { use datatypes::value::Value; + use partition::PartitionRule; use partition::expr::{Operand, PartitionExpr, RestrictedOp, col}; + use partition::multi_dim::MultiDimPartitionRule; use store_api::storage::RegionId; use super::*; @@ -275,9 +379,7 @@ mod tests { } #[test] - fn test_constraint_pruning_with_hash_dimension() { - use partition::function::IcebergHash; - + fn test_hash_equality_prunes_alongside_plain_column() { let hash = Operand::IcebergHash(IcebergHash::new("host")); let partitions = [ col("ts") @@ -301,28 +403,119 @@ mod tests { ("ts".to_string(), ConcreteDataType::int64_datatype()), ("host".to_string(), ConcreteDataType::string_datatype()), ]); + // Both 'b' and a key omitted from a write route to the negative range. + let host_eq = col("host").eq(Value::String("b".into())); let prune = |query: PartitionExpr| { - let mut regions = - ConstraintPruner::prune_regions(&[query], &partitions, column_datatypes.clone()) - .unwrap(); + let mut regions = ConstraintPruner::prune_regions_with_scan_equalities( + &[query], + &partitions, + column_datatypes.clone(), + std::slice::from_ref(&host_eq), + ) + .unwrap(); regions.sort(); regions }; + assert_eq!( + prune(host_eq.clone()), + vec![RegionId::new(1, 1), RegionId::new(1, 3)] + ); + assert_eq!( + prune(host_eq.clone().and(col("ts").gt_eq(Value::Int64(100)))), + vec![RegionId::new(1, 3)] + ); + } - // A filter on the hashed column can't exclude any hash range. - assert_eq!( - prune(col("host").eq(Value::String("a".into()))), - (1..=4).map(|i| RegionId::new(1, i)).collect::>() - ); - // Plain columns in the same rule still prune. - assert_eq!( - prune( - col("host") - .eq(Value::String("a".into())) - .and(col("ts").gt_eq(Value::Int64(100))) - ), - vec![RegionId::new(1, 3), RegionId::new(1, 4)] - ); + #[test] + fn test_hash_equality_keeps_null_and_unmatched_write_destinations() { + let hash = Operand::IcebergHash(IcebergHash::new("host")); + let exprs = vec![ + hash.clone().gt_eq(Value::Int32(1_073_741_824)), + hash.clone().lt(Value::Int32(0)), + hash.eq(Value::Int32(0)), + ]; + let build_rule = |check_exprs| { + MultiDimPartitionRule::try_new( + vec!["host".into()], + vec![0, 1, 2], + exprs.clone(), + check_exprs, + ) + }; + assert!(matches!( + build_rule(true), + Err(partition::error::Error::CheckpointNotCovered { .. }) + )); + + // The metadata loader skips the DDL coverage check. 'a' hashes into the gap. + let rule = build_rule(false).unwrap(); + let host = Value::from("a"); + assert_eq!(rule.find_region(std::slice::from_ref(&host)).unwrap(), 0); + assert_eq!(rule.find_region(&[Value::Null]).unwrap(), 1); + + let partitions = exprs + .into_iter() + .enumerate() + .map(|(i, expr)| create_test_partition_info(i as u64, Some(expr))) + .collect::>(); + let host_eq = [col("host").eq(host)]; + let mut regions = ConstraintPruner::prune_regions_with_scan_equalities( + &host_eq, + &partitions, + HashMap::from_iter([("host".to_string(), ConcreteDataType::string_datatype())]), + &host_eq, + ) + .unwrap(); + regions.sort_unstable(); + assert_eq!(regions, [RegionId::new(1, 0), RegionId::new(1, 1)]); + } + + #[test] + fn test_hash_pruning_keeps_all_regions_for_ineligible_equalities() { + let tenant_eq = col("tenant_id").eq(Value::Int32(7)); + let hash = Operand::IcebergHash(IcebergHash::new("user_id")); + let partition_expressions = [ + tenant_eq.clone().and(hash.clone().lt(Value::Int32(0))), + tenant_eq.clone().and(hash.gt_eq(Value::Int32(0))), + ]; + let partitions = partition_expressions + .iter() + .cloned() + .enumerate() + .map(|(i, expr)| create_test_partition_info(i as u64 + 1, Some(expr))) + .collect::>(); + let column_datatypes = HashMap::from_iter([ + ("user_id".to_string(), ConcreteDataType::int32_datatype()), + ("tenant_id".to_string(), ConcreteDataType::int32_datatype()), + ]); + + // 17_486 hashes below zero, so hashing the mismatched literal would prune region 2. + for equality in [tenant_eq, col("user_id").eq(Value::Int64(17_486))] { + let equalities = std::slice::from_ref(&equality); + // Overlap ignores dimensions absent from the route, so also check the inference. + assert!( + ConstraintPruner::iceberg_hash_constraints( + equalities, + &partition_expressions, + &column_datatypes, + ) + .is_empty(), + "{equality:?} should not produce a hash constraint" + ); + let mut regions = ConstraintPruner::prune_regions_with_scan_equalities( + equalities, + &partitions, + column_datatypes.clone(), + equalities, + ) + .unwrap(); + regions.sort_unstable(); + assert_eq!( + regions, + vec![RegionId::new(1, 1), RegionId::new(1, 2)], + "{equality:?} should keep both regions" + ); + } } #[test] diff --git a/tests/cases/standalone/common/partition_iceberg_hash_functions.result b/tests/cases/standalone/common/partition_iceberg_hash_functions.result index 6355cea0b0b..86b73df6851 100644 --- a/tests/cases/standalone/common/partition_iceberg_hash_functions.result +++ b/tests/cases/standalone/common/partition_iceberg_hash_functions.result @@ -162,7 +162,57 @@ ORDER BY region_number; | 3 | 1 | +---------------+-------------+ +-- 'b' and the omitted-key route share one region. The SQL predicate still rejects NULL. +-- SQLNESS REPLACE (?s)^.*?(MergeScanExec:\speers=\[[^\]]*\]).*$ $1 +-- SQLNESS REPLACE \d+\(\d+,\s+(\d+)\) r$1 +EXPLAIN SELECT "host-name", v FROM hash_function_rules WHERE 'b' = "host-name"; + +MergeScanExec: peers=[r0, ] + +SELECT "host-name", v FROM hash_function_rules WHERE 'b' = "host-name"; + ++-----------+---+ +| host-name | v | ++-----------+---+ +| b | 1 | ++-----------+---+ + DROP TABLE hash_function_rules; Affected Rows: 0 +-- Check visibility after DROP DEFAULT for a write that omitted host. The NULL route is +-- region 1 and 'a' routes to region 2; no input needs the region 0 fallback here. +CREATE TABLE hash_equality_default ( + host STRING DEFAULT 'a', + ts TIMESTAMP TIME INDEX, + PRIMARY KEY (host) +) +PARTITION ON COLUMNS (host) ( + iceberg_hash(host) >= 1073741824, + iceberg_hash(host) < 0, + iceberg_hash(host) >= 0 AND iceberg_hash(host) < 1073741824 +); + +Affected Rows: 0 + +INSERT INTO hash_equality_default (ts) VALUES (1); + +Affected Rows: 1 + +ALTER TABLE hash_equality_default MODIFY COLUMN host DROP DEFAULT; + +Affected Rows: 0 + +SELECT host FROM hash_equality_default WHERE host = 'a'; + ++------+ +| host | ++------+ +| a | ++------+ + +DROP TABLE hash_equality_default; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/partition_iceberg_hash_functions.sql b/tests/cases/standalone/common/partition_iceberg_hash_functions.sql index 44429a51709..4e1436e9539 100644 --- a/tests/cases/standalone/common/partition_iceberg_hash_functions.sql +++ b/tests/cases/standalone/common/partition_iceberg_hash_functions.sql @@ -69,4 +69,30 @@ WHERE table_id IN ( ) ORDER BY region_number; +-- 'b' and the omitted-key route share one region. The SQL predicate still rejects NULL. +-- SQLNESS REPLACE (?s)^.*?(MergeScanExec:\speers=\[[^\]]*\]).*$ $1 +-- SQLNESS REPLACE \d+\(\d+,\s+(\d+)\) r$1 +EXPLAIN SELECT "host-name", v FROM hash_function_rules WHERE 'b' = "host-name"; + +SELECT "host-name", v FROM hash_function_rules WHERE 'b' = "host-name"; + DROP TABLE hash_function_rules; + +-- Check visibility after DROP DEFAULT for a write that omitted host. The NULL route is +-- region 1 and 'a' routes to region 2; no input needs the region 0 fallback here. +CREATE TABLE hash_equality_default ( + host STRING DEFAULT 'a', + ts TIMESTAMP TIME INDEX, + PRIMARY KEY (host) +) +PARTITION ON COLUMNS (host) ( + iceberg_hash(host) >= 1073741824, + iceberg_hash(host) < 0, + iceberg_hash(host) >= 0 AND iceberg_hash(host) < 1073741824 +); + +INSERT INTO hash_equality_default (ts) VALUES (1); +ALTER TABLE hash_equality_default MODIFY COLUMN host DROP DEFAULT; +SELECT host FROM hash_equality_default WHERE host = 'a'; + +DROP TABLE hash_equality_default;