fix(mito2): keep SST replacements coherent with metadata counts

Signed-off-by: aumnertic <aumnertic@gmail.com>
This commit is contained in:
aumnertic
2026-11-26 00:22:42 -05:00
parent 1b5fa8d082
commit 42517b37e3
7 changed files with 440 additions and 386 deletions
+18 -15
View File
@@ -8,7 +8,7 @@ rewriting, benchmarking, and replacing Parquet SST files:
properties.
- `parquetbench`: benchmark reads from a local GreptimeDB SST or an SST in a
configured object store.
- `sst-replace`: replace an existing Mito SST object and update its manifest
- `sst-replace`: install a replacement Mito SST and update its manifest
metadata.
These are development and recovery tools, not stable user-facing interfaces.
@@ -183,17 +183,19 @@ iteration from profiling.
## Replace an existing region SST
> **Warning:** `sst-replace` mutates both an SST object and its region manifest.
> Stop the datanode that owns the region and back up the target SST and manifest
> before using `--confirm`. The SST write happens before the manifest update, so
> an interrupted or failed operation may require restoring the backup.
Stop the datanode that owns the region and back up its manifest before using
`--confirm`. The command writes the replacement under a fresh file ID, then
publishes one manifest edit that swaps the old ID for the new one. Readers of
the previous manifest can still use the original object.
`sst-replace` replaces the contents of an existing SST file ID. It does not add
a new file ID to a region. The command requires the replacement to have the same
row count and row-group count recorded in the manifest when those manifest
values are nonzero. It does not validate schema or row contents. The replacement
is loaded into memory in full, so ensure the machine has enough memory for the
SST.
The target must be a locally owned, unshared Parquet SST. The replacement must
belong to the same source region and time index and
match the manifest row and row-group counts when those counts are known.
Its footer must provide exact time bounds. Missing primary-key bounds remain
unknown. Index sidecars belong to the original file ID. When the manifest has
a sequence fence or preserves per-row sequences, the command compares the
sequence column of both files before retaining those guarantees. Allow memory
for both SSTs during validation.
Start with the default dry run using a local replacement file:
@@ -237,10 +239,11 @@ $GREPTIME datanode sst-replace \
--confirm
```
The confirmed operation overwrites the existing SST object, recalculates file
size and row-group statistics, and appends a manifest edit for the existing file
ID. Restart the datanode and validate queries against the region before removing
the backup.
The confirmed operation prints the new SST path and manifest version. Restart
the datanode and validate queries against the region before removing the
backup. To repair bounds or stale cache entries left by an older in-place
replacement, use its current object-store path as `--replacement-object` and
its current manifest ID as `--file-id`.
## Recommended rewrite and replacement workflow
+1 -1
View File
@@ -128,7 +128,7 @@ common-version.workspace = true
datanode = { workspace = true, features = ["testing"] }
file-engine.workspace = true
metric-engine.workspace = true
mito2.workspace = true
mito2 = { workspace = true, features = ["test"] }
serde.workspace = true
similar-asserts.workspace = true
temp-env = "0.3"
+257 -25
View File
@@ -19,18 +19,25 @@ use colored::Colorize;
use mito2::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList};
use mito2::manifest::manager::{RegionManifestManager, RegionManifestOptions};
use mito2::region::ManifestStats;
use mito2::sst::file::RegionFileId;
use mito2::sst::file::{FileFormat, FileMeta};
use mito2::sst::file_metadata::FileMetadataInterner;
use mito2::sst::location::{region_dir_from_table_dir, sst_file_path};
use mito2::sst::location::region_dir_from_table_dir;
use mito2::sst::parquet::max_row_group_decoded_size;
use object_store::ObjectStore;
use mito2::sst::parquet::metadata::{extract_primary_key_range, extract_time_range};
use object_store::{Buffer, ObjectStore};
use parquet::file::FOOTER_SIZE;
use parquet::file::metadata::{FooterTail, ParquetMetaDataReader};
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::record::RowAccessor;
use parquet::record::reader::RowIter;
use parquet::schema::types::Type;
use store_api::region_request::PathType;
use store_api::storage::FileId;
use store_api::storage::consts::SEQUENCE_COLUMN_NAME;
use crate::datanode::tool_util::{
build_object_store, max_row_group_uncompressed_size, parse_config, parse_file_id,
parse_path_type, parse_region_id,
build_object_store, extract_region_metadata, max_row_group_uncompressed_size, parse_config,
parse_file_id, parse_path_type, parse_region_id,
};
use crate::error;
@@ -65,7 +72,7 @@ pub struct SstReplaceCommand {
#[clap(long, default_value = "auto")]
path_type: String,
/// Actually overwrite the SST object and append a manifest delta.
/// Write the replacement under a new file ID and publish the manifest edit.
#[clap(long, default_value_t = false)]
confirm: bool,
@@ -148,8 +155,16 @@ impl SstReplaceCommand {
.fail();
};
let region_file_id = RegionFileId::new(old_file.region_id, old_file.file_id);
let target_path = sst_file_path(&self.table_dir, region_file_id, path_type);
if old_file.format != FileFormat::Parquet
|| old_file.region_id != region_id
|| old_file.level == mito2::sst::file::LEVEL_SHARED
{
return error::IllegalConfigSnafu {
msg: format!("file {file_id} must be a locally owned, unshared Parquet SST"),
}
.fail();
}
let target_path = old_file.file_path(&self.table_dir, path_type);
let target_stat = object_store.stat(&target_path).await.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("stat target SST {} failed: {e}", target_path),
@@ -168,12 +183,60 @@ impl SstReplaceCommand {
let new_num_row_groups = parquet_meta.num_row_groups() as u64;
validate_replacement(&old_file, new_num_rows, new_num_row_groups)?;
let mut new_file = old_file.as_ref().clone();
new_file.file_size = new_file_size;
new_file.num_rows = new_num_rows;
new_file.num_row_groups = new_num_row_groups;
new_file.max_row_group_uncompressed_size = max_row_group_uncompressed_size(&parquet_meta);
new_file.max_row_group_decoded_size = max_row_group_decoded_size(&parquet_meta);
let source = extract_region_metadata("replacement SST", &parquet_meta)?;
let time_index = source.time_index_column();
let manifest = manifest_manager.manifest();
if source.region_id != old_file.region_id
|| time_index.column_id != manifest.metadata.time_index_column().column_id
{
return error::IllegalConfigSnafu {
msg: "replacement region or time index differs from the target".to_string(),
}
.fail();
}
let time_range = extract_time_range(&parquet_meta, time_index).ok_or_else(|| {
error::IllegalConfigSnafu {
msg: "replacement has no exact time-index bounds".to_string(),
}
.build()
})?;
let replacement_bytes = Buffer::from(replacement_bytes);
if old_file.sequence.is_some() || old_file.preserve_row_sequence {
// The edit retains the original sequence fence and per-row trust.
let original = object_store.read(&target_path).await.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("read target SST {target_path}: {e}"),
}
.build()
})?;
validate_sequences(original, replacement_bytes.clone()).map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("validate replacement sequences: {e}"),
}
.build()
})?;
}
let (primary_key_min, primary_key_max) =
extract_primary_key_range(&parquet_meta, &source).unzip();
// A new identity isolates data, index and footer caches, including on restart.
// A replacement has no index sidecar, series count or proven partition scope.
let new_file = FileMeta {
file_id: FileId::random(),
region_id: old_file.region_id,
level: old_file.level,
sequence: old_file.sequence,
preserve_row_sequence: old_file.preserve_row_sequence,
time_range,
primary_key_min,
primary_key_max,
file_size: new_file_size,
num_rows: new_num_rows,
num_row_groups: new_num_row_groups,
max_row_group_uncompressed_size: max_row_group_uncompressed_size(&parquet_meta),
max_row_group_decoded_size: max_row_group_decoded_size(&parquet_meta),
..Default::default()
};
let replacement_path = new_file.file_path(&self.table_dir, path_type);
println!("{} Region: {}", "[ok]".green(), region_id);
println!("{} Target SST: {}", "[ok]".green(), target_path.cyan());
@@ -192,30 +255,25 @@ impl SstReplaceCommand {
if !self.confirm {
println!(
"{} Dry run only. Re-run with --confirm to overwrite the SST and update the manifest.",
"{} Dry run only. Re-run with --confirm to publish the replacement.",
"[dry-run]".yellow()
);
return Ok(());
}
object_store
.write(&target_path, replacement_bytes)
.write(&replacement_path, replacement_bytes)
.await
.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("write replacement SST {} failed: {e}", target_path),
msg: format!("write replacement SST {} failed: {e}", replacement_path),
}
.build()
})?;
let edit = RegionEdit {
files_to_add: vec![new_file],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
files_to_remove: vec![old_file.as_ref().clone()],
..Default::default()
};
let version = manifest_manager
@@ -226,13 +284,15 @@ impl SstReplaceCommand {
.await
.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("update manifest failed: {e:?}"),
msg: format!(
"update manifest for replacement {replacement_path} failed: {e:?}"
),
}
.build()
})?;
println!(
"{} Replacement committed, manifest version {}",
"{} Replacement committed at {replacement_path}, manifest version {}",
"[ok]".green(),
version
);
@@ -283,6 +343,39 @@ async fn load_replacement_bytes(
}
}
// Compare only the sequence column. Physical row-group boundaries and encodings
// may change in a layout rewrite without changing logical sequences.
fn validate_sequences(original: Buffer, replacement: Buffer) -> parquet::errors::Result<()> {
fn sequences(bytes: Buffer) -> parquet::errors::Result<RowIter<'static>> {
let reader = SerializedFileReader::new(bytes.to_bytes())?;
let schema = reader.metadata().file_metadata().schema();
let column = schema
.get_fields()
.iter()
.find(|field| field.name() == SEQUENCE_COLUMN_NAME)
.ok_or_else(|| {
parquet::errors::ParquetError::General("missing SST sequence column".into())
})?;
let projection = Type::group_type_builder(schema.name())
.with_fields(vec![column.clone()])
.build()?;
RowIter::from_file_into(Box::new(reader)).project(Some(projection))
}
let mut old = sequences(original)?;
let mut new = sequences(replacement)?;
loop {
match (old.next().transpose()?, new.next().transpose()?) {
(Some(old), Some(new)) if old.get_ulong(0)? == new.get_ulong(0)? => {}
(None, None) => return Ok(()),
_ => {
return Err(parquet::errors::ParquetError::General(
"replacement changes the target's row sequences".into(),
));
}
}
}
}
fn validate_replacement(
old_file: &mito2::sst::file::FileMeta,
new_num_rows: u64,
@@ -353,6 +446,145 @@ fn path_type_name(path_type: PathType) -> &'static str {
mod tests {
use super::*;
#[tokio::test]
async fn test_replace_refreshes_bounds_and_cache_identity() {
use datafusion::prelude::{col, lit};
use datafusion_common::ScalarValue;
use futures::TryStreamExt;
use mito2::config::MitoConfig;
use mito2::test_util::{self, CreateRequestBuilder, TestEnv};
use store_api::region_engine::RegionEngine;
use store_api::region_request::{RegionOpenRequest, RegionRequest};
use store_api::storage::{RegionId, ScanRequest};
let mut target = TestEnv::new().await;
let mut donor = TestEnv::new().await;
let region_id = RegionId::new(1, 1);
let create = CreateRequestBuilder::new().table_dir("table").build();
let schema = test_util::rows_schema(&create);
let region_dir = region_dir_from_table_dir(&create.table_dir, region_id, create.path_type);
let config = MitoConfig {
experimental_metadata_aggr: true,
enable_write_cache: true,
..Default::default()
};
// Two independent regions have the same schema and sequence. The target
// has a cached Delete and the replacement has one Put at a new key/time.
let mut paths = Vec::new();
for (env, key, second) in [(&mut target, "a", 1), (&mut donor, "b", 2)] {
let engine = env.create_engine(config.clone()).await;
engine
.handle_request(region_id, RegionRequest::Create(create.clone()))
.await
.unwrap();
let rows = api::v1::Rows {
schema: schema.clone(),
rows: test_util::build_rows_for_key(key, second, second + 1, 0),
};
if key == "a" {
test_util::delete_rows(&engine, region_id, rows).await;
} else {
test_util::put_rows(&engine, region_id, rows).await;
}
test_util::flush_region(&engine, region_id, None).await;
engine.stop().await.unwrap();
let dir = env
.data_home()
.join("data")
.join(region_dir.trim_start_matches('/'));
let files: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.map(|entry| entry.unwrap().path())
.filter(|path| path.extension().is_some_and(|ext| ext == "parquet"))
.collect();
assert_eq!(files.len(), 1);
paths.push(files.into_iter().next().unwrap());
}
let data_home = target.data_home().join("data");
let config_file = target.data_home().join("replace.toml");
std::fs::write(
&config_file,
format!(
"[storage]\ntype = \"File\"\ndata_home = {}\n[[region_engine]]\n[region_engine.mito]\n",
toml::Value::String(data_home.to_string_lossy().into_owned())
),
)
.unwrap();
let command = SstReplaceCommand {
config: config_file,
region_id: region_id.as_u64().to_string(),
table_dir: create.table_dir.clone(),
file_id: paths[0].file_stem().unwrap().to_str().unwrap().to_owned(),
replacement_file: Some(paths[1].clone()),
replacement_object: None,
path_type: "bare".into(),
confirm: true,
verbose: false,
};
let previous_bytes = std::fs::read(&paths[0]).unwrap();
command.run().await.unwrap();
assert_eq!(std::fs::read(&paths[0]).unwrap(), previous_bytes);
let engine = target.open_engine(config).await;
engine
.handle_request(
region_id,
RegionRequest::Open(RegionOpenRequest {
engine: String::new(),
table_dir: create.table_dir,
path_type: create.path_type,
options: create.options,
skip_wal_replay: false,
checkpoint: None,
requirements: Default::default(),
}),
)
.await
.unwrap();
let cutoff = lit(ScalarValue::TimestampMillisecond(Some(1500), None));
for (filter, expected) in [
(col("ts").gt_eq(cutoff), 1),
(col("tag_0").eq(lit("a")), 0),
(col("tag_0").eq(lit("b")), 1),
] {
let request = ScanRequest {
filters: vec![filter],
..Default::default()
};
let scanned = engine
.scan_to_stream(region_id, request.clone())
.await
.unwrap()
.try_fold(
0,
|count, batch| async move { Ok(count + batch.num_rows()) },
)
.await
.unwrap();
assert_eq!(scanned, expected);
let scanner = engine
.handle_query(
region_id,
ScanRequest {
metadata_aggr_hint: true,
..request
},
)
.await
.unwrap();
if expected == 1 {
assert_eq!(scanner.properties().exact_num_rows(), Some(expected));
} else {
assert!(
scanner
.properties()
.exact_num_rows()
.is_none_or(|count| count == expected)
);
}
}
engine.stop().await.unwrap();
}
#[test]
fn test_validate_replacement_counts() {
let old_file = mito2::sst::file::FileMeta {
+43 -61
View File
@@ -23,7 +23,9 @@ use datafusion::logical_expr::{Expr, TableType};
use datafusion::physical_plan::expressions::Column;
use datafusion::physical_plan::expressions::{DynamicFilterPhysicalExpr, lit as physical_lit};
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::{ExecutionPlan, StatisticsArgs, StatisticsContext, displayable};
use datafusion::physical_plan::{
ExecutionPlan, StatisticsArgs, StatisticsContext, collect, displayable,
};
use datafusion::prelude::SessionContext;
use datafusion_common::ScalarValue;
use datafusion_common::stats::Precision;
@@ -191,10 +193,10 @@ async fn run_compaction_sql_and_fallback(merge_mode: &str) {
ctx.register_table("t", Arc::new(CountTable { plan: scan }))
.unwrap();
let df = ctx.sql("SELECT count(*) FROM t").await.unwrap();
let plan = df.clone().create_physical_plan().await.unwrap();
let plan = df.create_physical_plan().await.unwrap();
let text = displayable(plan.as_ref()).indent(true).to_string();
assert!(!text.contains("RegionScanExec"), "{text}");
let batches = df.collect().await.unwrap();
assert!(text.contains("PlaceholderRowExec"), "{text}");
let batches = collect(plan, ctx.task_ctx()).await.unwrap();
assert_eq!(
ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
ScalarValue::Int64(Some(6))
@@ -477,8 +479,6 @@ async fn test_metadata_aggr_replacement_with_duplicate_rows_falls_back() {
#[rstest::rstest]
#[case::non_append_key_filter(false, false, "b", 1)]
#[case::append_key_filter(true, false, "b", 1)]
#[case::non_append_time_filter(false, false, "a", 2)]
#[case::append_time_filter(true, false, "a", 2)]
#[case::key_overlap(false, true, "b", 1)]
#[case::time_overlap(false, true, "a", 2)]
@@ -493,9 +493,22 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back(
use crate::manifest::action::RegionEdit;
let mut env = TestEnv::new().await;
let reads = Arc::new(AtomicUsize::new(0));
let observed = reads.clone();
let layer = MockLayerBuilder::default()
.reader_factory(Arc::new(move |path, _, inner| {
if path.ends_with(".parquet") {
observed.fetch_add(1, Ordering::Relaxed);
}
inner
}))
.build()
.unwrap();
let mut env = TestEnv::new().await.with_mock_layer(layer);
let config = MitoConfig {
experimental_metadata_aggr: true,
// Isolate query I/O from the background preloader on region open.
preload_index_cache: false,
schedule_compaction_after_edit: false,
..Default::default()
};
@@ -567,19 +580,6 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back(
.find(|file| file.file_id() != old_file.file_id())
.unwrap()
.clone();
assert_eq!(
old_file.time_range() != second_file.time_range(),
changed_time
);
assert_eq!(old_file.num_rows(), second_file.num_rows());
assert_eq!(
old_file.meta_ref().num_row_groups,
second_file.meta_ref().num_row_groups
);
assert_eq!(
old_file.raw_primary_key_range() != second_file.raw_primary_key_range(),
replacement_key != "a"
);
if keep_second_file {
let scan = engine
.handle_query(region_id, request.clone())
@@ -596,7 +596,7 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back(
file_size: bytes.len() as u64,
..old_file.meta_ref().clone()
};
// Like sst-replace, keep the file ID and the old manifest bounds.
// Reproduce an older sst-replace edit that kept its file ID and manifest bounds.
store
.write(&replacement.file_path(&table_dir, path_type), bytes)
.await
@@ -633,52 +633,34 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back(
)
.await
.unwrap();
assert_eq!(
engine
.get_region(region_id)
.unwrap()
.version()
.options
.append_mode,
append
);
if !keep_second_file && changed_time {
// The file is excluded by the old manifest. A cold proof must fall back
// without opening it just to validate that exclusion.
reads.store(0, Ordering::Relaxed);
let scan = engine
.handle_query(region_id, time_pruned_request)
.await
.unwrap();
assert_eq!(scan.properties().exact_num_rows(), None);
assert_eq!(reads.load(Ordering::Relaxed), 0);
}
let scan = engine
.handle_query(region_id, request.clone())
.await
.unwrap();
assert_eq!(scan.properties().exact_num_rows(), None);
if !keep_second_file {
if changed_time {
let scan = engine
.handle_query(region_id, time_pruned_request)
.await
.unwrap();
assert_eq!(scan.properties().exact_num_rows(), None);
}
for metadata_aggr_hint in [false, true] {
let request = ScanRequest {
metadata_aggr_hint,
..request.clone()
};
let scanner = engine
.handle_query(region_id, request.clone())
.await
.unwrap();
let plan = Arc::new(RegionScanExec::new(scanner, request, None).unwrap());
let ctx = SessionContext::new();
ctx.register_table("t", Arc::new(CountTable { plan }))
.unwrap();
let df = ctx.sql("SELECT count(*) FROM t").await.unwrap();
let plan = df.clone().create_physical_plan().await.unwrap();
let text = displayable(plan.as_ref()).indent(true).to_string();
let scan_name = if append { "UnorderedScan" } else { "SeqScan" };
assert!(text.contains(scan_name), "{text}");
let batches = df.collect().await.unwrap();
assert_eq!(
ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
ScalarValue::Int64(Some(0))
);
}
// Execute the same scanner whose statistics were inspected above.
let plan = Arc::new(RegionScanExec::new(scan, request, None).unwrap());
let ctx = SessionContext::new();
ctx.register_table("t", Arc::new(CountTable { plan }))
.unwrap();
let df = ctx.sql("SELECT count(*) FROM t").await.unwrap();
let batches = df.collect().await.unwrap();
assert_eq!(
ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
ScalarValue::Int64(Some(0))
);
}
engine.stop().await.unwrap();
}
+4 -2
View File
@@ -44,7 +44,7 @@ use datatypes::extension::json::is_json2_extension_type;
use datatypes::prelude::ConcreteDataType;
use datatypes::types::json_type::JsonNativeType;
use datatypes::value::timestamp_to_scalar_value;
use futures::StreamExt;
use futures::{FutureExt, StreamExt};
use mito_codec::row_converter::{SortField, build_primary_key_codec_with_fields};
use partition::expr::PartitionExpr;
use smallvec::SmallVec;
@@ -717,7 +717,9 @@ impl ScanRegion {
let mut input = input.build();
input.row_preserving_request = request_preserves_rows(&self.request);
if self.experimental_metadata_aggr && self.request.metadata_aggr_hint {
input.exact_num_rows = aggr::prepare(&input, &self.request, &self.version.ssts).await;
input.exact_num_rows = aggr::prepare(&input, &self.request, &self.version.ssts)
.boxed()
.await;
}
Ok(input)
}
+114 -280
View File
@@ -30,12 +30,12 @@ use datatypes::value::Value;
use futures::future::BoxFuture;
use futures::{FutureExt, StreamExt, TryStreamExt};
use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec};
use parquet::file::metadata::ParquetMetaData;
use parquet::file::metadata::{PageIndexPolicy, ParquetMetaData};
use store_api::codec::PrimaryKeyEncoding;
use store_api::metadata::{ColumnMetadata, RegionMetadata};
use store_api::storage::ScanRequest;
use store_api::storage::{ColumnId, ScanRequest};
use crate::cache::CacheStrategy;
use crate::cache::CachedSstMeta;
use crate::read::scan_region::aggr::overlap::{Extent, find_overlaps};
use crate::read::scan_region::{ScanInput, request_preserves_rows};
use crate::sst::file::FileHandle;
@@ -52,129 +52,84 @@ pub(crate) async fn prepare(
request: &ScanRequest,
ssts: &SstVersion,
) -> Option<usize> {
if !input.memtables.is_empty() {
return None;
let classification = classify(input, request)?;
if input.append_mode && request.filters.is_empty() {
return Some(classification.exact_rows);
}
let classification = classify(input, request, false)?;
if !classification.remaining.is_empty() {
return None;
}
let evidence = if input.append_mode && request.filters.is_empty() {
vec![true; classification.exact.len()]
} else {
read_file_evidence(input, &classification, ssts).await?
};
resolve(input, classification, &evidence)
}
/// Applies the footer evidence of the exact candidates.
fn resolve(
input: &ScanInput,
mut classification: Classification,
evidence: &[bool],
) -> Option<usize> {
classification.retain_exact(input, evidence);
(classification.remaining.is_empty() && input.memtables.is_empty())
.then_some(classification.exact_rows)
}
/// Validates the bounds used by classification before proving the visible row
/// count of each candidate. A stale or unknown bound may also invalidate the
/// exclusion of a pruned file or the disjointness of a residual file.
async fn read_file_evidence(
input: &ScanInput,
classification: &Classification,
ssts: &SstVersion,
) -> Option<Vec<bool>> {
let check_overlap = !input.append_mode
&& !classification.exact.is_empty()
&& classification.exact.len() + classification.remaining.len() > 1;
// Own the file handles across the async reads.
let mut files: Vec<_> = classification
.exact
.iter()
.map(|&index| {
(
input.files[index].clone(),
!input.append_mode,
classification.key_filter || check_overlap,
)
})
.collect();
if check_overlap {
files.extend(
classification
.remaining
.iter()
.map(|&index| (input.files[index].clone(), false, true)),
);
}
for level in ssts.levels() {
files.extend(
input
.time_pruned_files
.iter()
.filter_map(|id| level.files.get(id))
.map(|file| (file.clone(), false, false)),
);
}
let access_layer = input.access_layer.clone();
// The on-disk write cache can survive offline replacement of the same
// file ID. This proof needs metadata from the current object.
let cache = if input.cache_strategy.write_cache().is_some() {
CacheStrategy::Disabled
} else {
input.cache_strategy.clone()
};
let time_index_id = input.region_metadata().time_index_column().column_id;
// Readers are created only as buffer slots become available.
let reads = futures::stream::iter(files).map(
move |(file, check_rows, check_keys)| -> BoxFuture<'static, Result<bool, ()>> {
let key_range = if check_keys {
file.raw_primary_key_range()
} else {
None
};
let file_id = file.file_id();
let (start, end) = file.time_range();
let num_rows = file.num_rows();
let reader = access_layer.read_sst(file).cache(cache.clone());
async move {
let sst = reader.read_statistics().await.map_err(|e| {
debug!("Metadata count could not read footer of {file_id}: {e:?}");
})?;
let metadata = sst.parquet_metadata();
let region_metadata = sst.region_metadata();
let time_index = region_metadata.time_index_column();
let time_matches = time_index.column_id == time_index_id
&& extract_time_range(&metadata, time_index).is_some_and(|(min, max)| {
start.unit() == min.unit()
&& end.unit() == max.unit()
&& (start, end) == (min, max)
});
if !time_matches {
debug!("Metadata count could not verify time bounds of {file_id}");
return Err(());
}
if let Some(range) = key_range
&& extract_primary_key_range(&metadata, &region_metadata) != Some(range)
{
debug!("Metadata count could not verify key bounds of {file_id}");
return Err(());
}
Ok(!check_rows || footer_proves_visible_rows(&metadata, num_rows))
}
.boxed()
},
);
let mut proven: Vec<_> = reads
.buffered(input.max_concurrent_scan_files.max(1))
.try_collect()
verify_pruned_times(input, ssts).await?;
let check_keys =
classification.key_filter || (!input.append_mode && classification.exact.len() > 1);
let check_rows = !input.append_mode;
futures::stream::iter(classification.exact)
.map(|index| file_evidence(input, input.files[index].clone(), check_keys, check_rows))
.buffer_unordered(input.max_concurrent_scan_files.max(1))
.try_collect::<()>()
.await
.ok()?;
proven.truncate(classification.exact.len());
Some(proven)
Some(classification.exact_rows)
}
/// Older offline replacements could retain stale manifest bounds. Never open an
/// excluded SST for COUNT: a cold or inconsistent footer leaves the scan in place.
async fn verify_pruned_times(input: &ScanInput, ssts: &SstVersion) -> Option<()> {
let time_id = input.region_metadata().time_index_column().column_id;
for id in &input.time_pruned_files {
let file = ssts.levels().iter().find_map(|level| level.files.get(id))?;
let sst = input
.cache_strategy
.get_sst_meta_data_from_mem_cache(file.file_id(), PageIndexPolicy::Skip)
.await?;
if !time_bounds_match(file, &sst, time_id) {
return None;
}
}
Some(())
}
fn time_bounds_match(file: &FileHandle, sst: &CachedSstMeta, time_id: ColumnId) -> bool {
let region = sst.region_metadata();
let time_index = region.time_index_column();
let (start, end) = file.time_range();
time_index.column_id == time_id
&& extract_time_range(&sst.parquet_metadata(), time_index).is_some_and(|(min, max)| {
start.unit() == min.unit() && end.unit() == max.unit() && (start, end) == (min, max)
})
}
/// Proves the bounds and visible rows required for this exact candidate.
fn file_evidence(
input: &ScanInput,
file: FileHandle,
check_keys: bool,
check_rows: bool,
) -> BoxFuture<'static, Result<(), ()>> {
let time_id = input.region_metadata().time_index_column().column_id;
let reader = input
.access_layer
.read_sst(file.clone())
.cache(input.cache_strategy.clone());
async move {
let sst = reader.read_statistics().await.map_err(|e| {
debug!(
"Metadata count could not read footer of {}: {e:?}",
file.file_id()
);
})?;
let metadata = sst.parquet_metadata();
if !time_bounds_match(&file, &sst, time_id) {
return Err(());
}
if check_keys
&& let Some(range) = file.raw_primary_key_range()
&& extract_primary_key_range(&metadata, &sst.region_metadata()) != Some(range)
{
return Err(());
}
(!check_rows || footer_proves_visible_rows(&metadata, file.num_rows()))
.then_some(())
.ok_or(())
}
.boxed()
}
/// The footer and manifest must agree. Without the writer's uniqueness claim,
@@ -201,32 +156,12 @@ fn footer_proves_visible_rows(metadata: &ParquetMetaData, manifest_rows: usize)
struct Classification {
/// Indexes into `ScanInput::files` whose rows are all yielded exactly once.
exact: Vec<usize>,
/// Indexes of the other files intersecting the query time range.
remaining: Vec<usize>,
/// Sum of the manifest row counts of `exact`.
exact_rows: usize,
/// Whether the filter proof depends on key bounds.
key_filter: bool,
}
impl Classification {
/// Moves the exact files without proof to `remaining`.
fn retain_exact(&mut self, input: &ScanInput, proven: &[bool]) {
debug_assert_eq!(self.exact.len(), proven.len());
let mut exact = Vec::with_capacity(self.exact.len());
for (&index, &proven) in self.exact.iter().zip(proven) {
if proven {
exact.push(index);
} else {
self.exact_rows -= input.files[index].num_rows();
self.remaining.push(index);
}
}
self.exact = exact;
self.remaining.sort_unstable();
}
}
/// A file is an exact candidate if all of the following hold:
/// - The query time range covers it and every other static filter holds for
/// all of its rows (see [`AggrFilters`]).
@@ -237,12 +172,11 @@ impl Classification {
///
/// Returns `None` for scans whose visible rows can differ from the sources'
/// rows for reasons other than the files themselves.
fn classify(
input: &ScanInput,
request: &ScanRequest,
allow_partial: bool,
) -> Option<Classification> {
if !input.allows_exact_row_count() || !request_preserves_rows(request) {
fn classify(input: &ScanInput, request: &ScanRequest) -> Option<Classification> {
if !input.memtables.is_empty()
|| !input.allows_exact_row_count()
|| !request_preserves_rows(request)
{
return None;
}
let filters = AggrFilters::new(input.region_metadata(), &request.filters)?;
@@ -264,63 +198,36 @@ fn classify(
&& input.file_time_bounds_fit(file)
&& (input.region_partition_expr.is_none() || input.should_skip_region_partition(file))
&& filters.covers(file);
if !candidate && !allow_partial {
if !candidate {
return None;
}
intersecting.push((index, candidate));
intersecting.push(index);
}
// Append mode never merges rows, so sources cannot hide each other's rows.
let overlaps = if !input.append_mode && intersecting.iter().any(|&(_, candidate)| candidate) {
overlapping_files(input, &intersecting)
} else {
Vec::new()
};
let mut classification = Classification {
exact: Vec::new(),
remaining: Vec::new(),
exact_rows: 0,
if !input.append_mode && intersecting.len() > 1 {
let mapper = input.primary_key_mapper();
let extents: Vec<_> = intersecting
.iter()
.map(|&index| {
let file = &input.files[index];
Extent {
time: file.time_range(),
key: file.primary_key_range(mapper),
}
})
.collect();
if find_overlaps(&extents).contains(&true) {
return None;
}
}
let exact_rows = intersecting.iter().try_fold(0usize, |rows, &index| {
rows.checked_add(input.files[index].num_rows())
})?;
i64::try_from(exact_rows).ok()?;
Some(Classification {
exact: intersecting,
exact_rows,
key_filter: filters.codec.is_some(),
};
for (position, (index, candidate)) in intersecting.into_iter().enumerate() {
let file = &input.files[index];
if candidate && !overlaps.get(position).copied().unwrap_or(false) {
classification.exact_rows = classification.exact_rows.checked_add(file.num_rows())?;
classification.exact.push(index);
} else {
classification.remaining.push(index);
}
}
i64::try_from(classification.exact_rows).ok()?;
Some(classification)
}
/// Returns, for each file in `files`, whether another file or a memtable may
/// hold a row with the same primary key and timestamp.
fn overlapping_files(input: &ScanInput, files: &[(usize, bool)]) -> Vec<bool> {
let mapper = input.primary_key_mapper();
let mut extents: Vec<_> = files
.iter()
.map(|&(index, _)| {
let file = &input.files[index];
Extent {
time: file.time_range(),
key: file.primary_key_range(mapper),
}
})
.collect();
// Memtable key bounds are unknown.
for memtable in &input.memtables {
let stats = memtable.stats();
match stats.time_range {
Some(time) => extents.push(Extent { time, key: None }),
None if stats.num_rows == 0 => {}
None => return vec![true; files.len()],
}
}
let mut overlaps = find_overlaps(&extents);
overlaps.truncate(files.len());
overlaps
})
}
/// Static scan predicates a metadata count can absorb.
@@ -523,29 +430,14 @@ mod tests {
)
}
/// Footer evidence for the synthetic files in these classification tests.
fn evidence(input: &ScanInput, classification: &Classification) -> Vec<bool> {
let with_deletes = WITH_DELETES.lock().unwrap();
fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
let classification = classify(input, request)?;
let deletes = WITH_DELETES.lock().unwrap();
classification
.exact
.iter()
.map(|&index| {
input.append_mode || !with_deletes.contains(&input.files[index].meta_ref().file_id)
})
.collect()
}
fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
let classification = classify(input, request, false)?;
let no_deletes = evidence(input, &classification);
resolve(input, classification, &no_deletes)
}
fn classified(input: &ScanInput, request: &ScanRequest) -> Classification {
let mut classification = classify(input, request, true).unwrap();
let no_deletes = evidence(input, &classification);
classification.retain_exact(input, &no_deletes);
classification
.all(|&i| input.append_mode || !deletes.contains(&input.files[i].meta_ref().file_id))
.then_some(classification.exact_rows)
}
async fn input(files: Vec<FileHandle>, filters: &[Expr]) -> ScanInput {
@@ -634,18 +526,6 @@ mod tests {
};
assert_eq!(exact_count(&input, &request), expected, "{request:?}");
}
let filters = vec![k0("x")];
let input = input(vec![x(0, 10, 3), mixed()], &filters).await;
let request = ScanRequest {
filters,
..Default::default()
};
let classification = classified(&input, &request);
assert_eq!(
(classification.exact_rows, classification.remaining.len()),
(3, 1)
);
}
#[tokio::test]
@@ -695,52 +575,6 @@ mod tests {
input.append_mode = true;
assert_eq!(exact_count(&input, &ScanRequest::default()), None);
}
#[tokio::test]
async fn test_metadata_aggr_classifies_files() {
for (files, exact_rows, exact, remaining) in [
(
vec![file(0, 10, 3, true), file(20, 30, 2, false)],
3,
vec![0],
vec![1],
),
// Without key bounds, the wide file overlaps both others in time.
(
vec![
file(0, 100, 3, true),
file(5, 8, 2, false),
file(20, 30, 4, true),
],
0,
vec![],
vec![0, 1, 2],
),
(
vec![file(0, 10, 3, true), file(20, 30, 0, true)],
3,
vec![0],
vec![1],
),
// Disjoint keys keep time-overlapping files independent.
(
vec![
keyed_file(0, 10, 3, ("a", 0), ("a", 9)),
keyed_file(5, 15, 4, ("b", 0), ("b", 9)),
keyed_file(8, 9, 1, ("a", 5), ("a", 5)),
],
4,
vec![1],
vec![0, 2],
),
] {
let input = input(files, &[]).await;
let classification = classified(&input, &ScanRequest::default());
assert_eq!(classification.exact_rows, exact_rows);
assert_eq!(classification.exact, exact);
assert_eq!(classification.remaining, remaining);
}
}
#[test]
fn test_metadata_aggr_reads_op_type_statistics() {
use api::v1::OpType;
+3 -2
View File
@@ -198,7 +198,8 @@ pub(crate) fn deduped_sst_marker(
deduped.then(|| KeyValue::new(DEDUPED_SST_KEY.to_owned(), None))
}
pub(crate) fn extract_primary_key_range(
/// Returns complete encoded primary-key endpoints, if all row groups provide them.
pub fn extract_primary_key_range(
parquet_meta: &ParquetMetaData,
region_metadata: &RegionMetadata,
) -> Option<(Bytes, Bytes)> {
@@ -237,7 +238,7 @@ pub(crate) fn extract_primary_key_range(
}
/// Returns exact time-index bounds with the unit stored in this SST.
pub(crate) fn extract_time_range(
pub fn extract_time_range(
parquet_meta: &ParquetMetaData,
time_index: &ColumnMetadata,
) -> Option<FileTimeRange> {