From 2effff48d5fbea48ddae79c28b36aec2a31094de Mon Sep 17 00:00:00 2001 From: dennis zhuang Date: Mon, 23 Nov 2026 08:04:54 +0000 Subject: [PATCH] perf(mito2): prune files by their primary key range before reading footers (#10564) * perf(mito2): prune files by their primary key range before reading footers File-level pruning used only the manifest time range, so a scan read the footer of every file in the time range even when the file's primary key range excludes the predicate. The file-level pruning statistics now include the min and max of the first primary key column, decoded from FileMeta's primary key range, so such files are skipped without a footer read. For metric engine physical regions the first column is the table id. Signed-off-by: Dennis Zhuang * test(mito2): cover file pruning by primary key range end to end Signed-off-by: Dennis Zhuang * perf(mito2): decode the file primary key range only when pruning uses it Predicates on the time index or fields never ask for the first primary key column, so they no longer build a codec and two arrays per file. Signed-off-by: Dennis Zhuang * fix(mito2): prune files by primary key ranges loaded from footers Region open can fill a file handle's key range from the SST footer when the manifest has none. Let the handle decide whether bounds are known, so those files are pruned too. Signed-off-by: Dennis Zhuang * test: check file pruning by primary key range with EXPLAIN ANALYZE Signed-off-by: Dennis Zhuang --------- Signed-off-by: Dennis Zhuang --- src/mito2/src/read/scan_region.rs | 162 ++++++++++++++++-- src/mito2/src/read/scan_util.rs | 2 +- src/mito2/src/sst/parquet/reader.rs | 2 +- .../standalone/common/select/prune.result | 135 +++++++++++++++ .../cases/standalone/common/select/prune.sql | 49 ++++++ 5 files changed, 335 insertions(+), 15 deletions(-) diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index e908560ca09..389ebfb919f 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -41,10 +41,11 @@ use datatypes::prelude::ConcreteDataType; use datatypes::types::json_type::JsonNativeType; use datatypes::value::timestamp_to_scalar_value; use futures::StreamExt; +use mito_codec::row_converter::{SortField, build_primary_key_codec_with_fields}; use partition::expr::PartitionExpr; use smallvec::SmallVec; use snafu::{OptionExt, ResultExt, ensure}; -use store_api::metadata::{RegionMetadata, RegionMetadataRef}; +use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataRef}; use store_api::region_engine::{PartitionRange, RegionScannerRef}; use store_api::storage::{ ColumnId, RegionId, ScanRequest, SequenceNumber, SequenceRange, TimeSeriesDistribution, @@ -1523,11 +1524,14 @@ impl ScanInput { } } - /// Tries to build file-level pruning statistics using only the [FileHandle]'s manifest-level - /// time range, without reading any parquet metadata. + /// Tries to build file-level pruning statistics from the [FileHandle]'s time range and + /// primary key range, without reading any parquet metadata. /// /// Returns `None` if timestamp unit conversion overflows (conservative: keep the file). - fn try_file_level_pruning_stats(&self, file: &FileHandle) -> Option { + fn try_file_level_pruning_stats<'a>( + &'a self, + file: &'a FileHandle, + ) -> Option> { let (ts_min, ts_max) = file.time_range(); let time_index = self.mapper.metadata().time_index_column(); let time_index_unit = time_index.column_schema.data_type.as_timestamp()?.unit(); @@ -1541,11 +1545,56 @@ impl ScanInput { min_scalar: timestamp_to_scalar_value(time_index_unit, Some(min_ts.value())), max_scalar: timestamp_to_scalar_value(time_index_unit, Some(max_ts.value())), time_index_col_name: time_index.column_schema.name.clone(), + first_primary_key: self.first_primary_key_stats(file), }) } + /// Returns the first primary key column of `file`. Its range is decoded only when pruning + /// asks for the column. + fn first_primary_key_stats<'a>( + &'a self, + file: &'a FileHandle, + ) -> Option> { + let metadata = self.mapper.metadata(); + let column = metadata.column_by_id(*metadata.primary_key.first()?)?; + Some(FirstPrimaryKeyStats { + input: self, + file, + column, + range: OnceLock::new(), + }) + } + + /// Decodes the min and max of `column`, the first primary key column, from the primary key + /// range of `file`. + fn decode_first_primary_key_range( + &self, + file: &FileHandle, + column: &ColumnMetadata, + ) -> Option<(ArrayRef, ArrayRef)> { + use datatypes::data_type::DataType as _; + + let metadata = self.mapper.metadata(); + let (min, max) = file.primary_key_range(self.primary_key_mapper())?; + let codec = build_primary_key_codec_with_fields( + metadata.primary_key_encoding, + std::iter::once(( + column.column_id, + SortField::new(column.column_schema.data_type.clone()), + )), + ); + let to_array = |bytes: &[u8]| -> Option { + let value = codec.decode_leftmost(bytes).ok()??; + let mut builder = column.column_schema.data_type.create_mutable_vector(1); + builder.try_push_value_ref(&value.as_value_ref()).ok()?; + Some(builder.to_vector().to_arrow_array()) + }; + Some((to_array(&min)?, to_array(&max)?)) + } + /// Checks whether a file can be definitively pruned using only its manifest-level - /// time range and the current predicate, without reading any parquet metadata. + /// time and primary key ranges and the current predicate, without reading any parquet + /// metadata. /// /// Returns `true` if [PruningStatistics] proves the file cannot contain matching rows. #[inline] @@ -1588,7 +1637,7 @@ impl ScanInput { ) -> Result { let predicate = self.predicate_for_file(file); - // Early file-level pruning using manifest time range before any parquet metadata access. + // Early file-level pruning using manifest ranges before any parquet metadata access. if self.manifest_prunes_file(file, predicate.as_ref()) { reader_metrics.filter_metrics.files_time_range_pruned += 1; return Ok(FileRangeBuilder::default()); @@ -1870,24 +1919,50 @@ impl ScanInput { } } -/// Lightweight [PruningStatistics] that only uses the file-level time range from manifest -/// metadata, avoiding any parquet metadata reads. Used for early file-level pruning before -/// accessing row-group-level statistics. -pub(crate) struct FileLevelPruningStats { +/// Lightweight [PruningStatistics] that only uses the time range and first primary key range +/// known by the file handle, avoiding any parquet metadata reads. Used for early file-level +/// pruning before accessing row-group-level statistics. +pub(crate) struct FileLevelPruningStats<'a> { /// Scalar value for the file's minimum timestamp in the time index column's unit. pub(crate) min_scalar: ScalarValue, /// Scalar value for the file's maximum timestamp in the time index column's unit. pub(crate) max_scalar: ScalarValue, /// Name of the time index column. pub(crate) time_index_col_name: String, + /// First primary key column; `None` when the region has no primary key. + pub(crate) first_primary_key: Option>, } -impl PruningStatistics for FileLevelPruningStats { +/// Min and max of the first primary key column of a file, decoded from the file's primary key +/// range on first use. Predicates that do not reference the column skip the decoding. +pub(crate) struct FirstPrimaryKeyStats<'a> { + input: &'a ScanInput, + file: &'a FileHandle, + column: &'a ColumnMetadata, + range: OnceLock>, +} + +impl FirstPrimaryKeyStats<'_> { + fn range_of(&self, column: &Column) -> Option<&(ArrayRef, ArrayRef)> { + if column.name != self.column.column_schema.name { + return None; + } + self.range + .get_or_init(|| { + self.input + .decode_first_primary_key_range(self.file, self.column) + }) + .as_ref() + } +} + +impl PruningStatistics for FileLevelPruningStats<'_> { fn min_values(&self, column: &Column) -> Option { if column.name == self.time_index_col_name { ScalarValue::iter_to_array(std::iter::once(self.min_scalar.clone())).ok() } else { - None + let (min, _) = self.first_primary_key.as_ref()?.range_of(column)?; + Some(min.clone()) } } @@ -1895,7 +1970,8 @@ impl PruningStatistics for FileLevelPruningStats { if column.name == self.time_index_col_name { ScalarValue::iter_to_array(std::iter::once(self.max_scalar.clone())).ok() } else { - None + let (_, max) = self.first_primary_key.as_ref()?.range_of(column)?; + Some(max.clone()) } } @@ -3209,6 +3285,7 @@ mod tests { min_scalar: ScalarValue::TimestampMillisecond(Some(0), None), max_scalar: ScalarValue::TimestampMillisecond(Some(500), None), time_index_col_name: ts_col_name.to_string(), + first_primary_key: None, }; assert_eq!( vec![false], @@ -3220,6 +3297,7 @@ mod tests { min_scalar: ScalarValue::TimestampMillisecond(Some(0), None), max_scalar: ScalarValue::TimestampMillisecond(Some(2000), None), time_index_col_name: ts_col_name.to_string(), + first_primary_key: None, }; assert_eq!( vec![true], @@ -3236,6 +3314,7 @@ mod tests { min_scalar: ScalarValue::TimestampMillisecond(Some(0), None), max_scalar: ScalarValue::TimestampMillisecond(Some(500), None), time_index_col_name: "ts".to_string(), + first_primary_key: None, }; let arrow_schema = Arc::new(ArrowSchema::new(Vec::::new())); assert_eq!( @@ -3296,6 +3375,7 @@ mod tests { min_scalar: ScalarValue::TimestampMillisecond(Some(0), None), max_scalar: ScalarValue::TimestampMillisecond(Some(1000), None), time_index_col_name: ts_col_name.to_string(), + first_primary_key: None, }; assert_eq!( @@ -3333,6 +3413,62 @@ mod tests { assert!(ranges.is_empty()); } + #[tokio::test] + async fn test_manifest_pruning_uses_first_primary_key_range() { + let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false)); + let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap(); + let predicate_group = PredicateGroup::new( + metadata.as_ref(), + &[datafusion_expr::col("k0").eq(datafusion_expr::lit("b"))], + ) + .unwrap(); + let input = ScanInput::builder(SchedulerEnv::new().await.access_layer.clone(), mapper) + .with_predicate(predicate_group) + .build(); + use mito_codec::row_converter::PrimaryKeyCodec as _; + + let key = |k0: &str| { + let mut bytes = Vec::new(); + mito_codec::row_converter::DensePrimaryKeyCodec::new(&metadata) + .encode_values( + &[ + (0, datatypes::value::Value::from(k0)), + (1, datatypes::value::Value::from(1u32)), + ], + &mut bytes, + ) + .unwrap(); + bytes::Bytes::from(bytes) + }; + let file = |range: Option<(&str, &str)>| { + FileHandle::new( + FileMeta { + region_id: metadata.region_id, + time_range: ( + Timestamp::new_millisecond(0), + Timestamp::new_millisecond(1000), + ), + primary_key_min: range.map(|(min, _)| key(min)), + primary_key_max: range.map(|(_, max)| key(max)), + ..Default::default() + }, + Arc::new(crate::sst::file_purger::NoopFilePurger), + ) + }; + + // Files whose first-tag range excludes `k0 = 'b'` are pruned before reading their footer. + assert!(input.can_manifest_prune_file(&file(Some(("a", "a"))))); + assert!(input.can_manifest_prune_file(&file(Some(("c", "d"))))); + assert!(!input.can_manifest_prune_file(&file(Some(("a", "c"))))); + assert!(!input.can_manifest_prune_file(&file(Some(("b", "b"))))); + // Files without a recorded range are kept. + assert!(!input.can_manifest_prune_file(&file(None))); + // A range hydrated from the footer when the region opens also prunes the file. + let hydrated = file(None); + hydrated.set_primary_key_range((key("c"), key("d"))); + assert!(input.can_manifest_prune_file(&hydrated)); + } + #[tokio::test] async fn test_manifest_pruning_observes_dynamic_filter_update() { let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false)); diff --git a/src/mito2/src/read/scan_util.rs b/src/mito2/src/read/scan_util.rs index ca418f1b721..0ddc0565c52 100644 --- a/src/mito2/src/read/scan_util.rs +++ b/src/mito2/src/read/scan_util.rs @@ -195,7 +195,7 @@ pub(crate) struct ScanMetricsSet { pruner_cache_miss: usize, /// Duration spent waiting for pruner to build file ranges. pruner_prune_cost: Duration, - /// Number of files filtered by manifest time-range pruning. + /// Number of files pruned by their manifest time range or primary key range. files_time_range_pruned: usize, /// Number of record batches read from SST. num_sst_record_batches: usize, diff --git a/src/mito2/src/sst/parquet/reader.rs b/src/mito2/src/sst/parquet/reader.rs index a5feb33ca85..18cd65cf5d0 100644 --- a/src/mito2/src/sst/parquet/reader.rs +++ b/src/mito2/src/sst/parquet/reader.rs @@ -1565,7 +1565,7 @@ pub(crate) struct ReaderFilterMetrics { pub(crate) pruner_cache_miss: usize, /// Duration spent waiting for pruner to build file ranges. pub(crate) pruner_prune_cost: Duration, - /// Number of files filtered by manifest time-range pruning. + /// Number of files pruned by their manifest time range or primary key range. pub(crate) files_time_range_pruned: usize, } diff --git a/tests/cases/standalone/common/select/prune.result b/tests/cases/standalone/common/select/prune.result index 36b636a514b..7cfc679d269 100644 --- a/tests/cases/standalone/common/select/prune.result +++ b/tests/cases/standalone/common/select/prune.result @@ -197,3 +197,138 @@ DROP TABLE test_time_filter; Affected Rows: 0 +-- Files whose primary key range excludes the predicate are pruned before reading them. +CREATE TABLE pk_range_prune(ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING, idc STRING, PRIMARY KEY(host, idc)); + +Affected Rows: 0 + +INSERT INTO pk_range_prune VALUES (1, 1, 'a', 'idc1'), (2, 2, 'b', 'idc2'); + +Affected Rows: 2 + +ADMIN flush_table('pk_range_prune'); + ++-------------------------------------+ +| ADMIN flush_table('pk_range_prune') | ++-------------------------------------+ +| 0 | ++-------------------------------------+ + +INSERT INTO pk_range_prune VALUES (1, 3, 'c', 'idc1'), (2, 4, 'd', 'idc2'); + +Affected Rows: 2 + +ADMIN flush_table('pk_range_prune'); + ++-------------------------------------+ +| ADMIN flush_table('pk_range_prune') | ++-------------------------------------+ +| 0 | ++-------------------------------------+ + +-- SQLNESS REPLACE (?s)^.*("files_time_range_pruned":\d+).*$ $1 +EXPLAIN ANALYZE VERBOSE SELECT * FROM pk_range_prune WHERE host = 'c'; + +"files_time_range_pruned":1 + +SELECT * FROM pk_range_prune WHERE host = 'c'; + ++-------------------------+-----+------+------+ +| ts | val | host | idc | ++-------------------------+-----+------+------+ +| 1970-01-01T00:00:00.001 | 3.0 | c | idc1 | ++-------------------------+-----+------+------+ + +SELECT * FROM pk_range_prune WHERE host >= 'b' ORDER BY host; + ++-------------------------+-----+------+------+ +| ts | val | host | idc | ++-------------------------+-----+------+------+ +| 1970-01-01T00:00:00.002 | 2.0 | b | idc2 | +| 1970-01-01T00:00:00.001 | 3.0 | c | idc1 | +| 1970-01-01T00:00:00.002 | 4.0 | d | idc2 | ++-------------------------+-----+------+------+ + +SELECT * FROM pk_range_prune WHERE host < 'b'; + ++-------------------------+-----+------+------+ +| ts | val | host | idc | ++-------------------------+-----+------+------+ +| 1970-01-01T00:00:00.001 | 1.0 | a | idc1 | ++-------------------------+-----+------+------+ + +DROP TABLE pk_range_prune; + +Affected Rows: 0 + +CREATE TABLE pk_range_phy (ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE = metric WITH ("physical_metric_table" = ""); + +Affected Rows: 0 + +CREATE TABLE pk_range_t1 (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) ENGINE = metric WITH ("on_physical_table" = "pk_range_phy"); + +Affected Rows: 0 + +CREATE TABLE pk_range_t2 (ts TIMESTAMP TIME INDEX, val DOUBLE, job STRING PRIMARY KEY) ENGINE = metric WITH ("on_physical_table" = "pk_range_phy"); + +Affected Rows: 0 + +INSERT INTO pk_range_t1 VALUES ('host1', 0, 1), ('host2', 1, 2); + +Affected Rows: 2 + +ADMIN flush_table('pk_range_phy'); + ++-----------------------------------+ +| ADMIN flush_table('pk_range_phy') | ++-----------------------------------+ +| 0 | ++-----------------------------------+ + +INSERT INTO pk_range_t2 VALUES ('job1', 0, 3), ('job2', 1, 4); + +Affected Rows: 2 + +ADMIN flush_table('pk_range_phy'); + ++-----------------------------------+ +| ADMIN flush_table('pk_range_phy') | ++-----------------------------------+ +| 0 | ++-----------------------------------+ + +-- SQLNESS REPLACE (?s)^.*("files_time_range_pruned":\d+).*$ $1 +EXPLAIN ANALYZE VERBOSE SELECT * FROM pk_range_t1; + +"files_time_range_pruned":1 + +SELECT * FROM pk_range_t1 ORDER BY host; + ++-------+-------------------------+-----+ +| host | ts | val | ++-------+-------------------------+-----+ +| host1 | 1970-01-01T00:00:00 | 1.0 | +| host2 | 1970-01-01T00:00:00.001 | 2.0 | ++-------+-------------------------+-----+ + +SELECT * FROM pk_range_t2 ORDER BY job; + ++------+-------------------------+-----+ +| job | ts | val | ++------+-------------------------+-----+ +| job1 | 1970-01-01T00:00:00 | 3.0 | +| job2 | 1970-01-01T00:00:00.001 | 4.0 | ++------+-------------------------+-----+ + +DROP TABLE pk_range_t1; + +Affected Rows: 0 + +DROP TABLE pk_range_t2; + +Affected Rows: 0 + +DROP TABLE pk_range_phy; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/select/prune.sql b/tests/cases/standalone/common/select/prune.sql index 7a938e9c43e..cf229a5be93 100644 --- a/tests/cases/standalone/common/select/prune.sql +++ b/tests/cases/standalone/common/select/prune.sql @@ -65,3 +65,52 @@ SELECT host FROM test_time_filter WHERE greptime_timestamp > '2026-01-07 00:00:0 SELECT host, greptime_timestamp FROM test_time_filter WHERE greptime_timestamp > '2026-01-07 00:00:00'; DROP TABLE test_time_filter; + +-- Files whose primary key range excludes the predicate are pruned before reading them. +CREATE TABLE pk_range_prune(ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING, idc STRING, PRIMARY KEY(host, idc)); + +INSERT INTO pk_range_prune VALUES (1, 1, 'a', 'idc1'), (2, 2, 'b', 'idc2'); + +ADMIN flush_table('pk_range_prune'); + +INSERT INTO pk_range_prune VALUES (1, 3, 'c', 'idc1'), (2, 4, 'd', 'idc2'); + +ADMIN flush_table('pk_range_prune'); + +-- SQLNESS REPLACE (?s)^.*("files_time_range_pruned":\d+).*$ $1 +EXPLAIN ANALYZE VERBOSE SELECT * FROM pk_range_prune WHERE host = 'c'; + +SELECT * FROM pk_range_prune WHERE host = 'c'; + +SELECT * FROM pk_range_prune WHERE host >= 'b' ORDER BY host; + +SELECT * FROM pk_range_prune WHERE host < 'b'; + +DROP TABLE pk_range_prune; + +CREATE TABLE pk_range_phy (ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE = metric WITH ("physical_metric_table" = ""); + +CREATE TABLE pk_range_t1 (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) ENGINE = metric WITH ("on_physical_table" = "pk_range_phy"); + +CREATE TABLE pk_range_t2 (ts TIMESTAMP TIME INDEX, val DOUBLE, job STRING PRIMARY KEY) ENGINE = metric WITH ("on_physical_table" = "pk_range_phy"); + +INSERT INTO pk_range_t1 VALUES ('host1', 0, 1), ('host2', 1, 2); + +ADMIN flush_table('pk_range_phy'); + +INSERT INTO pk_range_t2 VALUES ('job1', 0, 3), ('job2', 1, 4); + +ADMIN flush_table('pk_range_phy'); + +-- SQLNESS REPLACE (?s)^.*("files_time_range_pruned":\d+).*$ $1 +EXPLAIN ANALYZE VERBOSE SELECT * FROM pk_range_t1; + +SELECT * FROM pk_range_t1 ORDER BY host; + +SELECT * FROM pk_range_t2 ORDER BY job; + +DROP TABLE pk_range_t1; + +DROP TABLE pk_range_t2; + +DROP TABLE pk_range_phy;