Skip to main content

query/dist_plan/
region_pruner.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//! [`ConstraintPruner`] prunes partition info based on given expressions.
16
17use std::cmp::Ordering;
18
19use ahash::{HashMap, HashSet};
20use common_telemetry::debug;
21use datatypes::prelude::ConcreteDataType;
22use datatypes::value::{OrderedFloat, Value};
23use partition::collider::{AtomicExpr, Collider};
24use partition::expr::{Operand, PartitionExpr, RestrictedOp};
25use partition::function::IcebergHash;
26use partition::manager::PartitionInfo;
27use partition::overlap::atomic_exprs_overlap;
28use store_api::storage::RegionId;
29
30use crate::error::Result;
31
32pub struct ConstraintPruner;
33
34impl ConstraintPruner {
35    /// Returns candidate Regions using only the supplied partition constraints.
36    ///
37    /// This public entry point does not require scan-local predicates. The distributed planner
38    /// supplies those separately when inferring constraints on hash dimensions.
39    pub fn prune_regions(
40        query_expressions: &[PartitionExpr],
41        partitions: &[PartitionInfo],
42        column_datatypes: HashMap<String, ConcreteDataType>,
43    ) -> Result<Vec<RegionId>> {
44        Self::prune_regions_with_scan_equalities(
45            query_expressions,
46            partitions,
47            column_datatypes,
48            &[],
49        )
50    }
51
52    /// Also prunes hash dimensions using equalities that apply directly to the scan.
53    pub(crate) fn prune_regions_with_scan_equalities(
54        query_expressions: &[PartitionExpr],
55        partitions: &[PartitionInfo],
56        column_datatypes: HashMap<String, ConcreteDataType>,
57        scan_equalities: &[PartitionExpr],
58    ) -> Result<Vec<RegionId>> {
59        let start = std::time::Instant::now();
60        let all_regions = partitions
61            .iter()
62            .map(|partition| partition.id)
63            .collect::<Vec<_>>();
64        if query_expressions.is_empty() || partitions.is_empty() {
65            // No constraints, return all regions
66            return Ok(all_regions);
67        }
68
69        // Collect all partition expressions for unified normalization
70        let Some(mut all_partition_expressions) = partitions
71            .iter()
72            .map(|partition| partition.partition_expr.clone())
73            .collect::<Option<Vec<_>>>()
74        else {
75            debug!(
76                "Partition metadata contains a missing partition expression, returning all regions conservatively"
77            );
78            return Ok(all_regions);
79        };
80
81        let hash_equalities = Self::iceberg_hash_equalities(
82            scan_equalities,
83            &all_partition_expressions,
84            &column_datatypes,
85        );
86        let mut all_expressions = query_expressions.to_vec();
87        if !Self::normalize_datatype(&mut all_expressions, &column_datatypes)
88            || !Self::normalize_datatype(&mut all_partition_expressions, &column_datatypes)
89        {
90            // A hash can still exclude a route even if we cannot compare its timestamp bounds.
91            if hash_equalities.is_empty() {
92                return Ok(all_regions);
93            }
94            let regions = all_regions
95                .into_iter()
96                .zip(&all_partition_expressions)
97                .filter_map(|(region, rule)| {
98                    (region.region_number() == 0
99                        || hash_equalities.iter().all(|eq| eq.may_match(rule)))
100                    .then_some(region)
101                })
102                .collect();
103            return Ok(regions);
104        }
105
106        // Derived comparisons already have the hash dimension's type (Int32 or NULL).
107        all_expressions.extend(
108            hash_equalities
109                .iter()
110                .map(IcebergHashEquality::as_constraint),
111        );
112        let partition_expr_offset = all_expressions.len();
113        all_expressions.extend(all_partition_expressions);
114        let collider = match Collider::new(&all_expressions) {
115            Ok(collider) => collider,
116            Err(err) => {
117                debug!(
118                    "Failed to create unified collider: {}, returning all regions conservatively",
119                    err
120                );
121                return Ok(all_regions);
122            }
123        };
124
125        let candidate_regions = Self::matching_regions(
126            &collider.atomic_exprs,
127            &all_regions,
128            query_expressions.len(),
129            partition_expr_offset,
130        );
131        debug!(
132            "Constraint pruning (cost {}ms): {} -> {} regions",
133            start.elapsed().as_millis(),
134            partitions.len(),
135            candidate_regions.len()
136        );
137        Ok(candidate_regions)
138    }
139
140    fn matching_regions(
141        atomics: &[AtomicExpr],
142        all_regions: &[RegionId],
143        query_expr_count: usize,
144        partition_expr_offset: usize,
145    ) -> Vec<RegionId> {
146        // In partition::collider, Collider::new visits sources in index order and
147        // Collider::collide_expr appends each source's OR branches together. Both partition_point
148        // and chunk_by below rely on that order.
149        let (filter_atomics, partition_atomics) = atomics.split_at(
150            atomics.partition_point(|atomic| atomic.source_expr_index < partition_expr_offset),
151        );
152        let (query_atomics, hash_atomics) = filter_atomics.split_at(
153            filter_atomics.partition_point(|atomic| atomic.source_expr_index < query_expr_count),
154        );
155        // Each scan equality must hold. Its literal and NULL routes are alternatives.
156        partition_atomics
157            .chunk_by(Self::same_source_expr)
158            .filter_map(|route| {
159                if !Self::atomic_sets_overlap(query_atomics, route) {
160                    return None;
161                }
162                let region = all_regions[route[0].source_expr_index - partition_expr_offset];
163                // Persisted rules are loaded without checking coverage. Writes in a gap go to
164                // region 0, so even a fully covered layout may scan one extra region here.
165                let hash_matches = region.region_number() == 0
166                    || hash_atomics
167                        .chunk_by(Self::same_source_expr)
168                        .all(|constraint| Self::atomic_sets_overlap(constraint, route));
169                hash_matches.then_some(region)
170            })
171            .collect::<HashSet<_>>()
172            .into_iter()
173            .collect()
174    }
175
176    fn same_source_expr(lhs: &AtomicExpr, rhs: &AtomicExpr) -> bool {
177        lhs.source_expr_index == rhs.source_expr_index
178    }
179
180    fn atomic_sets_overlap(lhs: &[AtomicExpr], rhs: &[AtomicExpr]) -> bool {
181        lhs.iter()
182            .any(|left| rhs.iter().any(|right| atomic_exprs_overlap(left, right)))
183    }
184
185    fn iceberg_hash_equalities<'a>(
186        scan_equalities: &'a [PartitionExpr],
187        partition_expressions: &[PartitionExpr],
188        column_datatypes: &HashMap<String, ConcreteDataType>,
189    ) -> Vec<IcebergHashEquality<'a>> {
190        if scan_equalities.is_empty() {
191            return Vec::new();
192        }
193        let mut hash_columns = HashSet::default();
194        for expr in partition_expressions {
195            Self::collect_hash_columns(expr, &mut hash_columns);
196        }
197        scan_equalities
198            .iter()
199            .filter_map(|expr| {
200                let (RestrictedOp::Eq, Operand::Column(column), Operand::Value(literal)) =
201                    (expr.op(), expr.lhs(), expr.rhs())
202                else {
203                    return None;
204                };
205                let datatype = column_datatypes.get(column)?;
206                if !hash_columns.contains(column.as_str()) || datatype != &literal.data_type() {
207                    return None;
208                }
209                let Value::Int32(hash) = IcebergHash::evaluate_value(literal).ok()? else {
210                    return None;
211                };
212                Some(IcebergHashEquality { column, hash })
213            })
214            .collect()
215    }
216
217    fn collect_hash_columns<'a>(expr: &'a PartitionExpr, columns: &mut HashSet<&'a str>) {
218        for operand in [expr.lhs(), expr.rhs()] {
219            match operand {
220                Operand::IcebergHash(hash) => {
221                    columns.insert(hash.column());
222                }
223                Operand::Expr(expr) => Self::collect_hash_columns(expr, columns),
224                Operand::Column(_) | Operand::Value(_) => {}
225            }
226        }
227    }
228
229    fn normalize_datatype(
230        all_expressions: &mut Vec<PartitionExpr>,
231        column_datatypes: &HashMap<String, ConcreteDataType>,
232    ) -> bool {
233        for expr in all_expressions {
234            if !Self::normalize_expr_datatype(&mut expr.lhs, &mut expr.rhs, column_datatypes) {
235                return false;
236            }
237        }
238        true
239    }
240
241    fn normalize_expr_datatype(
242        lhs: &mut Operand,
243        rhs: &mut Operand,
244        column_datatypes: &HashMap<String, ConcreteDataType>,
245    ) -> bool {
246        match (lhs, rhs) {
247            (Operand::Expr(lhs_expr), Operand::Expr(rhs_expr)) => {
248                Self::normalize_expr_datatype(
249                    &mut lhs_expr.lhs,
250                    &mut lhs_expr.rhs,
251                    column_datatypes,
252                ) && Self::normalize_expr_datatype(
253                    &mut rhs_expr.lhs,
254                    &mut rhs_expr.rhs,
255                    column_datatypes,
256                )
257            }
258            (Operand::Column(col_name), Operand::Value(val))
259            | (Operand::Value(val), Operand::Column(col_name)) => {
260                let Some(datatype) = column_datatypes.get(col_name) else {
261                    debug!("Column {} not found from type set, skip pruning", col_name);
262                    return false;
263                };
264
265                match datatype {
266                    ConcreteDataType::Int8(_)
267                    | ConcreteDataType::Int16(_)
268                    | ConcreteDataType::Int32(_)
269                    | ConcreteDataType::Int64(_) => {
270                        let Some(new_lit) = val.as_i64() else {
271                            debug!("Value {:?} cannot be converted to i64", val);
272                            return false;
273                        };
274                        *val = Value::Int64(new_lit);
275                    }
276
277                    ConcreteDataType::UInt8(_)
278                    | ConcreteDataType::UInt16(_)
279                    | ConcreteDataType::UInt32(_)
280                    | ConcreteDataType::UInt64(_) => {
281                        let Some(new_lit) = val.as_u64() else {
282                            debug!("Value {:?} cannot be converted to u64", val);
283                            return false;
284                        };
285                        *val = Value::UInt64(new_lit);
286                    }
287
288                    ConcreteDataType::Float32(_) | ConcreteDataType::Float64(_) => {
289                        let Some(new_lit) = val.as_f64_lossy() else {
290                            debug!("Value {:?} cannot be converted to f64", val);
291                            return false;
292                        };
293
294                        *val = Value::Float64(OrderedFloat(new_lit));
295                    }
296
297                    ConcreteDataType::String(_) | ConcreteDataType::Boolean(_) => {
298                        // no operation needed
299                    }
300
301                    ConcreteDataType::Decimal128(_)
302                    | ConcreteDataType::Binary(_)
303                    | ConcreteDataType::Date(_)
304                    | ConcreteDataType::Timestamp(_)
305                    | ConcreteDataType::Time(_)
306                    | ConcreteDataType::Duration(_)
307                    | ConcreteDataType::Interval(_)
308                    | ConcreteDataType::List(_)
309                    | ConcreteDataType::Dictionary(_)
310                    | ConcreteDataType::Struct(_)
311                    | ConcreteDataType::Json(_)
312                    | ConcreteDataType::Null(_)
313                    | ConcreteDataType::Vector(_) => {
314                        debug!("Unsupported data type {datatype}");
315                        return false;
316                    }
317                }
318
319                true
320            }
321            (Operand::IcebergHash(_), Operand::Value(val))
322            | (Operand::Value(val), Operand::IcebergHash(_)) => {
323                matches!(val, Value::Int32(_) | Value::Null)
324            }
325            _ => false,
326        }
327    }
328}
329
330struct IcebergHashEquality<'a> {
331    column: &'a str,
332    hash: i32,
333}
334
335impl IcebergHashEquality<'_> {
336    fn routing_values(&self) -> [Value; 2] {
337        // An omitted column can route as NULL before the region fills its default.
338        [Value::Int32(self.hash), Value::Null]
339    }
340
341    fn as_constraint(&self) -> PartitionExpr {
342        let dimension = Operand::IcebergHash(IcebergHash::new(self.column));
343        let [literal, missing] = self.routing_values();
344        PartitionExpr::new(
345            Operand::Expr(dimension.clone().eq(literal)),
346            RestrictedOp::Or,
347            Operand::Expr(dimension.eq(missing)),
348        )
349    }
350
351    fn may_match(&self, rule: &PartitionExpr) -> bool {
352        // The lower and upper bounds of a bucket must admit the same routing value.
353        self.routing_values()
354            .iter()
355            .any(|value| self.rule_admits(rule, value))
356    }
357
358    fn rule_admits(&self, rule: &PartitionExpr, routing_value: &Value) -> bool {
359        match (rule.lhs(), rule.op(), rule.rhs()) {
360            (Operand::Expr(lhs), RestrictedOp::And, Operand::Expr(rhs)) => {
361                self.rule_admits(lhs, routing_value) && self.rule_admits(rhs, routing_value)
362            }
363            (Operand::Expr(lhs), RestrictedOp::Or, Operand::Expr(rhs)) => {
364                self.rule_admits(lhs, routing_value) || self.rule_admits(rhs, routing_value)
365            }
366            (Operand::IcebergHash(hash), op, Operand::Value(bound))
367                if hash.column() == self.column
368                    && matches!(bound, Value::Int32(_) | Value::Null) =>
369            {
370                // Value orders NULL before every non-NULL hash, just as write routing does.
371                partition_comparison_matches(op, routing_value.cmp(bound)).unwrap_or(true)
372            }
373            // Other dimensions and unknown bounds can satisfy this branch.
374            _ => true,
375        }
376    }
377}
378
379/// Tests a scalar partition comparison after the operand types have been checked.
380pub(crate) fn partition_comparison_matches(op: &RestrictedOp, ordering: Ordering) -> Option<bool> {
381    Some(match op {
382        RestrictedOp::Eq => ordering.is_eq(),
383        RestrictedOp::NotEq => !ordering.is_eq(),
384        RestrictedOp::Lt => ordering.is_lt(),
385        RestrictedOp::LtEq => ordering.is_le(),
386        RestrictedOp::Gt => ordering.is_gt(),
387        RestrictedOp::GtEq => ordering.is_ge(),
388        RestrictedOp::And | RestrictedOp::Or => return None,
389    })
390}
391
392#[cfg(test)]
393mod tests {
394    use common_time::Timestamp;
395    use datatypes::value::Value;
396    use partition::PartitionRule;
397    use partition::expr::{Operand, PartitionExpr, RestrictedOp, col};
398    use partition::multi_dim::MultiDimPartitionRule;
399    use store_api::storage::RegionId;
400
401    use super::*;
402
403    fn create_test_partition_info(region_id: u64, expr: Option<PartitionExpr>) -> PartitionInfo {
404        PartitionInfo {
405            id: RegionId::new(1, region_id as u32),
406            partition_expr: expr,
407        }
408    }
409
410    #[test]
411    fn test_constraint_pruning_equality() {
412        let partitions = vec![
413            // Region 1: user_id >= 0 AND user_id < 100
414            create_test_partition_info(
415                1,
416                Some(
417                    col("user_id")
418                        .gt_eq(Value::Int64(0))
419                        .and(col("user_id").lt(Value::Int64(100))),
420                ),
421            ),
422            // Region 2: user_id >= 100 AND user_id < 200
423            create_test_partition_info(
424                2,
425                Some(
426                    col("user_id")
427                        .gt_eq(Value::Int64(100))
428                        .and(col("user_id").lt(Value::Int64(200))),
429                ),
430            ),
431            // Region 3: user_id >= 200 AND user_id < 300
432            create_test_partition_info(
433                3,
434                Some(
435                    col("user_id")
436                        .gt_eq(Value::Int64(200))
437                        .and(col("user_id").lt(Value::Int64(300))),
438                ),
439            ),
440        ];
441
442        // Query: user_id = 150 (should only match Region 2)
443        let query_exprs = vec![col("user_id").eq(Value::Int64(150))];
444        let mut column_datatypes = HashMap::default();
445        column_datatypes.insert("user_id".to_string(), ConcreteDataType::int64_datatype());
446        let pruned =
447            ConstraintPruner::prune_regions(&query_exprs, &partitions, column_datatypes).unwrap();
448
449        // Should include Region 2, and potentially others due to conservative approach
450        assert!(pruned.contains(&RegionId::new(1, 2)));
451    }
452
453    #[test]
454    fn test_hash_equality_prunes_alongside_plain_column() {
455        let hash = Operand::IcebergHash(IcebergHash::new("host"));
456        let partitions = [
457            col("ts")
458                .lt(Value::Int64(100))
459                .and(hash.clone().lt(Value::Int32(0))),
460            col("ts")
461                .lt(Value::Int64(100))
462                .and(hash.clone().gt_eq(Value::Int32(0))),
463            col("ts")
464                .gt_eq(Value::Int64(100))
465                .and(hash.clone().lt(Value::Int32(0))),
466            col("ts")
467                .gt_eq(Value::Int64(100))
468                .and(hash.gt_eq(Value::Int32(0))),
469        ]
470        .into_iter()
471        .enumerate()
472        .map(|(i, expr)| create_test_partition_info(i as u64 + 1, Some(expr)))
473        .collect::<Vec<_>>();
474        let column_datatypes = HashMap::from_iter([
475            ("ts".to_string(), ConcreteDataType::int64_datatype()),
476            ("host".to_string(), ConcreteDataType::string_datatype()),
477        ]);
478        // Both 'b' and a key omitted from a write route to the negative range.
479        let host_eq = col("host").eq(Value::String("b".into()));
480        let prune = |query: PartitionExpr| {
481            let mut regions = ConstraintPruner::prune_regions_with_scan_equalities(
482                &[query],
483                &partitions,
484                column_datatypes.clone(),
485                std::slice::from_ref(&host_eq),
486            )
487            .unwrap();
488            regions.sort();
489            regions
490        };
491        assert_eq!(
492            prune(host_eq.clone()),
493            vec![RegionId::new(1, 1), RegionId::new(1, 3)]
494        );
495        assert_eq!(
496            prune(host_eq.clone().and(col("ts").gt_eq(Value::Int64(100)))),
497            vec![RegionId::new(1, 3)]
498        );
499    }
500
501    #[test]
502    fn test_hash_fallback_checks_each_routing_value_against_the_whole_rule() {
503        let cutoff = Value::Timestamp(Timestamp::new_millisecond(100));
504        let column_types = HashMap::from_iter([
505            ("ts".to_string(), cutoff.data_type()),
506            ("host".to_string(), ConcreteDataType::string_datatype()),
507        ]);
508        let host_eq = [col("host").eq(Value::from("a"))];
509        let keeps = |id, rule, scan_equalities: &[PartitionExpr]| {
510            let region = create_test_partition_info(id, Some(rule));
511            ConstraintPruner::prune_regions_with_scan_equalities(
512                &host_eq,
513                std::slice::from_ref(&region),
514                column_types.clone(),
515                scan_equalities,
516            )
517            .unwrap()
518            .contains(&region.id)
519        };
520
521        // The hash of 'a' is above 100, while an omitted key routes as NULL, below zero.
522        let hash = Operand::IcebergHash(IcebergHash::new("host"));
523        let above = hash.clone().gt_eq(Value::Int32(0));
524        let below = hash.lt(Value::Int32(100));
525        let middle = above.clone().and(below.clone());
526        let before = col("ts").lt(cutoff);
527        let and_rule = before.clone().and(middle.clone());
528        let or_rule = PartitionExpr::new(
529            Operand::Expr(before.clone()),
530            RestrictedOp::Or,
531            Operand::Expr(middle),
532        );
533
534        assert!(keeps(1, before.clone().and(above), &host_eq)); // Literal route.
535        assert!(keeps(1, before.and(below), &host_eq)); // NULL route.
536        assert!(!keeps(1, and_rule.clone(), &host_eq));
537        assert!(keeps(1, or_rule, &host_eq)); // Time alone can match.
538        assert!(keeps(0, and_rule.clone(), &host_eq)); // Unmatched writes.
539        assert!(keeps(1, and_rule, &[])); // No scan-local equality.
540    }
541
542    #[test]
543    fn test_hash_equality_keeps_null_and_unmatched_write_destinations() {
544        let hash = Operand::IcebergHash(IcebergHash::new("host"));
545        let exprs = vec![
546            hash.clone().gt_eq(Value::Int32(1_073_741_824)),
547            hash.clone().lt(Value::Int32(0)),
548            hash.eq(Value::Int32(0)),
549        ];
550        let build_rule = |check_exprs| {
551            MultiDimPartitionRule::try_new(
552                vec!["host".into()],
553                vec![0, 1, 2],
554                exprs.clone(),
555                check_exprs,
556            )
557        };
558        assert!(matches!(
559            build_rule(true),
560            Err(partition::error::Error::CheckpointNotCovered { .. })
561        ));
562
563        // The metadata loader skips the DDL coverage check. 'a' hashes into the gap.
564        let rule = build_rule(false).unwrap();
565        let host = Value::from("a");
566        assert_eq!(rule.find_region(std::slice::from_ref(&host)).unwrap(), 0);
567        assert_eq!(rule.find_region(&[Value::Null]).unwrap(), 1);
568
569        let partitions = exprs
570            .into_iter()
571            .enumerate()
572            .map(|(i, expr)| create_test_partition_info(i as u64, Some(expr)))
573            .collect::<Vec<_>>();
574        let host_eq = [col("host").eq(host)];
575        let mut regions = ConstraintPruner::prune_regions_with_scan_equalities(
576            &host_eq,
577            &partitions,
578            HashMap::from_iter([("host".to_string(), ConcreteDataType::string_datatype())]),
579            &host_eq,
580        )
581        .unwrap();
582        regions.sort_unstable();
583        assert_eq!(regions, [RegionId::new(1, 0), RegionId::new(1, 1)]);
584    }
585
586    #[test]
587    fn test_hash_pruning_keeps_all_regions_for_ineligible_equalities() {
588        let tenant_eq = col("tenant_id").eq(Value::Int32(7));
589        let hash = Operand::IcebergHash(IcebergHash::new("user_id"));
590        let partition_expressions = [
591            tenant_eq.clone().and(hash.clone().lt(Value::Int32(0))),
592            tenant_eq.clone().and(hash.gt_eq(Value::Int32(0))),
593        ];
594        let partitions = partition_expressions
595            .iter()
596            .cloned()
597            .enumerate()
598            .map(|(i, expr)| create_test_partition_info(i as u64 + 1, Some(expr)))
599            .collect::<Vec<_>>();
600        let column_datatypes = HashMap::from_iter([
601            ("user_id".to_string(), ConcreteDataType::int32_datatype()),
602            ("tenant_id".to_string(), ConcreteDataType::int32_datatype()),
603        ]);
604
605        // 17_486 hashes below zero, so hashing the mismatched literal would prune region 2.
606        for equality in [tenant_eq, col("user_id").eq(Value::Int64(17_486))] {
607            let equalities = std::slice::from_ref(&equality);
608            // Overlap ignores dimensions absent from the route, so also check the inference.
609            assert!(
610                ConstraintPruner::iceberg_hash_equalities(
611                    equalities,
612                    &partition_expressions,
613                    &column_datatypes,
614                )
615                .is_empty(),
616                "{equality:?} should not produce a hash constraint"
617            );
618            let mut regions = ConstraintPruner::prune_regions_with_scan_equalities(
619                equalities,
620                &partitions,
621                column_datatypes.clone(),
622                equalities,
623            )
624            .unwrap();
625            regions.sort_unstable();
626            assert_eq!(
627                regions,
628                vec![RegionId::new(1, 1), RegionId::new(1, 2)],
629                "{equality:?} should keep both regions"
630            );
631        }
632    }
633
634    #[test]
635    fn test_constraint_pruning_in_list() {
636        let partitions = vec![
637            // Region 1: user_id >= 0 AND user_id < 100
638            create_test_partition_info(
639                1,
640                Some(
641                    col("user_id")
642                        .gt_eq(Value::Int64(0))
643                        .and(col("user_id").lt(Value::Int64(100))),
644                ),
645            ),
646            // Region 2: user_id >= 100 AND user_id < 200
647            create_test_partition_info(
648                2,
649                Some(
650                    col("user_id")
651                        .gt_eq(Value::Int64(100))
652                        .and(col("user_id").lt(Value::Int64(200))),
653                ),
654            ),
655            // Region 3: user_id >= 200 AND user_id < 300
656            create_test_partition_info(
657                3,
658                Some(
659                    col("user_id")
660                        .gt_eq(Value::Int64(200))
661                        .and(col("user_id").lt(Value::Int64(300))),
662                ),
663            ),
664        ];
665
666        // Query: user_id IN (50, 150, 250) - should match all regions
667        let query_exprs = vec![PartitionExpr::new(
668            Operand::Expr(PartitionExpr::new(
669                Operand::Expr(col("user_id").eq(Value::Int64(50))),
670                RestrictedOp::Or,
671                Operand::Expr(col("user_id").eq(Value::Int64(150))),
672            )),
673            RestrictedOp::Or,
674            Operand::Expr(col("user_id").eq(Value::Int64(250))),
675        )];
676
677        let mut column_datatypes = HashMap::default();
678        column_datatypes.insert("user_id".to_string(), ConcreteDataType::int64_datatype());
679        let pruned =
680            ConstraintPruner::prune_regions(&query_exprs, &partitions, column_datatypes).unwrap();
681
682        // Should include regions that can satisfy any of the values
683        assert!(!pruned.is_empty());
684    }
685
686    #[test]
687    fn test_constraint_pruning_range() {
688        let partitions = vec![
689            // Region 1: user_id >= 0 AND user_id < 100
690            create_test_partition_info(
691                1,
692                Some(
693                    col("user_id")
694                        .gt_eq(Value::Int64(0))
695                        .and(col("user_id").lt(Value::Int64(100))),
696                ),
697            ),
698            // Region 2: user_id >= 100 AND user_id < 200
699            create_test_partition_info(
700                2,
701                Some(
702                    col("user_id")
703                        .gt_eq(Value::Int64(100))
704                        .and(col("user_id").lt(Value::Int64(200))),
705                ),
706            ),
707            // Region 3: user_id >= 200 AND user_id < 300
708            create_test_partition_info(
709                3,
710                Some(
711                    col("user_id")
712                        .gt_eq(Value::Int64(200))
713                        .and(col("user_id").lt(Value::Int64(300))),
714                ),
715            ),
716        ];
717
718        // Query: user_id >= 150 (should include regions that can satisfy this constraint)
719        let query_exprs = vec![col("user_id").gt_eq(Value::Int64(150))];
720        let mut column_datatypes = HashMap::default();
721        column_datatypes.insert("user_id".to_string(), ConcreteDataType::int64_datatype());
722        let pruned =
723            ConstraintPruner::prune_regions(&query_exprs, &partitions, column_datatypes).unwrap();
724
725        // With constraint-based approach:
726        // Region 1: [0, 100) - user_id >= 150 is not satisfiable
727        // Region 2: [100, 200) - user_id >= 150 is satisfiable in range [150, 200)
728        // Region 3: [200, 300) - user_id >= 150 is satisfiable (all values >= 200 satisfy user_id >= 150)
729        // Conservative approach may include more regions, but should at least include regions 2 and 3
730        assert!(pruned.len() >= 2);
731        assert!(pruned.contains(&RegionId::new(1, 2))); // Region 2 should be included
732        assert!(pruned.contains(&RegionId::new(1, 3))); // Region 3 should be included
733    }
734
735    #[test]
736    fn test_prune_regions_no_constraints() {
737        let partitions = vec![
738            create_test_partition_info(1, None),
739            create_test_partition_info(2, None),
740        ];
741
742        let constraints = vec![];
743        let column_datatypes = HashMap::default();
744        let pruned =
745            ConstraintPruner::prune_regions(&constraints, &partitions, column_datatypes).unwrap();
746
747        // No constraints should return all regions
748        assert_eq!(pruned.len(), 2);
749    }
750
751    #[test]
752    fn test_missing_partition_expression_returns_all_regions() {
753        let partitions = vec![
754            create_test_partition_info(1, Some(col("user_id").lt(Value::Int64(100)))),
755            create_test_partition_info(2, None),
756            create_test_partition_info(3, Some(col("user_id").gt_eq(Value::Int64(200)))),
757        ];
758        let query_exprs = vec![col("user_id").eq(Value::Int64(150))];
759        let mut column_datatypes = HashMap::default();
760        column_datatypes.insert("user_id".to_string(), ConcreteDataType::int64_datatype());
761
762        let pruned =
763            ConstraintPruner::prune_regions(&query_exprs, &partitions, column_datatypes).unwrap();
764
765        assert_eq!(
766            vec![
767                RegionId::new(1, 1),
768                RegionId::new(1, 2),
769                RegionId::new(1, 3),
770            ],
771            pruned
772        );
773    }
774
775    #[test]
776    fn test_prune_regions_with_or_constraint() {
777        let partitions = vec![
778            // Region 1: user_id >= 0 AND user_id < 100
779            create_test_partition_info(
780                1,
781                Some(
782                    col("user_id")
783                        .gt_eq(Value::Int64(0))
784                        .and(col("user_id").lt(Value::Int64(100))),
785                ),
786            ),
787            // Region 2: user_id >= 100 AND user_id < 200
788            create_test_partition_info(
789                2,
790                Some(
791                    col("user_id")
792                        .gt_eq(Value::Int64(100))
793                        .and(col("user_id").lt(Value::Int64(200))),
794                ),
795            ),
796            // Region 3: user_id >= 200 AND user_id < 300
797            create_test_partition_info(
798                3,
799                Some(
800                    col("user_id")
801                        .gt_eq(Value::Int64(200))
802                        .and(col("user_id").lt(Value::Int64(300))),
803                ),
804            ),
805        ];
806
807        // Query: user_id = 50 OR user_id = 150 OR user_id = 250 - should match all 3 regions
808        let expr1 = col("user_id").eq(Value::Int64(50));
809        let expr2 = col("user_id").eq(Value::Int64(150));
810        let expr3 = col("user_id").eq(Value::Int64(250));
811
812        let or_expr = PartitionExpr::new(
813            Operand::Expr(PartitionExpr::new(
814                Operand::Expr(expr1),
815                RestrictedOp::Or,
816                Operand::Expr(expr2),
817            )),
818            RestrictedOp::Or,
819            Operand::Expr(expr3),
820        );
821
822        let query_exprs = vec![or_expr];
823        let mut column_datatypes = HashMap::default();
824        column_datatypes.insert("user_id".to_string(), ConcreteDataType::int64_datatype());
825        let pruned =
826            ConstraintPruner::prune_regions(&query_exprs, &partitions, column_datatypes).unwrap();
827
828        // Should match all 3 regions: 50 matches Region 1, 150 matches Region 2, 250 matches Region 3
829        assert_eq!(pruned.len(), 3);
830        assert!(pruned.contains(&RegionId::new(1, 1)));
831        assert!(pruned.contains(&RegionId::new(1, 2)));
832        assert!(pruned.contains(&RegionId::new(1, 3)));
833    }
834
835    #[test]
836    fn test_constraint_pruning_no_match() {
837        let partitions = vec![
838            // Region 1: user_id >= 0 AND user_id < 100
839            create_test_partition_info(
840                1,
841                Some(
842                    col("user_id")
843                        .gt_eq(Value::Int64(0))
844                        .and(col("user_id").lt(Value::Int64(100))),
845                ),
846            ),
847            // Region 2: user_id >= 100 AND user_id < 200
848            create_test_partition_info(
849                2,
850                Some(
851                    col("user_id")
852                        .gt_eq(Value::Int64(100))
853                        .and(col("user_id").lt(Value::Int64(200))),
854                ),
855            ),
856        ];
857
858        // Query: user_id = 300 (should match no regions)
859        let query_exprs = vec![col("user_id").eq(Value::Int64(300))];
860        let mut column_datatypes = HashMap::default();
861        column_datatypes.insert("user_id".to_string(), ConcreteDataType::int64_datatype());
862        let pruned =
863            ConstraintPruner::prune_regions(&query_exprs, &partitions, column_datatypes).unwrap();
864
865        // Should match no regions since 300 is outside both partition ranges
866        assert_eq!(pruned.len(), 0);
867    }
868
869    #[test]
870    fn test_constraint_pruning_partial_match() {
871        let partitions = vec![
872            // Region 1: user_id >= 0 AND user_id < 100
873            create_test_partition_info(
874                1,
875                Some(
876                    col("user_id")
877                        .gt_eq(Value::Int64(0))
878                        .and(col("user_id").lt(Value::Int64(100))),
879                ),
880            ),
881            // Region 2: user_id >= 100 AND user_id < 200
882            create_test_partition_info(
883                2,
884                Some(
885                    col("user_id")
886                        .gt_eq(Value::Int64(100))
887                        .and(col("user_id").lt(Value::Int64(200))),
888                ),
889            ),
890        ];
891
892        // Query: user_id >= 50 (should match both regions partially)
893        let query_exprs = vec![col("user_id").gt_eq(Value::Int64(50))];
894        let mut column_datatypes = HashMap::default();
895        column_datatypes.insert("user_id".to_string(), ConcreteDataType::int64_datatype());
896        let pruned =
897            ConstraintPruner::prune_regions(&query_exprs, &partitions, column_datatypes).unwrap();
898
899        // Region 1: [0,100) intersects with [50,∞) -> includes [50,100)
900        // Region 2: [100,200) is fully contained in [50,∞)
901        assert_eq!(pruned.len(), 2);
902        assert!(pruned.contains(&RegionId::new(1, 1)));
903        assert!(pruned.contains(&RegionId::new(1, 2)));
904    }
905}