merge: sync partial metadata counts with the SST replacement fix

Signed-off-by: aumnertic <aumnertic@gmail.com>
This commit is contained in:
aumnertic
2026-11-26 00:22:54 -05:00
7 changed files with 425 additions and 215 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;
@@ -192,10 +194,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))
@@ -483,8 +485,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", 3)]
@@ -499,9 +499,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()
};
@@ -580,19 +593,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"
);
let residual_request = if changed_time {
lower_bound_request.clone()
} else {
@@ -623,7 +623,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
@@ -660,15 +660,17 @@ 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, lower_bound_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
@@ -682,37 +684,17 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back(
.unwrap();
assert!(scan.take_statistics_split().is_none());
} else {
if changed_time {
let scan = engine
.handle_query(region_id, lower_bound_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();
}
+5 -2
View File
@@ -45,7 +45,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;
@@ -735,7 +735,10 @@ impl ScanRegion {
&& input.predicate_group().predicate_without_region().is_none()
&& input.source_row_counts_are_exact())
{
match aggr::prepare(&input, &self.request, &self.version.ssts, allow_partial).await {
match aggr::prepare(&input, &self.request, &self.version.ssts, allow_partial)
.boxed()
.await
{
Some(aggr::MetadataAggr::Exact(rows)) => input.exact_num_rows = Some(rows),
Some(aggr::MetadataAggr::Split(plan)) => input.statistics_split = Some(plan),
None => {}
+98 -109
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;
@@ -83,22 +83,47 @@ pub(crate) async fn prepare(
{
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, allow_partial)
if input.append_mode && request.filters.is_empty() {
return resolve(input, classification, allow_partial);
}
verify_pruned_times(input, ssts).await?;
let mut classification = classification;
let check_overlap = !input.append_mode
&& !classification.exact.is_empty()
&& classification.exact.len() + classification.remaining.len() > 1;
let check_keys = classification.key_filter || check_overlap;
let mut files: Vec<_> = classification
.exact
.iter()
.map(|&index| (index, check_keys, !input.append_mode))
.collect();
if check_overlap {
// A stale residual bound could hide an overlap with an exact file.
files.extend(
classification
.remaining
.iter()
.map(|&index| (index, true, false)),
);
}
let reads = futures::stream::iter(files)
.map(|(index, keys, rows)| file_evidence(input, input.files[index].clone(), keys, rows));
let mut proven: Vec<_> = reads
.buffered(input.max_concurrent_scan_files.max(1))
.try_collect()
.await
.ok()?;
proven.truncate(classification.exact.len());
classification.retain_exact(input, &proven);
resolve(input, classification, allow_partial)
}
/// Applies the footer evidence of the exact candidates.
fn resolve(
input: &ScanInput,
mut classification: Classification,
evidence: &[bool],
classification: Classification,
allow_partial: bool,
) -> Option<MetadataAggr> {
classification.retain_exact(input, evidence);
if classification.remaining.is_empty() && input.memtables.is_empty() {
return Some(MetadataAggr::Exact(classification.exact_rows));
}
@@ -115,103 +140,66 @@ fn resolve(
}))
}
/// 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)),
);
/// 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(())
}
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()
.await
.ok()?;
proven.truncate(classification.exact.len());
Some(proven)
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)
})
}
/// A bounds mismatch invalidates the classification. An unproven row count
/// can still be left to the residual scan when partial counts are supported.
fn file_evidence(
input: &ScanInput,
file: FileHandle,
check_keys: bool,
check_rows: bool,
) -> BoxFuture<'static, Result<bool, ()>> {
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(());
}
Ok(!check_rows || footer_proves_visible_rows(&metadata, file.num_rows()))
}
.boxed()
}
/// The footer and manifest must agree. Without the writer's uniqueness claim,
@@ -585,9 +573,10 @@ mod tests {
/// [`prepare`] with the test's footer evidence.
fn counted(input: &ScanInput, request: &ScanRequest) -> Option<MetadataAggr> {
let classification = classify(input, request, true)?;
let mut classification = classify(input, request, true)?;
let no_deletes = evidence(input, &classification);
resolve(input, classification, &no_deletes, true)
classification.retain_exact(input, &no_deletes);
resolve(input, classification, true)
}
fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
+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> {