(&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;