mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-26 12:44:10 +00:00
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 <killme2008@gmail.com> * test(mito2): cover file pruning by primary key range end to end Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * 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 <killme2008@gmail.com> * 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 <killme2008@gmail.com> * test: check file pruning by primary key range with EXPLAIN ANALYZE Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
@@ -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<FileLevelPruningStats> {
|
||||
fn try_file_level_pruning_stats<'a>(
|
||||
&'a self,
|
||||
file: &'a FileHandle,
|
||||
) -> Option<FileLevelPruningStats<'a>> {
|
||||
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<FirstPrimaryKeyStats<'a>> {
|
||||
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<ArrayRef> {
|
||||
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<FileRangeBuilder> {
|
||||
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<FirstPrimaryKeyStats<'a>>,
|
||||
}
|
||||
|
||||
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<Option<(ArrayRef, ArrayRef)>>,
|
||||
}
|
||||
|
||||
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<ArrayRef> {
|
||||
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::<Field>::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));
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user