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 de3fad2b421..289827bfd74 100644 --- a/src/mito2/src/config.rs +++ b/src/mito2/src/config.rs @@ -480,17 +480,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 cd9088637ee..3348fb98f33 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,