mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-03 07:55:25 +00:00
perf(query): prune iceberg_hash buckets across timestamp ranges (#10766)
perf(query): retain hash pruning when partition bounds cannot normalize Use scan-local iceberg_hash equalities to exclude routes even when another partition dimension prevents constraint normalization. Preserve NULL and unmatched-write destinations, and cover the fallback in a mixed timestamp/hash SQLNESS case. Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
This commit is contained in:
@@ -52,7 +52,7 @@ use table::table_name::TableName;
|
||||
use crate::dist_plan::PredicateExtractor;
|
||||
use crate::dist_plan::merge_scan::{MergeScanExec, MergeScanLogicalPlan};
|
||||
use crate::dist_plan::merge_sort::{MergeSortExec, MergeSortLogicalPlan};
|
||||
use crate::dist_plan::region_pruner::ConstraintPruner;
|
||||
use crate::dist_plan::region_pruner::{ConstraintPruner, partition_comparison_matches};
|
||||
use crate::error::{CatalogSnafu, PartitionRuleManagerSnafu, TableNotFoundSnafu};
|
||||
use crate::optimizer::expr_depth;
|
||||
use crate::region_query::RegionQueryHandlerRef;
|
||||
@@ -602,16 +602,7 @@ fn simplify_metric_partition_expr(
|
||||
if !matches!(bound, Value::Null) && known.data_type() != bound.data_type() {
|
||||
return None;
|
||||
}
|
||||
let ordering = known.cmp(&bound);
|
||||
let matches = match op {
|
||||
RestrictedOp::Eq => ordering.is_eq(),
|
||||
RestrictedOp::NotEq => !ordering.is_eq(),
|
||||
RestrictedOp::Lt => ordering.is_lt(),
|
||||
RestrictedOp::LtEq => ordering.is_le(),
|
||||
RestrictedOp::Gt => ordering.is_gt(),
|
||||
RestrictedOp::GtEq => ordering.is_ge(),
|
||||
RestrictedOp::And | RestrictedOp::Or => return None,
|
||||
};
|
||||
let matches = partition_comparison_matches(&op, known.cmp(&bound))?;
|
||||
Some(Constant(matches))
|
||||
}
|
||||
_ => None,
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
|
||||
//! [`ConstraintPruner`] prunes partition info based on given expressions.
|
||||
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use ahash::{HashMap, HashSet};
|
||||
use common_telemetry::debug;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
@@ -65,7 +67,7 @@ impl ConstraintPruner {
|
||||
}
|
||||
|
||||
// Collect all partition expressions for unified normalization
|
||||
let Some(all_partition_expressions) = partitions
|
||||
let Some(mut all_partition_expressions) = partitions
|
||||
.iter()
|
||||
.map(|partition| partition.partition_expr.clone())
|
||||
.collect::<Option<Vec<_>>>()
|
||||
@@ -76,19 +78,39 @@ impl ConstraintPruner {
|
||||
return Ok(all_regions);
|
||||
};
|
||||
|
||||
// Normalize the query, derived hash constraints and route bounds together.
|
||||
let mut all_expressions = query_expressions.to_vec();
|
||||
all_expressions.extend(Self::iceberg_hash_constraints(
|
||||
let hash_equalities = Self::iceberg_hash_equalities(
|
||||
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);
|
||||
);
|
||||
let mut all_expressions = query_expressions.to_vec();
|
||||
if !Self::normalize_datatype(&mut all_expressions, &column_datatypes)
|
||||
|| !Self::normalize_datatype(&mut all_partition_expressions, &column_datatypes)
|
||||
{
|
||||
// A hash can still exclude a route even if we cannot compare its timestamp bounds.
|
||||
if hash_equalities.is_empty() {
|
||||
return Ok(all_regions);
|
||||
}
|
||||
let regions = all_regions
|
||||
.into_iter()
|
||||
.zip(&all_partition_expressions)
|
||||
.filter_map(|(region, rule)| {
|
||||
(region.region_number() == 0
|
||||
|| hash_equalities.iter().all(|eq| eq.may_match(rule)))
|
||||
.then_some(region)
|
||||
})
|
||||
.collect();
|
||||
return Ok(regions);
|
||||
}
|
||||
|
||||
// Derived comparisons already have the hash dimension's type (Int32 or NULL).
|
||||
all_expressions.extend(
|
||||
hash_equalities
|
||||
.iter()
|
||||
.map(IcebergHashEquality::as_constraint),
|
||||
);
|
||||
let partition_expr_offset = all_expressions.len();
|
||||
all_expressions.extend(all_partition_expressions);
|
||||
let collider = match Collider::new(&all_expressions) {
|
||||
Ok(collider) => collider,
|
||||
Err(err) => {
|
||||
@@ -160,11 +182,11 @@ impl ConstraintPruner {
|
||||
.any(|left| rhs.iter().any(|right| atomic_exprs_overlap(left, right)))
|
||||
}
|
||||
|
||||
fn iceberg_hash_constraints(
|
||||
scan_equalities: &[PartitionExpr],
|
||||
fn iceberg_hash_equalities<'a>(
|
||||
scan_equalities: &'a [PartitionExpr],
|
||||
partition_expressions: &[PartitionExpr],
|
||||
column_datatypes: &HashMap<String, ConcreteDataType>,
|
||||
) -> Vec<PartitionExpr> {
|
||||
) -> Vec<IcebergHashEquality<'a>> {
|
||||
if scan_equalities.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -184,7 +206,10 @@ impl ConstraintPruner {
|
||||
if !hash_columns.contains(column.as_str()) || datatype != &literal.data_type() {
|
||||
return None;
|
||||
}
|
||||
Self::iceberg_hash_constraint(column, literal)
|
||||
let Value::Int32(hash) = IcebergHash::evaluate_value(literal).ok()? else {
|
||||
return None;
|
||||
};
|
||||
Some(IcebergHashEquality { column, hash })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -201,21 +226,6 @@ impl ConstraintPruner {
|
||||
}
|
||||
}
|
||||
|
||||
fn iceberg_hash_constraint(column: &str, literal: &Value) -> Option<PartitionExpr> {
|
||||
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(
|
||||
all_expressions: &mut Vec<PartitionExpr>,
|
||||
column_datatypes: &HashMap<String, ConcreteDataType>,
|
||||
@@ -316,10 +326,72 @@ impl ConstraintPruner {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Value range and atomic overlap logic is now refactored into `partition::diff`.
|
||||
|
||||
struct IcebergHashEquality<'a> {
|
||||
column: &'a str,
|
||||
hash: i32,
|
||||
}
|
||||
|
||||
impl IcebergHashEquality<'_> {
|
||||
fn routing_values(&self) -> [Value; 2] {
|
||||
// An omitted column can route as NULL before the region fills its default.
|
||||
[Value::Int32(self.hash), Value::Null]
|
||||
}
|
||||
|
||||
fn as_constraint(&self) -> PartitionExpr {
|
||||
let dimension = Operand::IcebergHash(IcebergHash::new(self.column));
|
||||
let [literal, missing] = self.routing_values();
|
||||
PartitionExpr::new(
|
||||
Operand::Expr(dimension.clone().eq(literal)),
|
||||
RestrictedOp::Or,
|
||||
Operand::Expr(dimension.eq(missing)),
|
||||
)
|
||||
}
|
||||
|
||||
fn may_match(&self, rule: &PartitionExpr) -> bool {
|
||||
// The lower and upper bounds of a bucket must admit the same routing value.
|
||||
self.routing_values()
|
||||
.iter()
|
||||
.any(|value| self.rule_admits(rule, value))
|
||||
}
|
||||
|
||||
fn rule_admits(&self, rule: &PartitionExpr, routing_value: &Value) -> bool {
|
||||
match (rule.lhs(), rule.op(), rule.rhs()) {
|
||||
(Operand::Expr(lhs), RestrictedOp::And, Operand::Expr(rhs)) => {
|
||||
self.rule_admits(lhs, routing_value) && self.rule_admits(rhs, routing_value)
|
||||
}
|
||||
(Operand::Expr(lhs), RestrictedOp::Or, Operand::Expr(rhs)) => {
|
||||
self.rule_admits(lhs, routing_value) || self.rule_admits(rhs, routing_value)
|
||||
}
|
||||
(Operand::IcebergHash(hash), op, Operand::Value(bound))
|
||||
if hash.column() == self.column
|
||||
&& matches!(bound, Value::Int32(_) | Value::Null) =>
|
||||
{
|
||||
// Value orders NULL before every non-NULL hash, just as write routing does.
|
||||
partition_comparison_matches(op, routing_value.cmp(bound)).unwrap_or(true)
|
||||
}
|
||||
// Other dimensions and unknown bounds can satisfy this branch.
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests a scalar partition comparison after the operand types have been checked.
|
||||
pub(crate) fn partition_comparison_matches(op: &RestrictedOp, ordering: Ordering) -> Option<bool> {
|
||||
Some(match op {
|
||||
RestrictedOp::Eq => ordering.is_eq(),
|
||||
RestrictedOp::NotEq => !ordering.is_eq(),
|
||||
RestrictedOp::Lt => ordering.is_lt(),
|
||||
RestrictedOp::LtEq => ordering.is_le(),
|
||||
RestrictedOp::Gt => ordering.is_gt(),
|
||||
RestrictedOp::GtEq => ordering.is_ge(),
|
||||
RestrictedOp::And | RestrictedOp::Or => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use common_time::Timestamp;
|
||||
use datatypes::value::Value;
|
||||
use partition::PartitionRule;
|
||||
use partition::expr::{Operand, PartitionExpr, RestrictedOp, col};
|
||||
@@ -426,6 +498,47 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hash_fallback_checks_each_routing_value_against_the_whole_rule() {
|
||||
let cutoff = Value::Timestamp(Timestamp::new_millisecond(100));
|
||||
let column_types = HashMap::from_iter([
|
||||
("ts".to_string(), cutoff.data_type()),
|
||||
("host".to_string(), ConcreteDataType::string_datatype()),
|
||||
]);
|
||||
let host_eq = [col("host").eq(Value::from("a"))];
|
||||
let keeps = |id, rule, scan_equalities: &[PartitionExpr]| {
|
||||
let region = create_test_partition_info(id, Some(rule));
|
||||
ConstraintPruner::prune_regions_with_scan_equalities(
|
||||
&host_eq,
|
||||
std::slice::from_ref(®ion),
|
||||
column_types.clone(),
|
||||
scan_equalities,
|
||||
)
|
||||
.unwrap()
|
||||
.contains(®ion.id)
|
||||
};
|
||||
|
||||
// The hash of 'a' is above 100, while an omitted key routes as NULL, below zero.
|
||||
let hash = Operand::IcebergHash(IcebergHash::new("host"));
|
||||
let above = hash.clone().gt_eq(Value::Int32(0));
|
||||
let below = hash.lt(Value::Int32(100));
|
||||
let middle = above.clone().and(below.clone());
|
||||
let before = col("ts").lt(cutoff);
|
||||
let and_rule = before.clone().and(middle.clone());
|
||||
let or_rule = PartitionExpr::new(
|
||||
Operand::Expr(before.clone()),
|
||||
RestrictedOp::Or,
|
||||
Operand::Expr(middle),
|
||||
);
|
||||
|
||||
assert!(keeps(1, before.clone().and(above), &host_eq)); // Literal route.
|
||||
assert!(keeps(1, before.and(below), &host_eq)); // NULL route.
|
||||
assert!(!keeps(1, and_rule.clone(), &host_eq));
|
||||
assert!(keeps(1, or_rule, &host_eq)); // Time alone can match.
|
||||
assert!(keeps(0, and_rule.clone(), &host_eq)); // Unmatched writes.
|
||||
assert!(keeps(1, and_rule, &[])); // No scan-local equality.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hash_equality_keeps_null_and_unmatched_write_destinations() {
|
||||
let hash = Operand::IcebergHash(IcebergHash::new("host"));
|
||||
@@ -494,7 +607,7 @@ mod tests {
|
||||
let equalities = std::slice::from_ref(&equality);
|
||||
// Overlap ignores dimensions absent from the route, so also check the inference.
|
||||
assert!(
|
||||
ConstraintPruner::iceberg_hash_constraints(
|
||||
ConstraintPruner::iceberg_hash_equalities(
|
||||
equalities,
|
||||
&partition_expressions,
|
||||
&column_datatypes,
|
||||
|
||||
@@ -181,6 +181,45 @@ DROP TABLE hash_function_rules;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- The same hash bucket is needed on each side of the timestamp boundary.
|
||||
CREATE TABLE hash_equality_time_ranges (
|
||||
host STRING,
|
||||
ts TIMESTAMP TIME INDEX,
|
||||
PRIMARY KEY (host)
|
||||
)
|
||||
PARTITION ON COLUMNS (ts, host) (
|
||||
ts < '2024-01-02 00:00:00' AND iceberg_hash(host) < 0,
|
||||
ts < '2024-01-02 00:00:00' AND iceberg_hash(host) >= 0,
|
||||
ts >= '2024-01-02 00:00:00' AND iceberg_hash(host) < 0,
|
||||
ts >= '2024-01-02 00:00:00' AND iceberg_hash(host) >= 0
|
||||
);
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
INSERT INTO hash_equality_time_ranges VALUES
|
||||
('b', '2024-01-01 00:00:00'), ('b', '2024-01-02 00:00:00'), ('a', '2024-01-02 00:00:00');
|
||||
|
||||
Affected Rows: 3
|
||||
|
||||
-- SQLNESS REPLACE (?s)^.*?(MergeScanExec:\speers=\[[^\]]*\]).*$ $1
|
||||
-- SQLNESS REPLACE \d+\(\d+,\s+\d+\) REGION
|
||||
EXPLAIN SELECT ts FROM hash_equality_time_ranges WHERE host = 'b';
|
||||
|
||||
MergeScanExec: peers=[REGION, REGION, ]
|
||||
|
||||
SELECT ts FROM hash_equality_time_ranges WHERE host = 'b' ORDER BY ts;
|
||||
|
||||
+---------------------+
|
||||
| ts |
|
||||
+---------------------+
|
||||
| 2024-01-01T00:00:00 |
|
||||
| 2024-01-02T00:00:00 |
|
||||
+---------------------+
|
||||
|
||||
DROP TABLE hash_equality_time_ranges;
|
||||
|
||||
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 (
|
||||
|
||||
@@ -78,6 +78,30 @@ SELECT "host-name", v FROM hash_function_rules WHERE 'b' = "host-name";
|
||||
|
||||
DROP TABLE hash_function_rules;
|
||||
|
||||
-- The same hash bucket is needed on each side of the timestamp boundary.
|
||||
CREATE TABLE hash_equality_time_ranges (
|
||||
host STRING,
|
||||
ts TIMESTAMP TIME INDEX,
|
||||
PRIMARY KEY (host)
|
||||
)
|
||||
PARTITION ON COLUMNS (ts, host) (
|
||||
ts < '2024-01-02 00:00:00' AND iceberg_hash(host) < 0,
|
||||
ts < '2024-01-02 00:00:00' AND iceberg_hash(host) >= 0,
|
||||
ts >= '2024-01-02 00:00:00' AND iceberg_hash(host) < 0,
|
||||
ts >= '2024-01-02 00:00:00' AND iceberg_hash(host) >= 0
|
||||
);
|
||||
|
||||
INSERT INTO hash_equality_time_ranges VALUES
|
||||
('b', '2024-01-01 00:00:00'), ('b', '2024-01-02 00:00:00'), ('a', '2024-01-02 00:00:00');
|
||||
|
||||
-- SQLNESS REPLACE (?s)^.*?(MergeScanExec:\speers=\[[^\]]*\]).*$ $1
|
||||
-- SQLNESS REPLACE \d+\(\d+,\s+\d+\) REGION
|
||||
EXPLAIN SELECT ts FROM hash_equality_time_ranges WHERE host = 'b';
|
||||
|
||||
SELECT ts FROM hash_equality_time_ranges WHERE host = 'b' ORDER BY ts;
|
||||
|
||||
DROP TABLE hash_equality_time_ranges;
|
||||
|
||||
-- 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 (
|
||||
|
||||
Reference in New Issue
Block a user