diff --git a/config/config.md b/config/config.md index 9bbed619ab3..4b046b7fbd1 100644 --- a/config/config.md +++ b/config/config.md @@ -223,6 +223,7 @@ | `region_engine.mito.schedule_compaction_after_edit` | Bool | `true` | Whether to allow to schedule a compaction after a successful region edit.

Setting this to "true" is a necessary but not sufficient condition for scheduling compaction after a region edit.
Other constraints, such as "min_compaction_interval", may still prevent compaction from being scheduled.
Setting this to "false", however, guarantees that compaction will not be scheduled after a region edit. | | `region_engine.mito.default_flat_format` | Bool | `true` | Whether to enable flat format as the default SST format. | | `region_engine.mito.experimental_series_scan_v2` | Bool | `false` | Whether to enable the experimental two-phase mode for eligible metric series scans. | +| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST data.
May read Parquet footers to rule out deletions; ingestion does no extra work. | | `region_engine.mito.index` | -- | -- | The options for index in Mito engine. | | `region_engine.mito.index.aux_path` | String | `""` | Auxiliary directory path for the index in filesystem, used to store intermediate files for
creating the index and staging files for searching the index, defaults to `{data_home}/index_intermediate`.
The default name for this directory is `index_intermediate` for backward compatibility.

This path contains two subdirectories:
- `__intm`: for storing intermediate files used during creating index.
- `staging`: for storing staging files used during searching index. | | `region_engine.mito.index.staging_size` | String | `2GB` | The max capacity of the staging directory. | @@ -706,6 +707,7 @@ | `region_engine.mito.schedule_compaction_after_edit` | Bool | `true` | Whether to allow to schedule a compaction after a successful region edit.

Setting this to "true" is a necessary but not sufficient condition for scheduling compaction after a region edit.
Other constraints, such as "min_compaction_interval", may still prevent compaction from being scheduled.
Setting this to "false", however, guarantees that compaction will not be scheduled after a region edit. | | `region_engine.mito.default_flat_format` | Bool | `true` | Whether to enable flat format as the default SST format. | | `region_engine.mito.experimental_series_scan_v2` | Bool | `false` | Whether to enable the experimental two-phase mode for eligible metric series scans. | +| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST data.
May read Parquet footers to rule out deletions; ingestion does no extra work. | | `region_engine.mito.index` | -- | -- | The options for index in Mito engine. | | `region_engine.mito.index.aux_path` | String | `""` | Auxiliary directory path for the index in filesystem, used to store intermediate files for
creating the index and staging files for searching the index, defaults to `{data_home}/index_intermediate`.
The default name for this directory is `index_intermediate` for backward compatibility.

This path contains two subdirectories:
- `__intm`: for storing intermediate files used during creating index.
- `staging`: for storing staging files used during searching index. | | `region_engine.mito.index.staging_size` | String | `2GB` | The max capacity of the staging directory. | diff --git a/config/datanode.example.toml b/config/datanode.example.toml index 45f1d93d39a..0c139164ceb 100644 --- a/config/datanode.example.toml +++ b/config/datanode.example.toml @@ -734,6 +734,10 @@ default_flat_format = true ## Whether to enable the experimental two-phase mode for eligible metric series scans. experimental_series_scan_v2 = false +## Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST data. +## May read Parquet footers to rule out deletions; ingestion does no extra work. +experimental_metadata_aggr = false + ## The options for index in Mito engine. [region_engine.mito.index] diff --git a/config/standalone.example.toml b/config/standalone.example.toml index 7682e537861..d30a7eb4de3 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -949,6 +949,10 @@ default_flat_format = true ## Whether to enable the experimental two-phase mode for eligible metric series scans. experimental_series_scan_v2 = false +## Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST data. +## May read Parquet footers to rule out deletions; ingestion does no extra work. +experimental_metadata_aggr = false + ## The options for index in Mito engine. [region_engine.mito.index] diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index 2aac0c1f2f8..f49f3a29367 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -86,6 +86,11 @@ pending. DDL cancellation retains its existing scheduling fence and priority. `tests/compatibility/manifest/table_compaction/` and `tests/compatibility/manifest/pending_tails/`. - **SST/Parquet layout** (`sst/`): readers must stay compatible with existing files. + Metadata COUNT (`read/scan_region/aggr.rs`) trusts a non-append SST's + `num_rows` only when its `__op_type` statistics show no deletes, which assumes + every SST of a non-append region is deduplicated within itself. Mito's flush, + bulk-part merge and compaction writers guarantee this; SSTs imported by region + edits or `sst_replace` must too. - **Series-index disk limit**: tasks estimate usage from entry sizes in open-region snapshots and defer new builds when the shared estimate is full. Cleanup still prunes obsolete range entries and expires series indexes to reclaim published usage. Concurrent builds may diff --git a/src/mito2/Cargo.toml b/src/mito2/Cargo.toml index 5265554728d..e4e77a59ea0 100644 --- a/src/mito2/Cargo.toml +++ b/src/mito2/Cargo.toml @@ -127,6 +127,11 @@ name = "bench_compaction_picker" harness = false required-features = ["testing"] +[[bench]] +name = "bench_metadata_aggr_overlap" +harness = false +required-features = ["testing"] + [[bench]] name = "bench_flat_merge" harness = false diff --git a/src/mito2/benches/bench_metadata_aggr_overlap.rs b/src/mito2/benches/bench_metadata_aggr_overlap.rs new file mode 100644 index 00000000000..37cdb8d45c2 --- /dev/null +++ b/src/mito2/benches/bench_metadata_aggr_overlap.rs @@ -0,0 +1,271 @@ +// 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. + +//! Compares the metadata aggregate overlap check with its earlier dual-tree +//! sweep and the pairwise oracle. Each case prints the allocations per call +//! before it is timed. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::collections::BTreeSet; +use std::hint::black_box; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; +use mito2::read::scan_region::metadata_aggr_overlap::{ + Extent, find_overlaps, find_overlaps_pairwise, +}; + +/// Counts heap allocations, including reallocations. +struct CountingAlloc; + +static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0); + +unsafe impl GlobalAlloc for CountingAlloc { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + ALLOCATIONS.fetch_add(1, Ordering::Relaxed); + unsafe { System.alloc(layout) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + ALLOCATIONS.fetch_add(1, Ordering::Relaxed); + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static GLOBAL: CountingAlloc = CountingAlloc; + +type Extents = Vec>; + +/// Every extent overlaps every other in time, but keys are disjoint: the +/// worst case for pairwise checking. +fn disjoint_keys(len: usize) -> Extents { + (0..len) + .map(|i| Extent { + time: (0, 100), + key: Some((i as u64 * 2, i as u64 * 2 + 1)), + }) + .collect() +} + +/// Every extent overlaps every other in both time and key. +fn dense_overlap(len: usize) -> Extents { + (0..len) + .map(|i| Extent { + time: (i as i64, i as i64 + len as i64), + key: Some((i as u64, i as u64 + len as u64)), + }) + .collect() +} + +/// Daily compaction outputs: each day splits the key space into a few files, +/// and adjacent days touch at their boundaries. +fn daily_outputs(len: usize) -> Extents { + const FILES_PER_DAY: usize = 4; + (0..len) + .map(|i| { + let day = (i / FILES_PER_DAY) as i64; + let part = (i % FILES_PER_DAY) as u64; + Extent { + time: (day * 86_400, (day + 1) * 86_400), + key: Some((part * 1000, part * 1000 + 999)), + } + }) + .collect() +} + +/// Repeated identical bounds, with every eighth key range unknown, on +/// disjoint hourly windows. +fn duplicate_unknown(len: usize) -> Extents { + (0..len) + .map(|i| { + let hour = (i / 4) as i64; + Extent { + time: (hour * 3_600, hour * 3_600 + 3_599), + key: (i % 8 != 7).then_some((0, 999)), + } + }) + .collect() +} + +fn allocations(f: impl FnOnce() -> R) -> usize { + let before = ALLOCATIONS.load(Ordering::Relaxed); + black_box(f()); + ALLOCATIONS.load(Ordering::Relaxed) - before +} + +#[allow(clippy::print_stdout)] +fn bench_overlaps(c: &mut Criterion) { + for (name, generate) in [ + ("disjoint_keys", disjoint_keys as fn(usize) -> Extents), + ("dense_overlap", dense_overlap), + ("daily_outputs", daily_outputs), + ("duplicate_unknown", duplicate_unknown), + ] { + let mut group = c.benchmark_group(format!("metadata_aggr_overlap/{name}")); + for len in [2, 8, 32, 128, 512, 2048] { + let extents = generate(len); + let expected = find_overlaps_pairwise(&extents); + assert_eq!(find_overlaps(&extents), expected); + assert_eq!(dual_tree::find_overlaps(&extents), expected); + println!( + "allocations {name}/{len}: sweep={} dual_tree={} pairwise={}", + allocations(|| find_overlaps(&extents)), + allocations(|| dual_tree::find_overlaps(&extents)), + allocations(|| find_overlaps_pairwise(&extents)), + ); + group.bench_with_input(BenchmarkId::new("sweep", len), &extents, |b, extents| { + b.iter(|| find_overlaps(black_box(extents))) + }); + group.bench_with_input( + BenchmarkId::new("dual_tree", len), + &extents, + |b, extents| b.iter(|| dual_tree::find_overlaps(black_box(extents))), + ); + group.bench_with_input(BenchmarkId::new("pairwise", len), &extents, |b, extents| { + b.iter(|| find_overlaps_pairwise(black_box(extents))) + }); + } + group.finish(); + } +} + +/// The previous sweep: one event pass with `active` and `unmarked` interval +/// trees whose leaves are `BTreeSet`s. Kept only as a baseline. +mod dual_tree { + use super::*; + + pub fn find_overlaps(extents: &[Extent]) -> Vec { + let mut keys: Vec<&K> = extents + .iter() + .filter_map(|extent| extent.key.as_ref()) + .flat_map(|(min, max)| [min, max]) + .collect(); + keys.sort_unstable(); + keys.dedup(); + let position = |key: &K| keys.partition_point(|k| *k < key) + 1; + let unbounded = keys.len() + 1; + let coordinates: Vec<_> = extents + .iter() + .map(|extent| match &extent.key { + Some((min, max)) => (position(min), position(max)), + None => (0, unbounded), + }) + .collect(); + let mut events: Vec<_> = extents + .iter() + .enumerate() + .flat_map(|(index, extent)| { + [ + (&extent.time.0, false, index), + (&extent.time.1, true, index), + ] + }) + .collect(); + events.sort_unstable_by(|lhs, rhs| lhs.0.cmp(rhs.0).then(lhs.1.cmp(&rhs.1))); + + let mut overlaps = vec![false; extents.len()]; + let mut active = KeyTree::new(unbounded + 1); + let mut unmarked = KeyTree::new(unbounded + 1); + for (_, is_end, index) in events { + let (low, high) = coordinates[index]; + if is_end { + active.remove(low, high, index); + if !overlaps[index] { + unmarked.remove(low, high, index); + } + continue; + } + if active.find(low, high).is_some() { + overlaps[index] = true; + while let Some(other) = unmarked.find(low, high) { + overlaps[other] = true; + let (other_low, other_high) = coordinates[other]; + unmarked.remove(other_low, other_high, other); + } + } + active.insert(low, high, index); + if !overlaps[index] { + unmarked.insert(low, high, index); + } + } + overlaps + } + + struct KeyTree { + leaves: Vec>, + max_high: Vec>, + base: usize, + } + + impl KeyTree { + fn new(len: usize) -> Self { + let base = len.next_power_of_two(); + Self { + leaves: vec![BTreeSet::new(); len], + max_high: vec![None; 2 * base], + base, + } + } + + fn insert(&mut self, low: usize, high: usize, id: usize) { + self.leaves[low].insert((high, id)); + self.update(low); + } + + fn remove(&mut self, low: usize, high: usize, id: usize) { + self.leaves[low].remove(&(high, id)); + self.update(low); + } + + fn update(&mut self, low: usize) { + let mut node = self.base + low; + self.max_high[node] = self.leaves[low].last().map(|(high, _)| *high); + while node > 1 { + node /= 2; + self.max_high[node] = self.max_high[2 * node].max(self.max_high[2 * node + 1]); + } + } + + fn find(&self, low: usize, high: usize) -> Option { + self.find_in(1, 0, self.base - 1, high, low) + } + + fn find_in( + &self, + node: usize, + node_start: usize, + node_end: usize, + max_low: usize, + min_high: usize, + ) -> Option { + if node_start > max_low || self.max_high[node].is_none_or(|high| high < min_high) { + return None; + } + if node >= self.base { + return self.leaves[node - self.base].last().map(|(_, id)| *id); + } + let mid = node_start + (node_end - node_start) / 2; + self.find_in(2 * node, node_start, mid, max_low, min_high) + .or_else(|| self.find_in(2 * node + 1, mid + 1, node_end, max_low, min_high)) + } + } +} + +criterion_group!(benches, bench_overlaps); +criterion_main!(benches); diff --git a/src/mito2/src/config.rs b/src/mito2/src/config.rs index 4ce536a9508..1e21d67d5dd 100644 --- a/src/mito2/src/config.rs +++ b/src/mito2/src/config.rs @@ -234,6 +234,11 @@ pub struct MitoConfig { /// Whether to enable the experimental two-phase mode for eligible metric series scans. pub experimental_series_scan_v2: bool, + /// Answers eligible scalar COUNT queries from manifest row counts instead + /// of scanning SST data. May read Parquet footers to rule out deletions; + /// ingestion does no extra work. + pub experimental_metadata_aggr: bool, + pub gc: GcConfig, } @@ -293,6 +298,7 @@ impl Default for MitoConfig { default_flat_format: true, // FIXME(#9435): Keep v2 opt-in while long-range scan memory usage is investigated. experimental_series_scan_v2: false, + experimental_metadata_aggr: false, gc: GcConfig::default(), }; @@ -460,6 +466,17 @@ impl MitoConfig { mod tests { use super::*; + #[test] + fn test_metadata_aggr_config_roundtrip() { + assert!(!MitoConfig::default().experimental_metadata_aggr); + let config: MitoConfig = toml::from_str("experimental_metadata_aggr = true").unwrap(); + assert!(config.experimental_metadata_aggr); + let serialized = toml::to_string(&config).unwrap(); + assert!(serialized.contains("experimental_metadata_aggr = true")); + let restored: MitoConfig = toml::from_str(&serialized).unwrap(); + assert!(restored.experimental_metadata_aggr); + } + #[test] fn test_scan_memory_policy_upgrade() { for policy in [ diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 7e215cf31a2..cf460122a8b 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -55,6 +55,8 @@ pub mod listener; #[cfg(test)] mod merge_mode_test; #[cfg(test)] +mod metadata_aggr_test; +#[cfg(test)] mod object_store_wal_recovery_test; #[cfg(test)] mod object_store_wal_test; @@ -1289,6 +1291,7 @@ impl EngineInner { .with_max_concurrent_scan_files(self.config.max_concurrent_scan_files) .with_scan_memory_tracker(self.scan_memory_tracker.clone()) .with_experimental_series_scan_v2(self.config.experimental_series_scan_v2) + .with_experimental_metadata_aggr(self.config.experimental_metadata_aggr) .with_ignore_inverted_index(self.config.inverted_index.apply_on_query.disabled()) .with_ignore_fulltext_index(self.config.fulltext_index.apply_on_query.disabled()) .with_ignore_bloom_filter(self.config.bloom_filter_index.apply_on_query.disabled()) diff --git a/src/mito2/src/engine/metadata_aggr_test.rs b/src/mito2/src/engine/metadata_aggr_test.rs new file mode 100644 index 00000000000..29cefe356f4 --- /dev/null +++ b/src/mito2/src/engine/metadata_aggr_test.rs @@ -0,0 +1,422 @@ +// 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. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +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::projection::ProjectionExec; +use datafusion::physical_plan::{ExecutionPlan, displayable}; +use datafusion::prelude::SessionContext; +use datafusion_common::ScalarValue; +use datafusion_expr::{col, lit}; +use datatypes::arrow::datatypes::SchemaRef; +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 crate::config::MitoConfig; +use crate::engine::compaction_test::{compact, delete_and_flush, put_and_flush}; +use crate::test_util::{self, CreateRequestBuilder, TestEnv}; + +/// Exercises DataFusion's normal SQL physical optimizer over a real Mito scan. +/// GreptimeDB's SQL-to-count hint is covered separately by ScanHintRule tests. +#[derive(Debug)] +struct CountTable { + plan: Arc, +} + +#[async_trait] +impl TableProvider for CountTable { + fn schema(&self) -> SchemaRef { + self.plan.schema() + } + fn table_type(&self) -> TableType { + TableType::Base + } + async fn scan( + &self, + _state: &dyn Session, + projection: Option<&Vec>, + _filters: &[Expr], + _limit: Option, + ) -> datafusion_common::Result> { + if let Some(projection) = projection { + let schema = self.plan.schema(); + let exprs: Vec<(Arc, String)> = projection + .iter() + .map(|index| { + let name = schema.field(*index).name(); + (Arc::new(Column::new(name, *index)) as _, name.clone()) + }) + .collect(); + Ok(Arc::new(ProjectionExec::try_new(exprs, self.plan.clone())?)) + } else { + Ok(self.plan.clone()) + } + } +} + +#[tokio::test] +async fn test_metadata_aggr_compaction_sql_and_fallback() { + run_compaction_sql_and_fallback("last_row").await; +} + +/// Both dedup merge modes keep one row per primary key and timestamp, so +/// field merging does not change which files are exact. +#[tokio::test] +async fn test_metadata_aggr_compaction_sql_and_fallback_last_non_null() { + run_compaction_sql_and_fallback("last_non_null").await; +} + +async fn run_compaction_sql_and_fallback(merge_mode: &str) { + let reads = Arc::new(AtomicUsize::new(0)); + let observed = reads.clone(); + let layer = MockLayerBuilder::default() + .reader_factory(Arc::new(move |path, _, inner| { + if path.ends_with(".parquet") { + observed.fetch_add(1, Ordering::Relaxed); + } + inner + })) + .build() + .unwrap(); + let mut env = TestEnv::new().await.with_mock_layer(layer); + let config = MitoConfig { + experimental_metadata_aggr: true, + min_compaction_interval: Duration::from_secs(3600), + schedule_compaction_after_edit: false, + ..Default::default() + }; + let engine = env.create_engine(config.clone()).await; + let region_id = RegionId::new(1, 1); + env.get_schema_metadata_manager() + .register_region_table_info( + region_id.table_id(), + "count_test", + "greptime", + "public", + None, + env.get_kv_backend(), + ) + .await; + let create = CreateRequestBuilder::new() + .insert_option("merge_mode", merge_mode) + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.trigger_file_num", "2") + .build(); + let schema = test_util::rows_schema(&create); + let table_dir = create.table_dir.clone(); + let options = create.options.clone(); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + for range in [0..5, 2..7, 0..3] { + put_and_flush(&engine, region_id, &schema, range).await; + } + delete_and_flush(&engine, region_id, &schema, 1..2).await; + let request = ScanRequest { + metadata_aggr_hint: true, + ..Default::default() + }; + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!( + scanner.properties().exact_num_rows(), + None, + "overlapping flush outputs may share rows" + ); + compact(&engine, region_id).await; + let region = engine.get_region(region_id).unwrap(); + let version = region.version(); + let files = version + .ssts + .levels() + .iter() + .flat_map(|level| level.files.values()) + .collect::>(); + assert_eq!(files.len(), 1); + assert_eq!(files[0].meta_ref().num_rows, 6); + drop(version); + drop(region); + + // Verify the capability survives manifest persistence and reopening. + test_util::reopen_region(&engine, region_id, table_dir, true, options).await; + // Only hinted COUNT scans prepare a count. + let ordinary = engine + .handle_query(region_id, ScanRequest::default()) + .await + .unwrap(); + assert_eq!(ordinary.properties().exact_num_rows(), None); + drop(ordinary); + // The first count may load the file's Parquet metadata. Later ones are + // served from the SST metadata cache, and no count reads SST data. + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!(scanner.properties().exact_num_rows(), Some(6)); + drop(scanner); + reads.store(0, Ordering::Relaxed); + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!(scanner.properties().exact_num_rows(), Some(6)); + let scan: Arc = + Arc::new(RegionScanExec::new(scanner, request.clone(), None).unwrap()); + let ctx = SessionContext::new(); + 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!(!text.contains("RegionScanExec"), "{text}"); + let batches = df.collect().await.unwrap(); + assert_eq!( + ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(), + ScalarValue::Int64(Some(6)) + ); + assert_eq!( + reads.load(Ordering::Relaxed), + 0, + "optimized COUNT must not open any SST" + ); + + let ts = |v| lit(ScalarValue::TimestampMillisecond(Some(v), None)); + for (filters, expected) in [ + ( + vec![col("ts").gt_eq(ts(0)).and(col("ts").lt(ts(7000)))], + Some(6), + ), + (vec![col("ts").lt(ts(3000))], None), + (vec![col("ts").gt(ts(7000))], Some(0)), + ] { + let scanner = engine + .handle_query( + region_id, + ScanRequest { + filters, + ..request.clone() + }, + ) + .await + .unwrap(); + assert_eq!(scanner.properties().exact_num_rows(), expected); + } + + // A new deletion in memory invalidates the complete count; ordinary scan + // still resolves the tombstone against the compacted file. + engine + .handle_request( + region_id, + RegionRequest::Delete(RegionDeleteRequest { + rows: api::v1::Rows { + schema: schema.clone(), + rows: test_util::build_rows_for_key("a", 2, 3, 0), + }, + hint: None, + partition_expr_version: None, + }), + ) + .await + .unwrap(); + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!(scanner.properties().exact_num_rows(), None); + let baseline = common_recordbatch::RecordBatches::try_collect( + engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + baseline.iter().map(|batch| batch.num_rows()).sum::(), + 5 + ); + // Ordinary writes retain their original behavior. + engine + .handle_request( + region_id, + RegionRequest::Put(RegionPutRequest { + rows: api::v1::Rows { + schema, + rows: test_util::build_rows_for_key("a", 2, 3, 0), + }, + hint: None, + partition_expr_version: None, + skip_wal: false, + }), + ) + .await + .unwrap(); + engine.stop().await.unwrap(); +} + +/// Deletions are read from the SST's `__op_type` statistics: a flushed file +/// without overlaps is exact unless it holds a delete marker. +#[tokio::test] +async fn test_metadata_aggr_reads_deletes_from_sst_statistics() { + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + experimental_metadata_aggr: true, + ..Default::default() + }) + .await; + let request = ScanRequest { + metadata_aggr_hint: true, + ..Default::default() + }; + for (region_id, delete) in [(RegionId::new(1, 1), false), (RegionId::new(1, 2), true)] { + let create = CreateRequestBuilder::new().build(); + let schema = test_util::rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + test_util::put_rows( + &engine, + region_id, + api::v1::Rows { + schema: schema.clone(), + rows: test_util::build_rows_for_key("a", 0, 5, 0), + }, + ) + .await; + if delete { + // The tombstone of a missing row is flushed into the same file. + engine + .handle_request( + region_id, + RegionRequest::Delete(RegionDeleteRequest { + rows: api::v1::Rows { + schema: schema.clone(), + rows: test_util::build_rows_for_key("a", 10, 11, 0), + }, + hint: None, + partition_expr_version: None, + }), + ) + .await + .unwrap(); + } + test_util::flush_region(&engine, region_id, None).await; + let region = engine.get_region(region_id).unwrap(); + let num_files = region.version().ssts.levels()[0].files.len(); + assert_eq!(num_files, 1); + + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!( + scanner.properties().exact_num_rows(), + (!delete).then_some(5), + "delete={delete}" + ); + let rows = common_recordbatch::RecordBatches::try_collect( + engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(rows.iter().map(|batch| batch.num_rows()).sum::(), 5); + } + 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] +async fn test_metadata_aggr_strict_bound_past_max() { + 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().build(); + let schema = test_util::rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + test_util::put_rows( + &engine, + region_id, + api::v1::Rows { + schema, + rows: test_util::build_rows_for_key("a", 0, 5, 0), + }, + ) + .await; + test_util::flush_region(&engine, region_id, None).await; + + let max = || lit(ScalarValue::TimestampMillisecond(Some(i64::MAX), None)); + for filter in [col("ts").gt(max()), max().lt(col("ts"))] { + let filters = vec![filter]; + let scanner = engine + .handle_query( + region_id, + ScanRequest { + filters: filters.clone(), + metadata_aggr_hint: true, + ..Default::default() + }, + ) + .await + .unwrap(); + let rows = common_recordbatch::RecordBatches::try_collect( + engine + .scan_to_stream( + region_id, + ScanRequest { + filters: filters.clone(), + ..Default::default() + }, + ) + .await + .unwrap(), + ) + .await + .unwrap(); + let scanned = rows.iter().map(|batch| batch.num_rows()).sum::(); + assert_eq!(scanned, 0, "{filters:?}"); + assert_eq!( + scanner.properties().exact_num_rows(), + Some(scanned), + "{filters:?}" + ); + } + engine.stop().await.unwrap(); +} diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index 6dd6fe81c63..4ea497f4207 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -14,6 +14,10 @@ //! Scans a region according to the scan request. +mod aggr; +#[cfg(any(test, feature = "test", feature = "testing"))] +pub use aggr::overlap as metadata_aggr_overlap; + use std::collections::{BTreeMap, HashSet}; use std::fmt; use std::num::NonZeroU64; @@ -246,6 +250,7 @@ pub(crate) struct ScanRegion { scan_memory_tracker: Option, /// Whether to enable the experimental two-phase metric series scan. experimental_series_scan_v2: bool, + experimental_metadata_aggr: bool, /// Whether to ignore range indexes during scans. ignore_range_index: bool, /// Whether to ignore inverted index. @@ -284,6 +289,7 @@ impl ScanRegion { max_concurrent_scan_files: DEFAULT_MAX_CONCURRENT_SCAN_FILES, scan_memory_tracker: None, experimental_series_scan_v2: false, + experimental_metadata_aggr: false, ignore_range_index: false, ignore_inverted_index: false, ignore_fulltext_index: false, @@ -336,6 +342,12 @@ impl ScanRegion { self } + /// Enables optional exact-count preparation for hinted scalar count scans. + pub(crate) fn with_experimental_metadata_aggr(mut self, enabled: bool) -> Self { + self.experimental_metadata_aggr = enabled; + self + } + /// Sets whether to ignore range indexes during scans. #[must_use] pub(crate) fn with_ignore_range_index(mut self, ignore: bool) -> Self { @@ -628,7 +640,11 @@ impl ScanRegion { } else { input }; - Ok(input.build()) + 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; + } + Ok(input) } /// Builds the deduplicated root column ids required by the projection and @@ -911,6 +927,8 @@ fn time_range_covers_file(time_range: Option<&TimestampRange>, file: &FileHandle /// Common input for different scanners. pub struct ScanInput { + /// Count proven against this read view and the complete static predicate. + pub(crate) exact_num_rows: 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. @@ -1012,6 +1030,7 @@ impl ScanInput { ) -> ScanInputBuilder { ScanInputBuilder { input: ScanInput { + exact_num_rows: 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 new file mode 100644 index 00000000000..afcf909d06c --- /dev/null +++ b/src/mito2/src/read/scan_region/aggr.rs @@ -0,0 +1,707 @@ +// 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. + +//! Answers aggregates of a scan from manifest and SST statistics instead of +//! reading SST data. The preparation result, an exact answer or a split into +//! exact and residual sources, does not depend on the aggregate; scalar COUNT +//! is the only aggregate served so far. + +pub mod overlap; + +use std::sync::Arc; + +use api::v1::OpType; +use common_telemetry::debug; +use common_time::range::TimestampRange; +use datafusion_common::ScalarValue; +use datafusion_expr::{Expr, Operator}; +use datatypes::data_type::DataType; +use datatypes::value::Value; +use futures::StreamExt; +use futures::future::BoxFuture; +use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec}; +use parquet::file::metadata::ParquetMetaData; +use parquet::file::statistics::Statistics; +use store_api::codec::PrimaryKeyEncoding; +use store_api::metadata::{ColumnMetadata, RegionMetadata}; +use store_api::storage::ScanRequest; +use store_api::storage::consts::OP_TYPE_COLUMN_NAME; + +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 { + 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) +} + +/// Applies the deletion evidence of the exact candidates. +fn resolve( + input: &ScanInput, + mut classification: Classification, + no_deletes: &[bool], +) -> Option { + classification.retain_exact(input, no_deletes); + (classification.remaining.is_empty() && input.memtables.is_empty()) + .then_some(classification.exact_rows) +} + +/// Returns, for each exact candidate, whether it holds no deletion markers. +/// Append-mode files need no evidence. In a deduplicating region every SST is +/// deduplicated within itself, so a file without deletions yields each of its +/// rows. A file whose metadata cannot be read counts as having deletions. +async fn read_no_deletes(input: &ScanInput, classification: &Classification) -> Vec { + if input.append_mode { + return vec![true; classification.exact.len()]; + } + // Each future owns its reader, so the stream does not borrow `input`. + // Boxing erases the metadata loader's deep future type for callers. + let reads: Vec> = classification + .exact + .iter() + .map(|&index| { + let file = input.files[index].clone(); + let reader = input + .access_layer + .read_sst(file.clone()) + .cache(input.cache_strategy.clone()); + Box::pin(async move { + match reader.read_statistics().await { + Ok(metadata) => has_no_deletes(&metadata), + Err(e) => { + debug!( + "Metadata count falls back to scanning file {}: {e:?}", + file.file_id() + ); + false + } + } + }) as BoxFuture<'static, bool> + }) + .collect(); + futures::stream::iter(reads) + .buffered(input.max_concurrent_scan_files.max(1)) + .collect() + .await +} + +/// Whether every row group's `__op_type` statistics prove it holds only puts. +fn has_no_deletes(metadata: &ParquetMetaData) -> bool { + let Some(column) = metadata + .file_metadata() + .schema_descr() + .columns() + .iter() + .position(|column| column.name() == OP_TYPE_COLUMN_NAME) + else { + return false; + }; + metadata.row_groups().iter().all(|row_group| { + matches!( + row_group.column(column).statistics(), + Some(Statistics::Int32(stats)) if stats.min_opt() == Some(&(OpType::Put as i32)) + ) + }) +} + +/// Files of one scan classified against its pinned read view. +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, +} + +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`]). +/// - Its manifest row count is known. +/// - In a deduplicating region, no other file or memtable may hold a row with +/// the same primary key and timestamp. The candidate must still be proven +/// free of deletions (see [`read_no_deletes`]). +/// +/// 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.compaction + || input.series_row_selector.is_some() + || input.sequence_range.is_some() + || request.limit.is_some() + || request.memtable_min_sequence.is_some() + || request.memtable_max_sequence.is_some() + || request.sst_min_sequence.is_some() + || request.snapshot_on_scan + || request.exact_sequence_range + || request.skip_sst_files + { + return None; + } + #[cfg(feature = "enterprise")] + if !input.extension_ranges.is_empty() { + return None; + } + let filters = AggrFilters::new(input.region_metadata(), &request.filters)?; + let range = input.time_range.as_ref()?; + + let mut intersecting = Vec::new(); + for (index, file) in input.files.iter().enumerate() { + let (start, end) = file.time_range(); + if start > end { + return None; + } + if range.intersects(&TimestampRange::new_inclusive(Some(start), Some(end))) { + intersecting.push(index); + } + } + // Append mode never merges rows, so sources cannot hide each other's rows. + let overlaps = if input.append_mode { + vec![false; intersecting.len()] + } else { + overlapping_files(input, &intersecting) + }; + + let mut classification = Classification { + exact: Vec::new(), + remaining: Vec::new(), + exact_rows: 0, + }; + for (index, overlaps) in intersecting.into_iter().zip(overlaps) { + let file = &input.files[index]; + let (start, end) = file.time_range(); + let exact = range.contains(&start) + && range.contains(&end) + // Zero is unknown in legacy manifests. + && file.num_rows() > 0 + && (input.region_partition_expr.is_none() || input.should_skip_region_partition(file)) + && filters.covers(file) + && (input.append_mode || !overlaps); + if exact { + classification.exact_rows = classification.exact_rows.checked_add(file.num_rows())?; + classification.exact.push(index); + } else { + classification.remaining.push(index); + } + } + Some(classification) +} + +/// Returns, for each file in `files`, whether another file or a memtable may +/// hold a row with the same primary key and timestamp. +fn overlapping_files(input: &ScanInput, files: &[usize]) -> 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 + .raw_primary_key_range() + .and_then(|_| file.primary_key_range(mapper)), + } + }) + .collect(); + // Memtable key bounds are unknown. + for memtable in &input.memtables { + let stats = memtable.stats(); + match stats.time_range { + Some(time) => extents.push(Extent { time, key: None }), + None if stats.num_rows == 0 => {} + None => return vec![true; files.len()], + } + } + let mut overlaps = find_overlaps(&extents); + overlaps.truncate(files.len()); + overlaps +} + +/// Static scan predicates a metadata count can absorb. +struct AggrFilters { + /// Values the leftmost primary key column must equal. + leftmost_values: Vec, + codec: Option>, +} + +impl AggrFilters { + /// Returns `None` if any conjunct is neither a time-index comparison nor an + /// equality between the leftmost primary key column and a literal. + fn new(metadata: &RegionMetadata, filters: &[Expr]) -> Option { + let time_index = &metadata.time_index_column().column_schema; + let time_type = time_index.data_type.as_arrow_type(); + let mut conjuncts = Vec::new(); + for expr in filters { + split_and(expr, &mut conjuncts); + } + let mut leftmost_values = Vec::new(); + for expr in conjuncts { + if time_filter(expr, &time_index.name, &time_type) { + continue; + } + let column = &leftmost_primary_key(metadata)?.column_schema; + let value = eq_literal(expr, &column.name, &column.data_type.as_arrow_type())?; + leftmost_values.push(Value::try_from(value.clone()).ok()?); + } + let codec = (!leftmost_values.is_empty()).then(|| build_primary_key_codec(metadata)); + Some(Self { + leftmost_values, + codec, + }) + } + + /// Whether the leftmost key equalities hold for every row of the file. + /// Keys are sorted memcomparable bytes, so when both bounds decode to the + /// same leftmost value, every key between them shares it. + fn covers(&self, file: &FileHandle) -> bool { + let Some(codec) = &self.codec else { + return true; + }; + let Some((min, max)) = file.raw_primary_key_range() else { + return false; + }; + match (codec.decode_leftmost(&min), codec.decode_leftmost(&max)) { + (Ok(Some(low)), Ok(Some(high))) => { + low == high && self.leftmost_values.iter().all(|value| *value == low) + } + _ => false, + } + } +} + +/// The leftmost primary key column. Sparse keys are not supported yet. +fn leftmost_primary_key(metadata: &RegionMetadata) -> Option<&ColumnMetadata> { + match metadata.primary_key_encoding { + PrimaryKeyEncoding::Sparse => None, + PrimaryKeyEncoding::Dense => metadata.primary_key_columns().next(), + } +} + +fn split_and<'a>(expr: &'a Expr, out: &mut Vec<&'a Expr>) { + match expr { + Expr::BinaryExpr(binary) if binary.op == Operator::And => { + split_and(&binary.left, out); + split_and(&binary.right, out); + } + _ => out.push(expr), + } +} + +/// Returns the literal of a non-null, same-type `column = literal` equality. +fn eq_literal<'a>( + expr: &'a Expr, + name: &str, + data_type: &datatypes::arrow::datatypes::DataType, +) -> Option<&'a ScalarValue> { + let Expr::BinaryExpr(binary) = expr else { + return None; + }; + if binary.op != Operator::Eq { + return None; + } + let (column, value) = match (binary.left.as_ref(), binary.right.as_ref()) { + (Expr::Column(column), Expr::Literal(value, _)) + | (Expr::Literal(value, _), Expr::Column(column)) => (column, value), + _ => return None, + }; + (column.name == name && !value.is_null() && &value.data_type() == data_type).then_some(value) +} + +fn time_filter(expr: &Expr, name: &str, data_type: &datatypes::arrow::datatypes::DataType) -> bool { + let Expr::BinaryExpr(binary) = expr else { + return false; + }; + if binary.op == Operator::And { + return time_filter(&binary.left, name, data_type) + && time_filter(&binary.right, name, data_type); + } + if !matches!( + binary.op, + Operator::Eq | Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq + ) { + return false; + } + let (column, value) = match (binary.left.as_ref(), binary.right.as_ref()) { + (Expr::Column(column), Expr::Literal(value, _)) + | (Expr::Literal(value, _), Expr::Column(column)) => (column, value), + _ => return false, + }; + column.name == name && !value.is_null() && &value.data_type() == data_type +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + use std::sync::{Arc, LazyLock, Mutex}; + + use bytes::Bytes; + use common_time::Timestamp; + use common_time::timestamp::TimeUnit; + use datafusion_expr::{col, lit}; + use datatypes::value::ValueRef; + use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodecExt}; + use store_api::storage::{FileId, RegionId}; + use table::predicate::build_time_range_predicate; + + use super::*; + use crate::read::flat_projection::FlatProjectionMapper; + 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. + static WITH_DELETES: LazyLock>> = LazyLock::new(Default::default); + + fn file(start: i64, end: i64, rows: u64, no_deletes: bool) -> FileHandle { + let file_id = FileId::random(); + if !no_deletes { + WITH_DELETES.lock().unwrap().insert(file_id); + } + FileHandle::new( + FileMeta { + file_id, + num_rows: rows, + time_range: ( + Timestamp::new_millisecond(start), + Timestamp::new_millisecond(end), + ), + ..Default::default() + }, + new_noop_file_purger(), + ) + } + + /// A file without deletions whose primary keys span `min..=max` over `(k0, k1)`. + fn keyed_file( + start: i64, + end: i64, + rows: u64, + min: (&str, u32), + max: (&str, u32), + ) -> FileHandle { + let codec = DensePrimaryKeyCodec::new(&metadata_with_primary_key(vec![0, 1], false)); + let encode = |(k0, k1): (&str, u32)| { + Bytes::from( + codec + .encode([ValueRef::String(k0), ValueRef::UInt32(k1)].into_iter()) + .unwrap(), + ) + }; + FileHandle::new( + FileMeta { + region_id: RegionId::new(123, 456), + file_id: FileId::random(), + num_rows: rows, + time_range: ( + Timestamp::new_millisecond(start), + Timestamp::new_millisecond(end), + ), + primary_key_min: Some(encode(min)), + primary_key_max: Some(encode(max)), + ..Default::default() + }, + new_noop_file_purger(), + ) + } + + /// The deletion evidence [`read_no_deletes`] would read for the candidates. + fn evidence(input: &ScanInput, classification: &Classification) -> Vec { + let with_deletes = WITH_DELETES.lock().unwrap(); + classification + .exact + .iter() + .map(|&index| { + input.append_mode || !with_deletes.contains(&input.files[index].meta_ref().file_id) + }) + .collect() + } + + fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option { + let classification = classify(input, request)?; + let no_deletes = evidence(input, &classification); + resolve(input, classification, &no_deletes) + } + + fn classified(input: &ScanInput, request: &ScanRequest) -> Classification { + let mut classification = classify(input, request).unwrap(); + let no_deletes = evidence(input, &classification); + classification.retain_exact(input, &no_deletes); + classification + } + + async fn input(files: Vec, filters: &[Expr]) -> 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_predicate(PredicateGroup::new(&metadata, filters).unwrap()) + .with_time_range(Some(build_time_range_predicate( + "ts", + TimeUnit::Millisecond, + filters, + ))) + .build() + } + + #[tokio::test] + async fn test_metadata_aggr_coverage_and_overlap() { + let ts = |v| lit(ScalarValue::TimestampMillisecond(Some(v), None)); + for (filters, expected) in [ + (vec![], Some(5)), + (vec![col("ts").lt(ts(20))], Some(3)), + (vec![col("ts").gt_eq(ts(20))], Some(2)), + (vec![col("ts").lt(ts(5))], None), + (vec![col("ts").gt(ts(30))], Some(0)), + (vec![col("ts").eq(ts(0)).or(col("ts").eq(ts(30)))], None), + (vec![col("ts").not_eq(ts(5))], None), + (vec![col("k0").eq(lit("x"))], None), + ] { + let input = input(vec![file(0, 10, 3, true), file(20, 30, 2, true)], &filters).await; + let request = ScanRequest { + filters, + metadata_aggr_hint: true, + ..Default::default() + }; + // Deletion evidence comes from the test, see `WITH_DELETES`. + assert_eq!(exact_count(&input, &request), expected, "{request:?}"); + } + for files in [ + vec![file(0, 10, 3, true), file(10, 20, 2, true)], + vec![file(0, 10, 3, true), file(5, 8, 2, true)], + vec![file(0, 10, 3, false)], + vec![file(0, 10, 0, false)], + ] { + assert_eq!( + exact_count(&input(files, &[]).await, &ScanRequest::default()), + None + ); + } + } + + #[tokio::test] + async fn test_metadata_aggr_leftmost_key_filter() { + let ts = |v| lit(ScalarValue::TimestampMillisecond(Some(v), None)); + let x = |start, end, rows| keyed_file(start, end, rows, ("x", 1), ("x", 9)); + let mixed = || keyed_file(20, 30, 2, ("x", 1), ("y", 1)); + let k0 = |v: &str| col("k0").eq(lit(v)); + for (files, filters, expected) in [ + // Both bounds prove the equality, so it holds for every row. + ( + vec![x(0, 10, 3), x(20, 30, 2)], + vec![col("ts").gt_eq(ts(0)).and(col("ts").lt(ts(40))), k0("x")], + Some(5), + ), + ( + vec![x(0, 10, 3), x(20, 30, 2)], + vec![lit("x").eq(col("k0"))], + Some(5), + ), + // A file spanning several leftmost values may hold other rows. + (vec![x(0, 10, 3), mixed()], vec![k0("x")], None), + // A disproved equality is not used to exclude files. + (vec![x(0, 10, 3)], vec![k0("y")], None), + // Only the leftmost column is decodable from the bounds. + (vec![x(0, 10, 3)], vec![col("k1").eq(lit(1u32))], None), + (vec![x(0, 10, 3)], vec![col("k0").not_eq(lit("y"))], None), + // Missing key statistics cannot prove anything. + (vec![file(0, 10, 3, true)], vec![k0("x")], None), + ] { + let input = input(files, &filters).await; + let request = ScanRequest { + filters, + metadata_aggr_hint: true, + ..Default::default() + }; + 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] + async fn test_metadata_aggr_fences_and_limits() { + let input = input(vec![file(0, 10, 3, true)], &[]).await; + for request in [ + ScanRequest { + limit: Some(1), + ..Default::default() + }, + ScanRequest { + memtable_max_sequence: Some(10), + ..Default::default() + }, + ScanRequest { + memtable_min_sequence: Some(10), + ..Default::default() + }, + ScanRequest { + snapshot_on_scan: true, + ..Default::default() + }, + ScanRequest { + sst_min_sequence: Some(10), + ..Default::default() + }, + ScanRequest { + exact_sequence_range: true, + ..Default::default() + }, + ScanRequest { + skip_sst_files: true, + ..Default::default() + }, + ] { + assert_eq!(exact_count(&input, &request), None); + } + let mut input = input; + input.files.clear(); + assert_eq!(exact_count(&input, &ScanRequest::default()), Some(0)); + } + + #[tokio::test] + async fn test_metadata_aggr_unknown_manifest_count_falls_back() { + let mut input = input(vec![file(0, 10, 0, true)], &[]).await; + assert_eq!(exact_count(&input, &ScanRequest::default()), None); + 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 datatypes::arrow::array::{ArrayRef, Int64Array, UInt8Array}; + use datatypes::arrow::record_batch::RecordBatch; + use parquet::arrow::ArrowWriter; + use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; + use parquet::file::properties::WriterProperties; + + let metadata = |name: &str, ops: Vec| { + let len = ops.len() as i64; + let batch = RecordBatch::try_from_iter([ + ( + "v", + Arc::new(Int64Array::from_iter_values(0..len)) as ArrayRef, + ), + (name, Arc::new(UInt8Array::from(ops)) as ArrayRef), + ]) + .unwrap(); + let mut buffer = Vec::new(); + // Two rows per row group, so a delete in a later row group counts. + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(2)) + .build(); + let mut writer = + ArrowWriter::try_new(&mut buffer, batch.schema(), Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + ParquetRecordBatchReaderBuilder::try_new(Bytes::from(buffer)) + .unwrap() + .metadata() + .clone() + }; + let put = OpType::Put as u8; + let delete = OpType::Delete as u8; + assert!(has_no_deletes(&metadata(OP_TYPE_COLUMN_NAME, vec![put; 4]))); + assert!(!has_no_deletes(&metadata( + OP_TYPE_COLUMN_NAME, + vec![put, put, put, delete] + ))); + assert!(!has_no_deletes(&metadata("other", vec![put; 4]))); + } +} diff --git a/src/mito2/src/read/scan_region/aggr/overlap.rs b/src/mito2/src/read/scan_region/aggr/overlap.rs new file mode 100644 index 00000000000..bd40acb4e2a --- /dev/null +++ b/src/mito2/src/read/scan_region/aggr/overlap.rs @@ -0,0 +1,347 @@ +// 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. + +//! Finds sources that may share a row in (time, primary key) space. + +use std::cmp::{max, min}; + +/// The inclusive time and primary key bounds of one source. +/// +/// A missing key range is unknown and conservatively spans every key. +#[derive(Debug, Clone)] +pub struct Extent { + /// Inclusive `(start, end)`; `start <= end`. + pub time: (T, T), + /// Inclusive `(min, max)`; `min <= max`. + pub key: Option<(K, K)>, +} + +/// Returns whether each extent intersects at least one other extent. Bounds +/// are inclusive in both dimensions, so touching endpoints count as overlap. +/// +/// Sorts the extents by start time once and sweeps them twice over one +/// array-backed segment tree on the compressed key coordinates. The forward +/// sweep finds each extent's conflict with an earlier-starting extent: an +/// extent that starts no later overlaps if, somewhere in its key range, an +/// earlier extent ends at or after its start. The reverse sweep finds the +/// conflict with a later-starting extent in the same way. Expired extents need +/// no removal, since their bounds fail the comparison. Each sweep queries +/// before it updates, so the cost is O(N log N), even when many extents +/// overlap in time but have disjoint keys. +pub fn find_overlaps(extents: &[Extent]) -> Vec { + // Compress key endpoints into 1..=len. 0 and len + 1 stand for the open + // ends of an unknown key range. + let mut keys: Vec<&K> = Vec::with_capacity(2 * extents.len()); + keys.extend( + extents + .iter() + .filter_map(|extent| extent.key.as_ref()) + .flat_map(|(min, max)| [min, max]), + ); + keys.sort_unstable(); + keys.dedup(); + let position = |key: &K| keys.partition_point(|k| *k < key) + 1; + let unbounded = keys.len() + 1; + let coordinates: Vec<_> = extents + .iter() + .map(|extent| { + debug_assert!(extent.time.0 <= extent.time.1); + match &extent.key { + Some((min, max)) => { + debug_assert!(min <= max); + (position(min), position(max)) + } + None => (0, unbounded), + } + }) + .collect(); + + // Equal starts in index order; an unstable sort needs no buffer. + let mut order: Vec = (0..extents.len()).collect(); + order.sort_unstable_by(|&lhs, &rhs| { + extents[lhs] + .time + .0 + .cmp(&extents[rhs].time.0) + .then(lhs.cmp(&rhs)) + }); + + let mut overlaps = vec![false; extents.len()]; + let mut tree = BoundTree::new(unbounded + 1); + // Latest end time over every key of the extents started so far. + for &index in &order { + let (low, high) = coordinates[index]; + let (start, end) = (&extents[index].time.0, &extents[index].time.1); + overlaps[index] |= tree + .query::(low, high) + .is_some_and(|last| last >= start); + tree.update::(low, high, end); + } + // Earliest start time over every key of the extents starting later. + tree.clear(); + for &index in order.iter().rev() { + let (low, high) = coordinates[index]; + let (start, end) = (&extents[index].time.0, &extents[index].time.1); + overlaps[index] |= tree + .query::(low, high) + .is_some_and(|first| first <= end); + tree.update::(low, high, start); + } + overlaps +} + +/// The quadratic reference implementation of [`find_overlaps`]. +#[cfg(any(test, feature = "test", feature = "testing"))] +pub fn find_overlaps_pairwise(extents: &[Extent]) -> Vec { + let mut overlaps = vec![false; extents.len()]; + for (index, lhs) in extents.iter().enumerate() { + for (offset, rhs) in extents[index + 1..].iter().enumerate() { + let keys_overlap = match (&lhs.key, &rhs.key) { + (Some(lhs), Some(rhs)) => (&lhs.0).max(&rhs.0) <= (&lhs.1).min(&rhs.1), + _ => true, + }; + if keys_overlap && (&lhs.time.0).max(&rhs.time.0) <= (&lhs.time.1).min(&rhs.time.1) { + overlaps[index] = true; + overlaps[index + 1 + offset] = true; + } + } + } + overlaps +} + +/// The best bound per key coordinate, for range updates and range queries +/// that take the larger (or smaller) of two bounds. +/// +/// A bound applied to a whole node is kept on that node and never pushed down, +/// since an update and a query only ever combine bounds with the same order. +struct BoundTree<'a, T> { + /// The best bound applied to every key of each node. + tags: Vec>, + /// The best bound applied to any key of each node, including its tag. + best: Vec>, + /// Number of leaves, a power of two. + width: usize, +} + +/// The order in which a [`BoundTree`] keeps the better of two bounds. A type +/// parameter rather than a function pointer, so each sweep is monomorphized. +trait Pick { + fn pick<'a, T: Ord>(lhs: &'a T, rhs: &'a T) -> &'a T; + + fn combine<'a, T: Ord>(lhs: Option<&'a T>, rhs: Option<&'a T>) -> Option<&'a T> { + match (lhs, rhs) { + (Some(lhs), Some(rhs)) => Some(Self::pick(lhs, rhs)), + (lhs, rhs) => lhs.or(rhs), + } + } +} + +/// Keeps the larger bound. +struct Latest; + +impl Pick for Latest { + fn pick<'a, T: Ord>(lhs: &'a T, rhs: &'a T) -> &'a T { + max(lhs, rhs) + } +} + +/// Keeps the smaller bound. +struct Earliest; + +impl Pick for Earliest { + fn pick<'a, T: Ord>(lhs: &'a T, rhs: &'a T) -> &'a T { + min(lhs, rhs) + } +} + +impl<'a, T: Ord> BoundTree<'a, T> { + fn new(len: usize) -> Self { + let width = len.next_power_of_two(); + Self { + tags: vec![None; 2 * width], + best: vec![None; 2 * width], + width, + } + } + + fn clear(&mut self) { + self.tags.fill(None); + self.best.fill(None); + } + + /// Applies `bound` to every key in `[low, high]`. + fn update(&mut self, low: usize, high: usize, bound: &'a T) { + self.update_in::

(1, 0, self.width - 1, low, high, bound); + } + + fn update_in( + &mut self, + node: usize, + node_low: usize, + node_high: usize, + low: usize, + high: usize, + bound: &'a T, + ) { + if high < node_low || node_high < low { + return; + } + self.best[node] = P::combine(self.best[node], Some(bound)); + if low <= node_low && node_high <= high { + self.tags[node] = P::combine(self.tags[node], Some(bound)); + return; + } + let mid = node_low + (node_high - node_low) / 2; + self.update_in::

(2 * node, node_low, mid, low, high, bound); + self.update_in::

(2 * node + 1, mid + 1, node_high, low, high, bound); + } + + /// Returns the best bound applied to any key in `[low, high]`. + fn query(&self, low: usize, high: usize) -> Option<&'a T> { + self.query_in::

(1, 0, self.width - 1, low, high) + } + + fn query_in( + &self, + node: usize, + node_low: usize, + node_high: usize, + low: usize, + high: usize, + ) -> Option<&'a T> { + if high < node_low || node_high < low { + return None; + } + if low <= node_low && node_high <= high { + return self.best[node]; + } + let mid = node_low + (node_high - node_low) / 2; + let children = P::combine( + self.query_in::

(2 * node, node_low, mid, low, high), + self.query_in::

(2 * node + 1, mid + 1, node_high, low, high), + ); + // The tag covers the part of the node inside the query range. + P::combine(self.tags[node], children) + } +} + +#[cfg(test)] +mod tests { + use rand::rngs::StdRng; + use rand::{Rng, SeedableRng}; + + use super::*; + + fn extent(time: (i64, i64), key: Option<(u32, u32)>) -> Extent { + Extent { time, key } + } + + #[test] + fn test_find_overlaps_boundaries() { + for (extents, expected) in [ + (vec![], vec![]), + (vec![extent((0, 10), Some((0, 0)))], vec![false]), + // Disjoint keys keep time-overlapping extents independent. + ( + vec![extent((0, 10), Some((0, 4))), extent((5, 15), Some((5, 9)))], + vec![false, false], + ), + // Touching time and key endpoints are inclusive. + ( + vec![ + extent((0, 10), Some((0, 4))), + extent((10, 20), Some((4, 9))), + ], + vec![true, true], + ), + ( + vec![ + extent((0, 10), Some((0, 4))), + extent((11, 20), Some((0, 4))), + ], + vec![false, false], + ), + // An unknown key range overlaps every key. + ( + vec![extent((0, 10), None), extent((5, 6), Some((7, 7)))], + vec![true, true], + ), + ( + vec![extent((0, 10), None), extent((11, 12), None)], + vec![false, false], + ), + // A contained extent marks the earlier one as well. + ( + vec![ + extent((0, 100), Some((0, 9))), + extent((40, 50), Some((3, 3))), + ], + vec![true, true], + ), + // Overlap is not transitive. + ( + vec![ + extent((0, 10), Some((0, 1))), + extent((5, 15), Some((1, 2))), + extent((12, 20), Some((0, 0))), + ], + vec![true, true, false], + ), + // Identical extents. + ( + vec![extent((3, 3), Some((2, 2))), extent((3, 3), Some((2, 2)))], + vec![true, true], + ), + ] { + assert_eq!(find_overlaps(&extents), expected, "{extents:?}"); + assert_eq!(find_overlaps_pairwise(&extents), expected, "{extents:?}"); + } + } + + #[test] + fn test_find_overlaps_matches_pairwise() { + let mut rng = StdRng::seed_from_u64(0x0c0_ffee); + for _ in 0..2000 { + let len = rng.random_range(0..40); + // Small domains force ties, containment and touching endpoints. + let time_domain = rng.random_range(1..60); + let key_domain = rng.random_range(1..30); + let extents: Vec<_> = (0..len) + .map(|_| { + let start = rng.random_range(0..time_domain); + let end = start + rng.random_range(0..time_domain / 4 + 1); + let key = (!rng.random_bool(0.1)).then(|| { + let min = rng.random_range(0..key_domain); + (min, min + rng.random_range(0..key_domain / 4 + 1)) + }); + extent((start, end), key) + }) + .collect(); + assert_eq!( + find_overlaps(&extents), + find_overlaps_pairwise(&extents), + "{extents:?}" + ); + } + } + + #[test] + fn test_find_overlaps_time_overlapping_disjoint_keys() { + // The pairwise worst case: every extent overlaps in time, none in key. + let extents: Vec<_> = (0..10_000) + .map(|i| extent((0, 100), Some((i, i)))) + .collect(); + assert!(find_overlaps(&extents).iter().all(|overlap| !overlap)); + } +} diff --git a/src/mito2/src/read/seq_scan.rs b/src/mito2/src/read/seq_scan.rs index a0513300910..1a209eeffe2 100644 --- a/src/mito2/src/read/seq_scan.rs +++ b/src/mito2/src/read/seq_scan.rs @@ -88,6 +88,7 @@ impl SeqScan { let mut properties = ScannerProperties::default() .with_append_mode(input.append_mode) .with_total_rows(input.total_rows()) + .with_exact_num_rows(input.exact_num_rows) .with_total_rows_is_exact(input.append_mode && input.total_rows_is_exact()); if let Some(counters) = input.query_stat_counters.clone() { properties.set_query_stat_counters(counters); @@ -627,6 +628,7 @@ impl RegionScanner for SeqScan { &mut self, filter_exprs: Vec>, ) -> Vec { + self.properties.clear_exact_num_rows(); self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs) } diff --git a/src/mito2/src/read/series_scan.rs b/src/mito2/src/read/series_scan.rs index 23418686cb9..90fa3dbc90c 100644 --- a/src/mito2/src/read/series_scan.rs +++ b/src/mito2/src/read/series_scan.rs @@ -147,6 +147,7 @@ impl SeriesScan { let mut properties = ScannerProperties::default() .with_append_mode(input.append_mode) .with_total_rows(input.total_rows()) + .with_exact_num_rows(input.exact_num_rows) .with_total_rows_is_exact(input.append_mode && input.total_rows_is_exact()); if let Some(counters) = input.query_stat_counters.clone() { properties.set_query_stat_counters(counters); @@ -590,6 +591,7 @@ impl RegionScanner for SeriesScan { &mut self, filter_exprs: Vec>, ) -> Vec { + self.properties.clear_exact_num_rows(); self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs) } diff --git a/src/mito2/src/read/unordered_scan.rs b/src/mito2/src/read/unordered_scan.rs index bda554e4c95..41109c1abfa 100644 --- a/src/mito2/src/read/unordered_scan.rs +++ b/src/mito2/src/read/unordered_scan.rs @@ -66,6 +66,7 @@ impl UnorderedScan { let mut properties = ScannerProperties::default() .with_append_mode(input.append_mode) .with_total_rows(input.total_rows()) + .with_exact_num_rows(input.exact_num_rows) .with_total_rows_is_exact(input.append_mode && input.total_rows_is_exact()); if let Some(counters) = input.query_stat_counters.clone() { properties.set_query_stat_counters(counters); @@ -364,6 +365,7 @@ impl RegionScanner for UnorderedScan { &mut self, filter_exprs: Vec>, ) -> Vec { + self.properties.clear_exact_num_rows(); self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs) } diff --git a/src/mito2/src/sst/parquet/reader.rs b/src/mito2/src/sst/parquet/reader.rs index e92ac60f93b..be5500af7e1 100644 --- a/src/mito2/src/sst/parquet/reader.rs +++ b/src/mito2/src/sst/parquet/reader.rs @@ -808,6 +808,19 @@ impl ParquetReaderBuilder { })) } + /// Reads the file's Parquet metadata for callers that only need file and + /// row group statistics. Uses the same metadata caches as scans and skips + /// the page index. + pub(crate) async fn read_statistics(&self) -> Result> { + let file_path = self.file_handle.file_path(&self.table_dir, self.path_type); + let file_size = self.file_handle.meta_ref().file_size; + let mut metrics = MetadataCacheMetrics::default(); + let (metadata, _) = self + .read_parquet_metadata(&file_path, file_size, &mut metrics, PageIndexPolicy::Skip) + .await?; + Ok(metadata.parquet_metadata()) + } + /// Reads parquet metadata of specific file. /// Returns (fused metadata, cache_miss_flag). pub(crate) async fn read_parquet_metadata( diff --git a/src/query/src/dummy_catalog.rs b/src/query/src/dummy_catalog.rs index 8f0a2c7ac60..1d4ce4a8c07 100644 --- a/src/query/src/dummy_catalog.rs +++ b/src/query/src/dummy_catalog.rs @@ -294,6 +294,19 @@ impl DummyTableProvider { self.scan_request.lock().unwrap().json_type_hint = hint; } + /// Whether this Mito scan still needs a count hint. Optimizer passes may + /// revisit the same aggregate; an already hinted provider is left alone. + pub(crate) fn needs_metadata_aggr_hint(&self) -> bool { + self.engine.name() == "mito" && !self.scan_request.lock().unwrap().metadata_aggr_hint + } + + /// Requests exact-count preparation from Mito. + pub(crate) fn with_metadata_aggr_hint(&self) { + if self.engine.name() == "mito" { + self.scan_request.lock().unwrap().metadata_aggr_hint = true; + } + } + /// Gets the scan request of the provider. #[cfg(test)] pub fn scan_request(&self) -> ScanRequest { diff --git a/src/query/src/optimizer/scan_hint.rs b/src/query/src/optimizer/scan_hint.rs index bc3c04ec1bf..a10b92debb5 100644 --- a/src/query/src/optimizer/scan_hint.rs +++ b/src/query/src/optimizer/scan_hint.rs @@ -65,6 +65,62 @@ impl ScanHintRule { plan.rewrite_with_subqueries(&mut rewriter) } + /// Limits metadata preparation to an ungrouped COUNT directly over a scan. + /// The cloned provider keeps the hint local to this use-site. Residual + /// filters, joins, limits and computed projections are deliberately excluded. + fn set_metadata_aggr_hint(plan: LogicalPlan) -> Result> { + let LogicalPlan::Aggregate(mut aggregate) = plan else { + return Ok(Transformed::no(plan)); + }; + let LogicalPlan::TableScan(scan) = aggregate.input.as_ref() else { + return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate))); + }; + if !aggregate.group_expr.is_empty() + || aggregate.aggr_expr.len() != 1 + || scan.fetch.is_some() + { + return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate))); + } + let Some(source) = scan.source.downcast_ref::() else { + return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate))); + }; + let Some(provider) = source.table_provider.downcast_ref::() else { + return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate))); + }; + if !provider.needs_metadata_aggr_hint() { + return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate))); + } + let expr = match &aggregate.aggr_expr[0] { + Expr::Alias(alias) => alias.expr.as_ref(), + expr => expr, + }; + let Expr::AggregateFunction(function) = expr else { + return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate))); + }; + let metadata = provider.region_metadata(); + let time_index = &metadata.time_index_column().column_schema.name; + let count_all_rows = match function.params.args.as_slice() { + [Expr::Column(column)] => &column.name == time_index, + [Expr::Literal(value, _)] => !value.is_null(), + _ => false, + }; + if (function.func.name() != "count" + && function.func.name() != aggr_state_func_name("count")) + || function.params.distinct + || function.params.filter.is_some() + || !function.params.order_by.is_empty() + || !count_all_rows + { + return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate))); + } + let provider = provider.clone_for_scan(); + provider.with_metadata_aggr_hint(); + let mut scan = scan.clone(); + scan.source = std::sync::Arc::new(DefaultTableSource::new(std::sync::Arc::new(provider))); + aggregate.input = std::sync::Arc::new(LogicalPlan::TableScan(scan)); + Ok(Transformed::yes(LogicalPlan::Aggregate(aggregate))) + } + fn set_hints( plan: LogicalPlan, rewriter: &mut ScanHintRewriter, @@ -321,7 +377,13 @@ impl TreeNodeRewriter for ScanHintRewriter { } } - ScanHintRule::set_hints(node, self) + let counted = ScanHintRule::set_metadata_aggr_hint(node)?; + let hinted = ScanHintRule::set_hints(counted.data, self)?; + Ok(Transformed::new( + hinted.data, + counted.transformed || hinted.transformed, + hinted.tnr, + )) } fn f_up(&mut self, node: LogicalPlan) -> Result> { @@ -693,6 +755,53 @@ mod test { MetaRegionEngine, mock_table_provider, mock_table_provider_with_tsid, }; + #[test] + fn metadata_aggr_hint_is_scoped_and_restricted() { + use datafusion::functions_aggregate::expr_fn::{count, count_distinct}; + let region_id = RegionId::new(1, 1); + let metadata = mock_table_provider(region_id).region_metadata(); + let provider = Arc::new(DummyTableProvider::new( + region_id, + Arc::new(MetaRegionEngine::with_metadata(metadata.clone()).with_engine_name("mito")), + metadata, + )); + for (groups, function, expected) in [ + (vec![], count(col("ts")), true), + (vec![], count(lit(1i64)), true), + (vec![], count(col("v0")), false), + (vec![], count_distinct(col("ts")), false), + (vec![col("k0")], count(col("ts")), false), + ] { + let plan = LogicalPlanBuilder::from(scan_plan(provider.clone(), "t")) + .aggregate(groups, vec![function]) + .unwrap() + .build() + .unwrap(); + let rewritten = ScanHintRule::optimize(plan).unwrap().data; + assert_eq!(scan_requests(&rewritten)[0].metadata_aggr_hint, expected); + assert!(!provider.scan_request().metadata_aggr_hint); + assert!(!ScanHintRule::optimize(rewritten).unwrap().transformed); + } + let plan = LogicalPlanBuilder::from(scan_plan(provider.clone(), "t")) + .limit(0, Some(1)) + .unwrap() + .aggregate(Vec::::new(), vec![count(col("ts"))]) + .unwrap() + .build() + .unwrap(); + let rewritten = ScanHintRule::optimize(plan).unwrap().data; + assert!(!scan_requests(&rewritten)[0].metadata_aggr_hint); + let plan = LogicalPlanBuilder::from(scan_plan(provider, "t")) + .filter(col("v0").gt(lit(1.0))) + .unwrap() + .aggregate(Vec::::new(), vec![count(col("ts"))]) + .unwrap() + .build() + .unwrap(); + let rewritten = ScanHintRule::optimize(plan).unwrap().data; + assert!(!scan_requests(&rewritten)[0].metadata_aggr_hint); + } + #[test] fn single_evaluation_sets_last_row_on_the_rewritten_scan() { let provider = Arc::new(mock_table_provider(RegionId::new(1, 1))); diff --git a/src/query/src/optimizer/test_util.rs b/src/query/src/optimizer/test_util.rs index 09f72bb08b7..5931e1e7a8a 100644 --- a/src/query/src/optimizer/test_util.rs +++ b/src/query/src/optimizer/test_util.rs @@ -41,6 +41,7 @@ use crate::dummy_catalog::DummyTableProvider; /// A mock region engine that can be used for testing the optimizer. pub(crate) struct MetaRegionEngine { metadatas: HashMap, + name: &'static str, } impl MetaRegionEngine { @@ -49,14 +50,23 @@ impl MetaRegionEngine { let mut metadatas = HashMap::new(); metadatas.insert(metadata.region_id, metadata); - Self { metadatas } + Self { + metadatas, + name: "MetaRegionEngine", + } + } + + /// Sets the engine name exposed to scan-hint capability checks. + pub(crate) fn with_engine_name(mut self, name: &'static str) -> Self { + self.name = name; + self } } #[async_trait] impl RegionEngine for MetaRegionEngine { fn name(&self) -> &str { - "MetaRegionEngine" + self.name } async fn handle_request( diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index a2e47640d42..8f2b3d6c228 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -318,6 +318,10 @@ pub struct ScannerProperties { /// Whether total_rows is exact before applying query predicates. total_rows_is_exact: bool, + /// Exact rows after static query predicates, prepared against the scanner's + /// read view. Unknown unless an engine has proved all visibility conditions. + exact_num_rows: Option, + /// Whether to yield an empty batch to distinguish partition ranges. pub distinguish_partition_range: bool, @@ -353,6 +357,22 @@ impl ScannerProperties { self } + /// Sets an exact count for the complete scan, including static predicates. + pub fn with_exact_num_rows(mut self, rows: Option) -> Self { + self.exact_num_rows = rows; + self + } + + /// Returns the prepared exact count after all static scan predicates. + pub fn exact_num_rows(&self) -> Option { + self.exact_num_rows + } + + /// Invalidates prepared statistics when the scan gains a dynamic predicate. + pub fn clear_exact_num_rows(&mut self) { + self.exact_num_rows = None; + } + /// Creates a new [`ScannerProperties`] with the given partitioning. pub fn new(partitions: Vec>, append_mode: bool, total_rows: usize) -> Self { Self { @@ -360,6 +380,7 @@ impl ScannerProperties { append_mode, total_rows, total_rows_is_exact: false, + exact_num_rows: None, distinguish_partition_range: false, target_partitions: 0, logical_region: false, diff --git a/src/store-api/src/storage/requests.rs b/src/store-api/src/storage/requests.rs index 3c9d4951d4b..6ba43fb6af1 100644 --- a/src/store-api/src/storage/requests.rs +++ b/src/store-api/src/storage/requests.rs @@ -47,6 +47,9 @@ pub enum TimeSeriesDistribution { #[derive(Default, Clone, Debug, PartialEq)] pub struct ScanRequest { + /// Requests bounded asynchronous exact-count preparation for a scalar COUNT. + /// This is an optimization hint; unsupported scans retain normal execution. + pub metadata_aggr_hint: bool, /// Optional projection information for the scan. `None` reads all root /// columns. pub projection: Option>, diff --git a/src/table/src/predicate.rs b/src/table/src/predicate.rs index 8dc85b610f4..1a5b8398062 100644 --- a/src/table/src/predicate.rs +++ b/src/table/src/predicate.rs @@ -363,11 +363,7 @@ fn extract_from_binary_expr( let (ts, reverse) = get_timestamp_filter(ts_col_name, left, right)?; if reverse { // [lit] < ts_col - let ts_val = ts.convert_to(ts_col_unit)?.value(); - Some(TimestampRange::from_start(Timestamp::new( - ts_val + 1, - ts_col_unit, - ))) + strictly_after(ts, ts_col_unit) } else { // ts_col < [lit] ts.convert_to_ceil(ts_col_unit) @@ -394,11 +390,7 @@ fn extract_from_binary_expr( .map(|t| TimestampRange::until_end(t, false)) } else { // ts_col > [lit] - let ts_val = ts.convert_to(ts_col_unit)?.value(); - Some(TimestampRange::from_start(Timestamp::new( - ts_val + 1, - ts_col_unit, - ))) + strictly_after(ts, ts_col_unit) } } Operator::GtEq => { @@ -431,6 +423,16 @@ fn extract_from_binary_expr( } } +/// Returns the timestamps after `ts` in `unit`. The range is empty when `ts` +/// is the largest representable timestamp, rather than wrapping around. +fn strictly_after(ts: Timestamp, unit: TimeUnit) -> Option { + let ts_val = ts.convert_to(unit)?.value(); + Some(match ts_val.checked_add(1) { + Some(next) => TimestampRange::from_start(Timestamp::new(next, unit)), + None => TimestampRange::empty(), + }) +} + fn get_timestamp_filter(ts_col_name: &str, left: &Expr, right: &Expr) -> Option<(Timestamp, bool)> { let (col, lit, reverse) = match (left, right) { (Expr::Column(column), Expr::Literal(scalar, _)) => (column, scalar, false), @@ -576,6 +578,14 @@ mod tests { col("ts").gt(lit(ScalarValue::TimestampSecond(Some(1), None))), TimestampRange::from_start(Timestamp::new_millisecond(1001)), ); + + // No timestamp is after the maximum, in either operand order. The + // successor must not wrap around to the minimum. + let max = || lit(ScalarValue::TimestampMillisecond(Some(i64::MAX), None)); + for expr in [col("ts").gt(max()), max().lt(col("ts"))] { + let range = build_time_range_predicate("ts", TimeUnit::Millisecond, &[expr]); + assert!(range.is_empty(), "{range:?}"); + } } #[test] diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs index 80878fae5bc..fabc2b51d19 100644 --- a/src/table/src/table/scan.rs +++ b/src/table/src/table/scan.rs @@ -513,14 +513,18 @@ impl ExecutionPlan for RegionScanExec { _input_stats: &[Arc], args: &StatisticsArgs, ) -> DfResult> { - if args.partition().is_some() || !self.append_mode { + if args.partition().is_some() { return Ok(Arc::new(Statistics::new_unknown(self.schema().as_ref()))); } let scanner = self.scanner.lock().unwrap(); - let statistics = if scanner.properties().total_rows_is_exact() - && !scanner.has_predicate_without_region() - { + let rows = scanner.properties().exact_num_rows().or_else(|| { + (self.append_mode + && scanner.properties().total_rows_is_exact() + && !scanner.has_predicate_without_region()) + .then_some(self.total_rows) + }); + let statistics = if let Some(rows) = rows { // Only the row count is known. DataFusion answers `count(col)` as // `num_rows - null_count` and `count(DISTINCT col)` as `distinct_count` // without scanning, so these must stay absent unless the schema @@ -540,7 +544,7 @@ impl ExecutionPlan for RegionScanExec { }) .collect(); Statistics { - num_rows: Precision::Exact(self.total_rows), + num_rows: Precision::Exact(rows), total_byte_size: Default::default(), column_statistics, } @@ -1278,10 +1282,11 @@ mod test { #[test] fn test_count_statistics_require_exact_source_rows() { - for (append_mode, exact, expected) in [ - (true, false, Precision::Absent), - (true, true, Precision::Exact(3)), - (false, true, Precision::Absent), + for (append_mode, exact, prepared, expected) in [ + (true, false, None, Precision::Absent), + (true, true, None, Precision::Exact(3)), + (false, true, None, Precision::Absent), + (false, false, Some(2), Precision::Exact(2)), ] { // Column `a` is nullable and `ts` is not. let (schema, batch, metadata) = dynamic_filter_test_data(5685, true); @@ -1290,7 +1295,8 @@ mod test { properties: ScannerProperties::default() .with_append_mode(append_mode) .with_total_rows(3) - .with_total_rows_is_exact(exact), + .with_total_rows_is_exact(exact) + .with_exact_num_rows(prepared), metadata, dynamic_filters: Arc::new(Mutex::new(Vec::new())), observed_pool: Default::default(), diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index 950feb8a6ca..4277369afa8 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -3597,6 +3597,7 @@ min_compaction_interval = "0s" schedule_compaction_after_edit = true default_flat_format = true experimental_series_scan_v2 = false +experimental_metadata_aggr = false [region_engine.mito.index] aux_path = "" diff --git a/tests/cases/standalone/common/aggregate/non_append_metadata_count.result b/tests/cases/standalone/common/aggregate/non_append_metadata_count.result new file mode 100644 index 00000000000..9835ab7fe84 --- /dev/null +++ b/tests/cases/standalone/common/aggregate/non_append_metadata_count.result @@ -0,0 +1,146 @@ +-- The same results must hold with experimental_metadata_aggr enabled or disabled. +CREATE TABLE metadata_count_test ( + host STRING, + ts TIMESTAMP TIME INDEX, + v BIGINT, + PRIMARY KEY (host) +) WITH ('compaction.type' = 'twcs', 'compaction.twcs.trigger_file_num' = '2'); + +Affected Rows: 0 + +INSERT INTO metadata_count_test VALUES ('a', 1000, 1), ('a', 2000, NULL), ('a', 3000, 3); + +Affected Rows: 3 + +SELECT count(*) FROM metadata_count_test; + ++----------+ +| count(*) | ++----------+ +| 3 | ++----------+ + +ADMIN FLUSH_TABLE('metadata_count_test'); + ++------------------------------------------+ +| ADMIN FLUSH_TABLE('metadata_count_test') | ++------------------------------------------+ +| 0 | ++------------------------------------------+ + +INSERT INTO metadata_count_test VALUES ('a', 1000, 11), ('a', 4000, 4); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('metadata_count_test'); + ++------------------------------------------+ +| ADMIN FLUSH_TABLE('metadata_count_test') | ++------------------------------------------+ +| 0 | ++------------------------------------------+ + +DELETE FROM metadata_count_test WHERE host = 'a' AND ts = 3000; + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('metadata_count_test'); + ++------------------------------------------+ +| ADMIN FLUSH_TABLE('metadata_count_test') | ++------------------------------------------+ +| 0 | ++------------------------------------------+ + +SELECT count(*) FROM metadata_count_test; + ++----------+ +| count(*) | ++----------+ +| 3 | ++----------+ + +ADMIN COMPACT_TABLE('metadata_count_test'); + ++--------------------------------------------+ +| ADMIN COMPACT_TABLE('metadata_count_test') | ++--------------------------------------------+ +| 0 | ++--------------------------------------------+ + +SELECT count(*) FROM metadata_count_test; + ++----------+ +| count(*) | ++----------+ +| 3 | ++----------+ + +SELECT count(*) FROM metadata_count_test WHERE ts >= 1000 AND ts < 5000; + ++----------+ +| count(*) | ++----------+ +| 3 | ++----------+ + +SELECT count(*) FROM metadata_count_test WHERE ts < 3000; + ++----------+ +| count(*) | ++----------+ +| 2 | ++----------+ + +SELECT count(*) FROM metadata_count_test WHERE ts = 1000 OR ts = 4000; + ++----------+ +| count(*) | ++----------+ +| 2 | ++----------+ + +SELECT count(*) FROM metadata_count_test WHERE v > 3; + ++----------+ +| count(*) | ++----------+ +| 2 | ++----------+ + +SELECT count(v), count(DISTINCT ts) FROM metadata_count_test; + ++------------------------------+----------------------------------------+ +| count(metadata_count_test.v) | count(DISTINCT metadata_count_test.ts) | ++------------------------------+----------------------------------------+ +| 2 | 3 | ++------------------------------+----------------------------------------+ + +INSERT INTO metadata_count_test VALUES ('a', 1000, 111), ('a', 5000, 5); + +Affected Rows: 2 + +SELECT count(*) FROM metadata_count_test; + ++----------+ +| count(*) | ++----------+ +| 4 | ++----------+ + +DELETE FROM metadata_count_test WHERE host = 'a' AND ts = 1000; + +Affected Rows: 1 + +SELECT count(*) FROM metadata_count_test; + ++----------+ +| count(*) | ++----------+ +| 3 | ++----------+ + +DROP TABLE metadata_count_test; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/aggregate/non_append_metadata_count.sql b/tests/cases/standalone/common/aggregate/non_append_metadata_count.sql new file mode 100644 index 00000000000..7bf2934f2bb --- /dev/null +++ b/tests/cases/standalone/common/aggregate/non_append_metadata_count.sql @@ -0,0 +1,28 @@ +-- The same results must hold with experimental_metadata_aggr enabled or disabled. +CREATE TABLE metadata_count_test ( + host STRING, + ts TIMESTAMP TIME INDEX, + v BIGINT, + PRIMARY KEY (host) +) WITH ('compaction.type' = 'twcs', 'compaction.twcs.trigger_file_num' = '2'); + +INSERT INTO metadata_count_test VALUES ('a', 1000, 1), ('a', 2000, NULL), ('a', 3000, 3); +SELECT count(*) FROM metadata_count_test; +ADMIN FLUSH_TABLE('metadata_count_test'); +INSERT INTO metadata_count_test VALUES ('a', 1000, 11), ('a', 4000, 4); +ADMIN FLUSH_TABLE('metadata_count_test'); +DELETE FROM metadata_count_test WHERE host = 'a' AND ts = 3000; +ADMIN FLUSH_TABLE('metadata_count_test'); +SELECT count(*) FROM metadata_count_test; +ADMIN COMPACT_TABLE('metadata_count_test'); +SELECT count(*) FROM metadata_count_test; +SELECT count(*) FROM metadata_count_test WHERE ts >= 1000 AND ts < 5000; +SELECT count(*) FROM metadata_count_test WHERE ts < 3000; +SELECT count(*) FROM metadata_count_test WHERE ts = 1000 OR ts = 4000; +SELECT count(*) FROM metadata_count_test WHERE v > 3; +SELECT count(v), count(DISTINCT ts) FROM metadata_count_test; +INSERT INTO metadata_count_test VALUES ('a', 1000, 111), ('a', 5000, 5); +SELECT count(*) FROM metadata_count_test; +DELETE FROM metadata_count_test WHERE host = 'a' AND ts = 1000; +SELECT count(*) FROM metadata_count_test; +DROP TABLE metadata_count_test;