feat: answer scalar COUNT on Mito from SST metadata (#9891)

* feat: answer scalar COUNT on Mito from SST metadata

Behind `experimental_metadata_aggr` (off by default), ScanHintRule marks
an ungrouped scalar COUNT directly over a Mito scan. Mito then proves the
scan's row count without reading SST data. Every file intersecting the
query time range must be covered by the static predicates and have a
known manifest row count. In deduplicating regions it must also share no
(time, primary key) point with another file or a memtable, and its
`__op_type` Parquet statistics must show no deletions. The statistics are
read through the SST metadata caches, only for files that pass the
manifest checks. RegionScanExec publishes the proven count as exact
statistics, which lets DataFusion replace the scan with a literal. Other
scans are unchanged.

Overlaps are found with one time sweep over a segment tree of compressed
primary key bounds, in O(N log N). The pairwise check remains as the
test oracle and benchmark baseline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: aumnertic <aumnertic@gmail.com>

* test(mito): cover metadata COUNT and address core review

Signed-off-by: aumnertic <aumnertic@gmail.com>

* test(mito): match metadata aggregate fixture region IDs

Signed-off-by: aumnertic <aumnertic@gmail.com>

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

Signed-off-by: aumnertic <aumnertic@gmail.com>

* test(mito2): add SQLness coverage for the SST footer marker

Signed-off-by: aumnertic <aumnertic@gmail.com>

* test(mito2): verify tightened partition bounds and source estimates

Signed-off-by: aumnertic <aumnertic@gmail.com>

* fix(mito2): keep lazy footer reads sendable

Signed-off-by: aumnertic <aumnertic@gmail.com>

* test(mito2): use valid sequence fences and SST owners

Signed-off-by: aumnertic <aumnertic@gmail.com>

* fix(mito2): validate SST key bounds before metadata count

Signed-off-by: aumnertic <aumnertic@gmail.com>

* fix(mito2): verify SST time bounds before metadata count

Signed-off-by: aumnertic <aumnertic@gmail.com>

* fix(mito2): own SST inputs to asynchronous bound checks

Signed-off-by: aumnertic <aumnertic@gmail.com>

* test(mito2): match displayed scan names in COUNT fallback

Signed-off-by: aumnertic <aumnertic@gmail.com>

* fix(mito2): keep SST replacements coherent with metadata counts

Signed-off-by: aumnertic <aumnertic@gmail.com>

* refactor(cmd): reuse the replacement SST reader during validation

Signed-off-by: aumnertic <aumnertic@gmail.com>

* test(mito2): verify listed SST sizes against object storage

Signed-off-by: aumnertic <aumnertic@gmail.com>

* fix(mito2): keep metadata count proofs within the SST read set

Signed-off-by: aumnertic <aumnertic@gmail.com>

* docs(mito2): use the actual scan memory limit key

Signed-off-by: aumnertic <aumnertic@gmail.com>

* fix(mito2): gate metadata counts on trusted SST dedup markers

Record the provenance of engine-written dedup markers in the manifest.
Clear it for external imports and preserve it during internal transfers.
Require this proof for metadata counts over non-append multi-row SSTs.

Keep the live file metadata consistent when an import supersedes a
background publication, and cover checkpoint downgrade and reopen.

Signed-off-by: aumnertic <aumnertic@gmail.com>

---------

Signed-off-by: aumnertic <aumnertic@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aum
2026-11-30 11:43:27 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 6c047d02b7
commit 6ffb0ec793
69 changed files with 4569 additions and 375 deletions
+2
View File
@@ -226,6 +226,7 @@
| `region_engine.mito.min_compaction_interval` | String | `0m` | Minimum time interval between two compactions.<br/>To align with the old behavior, the default value is 0 (no restrictions). |
| `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_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.<br/>The SST metadata cache (`region_engine.mito.sst_meta_cache_size`) is accounted separately from<br/>`region_engine.mito.scan_memory_limit` and `query.memory_pool_size`.<br/>Partial counts use captured source containers without a single-instant snapshot across partitions.<br/>Append-mode scans only use full metadata counts. |
| `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. |
@@ -716,6 +717,7 @@
| `region_engine.mito.min_compaction_interval` | String | `0m` | Minimum time interval between two compactions.<br/>To align with the old behavior, the default value is 0 (no restrictions). |
| `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_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.<br/>The SST metadata cache (`region_engine.mito.sst_meta_cache_size`) is accounted separately from<br/>`region_engine.mito.scan_memory_limit` and `query.memory_pool_size`.<br/>Partial counts use captured source containers without a single-instant snapshot across partitions.<br/>Append-mode scans only use full metadata counts. |
| `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. |
+8
View File
@@ -744,6 +744,14 @@ schedule_compaction_after_edit = true
## Whether to enable flat format as the default SST format.
default_flat_format = true
## 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.
## The SST metadata cache (`region_engine.mito.sst_meta_cache_size`) is accounted separately from
## `region_engine.mito.scan_memory_limit` and `query.memory_pool_size`.
## Partial counts use captured source containers without a single-instant snapshot across partitions.
## Append-mode scans only use full metadata counts.
experimental_metadata_aggr = false
## The options for index in Mito engine.
[region_engine.mito.index]
+8
View File
@@ -975,6 +975,14 @@ schedule_compaction_after_edit = true
## Whether to enable flat format as the default SST format.
default_flat_format = true
## 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.
## The SST metadata cache (`region_engine.mito.sst_meta_cache_size`) is accounted separately from
## `region_engine.mito.scan_memory_limit` and `query.memory_pool_size`.
## Partial counts use captured source containers without a single-instant snapshot across partitions.
## Append-mode scans only use full metadata counts.
experimental_metadata_aggr = false
## The options for index in Mito engine.
[region_engine.mito.index]
+25 -18
View File
@@ -8,7 +8,7 @@ rewriting, benchmarking, and replacing Parquet SST files:
properties.
- `parquetbench`: benchmark reads from a local GreptimeDB SST or an SST in a
configured object store.
- `sst-replace`: replace an existing Mito SST object and update its manifest
- `sst-replace`: install a replacement Mito SST and update its manifest
metadata.
These are development and recovery tools, not stable user-facing interfaces.
@@ -113,9 +113,10 @@ dump path must not be exactly the same path as the input, even with
`--overwrite`. This check does not resolve symbolic links, hard links, or other
spellings of the same path.
The rewrite decodes and writes the Arrow record batches and copies the Parquet
key-value metadata, but it creates a new physical Parquet layout. Inspect and
validate the result before using it as an SST:
The rewrite decodes and writes the Arrow record batches into a new physical
layout. It copies region metadata, recomputes decoded value sizes when present,
and drops the `greptimedb.deduped` marker. Inspect the result before using it
as an SST:
```bash
$GREPTIME datanode parquet-meta \
@@ -183,17 +184,22 @@ iteration from profiling.
## Replace an existing region SST
> **Warning:** `sst-replace` mutates both an SST object and its region manifest.
> Stop the datanode that owns the region and back up the target SST and manifest
> before using `--confirm`. The SST write happens before the manifest update, so
> an interrupted or failed operation may require restoring the backup.
Stop the datanode that owns the region and back up its manifest before using
`--confirm`. The command writes the replacement under a fresh file ID, then
publishes one manifest edit that swaps the old ID for the new one. Readers of
the previous manifest can still use the original object. If publication fails
after the upload, check the active manifest before cleaning up the reported
replacement path.
`sst-replace` replaces the contents of an existing SST file ID. It does not add
a new file ID to a region. The command requires the replacement to have the same
row count and row-group count recorded in the manifest when those manifest
values are nonzero. It does not validate schema or row contents. The replacement
is loaded into memory in full, so ensure the machine has enough memory for the
SST.
The target must be a locally owned, unshared Parquet SST. The replacement must
belong to the same source region and time index and
match the manifest row and row-group counts when those counts are known.
Its footer must provide exact time bounds. Missing primary-key bounds remain
unknown. Use `parquet-rewrite` first if the replacement carries
`greptimedb.deduped`. Index sidecars belong to the original file ID. When the manifest has
a sequence fence or preserves per-row sequences, the command compares the
sequence column of both files before retaining those guarantees. Allow memory
for both SSTs during validation.
Start with the default dry run using a local replacement file:
@@ -237,10 +243,11 @@ $GREPTIME datanode sst-replace \
--confirm
```
The confirmed operation overwrites the existing SST object, recalculates file
size and row-group statistics, and appends a manifest edit for the existing file
ID. Restart the datanode and validate queries against the region before removing
the backup.
The confirmed operation prints the new SST path and manifest version. Restart
the datanode and validate queries against the region before removing the
backup. To repair bounds or stale cache entries left by an older in-place
replacement, use its current manifest ID as `--file-id`. If the current object
has no deduplication marker, it can be passed directly as `--replacement-object`.
## Recommended rewrite and replacement workflow
+1 -1
View File
@@ -129,7 +129,7 @@ common-version.workspace = true
datanode = { workspace = true, features = ["testing"] }
file-engine.workspace = true
metric-engine.workspace = true
mito2.workspace = true
mito2 = { workspace = true, features = ["test"] }
serde.workspace = true
similar-asserts.workspace = true
temp-env = "0.3"
@@ -315,6 +315,7 @@ fn file_meta_from_sst_info(
primary_key_min: None,
primary_key_max: None,
preserve_row_sequence: false,
dedup_marker_trusted: false,
format: Default::default(),
}
}
+10 -1
View File
@@ -17,6 +17,7 @@ use std::path::{Path, PathBuf};
use clap::Parser;
use datatypes::arrow::record_batch::RecordBatchReader;
use mito2::sst::parquet::metadata::DEDUPED_SST_KEY;
use mito2::sst::parquet::{
MAX_ROW_GROUP_VALUE_BYTES_KEY, MAX_ROW_VALUE_WIDTH_KEY, RowGroupValueBytes,
};
@@ -166,6 +167,11 @@ impl ParquetRewriteCommand {
kvs.retain(|kv| !is_row_group_value_bytes_key(&kv.key));
kvs.len() != len
});
if let Some(kvs) = &mut key_value_metadata {
// Only the folding writers can certify uniqueness. These input
// bytes may have been edited while retaining the original footer.
kvs.retain(|kv| kv.key != DEDUPED_SST_KEY);
}
let mut reader_builder = ParquetRecordBatchReaderBuilder::try_new(open_file(&self.input)?)
.map_err(|e| parquet_error("open source parquet", &self.input, e))?;
@@ -593,9 +599,11 @@ mod tests {
.unwrap();
let mut value_bytes = RowGroupValueBytes::new(4);
value_bytes.update(&batch);
let mut metadata = value_bytes.into_key_values();
metadata.push(KeyValue::new(DEDUPED_SST_KEY.to_string(), None));
let props = WriterProperties::builder()
.set_max_row_group_row_count(Some(4))
.set_key_value_metadata(Some(value_bytes.into_key_values()))
.set_key_value_metadata(Some(metadata))
.build();
let mut writer =
ArrowWriter::try_new(File::create(&input).unwrap(), schema, Some(props)).unwrap();
@@ -620,6 +628,7 @@ mod tests {
let rewritten = load_local_parquet_metadata(&output).unwrap();
assert_eq!(2, rewritten.num_row_groups());
let key_values = rewritten.file_metadata().key_value_metadata().unwrap();
assert!(key_values.iter().all(|kv| kv.key != DEDUPED_SST_KEY));
let value_of = |key: &str| {
let values: Vec<_> = key_values
.iter()
+1
View File
@@ -358,6 +358,7 @@ impl ParquetbenchCommand {
primary_key_min: None,
primary_key_max: None,
preserve_row_sequence: false,
dedup_marker_trusted: false,
format: Default::default(),
},
Arc::new(NoopFilePurger),
+362 -67
View File
@@ -19,18 +19,25 @@ use colored::Colorize;
use mito2::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList};
use mito2::manifest::manager::{RegionManifestManager, RegionManifestOptions};
use mito2::region::ManifestStats;
use mito2::sst::file::RegionFileId;
use mito2::sst::file::{FileFormat, FileMeta};
use mito2::sst::file_metadata::FileMetadataInterner;
use mito2::sst::location::{region_dir_from_table_dir, sst_file_path};
use mito2::sst::location::region_dir_from_table_dir;
use mito2::sst::parquet::max_row_group_decoded_size;
use object_store::ObjectStore;
use parquet::file::FOOTER_SIZE;
use parquet::file::metadata::{FooterTail, ParquetMetaDataReader};
use mito2::sst::parquet::metadata::{
DEDUPED_SST_KEY, extract_primary_key_range, extract_time_range, has_deduped_sst_marker,
};
use object_store::{Buffer, ObjectStore};
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::record::RowAccessor;
use parquet::record::reader::RowIter;
use parquet::schema::types::Type;
use store_api::region_request::PathType;
use store_api::storage::FileId;
use store_api::storage::consts::SEQUENCE_COLUMN_NAME;
use crate::datanode::tool_util::{
build_object_store, max_row_group_uncompressed_size, parse_config, parse_file_id,
parse_path_type, parse_region_id,
build_object_store, extract_region_metadata, max_row_group_uncompressed_size, parse_config,
parse_file_id, parse_path_type, parse_region_id,
};
use crate::error;
@@ -65,7 +72,7 @@ pub struct SstReplaceCommand {
#[clap(long, default_value = "auto")]
path_type: String,
/// Actually overwrite the SST object and append a manifest delta.
/// Write the replacement under a new file ID and publish the manifest edit.
#[clap(long, default_value_t = false)]
confirm: bool,
@@ -148,32 +155,108 @@ impl SstReplaceCommand {
.fail();
};
let region_file_id = RegionFileId::new(old_file.region_id, old_file.file_id);
let target_path = sst_file_path(&self.table_dir, region_file_id, path_type);
if old_file.format != FileFormat::Parquet
|| old_file.region_id != region_id
|| old_file.level == mito2::sst::file::LEVEL_SHARED
{
return error::IllegalConfigSnafu {
msg: format!("file {file_id} must be a locally owned, unshared Parquet SST"),
}
.fail();
}
let target_path = old_file.file_path(&self.table_dir, path_type);
let target_stat = object_store.stat(&target_path).await.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("stat target SST {} failed: {e}", target_path),
}
.build()
})?;
let replacement_bytes = load_replacement_bytes(&object_store, replacement).await?;
let replacement_bytes = load_replacement_bytes(&object_store, replacement)
.await?
.to_bytes();
let new_file_size = replacement_bytes.len() as u64;
let parquet_meta = decode_parquet_metadata(&replacement_bytes).map_err(|e| {
let replacement_reader =
SerializedFileReader::new(replacement_bytes.clone()).map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("read replacement parquet metadata failed: {e}"),
}
.build()
})?;
let parquet_meta = replacement_reader.metadata();
let new_num_rows =
u64::try_from(parquet_meta.file_metadata().num_rows()).map_err(|_| {
error::IllegalConfigSnafu {
msg: "replacement has a negative row count".to_string(),
}
.build()
})?;
let new_num_row_groups = parquet_meta.num_row_groups() as u64;
validate_replacement(&old_file, new_num_rows, new_num_row_groups)?;
if has_deduped_sst_marker(parquet_meta) {
return error::IllegalConfigSnafu {
msg: format!(
"replacement SST carries the {DEDUPED_SST_KEY} marker; run parquet-rewrite to remove it first"
),
}
.fail();
}
let source = extract_region_metadata("replacement SST", parquet_meta)?;
let time_index = source.time_index_column();
let manifest = manifest_manager.manifest();
if source.region_id != old_file.region_id
|| time_index.column_id != manifest.metadata.time_index_column().column_id
{
return error::IllegalConfigSnafu {
msg: "replacement region or time index differs from the target".to_string(),
}
.fail();
}
let time_range = extract_time_range(parquet_meta, time_index).ok_or_else(|| {
error::IllegalConfigSnafu {
msg: format!("read replacement parquet metadata failed: {e}"),
msg: "replacement has no exact time-index bounds".to_string(),
}
.build()
})?;
let new_num_rows = parquet_meta.file_metadata().num_rows() as u64;
let new_num_row_groups = parquet_meta.num_row_groups() as u64;
validate_replacement(&old_file, new_num_rows, new_num_row_groups)?;
let mut new_file = old_file.as_ref().clone();
new_file.file_size = new_file_size;
new_file.num_rows = new_num_rows;
new_file.num_row_groups = new_num_row_groups;
new_file.max_row_group_uncompressed_size = max_row_group_uncompressed_size(&parquet_meta);
new_file.max_row_group_decoded_size = max_row_group_decoded_size(&parquet_meta);
if (old_file.sequence.is_some() || old_file.preserve_row_sequence)
&& self.replacement_object.as_deref() != Some(target_path.as_str())
{
// The edit retains the original sequence fence and per-row trust.
let original = object_store.read(&target_path).await.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("read target SST {target_path}: {e}"),
}
.build()
})?;
validate_sequences(original, &replacement_reader).map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("validate replacement sequences: {e}"),
}
.build()
})?;
}
let (primary_key_min, primary_key_max) =
extract_primary_key_range(parquet_meta, &source).unzip();
// A new identity isolates data, index and footer caches, including on restart.
// A replacement has no index sidecar, series count or proven partition scope.
// It has no trusted dedup marker, regardless of the old file's metadata.
let new_file = FileMeta {
file_id: FileId::random(),
region_id: old_file.region_id,
level: old_file.level,
sequence: old_file.sequence,
preserve_row_sequence: old_file.preserve_row_sequence,
time_range,
primary_key_min,
primary_key_max,
file_size: new_file_size,
num_rows: new_num_rows,
num_row_groups: new_num_row_groups,
max_row_group_uncompressed_size: max_row_group_uncompressed_size(parquet_meta),
max_row_group_decoded_size: max_row_group_decoded_size(parquet_meta),
..Default::default()
};
let replacement_path = new_file.file_path(&self.table_dir, path_type);
println!("{} Region: {}", "[ok]".green(), region_id);
println!("{} Target SST: {}", "[ok]".green(), target_path.cyan());
@@ -192,30 +275,25 @@ impl SstReplaceCommand {
if !self.confirm {
println!(
"{} Dry run only. Re-run with --confirm to overwrite the SST and update the manifest.",
"{} Dry run only. Re-run with --confirm to publish the replacement.",
"[dry-run]".yellow()
);
return Ok(());
}
object_store
.write(&target_path, replacement_bytes)
.write(&replacement_path, replacement_bytes)
.await
.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("write replacement SST {} failed: {e}", target_path),
msg: format!("write replacement SST {} failed: {e}", replacement_path),
}
.build()
})?;
let edit = RegionEdit {
files_to_add: vec![new_file],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
files_to_remove: vec![old_file.as_ref().clone()],
..Default::default()
};
let version = manifest_manager
@@ -226,13 +304,15 @@ impl SstReplaceCommand {
.await
.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("update manifest failed: {e:?}"),
msg: format!(
"update manifest for replacement {replacement_path} failed: {e:?}"
),
}
.build()
})?;
println!(
"{} Replacement committed, manifest version {}",
"{} Replacement committed at {replacement_path}, manifest version {}",
"[ok]".green(),
version
);
@@ -260,25 +340,55 @@ enum Replacement<'a> {
async fn load_replacement_bytes(
object_store: &ObjectStore,
replacement: Replacement<'_>,
) -> error::Result<Vec<u8>> {
) -> error::Result<Buffer> {
match replacement {
Replacement::Local(path) => tokio::fs::read(path).await.map_err(|e| {
Replacement::Local(path) => tokio::fs::read(path).await.map(Buffer::from).map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("read replacement file {} failed: {e}", path.display()),
}
.build()
}),
Replacement::Object(path) => {
object_store
.read(path)
.await
.map(|b| b.to_vec())
.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("read replacement object {} failed: {e}", path),
}
.build()
})
Replacement::Object(path) => object_store.read(path).await.map_err(|e| {
error::IllegalConfigSnafu {
msg: format!("read replacement object {} failed: {e}", path),
}
.build()
}),
}
}
// Compare only the sequence column. Physical row-group boundaries and encodings
// may change in a layout rewrite without changing logical sequences.
fn validate_sequences(
original: Buffer,
replacement: &dyn FileReader,
) -> parquet::errors::Result<()> {
fn sequences(reader: &dyn FileReader) -> parquet::errors::Result<RowIter<'_>> {
let schema = reader.metadata().file_metadata().schema();
let column = schema
.get_fields()
.iter()
.find(|field| field.name() == SEQUENCE_COLUMN_NAME)
.ok_or_else(|| {
parquet::errors::ParquetError::General("missing SST sequence column".into())
})?;
let projection = Type::group_type_builder(schema.name())
.with_fields(vec![column.clone()])
.build()?;
reader.get_row_iter(Some(projection))
}
let original = SerializedFileReader::new(original.to_bytes())?;
let mut old = sequences(&original)?;
let mut new = sequences(replacement)?;
loop {
match (old.next().transpose()?, new.next().transpose()?) {
(Some(old), Some(new)) if old.get_ulong(0)? == new.get_ulong(0)? => {}
(None, None) => return Ok(()),
_ => {
return Err(parquet::errors::ParquetError::General(
"replacement changes the target's row sequences".into(),
));
}
}
}
}
@@ -309,26 +419,6 @@ fn validate_replacement(
Ok(())
}
fn decode_parquet_metadata(
data: &[u8],
) -> Result<parquet::file::metadata::ParquetMetaData, Box<dyn std::error::Error + Send + Sync>> {
if data.len() < FOOTER_SIZE {
return Err("file too small".into());
}
let footer_start = data.len() - FOOTER_SIZE;
let mut footer = [0; FOOTER_SIZE];
footer.copy_from_slice(&data[footer_start..]);
let footer = FooterTail::try_new(&footer)?;
let metadata_len = footer.metadata_length();
if footer_start < metadata_len {
return Err("invalid footer/metadata length".into());
}
let metadata_start = footer_start - metadata_len;
Ok(ParquetMetaDataReader::decode_metadata(
&data[metadata_start..footer_start],
)?)
}
fn parse_optional_path_type(value: &str) -> error::Result<Option<PathType>> {
match value.to_lowercase().as_str() {
"auto" => Ok(None),
@@ -353,6 +443,211 @@ fn path_type_name(path_type: PathType) -> &'static str {
mod tests {
use super::*;
#[tokio::test]
async fn test_replace_refreshes_pruning_bounds() {
check_replacement(true, false).await;
}
#[tokio::test]
async fn test_replace_cached_delete_with_put_at_same_key_and_time() {
check_replacement(false, false).await;
}
#[tokio::test]
async fn test_replace_sst_rejects_marked_duplicate_rows() {
check_replacement(false, true).await;
}
async fn check_replacement(move_row: bool, marked_duplicates: bool) {
use datafusion::prelude::{col, lit};
use datafusion_common::ScalarValue;
use futures::TryStreamExt;
use mito2::config::MitoConfig;
use mito2::test_util::{self, CreateRequestBuilder, TestEnv};
use store_api::region_engine::RegionEngine;
use store_api::region_request::{RegionOpenRequest, RegionRequest};
use store_api::storage::{RegionId, ScanRequest};
let mut target = TestEnv::new().await;
let mut donor = TestEnv::new().await;
let region_id = RegionId::new(1, 1);
let create = CreateRequestBuilder::new().table_dir("table").build();
let rows_per_file = if marked_duplicates { 3 } else { 1 };
let schema = test_util::rows_schema(&create);
let region_dir = region_dir_from_table_dir(&create.table_dir, region_id, create.path_type);
let config = MitoConfig {
experimental_metadata_aggr: true,
enable_write_cache: true,
..Default::default()
};
// Two independent regions have the same schema and sequence. The target
// has deletes and the replacement has puts. Use an append-mode donor for
// the accepted cases so its output has no deduplication claim.
let mut paths = Vec::new();
let (new_key, new_second) = if move_row { ("b", 2) } else { ("a", 1) };
for (env, key, second, delete) in [
(&mut target, "a", 1, true),
(&mut donor, new_key, new_second, false),
] {
let engine = env.create_engine(config.clone()).await;
let mut create = create.clone();
if !delete && !marked_duplicates {
create.options.insert("append_mode".into(), "true".into());
}
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
let rows = api::v1::Rows {
schema: schema.clone(),
rows: test_util::build_rows_for_key(key, second, second + rows_per_file, 0),
};
if delete {
test_util::delete_rows(&engine, region_id, rows).await;
} else {
test_util::put_rows(&engine, region_id, rows).await;
}
test_util::flush_region(&engine, region_id, None).await;
engine.stop().await.unwrap();
let dir = env
.data_home()
.join("data")
.join(region_dir.trim_start_matches('/'));
let files: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.map(|entry| entry.unwrap().path())
.filter(|path| path.extension().is_some_and(|ext| ext == "parquet"))
.collect();
assert_eq!(files.len(), 1);
paths.push(files.into_iter().next().unwrap());
}
let data_home = target.data_home().join("data");
let config_file = target.data_home().join("replace.toml");
std::fs::write(
&config_file,
format!(
"[storage]\ntype = \"File\"\ndata_home = {}\n[[region_engine]]\n[region_engine.mito]\n",
toml::Value::String(data_home.to_string_lossy().into_owned())
),
)
.unwrap();
if marked_duplicates {
write_marked_duplicate_rows(&paths[1]);
}
let command = SstReplaceCommand {
config: config_file,
region_id: region_id.as_u64().to_string(),
table_dir: create.table_dir.clone(),
file_id: paths[0].file_stem().unwrap().to_str().unwrap().to_owned(),
replacement_file: Some(paths[1].clone()),
replacement_object: None,
path_type: "bare".into(),
confirm: true,
verbose: false,
};
let previous_bytes = std::fs::read(&paths[0]).unwrap();
if marked_duplicates {
let err = command.run().await.unwrap_err();
assert!(err.to_string().contains(DEDUPED_SST_KEY), "{err}");
assert_eq!(std::fs::read(&paths[0]).unwrap(), previous_bytes);
return;
}
command.run().await.unwrap();
assert_eq!(std::fs::read(&paths[0]).unwrap(), previous_bytes);
let engine = target.open_engine(config).await;
engine
.handle_request(
region_id,
RegionRequest::Open(RegionOpenRequest {
engine: String::new(),
table_dir: create.table_dir,
path_type: create.path_type,
options: create.options,
skip_wal_replay: false,
checkpoint: None,
requirements: Default::default(),
}),
)
.await
.unwrap();
let queries = if move_row {
let cutoff = lit(ScalarValue::TimestampMillisecond(Some(1500), None));
vec![
(vec![col("ts").gt_eq(cutoff)], 1),
(vec![col("tag_0").eq(lit("a"))], 0),
(vec![col("tag_0").eq(lit("b"))], 1),
]
} else {
vec![(vec![], 1)]
};
for (filters, expected) in queries {
let request = ScanRequest {
filters,
..Default::default()
};
let scanned = engine
.scan_to_stream(region_id, request.clone())
.await
.unwrap()
.try_fold(
0,
|count, batch| async move { Ok(count + batch.num_rows()) },
)
.await
.unwrap();
assert_eq!(scanned, expected);
let scanner = engine
.handle_query(
region_id,
ScanRequest {
metadata_aggr_hint: true,
..request
},
)
.await
.unwrap();
if expected == 1 {
assert_eq!(scanner.properties().exact_num_rows(), Some(expected));
} else {
assert!(
scanner
.properties()
.exact_num_rows()
.is_none_or(|count| count == expected)
);
}
}
engine.stop().await.unwrap();
}
fn write_marked_duplicate_rows(path: &std::path::Path) {
use std::fs::File;
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;
let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(path).unwrap()).unwrap();
assert!(has_deduped_sst_marker(reader.metadata()));
let metadata = reader
.metadata()
.file_metadata()
.key_value_metadata()
.cloned();
let batch = reader.build().unwrap().next().unwrap().unwrap();
// Keep the row count and time/key bounds while duplicating the first Put.
let batch = take_record_batch(&batch, &UInt32Array::from(vec![0, 0, 2])).unwrap();
let props = WriterProperties::builder()
.set_key_value_metadata(metadata)
.build();
let mut writer =
ArrowWriter::try_new(File::create(path).unwrap(), batch.schema(), Some(props)).unwrap();
writer.write(&batch).unwrap();
writer.close().unwrap();
}
#[test]
fn test_validate_replacement_counts() {
let old_file = mito2::sst::file::FileMeta {
@@ -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
+7
View File
@@ -95,6 +95,13 @@ 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`) 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. In non-append regions, a multi-row
SST also needs `FileMeta::dedup_marker_trusted`. Old manifests default this
field to false. External imports cannot establish trust, and internal file
transfers preserve it.
- **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
+5
View File
@@ -129,6 +129,11 @@ name = "bench_compaction_picker"
harness = false
required-features = ["testing"]
[[bench]]
name = "bench_metadata_aggr_overlap"
harness = false
required-features = ["testing"]
[[bench]]
name = "bench_flat_merge"
harness = false
@@ -0,0 +1,140 @@
// 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.
//! Compares the metadata aggregate overlap check with the pairwise oracle.
//! Each case prints the allocations per call before it is timed.
use std::alloc::{GlobalAlloc, Layout, System};
use std::hint::black_box;
use std::sync::atomic::{AtomicUsize, Ordering};
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use mito2::read::scan_region::metadata_aggr_overlap::{
Extent, find_overlaps, find_overlaps_pairwise,
};
/// Counts heap allocations, including reallocations.
struct CountingAlloc;
static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for CountingAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static GLOBAL: CountingAlloc = CountingAlloc;
type Extents = Vec<Extent<i64, u64>>;
/// Every extent overlaps every other in time, but keys are disjoint: the
/// worst case for pairwise checking.
fn disjoint_keys(len: usize) -> Extents {
(0..len)
.map(|i| Extent {
time: (0, 100),
key: Some((i as u64 * 2, i as u64 * 2 + 1)),
})
.collect()
}
/// Every extent overlaps every other in both time and key.
fn dense_overlap(len: usize) -> Extents {
(0..len)
.map(|i| Extent {
time: (i as i64, i as i64 + len as i64),
key: Some((i as u64, i as u64 + len as u64)),
})
.collect()
}
/// Daily compaction outputs: each day splits the key space into a few files,
/// and adjacent days touch at their boundaries.
fn daily_outputs(len: usize) -> Extents {
const FILES_PER_DAY: usize = 4;
(0..len)
.map(|i| {
let day = (i / FILES_PER_DAY) as i64;
let part = (i % FILES_PER_DAY) as u64;
Extent {
time: (day * 86_400, (day + 1) * 86_400),
key: Some((part * 1000, part * 1000 + 999)),
}
})
.collect()
}
/// Repeated identical bounds, with every eighth key range unknown, on
/// disjoint hourly windows.
fn duplicate_unknown(len: usize) -> Extents {
(0..len)
.map(|i| {
let hour = (i / 4) as i64;
Extent {
time: (hour * 3_600, hour * 3_600 + 3_599),
key: (i % 8 != 7).then_some((0, 999)),
}
})
.collect()
}
fn allocations<R>(f: impl FnOnce() -> R) -> usize {
let before = ALLOCATIONS.load(Ordering::Relaxed);
black_box(f());
ALLOCATIONS.load(Ordering::Relaxed) - before
}
#[allow(clippy::print_stdout)]
fn bench_overlaps(c: &mut Criterion) {
for (name, generate) in [
("disjoint_keys", disjoint_keys as fn(usize) -> Extents),
("dense_overlap", dense_overlap),
("daily_outputs", daily_outputs),
("duplicate_unknown", duplicate_unknown),
] {
let mut group = c.benchmark_group(format!("metadata_aggr_overlap/{name}"));
for len in [2, 8, 32, 128, 512, 2048] {
let extents = generate(len);
let expected = find_overlaps_pairwise(&extents);
assert_eq!(find_overlaps(&extents), expected);
println!(
"allocations {name}/{len}: sweep={} pairwise={}",
allocations(|| find_overlaps(&extents)),
allocations(|| find_overlaps_pairwise(&extents)),
);
group.bench_with_input(BenchmarkId::new("sweep", len), &extents, |b, extents| {
b.iter(|| find_overlaps(black_box(extents)))
});
group.bench_with_input(BenchmarkId::new("pairwise", len), &extents, |b, extents| {
b.iter(|| find_overlaps_pairwise(black_box(extents)))
});
}
group.finish();
}
}
criterion_group!(benches, bench_overlaps);
criterion_main!(benches);
+6 -2
View File
@@ -65,7 +65,7 @@ use crate::sst::index::intermediate::IntermediateManager;
use crate::sst::index::puffin_manager::PuffinManagerFactory;
use crate::sst::index::registry::{IndexBuildPlan, IndexRegistry};
use crate::sst::location::region_dir_from_table_dir;
use crate::sst::parquet::metadata::extract_primary_key_range;
use crate::sst::parquet::metadata::{extract_primary_key_range, has_deduped_sst_marker};
use crate::sst::parquet::parallel_writer::EncodeRuntime;
use crate::sst::parquet::writer::SstWriteContext;
use crate::sst::parquet::{SstInfo, WriteOptions};
@@ -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();
@@ -941,6 +941,10 @@ impl DefaultSstMerger {
primary_key_min,
primary_key_max,
preserve_row_sequence: sequence_metadata.exact_sequence_trusted,
dedup_marker_trusted: sst_info
.file_metadata
.as_deref()
.is_some_and(has_deduped_sst_marker),
format: sst_info.format.clone(),
})
})
@@ -209,6 +209,7 @@ impl<'a> TargetWriter<'a> {
primary_key_min: range.as_ref().map(|(min, _)| min.clone()),
primary_key_max: range.map(|(_, max)| max),
preserve_row_sequence: self.preserve_row_sequence,
dedup_marker_trusted: false,
format: info.format.clone(),
})
}
+10 -1
View File
@@ -226,6 +226,15 @@ pub struct MitoConfig {
/// When enabled, forces using BulkMemtable and BulkMemtableBuilder.
pub default_flat_format: bool,
/// 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. The SST metadata cache
/// (`region_engine.mito.sst_meta_cache_size`) is accounted separately from
/// `region_engine.mito.scan_memory_limit` and `query.memory_pool_size`.
/// Partial counts use captured source containers without a single-instant
/// snapshot across partitions. Append-mode scans only use full metadata counts.
pub experimental_metadata_aggr: bool,
pub gc: GcConfig,
}
@@ -282,7 +291,7 @@ impl Default for MitoConfig {
min_compaction_interval: Duration::from_secs(0),
schedule_compaction_after_edit: true,
default_flat_format: true,
// FIXME(#9435): Keep v2 opt-in while long-range scan memory usage is investigated.
experimental_metadata_aggr: false,
gc: GcConfig::default(),
};
+3
View File
@@ -55,6 +55,8 @@ pub mod listener;
#[cfg(test)]
mod merge_mode_test;
#[cfg(test)]
mod metadata_aggr_test;
#[cfg(test)]
mod object_store_wal_recovery_test;
#[cfg(test)]
pub(crate) mod object_store_wal_test;
@@ -1340,6 +1342,7 @@ impl EngineInner {
.with_query_stat_counters(region.region_stats.query_stat_counters())
.with_max_concurrent_scan_files(self.config.max_concurrent_scan_files)
.with_scan_memory_tracker(self.scan_memory_tracker.clone())
.with_experimental_metadata_aggr(self.config.experimental_metadata_aggr)
.with_ignore_inverted_index(self.config.inverted_index.apply_on_query.disabled())
.with_ignore_fulltext_index(self.config.fulltext_index.apply_on_query.disabled())
.with_ignore_bloom_filter(self.config.bloom_filter_index.apply_on_query.disabled())
@@ -54,6 +54,136 @@ fn range_expr(col_name: &str, start: i64, end: i64) -> PartitionExpr {
.and(col(col_name).lt(Value::Int64(end)))
}
#[rstest::rstest]
#[case::matching(10.0, Some(3), 3, false)]
#[case::narrowed(2.0, None, 2, false)]
#[case::matching_existing_index(10.0, Some(3), 3, true)]
#[case::narrowed_existing_index(2.0, None, 2, true)]
#[tokio::test]
async fn test_apply_staging_manifest_preserves_metadata_aggr_evidence(
#[case] target_upper_bound: f64,
#[case] expected_exact: Option<usize>,
#[case] expected_rows: usize,
#[case] existing_index: bool,
) {
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 source = RegionId::new(1, 1);
let target = RegionId::new(1, 2);
let source_expr = col("field_0").lt(Value::from(10.0));
let create = CreateRequestBuilder::new()
.partition_expr_json(Some(source_expr.as_json_str().unwrap()))
.build_with_index();
let schema = rows_schema(&create);
engine
.handle_request(source, RegionRequest::Create(create))
.await
.unwrap();
super::compaction_test::put_and_flush(&engine, source, &schema, 0..3).await;
let source_manifest = engine
.get_region(source)
.unwrap()
.manifest_ctx
.manifest()
.await;
let source_file = source_manifest.files.values().next().unwrap();
assert!(source_file.dedup_marker_trusted);
engine
.set_region_role_state_gracefully(source, SettableRegionRoleState::StagingLeader)
.await
.unwrap();
let target_partition = col("field_0").lt(Value::from(target_upper_bound));
let target_expr = target_partition.as_json_str().unwrap();
let remapped = engine
.remap_manifests(RemapManifestsRequest {
validate_only: false,
region_id: source,
input_regions: vec![source],
region_mapping: [(source, vec![target])].into_iter().collect(),
new_partition_exprs: [(target, target_expr.clone())].into_iter().collect(),
})
.await
.unwrap();
engine
.handle_request(
target,
RegionRequest::Create(CreateRequestBuilder::new().build_with_index()),
)
.await
.unwrap();
if existing_index {
assert!(source_file.exists_index());
engine
.edit_region(
target,
RegionEdit {
files_to_add: vec![FileMeta {
partition_expr: Some(target_partition.into()),
..source_file.as_ref().clone()
}],
..Default::default()
},
)
.await
.unwrap();
let target_version = engine.get_region(target).unwrap().version();
let handle = &target_version.ssts.levels()[0].files[&source_file.file_id];
assert!(!handle.dedup_marker_trusted());
assert_eq!(handle.index_id(), source_file.index_id());
}
engine
.handle_request(
target,
RegionRequest::EnterStaging(EnterStagingRequest {
partition_directive: StagingPartitionDirective::UpdatePartitionExpr(
target_expr.clone(),
),
}),
)
.await
.unwrap();
engine
.handle_request(
target,
RegionRequest::ApplyStagingManifest(ApplyStagingManifestRequest {
partition_expr: target_expr,
central_region_id: source,
manifest_path: remapped.manifest_paths[&target].clone(),
}),
)
.await
.unwrap();
let region = engine.get_region(target).unwrap();
let manifest = region.manifest_ctx.manifest().await;
let imported = &manifest.files[&source_file.file_id];
assert!(imported.dedup_marker_trusted);
assert_eq!(imported.partition_expr.as_deref(), Some(&source_expr));
let version = region.version();
let handle = &version.ssts.levels()[0].files[&source_file.file_id];
assert_eq!(imported.as_ref(), handle.meta_ref());
let request = ScanRequest {
metadata_aggr_hint: true,
..Default::default()
};
let scan = engine.handle_query(target, request.clone()).await.unwrap();
assert_eq!(scan.properties().exact_num_rows(), expected_exact);
let rows = RecordBatches::try_collect(engine.scan_to_stream(target, request).await.unwrap())
.await
.unwrap();
assert_eq!(
rows.iter().map(|batch| batch.num_rows()).sum::<usize>(),
expected_rows
);
}
#[tokio::test]
async fn test_apply_staging_manifest_sequence_domain() {
common_telemetry::init_default_ut_logging();
+39 -49
View File
@@ -1106,37 +1106,11 @@ async fn test_cache_null_primary_key_with_format(flat_format: bool) {
assert_eq!(expected, batches.pretty_print().unwrap());
}
#[rstest]
#[case(false)]
#[case(true)]
#[tokio::test]
async fn test_list_ssts() {
test_list_ssts_with_format(false, r#"
ManifestSstEntry { table_dir: "test/", region_id: 47244640257(11, 1), table_id: 11, region_number: 1, region_group: 0, region_sequence: 1, file_id: "<file_id>", index_version: 0, level: 0, file_path: "test/11_0000000001/<file_id>.parquet", file_size: 2951, max_row_group_uncompressed_size: 0, index_file_path: Some("test/11_0000000001/index/<file_id>.puffin"), index_file_size: Some(250), num_rows: 10, num_row_groups: 1, num_series: Some(1), min_ts: 0::Millisecond, max_ts: 9000::Millisecond, sequence: Some(10), partition_expr: None, origin_region_id: 47244640257(11, 1), node_id: None, visible: true, primary_key_min: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01"), primary_key_max: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01") }
ManifestSstEntry { table_dir: "test/", region_id: 47244640258(11, 2), table_id: 11, region_number: 2, region_group: 0, region_sequence: 2, file_id: "<file_id>", index_version: 0, level: 0, file_path: "test/11_0000000002/<file_id>.parquet", file_size: 2951, max_row_group_uncompressed_size: 0, index_file_path: Some("test/11_0000000002/index/<file_id>.puffin"), index_file_size: Some(250), num_rows: 10, num_row_groups: 1, num_series: Some(1), min_ts: 0::Millisecond, max_ts: 9000::Millisecond, sequence: Some(10), partition_expr: None, origin_region_id: 47244640258(11, 2), node_id: None, visible: true, primary_key_min: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01"), primary_key_max: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01") }
ManifestSstEntry { table_dir: "test/", region_id: 94489280554(22, 42), table_id: 22, region_number: 42, region_group: 0, region_sequence: 42, file_id: "<file_id>", index_version: 0, level: 0, file_path: "test/22_0000000042/<file_id>.parquet", file_size: 2951, max_row_group_uncompressed_size: 0, index_file_path: Some("test/22_0000000042/index/<file_id>.puffin"), index_file_size: Some(250), num_rows: 10, num_row_groups: 1, num_series: Some(1), min_ts: 0::Millisecond, max_ts: 9000::Millisecond, sequence: Some(10), partition_expr: None, origin_region_id: 94489280554(22, 42), node_id: None, visible: true, primary_key_min: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01"), primary_key_max: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01") }"# ,
r#"
StorageSstEntry { file_path: "test/11_0000000001/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/11_0000000001/index/<file_id>.puffin", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/11_0000000002/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/11_0000000002/index/<file_id>.puffin", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/22_0000000042/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/22_0000000042/index/<file_id>.puffin", file_size: None, last_modified_ms: None, node_id: None }"#).await;
test_list_ssts_with_format(true, r#"
ManifestSstEntry { table_dir: "test/", region_id: 47244640257(11, 1), table_id: 11, region_number: 1, region_group: 0, region_sequence: 1, file_id: "<file_id>", index_version: 0, level: 0, file_path: "test/11_0000000001/<file_id>.parquet", file_size: 3365, max_row_group_uncompressed_size: 0, index_file_path: Some("test/11_0000000001/index/<file_id>.puffin"), index_file_size: Some(250), num_rows: 10, num_row_groups: 1, num_series: Some(1), min_ts: 0::Millisecond, max_ts: 9000::Millisecond, sequence: Some(10), partition_expr: None, origin_region_id: 47244640257(11, 1), node_id: None, visible: true, primary_key_min: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01"), primary_key_max: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01") }
ManifestSstEntry { table_dir: "test/", region_id: 47244640258(11, 2), table_id: 11, region_number: 2, region_group: 0, region_sequence: 2, file_id: "<file_id>", index_version: 0, level: 0, file_path: "test/11_0000000002/<file_id>.parquet", file_size: 3365, max_row_group_uncompressed_size: 0, index_file_path: Some("test/11_0000000002/index/<file_id>.puffin"), index_file_size: Some(250), num_rows: 10, num_row_groups: 1, num_series: Some(1), min_ts: 0::Millisecond, max_ts: 9000::Millisecond, sequence: Some(10), partition_expr: None, origin_region_id: 47244640258(11, 2), node_id: None, visible: true, primary_key_min: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01"), primary_key_max: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01") }
ManifestSstEntry { table_dir: "test/", region_id: 94489280554(22, 42), table_id: 22, region_number: 42, region_group: 0, region_sequence: 42, file_id: "<file_id>", index_version: 0, level: 0, file_path: "test/22_0000000042/<file_id>.parquet", file_size: 3365, max_row_group_uncompressed_size: 0, index_file_path: Some("test/22_0000000042/index/<file_id>.puffin"), index_file_size: Some(250), num_rows: 10, num_row_groups: 1, num_series: Some(1), min_ts: 0::Millisecond, max_ts: 9000::Millisecond, sequence: Some(10), partition_expr: None, origin_region_id: 94489280554(22, 42), node_id: None, visible: true, primary_key_min: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01"), primary_key_max: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01") }"#,
r#"
StorageSstEntry { file_path: "test/11_0000000001/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/11_0000000001/index/<file_id>.puffin", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/11_0000000002/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/11_0000000002/index/<file_id>.puffin", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/22_0000000042/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/22_0000000042/index/<file_id>.puffin", file_size: None, last_modified_ms: None, node_id: None }"#).await;
}
async fn test_list_ssts_with_format(
flat_format: bool,
expected_manifest_ssts: &str,
expected_storage_ssts: &str,
) {
async fn test_list_ssts(#[case] flat_format: bool) {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
@@ -1183,24 +1157,33 @@ async fn test_list_ssts_with_format(
}
// list from manifest
let debug_format = engine
.all_ssts_from_manifest()
.await
.into_iter()
.map(|mut e| {
e.file_path = e.file_path.replace(&e.file_id, "<file_id>");
e.index_file_path = e
.index_file_path
.map(|p| p.replace(&e.file_id, "<file_id>"));
e.file_id = "<file_id>".to_string();
e.index_version = 0;
e.max_row_group_uncompressed_size = 0;
format!("\n{:?}", e)
})
.sorted()
.collect::<Vec<_>>()
.join("");
assert_eq!(debug_format, expected_manifest_ssts, "{}", debug_format);
let store = env.get_object_store().unwrap();
let mut manifest_ssts = Vec::new();
for mut entry in engine.all_ssts_from_manifest().await {
let actual = store.stat(&entry.file_path).await.unwrap();
assert_eq!(
entry.file_size,
actual.content_length(),
"{}",
entry.file_path
);
entry.file_path = entry.file_path.replace(&entry.file_id, "<file_id>");
entry.index_file_path = entry
.index_file_path
.map(|p| p.replace(&entry.file_id, "<file_id>"));
entry.file_id = "<file_id>".to_string();
entry.file_size = 0;
entry.index_version = 0;
entry.max_row_group_uncompressed_size = 0;
manifest_ssts.push(format!("\n{entry:?}"));
}
manifest_ssts.sort_unstable();
let expected_manifest_ssts = r#"
ManifestSstEntry { table_dir: "test/", region_id: 47244640257(11, 1), table_id: 11, region_number: 1, region_group: 0, region_sequence: 1, file_id: "<file_id>", index_version: 0, level: 0, file_path: "test/11_0000000001/<file_id>.parquet", file_size: 0, max_row_group_uncompressed_size: 0, index_file_path: Some("test/11_0000000001/index/<file_id>.puffin"), index_file_size: Some(250), num_rows: 10, num_row_groups: 1, num_series: Some(1), min_ts: 0::Millisecond, max_ts: 9000::Millisecond, sequence: Some(10), partition_expr: None, origin_region_id: 47244640257(11, 1), node_id: None, visible: true, primary_key_min: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01"), primary_key_max: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01") }
ManifestSstEntry { table_dir: "test/", region_id: 47244640258(11, 2), table_id: 11, region_number: 2, region_group: 0, region_sequence: 2, file_id: "<file_id>", index_version: 0, level: 0, file_path: "test/11_0000000002/<file_id>.parquet", file_size: 0, max_row_group_uncompressed_size: 0, index_file_path: Some("test/11_0000000002/index/<file_id>.puffin"), index_file_size: Some(250), num_rows: 10, num_row_groups: 1, num_series: Some(1), min_ts: 0::Millisecond, max_ts: 9000::Millisecond, sequence: Some(10), partition_expr: None, origin_region_id: 47244640258(11, 2), node_id: None, visible: true, primary_key_min: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01"), primary_key_max: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01") }
ManifestSstEntry { table_dir: "test/", region_id: 94489280554(22, 42), table_id: 22, region_number: 42, region_group: 0, region_sequence: 42, file_id: "<file_id>", index_version: 0, level: 0, file_path: "test/22_0000000042/<file_id>.parquet", file_size: 0, max_row_group_uncompressed_size: 0, index_file_path: Some("test/22_0000000042/index/<file_id>.puffin"), index_file_size: Some(250), num_rows: 10, num_row_groups: 1, num_series: Some(1), min_ts: 0::Millisecond, max_ts: 9000::Millisecond, sequence: Some(10), partition_expr: None, origin_region_id: 94489280554(22, 42), node_id: None, visible: true, primary_key_min: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01"), primary_key_max: Some(b"\x01\x01x\0\0\0\0\0\0\0\x01") }"#;
assert_eq!(manifest_ssts.concat(), expected_manifest_ssts);
// list from storage
let storage_entries = engine
@@ -1220,7 +1203,14 @@ async fn test_list_ssts_with_format(
.sorted()
.collect::<Vec<_>>()
.join("");
assert_eq!(debug_format, expected_storage_ssts, "{}", debug_format);
let expected_storage_ssts = r#"
StorageSstEntry { file_path: "test/11_0000000001/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/11_0000000001/index/<file_id>.puffin", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/11_0000000002/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/11_0000000002/index/<file_id>.puffin", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/22_0000000042/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }
StorageSstEntry { file_path: "test/22_0000000042/index/<file_id>.puffin", file_size: None, last_modified_ms: None, node_id: None }"#;
assert_eq!(debug_format, expected_storage_ssts);
}
#[tokio::test]
+59 -15
View File
@@ -30,13 +30,19 @@ use crate::test_util::{CreateRequestBuilder, TestEnv, build_rows, put_rows, rows
#[cfg(feature = "enterprise")]
#[rstest::rstest]
#[case::shared_only(false, false)]
#[case::mixed(true, false)]
#[case::metadata_rejected_before_copy(true, true)]
#[case::shared_only(false, false, false)]
#[case::mixed(true, false, false)]
#[case::metadata_rejected_before_copy(true, true, false)]
#[case::trusted_shared(false, false, true)]
#[tokio::test]
async fn test_copy_shared_reference_contract(#[case] mixed: bool, #[case] metadata: bool) {
async fn test_copy_shared_reference_contract(
#[case] mixed: bool,
#[case] metadata: bool,
#[case] trusted_shared: bool,
) {
use crate::manifest::action::RegionEdit;
use crate::sst::file::{FileMeta, LEVEL_SHARED, RegionFileId};
use crate::request::{RegionEditRequest, WorkerRequest};
use crate::sst::file::{FileMeta, LEVEL_SHARED, RegionFileId, SHARED_LEVEL_SLOT};
use crate::test_util::flush_region;
use std::collections::HashSet;
use store_api::region_request::PathType;
@@ -90,16 +96,24 @@ async fn test_copy_shared_reference_contract(#[case] mixed: bool, #[case] metada
.clone()
};
for id in [owner_id, source_id] {
engine
.edit_region(
id,
RegionEdit {
files_to_add: vec![shared.clone()],
..Default::default()
},
)
.await
.unwrap();
let edit = RegionEdit {
files_to_add: vec![shared.clone()],
..Default::default()
};
if trusted_shared {
assert!(shared.dedup_marker_trusted);
let (tx, rx) = tokio::sync::oneshot::channel();
let request = RegionEditRequest::new(id, edit, false, tx).for_copy_region();
engine
.inner
.workers
.submit_to_worker(id, WorkerRequest::EditRegion(request))
.await
.unwrap();
rx.await.unwrap().unwrap();
} else {
engine.edit_region(id, edit).await.unwrap();
}
}
let source = engine
.get_region(source_id)
@@ -107,6 +121,10 @@ async fn test_copy_shared_reference_contract(#[case] mixed: bool, #[case] metada
.manifest_ctx
.manifest()
.await;
assert_eq!(
source.files[&shared.file_id].dedup_marker_trusted,
trusted_shared
);
let target = engine.get_region(target_id).unwrap();
let before = target.manifest_ctx.manifest().await;
let target_path = |file_id| {
@@ -176,6 +194,10 @@ async fn test_copy_shared_reference_contract(#[case] mixed: bool, #[case] metada
.unwrap()
);
assert_eq!(Some(1), file.sequence.map(|sequence| sequence.get()));
assert_eq!(
file.dedup_marker_trusted,
file.level != LEVEL_SHARED || trusted_shared
);
}
let sequence = target.version_control.current().last_sequence;
let retry = engine
@@ -194,6 +216,28 @@ async fn test_copy_shared_reference_contract(#[case] mixed: bool, #[case] metada
);
assert_eq!(installed.files, target.manifest_ctx.manifest().await.files);
assert_eq!(sequence, target.version_control.current().last_sequence);
if trusted_shared {
engine
.edit_region(
target_id,
RegionEdit {
files_to_add: vec![FileMeta {
dedup_marker_trusted: false,
..installed.files[&shared.file_id].as_ref().clone()
}],
..Default::default()
},
)
.await
.unwrap();
let manifest = target.manifest_ctx.manifest().await;
let version = target.version();
let handle = &version.ssts.levels()[SHARED_LEVEL_SLOT].files[&shared.file_id];
assert!(manifest.files[&shared.file_id].dedup_marker_trusted);
assert!(handle.dedup_marker_trusted());
assert_eq!(installed.files, manifest.files);
assert_eq!(sequence, target.version_control.current().last_sequence);
}
let rows = RecordBatches::try_collect(
engine
.scan_to_stream(target_id, Default::default())
File diff suppressed because it is too large Load Diff
+91 -27
View File
@@ -38,6 +38,7 @@ use crate::engine::region_hook::{RegionHook, RegionHookRef, VerifiedSstFileInfo}
use crate::error::Error;
use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList};
use crate::region::{MitoRegionRef, RegionLeaderState};
use crate::request::{RegionEditRequest, WorkerRequest};
use crate::sst::file::{ColumnIndexMetadata, FileMeta, IndexType, LEVEL_SHARED, SHARED_LEVEL_SLOT};
use crate::sst::location;
use crate::test_util::sst_util::new_sparse_primary_key;
@@ -58,6 +59,7 @@ async fn copy_sst(region: &MitoRegionRef, source: &FileMeta, level: u8) -> FileM
let mut output = source.clone();
output.file_id = FileId::random();
output.level = level;
output.dedup_marker_trusted = false;
let access = &region.access_layer;
let path = |file: &FileMeta| {
location::sst_file_path(access.table_dir(), file.file_id(), access.path_type())
@@ -82,7 +84,7 @@ async fn copy_sst(region: &MitoRegionRef, source: &FileMeta, level: u8) -> FileM
/// Input admission is deliberately separate from the compaction API.
async fn seed(engine: &MitoEngine, region_id: RegionId) -> (TableCompactionSnapshot, FileMeta) {
let (snapshot, outputs) = seed_shared_inputs(engine, region_id, &[(0, 3)]).await;
let (snapshot, outputs) = seed_shared_inputs(engine, region_id, &[(0, 3)], false).await;
let output = outputs.into_iter().next().unwrap();
(snapshot, output)
}
@@ -93,6 +95,7 @@ async fn seed_shared_inputs(
engine: &MitoEngine,
region_id: RegionId,
row_ranges: &[(usize, usize)],
trusted_inputs: bool,
) -> (TableCompactionSnapshot, Vec<FileMeta>) {
let create = CreateRequestBuilder::new().build();
engine
@@ -111,13 +114,14 @@ async fn seed_shared_inputs(
.await;
flush_region(engine, region_id, None).await;
}
promote_flushed_files(engine, region_id, row_ranges.len()).await
promote_flushed_files(engine, region_id, row_ranges.len(), trusted_inputs).await
}
async fn promote_flushed_files(
engine: &MitoEngine,
region_id: RegionId,
file_count: usize,
trusted_inputs: bool,
) -> (TableCompactionSnapshot, Vec<FileMeta>) {
let region = engine.get_region(region_id).unwrap();
let originals = region.version().ssts.levels()[0]
@@ -127,19 +131,28 @@ async fn promote_flushed_files(
assert_eq!(file_count, originals.len());
let mut shared = Vec::with_capacity(originals.len());
for original in &originals {
shared.push(copy_sst(&region, original, LEVEL_SHARED).await);
let mut file = copy_sst(&region, original, LEVEL_SHARED).await;
file.dedup_marker_trusted = trusted_inputs && original.dedup_marker_trusted;
shared.push(file);
}
let edit = RegionEdit {
files_to_add: shared,
files_to_remove: originals,
..Default::default()
};
if trusted_inputs {
let (tx, rx) = tokio::sync::oneshot::channel();
let request = RegionEditRequest::new(region_id, edit, false, tx).for_copy_region();
engine
.inner
.workers
.submit_to_worker(region_id, WorkerRequest::EditRegion(request))
.await
.unwrap();
rx.await.unwrap().unwrap();
} else {
engine.edit_region(region_id, edit).await.unwrap();
}
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: shared,
files_to_remove: originals,
..Default::default()
},
)
.await
.unwrap();
let snapshot = engine.table_compaction_snapshot(region_id).unwrap();
assert_eq!(file_count, snapshot.inputs.len());
let mut outputs = Vec::with_capacity(snapshot.inputs.len());
@@ -149,6 +162,41 @@ async fn promote_flushed_files(
(snapshot, outputs)
}
#[rstest::rstest]
#[case::older_snapshot(true, false, false, PublicationOutcome::Applied)]
#[case::unproven_manifest(false, true, false, PublicationOutcome::StaleInputs)]
#[case::changed_rows(true, false, true, PublicationOutcome::StaleInputs)]
#[tokio::test]
async fn test_table_compaction_snapshot_dedup_marker_compatibility(
#[case] manifest_trusted: bool,
#[case] snapshot_trusted: bool,
#[case] changed_rows: bool,
#[case] expected: PublicationOutcome,
) {
let mut env = TestEnv::new().await;
let engine = env.create_engine(config()).await;
let region_id = RegionId::new(1, 1);
let (mut snapshot, outputs) =
seed_shared_inputs(&engine, region_id, &[(0, 3)], manifest_trusted).await;
let region = engine.get_region(region_id).unwrap();
let manifest = region.manifest_ctx.manifest().await;
let input = &mut snapshot.inputs[0];
assert_eq!(input, manifest.files[&input.file_id].as_ref());
assert_eq!(input.dedup_marker_trusted, manifest_trusted);
input.dedup_marker_trusted = snapshot_trusted;
if changed_rows {
input.num_rows += 1;
}
assert_eq!(
engine
.publish_table_compaction(region_id, snapshot, outputs)
.await
.unwrap(),
expected
);
assert_eq!(row_count(&engine, region_id).await, 3);
}
async fn row_count(engine: &MitoEngine, region_id: RegionId) -> usize {
RecordBatches::try_collect(
engine
@@ -246,7 +294,10 @@ async fn test_duplicate_publication_and_later_replacement_do_not_readmit_inputs(
let replacement = copy_sst(&region, &output, 0).await;
let edit = RegionEdit {
files_to_remove: vec![output.clone()],
files_to_add: vec![replacement.clone()],
files_to_add: vec![FileMeta {
dedup_marker_trusted: true,
..replacement.clone()
}],
..Default::default()
};
region
@@ -270,16 +321,19 @@ async fn test_duplicate_publication_and_later_replacement_do_not_readmit_inputs(
.delete(&path)
.await
.unwrap();
assert_eq!(
PublicationOutcome::StaleInputs,
engine
.publish_table_compaction(region_id, snapshot, vec![output.clone()])
.await
.unwrap()
);
// Neither the removed file nor the new file with its proof omitted matches a replay.
for retry_output in [output.clone(), replacement.clone()] {
assert_eq!(
PublicationOutcome::StaleInputs,
engine
.publish_table_compaction(region_id, snapshot.clone(), vec![retry_output])
.await
.unwrap()
);
}
let manifest = region.manifest_ctx.manifest().await;
assert_eq!(1, manifest.files.len());
assert!(manifest.files.contains_key(&replacement.file_id));
assert!(manifest.files[&replacement.file_id].dedup_marker_trusted);
assert!(!manifest.files.contains_key(&output.file_id));
reopen_region(&engine, region_id, "test".into(), true, Default::default()).await;
assert_eq!(3, row_count(&engine, region_id).await);
@@ -290,7 +344,8 @@ async fn test_replay_requires_all_inputs_absent_and_all_outputs_matching() {
let mut env = TestEnv::new().await;
let engine = env.create_engine(config()).await;
let region_id = RegionId::new(1, 1);
let (snapshot, outputs) = seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)]).await;
let (snapshot, outputs) =
seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)], false).await;
let mut subset = snapshot.clone();
subset.inputs.truncate(1);
let output = outputs[0].clone();
@@ -464,6 +519,13 @@ async fn test_invalid_results_preserve_inputs_and_reopen_can_replan() {
},
invalid_output,
),
(
FileMeta {
dedup_marker_trusted: true,
..output.clone()
},
invalid_output,
),
(
FileMeta {
available_indexes: smallvec::smallvec![IndexType::InvertedIndex],
@@ -1248,7 +1310,8 @@ async fn test_multiple_outputs_verify_notify_once_and_release_footers(#[case] wi
env.create_engine(config()).await
};
let region_id = RegionId::new(1, 1);
let (snapshot, outputs) = seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)]).await;
let (snapshot, outputs) =
seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)], false).await;
let publish = || engine.publish_table_compaction(region_id, snapshot.clone(), outputs.clone());
assert_eq!(PublicationOutcome::Applied, publish().await.unwrap());
let region = engine.get_region(region_id).unwrap();
@@ -1297,7 +1360,8 @@ async fn test_failed_verification_does_not_notify_hook() {
let mut env = TestEnv::new().await;
let engine = env.create_engine_with_plugins(config(), plugins).await;
let region_id = RegionId::new(1, 1);
let (snapshot, outputs) = seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)]).await;
let (snapshot, outputs) =
seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)], false).await;
let region = engine.get_region(region_id).unwrap();
let version = region.manifest_ctx.manifest_version().await;
let invalid = FileMeta {
@@ -1347,7 +1411,7 @@ async fn test_table_compaction_publication_after_nullable_tag_added() {
.await
.unwrap();
flush_region(&engine, region_id, None).await;
let (snapshot, outputs) = promote_flushed_files(&engine, region_id, 1).await;
let (snapshot, outputs) = promote_flushed_files(&engine, region_id, 1, false).await;
engine
.handle_request(
region_id,
+7
View File
@@ -696,6 +696,13 @@ async fn test_replays_own_tail_after_reopen() {
let version = region.version();
assert_eq!(1, version.ssts.levels()[0].files.len());
assert!(
!version.ssts.levels()[0]
.files()
.next()
.unwrap()
.dedup_marker_trusted()
);
assert_eq!(region.entries[1], version.flushed_entry_id);
assert_eq!(6, count_rows(&region.engine, region.region_id).await);
// The commit released the replayed WAL.
+92 -2
View File
@@ -68,7 +68,7 @@ use crate::request::{
use crate::schedule::CancellableTaskState;
use crate::schedule::scheduler::{Job, SchedulerRef};
use crate::sst::file::{FileMeta, UncommittedSsts};
use crate::sst::parquet::metadata::extract_primary_key_range;
use crate::sst::parquet::metadata::{extract_primary_key_range, has_deduped_sst_marker};
use crate::sst::parquet::{
DEFAULT_READ_BATCH_SIZE, DEFAULT_ROW_GROUP_SIZE, SstInfo, WriteOptions, flat_format,
row_group_size_for,
@@ -846,6 +846,11 @@ impl MemtableSstWriter {
.file_metadata
.as_ref()
.and_then(|meta| extract_primary_key_range(meta, &version.metadata));
let dedup_marker_trusted = matches!(self.kind, MemtableWriteKind::Flush(_))
&& sst_info
.file_metadata
.as_deref()
.is_some_and(has_deduped_sst_marker);
file_metas.push(Self::new_file_meta(
self.region_id,
max_sequence,
@@ -854,6 +859,7 @@ impl MemtableSstWriter {
pk_range,
version.options.preserve_row_sequence
|| version.options.sst_format == Some(FormatType::Narthex),
dedup_marker_trusted,
)?);
}
if self.hook.is_some() {
@@ -908,8 +914,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();
@@ -1007,6 +1017,7 @@ impl MemtableSstWriter {
partition_expr: Option<PartitionExpr>,
primary_key_range: Option<(Bytes, Bytes)>,
preserve_row_sequence: bool,
dedup_marker_trusted: bool,
) -> Result<FileMeta> {
let (primary_key_min, primary_key_max) = match primary_key_range {
Some((min, max)) => (Some(min), Some(max)),
@@ -1032,6 +1043,7 @@ impl MemtableSstWriter {
primary_key_min,
primary_key_max,
preserve_row_sequence,
dedup_marker_trusted,
format: sst_info.format.clone(),
})
}
@@ -2603,6 +2615,84 @@ mod tests {
}
}
#[tokio::test]
async fn test_tail_replay_does_not_trust_a_preencoded_bulk_marker() {
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use store_api::region_engine::RegionEngine;
use store_api::region_request::RegionRequest;
use crate::test_util::{
CreateRequestBuilder, TestEnv, build_rows_for_key, put_rows, rows_schema,
};
let mut env = TestEnv::new().await;
let config = Arc::new(MitoConfig::default());
let engine = env.create_engine(config.as_ref().clone()).await;
let region_id = RegionId::new(1, 1);
let create = CreateRequestBuilder::new()
.insert_option("memtable.type", "bulk")
.insert_option("memtable.bulk.merge_threshold", "2")
.insert_option("memtable.bulk.encode_row_threshold", "1")
.insert_option("memtable.bulk.encode_bytes_threshold", "1")
.build();
let schema = rows_schema(&create);
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
for (start, end) in [(0, 3), (3, 6)] {
put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows: build_rows_for_key("a", start, end, 0),
},
)
.await;
}
let region = engine.get_region(region_id).unwrap();
for memtable in region.version().memtables.list_memtables() {
memtable.compact(false).unwrap();
}
region.version_control.freeze_mutable().unwrap();
let cache = Arc::new(CacheManager::default());
let writer = MemtableSstWriter::new_tail_replay(
&region,
config,
cache.clone(),
Arc::new(Semaphore::new(1)),
);
let uncommitted = UncommittedSsts::new(region_id, region.access_layer.clone(), Some(cache));
let written = writer
.do_flush_memtables(
&region.version(),
WriteOptions::default(),
&CancellableTaskState::new(),
&uncommitted,
)
.await
.unwrap();
assert_eq!(written.encoded_part_count, 1);
let [file] = written.file_metas.as_slice() else {
panic!("expected one SST");
};
assert_eq!(file.num_rows, 6);
assert!(!file.dedup_marker_trusted);
let bytes = region
.access_layer
.object_store()
.read(&file.file_path(region.table_dir(), region.path_type()))
.await
.unwrap()
.to_bytes();
let reader = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
assert!(has_deduped_sst_marker(reader.metadata()));
uncommitted.cleanup().await;
engine.stop().await.unwrap();
}
#[test]
fn test_memtable_flat_sources_uses_non_encoded_schema() -> Result<()> {
struct TestIterBuilder {
@@ -92,6 +92,34 @@ fn test_decoded_row_group_size_is_optional_in_manifests() {
assert_eq!(file, serde_json::from_value::<FileMeta>(encoded).unwrap());
}
#[test]
fn test_file_meta_dedup_marker_trust_is_optional() {
let actions = RegionMetaActionList::decode(EDIT.as_bytes()).unwrap();
let RegionMetaAction::Edit(edit) = &actions.actions[0] else {
panic!("expected edit");
};
let legacy = &edit.files_to_add[0];
assert!(!legacy.dedup_marker_trusted);
assert!(
serde_json::to_value(legacy)
.unwrap()
.get("dedup_marker_trusted")
.is_none()
);
let trusted = FileMeta {
dedup_marker_trusted: true,
..legacy.clone()
};
assert_ne!(legacy, &trusted);
let encoded = serde_json::to_value(&trusted).unwrap();
assert_eq!(json!(true), encoded["dedup_marker_trusted"]);
assert_eq!(
trusted,
serde_json::from_value::<FileMeta>(encoded).unwrap()
);
}
#[rstest::rstest]
#[case("table_compaction")]
#[case("extensions")]
+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
@@ -71,6 +71,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::{
@@ -999,6 +1000,7 @@ impl From<Batch> for BatchBuilder {
pub struct FlatSource {
schema: SchemaRef,
inner: FlatSourceInner,
dedup_mode: Option<MergeMode>,
}
impl FlatSource {
@@ -1007,6 +1009,7 @@ impl FlatSource {
Self {
schema,
inner: FlatSourceInner::Iter(iter),
dedup_mode: None,
}
}
@@ -1015,9 +1018,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
+128 -37
View File
@@ -14,6 +14,10 @@
//! Scans a region according to the scan request.
mod aggr;
#[cfg(any(test, feature = "test", feature = "testing"))]
pub use aggr::overlap as metadata_aggr_overlap;
use std::collections::{BTreeMap, HashSet};
use std::fmt;
use std::num::NonZeroU64;
@@ -40,13 +44,13 @@ use datatypes::extension::json::is_json2_extension_type;
use datatypes::prelude::ConcreteDataType;
use datatypes::types::json_type::JsonNativeType;
use datatypes::value::timestamp_to_scalar_value;
use futures::StreamExt;
use futures::{FutureExt, StreamExt};
use mito_codec::row_converter::{SortField, build_primary_key_codec_with_fields};
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,
@@ -243,6 +247,7 @@ pub(crate) struct ScanRegion {
/// Maximum number of SST files to scan concurrently.
max_concurrent_scan_files: usize,
scan_memory_tracker: Option<QueryMemoryTracker>,
experimental_metadata_aggr: bool,
/// Whether to ignore range indexes during scans.
/// Whether to ignore inverted index.
ignore_inverted_index: bool,
@@ -278,6 +283,7 @@ impl ScanRegion {
cache_strategy,
max_concurrent_scan_files: DEFAULT_MAX_CONCURRENT_SCAN_FILES,
scan_memory_tracker: None,
experimental_metadata_aggr: false,
ignore_inverted_index: false,
ignore_fulltext_index: false,
ignore_bloom_filter: false,
@@ -312,6 +318,12 @@ impl ScanRegion {
self
}
/// Enables optional exact-count preparation for hinted scalar count scans.
pub(crate) fn with_experimental_metadata_aggr(mut self, enabled: bool) -> Self {
self.experimental_metadata_aggr = enabled;
self
}
/// Sets whether to ignore inverted index.
#[must_use]
pub(crate) fn with_ignore_inverted_index(mut self, ignore: bool) -> Self {
@@ -619,7 +631,14 @@ impl ScanRegion {
} else {
input
};
Ok(input.build())
let mut input = input.build();
input.row_preserving_request = request_preserves_rows(&self.request);
if self.experimental_metadata_aggr && self.request.metadata_aggr_hint {
// Reuse the scan's manifest time pruning. Footer checks apply only to
// files in the read set, even for manifests from older offline tools.
input.exact_num_rows = aggr::prepare(&input, &self.request).boxed().await;
}
Ok(input)
}
/// Builds the deduplicated root column ids required by the projection and
@@ -891,6 +910,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 {
@@ -902,6 +933,10 @@ fn time_range_covers_file(time_range: Option<&TimestampRange>, file: &FileHandle
/// Common input for different scanners.
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.
/// Whether to ignore range indexes while retaining series-index candidate discovery.
/// Region SST access layer.
@@ -1006,6 +1041,8 @@ impl ScanInput {
) -> ScanInputBuilder {
ScanInputBuilder {
input: ScanInput {
exact_num_rows: None,
row_preserving_request: true,
page_index_policy: None,
access_layer,
read_cols: mapper.read_columns().clone(),
@@ -1765,45 +1802,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 {
@@ -2653,6 +2731,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()
@@ -2665,8 +2754,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);
}
}
@@ -2703,8 +2793,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);
}
}
+720
View File
@@ -0,0 +1,720 @@
// 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.
//! Answers aggregates of a scan from manifest and SST statistics instead of
//! 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.
pub mod overlap;
use std::sync::Arc;
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::future::BoxFuture;
use futures::{FutureExt, StreamExt, TryStreamExt};
use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec};
use parquet::file::metadata::ParquetMetaData;
use store_api::codec::PrimaryKeyEncoding;
use store_api::metadata::{ColumnMetadata, RegionMetadata};
use store_api::storage::{ColumnId, ScanRequest};
use crate::cache::CachedSstMeta;
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::{
extract_primary_key_range, extract_time_range, has_deduped_sst_marker, has_only_puts,
};
/// Returns the exact number of rows the scan yields, or `None` if it cannot
/// 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 input.append_mode && request.filters.is_empty() {
return Some(classification.exact_rows);
}
let check_keys =
classification.key_filter || (!input.append_mode && classification.exact.len() > 1);
let check_rows = !input.append_mode;
futures::stream::iter(classification.exact)
.map(|index| file_evidence(input, input.files[index].clone(), check_keys, check_rows))
.buffer_unordered(input.max_concurrent_scan_files.max(1))
.try_collect::<()>()
.await
.ok()?;
Some(classification.exact_rows)
}
fn time_bounds_match(file: &FileHandle, sst: &CachedSstMeta, time_id: ColumnId) -> bool {
let region = sst.region_metadata();
let time_index = region.time_index_column();
let (start, end) = file.time_range();
time_index.column_id == time_id
&& extract_time_range(&sst.parquet_metadata(), time_index).is_some_and(|(min, max)| {
start.unit() == min.unit() && end.unit() == max.unit() && (start, end) == (min, max)
})
}
/// Proves the bounds and visible rows required for this exact candidate.
fn file_evidence(
input: &ScanInput,
file: FileHandle,
check_keys: bool,
check_rows: bool,
) -> BoxFuture<'static, Result<(), ()>> {
let time_id = input.region_metadata().time_index_column().column_id;
let reader = input
.access_layer
.read_sst(file.clone())
.cache(input.cache_strategy.clone());
async move {
let sst = reader.read_statistics().await.map_err(|e| {
debug!(
"Metadata count could not read footer of {}: {e:?}",
file.file_id()
);
})?;
let metadata = sst.parquet_metadata();
if !time_bounds_match(&file, &sst, time_id) {
return Err(());
}
if check_keys
&& let Some(range) = file.raw_primary_key_range()
&& extract_primary_key_range(&metadata, &sst.region_metadata()) != Some(range)
{
return Err(());
}
(!check_rows || footer_proves_visible_rows(&metadata, file.num_rows()))
.then_some(())
.ok_or(())
}
.boxed()
}
/// 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 || has_deduped_sst_marker(metadata);
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.
struct Classification {
/// Indexes into `ScanInput::files` whose rows are all yielded exactly once.
exact: Vec<usize>,
/// Sum of the manifest row counts of `exact`.
exact_rows: usize,
/// Whether the filter proof depends on key bounds.
key_filter: bool,
}
/// A file is an exact candidate if all of the following hold:
/// - The query time range covers it and every other static filter holds for
/// 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. A multi-row file needs a trusted
/// dedup marker. The footer must still prove uniqueness and all-Put rows.
///
/// 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.memtables.is_empty()
|| !input.allows_exact_row_count()
|| !request_preserves_rows(request)
{
return None;
}
let filters = AggrFilters::new(input.region_metadata(), &request.filters)?;
let range = input.time_range.as_ref()?;
let mut intersecting = Vec::new();
for (index, file) in input.files.iter().enumerate() {
let (start, end) = file.time_range();
if start > end {
return None;
}
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.append_mode || file.num_rows() == 1 || file.dedup_marker_trusted())
&& input.file_time_bounds_fit(file)
&& (input.region_partition_expr.is_none() || input.should_skip_region_partition(file))
&& filters.covers(file);
if !candidate {
return None;
}
intersecting.push(index);
}
if !input.append_mode && intersecting.len() > 1 {
let mapper = input.primary_key_mapper();
let extents: Vec<_> = intersecting
.iter()
.map(|&index| {
let file = &input.files[index];
Extent {
time: file.time_range(),
key: file.primary_key_range(mapper),
}
})
.collect();
if find_overlaps(&extents).contains(&true) {
return None;
}
}
let exact_rows = intersecting.iter().try_fold(0usize, |rows, &index| {
rows.checked_add(input.files[index].num_rows())
})?;
i64::try_from(exact_rows).ok()?;
Some(Classification {
exact: intersecting,
exact_rows,
key_filter: filters.codec.is_some(),
})
}
/// Static scan predicates a metadata count can absorb.
struct AggrFilters {
/// Values the leftmost primary key column must equal.
leftmost_values: Vec<Value>,
codec: Option<Arc<dyn PrimaryKeyCodec>>,
}
impl AggrFilters {
/// Returns `None` if any conjunct is neither a time-index comparison nor an
/// equality between the leftmost primary key column and a literal.
fn new(metadata: &RegionMetadata, filters: &[Expr]) -> Option<Self> {
let time_index = &metadata.time_index_column().column_schema;
let time_type = time_index.data_type.as_arrow_type();
let mut conjuncts = Vec::new();
for expr in filters {
split_and(expr, &mut conjuncts);
}
let mut leftmost_values = Vec::new();
for expr in conjuncts {
if time_filter(expr, &time_index.name, &time_type) {
continue;
}
let column = &leftmost_primary_key(metadata)?.column_schema;
let value = eq_literal(expr, &column.name, &column.data_type.as_arrow_type())?;
leftmost_values.push(Value::try_from(value.clone()).ok()?);
}
let codec = (!leftmost_values.is_empty()).then(|| build_primary_key_codec(metadata));
Some(Self {
leftmost_values,
codec,
})
}
/// Whether the leftmost key equalities hold for every row of the file.
/// Keys are sorted memcomparable bytes, so when both bounds decode to the
/// same leftmost value, every key between them shares it.
fn covers(&self, file: &FileHandle) -> bool {
let Some(codec) = &self.codec else {
return true;
};
let Some((min, max)) = file.raw_primary_key_range() else {
return false;
};
match (codec.decode_leftmost(&min), codec.decode_leftmost(&max)) {
(Ok(Some(low)), Ok(Some(high))) => {
low == high && self.leftmost_values.iter().all(|value| *value == low)
}
_ => false,
}
}
}
/// The leftmost primary key column. Sparse keys are not supported yet.
fn leftmost_primary_key(metadata: &RegionMetadata) -> Option<&ColumnMetadata> {
match metadata.primary_key_encoding {
PrimaryKeyEncoding::Sparse => None,
PrimaryKeyEncoding::Dense => metadata.primary_key_columns().next(),
}
}
fn split_and<'a>(expr: &'a Expr, out: &mut Vec<&'a Expr>) {
match expr {
Expr::BinaryExpr(binary) if binary.op == Operator::And => {
split_and(&binary.left, out);
split_and(&binary.right, out);
}
_ => out.push(expr),
}
}
/// Returns the literal of a non-null, same-type `column = literal` equality.
fn eq_literal<'a>(
expr: &'a Expr,
name: &str,
data_type: &datatypes::arrow::datatypes::DataType,
) -> Option<&'a ScalarValue> {
let Expr::BinaryExpr(binary) = expr else {
return None;
};
if binary.op != Operator::Eq {
return None;
}
let (column, value) = match (binary.left.as_ref(), binary.right.as_ref()) {
(Expr::Column(column), Expr::Literal(value, _))
| (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)
}
fn time_filter(expr: &Expr, name: &str, data_type: &datatypes::arrow::datatypes::DataType) -> bool {
let Expr::BinaryExpr(binary) = expr else {
return false;
};
if binary.op == Operator::And {
return time_filter(&binary.left, name, data_type)
&& time_filter(&binary.right, name, data_type);
}
if !matches!(
binary.op,
Operator::Eq | Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq
) {
return false;
}
let (column, value) = match (binary.left.as_ref(), binary.right.as_ref()) {
(Expr::Column(column), Expr::Literal(value, _))
| (Expr::Literal(value, _), Expr::Column(column)) => (column, value),
_ => return false,
};
column.name == name && !value.is_null() && &value.data_type() == data_type
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use std::sync::{Arc, LazyLock, Mutex};
use bytes::Bytes;
use common_time::Timestamp;
use common_time::timestamp::TimeUnit;
use datafusion_expr::{col, lit};
use datatypes::value::ValueRef;
use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodecExt};
use store_api::storage::{FileId, RegionId};
use table::predicate::build_time_range_predicate;
use super::*;
use crate::read::flat_projection::FlatProjectionMapper;
use crate::read::scan_region::PredicateGroup;
use crate::sst::file::FileMeta;
use crate::test_util::memtable_util::metadata_with_primary_key;
use crate::test_util::new_noop_file_purger;
use crate::test_util::scheduler_util::SchedulerEnv;
/// Files whose `__op_type` statistics would show deletions. Unit tests
/// have no Parquet files; engine tests cover reading the statistics.
static WITH_DELETES: LazyLock<Mutex<HashSet<FileId>>> = LazyLock::new(Default::default);
fn file(start: i64, end: i64, rows: u64, no_deletes: bool) -> FileHandle {
let file_id = FileId::random();
if !no_deletes {
WITH_DELETES.lock().unwrap().insert(file_id);
}
FileHandle::new(
FileMeta {
region_id: RegionId::new(123, 456),
file_id,
num_rows: rows,
dedup_marker_trusted: true,
time_range: (
Timestamp::new_millisecond(start),
Timestamp::new_millisecond(end),
),
..Default::default()
},
new_noop_file_purger(),
)
}
/// A file without deletions whose primary keys span `min..=max` over `(k0, k1)`.
fn keyed_file(
start: i64,
end: i64,
rows: u64,
min: (&str, u32),
max: (&str, u32),
) -> FileHandle {
let codec = DensePrimaryKeyCodec::new(&metadata_with_primary_key(vec![0, 1], false));
let encode = |(k0, k1): (&str, u32)| {
Bytes::from(
codec
.encode([ValueRef::String(k0), ValueRef::UInt32(k1)].into_iter())
.unwrap(),
)
};
FileHandle::new(
FileMeta {
region_id: RegionId::new(123, 456),
file_id: FileId::random(),
num_rows: rows,
dedup_marker_trusted: true,
time_range: (
Timestamp::new_millisecond(start),
Timestamp::new_millisecond(end),
),
primary_key_min: Some(encode(min)),
primary_key_max: Some(encode(max)),
..Default::default()
},
new_noop_file_purger(),
)
}
fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
let classification = classify(input, request)?;
let deletes = WITH_DELETES.lock().unwrap();
classification
.exact
.iter()
.all(|&i| input.append_mode || !deletes.contains(&input.files[i].meta_ref().file_id))
.then_some(classification.exact_rows)
}
async fn input(files: Vec<FileHandle>, filters: &[Expr]) -> 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_predicate(PredicateGroup::new(&metadata, filters).unwrap())
.with_time_range(Some(build_time_range_predicate(
"ts",
TimeUnit::Millisecond,
filters,
)))
.build()
}
#[tokio::test]
async fn test_metadata_aggr_requires_trusted_marker_for_non_append_multi_row_files() {
for (num_rows, append_mode, expected) in
[(2, false, None), (1, false, Some(1)), (2, true, Some(2))]
{
let file = FileHandle::new(
FileMeta {
num_rows,
dedup_marker_trusted: false,
..file(0, 0, num_rows, true).meta_ref().clone()
},
new_noop_file_purger(),
);
let mut input = input(vec![file], &[]).await;
input.append_mode = append_mode;
assert_eq!(exact_count(&input, &ScanRequest::default()), expected);
}
}
#[tokio::test]
async fn test_metadata_aggr_coverage_and_overlap() {
let ts = |v| lit(ScalarValue::TimestampMillisecond(Some(v), None));
for (filters, expected) in [
(vec![], Some(5)),
(vec![col("ts").lt(ts(20))], Some(3)),
(vec![col("ts").gt_eq(ts(20))], Some(2)),
(vec![col("ts").lt(ts(5))], None),
(vec![col("ts").gt(ts(30))], Some(0)),
(vec![col("ts").eq(ts(0)).or(col("ts").eq(ts(30)))], None),
(vec![col("ts").not_eq(ts(5))], None),
(vec![col("k0").eq(lit("x"))], None),
] {
let input = input(vec![file(0, 10, 3, true), file(20, 30, 2, true)], &filters).await;
let request = ScanRequest {
filters,
metadata_aggr_hint: true,
..Default::default()
};
// Deletion evidence comes from the test, see `WITH_DELETES`.
assert_eq!(exact_count(&input, &request), expected, "{request:?}");
}
for files in [
vec![file(0, 10, 3, true), file(10, 20, 2, true)],
vec![file(0, 10, 3, true), file(5, 8, 2, true)],
vec![file(0, 10, 3, false)],
vec![file(0, 10, 0, false)],
] {
assert_eq!(
exact_count(&input(files, &[]).await, &ScanRequest::default()),
None
);
}
}
#[tokio::test]
async fn test_metadata_aggr_leftmost_key_filter() {
let ts = |v| lit(ScalarValue::TimestampMillisecond(Some(v), None));
let x = |start, end, rows| keyed_file(start, end, rows, ("x", 1), ("x", 9));
let mixed = || keyed_file(20, 30, 2, ("x", 1), ("y", 1));
let k0 = |v: &str| col("k0").eq(lit(v));
for (files, filters, expected) in [
// Both bounds prove the equality, so it holds for every row.
(
vec![x(0, 10, 3), x(20, 30, 2)],
vec![col("ts").gt_eq(ts(0)).and(col("ts").lt(ts(40))), k0("x")],
Some(5),
),
(
vec![x(0, 10, 3), x(20, 30, 2)],
vec![lit("x").eq(col("k0"))],
Some(5),
),
// A file spanning several leftmost values may hold other rows.
(vec![x(0, 10, 3), mixed()], vec![k0("x")], None),
// A disproved equality is not used to exclude files.
(vec![x(0, 10, 3)], vec![k0("y")], None),
// Only the leftmost column is decodable from the bounds.
(vec![x(0, 10, 3)], vec![col("k1").eq(lit(1u32))], None),
(vec![x(0, 10, 3)], vec![col("k0").not_eq(lit("y"))], None),
// Missing key statistics cannot prove anything.
(vec![file(0, 10, 3, true)], vec![k0("x")], None),
] {
let input = input(files, &filters).await;
let request = ScanRequest {
filters,
metadata_aggr_hint: true,
..Default::default()
};
assert_eq!(exact_count(&input, &request), expected, "{request:?}");
}
}
#[tokio::test]
async fn test_metadata_aggr_fences_and_limits() {
let input = input(vec![file(0, 10, 3, true)], &[]).await;
for request in [
ScanRequest {
limit: Some(1),
..Default::default()
},
ScanRequest {
memtable_max_sequence: Some(10),
..Default::default()
},
ScanRequest {
memtable_min_sequence: Some(10),
..Default::default()
},
ScanRequest {
snapshot_on_scan: true,
..Default::default()
},
ScanRequest {
sst_min_sequence: Some(10),
..Default::default()
},
ScanRequest {
exact_sequence_range: true,
..Default::default()
},
ScanRequest {
skip_sst_files: true,
..Default::default()
},
] {
assert_eq!(exact_count(&input, &request), None);
}
let mut input = input;
input.files.clear();
assert_eq!(exact_count(&input, &ScanRequest::default()), Some(0));
}
#[tokio::test]
async fn test_metadata_aggr_unknown_manifest_count_falls_back() {
let mut input = input(vec![file(0, 10, 0, true)], &[]).await;
assert_eq!(exact_count(&input, &ScanRequest::default()), None);
input.append_mode = true;
assert_eq!(exact_count(&input, &ScanRequest::default()), None);
}
#[test]
fn test_metadata_aggr_reads_op_type_statistics() {
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::metadata::KeyValue;
use parquet::file::properties::{EnabledStatistics, WriterProperties};
use store_api::storage::consts::OP_TYPE_COLUMN_NAME;
use crate::sst::parquet::metadata::DEDUPED_SST_KEY;
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([
("payload", Arc::new(nested) as ArrayRef),
(name, Arc::new(UInt8Array::from(ops)) as ArrayRef),
])
.unwrap();
let mut buffer = Vec::new();
// 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();
writer.write(&batch).unwrap();
writer.close().unwrap();
ParquetRecordBatchReaderBuilder::try_new(Bytes::from(buffer))
.unwrap()
.metadata()
.clone()
};
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 original_scope = partition_col("k0").gt_eq(Value::String("a".into()));
let file = FileHandle::new(
FileMeta {
partition_expr: Some(original_scope.clone().into()),
..file(0, 10, 3, true).meta_ref().clone()
},
new_noop_file_purger(),
);
let mut input = input(vec![file], &[]).await;
input.region_partition_expr = Some(original_scope);
assert_eq!(exact_count(&input, &ScanRequest::default()), Some(3));
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)),
..file(0, 0, 2, true).meta_ref().clone()
},
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);
}
}
}
@@ -0,0 +1,347 @@
// 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.
//! Finds sources that may share a row in (time, primary key) space.
use std::cmp::{max, min};
/// The inclusive time and primary key bounds of one source.
///
/// A missing key range is unknown and conservatively spans every key.
#[derive(Debug, Clone)]
pub struct Extent<T, K> {
/// Inclusive `(start, end)`; `start <= end`.
pub time: (T, T),
/// Inclusive `(min, max)`; `min <= max`.
pub key: Option<(K, K)>,
}
/// Returns whether each extent intersects at least one other extent. Bounds
/// are inclusive in both dimensions, so touching endpoints count as overlap.
///
/// Sorts the extents by start time once and sweeps them twice over one
/// array-backed segment tree on the compressed key coordinates. The forward
/// sweep finds each extent's conflict with an earlier-starting extent: an
/// extent that starts no later overlaps if, somewhere in its key range, an
/// earlier extent ends at or after its start. The reverse sweep finds the
/// conflict with a later-starting extent in the same way. Expired extents need
/// no removal, since their bounds fail the comparison. Each sweep queries
/// before it updates, so the cost is O(N log N), even when many extents
/// overlap in time but have disjoint keys.
pub fn find_overlaps<T: Ord, K: Ord>(extents: &[Extent<T, K>]) -> Vec<bool> {
// Compress key endpoints into 1..=len. 0 and len + 1 stand for the open
// ends of an unknown key range.
let mut keys: Vec<&K> = Vec::with_capacity(2 * extents.len());
keys.extend(
extents
.iter()
.filter_map(|extent| extent.key.as_ref())
.flat_map(|(min, max)| [min, max]),
);
keys.sort_unstable();
keys.dedup();
let position = |key: &K| keys.partition_point(|k| *k < key) + 1;
let unbounded = keys.len() + 1;
let coordinates: Vec<_> = extents
.iter()
.map(|extent| {
debug_assert!(extent.time.0 <= extent.time.1);
match &extent.key {
Some((min, max)) => {
debug_assert!(min <= max);
(position(min), position(max))
}
None => (0, unbounded),
}
})
.collect();
// Equal starts in index order; an unstable sort needs no buffer.
let mut order: Vec<usize> = (0..extents.len()).collect();
order.sort_unstable_by(|&lhs, &rhs| {
extents[lhs]
.time
.0
.cmp(&extents[rhs].time.0)
.then(lhs.cmp(&rhs))
});
let mut overlaps = vec![false; extents.len()];
let mut tree = BoundTree::new(unbounded + 1);
// Latest end time over every key of the extents started so far.
for &index in &order {
let (low, high) = coordinates[index];
let (start, end) = (&extents[index].time.0, &extents[index].time.1);
overlaps[index] |= tree
.query::<Latest>(low, high)
.is_some_and(|last| last >= start);
tree.update::<Latest>(low, high, end);
}
// Earliest start time over every key of the extents starting later.
tree.clear();
for &index in order.iter().rev() {
let (low, high) = coordinates[index];
let (start, end) = (&extents[index].time.0, &extents[index].time.1);
overlaps[index] |= tree
.query::<Earliest>(low, high)
.is_some_and(|first| first <= end);
tree.update::<Earliest>(low, high, start);
}
overlaps
}
/// The quadratic reference implementation of [`find_overlaps`].
#[cfg(any(test, feature = "test", feature = "testing"))]
pub fn find_overlaps_pairwise<T: Ord, K: Ord>(extents: &[Extent<T, K>]) -> Vec<bool> {
let mut overlaps = vec![false; extents.len()];
for (index, lhs) in extents.iter().enumerate() {
for (offset, rhs) in extents[index + 1..].iter().enumerate() {
let keys_overlap = match (&lhs.key, &rhs.key) {
(Some(lhs), Some(rhs)) => (&lhs.0).max(&rhs.0) <= (&lhs.1).min(&rhs.1),
_ => true,
};
if keys_overlap && (&lhs.time.0).max(&rhs.time.0) <= (&lhs.time.1).min(&rhs.time.1) {
overlaps[index] = true;
overlaps[index + 1 + offset] = true;
}
}
}
overlaps
}
/// The best bound per key coordinate, for range updates and range queries
/// that take the larger (or smaller) of two bounds.
///
/// A bound applied to a whole node is kept on that node and never pushed down,
/// since an update and a query only ever combine bounds with the same order.
struct BoundTree<'a, T> {
/// The best bound applied to every key of each node.
tags: Vec<Option<&'a T>>,
/// The best bound applied to any key of each node, including its tag.
best: Vec<Option<&'a T>>,
/// Number of leaves, a power of two.
width: usize,
}
/// The order in which a [`BoundTree`] keeps the better of two bounds. A type
/// parameter rather than a function pointer, so each sweep is monomorphized.
trait Pick {
fn pick<'a, T: Ord>(lhs: &'a T, rhs: &'a T) -> &'a T;
fn combine<'a, T: Ord>(lhs: Option<&'a T>, rhs: Option<&'a T>) -> Option<&'a T> {
match (lhs, rhs) {
(Some(lhs), Some(rhs)) => Some(Self::pick(lhs, rhs)),
(lhs, rhs) => lhs.or(rhs),
}
}
}
/// Keeps the larger bound.
struct Latest;
impl Pick for Latest {
fn pick<'a, T: Ord>(lhs: &'a T, rhs: &'a T) -> &'a T {
max(lhs, rhs)
}
}
/// Keeps the smaller bound.
struct Earliest;
impl Pick for Earliest {
fn pick<'a, T: Ord>(lhs: &'a T, rhs: &'a T) -> &'a T {
min(lhs, rhs)
}
}
impl<'a, T: Ord> BoundTree<'a, T> {
fn new(len: usize) -> Self {
let width = len.next_power_of_two();
Self {
tags: vec![None; 2 * width],
best: vec![None; 2 * width],
width,
}
}
fn clear(&mut self) {
self.tags.fill(None);
self.best.fill(None);
}
/// Applies `bound` to every key in `[low, high]`.
fn update<P: Pick>(&mut self, low: usize, high: usize, bound: &'a T) {
self.update_in::<P>(1, 0, self.width - 1, low, high, bound);
}
fn update_in<P: Pick>(
&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::<P>(2 * node, node_low, mid, low, high, bound);
self.update_in::<P>(2 * node + 1, mid + 1, node_high, low, high, bound);
}
/// Returns the best bound applied to any key in `[low, high]`.
fn query<P: Pick>(&self, low: usize, high: usize) -> Option<&'a T> {
self.query_in::<P>(1, 0, self.width - 1, low, high)
}
fn query_in<P: Pick>(
&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::<P>(2 * node, node_low, mid, low, high),
self.query_in::<P>(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<i64, u32> {
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));
}
}
+2 -7
View File
@@ -87,13 +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_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()];
@@ -692,6 +686,7 @@ impl RegionScanner for SeqScan {
// rather than claiming pushdown that discovery cannot honor.
return vec![false; filter_exprs.len()];
}
self.properties.clear_exact_num_rows();
self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs)
}
+2 -7
View File
@@ -150,13 +150,7 @@ impl SeriesScan {
} else {
SeriesScanMode::Legacy
};
let mut properties = ScannerProperties::default()
.with_append_mode(input.append_mode)
.with_total_rows(input.total_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()];
@@ -896,6 +890,7 @@ impl RegionScanner for SeriesScan {
if self.stream_ctx.input.requires_narthex_preparation() {
return vec![false; filter_exprs.len()];
}
self.properties.clear_exact_num_rows();
let matched = self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs);
// The added filters change the predicate group the preflight inspects.
self.clear_preflight_cache();
+2 -7
View File
@@ -63,13 +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_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()];
@@ -364,6 +358,7 @@ impl RegionScanner for UnorderedScan {
&mut self,
filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
) -> Vec<bool> {
self.properties.clear_exact_num_rows();
self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs)
}
+45
View File
@@ -66,6 +66,7 @@ use crate::manifest::action::{
PendingTail, RegionChange, RegionEdit, RegionManifest, RegionMetaAction, RegionMetaActionList,
};
use crate::manifest::manager::RegionManifestManager;
use crate::memtable::MemtableId;
use crate::metrics::manifest_size::RegionManifestSizeMetric;
use crate::region::version::{VersionControlRef, VersionRef};
use crate::request::{OnFailure, OptionOutputTx};
@@ -355,6 +356,50 @@ impl MitoRegion {
version_data.version
}
/// Installs an edit reported by a completed manifest publication. Callers
/// must be outside the manifest lock.
pub(crate) async fn apply_published_edit(
&self,
mut edit: RegionEdit,
memtables_to_remove: &[MemtableId],
) {
let ssts = self.version().ssts.clone();
let conflicts = |file: &FileMeta| {
ssts.levels()
.iter()
.filter_map(|level| level.files.get(&file.file_id))
.any(|visible| {
visible.file_id() == file.file_id()
&& visible.dedup_marker_trusted() != file.dedup_marker_trusted
})
};
// An edit can publish while an earlier writer is still firing its manifest hook.
// When their proof differs, install the current metadata under the manifest lock.
let manifest_guard = if edit.files_to_add.iter().any(&conflicts) {
Some(self.manifest_ctx.manifest_manager.read().await)
} else {
None
};
if let Some(manager) = &manifest_guard {
let manifest = manager.manifest();
edit.files_to_add.retain_mut(|file| {
if !conflicts(file) {
return true;
}
let Some(current) = manifest.files.get(&file.file_id) else {
return false;
};
if current.file_id() != file.file_id() || current.level != file.level {
return false;
}
*file = current.as_ref().clone();
true
});
}
self.version_control
.apply_edit(Some(edit), memtables_to_remove, self.file_purger.clone());
}
/// Returns whether writes to this region should skip WAL.
pub(crate) fn skip_wal(&self) -> bool {
self.provider == Provider::Noop || self.version().options.skip_wal
+11 -2
View File
@@ -1544,7 +1544,9 @@ impl Waiters {
/// Transient execution semantics; this is never serialized into the manifest.
#[derive(Debug)]
pub(crate) enum RegionEditKind {
Import,
Import {
external: bool,
},
#[cfg(feature = "enterprise")]
Compaction(Box<crate::engine::table_compaction::PublicationContext>),
}
@@ -1575,7 +1577,7 @@ impl RegionEditRequest {
region_id,
edit,
preload_sst_cache,
kind: RegionEditKind::Import,
kind: RegionEditKind::Import { external: true },
waiters: Waiters::one(waiter),
staging_partition_expr: None,
}
@@ -1583,9 +1585,16 @@ impl RegionEditRequest {
/// Binds the edit to the staging for `partition_expr`.
pub(crate) fn for_staging(mut self, partition_expr: String) -> Self {
self.kind = RegionEditKind::Import { external: false };
self.staging_partition_expr = Some(partition_expr);
self
}
/// Preserves the provenance of SSTs copied from a source region's manifest.
pub(crate) fn for_copy_region(mut self) -> Self {
self.kind = RegionEditKind::Import { external: false };
self
}
}
/// Whether the worker needs to install the edit in the in-memory version.
+12
View File
@@ -436,6 +436,11 @@ pub struct FileMeta {
/// restore this capability for untrusted inputs.
#[serde(default, skip_serializing_if = "is_false")]
pub preserve_row_sequence: bool,
/// Whether `greptimedb.deduped` in this file's Parquet footer was emitted
/// by an engine writer that folded row versions. Defaults to `false` so
/// legacy manifests and checkpoints rewritten across a downgrade fail closed.
#[serde(default, skip_serializing_if = "is_false")]
pub dedup_marker_trusted: bool,
/// Physical encoding, omitted for legacy Parquet files.
#[serde(default, skip_serializing_if = "FileFormat::is_parquet")]
pub format: FileFormat,
@@ -517,6 +522,9 @@ impl Debug for FileMeta {
)
.field("partition_expr", &self.partition_expr)
.field("num_series", &self.num_series);
if self.dedup_marker_trusted {
debug_struct.field("dedup_marker_trusted", &self.dedup_marker_trusted);
}
if self.primary_key_min.is_some() || self.primary_key_max.is_some() {
debug_struct
.field(
@@ -944,6 +952,10 @@ impl FileHandle {
self.inner.meta.num_rows as usize
}
pub fn dedup_marker_trusted(&self) -> bool {
self.inner.meta.dedup_marker_trusted
}
pub fn level(&self) -> Level {
self.inner.meta.level
}
+5 -2
View File
@@ -855,8 +855,11 @@ pub(crate) fn parquet_row_group_time_range(
}
};
debug_assert!(min >= file_meta.time_range.0.value() && min <= file_meta.time_range.1.value());
debug_assert!(max >= file_meta.time_range.0.value() && max <= file_meta.time_range.1.value());
// The cached footer may have come from an offline replacement whose
// current statistics do not fit the old manifest bounds.
if min > max || min < file_meta.time_range.0.value() || max > file_meta.time_range.1.value() {
return None;
}
let unit = file_meta.time_range.0.unit();
Some((Timestamp::new(min, unit), Timestamp::new(max, unit)))
+138 -7
View File
@@ -15,22 +15,44 @@
use std::result::Result as StdResult;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use api::v1::OpType;
use bytes::Bytes;
use common_time::Timestamp;
use common_time::timestamp::TimeUnit;
use datatypes::arrow::datatypes::DataType;
use futures::FutureExt;
use futures::future::BoxFuture;
use object_store::ObjectStore;
use parquet::arrow::async_reader::MetadataFetch;
use parquet::arrow::parquet_to_arrow_schema;
use parquet::basic::{ConvertedType, LogicalType, TimeUnit as ParquetTimeUnit, 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::metadata::{ColumnMetadata, RegionMetadata};
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::file::FileTimeRange;
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 const DEDUPED_SST_KEY: &str = "greptimedb.deduped";
/// Whether the footer carries a writer's deduplication claim.
pub fn has_deduped_sst_marker(metadata: &ParquetMetaData) -> bool {
metadata
.file_metadata()
.key_value_metadata()
.is_some_and(|entries| entries.iter().any(|entry| entry.key == DEDUPED_SST_KEY))
}
/// 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,12 +147,67 @@ 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)
}
pub(crate) fn extract_primary_key_range(
/// 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))
}
/// Returns complete encoded primary-key endpoints, if all row groups provide them.
pub fn extract_primary_key_range(
parquet_meta: &ParquetMetaData,
region_metadata: &RegionMetadata,
) -> Option<(Bytes, Bytes)> {
@@ -168,6 +245,60 @@ pub(crate) fn extract_primary_key_range(
min.zip(max)
}
/// Returns exact time-index bounds with the unit stored in this SST.
pub fn extract_time_range(
parquet_meta: &ParquetMetaData,
time_index: &ColumnMetadata,
) -> Option<FileTimeRange> {
let name = &time_index.column_schema.name;
let file = parquet_meta.file_metadata();
let index = top_level_leaf_index(file.schema_descr(), name, Type::INT64)?;
let column = file.schema_descr().column(index);
let unit = match (column.logical_type_ref(), column.converted_type()) {
(Some(LogicalType::Timestamp(timestamp)), _) => match timestamp.unit {
ParquetTimeUnit::MILLIS => TimeUnit::Millisecond,
ParquetTimeUnit::MICROS => TimeUnit::Microsecond,
ParquetTimeUnit::NANOS => TimeUnit::Nanosecond,
},
(None, ConvertedType::TIMESTAMP_MILLIS) => TimeUnit::Millisecond,
(None, ConvertedType::TIMESTAMP_MICROS) => TimeUnit::Microsecond,
(None, ConvertedType::NONE) => {
// Parquet has no timestamp annotation for seconds. Arrow stores
// the type in its schema metadata and leaves the INT64 unannotated.
let schema =
parquet_to_arrow_schema(file.schema_descr(), file.key_value_metadata()).ok()?;
let DataType::Timestamp(unit, _) = schema.field_with_name(name).ok()?.data_type()
else {
return None;
};
TimeUnit::from(unit)
}
_ => return None,
};
if time_index.column_schema.data_type.as_timestamp()?.unit() != unit {
return None;
}
let mut min = i64::MAX;
let mut max = i64::MIN;
for group in parquet_meta.row_groups() {
let Statistics::Int64(stats) = group.column(index).statistics()? else {
return None;
};
let (low, high) = (*stats.min_opt()?, *stats.max_opt()?);
if low > high
|| !stats.min_is_exact()
|| !stats.max_is_exact()
|| stats.null_count_opt() != Some(0)
{
return None;
}
min = min.min(low);
max = max.max(high);
}
(min <= max).then(|| (Timestamp::new(min, unit), Timestamp::new(max, unit)))
}
struct ObjectStoreFetch<'a> {
object_store: &'a ObjectStore,
file_path: &'a str,
@@ -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?;
+13
View File
@@ -757,6 +757,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<Arc<CachedSstMeta>> {
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)
}
/// Reads parquet metadata of specific file.
/// Returns (fused metadata, cache_miss_flag).
pub(crate) async fn read_parquet_metadata(
+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,
@@ -589,6 +598,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.
@@ -630,6 +640,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;
@@ -744,6 +757,7 @@ where
) -> Result<SstInfoArray> {
let mut results = smallvec![];
let mut stats = SourceStats::default();
let dedup_mode = source.dedup_mode();
loop {
let start = Instant::now();
@@ -771,7 +785,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()
@@ -796,7 +811,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?;
}
@@ -807,7 +823,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)
+53 -6
View File
@@ -127,23 +127,37 @@ impl SstVersion {
let Some(slot) = file::level_slot(level) else {
panic!("Unsupported SST level {level}");
};
// If the file already exists, then we should only replace the handle when the index is outdated.
levels[slot]
.files
.entry(file.file_id)
.and_modify(|f| {
if f.meta_ref() == file.as_ref() || f.meta_ref().is_index_up_to_date(&file) {
// same file meta or current file handle's index is up-to-date, skip adding
if f.meta_ref() == file.as_ref() {
return;
}
if f.meta_ref().is_index_up_to_date(&file) {
if f.index_id().version > new_index_version {
// what does it mean for us to see older index version?
common_telemetry::warn!(
"Adding file with older index version, existing: {:?}, new: {:?}, ignoring new file",
"Adding file with older index version, existing: {:?}, new: {:?}, retaining current index",
f.meta_ref(),
file
);
}
let current = f.meta_ref();
if current.file_id() == file.file_id()
&& current.dedup_marker_trusted != file.dedup_marker_trusted
{
// Adopt the committed provenance with its file bounds and partition
// scope while keeping the current index generation.
let meta = FileMeta {
available_indexes: current.available_indexes.clone(),
indexes: current.indexes.clone(),
index_file_size: current.index_file_size,
index_version: current.index_version,
..file.as_ref().clone()
};
*f = f.with_updated_index(meta);
}
} else {
// include case like old file have no index or index is outdated
*f = f.with_updated_index(file.clone());
}
})
@@ -436,6 +450,39 @@ mod tests {
assert!(old_snapshot.levels()[0].files[&meta.file_id].is_deleted());
}
#[rstest::rstest]
fn test_file_meta_dedup_trust_update_retains_a_newer_index(
#[values(false, true)] trusted: bool,
) {
let purger = new_noop_file_purger();
let indexed = FileMeta {
file_id: FileId::random(),
index_version: 2,
available_indexes: smallvec::smallvec![crate::sst::file::IndexType::InvertedIndex],
dedup_marker_trusted: trusted,
..Default::default()
};
let mut version = SstVersion::new(crate::test_util::memtable_util::metadata_for_test());
version.add_files(purger.clone(), [indexed.clone()].into_iter());
let old_reader = version.levels()[0].files[&indexed.file_id].clone();
version.add_files(
purger,
[FileMeta {
index_version: 1,
dedup_marker_trusted: !trusted,
num_rows: 3,
..indexed.clone()
}]
.into_iter(),
);
let current = &version.levels()[0].files[&indexed.file_id];
assert_eq!(trusted, old_reader.dedup_marker_trusted());
assert_eq!(!trusted, current.dedup_marker_trusted());
assert_eq!(3, current.num_rows());
assert_eq!(current.index_id(), old_reader.index_id());
}
#[test]
fn test_add_files() {
let purger = new_noop_file_purger();
+1 -1
View File
@@ -1836,7 +1836,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
}
BackgroundNotify::RegionEdit(req) => self.handle_region_edit_result(req).await,
BackgroundNotify::CopyRegionFromFinished(req) => {
self.handle_copy_region_from_finished(req)
self.handle_copy_region_from_finished(req).await
}
BackgroundNotify::RegionFenced => {}
BackgroundNotify::RegionReloaded { old, result } => {
+2 -10
View File
@@ -61,11 +61,7 @@ impl<S> RegionWorkerLoop<S> {
}
let progress =
made_progress(edit.files_to_add.len(), edit.files_to_remove.len());
region.version_control.apply_edit(
Some(edit.clone()),
&[],
region.file_purger.clone(),
);
region.apply_published_edit(edit.clone(), &[]).await;
self.listener.on_compaction_unit_applied(region_id, plan_id);
self.compaction_scheduler.on_unit_finished(
region_id,
@@ -231,11 +227,7 @@ impl<S> RegionWorkerLoop<S> {
request.edit.files_to_remove.len(),
);
region.version_control.apply_edit(
Some(request.edit.clone()),
&[],
region.file_purger.clone(),
);
region.apply_published_edit(request.edit.clone(), &[]).await;
let index_build_file_metas = std::mem::take(&mut request.edit.files_to_add)
.into_iter()
+7 -5
View File
@@ -166,7 +166,8 @@ impl<S> RegionWorkerLoop<S> {
region_edit,
false,
tx,
),
)
.for_copy_region(),
)))
.await
.is_err()
@@ -217,7 +218,10 @@ impl<S> RegionWorkerLoop<S> {
});
}
pub(crate) fn handle_copy_region_from_finished(&mut self, request: CopyRegionFromFinished) {
pub(crate) async fn handle_copy_region_from_finished(
&mut self,
request: CopyRegionFromFinished,
) {
let region_id = request.region_id;
let sender = request.sender;
let region = match self.regions.writable_region(region_id) {
@@ -235,9 +239,7 @@ impl<S> RegionWorkerLoop<S> {
.map(|file_meta| file_meta.file_id)
.collect();
region
.version_control
.apply_edit(Some(request.edit), &[], region.file_purger.clone());
region.apply_published_edit(request.edit, &[]).await;
let _ = sender.send(Ok(MitoCopyRegionFromResponse { copied_file_ids }));
}
+3 -5
View File
@@ -513,11 +513,9 @@ impl<S: LogStore> RegionWorkerLoop<S> {
}
};
region.version_control.apply_edit(
Some(request.edit.clone()),
&request.memtables_to_remove,
region.file_purger.clone(),
);
region
.apply_published_edit(request.edit.clone(), &request.memtables_to_remove)
.await;
// The flush has committed its manifest. Count only its Parquet output, before
// WAL cleanup (which can fail after the commit).
+86 -55
View File
@@ -101,10 +101,12 @@ impl RegionEditQueue {
}
fn dequeue(&mut self) -> Option<RegionEditRequest> {
fn can_merge(request: &RegionEditRequest) -> bool {
if !matches!(request.kind, RegionEditKind::Import) {
return false;
}
fn mergeable_import(request: &RegionEditRequest) -> Option<bool> {
let external = match request.kind {
RegionEditKind::Import { external } => external,
#[cfg(feature = "enterprise")]
RegionEditKind::Compaction(_) => return None,
};
let edit = &request.edit;
// Only the `RegionEdit`:
// 1. contains the "raw" (file without a sequence) files to add,
@@ -115,7 +117,7 @@ impl RegionEditQueue {
// However, merging them means they will all share a same sequence, and if there are
// overlapping data in the files, the dedup is uncertain. This is a caution that must
// be noticed for editing region.
edit.files_to_add.iter().all(|f| f.sequence.is_none())
(edit.files_to_add.iter().all(|f| f.sequence.is_none())
&& edit.files_to_remove.is_empty()
&& edit.series_indexes_to_add.is_empty()
&& edit.series_indexes_to_remove.is_empty()
@@ -124,17 +126,19 @@ impl RegionEditQueue {
&& edit.flushed_entry_id.is_none()
&& edit.flushed_sequence.is_none()
&& edit.committed_sequence.is_none()
&& edit.wal_recovery == WalRecoveryEdit::default()
&& edit.wal_recovery == WalRecoveryEdit::default())
.then_some(external)
}
let mut merged = self.requests.pop_front()?;
if !can_merge(&merged) {
let Some(external) = mergeable_import(&merged) else {
return Some(merged);
}
};
// Merging must preserve the staging binding of every waiter.
// Merging must preserve the source and staging binding of every import.
while let Some(request) = self.requests.pop_front_if(|request| {
can_merge(request) && request.staging_partition_expr == merged.staging_partition_expr
mergeable_import(request) == Some(external)
&& request.staging_partition_expr == merged.staging_partition_expr
}) {
merged.edit.files_to_add.extend(request.edit.files_to_add);
merged.waiters.merge(request.waiters);
@@ -341,7 +345,8 @@ impl<S: LogStore> RegionWorkerLoop<S> {
impl<S: LogStore> RegionWorkerLoop<S> {
fn is_import_without_staging_binding(request: &RegionEditRequest) -> bool {
matches!(request.kind, RegionEditKind::Import) && request.staging_partition_expr.is_none()
matches!(request.kind, RegionEditKind::Import { .. })
&& request.staging_partition_expr.is_none()
}
/// Whether EnterStaging is pending in the worker, flush, or compaction queue.
@@ -451,9 +456,14 @@ impl<S: LogStore> RegionWorkerLoop<S> {
waiters.reply_with(|| RegionBusySnafu { region_id }.fail());
return RegionEditDispatch::Rejected;
}
if matches!(kind, RegionEditKind::Import)
&& let Err(error) = prepare_region_edit(&region, &mut edit)
{
let preparation = match kind {
RegionEditKind::Import { external } => {
prepare_region_edit(&region, &mut edit, external)
}
#[cfg(feature = "enterprise")]
RegionEditKind::Compaction(_) => Ok(()),
};
if let Err(error) = preparation {
let error = Arc::new(error);
waiters.reply_with(|| Err(error.clone()).context(EditRegionSnafu { region_id }));
return RegionEditDispatch::Rejected;
@@ -483,7 +493,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
// Updates manifest in background.
common_runtime::spawn_global(async move {
let result = match kind {
RegionEditKind::Import => edit_region(
RegionEditKind::Import { .. } => edit_region(
&region,
&mut edit,
cache_manager,
@@ -619,10 +629,12 @@ impl<S: LogStore> RegionWorkerLoop<S> {
});
edit.series_indexes_to_remove
.retain(|id| !manifest.series_indexes.contains_key(&id.file_id()));
region
.version_control
.apply_edit(Some(edit), &[], region.file_purger.clone());
} else {
region.apply_published_edit(edit, &[]).await;
}
region
.version_control
.apply_edit(Some(edit), &[], region.file_purger.clone());
}
if edit_result.update_region_state {
region.switch_state_to_writable(RegionLeaderState::Editing);
@@ -1012,7 +1024,11 @@ impl<S: LogStore> RegionWorkerLoop<S> {
}
}
fn prepare_region_edit(region: &MitoRegionRef, edit: &mut RegionEdit) -> Result<()> {
fn prepare_region_edit(
region: &MitoRegionRef,
edit: &mut RegionEdit,
external: bool,
) -> Result<()> {
let region_id = region.region_id;
region.version().options.validate_file_formats(
region_id,
@@ -1060,11 +1076,13 @@ fn prepare_region_edit(region: &MitoRegionRef, edit: &mut RegionEdit) -> Result<
);
for file in &edit.files_to_add {
if let Some(existing) = shared.get(&file.file_id) {
let existing = existing.meta_ref();
let mut imported = file.clone();
imported.sequence = existing.meta_ref().sequence;
imported.sequence = existing.sequence;
imported.preserve_row_sequence = false;
imported.dedup_marker_trusted = existing.dedup_marker_trusted;
snafu::ensure!(
&imported == existing.meta_ref(),
&imported == existing,
crate::error::InvalidRequestSnafu {
region_id,
reason: "Shared SST import conflicts with a visible reference",
@@ -1099,8 +1117,12 @@ fn prepare_region_edit(region: &MitoRegionRef, edit: &mut RegionEdit) -> Result<
NonZeroU64::new(sequence)
};
for file in &mut edit.files_to_add {
file.sequence = existing_sequence(file).or(sequence);
let existing_shared = shared.get(&file.file_id).map(|handle| handle.meta_ref());
file.sequence = existing_shared.and_then(|meta| meta.sequence).or(sequence);
file.preserve_row_sequence = false;
let trusted = !external && file.dedup_marker_trusted;
file.dedup_marker_trusted =
existing_shared.map_or(trusted, |meta| meta.dedup_marker_trusted);
}
Ok(())
}
@@ -1266,42 +1288,51 @@ mod tests {
use crate::test_util::{CreateRequestBuilder, TestEnv};
#[test]
fn test_edit_queue_preserves_staging_bindings() {
for (left, right, merge) in [
(None, None, true),
(Some("a"), Some("a"), true),
(None, Some("a"), false),
(Some("a"), None, false),
(Some("a"), Some("b"), false),
fn test_edit_queue_preserves_staging_bindings_and_import_source() {
for (left, right) in [
(None, None),
(Some("a"), Some("a")),
(None, Some("a")),
(Some("a"), None),
(Some("a"), Some("b")),
] {
let region_id = RegionId::new(1, 1);
let mut queue = RegionEditQueue::new(region_id);
let mut receivers = Vec::new();
for binding in [left, right] {
let (sender, receiver) = tokio::sync::oneshot::channel();
let mut request =
RegionEditRequest::new(region_id, RegionEdit::default(), false, sender);
request.staging_partition_expr = binding.map(str::to_string);
assert!(matches!(queue.enqueue(request), RegionEditDispatch::Queued));
receivers.push(receiver);
}
let first = queue.dequeue().unwrap();
assert_eq!(left, first.staging_partition_expr.as_deref());
first.waiters.reply_with(|| Ok(()));
assert!(receivers[0].try_recv().unwrap().is_ok());
if merge {
assert!(receivers[1].try_recv().unwrap().is_ok());
} else {
assert!(matches!(
receivers[1].try_recv(),
Err(tokio::sync::oneshot::error::TryRecvError::Empty)
));
let second = queue.dequeue().unwrap();
assert_eq!(right, second.staging_partition_expr.as_deref());
second.waiters.reply_with(|| Ok(()));
for (left_external, right_external) in
[(true, true), (false, false), (true, false), (false, true)]
{
let region_id = RegionId::new(1, 1);
let mut queue = RegionEditQueue::new(region_id);
let mut receivers = Vec::new();
for (binding, external) in [(left, left_external), (right, right_external)] {
let (sender, receiver) = tokio::sync::oneshot::channel();
let mut request =
RegionEditRequest::new(region_id, RegionEdit::default(), false, sender);
request.kind = RegionEditKind::Import { external };
request.staging_partition_expr = binding.map(str::to_string);
assert!(matches!(queue.enqueue(request), RegionEditDispatch::Queued));
receivers.push(receiver);
}
let first = queue.dequeue().unwrap();
assert_eq!(left, first.staging_partition_expr.as_deref());
assert!(
matches!(first.kind, RegionEditKind::Import { external } if external == left_external)
);
first.waiters.reply_with(|| Ok(()));
assert!(receivers[0].try_recv().unwrap().is_ok());
if left != right || left_external != right_external {
assert!(matches!(
receivers[1].try_recv(),
Err(tokio::sync::oneshot::error::TryRecvError::Empty)
));
let second = queue.dequeue().unwrap();
assert_eq!(right, second.staging_partition_expr.as_deref());
assert!(
matches!(second.kind, RegionEditKind::Import { external } if external == right_external)
);
second.waiters.reply_with(|| Ok(()));
}
assert!(receivers[1].try_recv().unwrap().is_ok());
assert!(queue.is_empty());
}
assert!(queue.is_empty());
}
}
@@ -118,9 +118,20 @@ fn is_replay(
&& !edit.files_to_remove.is_empty(),
StaleCompactionExecutionSnafu { region_id }
);
let matches =
|file: &FileMeta| manifest.files.get(&file.file_id).map(AsRef::as_ref) == Some(file);
if edit.files_to_remove.iter().all(matches) {
let matches_input = |input: &FileMeta| {
let Some(current) = manifest.files.get(&input.file_id) else {
return false;
};
if current.dedup_marker_trusted && !input.dedup_marker_trusted {
// An older compactor drops this field when it decodes the input snapshot.
let mut aligned = input.clone();
aligned.dedup_marker_trusted = true;
&aligned == current.as_ref()
} else {
input == current.as_ref()
}
};
if edit.files_to_remove.iter().all(matches_input) {
ensure!(
edit.files_to_add
.iter()
@@ -134,12 +145,14 @@ fn is_replay(
}
// With no durable receipt, only a still-visible, nonempty replacement proves success.
let matches_output =
|output: &FileMeta| manifest.files.get(&output.file_id).map(AsRef::as_ref) == Some(output);
ensure!(
edit.files_to_remove
.iter()
.all(|file| !manifest.files.contains_key(&file.file_id))
&& !edit.files_to_add.is_empty()
&& edit.files_to_add.iter().all(matches),
&& edit.files_to_add.iter().all(matches_output),
StaleCompactionExecutionSnafu { region_id }
);
Ok(true)
@@ -185,6 +198,7 @@ fn validate_files(
&& outputs.insert(file.file_id)
&& file.partition_expr.as_deref() == partition.as_ref()
&& file.preserve_row_sequence == trusted
&& !file.dedup_marker_trusted
&& file.sequence == sequence),
InvalidRequestSnafu {
region_id,
+1 -3
View File
@@ -240,9 +240,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
region.version_control.set_entry_id(flushed_entry_id);
}
let file_metas = edit.files_to_add.clone();
region
.version_control
.apply_edit(Some(edit), &[], region.file_purger.clone());
region.apply_published_edit(edit, &[]).await;
if self.config.index.build_mode == IndexBuildMode::Async && !file_metas.is_empty() {
self.handle_rebuild_index(
BuildIndexRequest {
+13
View File
@@ -305,6 +305,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 {
+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
+128 -2
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;
@@ -70,6 +70,61 @@ 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<Transformed<LogicalPlan>> {
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::<DefaultTableSource>() else {
return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate)));
};
let Some(provider) = source.table_provider.downcast_ref::<DummyTableProvider>() 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 !is_builtin_count_or_state(&function.func)
|| 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,
@@ -357,7 +412,13 @@ impl TreeNodeRewriter for ScanHintRewriter {
}
}
ScanHintRule::set_hints(node, self, fused_series_input)
let counted = ScanHintRule::set_metadata_aggr_hint(node)?;
let hinted = ScanHintRule::set_hints(counted.data, self, fused_series_input)?;
Ok(Transformed::new(
hinted.data,
counted.transformed || hinted.transformed,
hinted.tnr,
))
}
fn f_up(&mut self, node: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
@@ -738,6 +799,71 @@ mod test {
MetaRegionEngine, mock_table_provider, mock_table_provider_with_tsid,
};
#[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(
region_id,
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])
.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::<Expr>::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::<Expr>::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)));
+12 -2
View File
@@ -53,6 +53,7 @@ use crate::dummy_catalog::DummyTableProvider;
/// A mock region engine that can be used for testing the optimizer.
pub(crate) struct MetaRegionEngine {
metadatas: HashMap<RegionId, RegionMetadataRef>,
name: &'static str,
}
impl MetaRegionEngine {
@@ -61,14 +62,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(
+81 -1
View File
@@ -335,6 +335,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<usize>,
/// Whether to yield an empty batch to distinguish partition ranges.
pub distinguish_partition_range: bool,
@@ -370,6 +374,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<usize>) -> Self {
self.exact_num_rows = rows;
self
}
/// Returns the prepared exact count after all static scan predicates.
pub fn exact_num_rows(&self) -> Option<usize> {
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<Vec<PartitionRange>>, append_mode: bool, total_rows: usize) -> Self {
Self {
@@ -377,6 +397,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,
@@ -388,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 {
@@ -457,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>,
@@ -1026,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};
+3
View File
@@ -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<Vec<usize>>,
+37 -10
View File
@@ -631,11 +631,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)
@@ -662,11 +658,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 => {
@@ -797,6 +789,16 @@ fn date_bin_range(
}
}
/// 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<TimestampRange> {
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),
@@ -1185,6 +1187,31 @@ 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:?}");
}
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]
+17 -11
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);
}
@@ -1001,14 +1001,18 @@ impl ExecutionPlan for RegionScanExec {
_input_stats: &[Arc<Statistics>],
args: &StatisticsArgs,
) -> DfResult<Arc<Statistics>> {
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
@@ -1028,7 +1032,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,
}
@@ -1866,10 +1870,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);
@@ -1878,7 +1883,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(),
+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
+1
View File
@@ -4965,6 +4965,7 @@ scan_memory_on_exhausted = "fail"
min_compaction_interval = "0s"
schedule_compaction_after_edit = true
default_flat_format = true
experimental_metadata_aggr = false
[region_engine.mito.index]
aux_path = ""
+1
View File
@@ -28,6 +28,7 @@ mod flow_ddl_event;
mod gc_event;
mod json2;
mod jsonbench;
mod metadata_aggr;
#[macro_use]
mod sql;
#[macro_use]
+150
View File
@@ -0,0 +1,150 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_query::{Output, OutputData};
use common_recordbatch::RecordBatches;
use datatypes::arrow::array::Int64Array;
use frontend::instance::Instance;
use mito2::config::MitoConfig;
use servers::query_handler::sql::SqlQueryHandler;
use session::context::QueryContext;
use tests_integration::cluster::GreptimeDbClusterBuilder;
use tests_integration::standalone::GreptimeDbStandaloneBuilder;
const COUNT_SQL: &str = "SELECT count(*) FROM metadata_count";
#[rstest::rstest]
#[case::enabled(true)]
#[case::disabled(false)]
#[tokio::test(flavor = "multi_thread")]
async fn test_metadata_count_non_append(#[case] enabled: bool) {
common_telemetry::init_default_ut_logging();
let standalone = GreptimeDbStandaloneBuilder::new("metadata_count_non_append")
.with_mito_config(MitoConfig {
experimental_metadata_aggr: enabled,
schedule_compaction_after_edit: false,
..Default::default()
})
.build()
.await;
let frontend = standalone.fe_instance();
execute_sql(
frontend,
"CREATE TABLE metadata_count (
host STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, v BIGINT
) ENGINE=mito WITH (append_mode = 'false')",
)
.await;
execute_sql(
frontend,
"INSERT INTO metadata_count VALUES ('a', 1000, 1), ('a', 2000, 2), ('b', 1000, 3)",
)
.await;
execute_sql(frontend, "ADMIN FLUSH_TABLE('metadata_count')").await;
// The region has one SST and no mutable rows. Every row can be counted
// from metadata, but only when the flag is enabled.
assert_count_and_scan(frontend, 3, !enabled).await;
// A tombstone overlaps one of the settled rows. COUNT must fall back to
// the ordinary scan (with either setting) to reconcile the deletion.
execute_sql(
frontend,
"DELETE FROM metadata_count WHERE host = 'a' AND ts = 1000",
)
.await;
assert_count_and_scan(frontend, 2, true).await;
}
#[rstest::rstest]
#[case::enabled(true)]
#[case::disabled(false)]
#[tokio::test(flavor = "multi_thread")]
async fn test_metadata_count_distributed(#[case] enabled: bool) {
let cluster = GreptimeDbClusterBuilder::new("metadata_count_distributed")
.await
.with_datanodes(2)
.with_mito_config(MitoConfig {
experimental_metadata_aggr: enabled,
..Default::default()
})
.build(false)
.await;
let frontend = cluster.fe_instance();
execute_sql(
frontend,
"CREATE TABLE metadata_count (
host STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, v BIGINT
) PARTITION ON COLUMNS (host) (host < 'm', host >= 'm')
ENGINE=mito WITH (append_mode = 'false')",
)
.await;
execute_sql(
frontend,
"INSERT INTO metadata_count VALUES
('a', 1000, 1), ('a', 2000, 2), ('z', 1000, 3), ('z', 2000, 4)",
)
.await;
execute_sql(frontend, "ADMIN FLUSH_TABLE('metadata_count')").await;
assert_count_and_scan(frontend, 4, !enabled).await;
}
async fn execute_sql(frontend: &Instance, sql: &str) -> Output {
SqlQueryHandler::do_query(frontend, sql, QueryContext::arc())
.await
.remove(0)
.unwrap_or_else(|err| panic!("{sql}: {err}"))
}
async fn assert_count_and_scan(frontend: &Instance, expected: i64, expect_scan: bool) {
let output = execute_sql(frontend, COUNT_SQL).await;
let batches = match output.data {
OutputData::RecordBatches(batches) => batches,
OutputData::Stream(stream) => RecordBatches::try_collect(stream).await.unwrap(),
OutputData::AffectedRows(rows) => {
panic!("expected a COUNT result, got {rows} affected rows")
}
};
let counts = batches
.iter()
.flat_map(|batch| {
batch
.column(0)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
.iter()
})
.collect::<Vec<_>>();
assert_eq!(counts, vec![Some(expected)]);
// ANALYZE includes the actual region plan below the frontend MergeScan.
let plan = execute_sql(frontend, &format!("EXPLAIN ANALYZE {COUNT_SQL}"))
.await
.data
.pretty_print()
.await;
assert_eq!(
plan.contains("SeqScan:"),
expect_scan,
"unexpected region plan:\n{plan}"
);
if !expect_scan {
assert!(
plan.contains("PlaceholderRowExec"),
"expected the region scan to be replaced by a literal projection:\n{plan}"
);
}
}
@@ -0,0 +1,146 @@
-- Regression coverage for non-append COUNT with metadata aggregation off (the default).
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
@@ -0,0 +1,28 @@
-- Regression coverage for non-append COUNT with metadata aggregation off (the default).
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;
@@ -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,17 @@
SELECT count(*) AS total FROM t_metadata_count_footer;
+-------+
| total |
+-------+
| 3 |
+-------+
SELECT host, v FROM t_metadata_count_footer ORDER BY host, ts;
+------+---+
| host | v |
+------+---+
| a | 3 |
| a | 2 |
| b | 4 |
+------+---+
@@ -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;