From f19d142a4eec1d5ebb2f936bb6e0a3bc925f2847 Mon Sep 17 00:00:00 2001 From: aumnertic Date: Mon, 2 Nov 2026 10:41:14 -0500 Subject: [PATCH 1/7] feat: answer scalar COUNT on Mito from SST metadata Behind `experimental_metadata_aggr` (off by default), ScanHintRule marks an ungrouped scalar COUNT directly over a Mito scan. Mito then proves the scan's row count without reading SST data. Every file intersecting the query time range must be covered by the static predicates and have a known manifest row count. In deduplicating regions it must also share no (time, primary key) point with another file or a memtable, and its `__op_type` Parquet statistics must show no deletions. The statistics are read through the SST metadata caches, only for files that pass the manifest checks. RegionScanExec publishes the proven count as exact statistics, which lets DataFusion replace the scan with a literal. Other scans are unchanged. Overlaps are found with one time sweep over a segment tree of compressed primary key bounds, in O(N log N). The pairwise check remains as the test oracle and benchmark baseline. Co-Authored-By: Claude Opus 5.5 Signed-off-by: aumnertic --- config/config.md | 2 + config/datanode.example.toml | 4 + config/standalone.example.toml | 4 + src/mito2/AGENTS.md | 5 + src/mito2/Cargo.toml | 5 + .../benches/bench_metadata_aggr_overlap.rs | 271 +++++++ src/mito2/src/config.rs | 17 + src/mito2/src/engine.rs | 3 + src/mito2/src/engine/metadata_aggr_test.rs | 422 +++++++++++ src/mito2/src/read/scan_region.rs | 21 +- src/mito2/src/read/scan_region/aggr.rs | 707 ++++++++++++++++++ .../src/read/scan_region/aggr/overlap.rs | 347 +++++++++ src/mito2/src/read/seq_scan.rs | 2 + src/mito2/src/read/series_scan.rs | 2 + src/mito2/src/read/unordered_scan.rs | 2 + src/mito2/src/sst/parquet/reader.rs | 13 + src/query/src/dummy_catalog.rs | 13 + src/query/src/optimizer/scan_hint.rs | 111 ++- src/query/src/optimizer/test_util.rs | 14 +- src/store-api/src/region_engine.rs | 21 + src/store-api/src/storage/requests.rs | 3 + src/table/src/predicate.rs | 30 +- src/table/src/table/scan.rs | 26 +- tests-integration/tests/http.rs | 1 + .../non_append_metadata_count.result | 146 ++++ .../aggregate/non_append_metadata_count.sql | 28 + 26 files changed, 2196 insertions(+), 24 deletions(-) create mode 100644 src/mito2/benches/bench_metadata_aggr_overlap.rs create mode 100644 src/mito2/src/engine/metadata_aggr_test.rs create mode 100644 src/mito2/src/read/scan_region/aggr.rs create mode 100644 src/mito2/src/read/scan_region/aggr/overlap.rs create mode 100644 tests/cases/standalone/common/aggregate/non_append_metadata_count.result create mode 100644 tests/cases/standalone/common/aggregate/non_append_metadata_count.sql 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; From ab77265dbbc6a50b17f99db37c7b94ec41442383 Mon Sep 17 00:00:00 2001 From: aumnertic Date: Wed, 4 Nov 2026 02:42:21 -0500 Subject: [PATCH 2/7] feat: count exact files from metadata in partial COUNT scans When a hinted scalar COUNT has some exact files but other sources still need reading, Mito returns a split: the exact files with their manifest count, and a residual scan over the remaining files and memtables. Both parts share the original read view. `statistics_scan_plan` unions them, and `PartialAggrRule` turns the exact branch into one COUNT state before the aggregate-statistics rule, so only the residual sources are read. Classification and the deletion check run once, only for hinted COUNT scans, and a scan with no exact file is left unchanged. Ordinary scans are never split. Split parts keep the logical-region and query-load properties set on the original scanner. Co-Authored-By: Claude Opus 5.5 Signed-off-by: aumnertic --- src/mito2/src/engine.rs | 13 + src/mito2/src/engine/metadata_aggr_test.rs | 327 ++++++++++++++++- src/mito2/src/read/scan_region.rs | 83 ++++- src/mito2/src/read/scan_region/aggr.rs | 103 +++++- src/mito2/src/read/seq_scan.rs | 36 +- src/query/src/dummy_catalog.rs | 15 +- src/query/src/query_engine/state.rs | 15 + src/store-api/src/region_engine.rs | 18 + src/table/src/table/scan.rs | 5 + src/table/src/table/scan/statistics.rs | 329 ++++++++++++++++++ .../common/tql-explain-analyze/explain.result | 3 + 11 files changed, 921 insertions(+), 26 deletions(-) create mode 100644 src/table/src/table/scan/statistics.rs 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_| From f7ea6ba2e1a6c4539cf45253ce403e048d645360 Mon Sep 17 00:00:00 2001 From: aumnertic Date: Sun, 15 Nov 2026 02:24:10 -0500 Subject: [PATCH 3/7] refactor: bound residual memtables by their containers in metadata COUNT splits Following review, the split no longer pins memtable reads to a sequence fence. Bulk memtables deduplicate parts before the sequence is published, so a read bounded below the surviving version could lose that row. Instead, a file can only be exact if it is time-disjoint from the container of every captured memtable range, the time range of every row the range can ever yield: - Time partitions now keep their range when frozen, and scans list memtables with it (`MemtableVersion::list_memtables_with_time_ranges`). A time-series range reads its live series set, so its container is its partition. - Bulk ranges read immutable parts captured when they are built, so their container is the captured part's time range. - The container is carried as `MemRangeBuilder::container_time_range`, apart from the memtable stats. A range without one makes every file residual. The aggregate replacement moves to its own PR. `take_statistics_split` now returns the rows counted from metadata and the residual scanner, and a dynamic predicate drops a prepared split. Co-Authored-By: Claude Opus 5.5 Signed-off-by: aumnertic --- src/mito2/src/engine.rs | 13 - src/mito2/src/engine/metadata_aggr_test.rs | 571 +++++++++--------- src/mito2/src/memtable.rs | 24 +- src/mito2/src/memtable/bulk.rs | 12 + src/mito2/src/memtable/time_partition.rs | 42 +- src/mito2/src/memtable/version.rs | 82 ++- src/mito2/src/read/range.rs | 23 +- src/mito2/src/read/scan_region.rs | 37 +- src/mito2/src/read/scan_region/aggr.rs | 165 +++-- src/mito2/src/read/seq_scan.rs | 10 +- src/query/src/dummy_catalog.rs | 15 +- src/query/src/query_engine/state.rs | 15 - src/store-api/src/region_engine.rs | 20 +- src/table/src/table/scan.rs | 5 - src/table/src/table/scan/statistics.rs | 329 ---------- .../common/tql-explain-analyze/explain.result | 3 - 16 files changed, 634 insertions(+), 732 deletions(-) delete mode 100644 src/table/src/table/scan/statistics.rs diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index c9ab7f71552..cf460122a8b 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -1276,14 +1276,6 @@ 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(); @@ -1309,11 +1301,6 @@ 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 80b2645f6f6..be17433b6d6 100644 --- a/src/mito2/src/engine/metadata_aggr_test.rs +++ b/src/mito2/src/engine/metadata_aggr_test.rs @@ -28,10 +28,10 @@ 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_engine::{RegionEngine, RegionScannerRef}; use store_api::region_request::{RegionDeleteRequest, RegionPutRequest, RegionRequest}; use store_api::storage::{RegionId, ScanRequest}; -use table::table::scan::{PartialAggrRule, statistics_scan_plan}; +use table::table::scan::RegionScanExec; use crate::config::MitoConfig; use crate::engine::MitoEngine; @@ -76,21 +76,6 @@ 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; @@ -201,7 +186,7 @@ async fn run_compaction_sql_and_fallback(merge_mode: &str) { .unwrap(); assert_eq!(scanner.properties().exact_num_rows(), Some(6)); let scan: Arc = - statistics_scan_plan(scanner, request.clone(), None, false).unwrap(); + Arc::new(RegionScanExec::new(scanner, request.clone(), None).unwrap()); let ctx = SessionContext::new(); ctx.register_table("t", Arc::new(CountTable { plan: scan })) .unwrap(); @@ -369,236 +354,6 @@ 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] @@ -667,19 +422,293 @@ 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. +/// Rows a scanner yields. +async fn scanned_rows(scanner: RegionScannerRef, request: ScanRequest) -> usize { + let plan = Arc::new(RegionScanExec::new(scanner, request, None).unwrap()); + datafusion::physical_plan::collect(plan, SessionContext::new().task_ctx()) + .await + .unwrap() + .iter() + .map(|batch| batch.num_rows()) + .sum() +} + +/// Rows a plain scan of the region yields for `request`. +async fn plain_rows(engine: &MitoEngine, region_id: RegionId, request: ScanRequest) -> usize { + let request = ScanRequest { + metadata_aggr_hint: false, + ..request + }; + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + scanned_rows(scanner, request).await +} + +/// The rows a hinted scan counts from metadata and the rows its residual scan +/// yields, or `None` if it does not split. +async fn split_rows( + engine: &MitoEngine, + region_id: RegionId, + request: ScanRequest, +) -> Option<(usize, usize)> { + let mut scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + let split = scanner.take_statistics_split()?; + Some(( + split.exact_rows, + scanned_rows(split.residual, request).await, + )) +} + +/// Metadata rows and residual rows of the hinted scans of +/// [`test_metadata_aggr_fourteen_day_workload`], in its order. +struct FourteenDaySplits { + whole: Option<(usize, usize)>, + from_day_7: Option<(usize, usize)>, + days_5_to_10: Option<(usize, usize)>, + after_put: Option<(usize, usize)>, + after_delete: Option<(usize, usize)>, +} + +/// Days 0..7 are compacted into one file, days 7..13 are separate flushes, +/// and day 13 is still in the memtable. The memtable partition follows the +/// 7-day compaction window, `[7d, 14d)`. +/// +/// - A time-series memtable range is bounded by that partition, so it keeps +/// the files of days 7..13 residual. Only the compacted file is counted +/// from metadata. +/// - A bulk memtable range is bounded by the part it captured, day 13, so +/// every file is counted from metadata. #[rstest::rstest] -#[case::bulk("flat", "bulk")] -#[case::time_series("primary_key", "time_series")] +#[case::time_series("primary_key", "time_series", FourteenDaySplits { + whole: Some((7_000, 7_000)), + from_day_7: None, + // The memtable lies outside the query range, so it is not captured and + // bounds nothing; the compacted file is only partly covered. + days_5_to_10: Some((3_000, 2_000)), + // The put creates partition `[14d, 21d)`, the delete `[0, 7d)`. + after_put: Some((7_000, 7_001)), + after_delete: None, +})] +#[case::bulk("flat", "bulk", FourteenDaySplits { + whole: Some((13_000, 1_000)), + from_day_7: Some((6_000, 1_000)), + days_5_to_10: Some((3_000, 2_000)), + after_put: Some((13_000, 1_001)), + // The deletion's part overlaps the compacted file only. + after_delete: Some((6_000, 8_000)), +})] #[tokio::test] -async fn test_metadata_aggr_split_ignores_later_memtable_writes( +async fn test_metadata_aggr_fourteen_day_workload( #[case] sst_format: &str, #[case] memtable: &str, + #[case] splits: FourteenDaySplits, +) { + use api::v1::value::ValueData; + use store_api::region_request::RegionFlushRequest; + + const DAY_SECONDS: usize = 86_400; + let reads = Arc::new(Mutex::new(Vec::::new())); + let observed = reads.clone(); + let layer = MockLayerBuilder::default() + .reader_factory(Arc::new(move |path, _, inner| { + if path.ends_with(".parquet") { + observed.lock().unwrap().push(path.to_string()); + } + inner + })) + .build() + .unwrap(); + let mut env = TestEnv::new().await.with_mock_layer(layer); + let engine = env + .create_engine(MitoConfig { + experimental_metadata_aggr: true, + min_compaction_interval: Duration::from_secs(3600), + schedule_compaction_after_edit: false, + ..Default::default() + }) + .await; + let region_id = RegionId::new(2, 1); + let create = CreateRequestBuilder::new() + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.time_window", "7d") + .insert_option("compaction.twcs.trigger_file_num", "2") + .insert_option("sst_format", sst_format) + .insert_option("memtable.type", memtable) + .build(); + let schema = test_util::rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + let day_rows = |day: usize| { + let mut rows = test_util::build_rows_for_key("a", 0, 1000, 0); + for (minute, row) in rows.iter_mut().enumerate() { + row.values[2].value_data = Some(ValueData::TimestampMillisecondValue( + ((day * DAY_SECONDS + minute * 60) * 1000) as i64, + )); + } + api::v1::Rows { + schema: schema.clone(), + rows, + } + }; + for day in 0..14 { + test_util::put_rows(&engine, region_id, day_rows(day)).await; + if day < 13 { + engine + .handle_request( + region_id, + RegionRequest::Flush(RegionFlushRequest::default()), + ) + .await + .unwrap(); + } + if day == 6 { + compact(&engine, region_id).await; + } + } + + // Ordinary scans are never split, even with the option enabled. + let mut scanner = engine + .handle_query(region_id, ScanRequest::default()) + .await + .unwrap(); + assert!(scanner.take_statistics_split().is_none()); + + // The residual scanner keeps the properties the metric engine sets after + // Mito returns the scanner. This hinted scan also loads the files' metadata. + let hinted = ScanRequest { + metadata_aggr_hint: true, + ..Default::default() + }; + let mut scanner = engine + .handle_query(region_id, hinted.clone()) + .await + .unwrap(); + scanner.set_logical_region(true); + scanner.set_query_load_region_id(RegionId::new(2, 7)); + let split = scanner.take_statistics_split().unwrap(); + assert_eq!(Some(split.exact_rows), splits.whole.map(|(exact, _)| exact)); + assert!(split.residual.properties().is_logical_region()); + assert_eq!( + split.residual.properties().query_load_region_id(), + Some(RegionId::new(2, 7)) + ); + assert_eq!(split.residual.properties().exact_num_rows(), None); + drop(split); + + // A dynamic predicate invalidates the prepared split. + let mut scanner = engine + .handle_query(region_id, hinted.clone()) + .await + .unwrap(); + scanner.add_dyn_filter_to_predicate(vec![datafusion::physical_plan::expressions::lit(true)]); + assert!(scanner.take_statistics_split().is_none()); + + let ts = |day: i64| { + lit(ScalarValue::TimestampMillisecond( + Some(day * 86_400_000), + None, + )) + }; + // (filters, count, exact count, metadata and residual rows of a split) + for (filters, expected_count, exact, split) in [ + (vec![], 14_000, None, splits.whole), + // The memtable lies outside the query range, so it is not scanned. + (vec![col("ts").lt(ts(7))], 7_000, Some(7_000), None), + (vec![col("ts").gt_eq(ts(7))], 7_000, None, splits.from_day_7), + ( + vec![col("ts").gt_eq(ts(5)).and(col("ts").lt(ts(10)))], + 5_000, + None, + splits.days_5_to_10, + ), + ] { + reads.lock().unwrap().clear(); + let request = ScanRequest { + filters, + ..hinted.clone() + }; + let scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + assert_eq!(scanner.properties().exact_num_rows(), exact, "{request:?}"); + // The files' metadata is cached, so neither proof opens an SST. + let paths = reads.lock().unwrap().clone(); + assert!(paths.is_empty(), "COUNT opened SSTs: {paths:?}"); + assert_eq!( + split_rows(&engine, region_id, request.clone()).await, + split, + "{request:?}" + ); + assert_eq!( + plain_rows(&engine, region_id, request).await, + expected_count + ); + } + + for (timestamp, delete, expected, split) in [ + (15 * 86_400_000, false, 14_001, splits.after_put), + (86_400_000, true, 14_000, splits.after_delete), + ] { + let mut rows = test_util::build_rows_for_key("a", 0, 1, 0); + rows[0].values[2].value_data = Some(ValueData::TimestampMillisecondValue(timestamp)); + let rows = api::v1::Rows { + schema: schema.clone(), + rows, + }; + let request = if delete { + RegionRequest::Delete(RegionDeleteRequest { + rows, + hint: None, + partition_expr_version: None, + }) + } else { + RegionRequest::Put(RegionPutRequest { + rows, + hint: None, + partition_expr_version: None, + skip_wal: false, + }) + }; + engine.handle_request(region_id, request).await.unwrap(); + assert_eq!(split_rows(&engine, region_id, hinted.clone()).await, split); + assert_eq!( + plain_rows(&engine, region_id, hinted.clone()).await, + expected + ); + } + engine.stop().await.unwrap(); +} + +/// A captured memtable range bounds its rows by its container, not by the +/// rows present when it was captured. File A holds `a@100`, file B holds +/// `b@0` and `b@200`, and the memtable holds `a@memtable_second` when the +/// split is prepared. `a@100` is written again before the split executes. +/// +/// - A time-series range reads its live series set, so it sees the later +/// write. In the same daily partition A overlaps the container and stays +/// residual, although it is disjoint from the memtable's rows. In another +/// partition A is exact, and the later write lands in a partition the scan +/// never captured. +/// - A bulk range reads the parts captured with it, so A is exact even in the +/// same partition, and the later write lands in a part the scan never read. +#[rstest::rstest] +#[case::time_series_same_partition("primary_key", "time_series", 0, None)] +#[case::time_series_other_partition("primary_key", "time_series", 2 * 86_400, Some((1, 1)))] +#[case::bulk_same_partition("flat", "bulk", 0, Some((1, 1)))] +#[tokio::test] +async fn test_metadata_aggr_split_bounds_memtables_by_container( + #[case] sst_format: &str, + #[case] memtable: &str, + #[case] memtable_second: usize, + #[case] split: Option<(usize, usize)>, ) { let mut env = TestEnv::new().await; let engine = env @@ -707,33 +736,31 @@ async fn test_metadata_aggr_split_ignores_later_memtable_writes( }; 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; + test_util::put_rows(&engine, region_id, rows("a", &[memtable_second])).await; let request = ScanRequest { filters: vec![col("tag_0").eq(lit("a"))], metadata_aggr_hint: true, ..Default::default() }; - let scanner = engine + let mut scanner = engine .handle_query(region_id, request.clone()) .await .unwrap(); + let prepared = scanner.take_statistics_split(); // Written after the split is prepared, before it executes. test_util::put_rows(&engine, region_id, rows("a", &[100])).await; - let 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)) - ); + let actual = match prepared { + Some(prepared) => Some(( + prepared.exact_rows, + scanned_rows(prepared.residual, request.clone()).await, + )), + None => None, + }; + assert_eq!(actual, split); + // Whether or not the scan splits, `a@100` is counted once. + assert_eq!(plain_rows(&engine, region_id, request).await, 2); engine.stop().await.unwrap(); } diff --git a/src/mito2/src/memtable.rs b/src/mito2/src/memtable.rs index a63423cc92d..342afc2a1f3 100644 --- a/src/mito2/src/memtable.rs +++ b/src/mito2/src/memtable.rs @@ -754,12 +754,28 @@ pub struct MemtableRange { context: MemtableRangeContextRef, /// Statistics for this memtable range. stats: MemtableStats, + /// Inclusive time range of every row the range can yield, set only when + /// the range reads content captured when it was built. + captured_time_range: Option<(Timestamp, Timestamp)>, } impl MemtableRange { /// Creates a new range from context and stats. pub fn new(context: MemtableRangeContextRef, stats: MemtableStats) -> Self { - Self { context, stats } + Self { + context, + stats, + captured_time_range: None, + } + } + + /// Marks the range as reading immutable content captured when it was + /// built, whose rows all lie in the inclusive `time_range`. Writes after + /// that never reach the range. + #[must_use] + pub(crate) fn with_captured_time_range(mut self, time_range: (Timestamp, Timestamp)) -> Self { + self.captured_time_range = Some(time_range); + self } /// Returns the statistics for this range. @@ -767,6 +783,12 @@ impl MemtableRange { &self.stats } + /// Returns the inclusive time range of the captured content, if the range + /// reads only content captured when it was built. + pub(crate) fn captured_time_range(&self) -> Option<(Timestamp, Timestamp)> { + self.captured_time_range + } + /// Returns the id of the memtable to read. pub fn id(&self) -> MemtableId { self.context.id diff --git a/src/mito2/src/memtable/bulk.rs b/src/mito2/src/memtable/bulk.rs index ef7e89171ea..cf613372803 100644 --- a/src/mito2/src/memtable/bulk.rs +++ b/src/mito2/src/memtable/bulk.rs @@ -557,6 +557,7 @@ impl Memtable for BulkMemtable { bulk_parts.unordered_part.to_bulk_part(&self.metadata)? { let part_stats = unordered_bulk_part.to_memtable_stats(&self.metadata); + let captured = part_stats.time_range; let range = MemtableRange::new( Arc::new(MemtableRangeContext::new( self.id, @@ -569,6 +570,11 @@ impl Memtable for BulkMemtable { )), part_stats, ); + // The range reads a snapshot of the unordered part. + let range = match captured { + Some(time_range) => range.with_captured_time_range(time_range), + None => range, + }; ranges.insert(range_id, range); range_id += 1; } @@ -581,6 +587,7 @@ impl Memtable for BulkMemtable { } let part_stats = part_wrapper.part.to_memtable_stats(&self.metadata); + let captured = part_stats.time_range; let iter_builder: Box = match &part_wrapper.part { PartToMerge::Bulk { part, .. } => Box::new(BulkRangeIterBuilder { part: part.clone(), @@ -610,6 +617,11 @@ impl Memtable for BulkMemtable { )), part_stats, ); + // Parts are immutable once added, and the range holds this one. + let range = match captured { + Some(time_range) => range.with_captured_time_range(time_range), + None => range, + }; ranges.insert(range_id, range); range_id += 1; } diff --git a/src/mito2/src/memtable/time_partition.rs b/src/mito2/src/memtable/time_partition.rs index 0ca88ca9a70..117621ab26c 100644 --- a/src/mito2/src/memtable/time_partition.rs +++ b/src/mito2/src/memtable/time_partition.rs @@ -38,7 +38,7 @@ use store_api::metadata::RegionMetadataRef; use crate::error; use crate::error::{InvalidRequestSnafu, Result}; use crate::memtable::bulk::part::{BulkPart, BulkPartConverter}; -use crate::memtable::version::SmallMemtableVec; +use crate::memtable::version::{SmallMemtableVec, SmallPartTimeRangeVec}; use crate::memtable::{KeyValues, MemtableBuilderRef, MemtableId, MemtableRef}; use crate::sst::{FlatSchemaOptions, to_flat_sst_arrow_schema}; @@ -403,6 +403,20 @@ impl TimePartitions { memtables.extend(inner.parts.iter().map(|part| part.memtable.clone())); } + /// Appends memtables in partitions with their partition time ranges. + pub(crate) fn list_memtables_with_time_ranges( + &self, + memtables: &mut Vec<(MemtableRef, PartTimeRange)>, + ) { + let inner = self.inner.lock().unwrap(); + memtables.extend( + inner + .parts + .iter() + .map(|part| (part.memtable.clone(), part.time_range)), + ); + } + /// Returns the number of partitions. pub fn num_partitions(&self) -> usize { let inner = self.inner.lock().unwrap(); @@ -505,10 +519,16 @@ impl TimePartitions { .sum() } - /// Append memtables in partitions to small vec. - pub(crate) fn list_memtables_to_small_vec(&self, memtables: &mut SmallMemtableVec) { + /// Append memtables in partitions to small vec, and their partition time + /// ranges to `time_ranges` in the same order. + pub(crate) fn list_memtables_to_small_vec( + &self, + memtables: &mut SmallMemtableVec, + time_ranges: &mut SmallPartTimeRangeVec, + ) { let inner = self.inner.lock().unwrap(); memtables.extend(inner.parts.iter().map(|part| part.memtable.clone())); + time_ranges.extend(inner.parts.iter().map(|part| part.time_range)); } /// Returns the next memtable id. @@ -779,9 +799,11 @@ impl PartitionsInner { } } -/// Time range of a partition. -#[derive(Debug, Clone, Copy)] -struct PartTimeRange { +/// Time range of a partition. Writes route every row to the partition whose +/// range contains its timestamp, so the range bounds every row the partition's +/// memtable can ever hold, including rows written later. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct PartTimeRange { /// Inclusive min timestamp of rows in the partition. min_timestamp: Timestamp, /// Exclusive max timestamp of rows in the partition. @@ -805,6 +827,14 @@ impl PartTimeRange { fn contains_timestamp(&self, ts: Timestamp) -> bool { self.min_timestamp <= ts && ts < self.max_timestamp } + + /// Returns the range as inclusive `(min, max)` bounds, or `None` if it + /// holds no timestamp. + pub(crate) fn to_inclusive(self) -> Option<(Timestamp, Timestamp)> { + let max = self.max_timestamp.value().checked_sub(1)?; + let max = Timestamp::new(max, self.max_timestamp.unit()); + (self.min_timestamp <= max).then_some((self.min_timestamp, max)) + } } struct PartitionToWrite<'a> { diff --git a/src/mito2/src/memtable/version.rs b/src/mito2/src/memtable/version.rs index cd5dae10315..bf4af3b12d1 100644 --- a/src/mito2/src/memtable/version.rs +++ b/src/mito2/src/memtable/version.rs @@ -25,10 +25,11 @@ use store_api::storage::SequenceNumber; use crate::error::Result; use crate::memtable::bulk::part::BulkPart; -use crate::memtable::time_partition::TimePartitions; +use crate::memtable::time_partition::{PartTimeRange, TimePartitions}; use crate::memtable::{KeyValues, MemtableBuilderRef, MemtableId, MemtableRef}; pub(crate) type SmallMemtableVec = SmallVec<[MemtableRef; 2]>; +pub(crate) type SmallPartTimeRangeVec = SmallVec<[PartTimeRange; 2]>; /// A version of current memtables in a region. #[derive(Debug, Clone)] @@ -41,6 +42,9 @@ pub(crate) struct MemtableVersion { /// might need to store more than one immutable memtable on the next time we /// flush the region. immutables: SmallMemtableVec, + /// Time range of the partition each immutable memtable was created for, + /// in the order of `immutables`. + immutable_time_ranges: SmallPartTimeRangeVec, /// Whether immutable memtables may contain skip-WAL writes. /// Flushes are serialized per region and cover all immutable memtables. immutable_has_skip_wal_writes: bool, @@ -54,6 +58,7 @@ impl MemtableVersion { MemtableVersion { mutable: Arc::new(MutableMemtables::new(mutable)), immutables: SmallVec::new(), + immutable_time_ranges: SmallVec::new(), immutable_has_skip_wal_writes: false, } } @@ -76,6 +81,24 @@ impl MemtableVersion { mems } + /// Lists mutable and immutable memtables with the time range of the + /// partition each was created for. A memtable never holds a row outside + /// its partition range, even after later writes. + pub(crate) fn list_memtables_with_time_ranges(&self) -> Vec<(MemtableRef, PartTimeRange)> { + debug_assert_eq!(self.immutables.len(), self.immutable_time_ranges.len()); + let mut mems = Vec::with_capacity(self.immutables.len() + self.mutable.num_partitions()); + self.mutable + .partitions + .list_memtables_with_time_ranges(&mut mems); + mems.extend( + self.immutables + .iter() + .cloned() + .zip(self.immutable_time_ranges.iter().copied()), + ); + mems + } + /// Returns a sequence lower bound covering mutable and immutable memtables. /// Empty memtables impose no compaction barrier, including newly forked ones. pub(crate) fn min_sequence(&self) -> Option { @@ -117,6 +140,7 @@ impl MemtableVersion { return Ok(Some(MemtableVersion { mutable: Arc::new(MutableMemtables::new(mutable)), immutables: self.immutables.clone(), + immutable_time_ranges: self.immutable_time_ranges.clone(), immutable_has_skip_wal_writes: self.immutable_has_skip_wal_writes, })); } @@ -139,14 +163,16 @@ impl MemtableVersion { let mut immutables = SmallVec::with_capacity(self.immutables.len() + self.mutable.num_partitions()); immutables.extend(self.immutables.iter().cloned()); + let mut immutable_time_ranges = self.immutable_time_ranges.clone(); // Pushes the mutable memtable to immutable list. self.mutable .partitions - .list_memtables_to_small_vec(&mut immutables); + .list_memtables_to_small_vec(&mut immutables, &mut immutable_time_ranges); Ok(Some(MemtableVersion { mutable, immutables, + immutable_time_ranges, immutable_has_skip_wal_writes: self.immutable_has_skip_wal_writes || self.mutable.has_skip_wal_writes(), })) @@ -154,12 +180,13 @@ impl MemtableVersion { /// Removes memtables by ids from immutable memtables. pub(crate) fn remove_memtables(&mut self, ids: &[MemtableId]) { - self.immutables = self + (self.immutables, self.immutable_time_ranges) = self .immutables .iter() - .filter(|mem| !ids.contains(&mem.id())) - .cloned() - .collect(); + .zip(&self.immutable_time_ranges) + .filter(|(mem, _)| !ids.contains(&mem.id())) + .map(|(mem, time_range)| (mem.clone(), *time_range)) + .unzip(); if self.immutables.is_empty() { self.immutable_has_skip_wal_writes = false; } @@ -415,4 +442,47 @@ mod tests { assert!(!replacement.has_skip_wal_writes()); assert!(frozen.has_skip_wal_writes()); } + + #[test] + fn test_partition_time_ranges_follow_memtables() { + let metadata = memtable_util::metadata_for_test(); + let partitions = TimePartitions::new( + metadata.clone(), + Arc::new(TimeSeriesMemtableBuilder::default()), + 0, + Some(Duration::from_secs(5)), + ); + let version = MemtableVersion::new(partitions); + for ts in [1000, 7000] { + let kvs = memtable_util::build_key_values(&metadata, "hello".to_string(), 0, &[ts], 1); + version.mutable.write(&kvs).unwrap(); + } + let ranges = |version: &MemtableVersion| { + let mut ranges: Vec<_> = version + .list_memtables_with_time_ranges() + .into_iter() + .map(|(mem, range)| { + let (min, max) = range.to_inclusive().unwrap(); + (mem.id(), min.value(), max.value()) + }) + .collect(); + ranges.sort_unstable(); + ranges + }; + // The upper bound of a partition is exclusive. + assert_eq!(ranges(&version), [(0, 0, 4999), (1, 5000, 9999)]); + + // Frozen memtables keep their partition ranges. The forked mutable + // memtable covers the partition of the latest row. + let mut frozen = version + .freeze_mutable(&metadata, Some(Duration::from_secs(5))) + .unwrap() + .unwrap(); + assert_eq!( + ranges(&frozen), + [(0, 0, 4999), (1, 5000, 9999), (2, 5000, 9999)] + ); + frozen.remove_memtables(&[0]); + assert_eq!(ranges(&frozen), [(1, 5000, 9999), (2, 5000, 9999)]); + } } diff --git a/src/mito2/src/read/range.rs b/src/mito2/src/read/range.rs index 5e6da0a5986..b5846dc87be 100644 --- a/src/mito2/src/read/range.rs +++ b/src/mito2/src/read/range.rs @@ -463,12 +463,33 @@ pub(crate) struct MemRangeBuilder { range: MemtableRange, /// Stats of a memtable. stats: MemtableStats, + /// Inclusive time range of every row the range can yield, including rows + /// written to its memtable after the range was built. `None` if unknown. + /// Unlike `stats`, it never shrinks to the rows present at build time. + container_time_range: Option<(Timestamp, Timestamp)>, } impl MemRangeBuilder { /// Builds a mem range builder from row groups. pub(crate) fn new(range: MemtableRange, stats: MemtableStats) -> Self { - Self { range, stats } + Self { + range, + stats, + container_time_range: None, + } + } + + /// Sets the inclusive time range bounding every row the range can yield. + #[must_use] + pub(crate) fn with_container_time_range(mut self, time_range: (Timestamp, Timestamp)) -> Self { + self.container_time_range = Some(time_range); + self + } + + /// Returns the inclusive time range bounding every row the range can + /// yield, or `None` if it is unknown. + pub(crate) fn container_time_range(&self) -> Option<(Timestamp, Timestamp)> { + self.container_time_range } /// Builds mem ranges to read in the memtable. diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index c1e2d8c07c1..76540be05d8 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -252,9 +252,6 @@ 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. @@ -294,7 +291,6 @@ 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, @@ -353,17 +349,6 @@ 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 { @@ -538,7 +523,7 @@ impl ScanRegion { } .fail(); } - let memtables = self.version.memtables.list_memtables(); + let memtables = self.version.memtables.list_memtables_with_time_ranges(); // Skip empty memtables and memtables out of time range. let mut mem_range_builders = Vec::new(); let filter_mode = pre_filter_mode( @@ -546,7 +531,7 @@ impl ScanRegion { self.version.options.merge_mode(), ); - for m in memtables { + for (m, partition_range) in memtables { // check if memtable is empty by reading stats. let Some((start, end)) = m.stats().time_range() else { continue; @@ -562,15 +547,22 @@ impl ScanRegion { .with_predicate(predicate.clone()) .with_sequence(SequenceRange::new( self.request.memtable_min_sequence, - self.request - .memtable_max_sequence - .or(self.metadata_aggr_fence), + self.request.memtable_max_sequence, )) .with_pre_filter_mode(filter_mode), )?; + // A range bounds its rows by its captured content when it has one, + // otherwise by its partition: memtables may keep accepting writes + // after the range is built, but only inside their partition. + let partition_range = partition_range.to_inclusive(); mem_range_builders.extend(ranges_in_memtable.ranges.into_values().map(|v| { let stats = v.stats().clone(); - MemRangeBuilder::new(v, stats) + let container = v.captured_time_range().or(partition_range); + let builder = MemRangeBuilder::new(v, stats); + match container { + Some(time_range) => builder.with_container_time_range(time_range), + None => builder, + } })); } @@ -1053,14 +1045,13 @@ impl ScanInput { &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, + exact_num_rows: None, statistics_split: None, series_index: self.series_index.clone(), ignore_range_index: self.ignore_range_index, diff --git a/src/mito2/src/read/scan_region/aggr.rs b/src/mito2/src/read/scan_region/aggr.rs index 240bf2ef3d8..6b3c25423d5 100644 --- a/src/mito2/src/read/scan_region/aggr.rs +++ b/src/mito2/src/read/scan_region/aggr.rs @@ -53,15 +53,12 @@ pub(crate) enum MetadataAggr { /// 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`. + /// Sum of the manifest row counts of the files whose rows are all yielded + /// exactly once, without other sources. pub(crate) exact_rows: usize, - /// Other files intersecting the query time range. Memtables always stay - /// in the residual scan. + /// Other files intersecting the query time range. Memtable ranges 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` @@ -88,21 +85,13 @@ fn resolve( 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, + remaining_files: classification + .remaining + .iter() + .map(|&i| input.files[i].clone()) + .collect(), })) } @@ -265,8 +254,17 @@ fn classify(input: &ScanInput, request: &ScanRequest) -> Option 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. +/// Returns, for each file in `files`, whether another file or a memtable range +/// may hold a row with the same primary key and timestamp. +/// +/// A memtable range is bounded by its container, the time range of every row +/// it can ever yield (see [`MemRangeBuilder::container_time_range`]), not by +/// the rows it held when it was captured: a time-series memtable keeps +/// accepting writes into its partition and its ranges read them. A range +/// without a known container overlaps every file. Containers carry no key +/// bounds, so a file overlapping one in time stays residual. +/// +/// [`MemRangeBuilder::container_time_range`]: crate::read::range::MemRangeBuilder::container_time_range fn overlapping_files(input: &ScanInput, files: &[usize]) -> Vec { let mapper = input.primary_key_mapper(); let mut extents: Vec<_> = files @@ -281,12 +279,9 @@ fn overlapping_files(input: &ScanInput, files: &[usize]) -> Vec { } }) .collect(); - // Memtable key bounds are unknown. for memtable in &input.memtables { - let stats = memtable.stats(); - match stats.time_range { + match memtable.container_time_range() { Some(time) => extents.push(Extent { time, key: None }), - None if stats.num_rows == 0 => {} None => return vec![true; files.len()], } } @@ -422,7 +417,12 @@ mod tests { use table::predicate::build_time_range_predicate; use super::*; + use crate::memtable::{ + BoxedBatchIterator, BoxedRecordBatchIterator, IterBuilder, MemScanMetrics, MemtableRange, + MemtableRangeContext, MemtableStats, + }; use crate::read::flat_projection::FlatProjectionMapper; + use crate::read::range::MemRangeBuilder; use crate::read::scan_region::PredicateGroup; use crate::sst::file::FileMeta; use crate::test_util::memtable_util::metadata_with_primary_key; @@ -518,12 +518,67 @@ mod tests { classification } + struct EmptyIterBuilder; + + impl IterBuilder for EmptyIterBuilder { + fn build(&self, _: Option) -> crate::error::Result { + Ok(Box::new(std::iter::empty())) + } + + fn is_record_batch(&self) -> bool { + true + } + + fn build_record_batch( + &self, + _: Option<(Timestamp, Timestamp)>, + _: Option, + ) -> crate::error::Result { + Ok(Box::new(std::iter::empty())) + } + } + + /// A memtable range holding `rows` rows within `data`, inside `container`. + fn memtable(data: (i64, i64), container: Option<(i64, i64)>, rows: usize) -> MemRangeBuilder { + let ms = |(start, end): (i64, i64)| { + ( + Timestamp::new_millisecond(start), + Timestamp::new_millisecond(end), + ) + }; + let stats = MemtableStats { + time_range: Some(ms(data)), + num_rows: rows, + num_ranges: 1, + ..Default::default() + }; + let context = Arc::new(MemtableRangeContext::new( + 0, + Box::new(EmptyIterBuilder), + Default::default(), + )); + let builder = MemRangeBuilder::new(MemtableRange::new(context, stats.clone()), stats); + match container { + Some(container) => builder.with_container_time_range(ms(container)), + None => builder, + } + } + async fn input(files: Vec, filters: &[Expr]) -> ScanInput { + input_with_memtables(files, filters, Vec::new()).await + } + + async fn input_with_memtables( + files: Vec, + filters: &[Expr], + memtables: Vec, + ) -> ScanInput { let env = SchedulerEnv::new().await; let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false)); let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap(); ScanInput::builder(env.access_layer.clone(), mapper) .with_files(files) + .with_memtables(memtables) .with_predicate(PredicateGroup::new(&metadata, filters).unwrap()) .with_time_range(Some(build_time_range_predicate( "ts", @@ -757,12 +812,9 @@ mod tests { 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::Split(plan)) => { + Some((plan.exact_rows, plan.remaining_files.len())) + } Some(MetadataAggr::Exact(_)) => panic!("unexpected exact count"), None => None, } @@ -770,12 +822,12 @@ mod tests { // 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))) + Some((3, 1)) ); - // An unknown residual count is only an estimate, never a reason to fail. + // A residual file with an unknown row count is scanned as usual. assert_eq!( split(vec![file(0, 10, 3, true), file(20, 30, 0, false)]).await, - Some((1, 3, 1, None)) + Some((3, 1)) ); // Without an exact file the scan stays unchanged. assert_eq!( @@ -783,4 +835,47 @@ mod tests { None ); } + + /// Memtable ranges are bounded by their containers, never by the rows + /// they held when captured. + #[tokio::test] + async fn test_metadata_aggr_memtable_containers() { + let split = |memtables: Vec| async move { + let files = vec![file(0, 10, 3, true), file(20, 30, 2, true)]; + let input = input_with_memtables(files, &[], memtables).await; + match counted(&input, &ScanRequest::default()) { + Some(MetadataAggr::Split(plan)) => { + Some((plan.exact_rows, plan.remaining_files.len())) + } + Some(MetadataAggr::Exact(_)) => panic!("memtables must stay residual"), + None => None, + } + }; + // The memtable only holds a row at 0, but its container reaches 15, + // so a later write may land in the first file's range. + assert_eq!( + split(vec![memtable((0, 0), Some((0, 15)), 1)]).await, + Some((2, 1)) + ); + // A container disjoint from both files leaves them exact. + assert_eq!( + split(vec![memtable((40, 40), Some((40, 49)), 1)]).await, + Some((5, 0)) + ); + // Touching endpoints overlap; both bounds are inclusive. + assert_eq!( + split(vec![memtable((31, 31), Some((30, 39)), 1)]).await, + Some((3, 1)) + ); + // Without a known container no file is exact, whatever the data range. + assert_eq!(split(vec![memtable((40, 40), None, 1)]).await, None); + assert_eq!( + split(vec![ + memtable((40, 40), Some((40, 49)), 1), + memtable((50, 50), None, 1), + ]) + .await, + None + ); + } } diff --git a/src/mito2/src/read/seq_scan.rs b/src/mito2/src/read/seq_scan.rs index 4c8dc2040c3..7d2d20ca5b9 100644 --- a/src/mito2/src/read/seq_scan.rs +++ b/src/mito2/src/read/seq_scan.rs @@ -606,12 +606,10 @@ impl RegionScanner for 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)?; + let residual = input.with_sources(plan.remaining_files, input.memtables.clone())?; Some(StatisticsSplit { - exact: self.split_part(exact), - inexact: self.split_part(inexact), - inexact_rows: plan.remaining_rows, + exact_rows: plan.exact_rows, + residual: self.split_part(residual), }) } @@ -658,7 +656,9 @@ impl RegionScanner for SeqScan { &mut self, filter_exprs: Vec>, ) -> Vec { + // Prepared counts did not see the dynamic predicate. self.properties.clear_exact_num_rows(); + self.statistics_split = None; self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs) } diff --git a/src/query/src/dummy_catalog.rs b/src/query/src/dummy_catalog.rs index 3934561bf82..1d4ce4a8c07 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::statistics_scan_plan; +use table::table::scan::RegionScanExec; use crate::error::{GetRegionMetadataSnafu, Result}; use crate::options::{FlowIncrementalMode, FlowQueryExtensions}; @@ -195,14 +195,11 @@ impl TableProvider for DummyTableProvider { } let query_memory_tracker = self.engine.query_memory_tracker(); - statistics_scan_plan( - scanner, - request, - query_memory_tracker, - self.query_ctx - .as_ref() - .is_some_and(|ctx| ctx.explain_verbose()), - ) + 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)) } fn supports_filters_pushdown( diff --git a/src/query/src/query_engine/state.rs b/src/query/src/query_engine/state.rs index 14700cafa3c..f93ce49f7ee 100644 --- a/src/query/src/query_engine/state.rs +++ b/src/query/src/query_engine/state.rs @@ -280,21 +280,6 @@ 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 3ef12c2400c..84c9fa6f58c 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -512,15 +512,17 @@ impl Default for QueryScanContext { } } -/// Two source-disjoint scanners sharing the original scan read view. +/// A scan split into sources counted from metadata and a residual scan. +/// +/// The two parts are source-disjoint: no row the residual scan yields is +/// counted in `exact_rows`, so a scalar COUNT of the original scan is +/// `exact_rows` plus the COUNT of the residual scan. #[derive(Debug)] pub struct StatisticsSplit { - /// Sources with a proven exact query-visible row count. - pub exact: RegionScannerRef, + /// Query-visible rows of the sources answered from metadata. + pub exact_rows: usize, /// 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, + pub residual: RegionScannerRef, } /// A scanner that provides a way to scan the region concurrently. @@ -530,9 +532,9 @@ pub struct StatisticsSplit { 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. + /// Takes the source split an engine prepared for a scalar COUNT of a scan + /// hinted with `metadata_aggr_hint`. On success the caller must replace + /// this scanner with the residual scan and add the exact rows once. fn take_statistics_split(&mut self) -> Option { None } diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs index 3988273ed66..fabc2b51d19 100644 --- a/src/table/src/table/scan.rs +++ b/src/table/src/table/scan.rs @@ -59,11 +59,6 @@ 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 deleted file mode 100644 index a642a3ba111..00000000000 --- a/src/table/src/table/scan/statistics.rs +++ /dev/null @@ -1,329 +0,0 @@ -// 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 de6fe4eb67e..77870e8f062 100644 --- a/tests/cases/standalone/common/tql-explain-analyze/explain.result +++ b/tests/cases/standalone/common/tql-explain-analyze/explain.result @@ -186,7 +186,6 @@ 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_| @@ -349,7 +348,6 @@ 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_| @@ -542,7 +540,6 @@ 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_| From a34d60aae3c1b309b9a68a44f19010f826bafc78 Mon Sep 17 00:00:00 2001 From: Aum Date: Fri, 20 Nov 2026 15:26:37 +0800 Subject: [PATCH 4/7] test(mito): cover metadata COUNT and address core review Signed-off-by: aumnertic --- .../benches/bench_metadata_aggr_overlap.rs | 137 +----------------- src/mito2/src/config.rs | 11 -- src/mito2/src/read/scan_region/aggr.rs | 4 +- tests-integration/tests/main.rs | 1 + tests-integration/tests/metadata_aggr.rs | 116 +++++++++++++++ .../non_append_metadata_count.result | 2 +- .../aggregate/non_append_metadata_count.sql | 2 +- 7 files changed, 123 insertions(+), 150 deletions(-) create mode 100644 tests-integration/tests/metadata_aggr.rs diff --git a/src/mito2/benches/bench_metadata_aggr_overlap.rs b/src/mito2/benches/bench_metadata_aggr_overlap.rs index 37cdb8d45c2..196a18eb9cb 100644 --- a/src/mito2/benches/bench_metadata_aggr_overlap.rs +++ b/src/mito2/benches/bench_metadata_aggr_overlap.rs @@ -12,12 +12,10 @@ // 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. +//! Compares the metadata aggregate overlap check with 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}; @@ -122,21 +120,14 @@ fn bench_overlaps(c: &mut Criterion) { 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 {name}/{len}: sweep={} 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))) }); @@ -145,127 +136,5 @@ fn bench_overlaps(c: &mut Criterion) { } } -/// 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 1e21d67d5dd..a7a445fe134 100644 --- a/src/mito2/src/config.rs +++ b/src/mito2/src/config.rs @@ -466,17 +466,6 @@ 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/read/scan_region/aggr.rs b/src/mito2/src/read/scan_region/aggr.rs index afcf909d06c..88cdf5e08e9 100644 --- a/src/mito2/src/read/scan_region/aggr.rs +++ b/src/mito2/src/read/scan_region/aggr.rs @@ -235,9 +235,7 @@ fn overlapping_files(input: &ScanInput, files: &[usize]) -> Vec { let file = &input.files[index]; Extent { time: file.time_range(), - key: file - .raw_primary_key_range() - .and_then(|_| file.primary_key_range(mapper)), + key: file.primary_key_range(mapper), } }) .collect(); diff --git a/tests-integration/tests/main.rs b/tests-integration/tests/main.rs index 376fd24d7ff..b4abe0e1278 100644 --- a/tests-integration/tests/main.rs +++ b/tests-integration/tests/main.rs @@ -28,6 +28,7 @@ mod flow_ddl_event; mod gc_event; mod json2; mod jsonbench; +mod metadata_aggr; #[macro_use] mod sql; #[macro_use] diff --git a/tests-integration/tests/metadata_aggr.rs b/tests-integration/tests/metadata_aggr.rs new file mode 100644 index 00000000000..93281d8b167 --- /dev/null +++ b/tests-integration/tests/metadata_aggr.rs @@ -0,0 +1,116 @@ +// 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 common_query::{Output, OutputData}; +use common_recordbatch::RecordBatches; +use datatypes::arrow::array::Int64Array; +use frontend::instance::Instance; +use mito2::config::MitoConfig; +use servers::query_handler::sql::SqlQueryHandler; +use session::context::QueryContext; +use tests_integration::standalone::GreptimeDbStandaloneBuilder; + +const COUNT_SQL: &str = "SELECT count(*) FROM metadata_count"; + +#[rstest::rstest] +#[case::enabled(true)] +#[case::disabled(false)] +#[tokio::test(flavor = "multi_thread")] +async fn test_metadata_count_non_append(#[case] enabled: bool) { + common_telemetry::init_default_ut_logging(); + let standalone = GreptimeDbStandaloneBuilder::new("metadata_count_non_append") + .with_mito_config(MitoConfig { + experimental_metadata_aggr: enabled, + schedule_compaction_after_edit: false, + ..Default::default() + }) + .build() + .await; + let frontend = standalone.fe_instance(); + + execute_sql( + frontend, + "CREATE TABLE metadata_count ( + host STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, v BIGINT + ) ENGINE=mito WITH (append_mode = 'false')", + ) + .await; + execute_sql( + frontend, + "INSERT INTO metadata_count VALUES ('a', 1000, 1), ('a', 2000, 2), ('b', 1000, 3)", + ) + .await; + execute_sql(frontend, "ADMIN FLUSH_TABLE('metadata_count')").await; + + // The region has one SST and no mutable rows. Every row can be counted + // from metadata, but only when the flag is enabled. + assert_count_and_scan(frontend, 3, !enabled).await; + + // A tombstone overlaps one of the settled rows. COUNT must fall back to + // the ordinary scan (with either setting) to reconcile the deletion. + execute_sql( + frontend, + "DELETE FROM metadata_count WHERE host = 'a' AND ts = 1000", + ) + .await; + assert_count_and_scan(frontend, 2, true).await; +} + +async fn execute_sql(frontend: &Instance, sql: &str) -> Output { + SqlQueryHandler::do_query(frontend, sql, QueryContext::arc()) + .await + .remove(0) + .unwrap_or_else(|err| panic!("{sql}: {err}")) +} + +async fn assert_count_and_scan(frontend: &Instance, expected: i64, expect_scan: bool) { + let output = execute_sql(frontend, COUNT_SQL).await; + let batches = match output.data { + OutputData::RecordBatches(batches) => batches, + OutputData::Stream(stream) => RecordBatches::try_collect(stream).await.unwrap(), + OutputData::AffectedRows(rows) => { + panic!("expected a COUNT result, got {rows} affected rows") + } + }; + let counts = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .iter() + }) + .collect::>(); + assert_eq!(counts, vec![Some(expected)]); + + // ANALYZE includes the actual region plan below the frontend MergeScan. + let plan = execute_sql(frontend, &format!("EXPLAIN ANALYZE {COUNT_SQL}")) + .await + .data + .pretty_print() + .await; + assert_eq!( + plan.contains("SeqScan:"), + expect_scan, + "unexpected region plan:\n{plan}" + ); + if !expect_scan { + assert!( + plan.contains("PlaceholderRowExec"), + "expected the region scan to be replaced by a literal projection:\n{plan}" + ); + } +} diff --git a/tests/cases/standalone/common/aggregate/non_append_metadata_count.result b/tests/cases/standalone/common/aggregate/non_append_metadata_count.result index 9835ab7fe84..e358b2ad1b0 100644 --- a/tests/cases/standalone/common/aggregate/non_append_metadata_count.result +++ b/tests/cases/standalone/common/aggregate/non_append_metadata_count.result @@ -1,4 +1,4 @@ --- The same results must hold with experimental_metadata_aggr enabled or disabled. +-- Regression coverage for non-append COUNT with metadata aggregation off (the default). CREATE TABLE metadata_count_test ( host STRING, ts TIMESTAMP TIME INDEX, diff --git a/tests/cases/standalone/common/aggregate/non_append_metadata_count.sql b/tests/cases/standalone/common/aggregate/non_append_metadata_count.sql index 7bf2934f2bb..80f587f9b98 100644 --- a/tests/cases/standalone/common/aggregate/non_append_metadata_count.sql +++ b/tests/cases/standalone/common/aggregate/non_append_metadata_count.sql @@ -1,4 +1,4 @@ --- The same results must hold with experimental_metadata_aggr enabled or disabled. +-- Regression coverage for non-append COUNT with metadata aggregation off (the default). CREATE TABLE metadata_count_test ( host STRING, ts TIMESTAMP TIME INDEX, From 98dbc9643465d76c511f9c4b1c28b80a83159bfc Mon Sep 17 00:00:00 2001 From: Aum Date: Fri, 20 Nov 2026 15:53:17 +0800 Subject: [PATCH 5/7] test(mito): match metadata aggregate fixture region IDs Signed-off-by: aumnertic --- src/mito2/src/read/scan_region/aggr.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mito2/src/read/scan_region/aggr.rs b/src/mito2/src/read/scan_region/aggr.rs index 88cdf5e08e9..be199d03ea9 100644 --- a/src/mito2/src/read/scan_region/aggr.rs +++ b/src/mito2/src/read/scan_region/aggr.rs @@ -398,6 +398,7 @@ mod tests { } FileHandle::new( FileMeta { + region_id: RegionId::new(123, 456), file_id, num_rows: rows, time_range: ( From 20c9386968ed45d7b5d6292bb25f529125fab5af Mon Sep 17 00:00:00 2001 From: Aum Date: Fri, 20 Nov 2026 15:26:45 +0800 Subject: [PATCH 6/7] refactor(mito): pair immutable memtables with partition ranges Signed-off-by: aumnertic --- src/mito2/src/flush.rs | 8 +-- src/mito2/src/memtable/time_partition.rs | 15 +---- src/mito2/src/memtable/version.rs | 72 ++++++++++++------------ 3 files changed, 42 insertions(+), 53 deletions(-) diff --git a/src/mito2/src/flush.rs b/src/mito2/src/flush.rs index 2951d109d54..40589cc9352 100644 --- a/src/mito2/src/flush.rs +++ b/src/mito2/src/flush.rs @@ -401,7 +401,7 @@ impl RegionFlushTask { .memtables .immutables() .iter() - .map(|m| m.id()) + .map(|(mem, _)| mem.id()) .collect(); let flush_finished = FlushFinished { region_id: self.region_id, @@ -599,7 +599,7 @@ impl RegionFlushTask { let partition_expr = parse_partition_expr(self.partition_expr.as_deref())?; let hook = self.manifest_ctx.hook(); let mut all_sst_infos = Vec::new(); - for mem in memtables { + for (mem, _) in memtables { if mem.is_empty() { // Skip empty memtables. continue; @@ -2176,7 +2176,7 @@ mod tests { assert_eq!(1, job_scheduler.num_jobs()); // Check the new version. let version_data = version_control.current(); - assert_eq!(0, version_data.version.memtables.immutables()[0].id()); + assert_eq!(0, version_data.version.memtables.immutables()[0].0.id()); // Schedule remaining tasks. let output_rxs: Vec<_> = tasks .into_iter() @@ -2497,7 +2497,7 @@ mod tests { // Check the new version. let version_data = version_control.current(); - assert_eq!(0, version_data.version.memtables.immutables()[0].id()); + assert_eq!(0, version_data.version.memtables.immutables()[0].0.id()); // Assumes the flush job is finished. version_control.apply_edit( Some(RegionEdit { diff --git a/src/mito2/src/memtable/time_partition.rs b/src/mito2/src/memtable/time_partition.rs index 117621ab26c..fc3ce4ca935 100644 --- a/src/mito2/src/memtable/time_partition.rs +++ b/src/mito2/src/memtable/time_partition.rs @@ -38,7 +38,6 @@ use store_api::metadata::RegionMetadataRef; use crate::error; use crate::error::{InvalidRequestSnafu, Result}; use crate::memtable::bulk::part::{BulkPart, BulkPartConverter}; -use crate::memtable::version::{SmallMemtableVec, SmallPartTimeRangeVec}; use crate::memtable::{KeyValues, MemtableBuilderRef, MemtableId, MemtableRef}; use crate::sst::{FlatSchemaOptions, to_flat_sst_arrow_schema}; @@ -406,7 +405,7 @@ impl TimePartitions { /// Appends memtables in partitions with their partition time ranges. pub(crate) fn list_memtables_with_time_ranges( &self, - memtables: &mut Vec<(MemtableRef, PartTimeRange)>, + memtables: &mut impl Extend<(MemtableRef, PartTimeRange)>, ) { let inner = self.inner.lock().unwrap(); memtables.extend( @@ -519,18 +518,6 @@ impl TimePartitions { .sum() } - /// Append memtables in partitions to small vec, and their partition time - /// ranges to `time_ranges` in the same order. - pub(crate) fn list_memtables_to_small_vec( - &self, - memtables: &mut SmallMemtableVec, - time_ranges: &mut SmallPartTimeRangeVec, - ) { - let inner = self.inner.lock().unwrap(); - memtables.extend(inner.parts.iter().map(|part| part.memtable.clone())); - time_ranges.extend(inner.parts.iter().map(|part| part.time_range)); - } - /// Returns the next memtable id. pub(crate) fn next_memtable_id(&self) -> MemtableId { let inner = self.inner.lock().unwrap(); diff --git a/src/mito2/src/memtable/version.rs b/src/mito2/src/memtable/version.rs index bf4af3b12d1..8266fcf8d76 100644 --- a/src/mito2/src/memtable/version.rs +++ b/src/mito2/src/memtable/version.rs @@ -28,23 +28,17 @@ use crate::memtable::bulk::part::BulkPart; use crate::memtable::time_partition::{PartTimeRange, TimePartitions}; use crate::memtable::{KeyValues, MemtableBuilderRef, MemtableId, MemtableRef}; -pub(crate) type SmallMemtableVec = SmallVec<[MemtableRef; 2]>; -pub(crate) type SmallPartTimeRangeVec = SmallVec<[PartTimeRange; 2]>; - /// A version of current memtables in a region. #[derive(Debug, Clone)] pub(crate) struct MemtableVersion { /// Mutable memtable. pub(crate) mutable: MutableMemtablesRef, - /// Immutable memtables. + /// Immutable memtables paired with the time range of their original partition. /// /// We only allow one flush job per region but if a flush job failed, then we /// might need to store more than one immutable memtable on the next time we /// flush the region. - immutables: SmallMemtableVec, - /// Time range of the partition each immutable memtable was created for, - /// in the order of `immutables`. - immutable_time_ranges: SmallPartTimeRangeVec, + immutables: SmallVec<[(MemtableRef, PartTimeRange); 2]>, /// Whether immutable memtables may contain skip-WAL writes. /// Flushes are serialized per region and cover all immutable memtables. immutable_has_skip_wal_writes: bool, @@ -58,7 +52,6 @@ impl MemtableVersion { MemtableVersion { mutable: Arc::new(MutableMemtables::new(mutable)), immutables: SmallVec::new(), - immutable_time_ranges: SmallVec::new(), immutable_has_skip_wal_writes: false, } } @@ -68,8 +61,8 @@ impl MemtableVersion { self.mutable.has_skip_wal_writes() || self.immutable_has_skip_wal_writes } - /// Immutable memtables. - pub(crate) fn immutables(&self) -> &[MemtableRef] { + /// Immutable memtables and their original partition time ranges. + pub(crate) fn immutables(&self) -> &[(MemtableRef, PartTimeRange)] { &self.immutables } @@ -77,7 +70,7 @@ impl MemtableVersion { pub(crate) fn list_memtables(&self) -> Vec { let mut mems = Vec::with_capacity(self.immutables.len() + self.mutable.num_partitions()); self.mutable.list_memtables(&mut mems); - mems.extend_from_slice(&self.immutables); + mems.extend(self.immutables.iter().map(|(mem, _)| mem.clone())); mems } @@ -85,17 +78,11 @@ impl MemtableVersion { /// partition each was created for. A memtable never holds a row outside /// its partition range, even after later writes. pub(crate) fn list_memtables_with_time_ranges(&self) -> Vec<(MemtableRef, PartTimeRange)> { - debug_assert_eq!(self.immutables.len(), self.immutable_time_ranges.len()); let mut mems = Vec::with_capacity(self.immutables.len() + self.mutable.num_partitions()); self.mutable .partitions .list_memtables_with_time_ranges(&mut mems); - mems.extend( - self.immutables - .iter() - .cloned() - .zip(self.immutable_time_ranges.iter().copied()), - ); + mems.extend_from_slice(&self.immutables); mems } @@ -140,7 +127,6 @@ impl MemtableVersion { return Ok(Some(MemtableVersion { mutable: Arc::new(MutableMemtables::new(mutable)), immutables: self.immutables.clone(), - immutable_time_ranges: self.immutable_time_ranges.clone(), immutable_has_skip_wal_writes: self.immutable_has_skip_wal_writes, })); } @@ -163,16 +149,14 @@ impl MemtableVersion { let mut immutables = SmallVec::with_capacity(self.immutables.len() + self.mutable.num_partitions()); immutables.extend(self.immutables.iter().cloned()); - let mut immutable_time_ranges = self.immutable_time_ranges.clone(); // Pushes the mutable memtable to immutable list. self.mutable .partitions - .list_memtables_to_small_vec(&mut immutables, &mut immutable_time_ranges); + .list_memtables_with_time_ranges(&mut immutables); Ok(Some(MemtableVersion { mutable, immutables, - immutable_time_ranges, immutable_has_skip_wal_writes: self.immutable_has_skip_wal_writes || self.mutable.has_skip_wal_writes(), })) @@ -180,13 +164,7 @@ impl MemtableVersion { /// Removes memtables by ids from immutable memtables. pub(crate) fn remove_memtables(&mut self, ids: &[MemtableId]) { - (self.immutables, self.immutable_time_ranges) = self - .immutables - .iter() - .zip(&self.immutable_time_ranges) - .filter(|(mem, _)| !ids.contains(&mem.id())) - .map(|(mem, time_range)| (mem.clone(), *time_range)) - .unzip(); + self.immutables.retain(|(mem, _)| !ids.contains(&mem.id())); if self.immutables.is_empty() { self.immutable_has_skip_wal_writes = false; } @@ -201,7 +179,7 @@ impl MemtableVersion { pub(crate) fn immutables_usage(&self) -> usize { self.immutables .iter() - .map(|mem| mem.stats().estimated_bytes) + .map(|(mem, _)| mem.stats().estimated_bytes) .sum() } @@ -209,7 +187,7 @@ impl MemtableVersion { pub(crate) fn num_rows(&self) -> u64 { self.immutables .iter() - .map(|mem| mem.stats().num_rows as u64) + .map(|(mem, _)| mem.stats().num_rows as u64) .sum::() + self.mutable.num_rows() } @@ -220,6 +198,7 @@ impl MemtableVersion { self.mutable.list_memtables(&mut mutables); self.immutables .iter() + .map(|(mem, _)| mem) .chain(mutables.iter()) .filter_map(|mem| mem.stats().time_range()) .reduce(|(min_a, max_a), (min_b, max_b)| (min_a.min(min_b), max_a.max(max_b))) @@ -373,7 +352,11 @@ mod tests { frozen.mutable.mark_skip_wal_writes(); } frozen.mutable.write(&kvs).unwrap(); - let ids: Vec<_> = frozen.immutables().iter().map(|mem| mem.id()).collect(); + let ids: Vec<_> = frozen + .immutables() + .iter() + .map(|(mem, _)| mem.id()) + .collect(); frozen.remove_memtables(&ids); assert_eq!(new_skip_wal_writes, frozen.has_skip_wal_writes()); assert_eq!( @@ -388,7 +371,11 @@ mod tests { .freeze_mutable(&metadata, Some(Duration::from_secs(5))) .unwrap() .unwrap(); - let ids: Vec<_> = next_flush.immutables().iter().map(|mem| mem.id()).collect(); + let ids: Vec<_> = next_flush + .immutables() + .iter() + .map(|(mem, _)| mem.id()) + .collect(); next_flush.remove_memtables(&ids); assert!(!next_flush.has_skip_wal_writes()); } @@ -429,7 +416,11 @@ mod tests { .unwrap(); assert_eq!(2, retried.immutables().len()); assert!(retried.has_skip_wal_writes()); - let ids: Vec<_> = retried.immutables().iter().map(|mem| mem.id()).collect(); + let ids: Vec<_> = retried + .immutables() + .iter() + .map(|(mem, _)| mem.id()) + .collect(); retried.remove_memtables(&ids); assert!(!retried.has_skip_wal_writes()); @@ -482,7 +473,18 @@ mod tests { ranges(&frozen), [(0, 0, 4999), (1, 5000, 9999), (2, 5000, 9999)] ); + let snapshot = frozen.clone(); frozen.remove_memtables(&[0]); assert_eq!(ranges(&frozen), [(1, 5000, 9999), (2, 5000, 9999)]); + let [(remaining, range)] = frozen.immutables() else { + panic!("expected one immutable memtable after removing the first partition"); + }; + assert_eq!(remaining.id(), 1); + let (min, max) = range.to_inclusive().unwrap(); + assert_eq!((min.value(), max.value()), (5000, 9999)); + assert_eq!( + ranges(&snapshot), + [(0, 0, 4999), (1, 5000, 9999), (2, 5000, 9999)] + ); } } From 4aca170f8a8762e59fa83b6a7e4832926ad6fb13 Mon Sep 17 00:00:00 2001 From: Aum Date: Mon, 23 Nov 2026 10:17:51 +0800 Subject: [PATCH 7/7] chore: update compatibility CI version to v1.3.1 Signed-off-by: Aum --- tests/compatibility/ci.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/compatibility/ci.toml b/tests/compatibility/ci.toml index 2e89680c3f3..8113e9e96f3 100644 --- a/tests/compatibility/ci.toml +++ b/tests/compatibility/ci.toml @@ -6,7 +6,7 @@ # exercised by nightly runs (--nightly-window); they are not retained in the PR # window. Run .github/scripts/update-compat-versions.py --update --published-only # after release tags land. -from_versions = ["v1.2.1", "v1.3.0"] +from_versions = ["v1.2.1", "v1.3.1"] # Recent releases that must be able to reopen tables written by the PR build. downgrade_to_versions = ["v1.1.4"]