diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index cf460122a8b..c9ab7f71552 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -1276,6 +1276,14 @@ impl EngineInner { extension_provider_blocks_exact, )?; + // A metadata aggregate may split into exact files and a residual + // scan. Pin the residual memtable reads to this read view, so rows + // written after the split is proven are never read. + let metadata_aggr_fence = (self.config.experimental_metadata_aggr + && request.metadata_aggr_hint + && request.memtable_max_sequence.is_none()) + .then_some(version_data.committed_sequence); + // Get cache. let cache_manager = self.workers.cache_manager(); @@ -1301,6 +1309,11 @@ impl EngineInner { } else { scan_region }; + let scan_region = if let Some(sequence) = metadata_aggr_fence { + scan_region.with_metadata_aggr_fence(sequence) + } else { + scan_region + }; #[cfg(feature = "enterprise")] let scan_region = self.maybe_fill_extension_range_provider(scan_region, region); diff --git a/src/mito2/src/engine/metadata_aggr_test.rs b/src/mito2/src/engine/metadata_aggr_test.rs index 29cefe356f4..80b2645f6f6 100644 --- a/src/mito2/src/engine/metadata_aggr_test.rs +++ b/src/mito2/src/engine/metadata_aggr_test.rs @@ -12,8 +12,8 @@ // 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; @@ -31,9 +31,10 @@ use object_store::layers::mock::MockLayerBuilder; use store_api::region_engine::RegionEngine; use store_api::region_request::{RegionDeleteRequest, RegionPutRequest, RegionRequest}; use store_api::storage::{RegionId, ScanRequest}; -use table::table::scan::RegionScanExec; +use table::table::scan::{PartialAggrRule, statistics_scan_plan}; use crate::config::MitoConfig; +use crate::engine::MitoEngine; use crate::engine::compaction_test::{compact, delete_and_flush, put_and_flush}; use crate::test_util::{self, CreateRequestBuilder, TestEnv}; @@ -75,6 +76,21 @@ impl TableProvider for CountTable { } } +/// A session whose physical optimizer splits COUNT states like the query engine. +fn count_context() -> SessionContext { + let mut rules = datafusion::physical_optimizer::optimizer::PhysicalOptimizer::new().rules; + let index = rules + .iter() + .position(|rule| rule.name() == "aggregate_statistics") + .unwrap(); + rules.insert(index, Arc::new(PartialAggrRule::default())); + let state = datafusion::execution::session_state::SessionStateBuilder::new() + .with_default_features() + .with_physical_optimizer_rules(rules) + .build(); + SessionContext::new_with_state(state) +} + #[tokio::test] async fn test_metadata_aggr_compaction_sql_and_fallback() { run_compaction_sql_and_fallback("last_row").await; @@ -185,7 +201,7 @@ async fn run_compaction_sql_and_fallback(merge_mode: &str) { .unwrap(); assert_eq!(scanner.properties().exact_num_rows(), Some(6)); let scan: Arc = - Arc::new(RegionScanExec::new(scanner, request.clone(), None).unwrap()); + statistics_scan_plan(scanner, request.clone(), None, false).unwrap(); let ctx = SessionContext::new(); ctx.register_table("t", Arc::new(CountTable { plan: scan })) .unwrap(); @@ -353,6 +369,236 @@ async fn test_metadata_aggr_reads_deletes_from_sst_statistics() { engine.stop().await.unwrap(); } +/// Days 0..7 are compacted into one file, days 7..13 are separate flushes, +/// and day 13 is still in the memtable. A whole-range COUNT counts every file +/// from metadata and only scans the memtable. +#[tokio::test] +async fn test_metadata_aggr_fourteen_day_workload() { + use api::v1::value::ValueData; + use datafusion::physical_plan::statistics::{StatisticsArgs, StatisticsContext}; + use datafusion_common::stats::Precision; + 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") + .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. + let mut scanner = engine + .handle_query(region_id, ScanRequest::default()) + .await + .unwrap(); + assert!(scanner.take_statistics_split().is_none()); + + // Both parts keep 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(); + for part in [&split.exact, &split.inexact] { + assert!(part.properties().is_logical_region()); + assert_eq!( + part.properties().query_load_region_id(), + Some(RegionId::new(2, 7)) + ); + } + assert_eq!(split.exact.properties().exact_num_rows(), Some(13_000)); + assert_eq!(split.inexact.properties().exact_num_rows(), None); + drop(split); + + let ts = |day: i64| { + lit(ScalarValue::TimestampMillisecond( + Some(day * 86_400_000), + None, + )) + }; + // (filters, count, exact count, split into exact and residual scans) + for (filters, expected_count, exact, split) in [ + (vec![], 14_000, None, true), + (vec![col("ts").lt(ts(7))], 7_000, Some(7_000), false), + // Days 7..13 are exact; day 13 is in the memtable. + (vec![col("ts").gt_eq(ts(7))], 7_000, None, true), + // The compacted file is only partly covered; days 7..10 are exact. + ( + vec![col("ts").gt_eq(ts(5)).and(col("ts").lt(ts(10)))], + 5_000, + None, + true, + ), + ] { + 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:?}"); + let scan = statistics_scan_plan(scanner, request.clone(), None, false).unwrap(); + if request.filters.is_empty() { + let children = scan.children(); + assert_eq!(children.len(), 2); + let stats = |plan: &Arc| { + StatisticsContext::new() + .compute(plan.as_ref(), &StatisticsArgs::new()) + .unwrap() + .num_rows + }; + assert_eq!(stats(children[0]), Precision::Exact(13_000)); + assert_eq!(stats(children[1]), Precision::Inexact(1_000)); + assert_eq!(stats(&scan), Precision::Inexact(14_000)); + } + let ctx = count_context(); + ctx.register_table("t", Arc::new(CountTable { plan: scan })) + .unwrap(); + let df = ctx.sql("SELECT count(*) FROM t").await.unwrap(); + let plan = df.clone().create_physical_plan().await.unwrap(); + let text = displayable(plan.as_ref()).indent(true).to_string(); + assert_eq!(text.contains("SeqScan"), exact.is_none(), "{text}"); + assert_eq!(text.contains("InexactRegionScanExec"), split, "{text}"); + assert!( + !text.contains("ExactRegionScanExec: "), + "exact branch must be folded: {text}" + ); + let batches = df.collect().await.unwrap(); + assert_eq!( + ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(), + ScalarValue::Int64(Some(expected_count)) + ); + // The files' metadata is cached, and the residual of the whole-range + // COUNT is the memtable, so neither query opens an SST. + if exact.is_some() || request.filters.is_empty() { + let paths = reads.lock().unwrap(); + assert!(paths.is_empty(), "COUNT opened SSTs: {paths:?}"); + } + } + let raw = common_recordbatch::RecordBatches::try_collect( + engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + raw.iter().map(|batch| batch.num_rows()).sum::(), + 14_000 + ); + + for (timestamp, delete, expected, retains_exact) in [ + // A newer row leaves every file isolated. + (15 * 86_400_000, false, 14_001, true), + // A deletion in memory overlaps every file in time. + (86_400_000, true, 14_000, false), + ] { + 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(); + let scanner = engine + .handle_query(region_id, hinted.clone()) + .await + .unwrap(); + let plan = statistics_scan_plan(scanner, hinted.clone(), None, false).unwrap(); + let ctx = count_context(); + ctx.register_table("t", Arc::new(CountTable { plan })) + .unwrap(); + let df = ctx.sql("SELECT count(*) FROM t").await.unwrap(); + let plan = df.clone().create_physical_plan().await.unwrap(); + let text = displayable(plan.as_ref()).indent(true).to_string(); + assert_eq!(text.contains("13000 as"), retains_exact, "{text}"); + let batches = df.collect().await.unwrap(); + assert_eq!( + ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(), + ScalarValue::Int64(Some(expected)) + ); + } + engine.stop().await.unwrap(); +} + /// A strict lower bound past the largest timestamp matches no row. The count /// must agree with a plain scan rather than cover the file. #[tokio::test] @@ -420,3 +666,78 @@ async fn test_metadata_aggr_strict_bound_past_max() { } engine.stop().await.unwrap(); } + +/// A row written between preparing a split and executing it is counted once. +/// File A is exact, file B stays residual, and the memtable is disjoint from A +/// when the split is prepared. Rewriting A's row into the memtable afterwards +/// must not let the residual scan count it a second time. A time-series +/// memtable reads its live series set, so it sees rows written after its +/// ranges are built. +#[rstest::rstest] +#[case::bulk("flat", "bulk")] +#[case::time_series("primary_key", "time_series")] +#[tokio::test] +async fn test_metadata_aggr_split_ignores_later_memtable_writes( + #[case] sst_format: &str, + #[case] memtable: &str, +) { + 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", &[0])).await; + + let request = ScanRequest { + filters: vec![col("tag_0").eq(lit("a"))], + metadata_aggr_hint: true, + ..Default::default() + }; + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + // Written after the split is prepared, before it executes. + test_util::put_rows(&engine, region_id, rows("a", &[100])).await; + + let plan = statistics_scan_plan(scanner, request, None, false).unwrap(); + let ctx = count_context(); + ctx.register_table("t", Arc::new(CountTable { plan })) + .unwrap(); + let df = ctx.sql("SELECT count(*) FROM t").await.unwrap(); + let plan = df.clone().create_physical_plan().await.unwrap(); + let text = displayable(plan.as_ref()).indent(true).to_string(); + assert!(text.contains("InexactRegionScanExec"), "{text}"); + let batches = df.collect().await.unwrap(); + assert_eq!( + ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(), + ScalarValue::Int64(Some(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/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index 4ea497f4207..c1e2d8c07c1 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; @@ -251,6 +252,9 @@ pub(crate) struct ScanRegion { /// Whether to enable the experimental two-phase metric series scan. experimental_series_scan_v2: bool, experimental_metadata_aggr: bool, + /// Highest sequence memtables yield to a hinted metadata aggregate when + /// the request sets no upper bound. See [`Self::with_metadata_aggr_fence`]. + metadata_aggr_fence: Option, /// Whether to ignore range indexes during scans. ignore_range_index: bool, /// Whether to ignore inverted index. @@ -290,6 +294,7 @@ impl ScanRegion { scan_memory_tracker: None, experimental_series_scan_v2: false, experimental_metadata_aggr: false, + metadata_aggr_fence: None, ignore_range_index: false, ignore_inverted_index: false, ignore_fulltext_index: false, @@ -348,6 +353,17 @@ impl ScanRegion { self } + /// Pins memtable reads to `sequence`, the committed sequence of the read + /// view. A split proves its exact files disjoint from the memtables' + /// bounds when it is prepared, but memtables keep accepting writes, and + /// the residual scan would otherwise read rows written later, possibly + /// a row an exact file has already counted. + #[must_use] + pub(crate) fn with_metadata_aggr_fence(mut self, sequence: SequenceNumber) -> Self { + self.metadata_aggr_fence = Some(sequence); + self + } + /// Sets whether to ignore range indexes during scans. #[must_use] pub(crate) fn with_ignore_range_index(mut self, ignore: bool) -> Self { @@ -546,7 +562,9 @@ impl ScanRegion { .with_predicate(predicate.clone()) .with_sequence(SequenceRange::new( self.request.memtable_min_sequence, - self.request.memtable_max_sequence, + self.request + .memtable_max_sequence + .or(self.metadata_aggr_fence), )) .with_pre_filter_mode(filter_mode), )?; @@ -642,7 +660,11 @@ impl ScanRegion { }; let mut input = input.build(); if self.experimental_metadata_aggr && self.request.metadata_aggr_hint { - input.exact_num_rows = aggr::prepare(&input, &self.request).await; + match aggr::prepare(&input, &self.request).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) } @@ -929,6 +951,8 @@ fn time_range_covers_file(time_range: Option<&TimestampRange>, file: &FileHandle pub struct ScanInput { /// Count proven against this read view and the complete static predicate. pub(crate) exact_num_rows: Option, + /// 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. pub(crate) series_index: Option, /// Whether to ignore range indexes while retaining series-index candidate discovery. @@ -1005,6 +1029,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, @@ -1022,6 +1047,59 @@ 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, + exact_num_rows: Option, + ) -> Option { + #[cfg(feature = "enterprise")] + if !self.extension_ranges.is_empty() { + return None; + } + Some(Self { + exact_num_rows, + statistics_split: None, + series_index: self.series_index.clone(), + ignore_range_index: self.ignore_range_index, + 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, + 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( @@ -1031,6 +1109,7 @@ impl ScanInput { ScanInputBuilder { input: ScanInput { exact_num_rows: None, + statistics_split: None, series_index: None, ignore_range_index: false, access_layer, diff --git a/src/mito2/src/read/scan_region/aggr.rs b/src/mito2/src/read/scan_region/aggr.rs index afcf909d06c..240bf2ef3d8 100644 --- a/src/mito2/src/read/scan_region/aggr.rs +++ b/src/mito2/src/read/scan_region/aggr.rs @@ -42,15 +42,35 @@ use crate::read::scan_region::ScanInput; use crate::read::scan_region::aggr::overlap::{Extent, find_overlaps}; use crate::sst::file::FileHandle; -/// Returns the exact number of rows the scan yields, or `None` if it cannot -/// be proven. Reads no SST data: candidates come from the manifest, and in a -/// deduplicating region their Parquet metadata is read through the SST -/// metadata caches to rule out deletions. -pub(crate) async fn prepare(input: &ScanInput, request: &ScanRequest) -> Option { +/// 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), +} + +/// Disjoint source sets for an exact part and a residual scan of one read view. +pub(crate) struct StatisticsSplitPlan { + /// Files whose rows are all yielded exactly once, without other sources. + pub(crate) exact_files: Vec, + /// Sum of the manifest row counts of `exact_files`. + pub(crate) exact_rows: usize, + /// Other files intersecting the query time range. Memtables always stay + /// in the residual scan. + pub(crate) remaining_files: Vec, + /// Physical source rows of the residual scan, if all are known. + pub(crate) remaining_rows: Option, +} + +/// Classifies the sources of a hinted scalar COUNT scan once. Returns `None` +/// when no file is exact, so the scan stays unchanged. Reads no SST data: +/// candidates come from the manifest, and in a deduplicating region their +/// Parquet metadata is read through the SST metadata caches to rule out +/// deletions. +pub(crate) async fn prepare(input: &ScanInput, request: &ScanRequest) -> Option { let classification = classify(input, request)?; - if !classification.remaining.is_empty() || !input.memtables.is_empty() { - return None; - } let no_deletes = read_no_deletes(input, &classification).await; resolve(input, classification, &no_deletes) } @@ -60,10 +80,30 @@ fn resolve( input: &ScanInput, mut classification: Classification, no_deletes: &[bool], -) -> Option { +) -> Option { classification.retain_exact(input, no_deletes); - (classification.remaining.is_empty() && input.memtables.is_empty()) - .then_some(classification.exact_rows) + if classification.remaining.is_empty() && input.memtables.is_empty() { + return Some(MetadataAggr::Exact(classification.exact_rows)); + } + if classification.exact.is_empty() { + return None; + } + let files = |indexes: &[usize]| -> Vec { + indexes.iter().map(|&i| input.files[i].clone()).collect() + }; + // Zero is unknown in legacy manifests. + let remaining_rows = classification + .remaining + .iter() + .map(|&i| Some(input.files[i].num_rows()).filter(|&rows| rows > 0)) + .chain(input.memtables.iter().map(|m| Some(m.stats().num_rows))) + .try_fold(0usize, |total, rows| total.checked_add(rows?)); + Some(MetadataAggr::Split(StatisticsSplitPlan { + exact_files: files(&classification.exact), + exact_rows: classification.exact_rows, + remaining_files: files(&classification.remaining), + remaining_rows, + })) } /// Returns, for each exact candidate, whether it holds no deletion markers. @@ -457,12 +497,20 @@ mod tests { .collect() } - fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option { + /// [`prepare`] with the test's deletion evidence. + fn counted(input: &ScanInput, request: &ScanRequest) -> Option { let classification = classify(input, request)?; let no_deletes = evidence(input, &classification); resolve(input, classification, &no_deletes) } + 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).unwrap(); let no_deletes = evidence(input, &classification); @@ -704,4 +752,35 @@ mod tests { ))); assert!(!has_no_deletes(&metadata("other", vec![put; 4]))); } + + #[tokio::test] + async fn test_metadata_aggr_split_plan() { + let split = |files| async move { + match counted(&input(files, &[]).await, &ScanRequest::default()) { + Some(MetadataAggr::Split(plan)) => Some(( + plan.exact_files.len(), + plan.exact_rows, + plan.remaining_files.len(), + plan.remaining_rows, + )), + Some(MetadataAggr::Exact(_)) => panic!("unexpected exact count"), + None => None, + } + }; + // The second file holds a deletion. + assert_eq!( + split(vec![file(0, 10, 3, true), file(20, 30, 2, false)]).await, + Some((1, 3, 1, Some(2))) + ); + // An unknown residual count is only an estimate, never a reason to fail. + assert_eq!( + split(vec![file(0, 10, 3, true), file(20, 30, 0, false)]).await, + Some((1, 3, 1, None)) + ); + // Without an exact file the scan stays unchanged. + assert_eq!( + split(vec![file(0, 10, 3, false), file(20, 30, 2, false)]).await, + None + ); + } } diff --git a/src/mito2/src/read/seq_scan.rs b/src/mito2/src/read/seq_scan.rs index 1a209eeffe2..4c8dc2040c3 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, @@ -70,6 +71,8 @@ pub(crate) enum FlatReadMode { /// The output order is always `order by primary keys, time index` inside every /// [`PartitionRange`]. Each "partition" may contains many [`PartitionRange`]s. pub struct SeqScan { + /// Exact and residual sources prepared for a scalar COUNT, if any. + statistics_split: Option, /// Properties of the scanner. properties: ScannerProperties, /// Context of streams. @@ -84,7 +87,8 @@ pub struct SeqScan { 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 { + pub(crate) fn new(mut input: ScanInput) -> Self { + let statistics_split = input.statistics_split.take(); let mut properties = ScannerProperties::default() .with_append_mode(input.append_mode) .with_total_rows(input.total_rows()) @@ -101,6 +105,7 @@ impl SeqScan { let pruner = Arc::new(Pruner::new(stream_ctx.clone(), num_workers)); Self { + statistics_split, properties, stream_ctx, pruner, @@ -108,6 +113,19 @@ impl SeqScan { } } + /// Builds a scanner over a subset of this scan's sources. It keeps the + /// properties callers set after construction, such as the metric engine's + /// logical region and query-load attribution. + fn split_part(&self, input: ScanInput) -> RegionScannerRef { + let mut part = Self::new(input); + 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); + } + Box::new(part) + } + /// Builds a stream for the query. /// /// The returned stream is not partitioned and will contains all the data. If want @@ -585,6 +603,18 @@ impl RegionScanner for SeqScan { "SeqScan" } + fn take_statistics_split(&mut self) -> Option { + let plan = self.statistics_split.take()?; + let input = &self.stream_ctx.input; + let exact = input.with_sources(plan.exact_files, Vec::new(), Some(plan.exact_rows))?; + let inexact = input.with_sources(plan.remaining_files, input.memtables.clone(), None)?; + Some(StatisticsSplit { + exact: self.split_part(exact), + inexact: self.split_part(inexact), + inexact_rows: plan.remaining_rows, + }) + } + fn properties(&self) -> &ScannerProperties { &self.properties } diff --git a/src/query/src/dummy_catalog.rs b/src/query/src/dummy_catalog.rs index 1d4ce4a8c07..3934561bf82 100644 --- a/src/query/src/dummy_catalog.rs +++ b/src/query/src/dummy_catalog.rs @@ -42,7 +42,7 @@ use store_api::storage::{RegionId, ScanRequest, TimeSeriesDistribution, TimeSeri use table::TableRef; use table::metadata::{TableId, TableInfoRef}; use table::table::adapter::{dictionary_encode_string_columns, supports_pk_dictionary_encoding}; -use table::table::scan::RegionScanExec; +use table::table::scan::statistics_scan_plan; use crate::error::{GetRegionMetadataSnafu, Result}; use crate::options::{FlowIncrementalMode, FlowQueryExtensions}; @@ -195,11 +195,14 @@ impl TableProvider for DummyTableProvider { } let query_memory_tracker = self.engine.query_memory_tracker(); - let mut scan_exec = RegionScanExec::new(scanner, request, query_memory_tracker)?; - if let Some(query_ctx) = &self.query_ctx { - scan_exec.set_explain_verbose(query_ctx.explain_verbose()); - } - Ok(Arc::new(scan_exec)) + statistics_scan_plan( + scanner, + request, + query_memory_tracker, + self.query_ctx + .as_ref() + .is_some_and(|ctx| ctx.explain_verbose()), + ) } fn supports_filters_pushdown( diff --git a/src/query/src/query_engine/state.rs b/src/query/src/query_engine/state.rs index f93ce49f7ee..14700cafa3c 100644 --- a/src/query/src/query_engine/state.rs +++ b/src/query/src/query_engine/state.rs @@ -280,6 +280,21 @@ impl QueryEngineState { physical_optimizer .rules .push(Arc::new(EnsureGlobalLimitForFetch)); + // Split scalar COUNT states over a Mito statistics split before the + // aggregate-statistics rule folds the exact branch into a literal. + let aggregate_statistics_index = physical_optimizer + .rules + .iter() + .position(|rule| rule.name() == "aggregate_statistics") + .ok_or_else(|| { + datafusion_common::internal_datafusion_err!("Missing AggregateStatistics rule") + })?; + physical_optimizer.rules.insert( + aggregate_statistics_index, + Arc::new(table::table::scan::PartialAggrRule::with_count_state( + common_function::aggrs::aggr_wrapper::aggr_state_func_name("count"), + )), + ); // Add rule to remove duplicate nodes generated by other rules. Run this in the last. physical_optimizer.rules.push(Arc::new(RemoveDuplicate)); // Place SanityCheckPlan at the end of the list to ensure that it runs after all other rules. diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 8f2b3d6c228..3ef12c2400c 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -512,6 +512,17 @@ impl Default for QueryScanContext { } } +/// Two source-disjoint scanners sharing the original scan read view. +#[derive(Debug)] +pub struct StatisticsSplit { + /// Sources with a proven exact query-visible row count. + pub exact: RegionScannerRef, + /// All remaining sources, merged and deduplicated together. + pub inexact: RegionScannerRef, + /// Physical source-row estimate for the remaining scan, never an exact answer. + pub inexact_rows: Option, +} + /// 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. @@ -519,6 +530,13 @@ impl Default for QueryScanContext { pub trait RegionScanner: Debug + DisplayAs + Send { fn name(&self) -> &str; + /// Takes the source split an engine prepared for a scalar COUNT against + /// the original read view. On success the caller must replace this + /// scanner with both parts. + fn take_statistics_split(&mut self) -> Option { + None + } + /// Returns the properties of the scanner. fn properties(&self) -> &ScannerProperties; diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs index fabc2b51d19..3988273ed66 100644 --- a/src/table/src/table/scan.rs +++ b/src/table/src/table/scan.rs @@ -59,6 +59,11 @@ use store_api::storage::{ScanRequest, TimeSeriesDistribution}; use crate::table::metrics::StreamMetrics; +mod statistics; +pub use statistics::{ + ExactRegionScanExec, InexactRegionScanExec, PartialAggrRule, statistics_scan_plan, +}; + /// The name of [`RegionScanExec`] plan node. pub const REGION_SCAN_EXEC_NAME: &str = "RegionScanExec"; diff --git a/src/table/src/table/scan/statistics.rs b/src/table/src/table/scan/statistics.rs new file mode 100644 index 00000000000..a642a3ba111 --- /dev/null +++ b/src/table/src/table/scan/statistics.rs @@ -0,0 +1,329 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Independent statistics for source-disjoint scans, and COUNT state merging. + +use std::fmt; +use std::sync::Arc; + +use common_recordbatch::QueryMemoryTracker; +use datafusion::config::ConfigOptions; +use datafusion::execution::context::TaskContext; +use datafusion::physical_optimizer::PhysicalOptimizerRule; +use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode}; +use datafusion::physical_plan::execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}; +use datafusion::physical_plan::expressions::lit; +use datafusion::physical_plan::placeholder_row::PlaceholderRowExec; +use datafusion::physical_plan::projection::ProjectionExec; +use datafusion::physical_plan::statistics::{ChildStats, StatisticsArgs, StatisticsContext}; +use datafusion::physical_plan::udaf::StatisticsArgs as AggregateStatisticsArgs; +use datafusion::physical_plan::union::UnionExec; +use datafusion::physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, SendableRecordBatchStream, +}; +use datafusion_common::stats::Precision; +use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRecursion}; +use datafusion_common::{DataFusionError, Result, ScalarValue, Statistics}; +use datafusion_physical_expr::PhysicalExpr; +use store_api::region_engine::RegionScannerRef; +use store_api::storage::ScanRequest; + +use crate::table::scan::RegionScanExec; + +macro_rules! statistics_scan { + ($name:ident, $exact:literal) => { + /// A scan retaining the statistics of one source-disjoint subset. + #[derive(Debug)] + pub struct $name { + input: Arc, + source_rows: Option, + } + + impl DisplayAs for $name { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "{}: source_rows={:?}", + stringify!($name), + self.source_rows + ) + } + } + + impl ExecutionPlan for $name { + fn name(&self) -> &str { + stringify!($name) + } + + fn properties(&self) -> &Arc { + self.input.properties() + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn maintains_input_order(&self) -> Vec { + vec![true] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + if children.len() != 1 { + return Err(DataFusionError::Internal( + "statistics scan requires exactly one child".to_string(), + )); + } + Ok(Arc::new(Self { + input: children[0].clone(), + source_rows: self.source_rows, + })) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + self.input.execute(partition, context) + } + + fn reset_state(self: Arc) -> Result> { + let input = self.input.clone().reset_state()?; + Ok(Arc::new(Self { + input, + source_rows: self.source_rows, + })) + } + + fn child_stats_requests(&self, partition: Option) -> Vec { + vec![if $exact { + ChildStats::At(partition) + } else { + ChildStats::Skip + }] + } + + fn statistics_from_inputs( + &self, + input_stats: &[Arc], + args: &StatisticsArgs, + ) -> Result> { + if $exact { + // The child invalidates prepared counts on dynamic filters. + return Ok(input_stats.first().cloned().unwrap_or_else(|| { + Arc::new(Statistics::new_unknown(self.schema().as_ref())) + })); + } + let mut stats = Statistics::new_unknown(self.schema().as_ref()); + if args.partition().is_none() { + stats.num_rows = self + .source_rows + .map(Precision::Inexact) + .unwrap_or(Precision::Absent); + } + Ok(Arc::new(stats)) + } + } + }; +} + +statistics_scan!(ExactRegionScanExec, true); +statistics_scan!(InexactRegionScanExec, false); + +/// Builds the scan plan, replacing the scanner with a union of its exact and +/// inexact parts when the engine prepared a COUNT split. +pub fn statistics_scan_plan( + mut scanner: RegionScannerRef, + request: ScanRequest, + query_memory_tracker: Option, + explain_verbose: bool, +) -> Result> { + let build = |scanner, request, tracker| -> Result> { + let mut scan = RegionScanExec::new(scanner, request, tracker)?; + scan.set_explain_verbose(explain_verbose); + Ok(Arc::new(scan)) + }; + let Some(parts) = scanner.take_statistics_split() else { + return build(scanner, request, query_memory_tracker); + }; + let source_rows = parts.exact.properties().exact_num_rows(); + let exact: Arc = Arc::new(ExactRegionScanExec { + input: build(parts.exact, request.clone(), query_memory_tracker.clone())?, + source_rows, + }); + let inexact: Arc = Arc::new(InexactRegionScanExec { + input: build(parts.inexact, request, query_memory_tracker)?, + source_rows: parts.inexact_rows, + }); + UnionExec::try_new(vec![exact, inexact]) +} + +/// Distributes scalar COUNT states over the two statistics branches. +/// +/// The exact branch becomes one COUNT state, not one input row to be counted. +#[derive(Debug, Default)] +pub struct PartialAggrRule { + count_state_function: Option, +} + +impl PartialAggrRule { + /// Recognizes an engine COUNT-state wrapper without depending on its implementation. + pub fn with_count_state(function: String) -> Self { + Self { + count_state_function: Some(function), + } + } + + fn inputs(plan: &Arc) -> Result>>> { + if let Some(union) = plan.downcast_ref::() { + if union + .inputs() + .iter() + .any(|input| input.is::()) + && union.inputs().iter().all(|input| { + input.is::() || input.is::() + }) + { + return Ok(Some(union.inputs().clone())); + } + return Ok(None); + } + if let Some(projection) = plan.downcast_ref::() + && let Some(inputs) = Self::inputs(projection.input())? + { + return inputs + .into_iter() + .map(|input| { + plan.clone().replace_children( + vec![input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + }) + .collect::>>() + .map(Some); + } + Ok(None) + } + + fn partial( + aggregate: &AggregateExec, + input: Arc, + ) -> Result> { + let stats = StatisticsContext::new().compute(input.as_ref(), &StatisticsArgs::new())?; + let expr = &aggregate.aggr_expr()[0]; + let args = expr.expressions(); + let field = expr.field(); + let value = expr.fun().value_from_stats(&AggregateStatisticsArgs { + statistics: &stats, + return_type: field.data_type(), + is_distinct: false, + exprs: args.as_slice(), + }); + // State-wrapper aggregates return a struct, while their Partial mode + // emits the inner COUNT state as one scalar field. + let value = match value { + Some(ScalarValue::Struct(array)) + if array.num_columns() == 1 && array.column(0).len() == 1 => + { + Some(ScalarValue::try_from_array(array.column(0), 0)?) + } + value => value, + }; + let partial = AggregateExec::try_new( + AggregateMode::Partial, + aggregate.group_expr().clone(), + aggregate.aggr_expr().to_vec(), + aggregate.filter_expr().to_vec(), + input, + aggregate.input_schema(), + )?; + if let Some(value) = value + && partial.schema().fields().len() == 1 + && value.data_type() == *partial.schema().field(0).data_type() + { + return Ok(Arc::new(ProjectionExec::try_new( + vec![(lit(value), partial.schema().field(0).name().clone())], + Arc::new(PlaceholderRowExec::new(partial.schema())), + )?)); + } + Ok(Arc::new(partial)) + } + + fn rewrite(&self, plan: Arc) -> Result>> { + let Some(aggregate) = plan.downcast_ref::() else { + return Ok(Transformed::no(plan)); + }; + if !matches!( + aggregate.mode(), + AggregateMode::Partial | AggregateMode::Single | AggregateMode::SinglePartitioned + ) || !aggregate.group_expr().is_empty() + || aggregate.aggr_expr().len() != 1 + || (aggregate.aggr_expr()[0].fun().name() != "count" + && self.count_state_function.as_deref() + != Some(aggregate.aggr_expr()[0].fun().name())) + || aggregate.aggr_expr()[0].is_distinct() + || aggregate.filter_expr().iter().any(Option::is_some) + { + return Ok(Transformed::no(plan)); + } + let Some(inputs) = Self::inputs(aggregate.input())? else { + return Ok(Transformed::no(plan)); + }; + let states = inputs + .into_iter() + .map(|input| Self::partial(aggregate, input)) + .collect::>>()?; + let union = UnionExec::try_new(states)?; + if aggregate.mode() == &AggregateMode::Partial { + return Ok(Transformed::yes(union)); + } + Ok(Transformed::yes(Arc::new(AggregateExec::try_new( + AggregateMode::Final, + aggregate.group_expr().clone(), + aggregate.aggr_expr().to_vec(), + vec![None], + union, + aggregate.input_schema(), + )?))) + } +} + +impl PhysicalOptimizerRule for PartialAggrRule { + fn optimize( + &self, + plan: Arc, + _: &ConfigOptions, + ) -> Result> { + plan.transform_up(|plan| self.rewrite(plan)).data() + } + + fn name(&self) -> &str { + "partial_metadata_aggr" + } + + fn schema_check(&self) -> bool { + // Folding COUNT state to a literal can tighten nullability. + false + } +} diff --git a/tests/cases/standalone/common/tql-explain-analyze/explain.result b/tests/cases/standalone/common/tql-explain-analyze/explain.result index 77870e8f062..de6fe4eb67e 100644 --- a/tests/cases/standalone/common/tql-explain-analyze/explain.result +++ b/tests/cases/standalone/common/tql-explain-analyze/explain.result @@ -186,6 +186,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test; | physical_plan after OutputRequirements_| OutputRequirementExec: order_by=[], dist_by=Unspecified_| |_|_MergeScanExec: REDACTED |_|_| +| physical_plan after partial_metadata_aggr_| SAME TEXT AS ABOVE_| | physical_plan after aggregate_statistics_| SAME TEXT AS ABOVE_| | physical_plan after join_selection_| SAME TEXT AS ABOVE_| | physical_plan after LimitedDistinctAggregation_| SAME TEXT AS ABOVE_| @@ -348,6 +349,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test AS series; | physical_plan after OutputRequirements_| OutputRequirementExec: order_by=[], dist_by=Unspecified_| |_|_MergeScanExec: REDACTED |_|_| +| physical_plan after partial_metadata_aggr_| SAME TEXT AS ABOVE_| | physical_plan after aggregate_statistics_| SAME TEXT AS ABOVE_| | physical_plan after join_selection_| SAME TEXT AS ABOVE_| | physical_plan after LimitedDistinctAggregation_| SAME TEXT AS ABOVE_| @@ -540,6 +542,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test_nano; | physical_plan after OutputRequirements_| OutputRequirementExec: order_by=[], dist_by=Unspecified_| |_|_MergeScanExec: REDACTED |_|_| +| physical_plan after partial_metadata_aggr_| SAME TEXT AS ABOVE_| | physical_plan after aggregate_statistics_| SAME TEXT AS ABOVE_| | physical_plan after join_selection_| SAME TEXT AS ABOVE_| | physical_plan after LimitedDistinctAggregation_| SAME TEXT AS ABOVE_|