fix(mito2): prove SST row counts before publishing exact statistics

Signed-off-by: aumnertic <aumnertic@gmail.com>
This commit is contained in:
aumnertic
2026-11-25 21:47:22 -05:00
parent 8d3b05dd7a
commit be7f6e6dcd
31 changed files with 835 additions and 214 deletions
+2 -2
View File
@@ -227,7 +227,7 @@
| `region_engine.mito.schedule_compaction_after_edit` | Bool | `true` | Whether to allow to schedule a compaction after a successful region edit.<br/><br/>Setting this to "true" is a necessary but not sufficient condition for scheduling compaction after a region edit.<br/>Other constraints, such as "min_compaction_interval", may still prevent compaction from being scheduled.<br/>Setting this to "false", however, guarantees that compaction will not be scheduled after a region edit. |
| `region_engine.mito.default_flat_format` | Bool | `true` | Whether to enable flat format as the default SST format. |
| `region_engine.mito.experimental_series_scan_v2` | Bool | `false` | Whether to enable the experimental two-phase mode for eligible metric series scans. |
| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST data.<br/>May read Parquet footers to rule out deletions; ingestion does no extra work. |
| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.<br/>May read Parquet footers to prove uniqueness and the absence of deletes. |
| `region_engine.mito.index` | -- | -- | The options for index in Mito engine. |
| `region_engine.mito.index.aux_path` | String | `""` | Auxiliary directory path for the index in filesystem, used to store intermediate files for<br/>creating the index and staging files for searching the index, defaults to `{data_home}/index_intermediate`.<br/>The default name for this directory is `index_intermediate` for backward compatibility.<br/><br/>This path contains two subdirectories:<br/>- `__intm`: for storing intermediate files used during creating index.<br/>- `staging`: for storing staging files used during searching index. |
| `region_engine.mito.index.staging_size` | String | `2GB` | The max capacity of the staging directory. |
@@ -717,7 +717,7 @@
| `region_engine.mito.schedule_compaction_after_edit` | Bool | `true` | Whether to allow to schedule a compaction after a successful region edit.<br/><br/>Setting this to "true" is a necessary but not sufficient condition for scheduling compaction after a region edit.<br/>Other constraints, such as "min_compaction_interval", may still prevent compaction from being scheduled.<br/>Setting this to "false", however, guarantees that compaction will not be scheduled after a region edit. |
| `region_engine.mito.default_flat_format` | Bool | `true` | Whether to enable flat format as the default SST format. |
| `region_engine.mito.experimental_series_scan_v2` | Bool | `false` | Whether to enable the experimental two-phase mode for eligible metric series scans. |
| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST data.<br/>May read Parquet footers to rule out deletions; ingestion does no extra work. |
| `region_engine.mito.experimental_metadata_aggr` | Bool | `false` | Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.<br/>May read Parquet footers to prove uniqueness and the absence of deletes. |
| `region_engine.mito.index` | -- | -- | The options for index in Mito engine. |
| `region_engine.mito.index.aux_path` | String | `""` | Auxiliary directory path for the index in filesystem, used to store intermediate files for<br/>creating the index and staging files for searching the index, defaults to `{data_home}/index_intermediate`.<br/>The default name for this directory is `index_intermediate` for backward compatibility.<br/><br/>This path contains two subdirectories:<br/>- `__intm`: for storing intermediate files used during creating index.<br/>- `staging`: for storing staging files used during searching index. |
| `region_engine.mito.index.staging_size` | String | `2GB` | The max capacity of the staging directory. |
+2 -2
View File
@@ -742,8 +742,8 @@ default_flat_format = true
## Whether to enable the experimental two-phase mode for eligible metric series scans.
experimental_series_scan_v2 = false
## Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST data.
## May read Parquet footers to rule out deletions; ingestion does no extra work.
## Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.
## May read Parquet footers to prove uniqueness and the absence of deletes.
experimental_metadata_aggr = false
## The options for index in Mito engine.
+2 -2
View File
@@ -973,8 +973,8 @@ default_flat_format = true
## Whether to enable the experimental two-phase mode for eligible metric series scans.
experimental_series_scan_v2 = false
## Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST data.
## May read Parquet footers to rule out deletions; ingestion does no extra work.
## Answers eligible scalar COUNT queries from manifest row counts instead of scanning SST rows.
## May read Parquet footers to prove uniqueness and the absence of deletes.
experimental_metadata_aggr = false
## The options for index in Mito engine.
@@ -52,6 +52,15 @@ pub mod fix_order;
#[cfg(test)]
mod tests;
/// Checks the builtin COUNT identity, including inside its distributed state wrapper.
pub fn is_builtin_count_or_state(function: &AggregateUDF) -> bool {
let inner = function.inner();
inner.is::<Count>()
|| inner
.downcast_ref::<StateWrapper>()
.is_some_and(|state| state.inner().inner().is::<Count>())
}
/// Returns the name of the state function for the given aggregate function name.
/// The state function is used to compute the state of the aggregate function.
/// The state function's name is in the format `__<aggr_name>_state
+5 -5
View File
@@ -95,11 +95,11 @@ pending. DDL cancellation retains its existing scheduling fence and priority.
`tests/compatibility/manifest/table_compaction/` and
`tests/compatibility/manifest/pending_tails/`.
- **SST/Parquet layout** (`sst/`): readers must stay compatible with existing files.
Metadata COUNT (`read/scan_region/aggr.rs`) trusts a non-append SST's
`num_rows` only when its `__op_type` statistics show no deletes, which assumes
every SST of a non-append region is deduplicated within itself. Mito's flush,
bulk-part merge and compaction writers guarantee this; SSTs imported by region
edits or `sst_replace` must too.
Metadata COUNT (`read/scan_region/aggr.rs`) uses the footer for both file-local
uniqueness and all-Put evidence. Only writers that fold versions may add
`greptimedb.deduped`. LastNonNull can retain delete barriers, so it requires
all-Put output before adding the marker. Unmarked multi-row SSTs stay on the
scan path.
- **Index extensions**: shared contracts and provider validation live in `sst/index/registry.rs`;
typed sketch options are enterprise-gated. Lifecycle and failure tests live in
`engine/index_build_test.rs` and `compaction/`. A background rebuild must not replace a file
+1 -1
View File
@@ -867,7 +867,7 @@ impl DefaultSstMerger {
row_group_size,
..write_opts
};
let source = spawn_merge(source);
let source = spawn_merge(source).with_dedup_mode((!append_mode).then_some(merge_mode));
let mut metrics = Metrics::new(WriteType::Compaction);
let region_metadata = context.region_metadata.clone();
+2 -2
View File
@@ -248,8 +248,8 @@ pub struct MitoConfig {
pub experimental_series_scan_v2: bool,
/// Answers eligible scalar COUNT queries from manifest row counts instead
/// of scanning SST data. May read Parquet footers to rule out deletions;
/// ingestion does no extra work.
/// of scanning SST rows. May read Parquet footers to prove uniqueness and
/// the absence of deletes.
pub experimental_metadata_aggr: bool,
pub gc: GcConfig,
+197 -5
View File
@@ -21,16 +21,18 @@ use datafusion::catalog::Session;
use datafusion::datasource::TableProvider;
use datafusion::logical_expr::{Expr, TableType};
use datafusion::physical_plan::expressions::Column;
use datafusion::physical_plan::expressions::{DynamicFilterPhysicalExpr, lit as physical_lit};
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::{ExecutionPlan, displayable};
use datafusion::physical_plan::{ExecutionPlan, StatisticsArgs, StatisticsContext, displayable};
use datafusion::prelude::SessionContext;
use datafusion_common::ScalarValue;
use datafusion_common::stats::Precision;
use datafusion_expr::{col, lit};
use datatypes::arrow::datatypes::SchemaRef;
use object_store::layers::mock::MockLayerBuilder;
use store_api::region_engine::RegionEngine;
use store_api::region_request::{RegionDeleteRequest, RegionPutRequest, RegionRequest};
use store_api::storage::{RegionId, ScanRequest};
use store_api::storage::{RegionId, ScanRequest, TimeSeriesRowSelector};
use table::table::scan::RegionScanExec;
use crate::config::MitoConfig;
@@ -80,8 +82,7 @@ async fn test_metadata_aggr_compaction_sql_and_fallback() {
run_compaction_sql_and_fallback("last_row").await;
}
/// Both dedup merge modes keep one row per primary key and timestamp, so
/// field merging does not change which files are exact.
/// Compaction certifies LastNonNull outputs once delete barriers are removed.
#[tokio::test]
async fn test_metadata_aggr_compaction_sql_and_fallback_last_non_null() {
run_compaction_sql_and_fallback("last_non_null").await;
@@ -171,7 +172,7 @@ async fn run_compaction_sql_and_fallback(merge_mode: &str) {
assert_eq!(ordinary.properties().exact_num_rows(), None);
drop(ordinary);
// The first count may load the file's Parquet metadata. Later ones are
// served from the SST metadata cache, and no count reads SST data.
// served from the SST metadata cache without opening the SST.
let scanner = engine
.handle_query(region_id, request.clone())
.await
@@ -353,6 +354,197 @@ async fn test_metadata_aggr_reads_deletes_from_sst_statistics() {
engine.stop().await.unwrap();
}
#[tokio::test]
async fn test_metadata_aggr_replacement_with_duplicate_rows_falls_back() {
use bytes::Bytes;
use datatypes::arrow::array::UInt32Array;
use datatypes::arrow::compute::take_record_batch;
use parquet::arrow::ArrowWriter;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::file::properties::WriterProperties;
use store_api::storage::FileId;
use crate::manifest::action::RegionEdit;
use crate::sst::parquet::PARQUET_METADATA_KEY;
use crate::sst::parquet::metadata::DEDUPED_SST_KEY;
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
experimental_metadata_aggr: true,
schedule_compaction_after_edit: false,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let create = CreateRequestBuilder::new().build();
let table_dir = create.table_dir.clone();
let path_type = create.path_type;
let schema = test_util::rows_schema(&create);
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
put_and_flush(&engine, region_id, &schema, 0..3).await;
put_and_flush(&engine, region_id, &schema, 10..13).await;
let request = ScanRequest {
metadata_aggr_hint: true,
..Default::default()
};
let scan = engine
.handle_query(region_id, request.clone())
.await
.unwrap();
assert_eq!(scan.properties().exact_num_rows(), Some(6));
drop(scan);
let region = engine.get_region(region_id).unwrap();
let version = region.version();
let file = version.ssts.levels()[0]
.files
.values()
.min_by_key(|file| file.time_range().0)
.unwrap();
let store = region.access_layer.object_store();
let bytes = store
.read(&file.file_path(&table_dir, path_type))
.await
.unwrap()
.to_bytes();
let reader = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
let entries = reader
.metadata()
.file_metadata()
.key_value_metadata()
.unwrap();
assert!(entries.iter().any(|entry| entry.key == DEDUPED_SST_KEY));
let region_metadata = entries
.iter()
.find(|entry| entry.key == PARQUET_METADATA_KEY)
.unwrap()
.clone();
let batch = reader.build().unwrap().next().unwrap().unwrap();
// Preserve physical row count and time bounds, but replace the middle row
// with a second put for the first row's (primary key, timestamp).
let duplicate = take_record_batch(&batch, &UInt32Array::from(vec![0, 0, 2])).unwrap();
let mut replacement_bytes = Vec::new();
let props = WriterProperties::builder()
.set_key_value_metadata(Some(vec![region_metadata]))
.build();
let mut writer =
ArrowWriter::try_new(&mut replacement_bytes, duplicate.schema(), Some(props)).unwrap();
writer.write(&duplicate).unwrap();
writer.close().unwrap();
let replacement = crate::sst::file::FileMeta {
file_id: FileId::random(),
file_size: replacement_bytes.len() as u64,
..file.meta_ref().clone()
};
store
.write(
&replacement.file_path(&table_dir, path_type),
Bytes::from(replacement_bytes),
)
.await
.unwrap();
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![replacement],
files_to_remove: vec![file.meta_ref().clone()],
..Default::default()
},
)
.await
.unwrap();
let scan = engine
.handle_query(region_id, request.clone())
.await
.unwrap();
assert_eq!(scan.properties().exact_num_rows(), None);
for request in [request, ScanRequest::default()] {
let rows = common_recordbatch::RecordBatches::try_collect(
engine.scan_to_stream(region_id, request).await.unwrap(),
)
.await
.unwrap();
assert_eq!(rows.iter().map(|batch| batch.num_rows()).sum::<usize>(), 5);
}
engine.stop().await.unwrap();
}
#[tokio::test]
async fn test_metadata_aggr_statistics_follow_row_visibility() {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
experimental_metadata_aggr: true,
..Default::default()
})
.await;
for append in [false, true] {
let region_id = RegionId::new(1, if append { 2 } else { 1 });
let create = CreateRequestBuilder::new()
.insert_option("append_mode", if append { "true" } else { "false" })
.build();
let schema = test_util::rows_schema(&create);
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
put_and_flush(&engine, region_id, &schema, 0..3).await;
let request = ScanRequest {
metadata_aggr_hint: true,
..Default::default()
};
let scan = engine
.handle_query(region_id, request.clone())
.await
.unwrap();
let plan = RegionScanExec::new(scan, request.clone(), None).unwrap();
let row_count = |plan: &RegionScanExec| {
StatisticsContext::new()
.compute(plan, &StatisticsArgs::new())
.unwrap()
.num_rows
};
assert_eq!(row_count(&plan), Precision::Exact(3));
let filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], physical_lit(false)));
assert_eq!(plan.add_dyn_filters_to_predicate(vec![filter]), vec![true]);
assert_eq!(row_count(&plan), Precision::Absent);
for request in [
ScanRequest {
memtable_max_sequence: Some(1),
..request.clone()
},
ScanRequest {
snapshot_on_scan: true,
..request.clone()
},
ScanRequest {
series_row_selector: Some(TimeSeriesRowSelector::LastRow { after_merge: true }),
..request.clone()
},
ScanRequest {
limit: Some(1),
..request.clone()
},
] {
let scan = engine
.handle_query(region_id, request.clone())
.await
.unwrap();
let plan = RegionScanExec::new(scan, request, None).unwrap();
assert_eq!(row_count(&plan), Precision::Absent);
}
}
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]
+5 -1
View File
@@ -908,8 +908,12 @@ impl MemtableSstWriter {
let file_total = self.file_total();
let mut tasks = Vec::with_capacity(flat_sources.encoded.len() + flat_sources.sources.len());
let num_encoded = flat_sources.encoded.len();
let dedup_mode = (matches!(self.kind, MemtableWriteKind::Flush(_))
&& !version.options.append_mode)
.then(|| version.options.merge_mode());
for (source, max_sequence) in flat_sources.sources {
let write_request = self.new_write_request(version, max_sequence, source);
let write_request =
self.new_write_request(version, max_sequence, source.with_dedup_mode(dedup_mode));
let access_layer = self.access_layer.clone();
let write_opts = write_opts.clone();
let semaphore = self.write_semaphore.clone();
+2 -1
View File
@@ -1577,7 +1577,8 @@ impl MemtableCompactor {
),
float_field_encoding,
)?
.with_narthex_format(narthex_format);
.with_narthex_format(narthex_format)
.with_dedup_mode(dedup.then_some(merge_mode));
let mut metrics = BulkPartEncodeMetrics::default();
let encoded_part = encoder.encode_record_batch_iter(
boxed_iter,
+16
View File
@@ -69,10 +69,12 @@ use crate::memtable::bulk::context::{BulkIterContext, BulkIterContextRef};
use crate::memtable::bulk::part_reader::ParquetBulkPartIter;
use crate::memtable::time_series::{ValueBuilder, Values};
use crate::memtable::{BoxedRecordBatchIterator, MemScanMetrics, MemtableStats};
use crate::region::options::MergeMode;
use crate::sst::SeriesEstimator;
use crate::sst::index::IndexOutput;
use crate::sst::parquet::flat_format::primary_key_column_index;
use crate::sst::parquet::format::{PrimaryKeyArray, PrimaryKeyArrayBuilder};
use crate::sst::parquet::metadata::deduped_sst_marker;
use crate::sst::parquet::{
COLUMN_INDEX_TRUNCATE_LENGTH, PARQUET_METADATA_KEY, RowGroupValueBytes, SstInfo,
apply_column_compression, apply_float_field_encoding, apply_internal_column_encoding,
@@ -1484,6 +1486,7 @@ pub struct BulkPartEncoder {
metadata: RegionMetadataRef,
writer_props: Option<WriterProperties>,
narthex_format: bool,
dedup_mode: Option<MergeMode>,
}
impl BulkPartEncoder {
@@ -1517,11 +1520,17 @@ impl BulkPartEncoder {
metadata,
writer_props,
narthex_format: false,
dedup_mode: None,
})
}
}
impl BulkPartEncoder {
pub(crate) fn with_dedup_mode(mut self, mode: Option<MergeMode>) -> Self {
self.dedup_mode = mode;
self
}
pub(crate) fn with_narthex_format(mut self, narthex_format: bool) -> Self {
self.narthex_format = narthex_format;
self
@@ -1641,6 +1650,13 @@ impl BulkPartEncoder {
for kv in row_group_value_bytes.into_key_values() {
writer.append_key_value_metadata(kv);
}
if self.dedup_mode == Some(MergeMode::LastNonNull) {
// The final row group must also participate in the delete check.
writer.flush().context(EncodeMemtableSnafu)?;
}
if let Some(marker) = deduped_sst_marker(self.dedup_mode, writer.flushed_row_groups()) {
writer.append_key_value_metadata(marker);
}
let file_metadata = writer.close().context(EncodeMemtableSnafu)?;
metrics.write_cost += close_start.elapsed();
metrics.encoded_size += buf.len();
+14
View File
@@ -73,6 +73,7 @@ use crate::error::{
Result,
};
use crate::memtable::BoxedRecordBatchIterator;
use crate::region::options::MergeMode;
pub(crate) fn timestamp_array_to_i64_slice(arr: &ArrayRef) -> &[i64] {
use datatypes::arrow::array::{
@@ -986,6 +987,7 @@ impl From<Batch> for BatchBuilder {
pub struct FlatSource {
schema: SchemaRef,
inner: FlatSourceInner,
dedup_mode: Option<MergeMode>,
}
impl FlatSource {
@@ -994,6 +996,7 @@ impl FlatSource {
Self {
schema,
inner: FlatSourceInner::Iter(iter),
dedup_mode: None,
}
}
@@ -1002,9 +1005,20 @@ impl FlatSource {
Self {
schema,
inner: FlatSourceInner::Stream(stream),
dedup_mode: None,
}
}
/// Records the merge mode used to fold versions in this source.
pub(crate) fn with_dedup_mode(mut self, mode: Option<MergeMode>) -> Self {
self.dedup_mode = mode;
self
}
pub(crate) fn dedup_mode(&self) -> Option<MergeMode> {
self.dedup_mode
}
pub(crate) fn schema(&self) -> &SchemaRef {
&self.schema
}
+1 -1
View File
@@ -171,7 +171,7 @@ impl RangeMeta {
);
self.indices.append(&mut other.indices);
self.row_group_indices.append(&mut other.row_group_indices);
self.num_rows += other.num_rows;
self.num_rows = self.num_rows.saturating_add(other.num_rows);
}
/// Returns true if we can split the range into multiple smaller ranges and
+105 -35
View File
@@ -50,7 +50,7 @@ use partition::expr::PartitionExpr;
use smallvec::SmallVec;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataRef};
use store_api::region_engine::{PartitionRange, RegionScannerRef};
use store_api::region_engine::{PartitionRange, RegionScannerRef, ScannerProperties};
use store_api::storage::{
ColumnId, RegionId, ScanRequest, SequenceNumber, SequenceRange, TimeSeriesDistribution,
TimeSeriesRowSelector,
@@ -715,6 +715,7 @@ impl ScanRegion {
input
};
let mut input = input.build();
input.row_preserving_request = request_preserves_rows(&self.request);
if self.experimental_metadata_aggr && self.request.metadata_aggr_hint {
input.exact_num_rows = aggr::prepare(&input, &self.request).await;
}
@@ -990,6 +991,18 @@ fn file_in_range(file: &FileHandle, predicate: &TimestampRange) -> bool {
file_ts_range.intersects(predicate)
}
/// Whether the scan request leaves the source rows visible before predicates.
pub(crate) fn request_preserves_rows(request: &ScanRequest) -> bool {
request.series_row_selector.is_none()
&& request.limit.is_none()
&& request.memtable_min_sequence.is_none()
&& request.memtable_max_sequence.is_none()
&& request.sst_min_sequence.is_none()
&& !request.snapshot_on_scan
&& !request.exact_sequence_range
&& !request.skip_sst_files
}
/// Returns true if `time_range` contains the inclusive time range of `file`.
fn time_range_covers_file(time_range: Option<&TimestampRange>, file: &FileHandle) -> bool {
let Some(time_range) = time_range else {
@@ -1003,6 +1016,8 @@ fn time_range_covers_file(time_range: Option<&TimestampRange>, file: &FileHandle
pub struct ScanInput {
/// Count proven against this read view and the complete static predicate.
pub(crate) exact_num_rows: Option<usize>,
/// Whether the request leaves the source rows visible before predicates.
row_preserving_request: bool,
/// Pinned series-index snapshot and its storage, when configured.
pub(crate) series_index: Option<SeriesIndexReadContext>,
/// Whether to ignore range indexes while retaining series-index candidate discovery.
@@ -1112,6 +1127,7 @@ impl ScanInput {
ScanInputBuilder {
input: ScanInput {
exact_num_rows: None,
row_preserving_request: true,
series_index: None,
page_index_policy: None,
ignore_range_index: false,
@@ -1908,45 +1924,86 @@ impl ScanInput {
);
}
/// Whether physical source row counts are known and equal the rows visible
/// to this region, before applying query predicates.
pub(crate) fn total_rows_is_exact(&self) -> bool {
// Legacy SST metadata uses zero for unknown row counts.
if self.files.iter().any(|file| file.num_rows() == 0) {
return false;
}
if self.region_partition_expr.is_none() {
return true;
}
// Extension ranges do not expose their partition expressions.
/// Whether this read path preserves the ordinary row visibility semantics.
pub(crate) fn allows_exact_row_count(&self) -> bool {
#[cfg(feature = "enterprise")]
if !self.extension_ranges.is_empty() {
return false;
}
// Repartition flushes existing memtables before entering staging. New
// writes are routed under the target partition rules, whereas historical
// SSTs can be shared by regions and still need partition filtering.
self.files
.iter()
.all(|file| self.should_skip_region_partition(file))
self.row_preserving_request
&& !self.compaction
&& self.series_row_selector.is_none()
&& self.snapshot_sequence.is_none()
&& self.sequence_range.is_none()
&& !self.requires_narthex_preparation()
}
pub(crate) fn total_rows(&self) -> usize {
let rows_in_files: usize = self.files.iter().map(|f| f.num_rows()).sum();
let rows_in_memtables: usize = self.memtables.iter().map(|m| m.stats().num_rows()).sum();
/// Whether all timestamps in the file can be represented in the current
/// time-index unit. An older SST can overflow after a precision widening.
pub(crate) fn file_time_bounds_fit(&self, file: &FileHandle) -> bool {
let Some(timestamp_type) = self
.region_metadata()
.time_index_column()
.column_schema
.data_type
.as_timestamp()
else {
return false;
};
let (start, end) = file.time_range();
let unit = timestamp_type.unit();
start <= end
&& start.unit() == end.unit()
&& start.unit().factor() >= unit.factor()
&& start.convert_to(unit).is_some()
&& end.convert_to(unit).is_some()
}
let rows = rows_in_files + rows_in_memtables;
/// Whether physical source row counts are known and equal the rows visible
/// to this region, before applying query predicates.
fn source_row_counts_are_exact(&self) -> bool {
self.allows_exact_row_count()
&& self.files.iter().all(|file| {
// Legacy SST metadata uses zero for unknown row counts.
file.num_rows() > 0
&& self.file_time_bounds_fit(file)
// Historical SSTs can be shared and still need partition filtering.
&& (self.region_partition_expr.is_none()
|| self.should_skip_region_partition(file))
})
}
pub(crate) fn scanner_properties(&self) -> ScannerProperties {
let rows = self.checked_total_rows();
let exact = self.append_mode
&& rows.is_some_and(|rows| i64::try_from(rows).is_ok())
&& self.source_row_counts_are_exact();
let mut properties = ScannerProperties::default()
.with_append_mode(self.append_mode)
.with_total_rows(rows.unwrap_or(usize::MAX))
.with_total_rows_is_exact(exact)
.with_exact_num_rows(self.exact_num_rows);
if let Some(counters) = self.query_stat_counters.clone() {
properties.set_query_stat_counters(counters);
}
properties
}
fn checked_total_rows(&self) -> Option<usize> {
let rows = self
.files
.iter()
.map(FileHandle::num_rows)
.chain(self.memtables.iter().map(|m| m.stats().num_rows()))
.try_fold(0usize, usize::checked_add)?;
#[cfg(feature = "enterprise")]
let rows = rows
+ self
.extension_ranges
.iter()
.map(|x| x.num_rows())
.sum::<u64>() as usize;
rows
let rows = self
.extension_ranges
.iter()
.try_fold(rows, |total, range| {
total.checked_add(usize::try_from(range.num_rows()).ok()?)
})?;
Some(rows)
}
pub(crate) fn predicate_group(&self) -> &PredicateGroup {
@@ -2797,6 +2854,17 @@ mod tests {
(vec![file_meta.clone()], 10, true),
(vec![legacy_meta.clone()], 0, false),
(vec![file_meta, legacy_meta], 10, false),
(
vec![
FileMeta {
num_rows: usize::MAX as u64,
..Default::default()
};
2
],
usize::MAX,
false,
),
] {
let files = file_metas
.into_iter()
@@ -2809,8 +2877,9 @@ mod tests {
.with_append_mode(true)
.with_files(files)
.build();
assert_eq!(input.total_rows(), expected_rows);
assert_eq!(input.total_rows_is_exact(), exact);
let properties = input.scanner_properties();
assert_eq!(properties.total_rows(), expected_rows);
assert_eq!(properties.total_rows_is_exact(), exact);
}
}
@@ -2847,8 +2916,9 @@ mod tests {
let input = new_scan_input(metadata, vec![])
.await
.with_files(files)
.with_append_mode(true)
.build();
assert_eq!(input.total_rows_is_exact(), exact);
assert_eq!(input.scanner_properties().total_rows_is_exact(), exact);
}
}
+206 -117
View File
@@ -13,7 +13,7 @@
// limitations under the License.
//! Answers aggregates of a scan from manifest and SST statistics instead of
//! reading SST data. The preparation result, an exact answer or a split into
//! scanning SST rows. The preparation result, an exact answer or a split into
//! exact and residual sources, does not depend on the aggregate; scalar COUNT
//! is the only aggregate served so far.
@@ -21,107 +21,99 @@ pub mod overlap;
use std::sync::Arc;
use api::v1::OpType;
use common_telemetry::debug;
use common_time::range::TimestampRange;
use datafusion_common::ScalarValue;
use datafusion_expr::{Expr, Operator};
use datatypes::data_type::DataType;
use datatypes::value::Value;
use futures::StreamExt;
use futures::future::BoxFuture;
use futures::{FutureExt, StreamExt};
use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec};
use parquet::file::metadata::ParquetMetaData;
use parquet::file::statistics::Statistics;
use store_api::codec::PrimaryKeyEncoding;
use store_api::metadata::{ColumnMetadata, RegionMetadata};
use store_api::storage::ScanRequest;
use store_api::storage::consts::OP_TYPE_COLUMN_NAME;
use crate::read::scan_region::ScanInput;
use crate::read::scan_region::aggr::overlap::{Extent, find_overlaps};
use crate::read::scan_region::{ScanInput, request_preserves_rows};
use crate::sst::file::FileHandle;
use crate::sst::parquet::metadata::{DEDUPED_SST_KEY, has_only_puts};
/// Returns the exact number of rows the scan yields, or `None` if it cannot
/// be proven. Reads no SST data: candidates come from the manifest, and in a
/// deduplicating region their Parquet metadata is read through the SST
/// metadata caches to rule out deletions.
/// be proven. Non-append candidates use cached Parquet footers to prove
/// file-local uniqueness and the absence of deletes.
pub(crate) async fn prepare(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
let classification = classify(input, request)?;
if !classification.remaining.is_empty() || !input.memtables.is_empty() {
if !input.memtables.is_empty() {
return None;
}
let no_deletes = read_no_deletes(input, &classification).await;
resolve(input, classification, &no_deletes)
let classification = classify(input, request, false)?;
if !classification.remaining.is_empty() {
return None;
}
let evidence = read_file_evidence(input, &classification).await;
resolve(input, classification, &evidence)
}
/// Applies the deletion evidence of the exact candidates.
/// Applies the footer evidence of the exact candidates.
fn resolve(
input: &ScanInput,
mut classification: Classification,
no_deletes: &[bool],
evidence: &[bool],
) -> Option<usize> {
classification.retain_exact(input, no_deletes);
classification.retain_exact(input, evidence);
(classification.remaining.is_empty() && input.memtables.is_empty())
.then_some(classification.exact_rows)
}
/// Returns, for each exact candidate, whether it holds no deletion markers.
/// Append-mode files need no evidence. In a deduplicating region every SST is
/// deduplicated within itself, so a file without deletions yields each of its
/// rows. A file whose metadata cannot be read counts as having deletions.
async fn read_no_deletes(input: &ScanInput, classification: &Classification) -> Vec<bool> {
/// Returns whether each candidate yields all of its physical rows once.
async fn read_file_evidence(input: &ScanInput, classification: &Classification) -> Vec<bool> {
if input.append_mode {
return vec![true; classification.exact.len()];
}
// Each future owns its reader, so the stream does not borrow `input`.
// Boxing erases the metadata loader's deep future type for callers.
let reads: Vec<BoxFuture<'static, bool>> = classification
.exact
.iter()
.map(|&index| {
let file = input.files[index].clone();
let reader = input
.access_layer
.read_sst(file.clone())
.cache(input.cache_strategy.clone());
Box::pin(async move {
match reader.read_statistics().await {
Ok(metadata) => has_no_deletes(&metadata),
Err(e) => {
debug!(
"Metadata count falls back to scanning file {}: {e:?}",
file.file_id()
);
false
}
let reads = classification.exact.iter().map(|&index| {
let file = input.files[index].clone();
let reader = input
.access_layer
.read_sst(file.clone())
.cache(input.cache_strategy.clone());
async move {
match reader.read_statistics().await {
Ok(metadata) => footer_proves_visible_rows(&metadata, file.num_rows()),
Err(e) => {
debug!(
"Metadata count falls back to scanning file {}: {e:?}",
file.file_id()
);
false
}
}) as BoxFuture<'static, bool>
})
.collect();
}
}
.boxed()
});
futures::stream::iter(reads)
.buffered(input.max_concurrent_scan_files.max(1))
.collect()
.await
}
/// Whether every row group's `__op_type` statistics prove it holds only puts.
fn has_no_deletes(metadata: &ParquetMetaData) -> bool {
let Some(column) = metadata
.file_metadata()
.schema_descr()
.columns()
.iter()
.position(|column| column.name() == OP_TYPE_COLUMN_NAME)
else {
return false;
};
metadata.row_groups().iter().all(|row_group| {
matches!(
row_group.column(column).statistics(),
Some(Statistics::Int32(stats)) if stats.min_opt() == Some(&(OpType::Put as i32))
)
})
/// The footer and manifest must agree. Without the writer's uniqueness claim,
/// only a single physical row is independently known to be unique.
fn footer_proves_visible_rows(metadata: &ParquetMetaData, manifest_rows: usize) -> bool {
let footer = metadata.file_metadata();
let unique = manifest_rows == 1
|| footer
.key_value_metadata()
.is_some_and(|entries| entries.iter().any(|entry| entry.key == DEDUPED_SST_KEY));
unique
&& usize::try_from(footer.num_rows()) == Ok(manifest_rows)
&& metadata
.row_groups()
.iter()
.try_fold(0usize, |total, group| {
total.checked_add(usize::try_from(group.num_rows()).ok()?)
})
== Some(manifest_rows)
&& has_only_puts(metadata.row_groups())
}
/// Files of one scan classified against its pinned read view.
@@ -157,27 +149,17 @@ impl Classification {
/// all of its rows (see [`AggrFilters`]).
/// - Its manifest row count is known.
/// - In a deduplicating region, no other file or memtable may hold a row with
/// the same primary key and timestamp. The candidate must still be proven
/// free of deletions (see [`read_no_deletes`]).
/// the same primary key and timestamp. The footer must still prove
/// uniqueness within the file and that it holds only puts.
///
/// Returns `None` for scans whose visible rows can differ from the sources'
/// rows for reasons other than the files themselves.
fn classify(input: &ScanInput, request: &ScanRequest) -> Option<Classification> {
if input.compaction
|| input.series_row_selector.is_some()
|| input.sequence_range.is_some()
|| request.limit.is_some()
|| request.memtable_min_sequence.is_some()
|| request.memtable_max_sequence.is_some()
|| request.sst_min_sequence.is_some()
|| request.snapshot_on_scan
|| request.exact_sequence_range
|| request.skip_sst_files
{
return None;
}
#[cfg(feature = "enterprise")]
if !input.extension_ranges.is_empty() {
fn classify(
input: &ScanInput,
request: &ScanRequest,
allow_partial: bool,
) -> Option<Classification> {
if !input.allows_exact_row_count() || !request_preserves_rows(request) {
return None;
}
let filters = AggrFilters::new(input.region_metadata(), &request.filters)?;
@@ -189,15 +171,26 @@ fn classify(input: &ScanInput, request: &ScanRequest) -> Option<Classification>
if start > end {
return None;
}
if range.intersects(&TimestampRange::new_inclusive(Some(start), Some(end))) {
intersecting.push(index);
if !range.intersects(&TimestampRange::new_inclusive(Some(start), Some(end))) {
continue;
}
let candidate = range.contains(&start)
&& range.contains(&end)
// Zero is unknown in legacy manifests.
&& file.num_rows() > 0
&& input.file_time_bounds_fit(file)
&& (input.region_partition_expr.is_none() || input.should_skip_region_partition(file))
&& filters.covers(file);
if !candidate && !allow_partial {
return None;
}
intersecting.push((index, candidate));
}
// Append mode never merges rows, so sources cannot hide each other's rows.
let overlaps = if input.append_mode {
vec![false; intersecting.len()]
} else {
let overlaps = if !input.append_mode && intersecting.iter().any(|&(_, candidate)| candidate) {
overlapping_files(input, &intersecting)
} else {
Vec::new()
};
let mut classification = Classification {
@@ -205,33 +198,26 @@ fn classify(input: &ScanInput, request: &ScanRequest) -> Option<Classification>
remaining: Vec::new(),
exact_rows: 0,
};
for (index, overlaps) in intersecting.into_iter().zip(overlaps) {
for (position, (index, candidate)) in intersecting.into_iter().enumerate() {
let file = &input.files[index];
let (start, end) = file.time_range();
let exact = range.contains(&start)
&& range.contains(&end)
// Zero is unknown in legacy manifests.
&& file.num_rows() > 0
&& (input.region_partition_expr.is_none() || input.should_skip_region_partition(file))
&& filters.covers(file)
&& (input.append_mode || !overlaps);
if exact {
if candidate && !overlaps.get(position).copied().unwrap_or(false) {
classification.exact_rows = classification.exact_rows.checked_add(file.num_rows())?;
classification.exact.push(index);
} else {
classification.remaining.push(index);
}
}
i64::try_from(classification.exact_rows).ok()?;
Some(classification)
}
/// Returns, for each file in `files`, whether another file or a memtable may
/// hold a row with the same primary key and timestamp.
fn overlapping_files(input: &ScanInput, files: &[usize]) -> Vec<bool> {
fn overlapping_files(input: &ScanInput, files: &[(usize, bool)]) -> Vec<bool> {
let mapper = input.primary_key_mapper();
let mut extents: Vec<_> = files
.iter()
.map(|&index| {
.map(|&(index, _)| {
let file = &input.files[index];
Extent {
time: file.time_range(),
@@ -340,6 +326,15 @@ fn eq_literal<'a>(
| (Expr::Literal(value, _), Expr::Column(column)) => (column, value),
_ => return None,
};
// Arrow uses total ordering for floats. Decoded Values equate NaNs and
// both signs of zero, so those equalities cannot prove Arrow coverage.
if match value {
ScalarValue::Float32(Some(value)) => value.is_nan() || *value == 0.0,
ScalarValue::Float64(Some(value)) => value.is_nan() || *value == 0.0,
_ => false,
} {
return None;
}
(column.name == name && !value.is_null() && &value.data_type() == data_type).then_some(value)
}
@@ -444,7 +439,7 @@ mod tests {
)
}
/// The deletion evidence [`read_no_deletes`] would read for the candidates.
/// Footer evidence for the synthetic files in these classification tests.
fn evidence(input: &ScanInput, classification: &Classification) -> Vec<bool> {
let with_deletes = WITH_DELETES.lock().unwrap();
classification
@@ -457,13 +452,13 @@ mod tests {
}
fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
let classification = classify(input, request)?;
let classification = classify(input, request, false)?;
let no_deletes = evidence(input, &classification);
resolve(input, classification, &no_deletes)
}
fn classified(input: &ScanInput, request: &ScanRequest) -> Classification {
let mut classification = classify(input, request).unwrap();
let mut classification = classify(input, request, true).unwrap();
let no_deletes = evidence(input, &classification);
classification.retain_exact(input, &no_deletes);
classification
@@ -664,19 +659,25 @@ mod tests {
#[test]
fn test_metadata_aggr_reads_op_type_statistics() {
use datatypes::arrow::array::{ArrayRef, Int64Array, UInt8Array};
use api::v1::OpType;
use datatypes::arrow::array::{ArrayRef, StructArray, UInt8Array};
use datatypes::arrow::datatypes::{DataType as ArrowType, Field};
use datatypes::arrow::record_batch::RecordBatch;
use parquet::arrow::ArrowWriter;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::file::properties::WriterProperties;
use parquet::file::metadata::KeyValue;
use parquet::file::properties::{EnabledStatistics, WriterProperties};
use store_api::storage::consts::OP_TYPE_COLUMN_NAME;
let metadata = |name: &str, ops: Vec<u8>| {
let len = ops.len() as i64;
let put = OpType::Put as u8;
let del = OpType::Delete as u8;
let metadata = |name: &str, ops: Vec<Option<u8>>, stats, marker: bool| {
let nested = StructArray::from(vec![(
Arc::new(Field::new(OP_TYPE_COLUMN_NAME, ArrowType::UInt8, false)),
Arc::new(UInt8Array::from_value(put, ops.len())) as ArrayRef,
)]);
let batch = RecordBatch::try_from_iter([
(
"v",
Arc::new(Int64Array::from_iter_values(0..len)) as ArrayRef,
),
("payload", Arc::new(nested) as ArrayRef),
(name, Arc::new(UInt8Array::from(ops)) as ArrayRef),
])
.unwrap();
@@ -684,6 +685,10 @@ mod tests {
// Two rows per row group, so a delete in a later row group counts.
let props = WriterProperties::builder()
.set_max_row_group_row_count(Some(2))
.set_statistics_enabled(stats)
.set_key_value_metadata(
marker.then(|| vec![KeyValue::new(DEDUPED_SST_KEY.to_owned(), None)]),
)
.build();
let mut writer =
ArrowWriter::try_new(&mut buffer, batch.schema(), Some(props)).unwrap();
@@ -694,13 +699,97 @@ mod tests {
.metadata()
.clone()
};
let put = OpType::Put as u8;
let delete = OpType::Delete as u8;
assert!(has_no_deletes(&metadata(OP_TYPE_COLUMN_NAME, vec![put; 4])));
assert!(!has_no_deletes(&metadata(
OP_TYPE_COLUMN_NAME,
vec![put, put, put, delete]
)));
assert!(!has_no_deletes(&metadata("other", vec![put; 4])));
let ops = vec![Some(put); 4];
let stats = EnabledStatistics::Page;
for (name, ops, statistics, certified, expected) in [
(OP_TYPE_COLUMN_NAME, ops.clone(), stats, true, true),
(OP_TYPE_COLUMN_NAME, ops.clone(), stats, false, false),
(OP_TYPE_COLUMN_NAME, vec![Some(put)], stats, false, true),
("other", ops.clone(), stats, true, false),
(
OP_TYPE_COLUMN_NAME,
ops,
EnabledStatistics::None,
true,
false,
),
(OP_TYPE_COLUMN_NAME, vec![None; 4], stats, true, false),
(
OP_TYPE_COLUMN_NAME,
vec![Some(put), None],
stats,
true,
false,
),
(
OP_TYPE_COLUMN_NAME,
vec![Some(put), Some(put), Some(put), Some(del)],
stats,
true,
false,
),
] {
let rows = ops.len();
let footer = metadata(name, ops, statistics, certified);
assert_eq!(
footer_proves_visible_rows(&footer, rows),
expected,
"{footer:?}"
);
assert!(!footer_proves_visible_rows(&footer, rows + 1));
}
}
#[test]
fn test_metadata_aggr_rejects_non_arrow_float_equalities() {
use datatypes::arrow::datatypes::DataType as ArrowType;
for (value, data_type) in [
(
ScalarValue::Float32(Some(f32::from_bits(0x7fc0_0001))),
ArrowType::Float32,
),
(
ScalarValue::Float64(Some(f64::from_bits(0x7ff8_0000_0000_0001))),
ArrowType::Float64,
),
(ScalarValue::Float64(Some(-0.0)), ArrowType::Float64),
] {
let filter = col("k0").eq(lit(value));
assert!(eq_literal(&filter, "k0", &data_type).is_none());
}
let ordinary = col("k0").eq(lit(1.5f64));
assert!(eq_literal(&ordinary, "k0", &ArrowType::Float64).is_some());
}
#[tokio::test]
async fn test_metadata_aggr_narrowed_partition_falls_back() {
use partition::expr::col as partition_col;
let mut input = input(vec![file(0, 10, 3, true)], &[]).await;
input.region_partition_expr = Some(partition_col("k0").gt_eq(Value::String("x".into())));
assert_eq!(exact_count(&input, &ScanRequest::default()), None);
}
#[tokio::test]
async fn test_metadata_aggr_file_timestamp_unit_overflow() {
for (start, end) in [(i64::MIN / 1000 - 1, 0), (0, i64::MAX / 1000 + 1), (-1, 1)] {
let file = FileHandle::new(
FileMeta {
time_range: (Timestamp::new_second(start), Timestamp::new_second(end)),
num_rows: 2,
..Default::default()
},
new_noop_file_purger(),
);
let mut input = input(vec![file], &[]).await;
let fits = start == -1;
assert_eq!(
exact_count(&input, &ScanRequest::default()),
fits.then_some(2),
);
input.append_mode = true;
assert_eq!(input.scanner_properties().total_rows_is_exact(), fits);
}
}
}
+1 -8
View File
@@ -87,14 +87,7 @@ impl SeqScan {
/// Creates a new [SeqScan] with the given input.
/// If `input.compaction` is true, the scanner will not attempt to split ranges.
pub(crate) fn new(input: ScanInput) -> Self {
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);
}
let mut properties = input.scanner_properties();
let stream_ctx = Arc::new(StreamContext::seq_scan_ctx(input));
properties.partitions = vec![stream_ctx.partition_ranges()];
+1 -8
View File
@@ -235,14 +235,7 @@ impl SeriesScan {
} else {
SeriesScanMode::Legacy
};
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);
}
let mut properties = input.scanner_properties();
let stream_ctx = Arc::new(StreamContext::seq_scan_ctx(input));
properties.partitions = vec![stream_ctx.partition_ranges()];
+1 -8
View File
@@ -63,14 +63,7 @@ impl UnorderedScan {
/// Creates a new [UnorderedScan].
pub(crate) fn new(stream_ctx: StreamContext) -> Self {
let input = &stream_ctx.input;
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);
}
let mut properties = input.scanner_properties();
let stream_ctx = Arc::new(stream_ctx);
properties.partitions = vec![stream_ctx.partition_ranges()];
+68 -5
View File
@@ -15,22 +15,31 @@
use std::result::Result as StdResult;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use api::v1::OpType;
use bytes::Bytes;
use futures::FutureExt;
use futures::future::BoxFuture;
use object_store::ObjectStore;
use parquet::arrow::async_reader::MetadataFetch;
use parquet::basic::{ConvertedType, LogicalType, Type};
use parquet::errors::{ParquetError, Result as ParquetResult};
use parquet::file::metadata::{PageIndexPolicy, ParquetMetaData, ParquetMetaDataReader};
use parquet::file::metadata::{
KeyValue, PageIndexPolicy, ParquetMetaData, ParquetMetaDataReader, RowGroupMetaData,
};
use parquet::file::statistics::Statistics;
use parquet::schema::types::SchemaDescriptor;
use snafu::{IntoError as _, ResultExt};
use store_api::metadata::RegionMetadata;
use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
use store_api::storage::consts::{OP_TYPE_COLUMN_NAME, PRIMARY_KEY_COLUMN_NAME};
use crate::error::{self, Result};
use crate::region::options::MergeMode;
use crate::sst::parquet::reader::MetadataCacheMetrics;
/// Presence certifies at most one physical row per (primary key, timestamp).
/// The value has no meaning. Any new claim must use a different key.
pub(crate) const DEDUPED_SST_KEY: &str = "greptimedb.deduped";
/// The estimated size of the footer and metadata need to read from the end of parquet file.
const DEFAULT_PREFETCH_SIZE: u64 = 64 * 1024;
@@ -125,9 +134,63 @@ fn unbox_external_error(e: ParquetError) -> StdResult<object_store::Error, Parqu
/// Returns the leaf index of the top-level `__primary_key` column. A leaf name alone also
/// matches nested fields, such as a JSON child named `__primary_key`.
pub(crate) fn primary_key_leaf_index(schema: &SchemaDescriptor) -> Option<usize> {
schema.columns().iter().position(
|column| matches!(column.path().parts(), [name] if name == PRIMARY_KEY_COLUMN_NAME),
)
top_level_leaf_index(schema, PRIMARY_KEY_COLUMN_NAME, Type::BYTE_ARRAY)
}
/// Returns a leaf only if exactly one top-level column has this name and type.
fn top_level_leaf_index(
schema: &SchemaDescriptor,
name: &str,
physical_type: Type,
) -> Option<usize> {
let mut matches = schema
.columns()
.iter()
.enumerate()
.filter(|(_, column)| matches!(column.path().parts(), [part] if part == name));
let (index, column) = matches.next()?;
(matches.next().is_none() && column.physical_type() == physical_type).then_some(index)
}
/// Whether the internal op-type statistics prove that every row is a put.
pub(crate) fn has_only_puts(row_groups: &[RowGroupMetaData]) -> bool {
let Some(column) = row_groups.first().and_then(|group| {
let schema = group.schema_descr();
let index = top_level_leaf_index(schema, OP_TYPE_COLUMN_NAME, Type::INT32)?;
let column = schema.column(index);
let is_uint8 = match column.logical_type_ref() {
Some(logical_type) => *logical_type == LogicalType::integer(8, false),
None => column.converted_type() == ConvertedType::UINT_8,
};
is_uint8.then_some(index)
}) else {
return false;
};
let put = OpType::Put as i32;
row_groups.iter().all(|group| {
matches!(
group.column(column).statistics(),
Some(Statistics::Int32(stats))
if stats.null_count_opt() == Some(0)
&& stats.min_is_exact()
&& stats.max_is_exact()
&& stats.min_opt() == Some(&put)
&& stats.max_opt() == Some(&put)
)
})
}
/// Adds the uniqueness claim to an output of a writer that folded versions.
/// LastNonNull may preserve multiple rows for a key across delete barriers.
pub(crate) fn deduped_sst_marker(
merge_mode: Option<MergeMode>,
row_groups: &[RowGroupMetaData],
) -> Option<KeyValue> {
let deduped = match merge_mode? {
MergeMode::LastRow => true,
MergeMode::LastNonNull => has_only_puts(row_groups),
};
deduped.then(|| KeyValue::new(DEDUPED_SST_KEY.to_owned(), None))
}
pub(crate) fn extract_primary_key_range(
@@ -182,6 +182,11 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
self.file_writer.append_key_value_metadata(kv);
}
/// Returns the metadata of all encoded and flushed row groups.
pub(crate) fn flushed_row_groups(&self) -> &[parquet::file::metadata::RowGroupMetaData] {
self.file_writer.flushed_row_groups()
}
/// Finalizes the file while retaining the upload for abort if it fails.
pub(crate) async fn finish(&mut self) -> Result<ParquetMetaData> {
self.flush().await?;
+21 -4
View File
@@ -40,7 +40,7 @@ use parquet::arrow::AsyncArrowWriter;
use parquet::arrow::async_writer::AsyncFileWriter;
use parquet::basic::{Compression, Encoding, ZstdLevel};
use parquet::errors::ParquetError;
use parquet::file::metadata::{FileMetaData, KeyValue, ParquetMetaData};
use parquet::file::metadata::{FileMetaData, KeyValue, ParquetMetaData, RowGroupMetaData};
use parquet::file::properties::WriterProperties;
use smallvec::smallvec;
use snafu::{IntoError, OptionExt, ResultExt, ensure};
@@ -55,12 +55,14 @@ use crate::error::{
WriteParquetSnafu,
};
use crate::read::FlatSource;
use crate::region::options::MergeMode;
use crate::sst::file::RegionFileId;
use crate::sst::index::{Indexer, IndexerBuilder};
use crate::sst::parquet::flat_format::{
FlatWriteFormat, primary_key_column_index, time_index_column_index,
};
use crate::sst::parquet::format::{PrimaryKeyArray, PrimaryKeyWriteFormat};
use crate::sst::parquet::metadata::deduped_sst_marker;
use crate::sst::parquet::parallel_writer::ParallelArrowWriter;
use crate::sst::parquet::{
COLUMN_INDEX_TRUNCATE_LENGTH, PARQUET_METADATA_KEY, RowGroupValueBytes, SstInfo, WriteOptions,
@@ -190,6 +192,13 @@ impl<W: AsyncFileWriter> SstArrowWriter<W> {
}
}
fn flushed_row_groups(&self) -> &[RowGroupMetaData] {
match self {
SstArrowWriter::Serial(writer) => writer.flushed_row_groups(),
SstArrowWriter::Parallel(writer) => writer.flushed_row_groups(),
}
}
async fn finish(&mut self) -> parquet::errors::Result<ParquetMetaData> {
match self {
SstArrowWriter::Serial(writer) => writer.finish().await,
@@ -598,6 +607,7 @@ where
&mut self,
ssts: &mut SstInfoArray,
stats: &mut SourceStats,
dedup_mode: Option<MergeMode>,
) -> Result<()> {
self.check_cancelled()?;
// maybe_init_writer will re-create a new file.
@@ -639,6 +649,9 @@ where
{
writer.append_key_value_metadata(kv);
}
if let Some(marker) = deduped_sst_marker(dedup_mode, writer.flushed_row_groups()) {
writer.append_key_value_metadata(marker);
}
let parquet_metadata = writer.finish().await.map_err(map_write_error)?;
self.writer.take();
let file_size = self.bytes_written.load(Ordering::Relaxed) as u64;
@@ -753,6 +766,7 @@ where
) -> Result<SstInfoArray> {
let mut results = smallvec![];
let mut stats = SourceStats::default();
let dedup_mode = source.dedup_mode();
loop {
let start = Instant::now();
@@ -780,7 +794,8 @@ where
self.append_flat_batch(&batch, converter, opts, &mut stats)
.await?;
if self.exceeds_max_file_size(opts) {
self.finish_current_file(&mut results, &mut stats).await?;
self.finish_current_file(&mut results, &mut stats, dedup_mode)
.await?;
}
} else if self.exceeds_max_file_size(opts)
&& let Some(current_primary_key) = stats.last_primary_key.as_deref()
@@ -805,7 +820,8 @@ where
self.append_flat_batch(&tail, converter, opts, &mut stats)
.await?;
}
self.finish_current_file(&mut results, &mut stats).await?;
self.finish_current_file(&mut results, &mut stats, dedup_mode)
.await?;
self.append_flat_batch(&next_file_head, converter, opts, &mut stats)
.await?;
}
@@ -816,7 +832,8 @@ where
}
}
self.finish_current_file(&mut results, &mut stats).await?;
self.finish_current_file(&mut results, &mut stats, dedup_mode)
.await?;
// object_store.write will make sure all bytes are written or an error is raised.
Ok(results)
+2 -2
View File
@@ -163,12 +163,12 @@ fn assign_partition_ranges_by_time(
ranges.sort_by(|a, b| a.start.cmp(&b.start).then_with(|| a.end.cmp(&b.end)));
}
let mut partition_ranges = vec![vec![]; expected_partition_num];
let mut partition_rows = vec![0; expected_partition_num];
let mut partition_rows = vec![0usize; expected_partition_num];
for range in ranges {
let target = (0..expected_partition_num)
.min_by_key(|&i| (partition_rows[i], partition_ranges[i].len(), i))
.unwrap();
partition_rows[target] += range.num_rows;
partition_rows[target] = partition_rows[target].saturating_add(range.num_rows);
partition_ranges[target].push(range);
}
partition_ranges
+20 -3
View File
@@ -16,7 +16,7 @@ use std::collections::HashSet;
use api::v1::SemanticType;
use arrow_schema::SortOptions;
use common_function::aggrs::aggr_wrapper::aggr_state_func_name;
use common_function::aggrs::aggr_wrapper::{aggr_state_func_name, is_builtin_count_or_state};
use common_recordbatch::OrderOption;
use common_recordbatch::filter::SimpleFilterEvaluator;
use datafusion::datasource::DefaultTableSource;
@@ -109,8 +109,7 @@ impl ScanHintRule {
[Expr::Literal(value, _)] => !value.is_null(),
_ => false,
};
if (function.func.name() != "count"
&& function.func.name() != aggr_state_func_name("count"))
if !is_builtin_count_or_state(&function.func)
|| function.params.distinct
|| function.params.filter.is_some()
|| !function.params.order_by.is_empty()
@@ -802,7 +801,11 @@ mod test {
#[test]
fn metadata_aggr_hint_is_scoped_and_restricted() {
use common_function::aggrs::aggr_wrapper::StateWrapper;
use datafusion::functions_aggregate::count::count_udaf;
use datafusion::functions_aggregate::expr_fn::{count, count_distinct};
use datafusion_expr::{AggregateUDF, Volatility, create_udaf};
let region_id = RegionId::new(1, 1);
let metadata = mock_table_provider(region_id).region_metadata();
let provider = Arc::new(DummyTableProvider::new(
@@ -810,12 +813,26 @@ mod test {
Arc::new(MetaRegionEngine::with_metadata(metadata.clone()).with_engine_name("mito")),
metadata,
));
let user_count = create_udaf(
"count",
vec![DataType::Int64],
Arc::new(DataType::Int64),
Volatility::Immutable,
Arc::new(|_| unreachable!("a logical hint does not instantiate the function")),
Arc::new(vec![DataType::Int64]),
);
let builtin_state =
AggregateUDF::from(StateWrapper::new(count_udaf().as_ref().clone()).unwrap());
let user_state = AggregateUDF::from(StateWrapper::new(user_count.clone()).unwrap());
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),
(vec![], builtin_state.call(vec![lit(1i64)]), true),
(vec![], user_count.call(vec![lit(2i64)]), false),
(vec![], user_state.call(vec![lit(2i64)]), false),
] {
let plan = LogicalPlanBuilder::from(scan_plan(provider.clone(), "t"))
.aggregate(groups, vec![function])
+60 -1
View File
@@ -409,6 +409,12 @@ impl ScannerProperties {
/// Updates the properties with the given [PrepareRequest].
pub fn prepare(&mut self, request: PrepareRequest) {
if let Some(ranges) = request.ranges {
if (self.exact_num_rows.is_some() || self.total_rows_is_exact)
&& !same_partition_ranges(&self.partitions, &ranges)
{
self.exact_num_rows = None;
self.total_rows_is_exact = false;
}
self.partitions = ranges;
}
if let Some(distinguish_partition_range) = request.distinguish_partition_range {
@@ -478,10 +484,24 @@ impl ScannerProperties {
}
}
/// Checks that range assignment only reordered or regrouped the original ranges.
fn same_partition_ranges(left: &[Vec<PartitionRange>], right: &[Vec<PartitionRange>]) -> bool {
let mut left: Vec<_> = left.iter().flatten().collect();
let mut right: Vec<_> = right.iter().flatten().collect();
if left.len() != right.len() {
return false;
}
let key = |range: &&PartitionRange| (range.identifier, range.start, range.end, range.num_rows);
left.sort_unstable_by_key(key);
right.sort_unstable_by_key(key);
left == right
}
/// Request to override the scanner properties.
#[derive(Default)]
pub struct PrepareRequest {
/// Assigned partition ranges.
/// Range assignment may reorder and regroup existing ranges. Exact row
/// counts require preserving each range unchanged with its original multiplicity.
pub ranges: Option<Vec<Vec<PartitionRange>>>,
/// Distringuishes partition range by empty batches.
pub distinguish_partition_range: Option<bool>,
@@ -1047,6 +1067,45 @@ mod tests {
use super::*;
#[test]
fn test_metadata_aggr_partition_range_assignment() {
let range = PartitionRange {
start: Timestamp::new_millisecond(0),
end: Timestamp::new_millisecond(1),
num_rows: 5,
identifier: 0,
};
let later = PartitionRange {
start: range.end,
end: Timestamp::new_millisecond(2),
identifier: 1,
..range
};
let original = vec![vec![range, later]];
for (replacement, exact) in [
(vec![vec![later], vec![range]], true),
(vec![vec![later]], false),
(vec![vec![range, range]], false),
(
vec![vec![
PartitionRange {
num_rows: 4,
..range
},
later,
]],
false,
),
] {
let mut properties = ScannerProperties::new(original.clone(), true, 10)
.with_exact_num_rows(Some(10))
.with_total_rows_is_exact(true);
properties.prepare(PrepareRequest::default().with_ranges(replacement));
assert_eq!(properties.exact_num_rows(), exact.then_some(10));
assert_eq!(properties.total_rows_is_exact(), exact);
}
}
#[tokio::test]
async fn single_partition_scanner_raw_scan_panics_and_preserves_legacy_read() {
use std::panic::{AssertUnwindSafe, catch_unwind};
+17
View File
@@ -1187,6 +1187,23 @@ mod tests {
let range = build_time_range_predicate("ts", TimeUnit::Millisecond, &[expr]);
assert!(range.is_empty(), "{range:?}");
}
for (literal, successor) in [
(
ScalarValue::TimestampMillisecond(Some(i64::MIN), None),
i64::MIN + 1,
),
(ScalarValue::TimestampMicrosecond(Some(-1001), None), -1),
(ScalarValue::TimestampMicrosecond(Some(-1), None), 0),
(ScalarValue::TimestampSecond(Some(0), None), 1),
] {
let literal = lit(literal);
for expr in [col("ts").gt(literal.clone()), literal.lt(col("ts"))] {
check_build_predicate(
expr,
TimestampRange::from_start(Timestamp::new_millisecond(successor)),
);
}
}
}
#[test]
+1 -1
View File
@@ -162,7 +162,7 @@ pub fn assign_partition_ranges(
for range in ranges {
let mut node = part_heap.pop().unwrap();
let partition_idx = node.partition_idx;
node.num_rows += range.num_rows;
node.num_rows = node.num_rows.saturating_add(range.num_rows);
partition_ranges[partition_idx].push(range);
part_heap.push(node);
}
+15
View File
@@ -259,6 +259,7 @@ pub struct GreptimeDbClusterBuilder {
store_config: Option<ObjectStoreConfig>,
store_providers: Option<Vec<StorageType>>,
datanodes: Option<u32>,
mito_config: Option<mito2::config::MitoConfig>,
datanode_wal_config: DatanodeWalConfig,
metasrv_wal_config: MetasrvWalConfig,
datanode_gc_config: GcConfig,
@@ -301,6 +302,7 @@ impl GreptimeDbClusterBuilder {
store_config: None,
store_providers: None,
datanodes: None,
mito_config: None,
datanode_wal_config: DatanodeWalConfig::default(),
metasrv_wal_config: MetasrvWalConfig::default(),
datanode_gc_config: GcConfig::default(),
@@ -337,6 +339,12 @@ impl GreptimeDbClusterBuilder {
self
}
/// Overrides the Mito config of each datanode in the test cluster.
pub fn with_mito_config(mut self, config: mito2::config::MitoConfig) -> Self {
self.mito_config = Some(config);
self
}
#[must_use]
pub fn with_datanode_wal_config(mut self, datanode_wal_config: DatanodeWalConfig) -> Self {
self.datanode_wal_config = datanode_wal_config;
@@ -626,6 +634,13 @@ impl GreptimeDbClusterBuilder {
opts
};
if let Some(config) = &self.mito_config {
for engine in &mut opts.region_engine {
if let datanode::config::RegionEngineConfig::Mito(mito) = engine {
*mito = config.clone();
}
}
}
// Shared object storage must not make datanodes share a local WAL.
if self.shared_home_dir.is_some()
&& let DatanodeWalConfig::RaftEngine(config) = &mut opts.wal
+34
View File
@@ -19,6 +19,7 @@ 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";
@@ -67,6 +68,39 @@ async fn test_metadata_count_non_append(#[case] enabled: bool) {
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
@@ -0,0 +1,8 @@
name = "metadata_count_sst_footer"
reason = "Read non-append SSTs across versions with and without the deduplication footer marker."
introduced_by = "PR #9891"
topologies = ["standalone", "distributed"]
from_range = ["*"]
to_range = ["*"]
features = ["sst", "metadata"]
owner = "storage"
@@ -0,0 +1,9 @@
CREATE TABLE t_metadata_count_footer (
host STRING PRIMARY KEY,
ts TIMESTAMP TIME INDEX,
v BIGINT
) ENGINE=mito WITH (append_mode = 'false');
INSERT INTO t_metadata_count_footer VALUES ('a', 1000, 1), ('a', 2000, 2);
INSERT INTO t_metadata_count_footer VALUES ('a', 1000, 3), ('b', 1000, 4);
ADMIN FLUSH_TABLE('t_metadata_count_footer');
@@ -0,0 +1,3 @@
SELECT count(*) AS total FROM t_metadata_count_footer;
SELECT host, v FROM t_metadata_count_footer ORDER BY host, ts;