fix(mito2): keep metadata count proofs within the SST read set

Signed-off-by: aumnertic <aumnertic@gmail.com>
This commit is contained in:
aumnertic
2026-11-27 00:10:48 -05:00
parent f15778c63f
commit 458427fecb
11 changed files with 182 additions and 54 deletions
+2 -2
View File
@@ -228,7 +228,7 @@
| `region_engine.mito.schedule_compaction_after_edit` | Bool | `true` | Whether to allow to schedule a compaction after a successful region edit.<br/><br/>Setting this to "true" is a necessary but not sufficient condition for scheduling compaction after a region edit.<br/>Other constraints, such as "min_compaction_interval", may still prevent compaction from being scheduled.<br/>Setting this to "false", however, guarantees that compaction will not be scheduled after a region edit. |
| `region_engine.mito.default_flat_format` | Bool | `true` | Whether to enable flat format as the default SST format. |
| `region_engine.mito.experimental_series_scan_v2` | Bool | `false` | Whether to enable the experimental two-phase mode for eligible metric series scans. |
| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.<br/>May read Parquet footers to prove uniqueness and the absence of deletes. |
| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.<br/>May read Parquet footers to prove uniqueness and the absence of deletes.<br/>Footer reads use `sst_meta_cache` outside `query.scan_memory_limit` and `query.memory_pool_size`.<br/>Partial counts use captured source containers without a single-instant snapshot across partitions.<br/>Append-mode scans only use full metadata counts. |
| `region_engine.mito.index` | -- | -- | The options for index in Mito engine. |
| `region_engine.mito.index.aux_path` | String | `""` | Auxiliary directory path for the index in filesystem, used to store intermediate files for<br/>creating the index and staging files for searching the index, defaults to `{data_home}/index_intermediate`.<br/>The default name for this directory is `index_intermediate` for backward compatibility.<br/><br/>This path contains two subdirectories:<br/>- `__intm`: for storing intermediate files used during creating index.<br/>- `staging`: for storing staging files used during searching index. |
| `region_engine.mito.index.staging_size` | String | `2GB` | The max capacity of the staging directory. |
@@ -719,7 +719,7 @@
| `region_engine.mito.schedule_compaction_after_edit` | Bool | `true` | Whether to allow to schedule a compaction after a successful region edit.<br/><br/>Setting this to "true" is a necessary but not sufficient condition for scheduling compaction after a region edit.<br/>Other constraints, such as "min_compaction_interval", may still prevent compaction from being scheduled.<br/>Setting this to "false", however, guarantees that compaction will not be scheduled after a region edit. |
| `region_engine.mito.default_flat_format` | Bool | `true` | Whether to enable flat format as the default SST format. |
| `region_engine.mito.experimental_series_scan_v2` | Bool | `false` | Whether to enable the experimental two-phase mode for eligible metric series scans. |
| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.<br/>May read Parquet footers to prove uniqueness and the absence of deletes. |
| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.<br/>May read Parquet footers to prove uniqueness and the absence of deletes.<br/>Footer reads use `sst_meta_cache` outside `query.scan_memory_limit` and `query.memory_pool_size`.<br/>Partial counts use captured source containers without a single-instant snapshot across partitions.<br/>Append-mode scans only use full metadata counts. |
| `region_engine.mito.index` | -- | -- | The options for index in Mito engine. |
| `region_engine.mito.index.aux_path` | String | `""` | Auxiliary directory path for the index in filesystem, used to store intermediate files for<br/>creating the index and staging files for searching the index, defaults to `{data_home}/index_intermediate`.<br/>The default name for this directory is `index_intermediate` for backward compatibility.<br/><br/>This path contains two subdirectories:<br/>- `__intm`: for storing intermediate files used during creating index.<br/>- `staging`: for storing staging files used during searching index. |
| `region_engine.mito.index.staging_size` | String | `2GB` | The max capacity of the staging directory. |
+3
View File
@@ -747,6 +747,9 @@ experimental_series_scan_v2 = false
## Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.
## May read Parquet footers to prove uniqueness and the absence of deletes.
## Footer reads use `sst_meta_cache` outside `query.scan_memory_limit` and `query.memory_pool_size`.
## Partial counts use captured source containers without a single-instant snapshot across partitions.
## Append-mode scans only use full metadata counts.
experimental_metadata_aggr = false
## The options for index in Mito engine.
+3
View File
@@ -978,6 +978,9 @@ experimental_series_scan_v2 = false
## Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.
## May read Parquet footers to prove uniqueness and the absence of deletes.
## Footer reads use `sst_meta_cache` outside `query.scan_memory_limit` and `query.memory_pool_size`.
## Partial counts use captured source containers without a single-instant snapshot across partitions.
## Append-mode scans only use full metadata counts.
experimental_metadata_aggr = false
## The options for index in Mito engine.
+8 -6
View File
@@ -113,9 +113,10 @@ dump path must not be exactly the same path as the input, even with
`--overwrite`. This check does not resolve symbolic links, hard links, or other
spellings of the same path.
The rewrite decodes and writes the Arrow record batches and copies the Parquet
key-value metadata, but it creates a new physical Parquet layout. Inspect and
validate the result before using it as an SST:
The rewrite decodes and writes the Arrow record batches into a new physical
layout. It copies region metadata, recomputes decoded value sizes when present,
and drops the `greptimedb.deduped` marker. Inspect the result before using it
as an SST:
```bash
$GREPTIME datanode parquet-meta \
@@ -194,7 +195,8 @@ 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
unknown. Use `parquet-rewrite` first if the replacement carries
`greptimedb.deduped`. 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.
@@ -244,8 +246,8 @@ $GREPTIME datanode sst-replace \
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`.
replacement, use its current manifest ID as `--file-id`. If the current object
has no deduplication marker, it can be passed directly as `--replacement-object`.
## Recommended rewrite and replacement workflow
+10 -1
View File
@@ -17,6 +17,7 @@ use std::path::{Path, PathBuf};
use clap::Parser;
use datatypes::arrow::record_batch::RecordBatchReader;
use mito2::sst::parquet::metadata::DEDUPED_SST_KEY;
use mito2::sst::parquet::{
MAX_ROW_GROUP_VALUE_BYTES_KEY, MAX_ROW_VALUE_WIDTH_KEY, RowGroupValueBytes,
};
@@ -166,6 +167,11 @@ impl ParquetRewriteCommand {
kvs.retain(|kv| !is_row_group_value_bytes_key(&kv.key));
kvs.len() != len
});
if let Some(kvs) = &mut key_value_metadata {
// Only the folding writers can certify uniqueness. These input
// bytes may have been edited while retaining the original footer.
kvs.retain(|kv| kv.key != DEDUPED_SST_KEY);
}
let mut reader_builder = ParquetRecordBatchReaderBuilder::try_new(open_file(&self.input)?)
.map_err(|e| parquet_error("open source parquet", &self.input, e))?;
@@ -593,9 +599,11 @@ mod tests {
.unwrap();
let mut value_bytes = RowGroupValueBytes::new(4);
value_bytes.update(&batch);
let mut metadata = value_bytes.into_key_values();
metadata.push(KeyValue::new(DEDUPED_SST_KEY.to_string(), None));
let props = WriterProperties::builder()
.set_max_row_group_row_count(Some(4))
.set_key_value_metadata(Some(value_bytes.into_key_values()))
.set_key_value_metadata(Some(metadata))
.build();
let mut writer =
ArrowWriter::try_new(File::create(&input).unwrap(), schema, Some(props)).unwrap();
@@ -620,6 +628,7 @@ mod tests {
let rewritten = load_local_parquet_metadata(&output).unwrap();
assert_eq!(2, rewritten.num_row_groups());
let key_values = rewritten.file_metadata().key_value_metadata().unwrap();
assert!(key_values.iter().all(|kv| kv.key != DEDUPED_SST_KEY));
let value_of = |key: &str| {
let values: Vec<_> = key_values
.iter()
+65 -7
View File
@@ -23,7 +23,9 @@ use mito2::sst::file::{FileFormat, FileMeta};
use mito2::sst::file_metadata::FileMetadataInterner;
use mito2::sst::location::region_dir_from_table_dir;
use mito2::sst::parquet::max_row_group_decoded_size;
use mito2::sst::parquet::metadata::{extract_primary_key_range, extract_time_range};
use mito2::sst::parquet::metadata::{
DEDUPED_SST_KEY, extract_primary_key_range, extract_time_range, has_deduped_sst_marker,
};
use object_store::{Buffer, ObjectStore};
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::record::RowAccessor;
@@ -190,6 +192,14 @@ 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)?;
if has_deduped_sst_marker(parquet_meta) {
return error::IllegalConfigSnafu {
msg: format!(
"replacement SST carries the {DEDUPED_SST_KEY} marker; run parquet-rewrite to remove it first"
),
}
.fail();
}
let source = extract_region_metadata("replacement SST", parquet_meta)?;
let time_index = source.time_index_column();
@@ -434,15 +444,20 @@ mod tests {
#[tokio::test]
async fn test_replace_refreshes_pruning_bounds() {
check_replacement(true).await;
check_replacement(true, false).await;
}
#[tokio::test]
async fn test_replace_cached_delete_with_put_at_same_key_and_time() {
check_replacement(false).await;
check_replacement(false, false).await;
}
async fn check_replacement(move_row: bool) {
#[tokio::test]
async fn test_replace_sst_rejects_marked_duplicate_rows() {
check_replacement(false, true).await;
}
async fn check_replacement(move_row: bool, marked_duplicates: bool) {
use datafusion::prelude::{col, lit};
use datafusion_common::ScalarValue;
use futures::TryStreamExt;
@@ -456,6 +471,7 @@ mod tests {
let mut donor = TestEnv::new().await;
let region_id = RegionId::new(1, 1);
let create = CreateRequestBuilder::new().table_dir("table").build();
let rows_per_file = if marked_duplicates { 3 } else { 1 };
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 {
@@ -464,7 +480,8 @@ mod tests {
..Default::default()
};
// Two independent regions have the same schema and sequence. The target
// has a cached Delete and the replacement has one Put.
// has deletes and the replacement has puts. Use an append-mode donor for
// the accepted cases so its output has no deduplication claim.
let mut paths = Vec::new();
let (new_key, new_second) = if move_row { ("b", 2) } else { ("a", 1) };
for (env, key, second, delete) in [
@@ -472,13 +489,17 @@ mod tests {
(&mut donor, new_key, new_second, false),
] {
let engine = env.create_engine(config.clone()).await;
let mut create = create.clone();
if !delete && !marked_duplicates {
create.options.insert("append_mode".into(), "true".into());
}
engine
.handle_request(region_id, RegionRequest::Create(create.clone()))
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
let rows = api::v1::Rows {
schema: schema.clone(),
rows: test_util::build_rows_for_key(key, second, second + 1, 0),
rows: test_util::build_rows_for_key(key, second, second + rows_per_file, 0),
};
if delete {
test_util::delete_rows(&engine, region_id, rows).await;
@@ -509,6 +530,9 @@ mod tests {
),
)
.unwrap();
if marked_duplicates {
write_marked_duplicate_rows(&paths[1]);
}
let command = SstReplaceCommand {
config: config_file,
region_id: region_id.as_u64().to_string(),
@@ -521,6 +545,12 @@ mod tests {
verbose: false,
};
let previous_bytes = std::fs::read(&paths[0]).unwrap();
if marked_duplicates {
let err = command.run().await.unwrap_err();
assert!(err.to_string().contains(DEDUPED_SST_KEY), "{err}");
assert_eq!(std::fs::read(&paths[0]).unwrap(), previous_bytes);
return;
}
command.run().await.unwrap();
assert_eq!(std::fs::read(&paths[0]).unwrap(), previous_bytes);
let engine = target.open_engine(config).await;
@@ -589,6 +619,34 @@ mod tests {
engine.stop().await.unwrap();
}
fn write_marked_duplicate_rows(path: &std::path::Path) {
use std::fs::File;
use datatypes::arrow::array::UInt32Array;
use datatypes::arrow::compute::take_record_batch;
use parquet::arrow::ArrowWriter;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::file::properties::WriterProperties;
let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(path).unwrap()).unwrap();
assert!(has_deduped_sst_marker(reader.metadata()));
let metadata = reader
.metadata()
.file_metadata()
.key_value_metadata()
.cloned();
let batch = reader.build().unwrap().next().unwrap().unwrap();
// Keep the row count and time/key bounds while duplicating the first Put.
let batch = take_record_batch(&batch, &UInt32Array::from(vec![0, 0, 2])).unwrap();
let props = WriterProperties::builder()
.set_key_value_metadata(metadata)
.build();
let mut writer =
ArrowWriter::try_new(File::create(path).unwrap(), batch.schema(), Some(props)).unwrap();
writer.write(&batch).unwrap();
writer.close().unwrap();
}
#[test]
fn test_validate_replacement_counts() {
let old_file = mito2::sst::file::FileMeta {
+4 -1
View File
@@ -253,7 +253,10 @@ pub struct MitoConfig {
/// Answers eligible scalar COUNT queries from manifest row counts instead
/// of scanning SST rows. May read Parquet footers to prove uniqueness and
/// the absence of deletes.
/// the absence of deletes. Footer reads use `sst_meta_cache` outside
/// `query.scan_memory_limit` and `query.memory_pool_size`.
/// Partial counts use captured source containers without a single-instant
/// snapshot across partitions. Append-mode scans only use full metadata counts.
pub experimental_metadata_aggr: bool,
pub gc: GcConfig,
+69 -3
View File
@@ -634,14 +634,14 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back(
.await
.unwrap();
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.
// Time pruning uses the manifest just as the ordinary scan does, even
// if an older offline replacement left stale bounds there.
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!(scan.properties().exact_num_rows(), Some(0));
assert_eq!(reads.load(Ordering::Relaxed), 0);
}
let scan = engine
@@ -665,6 +665,72 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back(
engine.stop().await.unwrap();
}
#[tokio::test]
async fn test_metadata_aggr_time_pruning_skips_cold_footers() {
let reads = Arc::new(std::sync::Mutex::new(Vec::new()));
let observed = reads.clone();
let layer = MockLayerBuilder::default()
.reader_factory(Arc::new(move |path, _, inner| {
if path.ends_with(".parquet") {
observed.lock().unwrap().push(path.to_owned());
}
inner
}))
.build()
.unwrap();
let mut env = TestEnv::new().await.with_mock_layer(layer);
let config = MitoConfig {
experimental_metadata_aggr: true,
enable_write_cache: false,
preload_index_cache: false,
schedule_compaction_after_edit: false,
..Default::default()
};
let engine = env.create_engine(config.clone()).await;
let region_id = RegionId::new(1, 1);
let create = CreateRequestBuilder::new().build();
let table_dir = create.table_dir.clone();
let options = create.options.clone();
let schema = test_util::rows_schema(&create);
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
put_and_flush(&engine, region_id, &schema, 0..3).await;
put_and_flush(&engine, region_id, &schema, 10..13).await;
let inside = engine
.get_region(region_id)
.unwrap()
.version()
.ssts
.levels()[0]
.files
.values()
.max_by_key(|file| file.time_range().0)
.unwrap()
.file_id();
let engine = env.reopen_engine(engine, config).await;
test_util::reopen_region(&engine, region_id, table_dir, false, options).await;
reads.lock().unwrap().clear();
let request = ScanRequest {
filters: vec![col("ts").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(10_000), None)))],
metadata_aggr_hint: true,
..Default::default()
};
let scanner = engine.handle_query(region_id, request).await.unwrap();
assert_eq!(scanner.properties().exact_num_rows(), Some(3));
let reads = reads.lock().unwrap().clone();
assert!(!reads.is_empty(), "the in-range footer starts cold");
assert!(
reads
.iter()
.all(|path| path.ends_with(&format!("{}.parquet", inside.file_id()))),
"{reads:?}"
);
engine.stop().await.unwrap();
}
#[tokio::test]
async fn test_metadata_aggr_statistics_follow_row_visibility() {
let mut env = TestEnv::new().await;
+3 -3
View File
@@ -717,9 +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)
.boxed()
.await;
// Reuse the scan's manifest time pruning. Footer checks apply only to
// files in the read set, even for manifests from older offline tools.
input.exact_num_rows = aggr::prepare(&input, &self.request).boxed().await;
}
Ok(input)
}
+6 -30
View File
@@ -30,7 +30,7 @@ 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::{PageIndexPolicy, ParquetMetaData};
use parquet::file::metadata::ParquetMetaData;
use store_api::codec::PrimaryKeyEncoding;
use store_api::metadata::{ColumnMetadata, RegionMetadata};
use store_api::storage::{ColumnId, ScanRequest};
@@ -40,23 +40,17 @@ use crate::read::scan_region::aggr::overlap::{Extent, find_overlaps};
use crate::read::scan_region::{ScanInput, request_preserves_rows};
use crate::sst::file::FileHandle;
use crate::sst::parquet::metadata::{
DEDUPED_SST_KEY, extract_primary_key_range, extract_time_range, has_only_puts,
extract_primary_key_range, extract_time_range, has_deduped_sst_marker, has_only_puts,
};
use crate::sst::version::SstVersion;
/// Returns the exact number of rows the scan yields, or `None` if it cannot
/// be proven. Non-append candidates use cached Parquet footers to prove
/// file-local uniqueness and the absence of deletes.
pub(crate) async fn prepare(
input: &ScanInput,
request: &ScanRequest,
ssts: &SstVersion,
) -> Option<usize> {
pub(crate) async fn prepare(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
let classification = classify(input, request)?;
if input.append_mode && request.filters.is_empty() {
return Some(classification.exact_rows);
}
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;
@@ -69,23 +63,6 @@ pub(crate) async fn prepare(
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();
@@ -136,10 +113,7 @@ fn file_evidence(
/// only a single physical row is independently known to be unique.
fn footer_proves_visible_rows(metadata: &ParquetMetaData, manifest_rows: usize) -> bool {
let footer = metadata.file_metadata();
let unique = manifest_rows == 1
|| footer
.key_value_metadata()
.is_some_and(|entries| entries.iter().any(|entry| entry.key == DEDUPED_SST_KEY));
let unique = manifest_rows == 1 || has_deduped_sst_marker(metadata);
unique
&& usize::try_from(footer.num_rows()) == Ok(manifest_rows)
&& metadata
@@ -587,6 +561,8 @@ mod tests {
use parquet::file::properties::{EnabledStatistics, WriterProperties};
use store_api::storage::consts::OP_TYPE_COLUMN_NAME;
use crate::sst::parquet::metadata::DEDUPED_SST_KEY;
let put = OpType::Put as u8;
let del = OpType::Delete as u8;
let metadata = |name: &str, ops: Vec<Option<u8>>, stats, marker: bool| {
+9 -1
View File
@@ -43,7 +43,15 @@ use crate::sst::parquet::reader::MetadataCacheMetrics;
/// Presence certifies at most one physical row per (primary key, timestamp).
/// The value has no meaning. Any new claim must use a different key.
pub(crate) const DEDUPED_SST_KEY: &str = "greptimedb.deduped";
pub const DEDUPED_SST_KEY: &str = "greptimedb.deduped";
/// Whether the footer carries a writer's deduplication claim.
pub fn has_deduped_sst_marker(metadata: &ParquetMetaData) -> bool {
metadata
.file_metadata()
.key_value_metadata()
.is_some_and(|entries| entries.iter().any(|entry| entry.key == DEDUPED_SST_KEY))
}
/// The estimated size of the footer and metadata need to read from the end of parquet file.
const DEFAULT_PREFETCH_SIZE: u64 = 64 * 1024;