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 <noreply@anthropic.com>
Signed-off-by: aumnertic <aumnertic@gmail.com>
This commit is contained in:
aumnertic
2026-11-15 03:55:56 -05:00
co-authored by Claude Opus 5.5
parent 4f10cf7cc0
commit f7ea6ba2e1
16 changed files with 634 additions and 732 deletions
-13
View File
@@ -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);
+299 -272
View File
@@ -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<dyn ExecutionPlan> =
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::<String>::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<dyn ExecutionPlan>| {
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::<usize>(),
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::<String>::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();
}
+23 -1
View File
@@ -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
+12
View File
@@ -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<dyn IterBuilder> = 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;
}
+36 -6
View File
@@ -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> {
+76 -6
View File
@@ -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<SequenceNumber> {
@@ -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)]);
}
}
+22 -1
View File
@@ -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.
+14 -23
View File
@@ -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<SequenceNumber>,
/// 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<FileHandle>,
memtables: Vec<MemRangeBuilder>,
exact_num_rows: Option<usize>,
) -> Option<Self> {
#[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,
+130 -35
View File
@@ -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<FileHandle>,
/// 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<FileHandle>,
/// Physical source rows of the residual scan, if all are known.
pub(crate) remaining_rows: Option<usize>,
}
/// 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<FileHandle> {
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<Classification>
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<bool> {
let mapper = input.primary_key_mapper();
let mut extents: Vec<_> = files
@@ -281,12 +279,9 @@ fn overlapping_files(input: &ScanInput, files: &[usize]) -> Vec<bool> {
}
})
.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<MemScanMetrics>) -> crate::error::Result<BoxedBatchIterator> {
Ok(Box::new(std::iter::empty()))
}
fn is_record_batch(&self) -> bool {
true
}
fn build_record_batch(
&self,
_: Option<(Timestamp, Timestamp)>,
_: Option<MemScanMetrics>,
) -> crate::error::Result<BoxedRecordBatchIterator> {
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<FileHandle>, filters: &[Expr]) -> ScanInput {
input_with_memtables(files, filters, Vec::new()).await
}
async fn input_with_memtables(
files: Vec<FileHandle>,
filters: &[Expr],
memtables: Vec<MemRangeBuilder>,
) -> 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<MemRangeBuilder>| 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
);
}
}
+5 -5
View File
@@ -606,12 +606,10 @@ impl RegionScanner for SeqScan {
fn take_statistics_split(&mut self) -> Option<StatisticsSplit> {
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<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
) -> Vec<bool> {
// 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)
}
+6 -9
View File
@@ -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(
-15
View File
@@ -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.
+11 -9
View File
@@ -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<usize>,
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<StatisticsSplit> {
None
}
-5
View File
@@ -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";
-329
View File
@@ -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<dyn ExecutionPlan>,
source_rows: Option<usize>,
}
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<PlanProperties> {
self.input.properties()
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.input]
}
fn apply_expressions(
&self,
_: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn maintains_input_order(&self) -> Vec<bool> {
vec![true]
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
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<TaskContext>,
) -> Result<SendableRecordBatchStream> {
self.input.execute(partition, context)
}
fn reset_state(self: Arc<Self>) -> Result<Arc<dyn ExecutionPlan>> {
let input = self.input.clone().reset_state()?;
Ok(Arc::new(Self {
input,
source_rows: self.source_rows,
}))
}
fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
vec![if $exact {
ChildStats::At(partition)
} else {
ChildStats::Skip
}]
}
fn statistics_from_inputs(
&self,
input_stats: &[Arc<Statistics>],
args: &StatisticsArgs,
) -> Result<Arc<Statistics>> {
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<QueryMemoryTracker>,
explain_verbose: bool,
) -> Result<Arc<dyn ExecutionPlan>> {
let build = |scanner, request, tracker| -> Result<Arc<dyn ExecutionPlan>> {
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<dyn ExecutionPlan> = Arc::new(ExactRegionScanExec {
input: build(parts.exact, request.clone(), query_memory_tracker.clone())?,
source_rows,
});
let inexact: Arc<dyn ExecutionPlan> = 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<String>,
}
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<dyn ExecutionPlan>) -> Result<Option<Vec<Arc<dyn ExecutionPlan>>>> {
if let Some(union) = plan.downcast_ref::<UnionExec>() {
if union
.inputs()
.iter()
.any(|input| input.is::<ExactRegionScanExec>())
&& union.inputs().iter().all(|input| {
input.is::<ExactRegionScanExec>() || input.is::<InexactRegionScanExec>()
})
{
return Ok(Some(union.inputs().clone()));
}
return Ok(None);
}
if let Some(projection) = plan.downcast_ref::<ProjectionExec>()
&& let Some(inputs) = Self::inputs(projection.input())?
{
return inputs
.into_iter()
.map(|input| {
plan.clone().replace_children(
vec![input],
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)
})
.collect::<Result<Vec<_>>>()
.map(Some);
}
Ok(None)
}
fn partial(
aggregate: &AggregateExec,
input: Arc<dyn ExecutionPlan>,
) -> Result<Arc<dyn ExecutionPlan>> {
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<dyn ExecutionPlan>) -> Result<Transformed<Arc<dyn ExecutionPlan>>> {
let Some(aggregate) = plan.downcast_ref::<AggregateExec>() 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::<Result<Vec<_>>>()?;
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<dyn ExecutionPlan>,
_: &ConfigOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
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
}
}
@@ -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_|