mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-04 00:15:29 +00:00
* 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 <noreply@anthropic.com> Signed-off-by: aumnertic <aumnertic@gmail.com> * test(mito): cover metadata COUNT and address core review Signed-off-by: aumnertic <aumnertic@gmail.com> * test(mito): match metadata aggregate fixture region IDs Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): prove SST row counts before publishing exact statistics Signed-off-by: aumnertic <aumnertic@gmail.com> * test(mito2): add SQLness coverage for the SST footer marker Signed-off-by: aumnertic <aumnertic@gmail.com> * test(mito2): verify tightened partition bounds and source estimates Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): keep lazy footer reads sendable Signed-off-by: aumnertic <aumnertic@gmail.com> * test(mito2): use valid sequence fences and SST owners Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): validate SST key bounds before metadata count Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): verify SST time bounds before metadata count Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): own SST inputs to asynchronous bound checks Signed-off-by: aumnertic <aumnertic@gmail.com> * test(mito2): match displayed scan names in COUNT fallback Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): keep SST replacements coherent with metadata counts Signed-off-by: aumnertic <aumnertic@gmail.com> * refactor(cmd): reuse the replacement SST reader during validation Signed-off-by: aumnertic <aumnertic@gmail.com> * test(mito2): verify listed SST sizes against object storage Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): keep metadata count proofs within the SST read set Signed-off-by: aumnertic <aumnertic@gmail.com> * docs(mito2): use the actual scan memory limit key Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): gate metadata counts on trusted SST dedup markers Record the provenance of engine-written dedup markers in the manifest. Clear it for external imports and preserve it during internal transfers. Require this proof for metadata counts over non-append multi-row SSTs. Keep the live file metadata consistent when an import supersedes a background publication, and cover checkpoint downgrade and reopen. Signed-off-by: aumnertic <aumnertic@gmail.com> --------- Signed-off-by: aumnertic <aumnertic@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
151 lines
5.1 KiB
Rust
151 lines
5.1 KiB
Rust
// 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::cluster::GreptimeDbClusterBuilder;
|
|
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;
|
|
}
|
|
|
|
#[rstest::rstest]
|
|
#[case::enabled(true)]
|
|
#[case::disabled(false)]
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn test_metadata_count_distributed(#[case] enabled: bool) {
|
|
let cluster = GreptimeDbClusterBuilder::new("metadata_count_distributed")
|
|
.await
|
|
.with_datanodes(2)
|
|
.with_mito_config(MitoConfig {
|
|
experimental_metadata_aggr: enabled,
|
|
..Default::default()
|
|
})
|
|
.build(false)
|
|
.await;
|
|
let frontend = cluster.fe_instance();
|
|
execute_sql(
|
|
frontend,
|
|
"CREATE TABLE metadata_count (
|
|
host STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, v BIGINT
|
|
) PARTITION ON COLUMNS (host) (host < 'm', host >= 'm')
|
|
ENGINE=mito WITH (append_mode = 'false')",
|
|
)
|
|
.await;
|
|
execute_sql(
|
|
frontend,
|
|
"INSERT INTO metadata_count VALUES
|
|
('a', 1000, 1), ('a', 2000, 2), ('z', 1000, 3), ('z', 2000, 4)",
|
|
)
|
|
.await;
|
|
execute_sql(frontend, "ADMIN FLUSH_TABLE('metadata_count')").await;
|
|
assert_count_and_scan(frontend, 4, !enabled).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::<Int64Array>()
|
|
.unwrap()
|
|
.iter()
|
|
})
|
|
.collect::<Vec<_>>();
|
|
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}"
|
|
);
|
|
}
|
|
}
|