From ea7e61e82a3762dbf7311ab31acedd49d5bd9947 Mon Sep 17 00:00:00 2001 From: Aum Date: Wed, 2 Dec 2026 10:48:38 +0000 Subject: [PATCH] feat: count exact files from metadata in partial COUNT scans (#10140) * feat(mito2): split metadata counts from residual scans Signed-off-by: aumnertic * fix(mito2): preserve dedup ranges for metadata count residuals Signed-off-by: aumnertic * test(mito): set TWCS type for metadata count fixtures Signed-off-by: aumnertic * fix(mito2): record SST counts once per scan Signed-off-by: aumnertic --------- Signed-off-by: aumnertic --- src/mito2/src/engine/metadata_aggr_test.rs | 946 +++++++++++++++++++-- src/mito2/src/flush.rs | 8 +- src/mito2/src/memtable.rs | 24 +- src/mito2/src/memtable/bulk.rs | 12 + src/mito2/src/memtable/time_partition.rs | 37 +- src/mito2/src/memtable/version.rs | 112 ++- src/mito2/src/read/pruner.rs | 12 +- src/mito2/src/read/range.rs | 77 +- src/mito2/src/read/scan_region.rs | 111 ++- src/mito2/src/read/scan_region/aggr.rs | 667 +++++++++++++-- src/mito2/src/read/seq_scan.rs | 68 +- src/store-api/src/region_engine.rs | 28 + 12 files changed, 1883 insertions(+), 219 deletions(-) diff --git a/src/mito2/src/engine/metadata_aggr_test.rs b/src/mito2/src/engine/metadata_aggr_test.rs index cc5d9a6e256..e00ec1daf4d 100644 --- a/src/mito2/src/engine/metadata_aggr_test.rs +++ b/src/mito2/src/engine/metadata_aggr_test.rs @@ -12,16 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use async_trait::async_trait; use datafusion::catalog::Session; use datafusion::datasource::TableProvider; 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::expressions::{ + BinaryExpr, Column, DynamicFilterPhysicalExpr, col as physical_col, lit as physical_lit, +}; +use datafusion::physical_plan::filter::FilterExec; use datafusion::physical_plan::projection::ProjectionExec; use datafusion::physical_plan::{ ExecutionPlan, StatisticsArgs, StatisticsContext, collect, displayable, @@ -29,16 +31,18 @@ use datafusion::physical_plan::{ use datafusion::prelude::SessionContext; use datafusion_common::ScalarValue; use datafusion_common::stats::Precision; -use datafusion_expr::{col, lit}; +use datafusion_expr::{Operator, col, lit}; use datatypes::arrow::datatypes::SchemaRef; use object_store::layers::mock::MockLayerBuilder; -use store_api::region_engine::RegionEngine; +use store_api::region_engine::{PrepareRequest, RegionEngine, RegionScannerRef}; use store_api::region_request::{RegionDeleteRequest, RegionPutRequest, RegionRequest}; use store_api::storage::{RegionId, ScanRequest, TimeSeriesRowSelector}; use table::table::scan::RegionScanExec; use crate::config::MitoConfig; +use crate::engine::MitoEngine; use crate::engine::compaction_test::{compact, delete_and_flush, put_and_flush}; +use crate::sst::file::{FileHandle, RegionFileId}; use crate::test_util::{self, CreateRequestBuilder, TestEnv}; /// Exercises DataFusion's normal SQL physical optimizer over a real Mito scan. @@ -361,18 +365,6 @@ async fn test_metadata_aggr_reads_deletes_from_sst_statistics() { #[case::unmarked(false)] #[tokio::test] async fn test_metadata_aggr_replacement_with_duplicate_rows_falls_back(#[case] marked: bool) { - use bytes::Bytes; - 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; - use store_api::storage::FileId; - - use crate::manifest::action::RegionEdit; - use crate::sst::parquet::PARQUET_METADATA_KEY; - use crate::sst::parquet::metadata::DEDUPED_SST_KEY; - let mut env = TestEnv::new().await; let engine = env .create_engine(MitoConfig { @@ -389,7 +381,6 @@ async fn test_metadata_aggr_replacement_with_duplicate_rows_falls_back(#[case] m .insert_option("compaction.twcs.trigger_file_num", "2") .build(); let table_dir = create.table_dir.clone(); - let path_type = create.path_type; let options = create.options.clone(); let schema = test_util::rows_schema(&create); engine @@ -416,63 +407,10 @@ async fn test_metadata_aggr_replacement_with_duplicate_rows_falls_back(#[case] m .values() .min_by_key(|file| file.time_range().0) .unwrap(); - let store = region.access_layer.object_store(); - let bytes = store - .read(&file.file_path(&table_dir, path_type)) - .await - .unwrap() - .to_bytes(); - let reader = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap(); - let entries = reader - .metadata() - .file_metadata() - .key_value_metadata() - .unwrap(); - assert!(entries.iter().any(|entry| entry.key == DEDUPED_SST_KEY)); - let entries = entries - .iter() - .filter(|entry| { - entry.key == PARQUET_METADATA_KEY || (marked && entry.key == DEDUPED_SST_KEY) - }) - .cloned() - .collect(); - let batch = reader.build().unwrap().next().unwrap().unwrap(); // Preserve physical row count and time bounds, but replace the middle row // with a second put for the first row's (primary key, timestamp). - let duplicate = take_record_batch(&batch, &UInt32Array::from(vec![0, 0, 2])).unwrap(); - let mut replacement_bytes = Vec::new(); - let props = WriterProperties::builder() - .set_key_value_metadata(Some(entries)) - .build(); - let mut writer = - ArrowWriter::try_new(&mut replacement_bytes, duplicate.schema(), Some(props)).unwrap(); - writer.write(&duplicate).unwrap(); - writer.close().unwrap(); - let replacement = crate::sst::file::FileMeta { - file_id: FileId::random(), - file_size: replacement_bytes.len() as u64, - dedup_marker_trusted: true, - ..file.meta_ref().clone() - }; - let replacement_id = replacement.file_id; - store - .write( - &replacement.file_path(&table_dir, path_type), - Bytes::from(replacement_bytes), - ) - .await - .unwrap(); - engine - .edit_region( - region_id, - RegionEdit { - files_to_add: vec![replacement], - files_to_remove: vec![file.meta_ref().clone()], - ..Default::default() - }, - ) - .await - .unwrap(); + let replacement_file = replace_sst_rows(&engine, file, vec![0, 0, 2], marked, None).await; + let replacement_id = replacement_file.file_id(); for reopened in [false, true] { if reopened { @@ -497,6 +435,32 @@ async fn test_metadata_aggr_replacement_with_duplicate_rows_falls_back(#[case] m } } + let cache = engine.cache_manager(); + cache.remove_parquet_meta_data(replacement_file).await; + assert!( + cache + .get_parquet_meta_data_from_mem_cache(replacement_file) + .await + .is_none() + ); + let mut cold = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!(cold.properties().exact_num_rows(), None); + assert!(cold.take_statistics_split().is_none()); + assert_eq!(scanned_rows(cold, request.clone()).await, 5); + assert!( + cache + .get_parquet_meta_data_from_mem_cache(replacement_file) + .await + .is_some() + ); + assert_eq!( + split_rows(&engine, region_id, request.clone()).await, + Some((3, 2)) + ); + compact(&engine, region_id).await; let region = engine.get_region(region_id).unwrap(); let manifest = region.manifest_ctx.manifest().await; @@ -508,6 +472,172 @@ async fn test_metadata_aggr_replacement_with_duplicate_rows_falls_back(#[case] m engine.stop().await.unwrap(); } +#[tokio::test] +async fn test_metadata_aggr_preserves_dedup_across_residual_row_groups() { + use common_time::Timestamp; + + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + experimental_metadata_aggr: true, + schedule_compaction_after_edit: false, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let create = CreateRequestBuilder::new() + .insert_option("append_mode", "false") + .insert_option("memtable.type", "time_series") + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.time_window", "1h") + .insert_option("compaction.twcs.active_window.trigger_file_num", "10") + .insert_option("compaction.twcs.inactive_window.trigger_file_num", "10") + .build(); + let schema = test_util::rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + for group in [ + &[("a", 0), ("a", 10)][..], + &[("a", 0), ("e", 2)], + &[("e", 4), ("i", 4)], + &[("i", 6)], + ] { + let rows = group + .iter() + .flat_map(|&(key, second)| test_util::build_rows_for_key(key, second, second + 1, 0)) + .collect(); + put_and_flush_rows( + &engine, + region_id, + api::v1::Rows { + schema: schema.clone(), + rows, + }, + ) + .await; + } + + let region = engine.get_region(region_id).unwrap(); + let version = region.version(); + let time = Timestamp::new_millisecond(6_000); + let file = version.ssts.levels()[0] + .files + .values() + .find(|file| file.time_range() == (time, time)) + .unwrap(); + let replacement = replace_sst_rows(&engine, file, vec![0, 0], true, Some(1)).await; + let manifest = region.manifest_ctx.manifest().await; + assert_eq!(manifest.files.len(), 4); + let imported = &manifest.files[&replacement.file_id()]; + assert_eq!(imported.num_row_groups, 2); + assert!(!imported.dedup_marker_trusted); + + let request = ScanRequest { + metadata_aggr_hint: true, + ..Default::default() + }; + assert_eq!(plain_rows(&engine, region_id, request.clone()).await, 6); + // The first two files form a group spanning a..e and 0..10s. The exact + // file at 4s joins that group and extends it to include the import at 6s. + // Keep both row groups of the import together after removing the exact file. + assert_eq!(split_rows(&engine, region_id, request).await, Some((2, 4))); + engine.stop().await.unwrap(); +} + +/// Publishes a rewritten SST through the external import path. The selected +/// rows preserve the source file's time and primary-key bounds. +async fn replace_sst_rows( + engine: &MitoEngine, + file: &FileHandle, + row_indices: Vec, + marked: bool, + max_row_group_rows: Option, +) -> RegionFileId { + use bytes::Bytes; + 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; + use store_api::storage::FileId; + + use crate::manifest::action::RegionEdit; + use crate::sst::file::FileMeta; + use crate::sst::parquet::PARQUET_METADATA_KEY; + use crate::sst::parquet::metadata::DEDUPED_SST_KEY; + + let region_id = file.region_id(); + let region = engine.get_region(region_id).unwrap(); + let table_dir = region.access_layer.table_dir(); + let path_type = region.access_layer.path_type(); + let store = region.access_layer.object_store(); + let bytes = store + .read(&file.file_path(table_dir, path_type)) + .await + .unwrap() + .to_bytes(); + let reader = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap(); + let entries = reader + .metadata() + .file_metadata() + .key_value_metadata() + .unwrap(); + assert!(entries.iter().any(|entry| entry.key == DEDUPED_SST_KEY)); + let entries = entries + .iter() + .filter(|entry| { + entry.key == PARQUET_METADATA_KEY || (marked && entry.key == DEDUPED_SST_KEY) + }) + .cloned() + .collect(); + let batch = reader.build().unwrap().next().unwrap().unwrap(); + let batch = take_record_batch(&batch, &UInt32Array::from(row_indices)).unwrap(); + let mut replacement_bytes = Vec::new(); + let props = WriterProperties::builder() + .set_key_value_metadata(Some(entries)) + .set_max_row_group_row_count(max_row_group_rows) + .build(); + let mut writer = + ArrowWriter::try_new(&mut replacement_bytes, batch.schema(), Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + let replacement_bytes = Bytes::from(replacement_bytes); + let num_row_groups = ParquetRecordBatchReaderBuilder::try_new(replacement_bytes.clone()) + .unwrap() + .metadata() + .num_row_groups(); + let replacement = FileMeta { + file_id: FileId::random(), + file_size: replacement_bytes.len() as u64, + num_rows: batch.num_rows() as u64, + num_row_groups: num_row_groups as u64, + dedup_marker_trusted: true, + ..file.meta_ref().clone() + }; + let replacement_id = RegionFileId::new(region_id, replacement.file_id); + store + .write( + &replacement.file_path(table_dir, path_type), + replacement_bytes, + ) + .await + .unwrap(); + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![replacement], + files_to_remove: vec![file.meta_ref().clone()], + ..Default::default() + }, + ) + .await + .unwrap(); + replacement_id +} + #[rstest::rstest] #[case::after_flush(false)] #[case::before_flush_notification(true)] @@ -795,7 +925,7 @@ async fn test_metadata_aggr_falls_back_after_legacy_checkpoint_rewrite() { #[case::non_append_key_filter(false, false, "b", 1)] #[case::append_time_filter(true, false, "a", 2)] #[case::key_overlap(false, true, "b", 1)] -#[case::time_overlap(false, true, "a", 2)] +#[case::time_overlap(false, true, "a", 3)] #[tokio::test] async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back( #[case] append: bool, @@ -841,9 +971,17 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back( let region = engine.get_region(region_id).unwrap(); let store = region.access_layer.object_store().clone(); + let changed_time = replacement_second != 1; + // In the time-overlap case the old file straddles the lower query bound, + // so the ordinary scan cannot prune it using its manifest. + let rows_per_file = if keep_second_file && changed_time { + 2 + } else { + 1 + }; let put = |key, second| 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), }; test_util::put_rows(&engine, region_id, put("a", 1)).await; test_util::flush_region(&engine, region_id, None).await; @@ -854,7 +992,6 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back( .unwrap() .clone(); let ts = || lit(ScalarValue::TimestampMillisecond(Some(1500), None)); - let changed_time = replacement_second != 1; let filters = if keep_second_file { vec![] } else if changed_time { @@ -867,7 +1004,7 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back( metadata_aggr_hint: true, ..Default::default() }; - let time_pruned_request = ScanRequest { + let lower_bound_request = ScanRequest { filters: vec![col("ts").gt_eq(ts())], ..request.clone() }; @@ -879,7 +1016,7 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back( assert_eq!(scan.properties().exact_num_rows(), Some(1)); if changed_time { let scan = engine - .handle_query(region_id, time_pruned_request.clone()) + .handle_query(region_id, lower_bound_request.clone()) .await .unwrap(); assert_eq!(scan.properties().exact_num_rows(), Some(0)); @@ -894,12 +1031,23 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back( .find(|file| file.file_id() != old_file.file_id()) .unwrap() .clone(); + let residual_request = (keep_second_file && changed_time).then(|| lower_bound_request.clone()); if keep_second_file { let scan = engine .handle_query(region_id, request.clone()) .await .unwrap(); - assert_eq!(scan.properties().exact_num_rows(), Some(2)); + assert_eq!(scan.properties().exact_num_rows(), Some(2 * rows_per_file)); + if let Some(residual_request) = &residual_request { + let mut scanner = engine + .handle_query(region_id, residual_request.clone()) + .await + .unwrap(); + let split = scanner + .take_statistics_split() + .expect("disjoint SST bounds"); + assert_eq!(split.exact_rows, rows_per_file); + } } let bytes = store @@ -952,17 +1100,62 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back( // if an older offline replacement left stale bounds there. reads.store(0, Ordering::Relaxed); let scan = engine - .handle_query(region_id, time_pruned_request) + .handle_query(region_id, lower_bound_request) .await .unwrap(); assert_eq!(scan.properties().exact_num_rows(), Some(0)); assert_eq!(reads.load(Ordering::Relaxed), 0); } - let scan = engine + if let Some(residual_request) = &residual_request { + // A cold residual footer leaves the ordinary scan in place. Even the + // other file's footer is unnecessary once the proof cannot succeed. + assert!( + engine + .cache_manager() + .get_parquet_meta_data_from_mem_cache(old_file.file_id()) + .await + .is_none() + ); + reads.store(0, Ordering::Relaxed); + let mut scanner = engine + .handle_query(region_id, residual_request.clone()) + .await + .unwrap(); + assert_eq!(scanner.properties().exact_num_rows(), None); + assert!(scanner.take_statistics_split().is_none()); + assert_eq!(reads.load(Ordering::Relaxed), 0); + } + let mut scan = engine .handle_query(region_id, request.clone()) .await .unwrap(); assert_eq!(scan.properties().exact_num_rows(), None); + assert!(scan.take_statistics_split().is_none()); + if let Some(residual_request) = residual_request { + let cache = engine.cache_manager(); + assert_eq!(reads.load(Ordering::Relaxed), 0); + assert!( + cache + .get_parquet_meta_data_from_mem_cache(old_file.file_id()) + .await + .is_none() + ); + // Preparing either query leaves the untrusted replacement cold. Read + // it through a plain scan before checking the stale cached bounds. + plain_rows(&engine, region_id, residual_request.clone()).await; + assert!( + cache + .get_parquet_meta_data_from_mem_cache(old_file.file_id()) + .await + .is_some() + ); + let mut scanner = engine + .handle_query(region_id, residual_request) + .await + .unwrap(); + assert_eq!(scanner.properties().exact_num_rows(), None); + assert!(scanner.take_statistics_split().is_none()); + } if !keep_second_file { // Execute the same scanner whose statistics were inspected above. let plan = Arc::new(RegionScanExec::new(scan, request, None).unwrap()); @@ -979,6 +1172,232 @@ async fn test_metadata_aggr_replacement_with_stale_bounds_falls_back( engine.stop().await.unwrap(); } +#[tokio::test] +async fn test_metadata_aggr_cold_residual_footer_falls_back_without_reads() { + 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 engine = env + .create_engine(MitoConfig { + experimental_metadata_aggr: true, + enable_write_cache: false, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let residual_file = flush_disjoint_ssts(&engine, region_id).await; + let request = partial_time_request(); + assert_eq!( + split_rows(&engine, region_id, request.clone()).await, + Some((3, 1)) + ); + + let cache = engine.cache_manager(); + cache.remove_parquet_meta_data(residual_file).await; + assert!( + cache + .get_parquet_meta_data_from_mem_cache(residual_file) + .await + .is_none() + ); + reads.store(0, Ordering::Relaxed); + let mut scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert!(scanner.take_statistics_split().is_none()); + assert_eq!(scanner.properties().exact_num_rows(), None); + assert_eq!(reads.load(Ordering::Relaxed), 0); + + let plan = Arc::new(RegionScanExec::new(scanner, request, None).unwrap()); + assert_eq!(count_rows(plan).await, 4); + engine.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_metadata_aggr_discards_split_after_dynamic_filter() { + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + experimental_metadata_aggr: true, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + flush_disjoint_ssts(&engine, region_id).await; + let request = partial_time_request(); + assert_eq!( + split_rows(&engine, region_id, request.clone()).await, + Some((3, 1)) + ); + + let mut scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!(scanner.name(), "SeqScan"); + let time = physical_col("ts", scanner.schema().arrow_schema()).unwrap(); + let predicate = Arc::new(BinaryExpr::new( + time.clone(), + Operator::GtEq, + physical_lit(ScalarValue::TimestampMillisecond(Some(15_000), None)), + )); + let filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![time], predicate)); + assert_eq!( + scanner.add_dyn_filter_to_predicate(vec![filter.clone()]), + vec![true] + ); + assert!(scanner.take_statistics_split().is_none()); + + let scan = Arc::new(RegionScanExec::new(scanner, request, None).unwrap()); + let plan = Arc::new(FilterExec::try_new(filter, scan).unwrap()); + assert_eq!(count_rows(plan).await, 2); + engine.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_metadata_aggr_discards_split_after_range_subset() { + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + experimental_metadata_aggr: true, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + flush_disjoint_ssts(&engine, region_id).await; + let request = partial_time_request(); + + let mut reordered = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + let mut ranges = reordered.properties().partitions[0].clone(); + assert_eq!(ranges.len(), 2); + ranges.reverse(); + let residual_range = *ranges.iter().min_by_key(|range| range.start).unwrap(); + reordered + .prepare(PrepareRequest::default().with_ranges(vec![ranges])) + .unwrap(); + let split = reordered + .take_statistics_split() + .expect("the full range set is preserved"); + assert_eq!(split.exact_rows, 3); + assert_eq!(scanned_rows(split.residual, request.clone()).await, 1); + + let mut scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!(scanner.name(), "SeqScan"); + scanner + .prepare(PrepareRequest::default().with_ranges(vec![vec![residual_range]])) + .unwrap(); + assert!(scanner.take_statistics_split().is_none()); + assert_eq!(scanned_rows(scanner, request).await, 1); + engine.stop().await.unwrap(); +} + +/// Flushes two disjoint, trusted SSTs and returns the ID of the earlier one. +async fn flush_disjoint_ssts(engine: &MitoEngine, region_id: RegionId) -> RegionFileId { + let create = CreateRequestBuilder::new() + .insert_option("append_mode", "false") + .insert_option("memtable.type", "time_series") + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.time_window", "1h") + .build(); + let schema = test_util::rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + for seconds in [&[10, 15, 20][..], &[0, 8][..]] { + let rows = seconds + .iter() + .flat_map(|&second| test_util::build_rows_for_key("a", second, second + 1, 0)) + .collect(); + put_and_flush_rows( + engine, + region_id, + api::v1::Rows { + schema: schema.clone(), + rows, + }, + ) + .await; + } + + let region = engine.get_region(region_id).unwrap(); + let manifest = region.manifest_ctx.manifest().await; + assert_eq!(manifest.files.len(), 2); + assert!( + manifest + .files + .values() + .all(|file| file.dedup_marker_trusted) + ); + let cache = engine.cache_manager(); + // Wait for both asynchronous flush prewarms before a query can load the + // same footer, or an eviction can race a late insertion. + tokio::time::timeout(Duration::from_secs(10), async { + for file in manifest.files.values() { + let id = RegionFileId::new(region_id, file.file_id); + while cache + .get_parquet_meta_data_from_mem_cache(id) + .await + .is_none() + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + }) + .await + .expect("flush metadata prewarming did not complete"); + + let residual = manifest + .files + .values() + .min_by_key(|file| file.time_range.0) + .unwrap(); + RegionFileId::new(region_id, residual.file_id) +} + +fn partial_time_request() -> ScanRequest { + ScanRequest { + filters: vec![col("ts").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(5_000), None)))], + metadata_aggr_hint: true, + ..Default::default() + } +} + +async fn count_rows(plan: Arc) -> i64 { + let ctx = SessionContext::new(); + ctx.register_table("t", Arc::new(CountTable { plan })) + .unwrap(); + let batches = ctx + .sql("SELECT count(*) FROM t") + .await + .unwrap() + .collect() + .await + .unwrap(); + let ScalarValue::Int64(Some(rows)) = + ScalarValue::try_from_array(batches[0].column(0), 0).unwrap() + else { + panic!("expected a non-null Int64 COUNT result"); + }; + rows +} + #[tokio::test] async fn test_metadata_aggr_time_pruning_skips_cold_footers() { let reads = Arc::new(std::sync::Mutex::new(Vec::new())); @@ -1074,6 +1493,9 @@ async fn test_metadata_aggr_statistics_follow_row_visibility() { .handle_query(region_id, request.clone()) .await .unwrap(); + if append { + assert_eq!(scan.properties().exact_num_rows(), None); + } let plan = RegionScanExec::new(scan, request.clone(), None).unwrap(); let row_count = |plan: &RegionScanExec| { StatisticsContext::new() @@ -1196,3 +1618,365 @@ async fn test_metadata_aggr_strict_bound_past_max() { } engine.stop().await.unwrap(); } + +/// Rows a scanner yields. +async fn scanned_rows(scanner: RegionScannerRef, request: ScanRequest) -> usize { + let plan = Arc::new(RegionScanExec::new(scanner, request, None).unwrap()); + datafusion::physical_plan::collect(plan, SessionContext::new().task_ctx()) + .await + .unwrap() + .iter() + .map(|batch| batch.num_rows()) + .sum() +} + +/// Rows a plain scan of the region yields for `request`. +async fn plain_rows(engine: &MitoEngine, region_id: RegionId, request: ScanRequest) -> usize { + let request = ScanRequest { + metadata_aggr_hint: false, + ..request + }; + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + scanned_rows(scanner, request).await +} + +/// The rows a hinted scan counts from metadata and the rows its residual scan +/// yields, or `None` if it does not split. +async fn split_rows( + engine: &MitoEngine, + region_id: RegionId, + request: ScanRequest, +) -> Option<(usize, usize)> { + let mut scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + let split = scanner.take_statistics_split()?; + Some(( + split.exact_rows, + scanned_rows(split.residual, request).await, + )) +} + +/// Metadata rows and residual rows of the hinted scans of +/// [`test_metadata_aggr_fourteen_day_workload`], in its order. +struct FourteenDaySplits { + whole: Option<(usize, usize)>, + from_day_7: Option<(usize, usize)>, + days_5_to_10: Option<(usize, usize)>, + after_put: Option<(usize, usize)>, + after_delete: Option<(usize, usize)>, +} + +/// Days 0..7 are compacted into one file, days 7..13 are separate flushes, +/// and day 13 is still in the memtable. The memtable partition follows the +/// 7-day compaction window, `[7d, 14d)`. +/// +/// - A time-series memtable range is bounded by that partition, so it keeps +/// the files of days 7..13 residual. Only the compacted file is counted +/// from metadata. +/// - A bulk memtable range is bounded by the part it captured, day 13, so +/// every file is counted from metadata. +#[rstest::rstest] +#[case::time_series("primary_key", "time_series", FourteenDaySplits { + whole: Some((7_000, 7_000)), + from_day_7: None, + // The memtable lies outside the query range, so it is not captured and + // bounds nothing; the compacted file is only partly covered. + days_5_to_10: Some((3_000, 2_000)), + // The put creates partition `[14d, 21d)`, the delete `[0, 7d)`. + after_put: Some((7_000, 7_001)), + after_delete: None, +})] +#[case::bulk("flat", "bulk", FourteenDaySplits { + whole: Some((13_000, 1_000)), + from_day_7: Some((6_000, 1_000)), + days_5_to_10: Some((3_000, 2_000)), + after_put: Some((13_000, 1_001)), + // The deletion's part overlaps the compacted file only. + after_delete: Some((6_000, 8_000)), +})] +#[tokio::test] +async fn test_metadata_aggr_fourteen_day_workload( + #[case] sst_format: &str, + #[case] memtable: &str, + #[case] splits: FourteenDaySplits, +) { + use api::v1::value::ValueData; + use store_api::region_request::RegionFlushRequest; + + const DAY_SECONDS: usize = 86_400; + let reads = Arc::new(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_string()); + } + inner + })) + .build() + .unwrap(); + let mut env = TestEnv::new().await.with_mock_layer(layer); + let engine = env + .create_engine(MitoConfig { + experimental_metadata_aggr: true, + min_compaction_interval: Duration::from_secs(3600), + schedule_compaction_after_edit: false, + ..Default::default() + }) + .await; + let region_id = RegionId::new(2, 1); + let create = CreateRequestBuilder::new() + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.time_window", "7d") + .insert_option("compaction.twcs.trigger_file_num", "2") + .insert_option("sst_format", sst_format) + .insert_option("memtable.type", memtable) + .build(); + let schema = test_util::rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + let day_rows = |day: usize| { + let mut rows = test_util::build_rows_for_key("a", 0, 1000, 0); + for (minute, row) in rows.iter_mut().enumerate() { + row.values[2].value_data = Some(ValueData::TimestampMillisecondValue( + ((day * DAY_SECONDS + minute * 60) * 1000) as i64, + )); + } + api::v1::Rows { + schema: schema.clone(), + rows, + } + }; + for day in 0..14 { + test_util::put_rows(&engine, region_id, day_rows(day)).await; + if day < 13 { + engine + .handle_request( + region_id, + RegionRequest::Flush(RegionFlushRequest::default()), + ) + .await + .unwrap(); + } + if day == 6 { + compact(&engine, region_id).await; + } + } + + // Ordinary scans are never split, even with the option enabled. Execute + // the scan once to warm the footers before checking the split's I/O. + let ordinary = ScanRequest::default(); + let mut scanner = engine + .handle_query(region_id, ordinary.clone()) + .await + .unwrap(); + assert!(scanner.take_statistics_split().is_none()); + assert_eq!(scanned_rows(scanner, ordinary).await, 14_000); + + // The residual scanner keeps the properties the metric engine sets after + // Mito returns the scanner. This hinted scan also loads the files' metadata. + let hinted = ScanRequest { + metadata_aggr_hint: true, + ..Default::default() + }; + let mut scanner = engine + .handle_query(region_id, hinted.clone()) + .await + .unwrap(); + scanner.set_logical_region(true); + scanner.set_query_load_region_id(RegionId::new(2, 7)); + let split = scanner.take_statistics_split().unwrap(); + assert_eq!(Some(split.exact_rows), splits.whole.map(|(exact, _)| exact)); + assert!(split.residual.properties().is_logical_region()); + assert_eq!( + split.residual.properties().query_load_region_id(), + Some(RegionId::new(2, 7)) + ); + assert_eq!(split.residual.properties().exact_num_rows(), None); + drop(split); + + let mut scanner = engine + .handle_query(region_id, hinted.clone()) + .await + .unwrap(); + scanner + .prepare( + store_api::region_engine::PrepareRequest::default() + .with_distinguish_partition_range(true), + ) + .unwrap(); + assert!(scanner.take_statistics_split().is_none()); + + // A dynamic predicate invalidates the prepared split. + let mut scanner = engine + .handle_query(region_id, hinted.clone()) + .await + .unwrap(); + scanner.add_dyn_filter_to_predicate(vec![datafusion::physical_plan::expressions::lit(true)]); + assert!(scanner.take_statistics_split().is_none()); + + let ts = |day: i64| { + lit(ScalarValue::TimestampMillisecond( + Some(day * 86_400_000), + None, + )) + }; + // (filters, count, exact count, metadata and residual rows of a split) + for (filters, expected_count, exact, split) in [ + (vec![], 14_000, None, splits.whole), + // The memtable lies outside the query range, so it is not scanned. + (vec![col("ts").lt(ts(7))], 7_000, Some(7_000), None), + (vec![col("ts").gt_eq(ts(7))], 7_000, None, splits.from_day_7), + ( + vec![col("ts").gt_eq(ts(5)).and(col("ts").lt(ts(10)))], + 5_000, + None, + splits.days_5_to_10, + ), + ] { + reads.lock().unwrap().clear(); + let request = ScanRequest { + filters, + ..hinted.clone() + }; + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!(scanner.properties().exact_num_rows(), exact, "{request:?}"); + // The files' metadata is cached, so neither proof opens an SST. + let paths = reads.lock().unwrap().clone(); + assert!(paths.is_empty(), "COUNT opened SSTs: {paths:?}"); + assert_eq!( + split_rows(&engine, region_id, request.clone()).await, + split, + "{request:?}" + ); + assert_eq!( + plain_rows(&engine, region_id, request).await, + expected_count + ); + } + + for (timestamp, delete, expected, split) in [ + (15 * 86_400_000, false, 14_001, splits.after_put), + (86_400_000, true, 14_000, splits.after_delete), + ] { + let mut rows = test_util::build_rows_for_key("a", 0, 1, 0); + rows[0].values[2].value_data = Some(ValueData::TimestampMillisecondValue(timestamp)); + let rows = api::v1::Rows { + schema: schema.clone(), + rows, + }; + let request = if delete { + RegionRequest::Delete(RegionDeleteRequest { + rows, + hint: None, + partition_expr_version: None, + }) + } else { + RegionRequest::Put(RegionPutRequest { + rows, + hint: None, + partition_expr_version: None, + skip_wal: false, + }) + }; + engine.handle_request(region_id, request).await.unwrap(); + assert_eq!(split_rows(&engine, region_id, hinted.clone()).await, split); + assert_eq!( + plain_rows(&engine, region_id, hinted.clone()).await, + expected + ); + } + engine.stop().await.unwrap(); +} + +/// A captured memtable range bounds its rows by its container, not by the +/// rows present when it was captured. File A holds `a@100`, file B holds +/// `b@0` and `b@200`, and the memtable holds `a@memtable_second` when the +/// split is prepared. `a@100` is written again before the split executes. +/// +/// - A time-series range reads its live series set, so it sees the later +/// write. In the same daily partition A overlaps the container and stays +/// residual, although it is disjoint from the memtable's rows. In another +/// partition A is exact, and the later write lands in a partition the scan +/// never captured. +/// - A bulk range reads the parts captured with it, so A is exact even in the +/// same partition, and the later write lands in a part the scan never read. +#[rstest::rstest] +#[case::time_series_same_partition("primary_key", "time_series", 0, None)] +#[case::time_series_other_partition("primary_key", "time_series", 2 * 86_400, Some((1, 1)))] +#[case::bulk_same_partition("flat", "bulk", 0, Some((1, 1)))] +#[tokio::test] +async fn test_metadata_aggr_split_bounds_memtables_by_container( + #[case] sst_format: &str, + #[case] memtable: &str, + #[case] memtable_second: usize, + #[case] split: Option<(usize, usize)>, +) { + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + experimental_metadata_aggr: true, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let create = CreateRequestBuilder::new() + .insert_option("sst_format", sst_format) + .insert_option("memtable.type", memtable) + .build(); + let schema = test_util::rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + let rows = |key: &str, seconds: &[usize]| api::v1::Rows { + schema: schema.clone(), + rows: seconds + .iter() + .flat_map(|&second| test_util::build_rows_for_key(key, second, second + 1, 0)) + .collect(), + }; + put_and_flush_rows(&engine, region_id, rows("a", &[100])).await; + put_and_flush_rows(&engine, region_id, rows("b", &[0, 200])).await; + test_util::put_rows(&engine, region_id, rows("a", &[memtable_second])).await; + + let request = ScanRequest { + filters: vec![col("tag_0").eq(lit("a"))], + metadata_aggr_hint: true, + ..Default::default() + }; + let mut scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + let prepared = scanner.take_statistics_split(); + // Written after the split is prepared, before it executes. + test_util::put_rows(&engine, region_id, rows("a", &[100])).await; + + let actual = match prepared { + Some(prepared) => Some(( + prepared.exact_rows, + scanned_rows(prepared.residual, request.clone()).await, + )), + None => None, + }; + assert_eq!(actual, split); + // Whether or not the scan splits, `a@100` is counted once. + assert_eq!(plain_rows(&engine, region_id, request).await, 2); + engine.stop().await.unwrap(); +} + +async fn put_and_flush_rows(engine: &MitoEngine, region_id: RegionId, rows: api::v1::Rows) { + test_util::put_rows(engine, region_id, rows).await; + test_util::flush_region(engine, region_id, None).await; +} diff --git a/src/mito2/src/flush.rs b/src/mito2/src/flush.rs index 78dda4f5203..61eab02cc37 100644 --- a/src/mito2/src/flush.rs +++ b/src/mito2/src/flush.rs @@ -447,7 +447,7 @@ impl RegionFlushTask { .memtables .immutables() .iter() - .map(|m| m.id()) + .map(|(mem, _)| mem.id()) .collect(); let flush_finished = FlushFinished { region_id: self.region_id, @@ -773,7 +773,7 @@ impl MemtableSstWriter { let mut flush_metrics = Metrics::new(self.kind.write_type()); let partition_expr = parse_partition_expr(self.partition_expr.as_deref())?; let mut all_sst_infos = Vec::new(); - for mem in memtables { + for (mem, _) in memtables { if mem.is_empty() { // Skip empty memtables. continue; @@ -2491,7 +2491,7 @@ mod tests { assert_eq!(1, job_scheduler.num_jobs()); // Check the new version. let version_data = version_control.current(); - assert_eq!(0, version_data.version.memtables.immutables()[0].id()); + assert_eq!(0, version_data.version.memtables.immutables()[0].0.id()); // Schedule remaining tasks. let output_rxs: Vec<_> = tasks .into_iter() @@ -2973,7 +2973,7 @@ mod tests { // Check the new version. let version_data = version_control.current(); - assert_eq!(0, version_data.version.memtables.immutables()[0].id()); + assert_eq!(0, version_data.version.memtables.immutables()[0].0.id()); // Assumes the flush job is finished. version_control.apply_edit( Some(RegionEdit { diff --git a/src/mito2/src/memtable.rs b/src/mito2/src/memtable.rs index 3e704650551..d99379ee5cc 100644 --- a/src/mito2/src/memtable.rs +++ b/src/mito2/src/memtable.rs @@ -863,12 +863,28 @@ pub struct MemtableRange { context: MemtableRangeContextRef, /// Statistics for this memtable range. stats: MemtableStats, + /// Inclusive time range of every row the range can yield, set only when + /// the range reads content captured when it was built. + captured_time_range: Option<(Timestamp, Timestamp)>, } impl MemtableRange { /// Creates a new range from context and stats. pub fn new(context: MemtableRangeContextRef, stats: MemtableStats) -> Self { - Self { context, stats } + Self { + context, + stats, + captured_time_range: None, + } + } + + /// Marks the range as reading immutable content captured when it was + /// built, whose rows all lie in the inclusive `time_range`. Writes after + /// that never reach the range. + #[must_use] + pub(crate) fn with_captured_time_range(mut self, time_range: (Timestamp, Timestamp)) -> Self { + self.captured_time_range = Some(time_range); + self } /// Returns the statistics for this range. @@ -876,6 +892,12 @@ impl MemtableRange { &self.stats } + /// Returns the inclusive time range of the captured content, if the range + /// reads only content captured when it was built. + pub(crate) fn captured_time_range(&self) -> Option<(Timestamp, Timestamp)> { + self.captured_time_range + } + /// Returns the id of the memtable to read. pub fn id(&self) -> MemtableId { self.context.id diff --git a/src/mito2/src/memtable/bulk.rs b/src/mito2/src/memtable/bulk.rs index c67896fe2c2..da3d3759d60 100644 --- a/src/mito2/src/memtable/bulk.rs +++ b/src/mito2/src/memtable/bulk.rs @@ -584,6 +584,7 @@ impl Memtable for BulkMemtable { bulk_parts.unordered_part.to_bulk_part(&self.metadata)? { let part_stats = unordered_bulk_part.to_memtable_stats(&self.metadata); + let captured = part_stats.time_range; let range = MemtableRange::new( Arc::new(MemtableRangeContext::new( self.id, @@ -598,6 +599,11 @@ impl Memtable for BulkMemtable { )), part_stats, ); + // The range reads a snapshot of the unordered part. + let range = match captured { + Some(time_range) => range.with_captured_time_range(time_range), + None => range, + }; ranges.insert(range_id, range); range_id += 1; } @@ -611,6 +617,7 @@ impl Memtable for BulkMemtable { let part_stats = part_wrapper.part.to_memtable_stats(&self.metadata); let charges = vec![part_wrapper.charge.clone()]; + let captured = part_stats.time_range; let iter_builder: Box = match &part_wrapper.part { PartToMerge::Bulk { part, .. } => Box::new(BulkRangeIterBuilder { part: part.clone(), @@ -643,6 +650,11 @@ impl Memtable for BulkMemtable { )), part_stats, ); + // Parts are immutable once added, and the range holds this one. + let range = match captured { + Some(time_range) => range.with_captured_time_range(time_range), + None => range, + }; ranges.insert(range_id, range); range_id += 1; } diff --git a/src/mito2/src/memtable/time_partition.rs b/src/mito2/src/memtable/time_partition.rs index 519ab531dd3..86ca2f76419 100644 --- a/src/mito2/src/memtable/time_partition.rs +++ b/src/mito2/src/memtable/time_partition.rs @@ -38,7 +38,6 @@ use store_api::metadata::RegionMetadataRef; use crate::error; use crate::error::{InvalidRequestSnafu, Result}; use crate::memtable::bulk::part::{BulkPart, BulkPartConverter}; -use crate::memtable::version::SmallMemtableVec; use crate::memtable::{KeyValues, MemtableBuilderRef, MemtableId, MemtableRef}; use crate::sst::{FlatSchemaOptions, to_flat_sst_arrow_schema}; @@ -403,6 +402,20 @@ impl TimePartitions { memtables.extend(inner.parts.iter().map(|part| part.memtable.clone())); } + /// Appends memtables in partitions with their partition time ranges. + pub(crate) fn list_memtables_with_time_ranges( + &self, + memtables: &mut impl Extend<(MemtableRef, PartTimeRange)>, + ) { + let inner = self.inner.lock().unwrap(); + memtables.extend( + inner + .parts + .iter() + .map(|part| (part.memtable.clone(), part.time_range)), + ); + } + /// Returns the number of partitions. pub fn num_partitions(&self) -> usize { let inner = self.inner.lock().unwrap(); @@ -515,12 +528,6 @@ impl TimePartitions { .sum() } - /// Append memtables in partitions to small vec. - pub(crate) fn list_memtables_to_small_vec(&self, memtables: &mut SmallMemtableVec) { - let inner = self.inner.lock().unwrap(); - memtables.extend(inner.parts.iter().map(|part| part.memtable.clone())); - } - /// Returns the next memtable id. pub(crate) fn next_memtable_id(&self) -> MemtableId { let inner = self.inner.lock().unwrap(); @@ -789,9 +796,11 @@ impl PartitionsInner { } } -/// Time range of a partition. -#[derive(Debug, Clone, Copy)] -struct PartTimeRange { +/// Time range of a partition. Writes route every row to the partition whose +/// range contains its timestamp, so the range bounds every row the partition's +/// memtable can ever hold, including rows written later. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct PartTimeRange { /// Inclusive min timestamp of rows in the partition. min_timestamp: Timestamp, /// Exclusive max timestamp of rows in the partition. @@ -815,6 +824,14 @@ impl PartTimeRange { fn contains_timestamp(&self, ts: Timestamp) -> bool { self.min_timestamp <= ts && ts < self.max_timestamp } + + /// Returns the range as inclusive `(min, max)` bounds, or `None` if it + /// holds no timestamp. + pub(crate) fn to_inclusive(self) -> Option<(Timestamp, Timestamp)> { + let max = self.max_timestamp.value().checked_sub(1)?; + let max = Timestamp::new(max, self.max_timestamp.unit()); + (self.min_timestamp <= max).then_some((self.min_timestamp, max)) + } } struct PartitionToWrite<'a> { diff --git a/src/mito2/src/memtable/version.rs b/src/mito2/src/memtable/version.rs index 4ee4154776e..3a52a37dfcc 100644 --- a/src/mito2/src/memtable/version.rs +++ b/src/mito2/src/memtable/version.rs @@ -25,22 +25,20 @@ use store_api::storage::SequenceNumber; use crate::error::Result; use crate::memtable::bulk::part::BulkPart; -use crate::memtable::time_partition::TimePartitions; +use crate::memtable::time_partition::{PartTimeRange, TimePartitions}; use crate::memtable::{KeyValues, MemtableBuilderRef, MemtableId, MemtableRef}; -pub(crate) type SmallMemtableVec = SmallVec<[MemtableRef; 2]>; - /// A version of current memtables in a region. #[derive(Debug, Clone)] pub(crate) struct MemtableVersion { /// Mutable memtable. pub(crate) mutable: MutableMemtablesRef, - /// Immutable memtables. + /// Immutable memtables paired with the time range of their original partition. /// /// We only allow one flush job per region but if a flush job failed, then we /// might need to store more than one immutable memtable on the next time we /// flush the region. - immutables: SmallMemtableVec, + immutables: SmallVec<[(MemtableRef, PartTimeRange); 2]>, /// Whether immutable memtables may contain skip-WAL writes. /// Flushes are serialized per region and cover all immutable memtables. immutable_has_skip_wal_writes: bool, @@ -63,8 +61,8 @@ impl MemtableVersion { self.mutable.has_skip_wal_writes() || self.immutable_has_skip_wal_writes } - /// Immutable memtables. - pub(crate) fn immutables(&self) -> &[MemtableRef] { + /// Immutable memtables and their original partition time ranges. + pub(crate) fn immutables(&self) -> &[(MemtableRef, PartTimeRange)] { &self.immutables } @@ -72,6 +70,18 @@ impl MemtableVersion { pub(crate) fn list_memtables(&self) -> Vec { let mut mems = Vec::with_capacity(self.immutables.len() + self.mutable.num_partitions()); self.mutable.list_memtables(&mut mems); + mems.extend(self.immutables.iter().map(|(mem, _)| mem.clone())); + mems + } + + /// Lists mutable and immutable memtables with the time range of the + /// partition each was created for. A memtable never holds a row outside + /// its partition range, even after later writes. + pub(crate) fn list_memtables_with_time_ranges(&self) -> Vec<(MemtableRef, PartTimeRange)> { + let mut mems = Vec::with_capacity(self.immutables.len() + self.mutable.num_partitions()); + self.mutable + .partitions + .list_memtables_with_time_ranges(&mut mems); mems.extend_from_slice(&self.immutables); mems } @@ -142,7 +152,7 @@ impl MemtableVersion { // Pushes the mutable memtable to immutable list. self.mutable .partitions - .list_memtables_to_small_vec(&mut immutables); + .list_memtables_with_time_ranges(&mut immutables); Ok(Some(MemtableVersion { mutable, @@ -154,12 +164,7 @@ impl MemtableVersion { /// Removes memtables by ids from immutable memtables. pub(crate) fn remove_memtables(&mut self, ids: &[MemtableId]) { - self.immutables = self - .immutables - .iter() - .filter(|mem| !ids.contains(&mem.id())) - .cloned() - .collect(); + self.immutables.retain(|(mem, _)| !ids.contains(&mem.id())); if self.immutables.is_empty() { self.immutable_has_skip_wal_writes = false; } @@ -174,7 +179,7 @@ impl MemtableVersion { pub(crate) fn immutables_usage(&self) -> usize { self.immutables .iter() - .map(|mem| mem.stats().estimated_bytes) + .map(|(mem, _)| mem.stats().estimated_bytes) .sum() } @@ -185,7 +190,7 @@ impl MemtableVersion { + self .immutables .iter() - .map(|mem| mem.stats().decoded_bytes()) + .map(|(mem, _)| mem.stats().decoded_bytes()) .sum::() } @@ -193,7 +198,7 @@ impl MemtableVersion { pub(crate) fn num_rows(&self) -> u64 { self.immutables .iter() - .map(|mem| mem.stats().num_rows as u64) + .map(|(mem, _)| mem.stats().num_rows as u64) .sum::() + self.mutable.num_rows() } @@ -204,6 +209,7 @@ impl MemtableVersion { self.mutable.list_memtables(&mut mutables); self.immutables .iter() + .map(|(mem, _)| mem) .chain(mutables.iter()) .filter_map(|mem| mem.stats().time_range()) .reduce(|(min_a, max_a), (min_b, max_b)| (min_a.min(min_b), max_a.max(max_b))) @@ -362,7 +368,11 @@ mod tests { frozen.mutable.mark_skip_wal_writes(); } frozen.mutable.write(&kvs).unwrap(); - let ids: Vec<_> = frozen.immutables().iter().map(|mem| mem.id()).collect(); + let ids: Vec<_> = frozen + .immutables() + .iter() + .map(|(mem, _)| mem.id()) + .collect(); frozen.remove_memtables(&ids); assert_eq!(new_skip_wal_writes, frozen.has_skip_wal_writes()); assert_eq!( @@ -377,7 +387,11 @@ mod tests { .freeze_mutable(&metadata, Some(Duration::from_secs(5))) .unwrap() .unwrap(); - let ids: Vec<_> = next_flush.immutables().iter().map(|mem| mem.id()).collect(); + let ids: Vec<_> = next_flush + .immutables() + .iter() + .map(|(mem, _)| mem.id()) + .collect(); next_flush.remove_memtables(&ids); assert!(!next_flush.has_skip_wal_writes()); } @@ -418,7 +432,11 @@ mod tests { .unwrap(); assert_eq!(2, retried.immutables().len()); assert!(retried.has_skip_wal_writes()); - let ids: Vec<_> = retried.immutables().iter().map(|mem| mem.id()).collect(); + let ids: Vec<_> = retried + .immutables() + .iter() + .map(|(mem, _)| mem.id()) + .collect(); retried.remove_memtables(&ids); assert!(!retried.has_skip_wal_writes()); @@ -431,4 +449,58 @@ mod tests { assert!(!replacement.has_skip_wal_writes()); assert!(frozen.has_skip_wal_writes()); } + + #[test] + fn test_partition_time_ranges_follow_memtables() { + let metadata = memtable_util::metadata_for_test(); + let partitions = TimePartitions::new( + metadata.clone(), + Arc::new(TimeSeriesMemtableBuilder::default()), + 0, + Some(Duration::from_secs(5)), + ); + let version = MemtableVersion::new(partitions); + for ts in [1000, 7000] { + let kvs = memtable_util::build_key_values(&metadata, "hello".to_string(), 0, &[ts], 1); + version.mutable.write(&kvs).unwrap(); + } + let ranges = |version: &MemtableVersion| { + let mut ranges: Vec<_> = version + .list_memtables_with_time_ranges() + .into_iter() + .map(|(mem, range)| { + let (min, max) = range.to_inclusive().unwrap(); + (mem.id(), min.value(), max.value()) + }) + .collect(); + ranges.sort_unstable(); + ranges + }; + // The upper bound of a partition is exclusive. + assert_eq!(ranges(&version), [(0, 0, 4999), (1, 5000, 9999)]); + + // Frozen memtables keep their partition ranges. The forked mutable + // memtable covers the partition of the latest row. + let mut frozen = version + .freeze_mutable(&metadata, Some(Duration::from_secs(5))) + .unwrap() + .unwrap(); + assert_eq!( + ranges(&frozen), + [(0, 0, 4999), (1, 5000, 9999), (2, 5000, 9999)] + ); + let snapshot = frozen.clone(); + frozen.remove_memtables(&[0]); + assert_eq!(ranges(&frozen), [(1, 5000, 9999), (2, 5000, 9999)]); + let [(remaining, range)] = frozen.immutables() else { + panic!("expected one immutable memtable after removing the first partition"); + }; + assert_eq!(remaining.id(), 1); + let (min, max) = range.to_inclusive().unwrap(); + assert_eq!((min.value(), max.value()), (5000, 9999)); + assert_eq!( + ranges(&snapshot), + [(0, 0, 4999), (1, 5000, 9999), (2, 5000, 9999)] + ); + } } diff --git a/src/mito2/src/read/pruner.rs b/src/mito2/src/read/pruner.rs index df0be133a6e..098c7957abb 100644 --- a/src/mito2/src/read/pruner.rs +++ b/src/mito2/src/read/pruner.rs @@ -809,11 +809,7 @@ mod tests { .build(); let query_start = input.query_start.unwrap_or_else(Instant::now); let ranges = RangeMeta::unordered_scan_ranges(&input).await; - let stream_ctx = Arc::new(StreamContext::unordered_scan_ctx( - input, - ranges, - query_start, - )); + let stream_ctx = Arc::new(StreamContext::with_ranges(input, ranges, query_start)); let pruner = Arc::new(Pruner::new(stream_ctx, 1)); (env, pruner) } @@ -867,11 +863,7 @@ mod tests { .build(); let query_start = input.query_start.unwrap_or_else(Instant::now); let ranges = RangeMeta::unordered_scan_ranges(&input).await; - let stream_ctx = Arc::new(StreamContext::unordered_scan_ctx( - input, - ranges, - query_start, - )); + let stream_ctx = Arc::new(StreamContext::with_ranges(input, ranges, query_start)); let pruner = Arc::new(Pruner::new(stream_ctx, 1)); (env, pruner) } diff --git a/src/mito2/src/read/range.rs b/src/mito2/src/read/range.rs index 47310647a75..e39fa83efef 100644 --- a/src/mito2/src/read/range.rs +++ b/src/mito2/src/read/range.rs @@ -71,6 +71,60 @@ pub(crate) struct RangeMeta { } impl RangeMeta { + /// Retains the sources mapped into `input` and keeps their row groups in + /// this range together for deduplication. + pub(crate) fn remap_sources( + &self, + mapping: &[Option], + input: &ScanInput, + ) -> Option { + let indices: SmallVec<[SourceIndex; 2]> = self + .indices + .iter() + .filter_map(|source| { + Some(SourceIndex { + index: mapping[source.index]?, + ..*source + }) + }) + .collect(); + if indices.is_empty() { + return None; + } + let row_group_indices = self + .row_group_indices + .iter() + .filter_map(|row_group| { + Some(RowGroupIndex { + index: mapping[row_group.index]?, + ..*row_group + }) + }) + .collect(); + let num_rows = if indices.len() == self.indices.len() { + self.num_rows + } else { + // A multi-source sequential range contains all row groups of each source. + indices + .iter() + .map(|source| { + if source.index < input.num_memtables() { + input.memtables[source.index].stats().num_rows() + } else { + input.files[source.index - input.num_memtables()].num_rows() + } + }) + .fold(0, usize::saturating_add) + }; + Some(Self { + // Keep the original bounds used for time filtering. + time_range: self.time_range, + indices, + row_group_indices, + num_rows, + }) + } + /// Creates a [PartitionRange] with specific identifier. /// It converts the inclusive max timestamp to exclusive end timestamp. pub(crate) fn new_partition_range(&self, identifier: usize) -> PartitionRange { @@ -532,12 +586,33 @@ pub(crate) struct MemRangeBuilder { range: MemtableRange, /// Stats of a memtable. stats: MemtableStats, + /// Inclusive time range of every row the range can yield, including rows + /// written to its memtable after the range was built. `None` if unknown. + /// Unlike `stats`, it never shrinks to the rows present at build time. + container_time_range: Option<(Timestamp, Timestamp)>, } impl MemRangeBuilder { /// Builds a mem range builder from row groups. pub(crate) fn new(range: MemtableRange, stats: MemtableStats) -> Self { - Self { range, stats } + Self { + range, + stats, + container_time_range: None, + } + } + + /// Sets the inclusive time range bounding every row the range can yield. + #[must_use] + pub(crate) fn with_container_time_range(mut self, time_range: (Timestamp, Timestamp)) -> Self { + self.container_time_range = Some(time_range); + self + } + + /// Returns the inclusive time range bounding every row the range can + /// yield, or `None` if it is unknown. + pub(crate) fn container_time_range(&self) -> Option<(Timestamp, Timestamp)> { + self.container_time_range } /// Builds mem ranges to read in the memtable. diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index 6cbcdfc48e7..292ea7c0316 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -15,6 +15,7 @@ //! Scans a region according to the scan request. mod aggr; +pub(crate) use aggr::StatisticsSplitPlan; #[cfg(any(test, feature = "test", feature = "testing"))] pub use aggr::overlap as metadata_aggr_overlap; @@ -418,7 +419,8 @@ impl ScanRegion { let input = self.scan_input().await?; let query_start = input.query_start.unwrap_or_else(Instant::now); let ranges = RangeMeta::unordered_scan_ranges(&input).await; - let stream_ctx = StreamContext::unordered_scan_ctx(input, ranges, query_start); + READ_SST_COUNT.observe(input.num_files() as f64); + let stream_ctx = StreamContext::with_ranges(input, ranges, query_start); Ok(UnorderedScan::new(stream_ctx)) } @@ -452,6 +454,9 @@ impl ScanRegion { /// Creates a scan input. #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))] async fn scan_input(mut self) -> Result { + // Only SeqScan consumes a split. Other scanners can still use a + // full count when every source is covered. + let allow_partial = !self.use_unordered_scan() && !self.use_series_scan(); let metadata = &self.version.metadata; let sst_min_sequence = self.request.sst_min_sequence.and_then(NonZeroU64::new); let time_range = self.build_time_range_predicate(); @@ -491,7 +496,7 @@ impl ScanRegion { } .fail(); } - let memtables = self.version.memtables.list_memtables(); + let memtables = self.version.memtables.list_memtables_with_time_ranges(); // Skip empty memtables and memtables out of time range. let mut mem_range_builders = Vec::new(); // Narthex may serve raw-series output, which deduplicates append rows. @@ -512,7 +517,7 @@ impl ScanRegion { ) }; - for m in memtables { + for (m, partition_range) in memtables { // check if memtable is empty by reading stats. let Some((start, end)) = m.stats().time_range() else { continue; @@ -532,9 +537,18 @@ impl ScanRegion { )) .with_pre_filter_mode(filter_mode), )?; + // A range bounds its rows by its captured content when it has one, + // otherwise by its partition: memtables may keep accepting writes + // after the range is built, but only inside their partition. + let partition_range = partition_range.to_inclusive(); mem_range_builders.extend(ranges_in_memtable.ranges.into_values().map(|v| { let stats = v.stats().clone(); - MemRangeBuilder::new(v, stats) + let container = v.captured_time_range().or(partition_range); + let builder = MemRangeBuilder::new(v, stats); + match container { + Some(time_range) => builder.with_container_time_range(time_range), + None => builder, + } })); } @@ -633,10 +647,22 @@ 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 { - // 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; + if self.experimental_metadata_aggr + && self.request.metadata_aggr_hint + && !(input.append_mode + && input.predicate_group().predicate_without_region().is_none() + && input.source_row_counts_are_exact()) + { + // Reuse the scan's manifest time pruning, even for manifests from + // older offline tools. + match aggr::prepare(&input, &self.request, 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 => {} + } } Ok(input) } @@ -937,6 +963,8 @@ pub struct ScanInput { pub(crate) exact_num_rows: Option, /// Whether the request leaves the source rows visible before predicates. row_preserving_request: bool, + /// Exact and residual sources of a hinted COUNT, taken by the scanner. + pub(crate) statistics_split: Option, /// Pinned series-index snapshot and its storage, when configured. /// Whether to ignore range indexes while retaining series-index candidate discovery. /// Region SST access layer. @@ -1016,6 +1044,7 @@ pub struct ScanInput { /// Cached output of scan request analysis: the optional range-cache fingerprint /// plus the derived implied time range used by range cache and prefilter. +#[derive(Clone)] struct ScanAnalysis { /// `None` when the scan is not eligible for range caching. fingerprint: Option, @@ -1033,6 +1062,60 @@ pub(crate) struct ScanInputBuilder { } impl ScanInput { + /// Returns this scan restricted to the given sources, sharing the read + /// view and every query setting. Opens no SST data. + pub(crate) fn with_sources( + &self, + files: Vec, + memtables: Vec, + ) -> Option { + #[cfg(feature = "enterprise")] + if !self.extension_ranges.is_empty() { + return None; + } + Some(Self { + exact_num_rows: None, + row_preserving_request: self.row_preserving_request, + statistics_split: None, + page_index_policy: self.page_index_policy, + access_layer: self.access_layer.clone(), + mapper: self.mapper.clone(), + read_cols: self.read_cols.clone(), + time_range: self.time_range, + scan_analysis: self.scan_analysis.clone(), + predicate: self.predicate.clone(), + region_partition_expr: self.region_partition_expr.clone(), + memtables, + files, + narthex_series_indexes: self.narthex_series_indexes.clone(), + narthex_format: self.narthex_format, + primary_key_mapper: self.primary_key_mapper.clone(), + batch_size: self.batch_size, + cache_strategy: self.cache_strategy.clone(), + ignore_file_not_found: self.ignore_file_not_found, + max_concurrent_scan_files: self.max_concurrent_scan_files, + scan_memory_tracker: self.scan_memory_tracker.clone(), + inverted_index_appliers: self.inverted_index_appliers.clone(), + bloom_filter_index_appliers: self.bloom_filter_index_appliers.clone(), + fulltext_index_appliers: self.fulltext_index_appliers.clone(), + query_start: self.query_start, + append_mode: self.append_mode, + filter_deleted: self.filter_deleted, + merge_mode: self.merge_mode, + series_row_selector: self.series_row_selector, + distribution: self.distribution, + explain_flat_format: self.explain_flat_format, + snapshot_sequence: self.snapshot_sequence, + sequence_range: self.sequence_range, + compaction: self.compaction, + compaction_read_parallelism: self.compaction_read_parallelism, + json2_rewrite_targets: self.json2_rewrite_targets.clone(), + query_stat_counters: self.query_stat_counters.clone(), + #[cfg(feature = "enterprise")] + extension_ranges: Vec::new(), + }) + } + /// Creates a new [ScanInputBuilder]. #[must_use] pub(crate) fn builder( @@ -1043,6 +1126,7 @@ impl ScanInput { input: ScanInput { exact_num_rows: None, row_preserving_request: true, + statistics_split: None, page_index_policy: None, access_layer, read_cols: mapper.read_columns().clone(), @@ -2187,20 +2271,15 @@ impl StreamContext { let query_start = input.query_start.unwrap_or_else(Instant::now); let ranges = RangeMeta::seq_scan_ranges(&input); READ_SST_COUNT.observe(input.num_files() as f64); - Self { - input, - ranges, - query_start, - } + Self::with_ranges(input, ranges, query_start) } - /// Creates a new [StreamContext] for [UnorderedScan]. - pub(crate) fn unordered_scan_ctx( + /// Creates a new [StreamContext] with the caller's range layout. + pub(crate) fn with_ranges( input: ScanInput, ranges: Vec, query_start: Instant, ) -> Self { - READ_SST_COUNT.observe(input.num_files() as f64); Self { input, ranges, diff --git a/src/mito2/src/read/scan_region/aggr.rs b/src/mito2/src/read/scan_region/aggr.rs index 13612adc5cb..23e7f7925ba 100644 --- a/src/mito2/src/read/scan_region/aggr.rs +++ b/src/mito2/src/read/scan_region/aggr.rs @@ -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::ParquetMetaData; +use parquet::file::metadata::{PageIndexPolicy, ParquetMetaData}; use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::{ColumnMetadata, RegionMetadata}; use store_api::storage::{ColumnId, ScanRequest}; @@ -43,43 +43,133 @@ use crate::sst::parquet::metadata::{ extract_primary_key_range, extract_time_range, has_deduped_sst_marker, has_only_puts, }; -/// 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) -> Option { - let classification = classify(input, request)?; - if input.append_mode && request.filters.is_empty() { - return Some(classification.exact_rows); - } - 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()?; - Some(classification.exact_rows) +/// What the manifest and SST statistics prove about the row count of a +/// hinted scalar COUNT scan. +pub(crate) enum MetadataAggr { + /// The whole scan yields exactly this many rows. + Exact(usize), + /// Some files are exact; the rest of the sources must still be scanned. + Split(StatisticsSplitPlan), } -fn time_bounds_match(file: &FileHandle, sst: &CachedSstMeta, time_id: ColumnId) -> bool { +/// Disjoint source sets for an exact part and a residual scan of one read view. +pub(crate) struct StatisticsSplitPlan { + /// Sum of the manifest row counts of the files whose rows are all yielded + /// exactly once, without other sources. + pub(crate) exact_rows: usize, + /// Indexes into `ScanInput::files` of the other files intersecting the query + /// time range. Memtable ranges always stay in the residual scan. + pub(crate) remaining_file_indices: Vec, +} + +/// Classifies sources once. 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, + allow_partial: bool, +) -> Option { + if !allow_partial && !input.memtables.is_empty() { + return None; + } + let classification = classify(input, request, allow_partial)?; + if !allow_partial && !classification.remaining.is_empty() { + return None; + } + if classification.exact.is_empty() + && (!classification.remaining.is_empty() || !input.memtables.is_empty()) + { + return None; + } + if input.append_mode && request.filters.is_empty() { + return resolve(input, classification, allow_partial); + } + let mut classification = classification; + let check_overlap = + !input.append_mode && classification.exact.len() + classification.remaining.len() > 1; + if check_overlap { + verify_residual_bounds(input, &classification.remaining).await?; + } + let check_keys = classification.key_filter || check_overlap; + let check_rows = !input.append_mode; + let proven: Vec<_> = futures::stream::iter(classification.exact.iter().copied()) + .map(|index| file_evidence(input, input.files[index].clone(), check_keys, check_rows)) + .buffered(input.max_concurrent_scan_files.max(1)) + .try_collect() + .await + .ok()?; + classification.retain_exact(input, &proven); + resolve(input, classification, allow_partial) +} + +/// Applies the footer evidence of the exact candidates. +fn resolve( + input: &ScanInput, + classification: Classification, + allow_partial: bool, +) -> Option { + if classification.remaining.is_empty() && input.memtables.is_empty() { + return Some(MetadataAggr::Exact(classification.exact_rows)); + } + if !allow_partial || classification.exact.is_empty() { + return None; + } + Some(MetadataAggr::Split(StatisticsSplitPlan { + exact_rows: classification.exact_rows, + remaining_file_indices: classification.remaining, + })) +} + +/// Reuses ordinary scan pruning for files the residual cannot read. For files +/// it can read, a stale bound (e.g. from older offline replacement) could +/// hide an overlap with an exact candidate. Only consult memory for these +/// bounds and let the ordinary scan handle a cache miss. +async fn verify_residual_bounds(input: &ScanInput, remaining: &[usize]) -> Option<()> { + let time_id = input.region_metadata().time_index_column().column_id; + for &index in remaining { + let file = &input.files[index]; + if input.can_manifest_prune_file(file) { + continue; + } + let sst = input + .cache_strategy + .get_sst_meta_data_from_mem_cache(file.file_id(), PageIndexPolicy::Skip) + .await?; + if !bounds_match(file, &sst, time_id, true) { + return None; + } + } + Some(()) +} + +fn bounds_match( + file: &FileHandle, + sst: &CachedSstMeta, + time_id: ColumnId, + check_keys: bool, +) -> bool { let region = sst.region_metadata(); let time_index = region.time_index_column(); let (start, end) = file.time_range(); + let metadata = sst.parquet_metadata(); time_index.column_id == time_id - && extract_time_range(&sst.parquet_metadata(), time_index).is_some_and(|(min, max)| { + && extract_time_range(&metadata, time_index).is_some_and(|(min, max)| { start.unit() == min.unit() && end.unit() == max.unit() && (start, end) == (min, max) }) + && (!check_keys + || file + .raw_primary_key_range() + .is_none_or(|range| extract_primary_key_range(&metadata, ®ion) == Some(range))) } -/// Proves the bounds and visible rows required for this exact candidate. +/// 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<(), ()>> { +) -> BoxFuture<'static, Result> { let time_id = input.region_metadata().time_index_column().column_id; let reader = input .access_layer @@ -92,19 +182,10 @@ fn file_evidence( file.file_id() ); })?; - let metadata = sst.parquet_metadata(); - if !time_bounds_match(&file, &sst, time_id) { + if !bounds_match(&file, &sst, time_id, check_keys) { 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(()) + Ok(!check_rows || footer_proves_visible_rows(&sst.parquet_metadata(), file.num_rows())) } .boxed() } @@ -130,12 +211,32 @@ 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, + /// Indexes of the other files intersecting the query time range. + remaining: Vec, /// 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`]). @@ -146,11 +247,12 @@ struct 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) -> Option { - if !input.memtables.is_empty() - || !input.allows_exact_row_count() - || !request_preserves_rows(request) - { +fn classify( + input: &ScanInput, + request: &ScanRequest, + allow_partial: bool, +) -> Option { + if !input.allows_exact_row_count() || !request_preserves_rows(request) { return None; } let filters = AggrFilters::new(input.region_metadata(), &request.filters)?; @@ -173,36 +275,73 @@ fn classify(input: &ScanInput, request: &ScanRequest) -> Option && input.file_time_bounds_fit(file) && (input.region_partition_expr.is_none() || input.should_skip_region_partition(file)) && filters.covers(file); - if !candidate { + if !candidate && !allow_partial { return None; } - intersecting.push(index); + intersecting.push((index, candidate)); } - 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, + // 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, 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 range +/// may hold a row with the same primary key and timestamp. +/// +/// Uses manifest bounds for the overlap check. Preparation verifies the bounds +/// of files that can affect the count. Files pruned by the ordinary scan use +/// the same manifest bounds without rechecking their footers. +/// +/// A memtable range is bounded by its container, the time range of every row +/// it can ever yield (see [`MemRangeBuilder::container_time_range`]), not by +/// the rows it held when it was captured: a time-series memtable keeps +/// accepting writes into its partition and its ranges read them. A range +/// without a known container overlaps every file. Containers carry no key +/// bounds, so a file overlapping one in time stays residual. +/// +/// [`MemRangeBuilder::container_time_range`]: crate::read::range::MemRangeBuilder::container_time_range +fn overlapping_files(input: &ScanInput, files: &[(usize, bool)]) -> Vec { + 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(); + for memtable in &input.memtables { + match memtable.container_time_range() { + Some(time) => extents.push(Extent { time, key: None }), + 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. @@ -341,15 +480,19 @@ mod tests { use table::predicate::build_time_range_predicate; use super::*; + use crate::memtable::{ + BoxedBatchIterator, BoxedRecordBatchIterator, IterBuilder, MemScanMetrics, MemtableRange, + MemtableRangeContext, MemtableStats, + }; use crate::read::flat_projection::FlatProjectionMapper; + use crate::read::range::MemRangeBuilder; use crate::read::scan_region::PredicateGroup; use crate::sst::file::FileMeta; use crate::test_util::memtable_util::metadata_with_primary_key; use crate::test_util::new_noop_file_purger; use crate::test_util::scheduler_util::SchedulerEnv; - /// Files whose `__op_type` statistics would show deletions. Unit tests - /// have no Parquet files; engine tests cover reading the statistics. + /// Synthetic delete evidence for tests that only exercise classification. static WITH_DELETES: LazyLock>> = LazyLock::new(Default::default); fn file(start: i64, end: i64, rows: u64, no_deletes: bool) -> FileHandle { @@ -407,22 +550,101 @@ mod tests { ) } - fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option { - let classification = classify(input, request)?; - let deletes = WITH_DELETES.lock().unwrap(); + /// Footer evidence for the synthetic files in these classification tests. + fn evidence(input: &ScanInput, classification: &Classification) -> Vec { + let with_deletes = WITH_DELETES.lock().unwrap(); classification .exact .iter() - .all(|&i| input.append_mode || !deletes.contains(&input.files[i].meta_ref().file_id)) - .then_some(classification.exact_rows) + .map(|&index| { + input.append_mode || !with_deletes.contains(&input.files[index].meta_ref().file_id) + }) + .collect() + } + + /// [`prepare`] with the test's footer evidence. + fn counted(input: &ScanInput, request: &ScanRequest) -> Option { + let mut classification = classify(input, request, true)?; + let no_deletes = evidence(input, &classification); + classification.retain_exact(input, &no_deletes); + resolve(input, classification, true) + } + + fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option { + match counted(input, request)? { + MetadataAggr::Exact(rows) => Some(rows), + MetadataAggr::Split(_) => None, + } + } + + 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 + } + + struct EmptyIterBuilder; + + impl IterBuilder for EmptyIterBuilder { + fn build(&self, _: Option) -> crate::error::Result { + Ok(Box::new(std::iter::empty())) + } + + fn is_record_batch(&self) -> bool { + true + } + + fn build_record_batch( + &self, + _: Option<(Timestamp, Timestamp)>, + _: Option, + ) -> crate::error::Result { + Ok(Box::new(std::iter::empty())) + } + } + + /// A memtable range holding `rows` rows within `data`, inside `container`. + fn memtable(data: (i64, i64), container: Option<(i64, i64)>, rows: usize) -> MemRangeBuilder { + let ms = |(start, end): (i64, i64)| { + ( + Timestamp::new_millisecond(start), + Timestamp::new_millisecond(end), + ) + }; + let stats = MemtableStats { + time_range: Some(ms(data)), + num_rows: rows, + num_ranges: 1, + ..Default::default() + }; + let context = Arc::new(MemtableRangeContext::new( + 0, + Box::new(EmptyIterBuilder), + Default::default(), + )); + let builder = MemRangeBuilder::new(MemtableRange::new(context, stats.clone()), stats); + match container { + Some(container) => builder.with_container_time_range(ms(container)), + None => builder, + } } async fn input(files: Vec, filters: &[Expr]) -> ScanInput { + input_with_memtables(files, filters, Vec::new()).await + } + + async fn input_with_memtables( + files: Vec, + filters: &[Expr], + memtables: Vec, + ) -> ScanInput { let env = SchedulerEnv::new().await; let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false)); let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap(); ScanInput::builder(env.access_layer.clone(), mapper) .with_files(files) + .with_memtables(memtables) .with_predicate(PredicateGroup::new(&metadata, filters).unwrap()) .with_time_range(Some(build_time_range_predicate( "ts", @@ -522,6 +744,18 @@ 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] @@ -571,6 +805,52 @@ 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; @@ -717,4 +997,247 @@ mod tests { assert_eq!(input.scanner_properties().total_rows_is_exact(), fits); } } + + #[tokio::test] + async fn test_metadata_aggr_split_plan() { + use api::v1::OpType; + use datatypes::arrow::array::{TimestampMillisecondArray, UInt8Array}; + use datatypes::arrow::record_batch::RecordBatch; + use parquet::file::statistics::Statistics; + use store_api::storage::consts::OP_TYPE_COLUMN_NAME; + + use crate::access_layer::{Metrics, OperationType, SstWriteRequest, WriteType}; + use crate::cache::{CacheManager, CacheStrategy}; + use crate::region::options::MergeMode; + use crate::sst::FormatType; + use crate::sst::parquet::WriteOptions; + use crate::test_util::sst_util::{ + new_flat_source_from_record_batches, new_record_batch_by_range, sst_region_metadata, + }; + + let env = SchedulerEnv::new().await; + let metadata = Arc::new(sst_region_metadata()); + let cache = Arc::new( + CacheManager::builder() + .sst_meta_cache_size(1024 * 1024) + .disable_sst_meta_cache_on_write() + .build(), + ); + let cache_strategy = CacheStrategy::EnableAll(cache.clone()); + let put = OpType::Put as u8; + let delete = OpType::Delete as u8; + let mut files = Vec::new(); + for (timestamps, operations) in [ + (vec![10_000, 15_000, 20_000], vec![put; 3]), + (vec![0, 8_000], vec![put, delete]), + ] { + let batch = new_record_batch_by_range(&["a", "b"], 0, timestamps.len()); + let schema = batch.schema(); + let mut columns = batch.columns().to_vec(); + columns[schema.index_of("ts").unwrap()] = + Arc::new(TimestampMillisecondArray::from(timestamps)); + let has_delete = operations.contains(&delete); + columns[schema.index_of(OP_TYPE_COLUMN_NAME).unwrap()] = + Arc::new(UInt8Array::from(operations)); + let batch = RecordBatch::try_new(schema, columns).unwrap(); + let source = new_flat_source_from_record_batches(vec![batch]) + .with_dedup_mode(Some(MergeMode::LastRow)); + let output = env + .access_layer + .write_sst( + SstWriteRequest { + index_build_inputs: None, + op_type: OperationType::Flush, + metadata: metadata.clone(), + source, + cache_manager: cache.clone(), + max_sequence: None, + sst_write_format: FormatType::Flat, + preserve_row_sequence: false, + index_options: Default::default(), + index_config: Default::default(), + inverted_index_config: Default::default(), + fulltext_index_config: Default::default(), + bloom_filter_index_config: Default::default(), + }, + &WriteOptions::default(), + &mut Metrics::new(WriteType::Flush), + ) + .await + .unwrap(); + assert_eq!(output.len(), 1); + let info = &output[0]; + let footer = info.file_metadata.as_ref().unwrap(); + assert!(has_deduped_sst_marker(footer)); + assert_eq!(has_only_puts(footer.row_groups()), !has_delete); + if has_delete { + let op_column = footer + .row_group(0) + .columns() + .iter() + .find(|column| column.column_path().string() == OP_TYPE_COLUMN_NAME) + .unwrap(); + let Some(Statistics::Int32(stats)) = op_column.statistics() else { + panic!("expected op-type statistics"); + }; + assert_eq!(stats.min_opt().copied(), Some(i32::from(put.min(delete)))); + assert_eq!(stats.max_opt().copied(), Some(i32::from(put.max(delete)))); + } + let (min, max) = extract_primary_key_range(footer, &metadata).unwrap(); + let file = FileHandle::new( + FileMeta { + region_id: metadata.region_id, + file_id: info.file_id, + file_size: info.file_size, + time_range: info.time_range, + num_rows: info.num_rows as u64, + num_row_groups: info.num_row_groups, + primary_key_min: Some(min), + primary_key_max: Some(max), + dedup_marker_trusted: true, + format: info.format.clone(), + ..Default::default() + }, + new_noop_file_purger(), + ); + assert!(file.dedup_marker_trusted()); + files.push(file); + } + let residual = &files[1]; + let build_input = |request: &ScanRequest| { + let mapper = FlatProjectionMapper::new(&metadata, [0, 1, 2, 3]).unwrap(); + ScanInput::builder(env.access_layer.clone(), mapper) + .with_files(files.clone()) + .with_cache(cache_strategy.clone()) + .with_predicate(PredicateGroup::new(&metadata, &request.filters).unwrap()) + .with_time_range(Some(build_time_range_predicate( + "ts", + TimeUnit::Millisecond, + &request.filters, + ))) + .build() + }; + let assert_split = |result| { + let Some(MetadataAggr::Split(plan)) = result else { + panic!("expected metadata and residual sources"); + }; + assert_eq!(plan.exact_rows, 3); + let [index] = plan.remaining_file_indices.as_slice() else { + panic!("expected one residual file"); + }; + assert_eq!(files[*index].file_id(), residual.file_id()); + }; + let request = ScanRequest { + metadata_aggr_hint: true, + ..Default::default() + }; + let input = build_input(&request); + assert_eq!(classify(&input, &request, true).unwrap().exact.len(), 2); + assert_split(prepare(&input, &request, true).await); + + let request = ScanRequest { + filters: vec![ + col("ts").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(5_000), None))), + ], + ..request + }; + let input = build_input(&request); + assert_eq!(classify(&input, &request, true).unwrap().remaining, vec![1]); + assert!(!input.can_manifest_prune_file(residual)); + let footer = env + .access_layer + .read_sst(residual.clone()) + .cache(cache_strategy.clone()) + .read_statistics() + .await + .unwrap(); + assert!(bounds_match( + residual, + &footer, + metadata.time_index_column().column_id, + true + )); + assert!( + cache + .get_parquet_meta_data_from_mem_cache(residual.file_id()) + .await + .is_some() + ); + assert_split(prepare(&input, &request, true).await); + + cache.remove_parquet_meta_data(residual.file_id()).await; + assert!( + cache + .get_parquet_meta_data_from_mem_cache(residual.file_id()) + .await + .is_none() + ); + assert!(prepare(&input, &request, true).await.is_none()); + } + + #[tokio::test] + async fn test_metadata_aggr_split_plan_unknown_and_no_exact() { + let split = |files| async move { + match counted(&input(files, &[]).await, &ScanRequest::default()) { + Some(MetadataAggr::Split(plan)) => { + Some((plan.exact_rows, plan.remaining_file_indices.len())) + } + Some(MetadataAggr::Exact(_)) => panic!("unexpected exact count"), + None => None, + } + }; + // A residual file with an unknown row count is scanned as usual. + assert_eq!( + split(vec![file(0, 10, 3, true), file(20, 30, 0, true)]).await, + Some((3, 1)) + ); + // Without an exact file the scan stays unchanged. + assert_eq!( + split(vec![file(0, 10, 3, true), file(5, 15, 2, true)]).await, + None + ); + } + + /// Memtable ranges are bounded by their containers, never by the rows + /// they held when captured. + #[tokio::test] + async fn test_metadata_aggr_memtable_containers() { + let split = |memtables: Vec| async move { + let files = vec![file(0, 10, 3, true), file(20, 30, 2, true)]; + let input = input_with_memtables(files, &[], memtables).await; + match counted(&input, &ScanRequest::default()) { + Some(MetadataAggr::Split(plan)) => { + Some((plan.exact_rows, plan.remaining_file_indices.len())) + } + Some(MetadataAggr::Exact(_)) => panic!("memtables must stay residual"), + None => None, + } + }; + // The memtable only holds a row at 0, but its container reaches 15, + // so a later write may land in the first file's range. + assert_eq!( + split(vec![memtable((0, 0), Some((0, 15)), 1)]).await, + Some((2, 1)) + ); + // A container disjoint from both files leaves them exact. + assert_eq!( + split(vec![memtable((40, 40), Some((40, 49)), 1)]).await, + Some((5, 0)) + ); + // Touching endpoints overlap; both bounds are inclusive. + assert_eq!( + split(vec![memtable((31, 31), Some((30, 39)), 1)]).await, + Some((3, 1)) + ); + // Without a known container no file is exact, whatever the data range. + assert_eq!(split(vec![memtable((40, 40), None, 1)]).await, None); + assert_eq!( + split(vec![ + memtable((40, 40), Some((40, 49)), 1), + memtable((50, 50), None, 1), + ]) + .await, + None + ); + } } diff --git a/src/mito2/src/read/seq_scan.rs b/src/mito2/src/read/seq_scan.rs index bd1038488b4..07d2cd809f0 100644 --- a/src/mito2/src/read/seq_scan.rs +++ b/src/mito2/src/read/seq_scan.rs @@ -30,7 +30,8 @@ use futures::{StreamExt, TryStreamExt}; use snafu::ensure; use store_api::metadata::RegionMetadataRef; use store_api::region_engine::{ - PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties, + PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, RegionScannerRef, + ScannerProperties, StatisticsSplit, }; use store_api::storage::TimeSeriesRowSelector; use tokio::sync::Semaphore; @@ -43,7 +44,7 @@ use crate::read::last_row::FlatLastRowReader; use crate::read::pruner::{PartitionPruner, Pruner}; use crate::read::range::RangeMeta; use crate::read::range_cache::{CachedRangeReader, build_range_cache_key}; -use crate::read::scan_region::{ScanInput, StreamContext}; +use crate::read::scan_region::{ScanInput, StatisticsSplitPlan, StreamContext}; use crate::read::scan_util::{ BATCH_SIZE_THRESHOLD, MIN_COMPACTION_SPLIT_ROWS, PartitionMetrics, PartitionMetricsList, SplitRecordBatchStream, compute_parallel_channel_size, prepare_flat_mem_stream, @@ -72,6 +73,8 @@ pub(crate) enum FlatReadMode { pub struct SeqScan { /// Shares narthex candidate discovery across batch-output partitions. narthex_preparation: Option>, + /// Exact and residual sources prepared for a scalar COUNT, if any. + statistics_split: Option, /// Properties of the scanner. properties: ScannerProperties, /// Context of streams. @@ -87,8 +90,13 @@ impl SeqScan { /// Creates a new [SeqScan] with the given input. /// If `input.compaction` is true, the scanner will not attempt to split ranges. pub(crate) fn new(input: ScanInput) -> Self { - let mut properties = input.scanner_properties(); - let stream_ctx = Arc::new(StreamContext::seq_scan_ctx(input)); + Self::with_stream_ctx(StreamContext::seq_scan_ctx(input)) + } + + fn with_stream_ctx(mut stream_ctx: StreamContext) -> Self { + let statistics_split = stream_ctx.input.statistics_split.take(); + let mut properties = stream_ctx.input.scanner_properties(); + let stream_ctx = Arc::new(stream_ctx); properties.partitions = vec![stream_ctx.partition_ranges()]; // Create the shared pruner with number of workers equal to CPU cores. @@ -100,6 +108,7 @@ impl SeqScan { .input .requires_narthex_preparation() .then(|| Arc::new(crate::read::series_scan::prepared::Preparation::default())), + statistics_split, properties, stream_ctx, pruner, @@ -107,6 +116,40 @@ impl SeqScan { } } + /// Keeps the original deduplication groups when removing exact files. + fn residual_scanner(&self, remaining_file_indices: &[usize]) -> Option { + let input = &self.stream_ctx.input; + let num_memtables = input.num_memtables(); + let mut mapping: Vec<_> = (0..num_memtables).map(Some).collect(); + mapping.resize(num_memtables + input.num_files(), None); + let files = remaining_file_indices + .iter() + .enumerate() + .map(|(new, &old)| { + mapping[num_memtables + old] = Some(num_memtables + new); + input.files[old].clone() + }) + .collect(); + let residual = input.with_sources(files, input.memtables.clone())?; + let ranges = self + .stream_ctx + .ranges + .iter() + .filter_map(|range| range.remap_sources(&mapping, &residual)) + .collect(); + let mut part = Self::with_stream_ctx(StreamContext::with_ranges( + residual, + ranges, + self.stream_ctx.query_start, + )); + part.properties + .set_logical_region(self.properties.is_logical_region()); + if let Some(region_id) = self.properties.query_load_region_id() { + part.properties.set_query_load_region_id(region_id); + } + Some(Box::new(part)) + } + /// Builds a stream for the query. /// /// The returned stream is not partitioned and will contains all the data. If want @@ -635,6 +678,17 @@ impl RegionScanner for SeqScan { "SeqScan" } + fn take_statistics_split(&mut self) -> Option { + if self.properties.distinguish_partition_range { + return None; + } + let plan = self.statistics_split.take()?; + Some(StatisticsSplit { + exact_rows: plan.exact_rows, + residual: self.residual_scanner(&plan.remaining_file_indices)?, + }) + } + fn properties(&self) -> &ScannerProperties { &self.properties } @@ -661,6 +715,10 @@ impl RegionScanner for SeqScan { if let Some(preparation) = &mut self.narthex_preparation { *preparation = Arc::new(crate::read::series_scan::prepared::Preparation::default()); } + if self.statistics_split.is_some() && !request.preserves_ranges(&self.properties.partitions) + { + self.statistics_split = None; + } self.properties.prepare(request); self.check_scan_limit().map_err(BoxedError::new)?; @@ -686,7 +744,9 @@ impl RegionScanner for SeqScan { // rather than claiming pushdown that discovery cannot honor. return vec![false; filter_exprs.len()]; } + // Prepared counts did not see the dynamic predicate. self.properties.clear_exact_num_rows(); + self.statistics_split = None; self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs) } diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 1d558012a2e..804c53f0265 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -511,6 +511,13 @@ pub struct PrepareRequest { } impl PrepareRequest { + /// Returns whether this request preserves all ranges of the given layout. + pub fn preserves_ranges(&self, current: &[Vec]) -> bool { + self.ranges + .as_ref() + .is_none_or(|replacement| same_partition_ranges(current, replacement)) + } + /// Sets the ranges. pub fn with_ranges(mut self, ranges: Vec>) -> Self { self.ranges = Some(ranges); @@ -683,6 +690,19 @@ pub trait PreparedSeriesSource: Send + Sync { ) -> Result; } +/// A scan split into sources counted from metadata and a residual scan. +/// +/// The two parts are source-disjoint: no row the residual scan yields is +/// counted in `exact_rows`, so a scalar COUNT of the original scan is +/// `exact_rows` plus the COUNT of the residual scan. +#[derive(Debug)] +pub struct StatisticsSplit { + /// Query-visible rows of the sources answered from metadata. + pub exact_rows: usize, + /// All remaining sources, merged and deduplicated together. + pub residual: RegionScannerRef, +} + /// A scanner that provides a way to scan the region concurrently. /// /// The scanner splits the region into partitions so that each partition can be scanned concurrently. @@ -690,6 +710,14 @@ pub trait PreparedSeriesSource: Send + Sync { pub trait RegionScanner: Debug + DisplayAs + Send { fn name(&self) -> &str; + /// Takes the source split an engine prepared for a scalar COUNT of a scan + /// hinted with `metadata_aggr_hint`. On success the caller must replace + /// this scanner with the residual scan and add the exact rows once. + /// Partition assignments must use the residual scanner's ranges. + fn take_statistics_split(&mut self) -> Option { + None + } + /// Returns the properties of the scanner. fn properties(&self) -> &ScannerProperties;