refactor(mito2): remove shared SST compaction (#10934)

refactor(mito2)!: remove shared SST compaction

Remove the cross-region shared SST compaction mechanism from OSS:

- Delete the table-compaction publication kernel, the multi-region
  compaction executor, and the dedicated upload/metadata budgets.
- Restore L0/L1-only SST storage and remove shared-level handling from
  pickers, compaction, COPY, purging, and manifest edits.
- Restore GC behavior from before shared SST: no protection hook lookup,
  no post-scan publication recheck, and dropped-region unknown objects are
  reclaimed immediately.
- Remove the prototype manifest task-state guard and move the ordinary
  L0/L1 manifest fixtures to tests/compatibility/manifest/region_edit/.

Ordinary region compaction, ADMIN COMPACT_TABLE, COPY, repartition file
references, and the generic SST write guard remain unchanged.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
This commit is contained in:
Lei, HUANG authored and GitHub committed 2026-12-04 10:03:54 +00:00
1 parent 39c6d4fd89
commit 4b205bc0f0
60 files changed
+204 -10266

No files matched your search

-11
View File
@@ -26,17 +26,6 @@ includes = [
"src/sql/src/parsers/create_parser/trigger.rs",
"src/sql/src/parsers/show_parser/trigger.rs",
"src/mito2/src/extension.rs",
"src/mito2/src/engine/table_compaction.rs",
"src/mito2/src/engine/table_compaction/output.rs",
"src/mito2/src/engine/table_compaction/tests.rs",
"src/mito2/src/worker/handle_table_compaction.rs",
"src/mito2/src/compaction/multi_region.rs",
"src/mito2/src/compaction/multi_region/source.rs",
"src/mito2/src/compaction/multi_region/memory.rs",
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
"src/mito2/src/sst/upload/buffered.rs",
"src/common/function/src/admin/purge_table.rs",
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
"src/common/meta/src/ddl/purge_dropped_table.rs",
-11
View File
@@ -42,17 +42,6 @@ excludes = [
"src/sql/src/parsers/create_parser/trigger.rs",
"src/sql/src/parsers/show_parser/trigger.rs",
"src/mito2/src/extension.rs",
"src/mito2/src/engine/table_compaction.rs",
"src/mito2/src/engine/table_compaction/output.rs",
"src/mito2/src/engine/table_compaction/tests.rs",
"src/mito2/src/worker/handle_table_compaction.rs",
"src/mito2/src/compaction/multi_region.rs",
"src/mito2/src/compaction/multi_region/source.rs",
"src/mito2/src/compaction/multi_region/memory.rs",
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
"src/mito2/src/sst/upload/buffered.rs",
"src/common/function/src/admin/purge_table.rs",
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
"src/common/meta/src/ddl/purge_dropped_table.rs",
+2 -2
View File
@@ -157,10 +157,10 @@ impl SstReplaceCommand {
if old_file.format != FileFormat::Parquet
|| old_file.region_id != region_id
|| old_file.level == mito2::sst::file::LEVEL_SHARED
|| old_file.level > 1
{
return error::IllegalConfigSnafu {
msg: format!("file {file_id} must be a locally owned, unshared Parquet SST"),
msg: format!("file {file_id} must be a locally owned L0/L1 Parquet SST"),
}
.fail();
}
+4 -12
View File
@@ -24,8 +24,6 @@ snapshot isolation). It implements the `RegionEngine` trait from `store-api`.
| `memtable` | `src/mito2/src/memtable/` | In-memory write buffers (time-series / bulk / partition) |
| `flush` | `src/mito2/src/flush.rs` | `FlushScheduler`, `WriteBufferManager`, memtable → SST |
| `compaction` | `src/mito2/src/compaction/` | Compaction scheduler (`scheduler.rs` + `scheduler/`), TWCS picker, strict-window manual picker, compactor, memory control |
| `compaction/multi_region` | `src/mito2/src/compaction/multi_region.rs` | Enterprise lossless routing by a captured table partition rule; selected SSTs to per-region outputs, without manifest publication |
| `engine/table_compaction` | `src/mito2/src/engine/table_compaction.rs` | Enterprise conditional publication of table-compaction results: shared-input snapshot, verified-output checks, and the manifest-locked swap of shared inputs for L0 outputs |
| `access_layer` | `src/mito2/src/access_layer.rs` | SST read/write over the object store |
| `sst` | `src/mito2/src/sst/` | Parquet format, file metadata, index layout |
| `series_index` | `src/mito2/src/series_index/` | Native series and samples codecs, exact-key discovery and manifest-backed series index maintenance |
@@ -60,10 +58,6 @@ immutable `Version` (`region/version.rs`) → scans memtables and Parquet SSTs
(`sst/parquet.rs`) → merges (`read/`) and dedups by sequence → projected,
filtered `RecordBatch` stream.
Compaction SST scans share a read path. Multi-region compaction retains raw
versions and routes each row before merging. Sparse routing temporarily
materializes only the columns used by the partition rule.
Internal series merges use the query runtime pool forwarded through
`QueryScanContext`; reader and output-batch accounting uses the separate scan
memory tracker. Direct scanner callers default to an unbounded operator pool.
@@ -90,9 +84,8 @@ pending. DDL cancellation retains its existing scheduling fence and priority.
- **Manifest format** (`manifest/action.rs`): affects crash recovery and
follower replay. Keep it backward compatible. Compaction task state does not
belong in the manifest; publication uses ordinary file edits after locked input
checks. Shared SSTs require Enterprise capability. Compatibility fixtures:
`tests/compatibility/manifest/table_compaction/` and
belong in the manifest. Compatibility fixtures:
`tests/compatibility/manifest/region_edit/` and
`tests/compatibility/manifest/pending_tails/`.
- **SST layout** (`sst/`): readers must stay compatible with existing files.
[Narthex samples](../../docs/formats/mito-samples.md) use series blocks or
@@ -238,9 +231,8 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
- Loaded regions have resident compaction state, including `Idle` and handed-off
DDLs. Publish create/open/catchup results through the worker's `register_region`;
only close/drop unregisters them. See `compaction/scheduler/state.rs`.
- Explicit truncate retires shared references too (`worker/handle_truncate.rs`):
`All` removes all data; `ByTimeRanges` removes fully contained files. Other
regions/readers still protect the shared objects. Stale compaction results must
- Explicit truncate (`worker/handle_truncate.rs`): `All` removes all data;
`ByTimeRanges` removes fully contained files. Stale compaction results must
not reinstate truncated inputs.
- Manifest and runtime file views share immutable `FileMetaRef` values. The engine-local
metadata interner compares complete metadata before sharing; file identity alone is insufficient.
+1 -1
View File
@@ -9,7 +9,7 @@ default = []
test = ["common-test-util", "rstest", "rstest_reuse", "rskafka"]
testing = ["test"]
test-shared-fs-region-migration = []
enterprise = ["datatypes/enterprise", "tokio-util/rt"]
enterprise = ["datatypes/enterprise"]
hdfs-object-store = ["object-store/hdfs-object-store"]
[lints]
+3 -53
View File
@@ -145,7 +145,6 @@ pub struct AccessLayer {
puffin_manager_factory: PuffinManagerFactory,
/// Intermediate manager for inverted index.
intermediate_manager: IntermediateManager,
file_protection: Option<crate::engine::region_hook::RegionHookRef>,
}
impl std::fmt::Debug for AccessLayer {
@@ -171,26 +170,6 @@ impl AccessLayer {
object_store,
puffin_manager_factory,
intermediate_manager,
file_protection: None,
}
}
/// Attaches the engine's deletion-time protection provider for local purging.
pub(crate) fn with_file_protection(
mut self,
hook: Option<crate::engine::region_hook::RegionHookRef>,
) -> Self {
self.file_protection = hook;
self
}
pub(crate) async fn is_file_protected(&self, file: RegionFileId) -> crate::error::Result<bool> {
match &self.file_protection {
Some(hook) => Ok(hook
.protected_sst_files(self, &[file])
.await?
.contains(&file)),
None => Ok(false),
}
}
@@ -405,12 +384,6 @@ impl AccessLayer {
let context = context.unwrap_or_default();
let override_sequence = request.sequence_override();
if request.sst_write_format == FormatType::Narthex {
if context.limits.is_some() {
return crate::error::UnsupportedOperationSnafu {
err_msg: "Narthex table compaction is unsupported",
}
.fail();
}
return crate::sst::narthex::write_samples(
self,
request,
@@ -420,16 +393,13 @@ impl AccessLayer {
)
.await;
}
let limits = context.limits;
let guard = context.guard.clone();
let cancellation = context.cancellation.clone();
let op_type = request.op_type;
let region_id = request.metadata.region_id;
let region_metadata = request.metadata.clone();
let cache_manager = request.cache_manager.clone();
let sst_info = if let Some(write_cache) = cache_manager.write_cache()
&& limits.is_none()
{
let sst_info = if let Some(write_cache) = cache_manager.write_cache() {
// Write to the write cache.
write_cache
.write_and_upload_sst_with_context(
@@ -447,17 +417,9 @@ impl AccessLayer {
)
.await?
} else {
// The write cache does not enforce SstWriteLimits, so bounded writes
// bypass it.
let store = self.object_store.clone();
let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
let puffin_factory = self.puffin_manager_factory.clone();
#[cfg(feature = "enterprise")]
let puffin_factory = if let Some(limits) = limits {
puffin_factory.with_upload_limits(limits.upload_limits)
} else {
puffin_factory
};
let indexer_builder = IndexerBuilderImpl {
index_build_inputs: request.index_build_inputs,
build_type: request.op_type.into(),
@@ -486,20 +448,9 @@ impl AccessLayer {
)
.await
.with_file_cleaner(cleaner)
.with_write_concurrency(if limits.is_some() {
1
} else {
crate::sst::DEFAULT_WRITE_CONCURRENCY
})
.with_write_concurrency(crate::sst::DEFAULT_WRITE_CONCURRENCY)
.with_write_guard(guard)
.with_cancellation(cancellation)
.with_memory_limits(limits);
#[cfg(feature = "enterprise")]
let writer = if let Some(limits) = limits {
writer.with_upload_limits(limits.upload_limits)
} else {
writer
};
.with_cancellation(cancellation);
let mut writer = writer;
match request.sst_write_format {
FormatType::PrimaryKey => {
@@ -1263,7 +1214,6 @@ mod tests {
SstWriteContext {
guard: Some(Arc::new(uncommitted.clone())),
cancellation: Some(cancellation),
..Default::default()
},
)
.await;
-2
View File
@@ -17,8 +17,6 @@ pub mod compactor;
mod json2;
mod last_non_null;
pub mod memory_manager;
#[cfg(feature = "enterprise")]
pub mod multi_region;
mod overlap;
pub mod picker;
mod reader;
+2 -32
View File
@@ -27,7 +27,7 @@ use itertools::Itertools;
use object_store::manager::ObjectStoreManagerRef;
use partition::expr::PartitionExpr;
use serde::{Deserialize, Serialize};
use snafu::{OptionExt, ResultExt, ensure};
use snafu::{OptionExt, ResultExt};
use store_api::ManifestVersion;
use store_api::metadata::RegionMetadataRef;
use store_api::region_request::PathType;
@@ -56,7 +56,7 @@ use crate::region::{ManifestContext, RegionLeaderState, RegionRoleState};
use crate::schedule::scheduler::LocalScheduler;
use crate::sst::FormatType;
use crate::sst::file::{
self, FileFormat, FileHandle, FileMeta, RegionFileId, RowSequenceProvenance, UncommittedSsts,
FileFormat, FileHandle, FileMeta, RegionFileId, RowSequenceProvenance, UncommittedSsts,
};
use crate::sst::file_metadata::{FileMetadataInterner, FileMetadataInternerRef};
use crate::sst::file_purger::LocalFilePurger;
@@ -755,21 +755,6 @@ fn reusable_index_inputs(
.flat_map(|output| output.inputs.iter())
}
fn validate_region_compaction_output(region_id: RegionId, output: &CompactionOutput) -> Result<()> {
ensure!(
output.output_level < file::LEVEL_SHARED
&& output
.inputs
.iter()
.all(|file| file.level() < file::LEVEL_SHARED),
error::InvalidRequestSnafu {
region_id,
reason: "Region compaction cannot consume or produce shared SSTs",
}
);
Ok(())
}
#[async_trait::async_trait]
impl SstMerger for DefaultSstMerger {
async fn merge_single_output(
@@ -810,7 +795,6 @@ impl DefaultSstMerger {
cancellation: CancellationToken,
) -> Result<(Vec<FileMeta>, Vec<SstInfo>)> {
let region_id = context.region_id;
validate_region_compaction_output(region_id, &output)?;
let index_options = context.version_options.index_options.clone();
let append_mode = context.version_options.append_mode;
let merge_mode = context.version_options.merge_mode();
@@ -925,7 +909,6 @@ impl DefaultSstMerger {
SstWriteContext {
guard: Some(Arc::new(uncommitted.clone())),
cancellation: Some(cancellation),
..Default::default()
},
)
.await?;
@@ -1106,19 +1089,6 @@ where
compaction_region: &CompactionRegion,
mut picker_output: PickerOutput,
) -> Result<MergeOutput> {
for output in &picker_output.outputs {
validate_region_compaction_output(compaction_region.region_id, output)?;
}
ensure!(
picker_output
.expired_ssts
.iter()
.all(|file| file.level() < file::LEVEL_SHARED),
error::InvalidRequestSnafu {
region_id: compaction_region.region_id,
reason: "Region compaction cannot expire shared SSTs",
}
);
let internal_parallelism = compaction_region.max_parallelism.max(1);
let compaction_time_window = picker_output.time_window_size;
let region_id = compaction_region.region_id;
+2 -5
View File
@@ -24,7 +24,7 @@ use crate::compaction::overlap::FileOverlapIndex;
use crate::compaction::picker::{Picker, PickerOutput};
use crate::compaction::twcs::TwcsPicker;
use crate::error::{JoinSnafu, Result};
use crate::sst::file::{self, FileHandle, RegionFileId};
use crate::sst::file::{FileHandle, RegionFileId};
/// Picker for [`MergeMode::LastNonNull`](crate::region::options::MergeMode).
///
@@ -167,10 +167,7 @@ fn build_closed_outputs(
};
let output = expand_closure(output, &mut seeds, &seed_by_file, &mut remaining);
// Defer the entire closure rather than truncate it around busy files.
if !output
.inputs
.iter()
.any(|file| file.compacting() || file.level() == file::LEVEL_SHARED)
if !output.inputs.iter().any(|file| file.compacting())
&& inputs_precede_memtables(&output.inputs, limits.memtable_min_sequence)
{
outputs.push(output);
-268
View File
@@ -1,268 +0,0 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
//! Lossless multi-region SST compaction using a captured table partition rule.
//!
//! The caller selects and pins the inputs (for example, from LEVEL_SHARED), and
//! supplies their effective metadata in every target. This primitive deliberately
//! does not select files, change existing persisted levels, publish manifests, or
//! fold row versions. Output protection and eventual publication belong to its
//! caller; see [MultiRegionCompactionOutput::files] for the output level convention.
mod memory;
mod source;
#[cfg(test)]
mod tests;
mod worker;
mod writer;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use common_time::Timestamp;
use partition::PartitionRuleRef;
use snafu::{OptionExt, ensure};
use store_api::metadata::RegionMetadataRef;
use store_api::storage::RegionId;
use tokio_util::sync::CancellationToken;
use crate::access_layer::AccessLayerRef;
use crate::cache::CacheManagerRef;
use crate::config::MitoConfig;
use crate::error::CompactionCancelledSnafu;
use crate::error::{InvalidMultiRegionCompactionSnafu, Result};
use crate::region::options::RegionOptions;
use crate::sst::file::{FileMeta, RegionFileId};
use crate::sst::index::handler::IndexKindProviderRef;
use crate::sst::index::registry::IndexRegistry;
use crate::sst::parquet::SstInfo;
use crate::sst::parquet::writer::SstWriteGuard;
/// A target partition and the source versions currently visible in its sequence domain.
#[derive(Debug, Clone)]
pub struct MultiRegionTarget {
pub metadata: RegionMetadataRef,
pub options: RegionOptions,
/// All selected sources, with the sequence metadata used by this target's reader.
pub inputs: HashMap<RegionFileId, FileMeta>,
}
/// Immutable inputs, routing snapshot and execution limits for one compaction.
pub struct MultiRegionCompactionPlan {
/// Captured table routing rule; the executor never fetches mutable routing metadata.
pub partition_rule: PartitionRuleRef,
/// Unique sources. The caller retains their GC protection.
pub sources: Vec<FileMeta>,
/// Metadata and routing must belong to the same physical-table snapshot.
pub targets: BTreeMap<RegionId, MultiRegionTarget>,
/// Total working-set admission budget for computation and all resident uploads.
/// Upload chunks follow the destination backend's limits independently of the Arrow
/// batch limit. The executor reserves uploads before sizing the compute buffers and
/// checks the estimated working set before creating outputs. This is not a process RSS limit.
pub memory_limit: usize,
/// Soft size limit, in bytes, of one output SST. A file rolls over at the next
/// series boundary after it is exceeded, so a single series may stay in one file.
pub max_output_file_size: usize,
/// Aligned start of the only task window, in seconds since the epoch.
pub window_start: i64,
/// Width of the only task window in seconds; the window is
/// `[window_start, window_start + window_seconds)`.
pub window_seconds: i64,
}
/// Shared storage services and attempt-owned output resources.
pub struct MultiRegionCompactionContext {
/// Optional enterprise index implementation. Each routed output builds its own state.
pub index_kind_provider: Option<IndexKindProviderRef>,
pub access_layer: AccessLayerRef,
pub cache: CacheManagerRef,
pub config: Arc<MitoConfig>,
pub protection: Arc<dyn SstWriteGuard>,
pub cancellation: CancellationToken,
}
/// Source I/O and lossless output accounting, excluding footer and query reads.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MultiRegionCompactionStats {
pub source_files: u64,
pub source_rows: u64,
/// Row-group page bytes fetched from object storage, excluding footer traffic and retries.
pub source_store_page_bytes: u64,
pub output_rows: u64,
pub output_bytes: u64,
/// Admission estimate for reader pages, encoders, indexes, uploads, and finish workspace.
pub estimated_memory_bytes: u64,
/// Peak retained equal-key group storage (including shared buffer capacities).
pub peak_group_bytes: u64,
}
/// Complete per-target outputs, including explicit empty partitions.
pub struct MultiRegionCompactionOutput {
/// Output files, already assigned to region-local L0.
///
/// Window merging and semantic folding stay with ordinary region compaction,
/// which runs after publication; the caller does not adjust the level.
pub files: BTreeMap<RegionId, Vec<FileMeta>>,
/// Complete footer/index statistics for target hook delivery; not fabricated from FileMeta.
pub sst_infos: BTreeMap<RegionId, Vec<SstInfo>>,
pub stats: MultiRegionCompactionStats,
}
#[derive(Default)]
struct SourceCounters {
files: AtomicU64,
rows: AtomicU64,
store_page_bytes: AtomicU64,
}
/// Computes a complete result or an error. Any already-written outputs remain
/// owned by the attempt's durable protection; this function never purges sources.
/// Outputs that legacy reading would reinterpret as newly admitted versions are rejected.
pub async fn compact_regions(
plan: MultiRegionCompactionPlan,
context: MultiRegionCompactionContext,
) -> Result<MultiRegionCompactionOutput> {
let metadata = validate_plan(&plan)?;
// Invalid registrations still fail, but unavailable sketches only warn so
// compaction can continue after a downgrade.
let registry =
IndexRegistry::from_config(&context.config, context.index_kind_provider.clone())?;
for target in plan.targets.values() {
registry.warn_missing_compaction_handlers(
&target.metadata,
plan.sources.iter().chain(target.inputs.values()),
);
}
if context.cancellation.is_cancelled() {
return CompactionCancelledSnafu.fail();
}
let cancellation = context.cancellation.clone();
let execution = async move {
let counters = Arc::new(SourceCounters::default());
let source =
source::SharedSource::build(&plan, &context, metadata, counters.clone()).await?;
worker::execute(plan, context, source, counters).await
};
tokio::select! {
biased;
_ = cancellation.cancelled() => crate::error::CompactionCancelledSnafu.fail(),
result = execution => result,
}
}
fn validate_plan(plan: &MultiRegionCompactionPlan) -> Result<RegionMetadataRef> {
ensure!(
plan.targets
.values()
.all(|target| target.options.sst_format != Some(crate::sst::FormatType::Narthex)),
InvalidMultiRegionCompactionSnafu {
reason: "Table compaction does not support Narthex storage"
}
);
ensure!(
!plan.sources.is_empty(),
InvalidMultiRegionCompactionSnafu {
reason: "sources must not be empty"
}
);
ensure!(
plan.memory_limit >= 1024 * 1024,
InvalidMultiRegionCompactionSnafu {
reason: "memory_limit must be at least 1 MiB"
}
);
ensure!(
plan.max_output_file_size > 0,
InvalidMultiRegionCompactionSnafu {
reason: "max_output_file_size must be greater than 0"
}
);
ensure!(
plan.window_seconds > 0,
InvalidMultiRegionCompactionSnafu {
reason: "window_seconds must be greater than 0"
}
);
let control_bytes = plan.targets.len().saturating_mul(8 * 1024).saturating_add(
plan.sources
.len()
.saturating_mul(std::mem::size_of::<FileMeta>()),
);
ensure!(
control_bytes <= plan.memory_limit,
crate::error::MultiRegionCompactionResourceSnafu {
reason: "Input/target control state exceeds the task budget",
}
);
let first = plan
.targets
.values()
.next()
.context(InvalidMultiRegionCompactionSnafu {
reason: "No routing targets",
})?;
let window_end = plan.window_start.checked_add(plan.window_seconds).context(
InvalidMultiRegionCompactionSnafu {
reason: "Task window overflow",
},
)?;
ensure!(
plan.window_start.rem_euclid(plan.window_seconds) == 0,
InvalidMultiRegionCompactionSnafu {
reason: "Task window start is not aligned"
}
);
let start = Timestamp::new_second(plan.window_start);
let end = Timestamp::new_second(window_end);
let mut sources = HashSet::new();
for file in &plan.sources {
ensure!(
file.time_range.0 >= start
&& file.time_range.1 < end
&& file.time_range.0 <= file.time_range.1,
InvalidMultiRegionCompactionSnafu {
reason: "Source is not wholly inside the task window"
}
);
ensure!(
file.region_id.table_id() == first.metadata.region_id.table_id()
&& sources.insert(file.file_id()),
InvalidMultiRegionCompactionSnafu {
reason: "Expected unique source files from one physical table"
}
);
}
for (id, target) in &plan.targets {
target.options.validate()?;
ensure!(
*id == target.metadata.region_id
&& id.table_id() == first.metadata.region_id.table_id()
&& target.metadata.column_metadatas == first.metadata.column_metadatas
&& target.metadata.primary_key == first.metadata.primary_key
&& target.metadata.primary_key_encoding == first.metadata.primary_key_encoding,
InvalidMultiRegionCompactionSnafu {
reason: "Target schemas are not a consistent physical-table snapshot"
}
);
ensure!(
target.inputs.len() == sources.len()
&& target
.inputs
.iter()
.all(|(key, file)| *key == file.file_id() && sources.contains(key)),
InvalidMultiRegionCompactionSnafu {
reason: "Every target must describe the effective metadata of every selected source"
}
);
}
Ok(first.metadata.clone())
}
@@ -1,497 +0,0 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
use std::sync::Arc;
use api::v1::SemanticType;
use datatypes::arrow::datatypes::SchemaRef;
use datatypes::schema::{ColumnEncoding, FulltextBackend};
use index::fulltext_index::create::TantivyFulltextIndexCreator;
use object_store::ObjectStore;
use parquet::arrow::ArrowSchemaConverter;
use parquet::file::metadata::ParquetMetaData;
use snafu::{OptionExt, ResultExt, ensure};
use crate::compaction::multi_region::{MultiRegionCompactionPlan, MultiRegionTarget};
use crate::config::{FulltextIndexConfig, MitoConfig};
use crate::error::{IndexOptionsSnafu, MultiRegionCompactionResourceSnafu, Result};
use crate::sst::DEFAULT_WRITE_BUFFER_SIZE;
use crate::sst::parquet::max_row_group_value_bytes;
use crate::sst::parquet::writer::SstWriteLimits;
use crate::sst::upload::buffered::UploadLimits;
pub(crate) const BATCH_SIZE: usize = 64;
/// Cap on the rows of one output row group.
///
/// Every resident target admits an encoder sized by this count, while readers
/// and index row ids only require uniform groups except for the last one.
/// Ordinary compaction forwards the region option uncapped; this executor caps
/// it so the working set stays inside the task budget.
pub(crate) const MAX_ROW_GROUP_SIZE: usize = 1024;
/// Admission includes every resident writer, not just concurrently polled tasks.
/// Codec/index thresholds are estimates; Arrow batches and output metadata have
/// separate runtime checks. Neither estimate nor buffer accounting measures RSS.
#[derive(Clone)]
pub(crate) struct MemoryLimits {
pub(crate) arrow_batch_bytes: usize,
pub(crate) group: usize,
pub(crate) index: usize,
upload_reserved_bytes: usize,
compute_budget: usize,
/// Reuses index allocation only when the optional working set fits admission.
pub(crate) extension_index_memory_limit: Option<usize>,
pub(crate) writer: SstWriteLimits,
pub(crate) estimated: u64,
}
impl MemoryLimits {
pub(crate) fn new(
plan: &MultiRegionCompactionPlan,
schema: &SchemaRef,
upload: UploadBudget,
) -> Result<Self> {
let schema = crate::sst::maybe_wrap_schema(schema)?;
let columns = ArrowSchemaConverter::new()
.convert(&schema)
.context(crate::error::WriteParquetSnafu)?
.num_columns();
let targets = plan.targets.len();
let batch_share = 64usize.saturating_mul(
plan.sources
.len()
.saturating_add(targets)
.saturating_add(BATCH_SIZE + 4),
);
let arrow_batch_bytes = upload.compute_bytes / batch_share;
ensure!(
arrow_batch_bytes > 0,
MultiRegionCompactionResourceSnafu {
reason: "No Arrow batch budget after reserving upload memory",
}
);
Ok(Self {
arrow_batch_bytes,
group: upload.compute_bytes / 16,
index: upload.compute_bytes / targets / 64,
upload_reserved_bytes: upload.reserved_bytes,
compute_budget: upload.compute_bytes,
extension_index_memory_limit: None,
writer: SstWriteLimits {
// Parquet 59 preallocates a 1 MiB bit writer for each of the
// timestamp/sequence delta encoders. Dictionary interner tables
// also have a nonzero minimum, independent of batch row count.
working_bytes: (2usize << 20)
.saturating_add(columns.saturating_mul(128 << 10))
.saturating_add(arrow_batch_bytes * (MAX_ROW_GROUP_SIZE / BATCH_SIZE)),
metadata_bytes: upload.compute_bytes / targets / 8,
upload_limits: upload.limits,
},
estimated: 0,
})
}
pub(crate) fn admit(
&mut self,
plan: &MultiRegionCompactionPlan,
config: &MitoConfig,
footers: &[Arc<ParquetMetaData>],
extension_targets: usize,
) -> Result<()> {
let mut extra_delta = 0;
for target in plan.targets.values() {
extra_delta = extra_delta.max(extra_delta_encoder_bytes(target)?);
}
self.writer.working_bytes = self.writer.working_bytes.saturating_add(extra_delta);
let estimate = self.estimate_compute_bytes(plan, config, footers)?;
let upload = self.writer.upload_limits;
ensure!(
estimate <= self.compute_budget as u64,
MultiRegionCompactionResourceSnafu {
reason: format!(
"Reader/writer/index minimum working set needs {estimate} bytes, compute budget is {} ({} bytes reserved for {}-byte upload chunks out of {} total)",
self.compute_budget,
self.upload_reserved_bytes,
upload.chunk_bytes,
plan.memory_limit,
),
}
);
// Optional indexes must not turn an admitted data compaction into a
// resource failure. Reserve all resident target states together or skip.
let admission =
admit_extension_indexes(estimate, self.compute_budget, self.index, extension_targets);
self.extension_index_memory_limit = admission.limit;
self.estimated = admission.estimated + self.upload_reserved_bytes as u64;
common_telemetry::debug!(
memory_limit = plan.memory_limit,
compute_budget = self.compute_budget,
arrow_batch_bytes = self.arrow_batch_bytes,
upload_chunk_bytes = upload.chunk_bytes,
upload_max_object_bytes = upload.max_object_bytes,
upload_reserved_bytes = self.upload_reserved_bytes,
estimated_memory_bytes = self.estimated,
"Admitted multi-region compaction working set",
);
Ok(())
}
/// Estimates the compute working set to compare against the compute budget.
fn estimate_compute_bytes(
&self,
plan: &MultiRegionCompactionPlan,
config: &MitoConfig,
footers: &[Arc<ParquetMetaData>],
) -> Result<u64> {
// Merge assembly can retain exhausted batches until an output batch is full.
let mut bytes = 4_u64
.saturating_mul((plan.sources.len() as u64).saturating_add((BATCH_SIZE + 2) as u64))
.saturating_mul(self.arrow_batch_bytes as u64)
.saturating_add(6 * self.group as u64);
for footer in footers {
bytes = bytes.saturating_add(reader_bytes(footer));
}
for target in plan.targets.values() {
bytes = bytes.saturating_add(self.target_bytes(target, config)?);
}
Ok(bytes)
}
fn target_bytes(&self, target: &MultiRegionTarget, config: &MitoConfig) -> Result<u64> {
let schema_bytes = target
.metadata
.to_json()
.context(crate::error::InvalidMetadataSnafu)?
.len();
// Task/channel allocation plus captured schema and input-map copies.
let control = (8_u64 << 10)
.saturating_add((schema_bytes as u64).saturating_mul(3))
.saturating_add(
(target.inputs.len() as u64)
.saturating_mul((3 * std::mem::size_of::<crate::sst::file::FileMeta>()) as u64),
);
// A routed batch can be queued while the writer encodes another batch.
// Finish workspace includes the encoded Parquet block handed to the uploader.
let writer = (self.writer.working_bytes as u64)
.saturating_mul(RETAINED_AND_FINISH_SCRATCH_FACTOR)
.saturating_add(2 * self.arrow_batch_bytes as u64)
.saturating_add(self.writer.metadata_bytes as u64);
// Creators are instantiated even in async-index mode. Inverted/skipping
// thresholds are shared within their indexers, fulltext is per column.
Ok(control
.saturating_add(writer)
.saturating_add(4 * self.index as u64)
.saturating_add(self.fulltext_bytes(target, &config.fulltext_index)?))
}
fn fulltext_bytes(
&self,
target: &MultiRegionTarget,
config: &FulltextIndexConfig,
) -> Result<u64> {
if config.create_on_compaction.disabled() {
return Ok(0);
}
let threshold = self.index.min(config.mem_threshold_on_create());
let mut bytes = 0_u64;
for column in target
.metadata
.column_metadatas
.iter()
.filter(|column| column.semantic_type != SemanticType::Tag)
{
let Some(options) = column
.column_schema
.fulltext_options()
.context(IndexOptionsSnafu {
column_name: &column.column_schema.name,
})?
.filter(|options| options.enable)
else {
continue;
};
let allocation = match options.backend {
FulltextBackend::Tantivy => {
TantivyFulltextIndexCreator::sanitize_memory_limit(threshold)
}
FulltextBackend::Bloom => threshold,
};
bytes = bytes.saturating_add(2 * allocation as u64);
}
Ok(bytes)
}
}
/// Each serial upload can retain three parts: local assembly, the OpenDAL chunker,
/// and the backend's pending or in-flight part. Both writers can hold parts while
/// Puffin finishes, before Parquet closes.
const UPLOAD_CHUNKS_PER_TARGET: usize = 6;
const LOCAL_CHUNK_BYTES: usize = 256 << 10;
const PUFFIN_COPY_BUFFER_BYTES: usize = 8 << 10;
/// Estimate for two writers' part receipts and completion requests, per part number.
const COMPLETION_BYTES_PER_PART: usize = 512;
#[derive(Clone, Copy)]
pub(crate) struct UploadBudget {
limits: UploadLimits,
reserved_bytes: usize,
pub(crate) compute_bytes: usize,
}
struct UploadGeometry {
min_part_bytes: usize,
max_part_bytes: usize,
max_parts: Option<usize>,
max_object_bytes: u64,
}
impl UploadBudget {
pub(crate) fn new(plan: &MultiRegionCompactionPlan, store: &ObjectStore) -> Result<Self> {
let geometry = UploadGeometry::from_store(store)?;
let targets = plan.targets.len();
let chunk_bytes = geometry.choose_chunk_bytes(plan);
let fixed_bytes =
PUFFIN_COPY_BUFFER_BYTES + COMPLETION_BYTES_PER_PART * geometry.max_parts.unwrap_or(0);
let reserved_bytes = chunk_bytes
.checked_mul(UPLOAD_CHUNKS_PER_TARGET)
.and_then(|bytes| bytes.checked_add(fixed_bytes))
.and_then(|bytes| bytes.checked_mul(targets))
.context(MultiRegionCompactionResourceSnafu {
reason: "Table compaction upload reservation overflow",
})?;
let compute_bytes = plan.memory_limit.checked_sub(reserved_bytes).filter(|bytes| *bytes > 0)
.with_context(|| MultiRegionCompactionResourceSnafu {
reason: format!(
"Upload reservation of {reserved_bytes} bytes for {targets} resident targets with {chunk_bytes}-byte chunks leaves no compute budget (task budget is {})",
plan.memory_limit,
),
})?;
Ok(Self {
limits: geometry.limits(chunk_bytes),
reserved_bytes,
compute_bytes,
})
}
}
impl UploadGeometry {
fn from_store(store: &ObjectStore) -> Result<Self> {
let store_info = store.info();
let scheme = store_info.scheme();
let caps = store_info.capability();
let (max_parts, protocol_part_max, protocol_object_max) = match scheme {
"s3" | "oss" => (Some(10_000), usize::MAX, u64::MAX),
// GCS caps even multipart objects at 5 TiB: https://cloud.google.com/storage/quotas#objects
"gcs" => (Some(10_000), usize::MAX, 5_u64 << 40),
// OpenDAL 0.59 does not advertise Azure's Put Block limit.
"azblob" => (Some(50_000), 4000 << 20, u64::MAX),
"fs" => (None, usize::MAX, u64::MAX),
// Writers that spool a whole object or have their own transfer queues
// need different admission rules (e.g. MySQL and HDFS).
_ => {
return MultiRegionCompactionResourceSnafu {
reason: format!(
"Cannot bound table compaction uploads for storage backend {scheme}"
),
}
.fail();
}
};
let min_part_bytes = caps.write_multi_min_size.unwrap_or(1).max(1);
let max_part_bytes = caps
.write_multi_max_size
.unwrap_or(protocol_part_max)
.min(protocol_part_max);
let max_object_bytes = caps
.write_total_max_size
.map_or(protocol_object_max, |size| {
protocol_object_max.min(size as u64)
});
ensure!(
caps.write
&& caps.write_can_multi
&& min_part_bytes <= max_part_bytes
&& max_object_bytes > 0,
MultiRegionCompactionResourceSnafu {
reason: format!(
"No supported upload chunk size for {scheme}: minimum {min_part_bytes}, maximum {max_part_bytes}, object limit {max_object_bytes}"
),
}
);
Ok(Self {
min_part_bytes,
max_part_bytes,
max_parts,
max_object_bytes,
})
}
fn limits(&self, chunk_bytes: usize) -> UploadLimits {
let max_object_bytes = self.max_parts.map_or(self.max_object_bytes, |parts| {
self.max_object_bytes
.min((chunk_bytes as u64).saturating_mul(parts as u64))
});
UploadLimits {
chunk_bytes,
max_object_bytes,
}
}
fn choose_chunk_bytes(&self, plan: &MultiRegionCompactionPlan) -> usize {
let preferred = self.max_parts.map_or(LOCAL_CHUNK_BYTES, |parts| {
// Leave room for a final part near the soft rollover target. The
// hard upload limit still applies to a long series or large index.
(DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize)
.max(plan.max_output_file_size.div_ceil(parts - 1))
});
// Prefer to spend at most one eighth of the task on part buffers
// unless the backend minimum requires more.
preferred
.min(plan.memory_limit / plan.targets.len() / 8 / UPLOAD_CHUNKS_PER_TARGET)
.clamp(self.min_part_bytes, self.max_part_bytes)
}
}
fn extra_delta_encoder_bytes(target: &MultiRegionTarget) -> Result<usize> {
let mut bytes = 0;
for column in target
.metadata
.column_metadatas
.iter()
.filter(|column| column.semantic_type != SemanticType::Timestamp)
{
if column
.column_schema
.compression_options()
.context(crate::error::CompressionOptionsSnafu {
column_name: &column.column_schema.name,
})?
.is_some_and(|options| options.encoding == Some(ColumnEncoding::DeltaBinaryPacked))
{
bytes += 1024 * 1024;
}
}
Ok(bytes)
}
pub(super) fn reader_bytes(footer: &ParquetMetaData) -> u64 {
// Dictionary-encoded values decode to more than the uncompressed row group size; the footer
// records the largest decoded row group of the file.
let decoded = max_row_group_value_bytes(footer);
let pages = footer
.row_groups()
.iter()
.map(|group| {
(group.total_byte_size().max(0) as u64)
.max(decoded)
.saturating_mul(RETAINED_AND_FINISH_SCRATCH_FACTOR)
.saturating_add(group.compressed_size().max(0) as u64)
})
.max()
.unwrap_or(0);
pages.saturating_add(footer.memory_size() as u64)
}
/// Retained state and temporary finish allocations share the admission budget.
const RETAINED_AND_FINISH_SCRATCH_FACTOR: u64 = 2;
#[derive(Debug, PartialEq, Eq)]
struct ExtensionIndexAdmission {
limit: Option<usize>,
estimated: u64,
}
/// Reserves all target states together, or preserves the admitted data budget.
fn admit_extension_indexes(
base: u64,
budget: usize,
index: usize,
targets: usize,
) -> ExtensionIndexAdmission {
let with_extension_indexes = base.saturating_add(
(index as u64)
.saturating_mul(RETAINED_AND_FINISH_SCRATCH_FACTOR)
.saturating_mul(targets as u64),
);
if targets > 0 && index > 0 && with_extension_indexes <= budget as u64 {
ExtensionIndexAdmission {
limit: Some(index),
estimated: with_extension_indexes,
}
} else {
ExtensionIndexAdmission {
limit: None,
estimated: base,
}
}
}
#[cfg(test)]
mod tests {
use object_store::ObjectStore;
use object_store::layers::CapabilityOverrideLayer;
use object_store::services::Gcs;
use super::{ExtensionIndexAdmission, UploadGeometry, admit_extension_indexes};
#[rstest::rstest]
#[case::service_limit(1 << 30, None, 5_u64 << 40)]
#[case::advertised_limit(1 << 30, Some(2 << 30), 2 << 30)]
#[case::part_count_limit(5 << 20, None, 10_000 * (5_u64 << 20))]
fn test_gcs_multipart_object_limit(
#[case] chunk_bytes: usize,
#[case] advertised: Option<usize>,
#[case] expected: u64,
) {
let store = ObjectStore::new(Gcs::default().bucket("test"))
.unwrap()
.layer(CapabilityOverrideLayer::new(move |mut caps| {
caps.write_total_max_size = advertised;
caps
}));
let geometry = UploadGeometry::from_store(&store).unwrap();
assert_eq!(expected, geometry.limits(chunk_bytes).max_object_bytes);
}
#[test]
fn test_extension_indexes_do_not_reject_admitted_data() {
// Both target writers are resident. Insufficient extra room leaves the
// already-admitted data budget unchanged and explicitly disables optional indexes.
assert_eq!(
admit_extension_indexes(900, 1000, 30, 2),
ExtensionIndexAdmission {
limit: None,
estimated: 900
}
);
assert_eq!(
admit_extension_indexes(880, 1000, 30, 2),
ExtensionIndexAdmission {
limit: Some(30),
estimated: 1000
}
);
assert_eq!(
admit_extension_indexes(900, 1000, 30, 0),
ExtensionIndexAdmission {
limit: None,
estimated: 900
}
);
assert_eq!(
admit_extension_indexes(900, 1000, 0, 2),
ExtensionIndexAdmission {
limit: None,
estimated: 900
}
);
}
}
@@ -1,876 +0,0 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use common_base::readable_size::ReadableSize;
use common_time::Timestamp;
use datatypes::arrow::array::{
Array, ArrayRef, BinaryArray, GenericByteArray, GenericByteDictionaryBuilder, UInt64Array,
};
use datatypes::arrow::compute::{cast, concat_batches, take_record_batch};
use datatypes::arrow::datatypes::{
BinaryType, ByteArrayType, DataType, Field, Schema, SchemaRef, UInt32Type, Utf8Type,
};
use datatypes::arrow::record_batch::RecordBatch;
use parquet::file::metadata::PageIndexPolicy;
use partition::PartitionRuleRef;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::metadata::RegionMetadataRef;
use store_api::storage::RegionId;
use tokio_util::sync::CancellationToken;
use crate::cache::CacheStrategy;
use crate::compaction::json2::collect_json2_rewrite_plans_from_parquet;
use crate::compaction::multi_region::memory::{BATCH_SIZE, MemoryLimits, UploadBudget};
use crate::compaction::multi_region::{
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, SourceCounters,
};
use crate::config::MemoryThreshold;
use crate::error::{
ComputeArrowSnafu, ExternalSnafu, InvalidMultiRegionCompactionSnafu,
MultiRegionCompactionResourceSnafu, NewRecordBatchSnafu, Result,
};
use crate::read::flat_merge::FlatMergeReader;
use crate::read::flat_projection::FlatProjectionMapper;
use crate::read::read_columns::ReadColumns;
use crate::read::scan_region::ScanInput;
use crate::read::{BoxedRecordBatchStream, timestamp_array_to_i64_slice};
use crate::sst::file::{FileHandle, FileMeta};
use crate::sst::file_purger::NoopFilePurger;
use crate::sst::index::IndexBuildType;
use crate::sst::index::handler::PlanContext;
use crate::sst::index::registry::{IndexBuildPlan, IndexRegistry};
use crate::sst::parquet::decoded_input_size;
use crate::sst::parquet::file_range::PreFilterMode;
use crate::sst::parquet::flat_format::{
primary_key_column_index, sequence_column_index, time_index_column_index,
};
use crate::sst::parquet::format::{PrimaryKeyArray, need_override_sequence};
use crate::sst::parquet::reader::{MetadataCacheMetrics, ReaderMetrics};
use crate::sst::parquet::row_group::ParquetFetchMetrics;
pub(crate) struct SourceEvent {
pub(crate) region_id: RegionId,
pub(crate) batch: RecordBatch,
}
/// Complete leading-key groups, ordered by target, key-group ordinal and version.
/// Only the next bounded fragment is materialized, not one array per destination.
struct RoutedBatch {
batch: RecordBatch,
rows: Vec<(RegionId, usize, Reverse<u64>, usize)>,
offset: usize,
}
impl RoutedBatch {
fn next_fragment(&mut self, source: &SharedSource) -> Result<Option<SourceEvent>> {
source.check_cancelled()?;
let Some(&(region_id, _, _, _)) = self.rows.get(self.offset) else {
return Ok(None);
};
let rows = &self.rows[self.offset..];
let len = rows
.partition_point(|row| row.0 == region_id)
.min(BATCH_SIZE);
let indices = UInt64Array::from_iter_values(rows[..len].iter().map(|row| row.3 as u64));
let batch = take_record_batch(&self.batch, &indices).context(ComputeArrowSnafu)?;
let batch = compact_dictionaries(batch)?;
ensure!(
batch.get_array_memory_size() <= source.limits.arrow_batch_bytes,
MultiRegionCompactionResourceSnafu {
reason: "Routed batch exceeds the task buffer budget"
}
);
self.offset += len;
Ok(Some(SourceEvent { region_id, batch }))
}
}
pub(crate) struct SharedSource {
sources: Vec<FileMeta>,
legacy_overrides: Vec<bool>,
expected_rows: Vec<i64>,
targets: BTreeMap<RegionId, MultiRegionTarget>,
metadata: RegionMetadataRef,
scan_input: ScanInput,
routing_codec: Arc<dyn mito_codec::row_converter::PrimaryKeyCodec>,
schema: SchemaRef,
merge_schema: SchemaRef,
partition_rule: PartitionRuleRef,
window: (Timestamp, Timestamp),
pub(crate) limits: MemoryLimits,
pub(crate) index_plans: BTreeMap<RegionId, Arc<IndexBuildPlan>>,
/// Targets whose every routed row keeps the numbers their own allocator
/// assigned, so an output of the target can state `Original` for its bytes.
proved_row_sequences: BTreeSet<RegionId>,
/// Rows and decoded bytes of the sources, which size output row groups.
pub(crate) input_size: (u64, u64),
peak_group_bytes: AtomicU64,
cancellation: CancellationToken,
stop: CancellationToken,
counters: Arc<SourceCounters>,
}
impl SharedSource {
pub(crate) async fn build(
plan: &MultiRegionCompactionPlan,
context: &MultiRegionCompactionContext,
metadata: RegionMetadataRef,
counters: Arc<SourceCounters>,
) -> Result<Arc<Self>> {
let upload = UploadBudget::new(plan, context.access_layer.object_store())?;
let mut common = (*metadata).clone();
common.set_partition_expr(None);
let metadata = Arc::new(common);
let cache = CacheStrategy::Compaction(context.cache.clone());
let mut footers = Vec::with_capacity(plan.sources.len());
let mut footer_bytes = 0usize;
for file in &plan.sources {
ensure!(
!context.cancellation.is_cancelled(),
crate::error::CompactionCancelledSnafu
);
let handle = FileHandle::new(file.clone(), Arc::new(NoopFilePurger));
let path = handle.file_path(
context.access_layer.table_dir(),
context.access_layer.path_type(),
);
let (sst, _) = context
.access_layer
.read_sst(handle)
.cache(cache.clone())
.read_parquet_metadata(
&path,
file.file_size,
&mut MetadataCacheMetrics::default(),
PageIndexPolicy::Skip,
)
.await?;
let footer = sst.parquet_metadata();
footer_bytes = footer_bytes.saturating_add(footer.memory_size());
ensure!(
footer_bytes <= upload.compute_bytes / 8,
MultiRegionCompactionResourceSnafu {
reason: format!(
"Source footer metadata needs {footer_bytes} bytes, budget after reserving uploads is {}",
upload.compute_bytes / 8,
),
}
);
footers.push(footer);
}
let legacy_overrides: Vec<bool> = footers
.iter()
.map(|footer| need_override_sequence(footer))
.collect();
let expected_rows = footers
.iter()
.map(|footer| footer.file_metadata().num_rows())
.collect();
let proved_row_sequences = proved_row_sequence_targets(plan, &legacy_overrides);
let input_size = decoded_input_size(footers.iter().map(Arc::as_ref));
let layouts = collect_json2_rewrite_plans_from_parquet(&metadata, &footers)?;
let json2_targets = crate::compaction::reader::json2_rewrite_targets(&metadata, &layouts)?;
let mapper = FlatProjectionMapper::new_with_json2_rewrite_targets(
&metadata,
(0..metadata.column_metadatas.len()).collect(),
ReadColumns::new(
metadata
.column_metadatas
.iter()
.map(|column| column.column_id),
),
&json2_targets,
)?;
let schema = mapper.input_arrow_schema(true);
let scan_input = ScanInput::builder(context.access_layer.clone(), mapper)
.with_compaction(true)
.with_page_index_policy(PageIndexPolicy::Skip)
.with_batch_size(BATCH_SIZE)
.with_cache(cache.clone())
.with_json2_rewrite_targets(json2_targets.clone())
.build();
let mut limits = MemoryLimits::new(plan, &schema, upload)?;
let mut inverted = context.config.inverted_index.clone();
inverted.mem_threshold_on_create =
admitted_index_threshold(inverted.mem_threshold_on_create(), limits.index);
let mut fulltext = context.config.fulltext_index.clone();
fulltext.mem_threshold_on_create =
admitted_index_threshold(Some(fulltext.mem_threshold_on_create()), limits.index);
let mut bloom = context.config.bloom_filter_index.clone();
bloom.mem_threshold_on_create =
admitted_index_threshold(bloom.mem_threshold_on_create(), limits.index);
let registry = IndexRegistry::new(inverted, fulltext, bloom)
.with_provider(context.index_kind_provider.clone())
.with_context(|_| ExternalSnafu {
context: "registering index handlers".to_string(),
})?;
let mut index_plans = plan
.targets
.iter()
.map(|(id, target)| {
let work = registry.plan(&PlanContext {
metadata: &target.metadata,
index_options: &target.options.index_options,
build_type: IndexBuildType::Compact,
existing_indexes: &[],
});
(*id, Arc::new(work))
})
.collect::<BTreeMap<_, _>>();
limits.admit(
plan,
&context.config,
&footers,
index_plans
.values()
.filter(|work| work.entries().any(|entry| !entry.kind.is_builtin()))
.count(),
)?;
if limits.extension_index_memory_limit.is_none() {
for (region_id, work) in &mut index_plans {
Arc::make_mut(work).omit_extensions_for_budget(*region_id);
}
}
// Compute routing/version annotations on bounded reader batches, but
// keep physical __sequence as the merge key. The annotations are not
// persisted and fixed-position time/PK/sequence/op columns stay last.
let fields = ["__compaction_region", "__compaction_sequence"]
.into_iter()
.map(|name| Arc::new(Field::new(name, DataType::UInt64, false)))
.chain(schema.fields().iter().cloned())
.collect::<Vec<_>>();
let merge_schema = Arc::new(Schema::new(fields));
Ok(Arc::new(Self {
sources: plan.sources.clone(),
legacy_overrides,
expected_rows,
targets: plan.targets.clone(),
routing_codec: mito_codec::row_converter::build_primary_key_codec(&metadata),
metadata,
scan_input,
schema,
merge_schema,
partition_rule: plan.partition_rule.clone(),
window: (
Timestamp::new_second(plan.window_start),
Timestamp::new_second(plan.window_start + plan.window_seconds),
),
limits,
index_plans,
proved_row_sequences,
input_size,
peak_group_bytes: AtomicU64::new(0),
cancellation: context.cancellation.clone(),
stop: CancellationToken::new(),
counters,
}))
}
pub(crate) fn cancel_on_drop(&self) -> tokio_util::sync::DropGuard {
self.stop.clone().drop_guard()
}
pub(crate) fn schema(&self) -> SchemaRef {
self.schema.clone()
}
/// Whether an output of `target` can state that its encoded numbers belong to
/// that target's allocator.
pub(crate) fn proves_row_sequences(&self, target: RegionId) -> bool {
self.proved_row_sequences.contains(&target)
}
pub(crate) fn peak_group_bytes(&self) -> u64 {
self.peak_group_bytes.load(Ordering::Relaxed)
}
/// One global merge closes leading (PK,time) groups. Only that group's
/// versions need reordering after applying target-local admission sequences.
/// This also supports field partitions and reversed installation orders.
pub(crate) fn batches(
self: Arc<Self>,
) -> std::pin::Pin<Box<dyn futures::Stream<Item = Result<SourceEvent>> + Send>> {
use futures::TryStreamExt;
Box::pin(async_stream::try_stream! {
let streams = (0..self.sources.len())
.map(|index| self.clone().source_batches(index))
.collect();
let mut merged =
FlatMergeReader::new(self.merge_schema.clone(), streams, BATCH_SIZE, None).await?;
let mut groups = KeyGroups::new(self.limits.group);
while let Some(batch) = merged.next_batch().await? {
self.check_cancelled()?;
let complete = groups.push(batch)?;
self.peak_group_bytes.fetch_max(groups.peak as u64, Ordering::Relaxed);
if let Some(complete) = complete {
let mut fragments = self.clone().route_batches(complete);
while let Some(fragment) = fragments.try_next().await? { yield fragment; }
}
}
if !groups.batches.is_empty() {
let mut fragments = self.clone().route_batches(groups.batches);
while let Some(fragment) = fragments.try_next().await? { yield fragment; }
}
})
}
fn route_batches(
self: Arc<Self>,
batches: Vec<RecordBatch>,
) -> std::pin::Pin<Box<dyn futures::Stream<Item = Result<SourceEvent>> + Send>> {
Box::pin(async_stream::try_stream! {
let router = self.clone();
let mut routed = common_runtime::spawn_blocking_compact(move || router.route(batches))
.await
.context(crate::error::JoinSnafu)??;
loop {
let router = self.clone();
let (event, next) = common_runtime::spawn_blocking_compact(move || {
let event = routed.next_fragment(&router)?;
Ok::<_, crate::error::Error>((event, routed))
}).await.context(crate::error::JoinSnafu)??;
routed = next;
let Some(event) = event else { break; };
yield event;
}
})
}
fn source_batches(self: Arc<Self>, index: usize) -> BoxedRecordBatchStream {
Box::pin(async_stream::try_stream! {
self.check_cancelled()?;
let file = &self.sources[index];
let mut raw_meta = file.clone();
raw_meta.sequence = None;
raw_meta.preserve_row_sequence = true;
let handle = FileHandle::new(raw_meta, Arc::new(NoopFilePurger));
let input = self.scan_input.prune_file(
&handle, PreFilterMode::All, &mut ReaderMetrics::default(),
).await?;
let mut ranges = smallvec::SmallVec::new();
input.build_ranges(-1, &mut ranges);
let fetch_metrics = ParquetFetchMetrics::default();
let mut rows = 0u64;
let mut last_key = None;
for range in ranges {
let Some(mut reader) = range.flat_reader(None, Some(&fetch_metrics)).await? else {
continue;
};
while let Some(batch) = crate::read::scan_util::next_aligned_file_batch(
&range, &mut reader, None, false,
).await? {
self.check_cancelled()?;
let preparing = self.clone();
let (batch, previous) = common_runtime::spawn_blocking_compact(move || {
preparing.check_cancelled()?;
let batch = compact_dictionaries(batch)?;
let batch_bytes = batch.get_array_memory_size();
ensure!(
batch_bytes <= preparing.limits.arrow_batch_bytes,
MultiRegionCompactionResourceSnafu {
reason: format!(
"Decoded source batch uses {} bytes, budget is {}",
batch_bytes,
preparing.limits.arrow_batch_bytes,
),
}
);
preparing.validate_batch(&batch, &mut last_key)?;
let batch = preparing.annotate(batch, index)?;
Ok::<_, crate::error::Error>((batch, last_key))
}).await.context(crate::error::JoinSnafu)??;
last_key = previous;
rows += batch.num_rows() as u64;
self.counters.rows.fetch_add(batch.num_rows() as u64, Ordering::Relaxed);
yield batch;
}
}
let store_bytes = fetch_metrics.data.lock()
.map(|metrics| metrics.page_size_to_fetch_store)
.map_err(|_| crate::error::UnexpectedSnafu {
reason: "Source fetch metrics lock poisoned",
}.build())?;
self.counters.store_page_bytes.fetch_add(store_bytes, Ordering::Relaxed);
let expected = self.expected_rows[index];
if expected < 0 || rows != expected as u64 {
Err(InvalidMultiRegionCompactionSnafu {
reason: "Shared source scan did not cover its complete footer row count",
}
.build())?;
}
self.counters.files.fetch_add(1, Ordering::Relaxed);
})
}
fn validate_batch(
&self,
batch: &RecordBatch,
previous: &mut Option<(Vec<u8>, i64, Reverse<u64>)>,
) -> Result<()> {
let time = batch.column(time_index_column_index(batch.num_columns()));
let sequences = batch
.column(sequence_column_index(batch.num_columns()))
.as_any()
.downcast_ref::<UInt64Array>()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Invalid sequence column",
})?;
ensure!(
time.null_count() == 0 && sequences.null_count() == 0,
InvalidMultiRegionCompactionSnafu {
reason: "Null timestamp or sequence in source"
}
);
let unit = self
.metadata
.time_index_column()
.column_schema
.data_type
.as_timestamp()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Time index is not a timestamp",
})?
.unit();
for (row, &value) in timestamp_array_to_i64_slice(time).iter().enumerate() {
let timestamp = Timestamp::new(value, unit);
ensure!(
timestamp >= self.window.0 && timestamp < self.window.1,
InvalidMultiRegionCompactionSnafu {
reason: "Source row is outside the task window"
}
);
let current = (
key_at(batch, row)?.to_vec(),
value,
Reverse(sequences.value(row)),
);
ensure!(
previous
.as_ref()
.is_none_or(|previous| *previous <= current),
InvalidMultiRegionCompactionSnafu {
reason: "Source is not ordered after schema alignment"
}
);
*previous = Some(current);
}
Ok(())
}
fn annotate(&self, batch: RecordBatch, index: usize) -> Result<RecordBatch> {
// Evaluate masks before adding private columns, avoiding name collisions
// and N-target masks over a potentially much larger equal-key group.
let owners = self.row_owners(&batch)?;
let physical = batch
.column(sequence_column_index(batch.num_columns()))
.as_any()
.downcast_ref::<UInt64Array>()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Invalid sequence column",
})?;
let source = &self.sources[index];
let sequences = owners.iter().enumerate().map(|(row, region)| {
let input = &self.targets[region].inputs[&source.file_id()];
if keeps_physical_sequence(input, *region, self.legacy_overrides[index]) {
physical.value(row)
} else {
input
.sequence
.map(|value| value.get())
.unwrap_or_else(|| physical.value(row))
}
});
let columns = [
Arc::new(UInt64Array::from_iter_values(
owners.iter().map(RegionId::as_u64),
)) as ArrayRef,
Arc::new(UInt64Array::from_iter_values(sequences)) as ArrayRef,
]
.into_iter()
.chain(batch.columns().iter().cloned())
.collect();
RecordBatch::try_new(self.merge_schema.clone(), columns).context(NewRecordBatchSnafu)
}
fn route(&self, batches: Vec<RecordBatch>) -> Result<RoutedBatch> {
self.check_cancelled()?;
let batch = concat_batches(&self.merge_schema, &batches).context(ComputeArrowSnafu)?;
let owners = batch
.column(0)
.as_any()
.downcast_ref::<UInt64Array>()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Missing routing annotation",
})?;
let sequences = batch
.column(1)
.as_any()
.downcast_ref::<UInt64Array>()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Missing sequence annotation",
})?;
let mut group = 0usize;
let mut rows = Vec::with_capacity(batch.num_rows());
for row in 0..batch.num_rows() {
if row > 0 && !same_key(&batch, row - 1, &batch, row)? {
group += 1;
}
rows.push((
RegionId::from_u64(owners.value(row)),
group,
Reverse(sequences.value(row)),
row,
));
}
rows.sort_unstable();
let mut columns = batch.columns()[2..].to_vec();
let sequence_index = sequence_column_index(columns.len());
columns[sequence_index] = batch.column(1).clone();
let batch =
RecordBatch::try_new(self.schema.clone(), columns).context(NewRecordBatchSnafu)?;
Ok(RoutedBatch {
batch,
rows,
offset: 0,
})
}
/// Materialize only routing dependencies; merge and output retain encoded keys.
fn routing_batch(&self, batch: &RecordBatch) -> Result<(RecordBatch, usize)> {
let mut materialized_bytes = 0usize;
let mut decoded = None;
let mut fields = Vec::new();
let mut arrays = Vec::new();
for name in self.partition_rule.partition_columns() {
let column =
self.metadata
.column_by_name(name)
.context(InvalidMultiRegionCompactionSnafu {
reason: "Unknown partition column",
})?;
let array = if let Some(array) = batch.column_by_name(name) {
array.clone()
} else {
if decoded.is_none() {
decoded = Some(crate::sst::parquet::flat_format::decode_primary_keys(
self.routing_codec.as_ref(),
batch,
)?);
}
let array = decoded
.as_mut()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Missing decoded routing key",
})?
.get_tag_column(column.column_id, None, &column.column_schema.data_type)?;
materialized_bytes =
materialized_bytes.saturating_add(array.get_array_memory_size());
array
};
fields.push(Field::new(name, array.data_type().clone(), true));
arrays.push(array);
}
let options = datatypes::arrow::record_batch::RecordBatchOptions::new()
.with_row_count(Some(batch.num_rows()));
let routing =
RecordBatch::try_new_with_options(Arc::new(Schema::new(fields)), arrays, &options)
.context(NewRecordBatchSnafu)?;
Ok((routing, materialized_bytes))
}
pub(super) fn row_owners(&self, batch: &RecordBatch) -> Result<Vec<RegionId>> {
let (routing, materialized_bytes) = self.routing_batch(batch)?;
ensure!(
batch
.get_array_memory_size()
.saturating_add(materialized_bytes)
<= self.limits.arrow_batch_bytes,
MultiRegionCompactionResourceSnafu {
reason: "Routing projection exceeds the task buffer budget"
}
);
let batch = &routing;
let rows = batch.num_rows();
let masks = self
.partition_rule
.split_record_batch(batch)
.context(crate::error::RouteMultiRegionSnafu)?;
let mut owners = vec![None; rows];
for (number, mask) in masks {
ensure!(
mask.array().len() == rows,
InvalidMultiRegionCompactionSnafu {
reason: "Partition rule returned a mask with the wrong row count"
}
);
let id = RegionId::new(self.metadata.region_id.table_id(), number);
for (row, selected) in mask.array().iter().enumerate() {
if selected == Some(true) {
ensure!(
owners[row].replace(id).is_none(),
InvalidMultiRegionCompactionSnafu {
reason: "Source row matches multiple target partitions"
}
);
}
}
}
self.resolve_unassigned(batch, &mut owners)?;
owners
.into_iter()
.map(|owner| {
owner.filter(|id| self.targets.contains_key(id)).context(
InvalidMultiRegionCompactionSnafu {
reason: "Partition rule selected a region outside the captured targets",
},
)
})
.collect()
}
fn resolve_unassigned(
&self,
batch: &RecordBatch,
owners: &mut [Option<RegionId>],
) -> Result<()> {
if owners.iter().all(Option::is_some) {
return Ok(());
}
let columns = self
.partition_rule
.partition_columns()
.iter()
.map(|name| {
let array =
batch
.column_by_name(name)
.context(InvalidMultiRegionCompactionSnafu {
reason: "Partition column missing from the source batch",
})?;
datatypes::vectors::Helper::try_into_vector(array.clone())
.context(crate::error::ConvertVectorSnafu)
})
.collect::<Result<Vec<_>>>()?;
for (row, owner) in owners
.iter_mut()
.enumerate()
.filter(|(_, owner)| owner.is_none())
{
let values = columns
.iter()
.map(|column| column.get(row))
.collect::<Vec<_>>();
let number = self
.partition_rule
.find_region(&values)
.context(crate::error::RouteMultiRegionSnafu)?;
*owner = Some(RegionId::new(self.metadata.region_id.table_id(), number));
}
Ok(())
}
fn check_cancelled(&self) -> Result<()> {
ensure!(
!self.stop.is_cancelled() && !self.cancellation.is_cancelled(),
crate::error::CompactionCancelledSnafu
);
Ok(())
}
}
/// Carries only the trailing equal (PK,time) group. Complete groups can be
/// routed immediately; EOF closes the remaining group without another scan.
struct KeyGroups {
batches: Vec<RecordBatch>,
bytes: usize,
peak: usize,
limit: usize,
}
impl KeyGroups {
fn new(limit: usize) -> Self {
Self {
batches: Vec::new(),
bytes: 0,
peak: 0,
limit,
}
}
fn push(&mut self, batch: RecordBatch) -> Result<Option<Vec<RecordBatch>>> {
let tail = trailing_group_start(&batch)?;
let same_tail = self
.batches
.last()
.map(|previous| {
same_key(
previous,
previous.num_rows() - 1,
&batch,
batch.num_rows() - 1,
)
})
.transpose()?
.unwrap_or(false);
let complete = if (!same_tail && !self.batches.is_empty()) || tail > 0 {
if tail > 0 {
self.retain(batch.slice(0, tail))?;
}
self.bytes = 0;
Some(std::mem::take(&mut self.batches))
} else {
None
};
self.retain(batch.slice(tail, batch.num_rows() - tail))?;
Ok(complete)
}
fn retain(&mut self, batch: RecordBatch) -> Result<()> {
self.bytes = self
.bytes
.saturating_add(batch.get_array_memory_size() + std::mem::size_of::<RecordBatch>());
ensure!(
self.bytes <= self.limit,
MultiRegionCompactionResourceSnafu {
reason: "Equal-key version group exceeds the task buffer budget"
}
);
self.peak = self.peak.max(self.bytes);
self.batches.push(batch);
Ok(())
}
}
/// Whether a row of `input` routed to `owner` keeps the physical `__sequence` it
/// carries instead of the number the target's reader would assign it.
fn keeps_physical_sequence(input: &FileMeta, owner: RegionId, legacy_override: bool) -> bool {
input.region_id == owner && (input.preserve_row_sequence || !legacy_override)
}
/// Targets whose every possible contributor proves its own encoded numbers and
/// whose routing keeps them.
fn proved_row_sequence_targets(
plan: &MultiRegionCompactionPlan,
legacy_overrides: &[bool],
) -> BTreeSet<RegionId> {
plan.targets
.iter()
.filter(|(id, target)| {
plan.sources.iter().enumerate().all(|(index, source)| {
let input = &target.inputs[&source.file_id()];
input.has_original_row_sequences()
&& keeps_physical_sequence(input, **id, legacy_overrides[index])
})
})
.map(|(id, _)| *id)
.collect()
}
fn trailing_group_start(batch: &RecordBatch) -> Result<usize> {
let last = batch.num_rows() - 1;
let mut start = last;
while start > 0 && same_key(batch, start - 1, batch, last)? {
start -= 1;
}
Ok(start)
}
fn same_key(
left: &RecordBatch,
left_row: usize,
right: &RecordBatch,
right_row: usize,
) -> Result<bool> {
let left_time =
timestamp_array_to_i64_slice(left.column(time_index_column_index(left.num_columns())))
[left_row];
let right_time =
timestamp_array_to_i64_slice(right.column(time_index_column_index(right.num_columns())))
[right_row];
Ok(left_time == right_time && key_at(left, left_row)? == key_at(right, right_row)?)
}
/// A selected batch must not pin dictionaries for a whole row group or version
/// group. Casting through the value type compacts both tag and PK dictionaries.
fn compact_dictionaries(batch: RecordBatch) -> Result<RecordBatch> {
let columns = batch
.columns()
.iter()
.map(|array| match array.data_type() {
DataType::Dictionary(key, values) if **key == DataType::UInt32 => match **values {
DataType::Utf8 => compact_dictionary::<Utf8Type>(array),
DataType::Binary => compact_dictionary::<BinaryType>(array),
_ => Ok(array.clone()),
},
_ => Ok(array.clone()),
})
.collect::<Result<Vec<_>>>()?;
RecordBatch::try_new(batch.schema(), columns).context(NewRecordBatchSnafu)
}
fn compact_dictionary<T: ByteArrayType>(array: &ArrayRef) -> Result<ArrayRef> {
let decoded = cast(array, &T::DATA_TYPE).context(ComputeArrowSnafu)?;
let values = decoded
.as_any()
.downcast_ref::<GenericByteArray<T>>()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Invalid decoded dictionary",
})?;
let mut builder = GenericByteDictionaryBuilder::<UInt32Type, T>::with_capacity(
values.len(),
values.len(),
values.value_data().len(),
);
for value in values.iter() {
if let Some(value) = value {
builder.append(value).context(ComputeArrowSnafu)?;
} else {
builder.append_null();
}
}
Ok(Arc::new(builder.finish()))
}
fn key_at(batch: &RecordBatch, row: usize) -> Result<&[u8]> {
let keys = batch
.column(primary_key_column_index(batch.num_columns()))
.as_any()
.downcast_ref::<PrimaryKeyArray>()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Invalid primary-key column",
})?;
let values = keys
.values()
.as_any()
.downcast_ref::<BinaryArray>()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Invalid primary-key dictionary",
})?;
let index = keys.key(row).context(InvalidMultiRegionCompactionSnafu {
reason: "Null internal primary key",
})?;
ensure!(
!values.is_null(index),
InvalidMultiRegionCompactionSnafu {
reason: "Null internal primary-key value"
}
);
Ok(values.value(index))
}
fn admitted_index_threshold(configured: Option<usize>, limit: usize) -> MemoryThreshold {
MemoryThreshold::Size(ReadableSize(configured.unwrap_or(limit).min(limit) as u64))
}
File diff suppressed because it is too large. Load diff
@@ -1,169 +0,0 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
//! Incremental sinks for the already merged stream. All resident writers are
//! admitted together. No writer holds a work permit while waiting for input,
//! and no sink waits for another source head to consume its channel.
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use datatypes::arrow::record_batch::RecordBatch;
use futures::stream::FuturesUnordered;
use futures::{StreamExt, TryStreamExt};
use snafu::{OptionExt, ResultExt, ensure};
use store_api::storage::RegionId;
use tokio::sync::mpsc;
use tokio_util::task::AbortOnDropHandle;
use crate::compaction::multi_region::source::SharedSource;
use crate::compaction::multi_region::{
MultiRegionCompactionContext, MultiRegionCompactionOutput, MultiRegionCompactionPlan,
MultiRegionCompactionStats, SourceCounters, writer,
};
use crate::error::{InvalidMultiRegionCompactionSnafu, Result};
use crate::read::FlatSource;
/// Transport closure is failure; only the dispatcher can signal successful EOF.
enum Message {
Batch(RecordBatch),
Finish,
}
pub(crate) async fn execute(
plan: MultiRegionCompactionPlan,
context: MultiRegionCompactionContext,
source: Arc<SharedSource>,
counters: Arc<SourceCounters>,
) -> Result<MultiRegionCompactionOutput> {
let _cancel_on_drop = source.cancel_on_drop();
let plan = Arc::new(plan);
let context = Arc::new(context);
let mut senders = BTreeMap::new();
let mut workers = FuturesUnordered::new();
for &id in plan.targets.keys() {
let (sender, mut receiver) = mpsc::channel(1);
senders.insert(id, sender);
let schema = source.schema();
let limits = source.limits.clone();
let input_size = source.input_size;
let proved_row_sequences = source.proves_row_sequences(id);
let index_plan =
source
.index_plans
.get(&id)
.cloned()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Missing index plan for compaction target",
})?;
let plan = plan.clone();
let context = context.clone();
workers.push(AbortOnDropHandle::new(common_runtime::spawn_compact(
async move {
let stream = async_stream::try_stream! {
while let Message::Batch(batch) = receiver
.recv()
.await
.context(InvalidMultiRegionCompactionSnafu {
reason: "Source channel closed without Finish",
})?
{
yield batch;
}
};
let input = FlatSource::new_stream(schema, Box::pin(stream));
let (files, infos) = writer::TargetWriter::new(
&plan.targets[&id],
&context,
&limits,
plan.max_output_file_size,
input_size,
index_plan,
proved_row_sequences,
)
.write(input)
.await?;
Ok::<_, crate::error::Error>((id, files, infos))
},
)));
}
let scan = dispatch(source.clone(), senders);
tokio::pin!(scan);
let mut scan_finished = false;
let mut output = MultiRegionCompactionOutput {
files: BTreeMap::new(),
sst_infos: BTreeMap::new(),
stats: MultiRegionCompactionStats::default(),
};
while !scan_finished || !workers.is_empty() {
tokio::select! {
biased;
Some(result) = workers.next(), if !workers.is_empty() => {
let (id, files, infos) = result.context(crate::error::JoinSnafu)??;
output.stats.output_rows += files
.iter()
.map(|file| file.num_rows)
.sum::<u64>();
output.stats.output_bytes += files
.iter()
.map(|file| file.file_size + file.index_file_size)
.sum::<u64>();
output.files.insert(id, files);
output.sst_infos.insert(id, infos);
}
result = &mut scan, if !scan_finished => {
result?;
scan_finished = true;
}
}
}
output.stats.source_files = counters.files.load(Ordering::Relaxed);
output.stats.source_rows = counters.rows.load(Ordering::Relaxed);
output.stats.source_store_page_bytes = counters.store_page_bytes.load(Ordering::Relaxed);
output.stats.estimated_memory_bytes = source.limits.estimated;
output.stats.peak_group_bytes = source.peak_group_bytes();
ensure!(
output.stats.source_files == plan.sources.len() as u64
&& output.stats.output_rows == output.stats.source_rows,
InvalidMultiRegionCompactionSnafu {
reason: "Multi-region compaction did not account for every source row"
}
);
Ok(output)
}
async fn dispatch(
source: Arc<SharedSource>,
senders: BTreeMap<RegionId, mpsc::Sender<Message>>,
) -> Result<()> {
let mut batches = source.batches();
while let Some(event) = batches.try_next().await? {
let sender = senders
.get(&event.region_id)
.context(InvalidMultiRegionCompactionSnafu {
reason: "Unknown routing target",
})?;
send(sender, Message::Batch(event.batch)).await;
}
for sender in senders.values() {
send(sender, Message::Finish).await;
}
Ok(())
}
async fn send(sender: &mpsc::Sender<Message>, message: Message) {
if sender.send(message).await.is_err() {
// The supervisor reports the writer's original error, not a racing
// channel-closed error. It also aborts siblings on failure or drop.
futures::future::pending::<()>().await;
}
}
@@ -1,235 +0,0 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
use std::num::NonZeroU64;
use std::sync::Arc;
use common_base::readable_size::ReadableSize;
use partition::expr::PartitionExpr;
use snafu::ensure;
use tokio_util::sync::CancellationToken;
use crate::access_layer::{Metrics, OperationType, SstWriteRequest, WriteType};
use crate::compaction::multi_region::memory::{self, MemoryLimits};
use crate::compaction::multi_region::{MultiRegionCompactionContext, MultiRegionTarget};
use crate::error::Result;
use crate::read::FlatSource;
use crate::sst::FormatType;
use crate::sst::file::{FileFormat, FileMeta, RowSequenceProvenance};
use crate::sst::index::build::IndexBuildInputs;
use crate::sst::index::registry::IndexBuildPlan;
use crate::sst::parquet::metadata::extract_primary_key_range;
use crate::sst::parquet::parallel_writer::EncodeRuntime;
use crate::sst::parquet::writer::SstWriteContext;
use crate::sst::parquet::{SstInfo, WriteOptions, row_group_size_for};
pub(crate) struct TargetWriter<'a> {
target: &'a MultiRegionTarget,
context: &'a MultiRegionCompactionContext,
limits: &'a MemoryLimits,
index_plan: Arc<IndexBuildPlan>,
max_file_size: usize,
/// Rows and decoded bytes of the shared sources.
input_size: (u64, u64),
sequence: Option<NonZeroU64>,
preserve_row_sequence: bool,
/// Every possible contributor proves its own numbers are this target's and
/// routing keeps them.
proved_row_sequences: bool,
}
impl<'a> TargetWriter<'a> {
pub(crate) fn new(
target: &'a MultiRegionTarget,
context: &'a MultiRegionCompactionContext,
limits: &'a MemoryLimits,
max_file_size: usize,
input_size: (u64, u64),
index_plan: Arc<IndexBuildPlan>,
proved_row_sequences: bool,
) -> Self {
let sequence = crate::sst::file::known_max_input_sequence(target.inputs.values());
let preserve_row_sequence = target.options.preserve_row_sequence
&& target
.inputs
.values()
.all(|file| file.is_effective_target_sequence_trusted(target.metadata.region_id));
Self {
target,
context,
limits,
index_plan,
max_file_size,
input_size,
sequence,
preserve_row_sequence,
proved_row_sequences,
}
}
pub(crate) async fn write(&self, source: FlatSource) -> Result<(Vec<FileMeta>, Vec<SstInfo>)> {
ensure!(
!self.context.cancellation.is_cancelled(),
crate::error::CompactionCancelledSnafu
);
let request = self.request(source)?;
let mut metrics = Metrics::new(WriteType::Compaction);
let infos = self
.context
.access_layer
.write_sst_with_context(
request,
&self.options(),
&mut metrics,
SstWriteContext {
guard: Some(self.context.protection.clone()),
limits: Some(self.limits.writer),
..Default::default()
},
)
.await?;
metrics.observe();
let expression =
crate::region::parse_partition_expr(self.target.metadata.partition_expr.as_deref())?;
let files = infos
.iter()
.map(|info| {
self.validate_sequence(info)?;
self.file_metadata(info, expression.clone())
})
.collect::<Result<Vec<_>>>()?;
Ok((files, infos.into_iter().collect()))
}
fn request(&self, source: FlatSource) -> Result<SstWriteRequest> {
let config = &self.context.config;
// The shared source plan already applies the admitted index thresholds.
let source = cancellable_source(source, self.context.cancellation.clone());
let index_build_inputs = Some(IndexBuildInputs {
output_rows: None,
plan: self.index_plan.clone(),
input_puffin_manager: self.context.access_layer.build_puffin_manager(),
// Routing and file rollover change coverage. Consume only actual output rows.
inputs: Arc::from([]),
can_merge_inputs: false,
memory_limit: self.limits.extension_index_memory_limit,
});
Ok(SstWriteRequest {
index_build_inputs,
op_type: OperationType::Compact,
metadata: self.target.metadata.clone(),
source,
cache_manager: self.context.cache.clone(),
max_sequence: None,
sst_write_format: self.target.options.sst_format.unwrap_or(
if config.default_flat_format {
FormatType::Flat
} else {
FormatType::PrimaryKey
},
),
preserve_row_sequence: self.preserve_row_sequence,
index_options: self.target.options.index_options.clone(),
index_config: config.index.clone(),
inverted_index_config: config.inverted_index.clone(),
fulltext_index_config: config.fulltext_index.clone(),
bloom_filter_index_config: config.bloom_filter_index.clone(),
})
}
pub(super) fn options(&self) -> WriteOptions {
WriteOptions {
write_buffer_size: ReadableSize(self.limits.writer.upload_limits.chunk_bytes as u64),
max_file_size: Some(self.max_file_size),
// Capped so each admitted encoder stays within the task budget; see
// [memory::MAX_ROW_GROUP_SIZE].
row_group_size: row_group_size_for(
self.input_size.0,
self.input_size.1,
self.target
.options
.row_group_size()
.min(memory::MAX_ROW_GROUP_SIZE),
),
float_field_encoding: self.target.options.float_field_encoding,
// Every resident encoder and its finish workspace are admitted together.
encode_parallelism: 1,
encode_runtime: EncodeRuntime::Compact,
}
}
fn validate_sequence(&self, info: &SstInfo) -> Result<()> {
// Routing nonzero versions elsewhere can turn a mixed native input into
// an all-zero output. A legacy reader must not replace those zeros with
// the positive file bound; neither trust nor the bound may be fabricated.
ensure!(
self.preserve_row_sequence
|| self.sequence.is_none()
|| !info.file_metadata.as_ref().is_some_and(|footer| {
crate::sst::parquet::format::need_override_sequence(footer)
}),
crate::error::InvalidMultiRegionCompactionSnafu {
reason: "Legacy sequence override would change zero output versions"
}
);
Ok(())
}
fn file_metadata(
&self,
info: &SstInfo,
partition_expr: Option<PartitionExpr>,
) -> Result<FileMeta> {
let range = info
.file_metadata
.as_ref()
.and_then(|footer| extract_primary_key_range(footer, &self.target.metadata));
Ok(FileMeta {
region_id: self.target.metadata.region_id,
file_id: info.file_id,
time_range: info.time_range,
// Region-local L0: window merges and semantic folding stay with
// ordinary region compaction.
level: 0,
file_size: info.file_size,
max_row_group_uncompressed_size: info.max_row_group_uncompressed_size,
max_row_group_decoded_size: info.max_row_group_decoded_size,
available_indexes: info.index_metadata.build_available_indexes(),
indexes: info.index_metadata.build_indexes()?,
index_file_size: info.index_metadata.file_size,
index_version: 0,
num_rows: info.num_rows as u64,
num_row_groups: info.num_row_groups,
sequence: self.sequence,
partition_expr: partition_expr.map(Into::into),
num_series: info.num_series,
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,
row_sequence_provenance: (self.proved_row_sequences
&& matches!(&info.format, FileFormat::Parquet))
.then_some(RowSequenceProvenance::Original),
format: info.format.clone(),
})
}
}
fn cancellable_source(mut source: FlatSource, cancellation: CancellationToken) -> FlatSource {
let schema = source.schema().clone();
let stream = async_stream::try_stream! {
while let Some(batch) = source.next_batch().await? {
if cancellation.is_cancelled() { Err(crate::error::CompactionCancelledSnafu.build())?; }
yield batch;
}
};
FlatSource::new_stream(schema, Box::pin(stream))
}
+1 -2
View File
@@ -27,7 +27,7 @@ use crate::compaction::window::WindowedCompactionPicker;
use crate::compaction::{CompactionOutput, SerializedCompactionOutput};
use crate::error::Result;
use crate::region::options::{CompactionOptions, MergeMode, RegionOptions};
use crate::sst::file::{self, FileHandle, FileMeta};
use crate::sst::file::{FileHandle, FileMeta};
use crate::sst::file_purger::FilePurger;
use crate::sst::version::LevelMeta;
@@ -188,7 +188,6 @@ pub(super) fn get_expired_ssts(
levels
.iter()
.filter(|level| level.level < file::LEVEL_SHARED)
.flat_map(|l| l.get_expired_files(&now, &ttl).into_iter())
.collect()
}
+3 -8
View File
@@ -41,7 +41,7 @@ use crate::compaction::twcs::units::{ClosedMergeOptions, PickLimits};
use crate::error::{JoinSnafu, Result};
use crate::metrics::{TWCS_PICK_ELAPSED, TWCS_SCANNED_WINDOWS};
use crate::region::options::MergeMode;
use crate::sst::file::{self, FileHandle, Level, overlaps};
use crate::sst::file::{FileHandle, Level, overlaps};
use crate::sst::primary_key::PrimaryKeyRangeMapper;
use crate::sst::version::LevelMeta;
@@ -394,11 +394,7 @@ impl TwcsPicker {
} = *context;
// Shared files remain in the window map for overlap/tombstone safety,
// but only the table executor may rewrite them.
let mut files: Vec<_> = window
.files()
.filter(|file| file.level() < file::LEVEL_SHARED)
.cloned()
.collect();
let mut files: Vec<_> = window.files().cloned().collect();
let quiet = is_quiet_window(&files, region_sequence);
// Filter out large files in append mode - they won't benefit from compaction
@@ -1161,8 +1157,7 @@ impl TwcsPicker {
// Compute activity from the candidate files so expired or
// compacting files cannot identify a window absent from `windows`.
let active_window = find_active_window_by_sequence(
windows.values().flat_map(Window::files)
.filter(|file| file.level() < file::LEVEL_SHARED),
windows.values().flat_map(Window::files),
time_window_size,
)
.or_else(|| {
+3 -7
View File
@@ -30,7 +30,7 @@ use crate::compaction::last_non_null::inputs_precede_memtables;
use crate::compaction::picker::{Picker, PickerOutput, get_expired_ssts};
use crate::error::{JoinSnafu, Result};
use crate::region::options::{CompactionOptions, MergeMode};
use crate::sst::file::{self, FileHandle};
use crate::sst::file::FileHandle;
/// Compaction picker that splits input files into disjoint time windows and merges the
/// segments within each window. Outputs may be split further by the configured file size
@@ -115,9 +115,7 @@ impl WindowedCompactionPicker {
.iter()
.flat_map(|level| level.files.values())
.filter(|file| !expired_file_ids.contains(&file.file_id()))
.filter(|file| {
last_non_null || (!file.compacting() && file.level() < file::LEVEL_SHARED)
}),
.filter(|file| last_non_null || !file.compacting()),
);
let windows = filter_time_windows(windows, self.time_range);
@@ -125,9 +123,7 @@ impl WindowedCompactionPicker {
// would remove that SST without rewriting all its remaining segments.
if last_non_null
&& windows.values().any(|(_, inputs)| {
inputs
.iter()
.any(|file| file.compacting() || file.level() == file::LEVEL_SHARED)
inputs.iter().any(|file| file.compacting())
|| !inputs_precede_memtables(inputs, current_version.memtable_min_sequence)
})
{
-4
View File
@@ -82,15 +82,11 @@ mod sequence_test;
#[cfg(test)]
mod set_role_state_test;
#[cfg(test)]
mod shared_file_test;
#[cfg(test)]
mod skip_wal_test;
#[cfg(test)]
mod staging_test;
#[cfg(test)]
mod sync_test;
#[cfg(feature = "enterprise")]
pub mod table_compaction;
#[cfg(test)]
mod tail_replay_test;
#[cfg(test)]
@@ -28,230 +28,6 @@ use crate::config::MitoConfig;
use crate::error::Error;
use crate::test_util::{CreateRequestBuilder, TestEnv, build_rows, put_rows, rows_schema};
#[cfg(feature = "enterprise")]
#[rstest::rstest]
#[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,
#[case] trusted_shared: bool,
) {
use crate::manifest::action::RegionEdit;
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;
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
schedule_compaction_after_edit: false,
..Default::default()
})
.await;
let owner_id = RegionId::new(1, 0);
let source_id = RegionId::new(1, 1);
let target_id = RegionId::new(1, 2);
let path_type = if metadata {
PathType::Metadata
} else {
PathType::Bare
};
let mut create = CreateRequestBuilder::new().build();
create.path_type = path_type;
for id in [owner_id, source_id, target_id] {
engine
.handle_request(id, RegionRequest::Create(create.clone()))
.await
.unwrap();
}
for (id, start) in [(owner_id, 0), (source_id, 10)] {
if id == source_id && !mixed {
continue;
}
put_rows(
&engine,
id,
Rows {
schema: rows_schema(&create),
rows: build_rows(start, start + 3),
},
)
.await;
flush_region(&engine, id, None).await;
}
let owner = engine.get_region(owner_id).unwrap();
let shared = FileMeta {
level: LEVEL_SHARED,
..owner.version().ssts.levels()[0]
.files()
.next()
.unwrap()
.meta_ref()
.clone()
};
for id in [owner_id, source_id] {
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)
.unwrap()
.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| {
crate::sst::location::sst_file_path(
target.access_layer.table_dir(),
RegionFileId::new(target_id, file_id),
path_type,
)
};
let result = engine
.copy_region_from(
target_id,
MitoCopyRegionFromRequest {
source_region_id: source_id,
parallelism: 1,
},
)
.await;
if metadata {
assert!(matches!(result, Err(Error::InvalidRequest { .. })));
let after = target.manifest_ctx.manifest().await;
assert_eq!(before.manifest_version, after.manifest_version);
assert_eq!(before.files, after.files);
assert_eq!(0, target.version_control.current().last_sequence);
for id in source.files.keys() {
assert!(
!target
.access_layer
.object_store()
.exists(&target_path(*id))
.await
.unwrap()
);
}
return;
}
let expected_ids = source.files.keys().copied().collect::<HashSet<_>>();
assert_eq!(
expected_ids,
result
.unwrap()
.copied_file_ids
.into_iter()
.collect::<HashSet<_>>()
);
let installed = target.manifest_ctx.manifest().await;
assert_eq!(
expected_ids,
installed.files.keys().copied().collect::<HashSet<_>>()
);
for file in installed.files.values() {
assert_eq!(
if file.level == LEVEL_SHARED {
owner_id
} else {
target_id
},
file.region_id
);
assert_eq!(
file.level != LEVEL_SHARED,
target
.access_layer
.object_store()
.exists(&target_path(file.file_id))
.await
.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
.copy_region_from(
target_id,
MitoCopyRegionFromRequest {
source_region_id: source_id,
parallelism: 1,
},
)
.await
.unwrap();
assert_eq!(
expected_ids,
retry.copied_file_ids.into_iter().collect::<HashSet<_>>()
);
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())
.await
.unwrap(),
)
.await
.unwrap();
assert_eq!(
if mixed { 6 } else { 3 },
rows.iter().map(|batch| batch.num_rows()).sum::<usize>()
);
}
/// A physical copy relabels the bytes under a new creator, so the target inherits no proof of the
/// numbers inside them: the copy states nothing about the numbering it carries.
#[tokio::test]
+1 -5
View File
@@ -459,11 +459,7 @@ async fn narthex_import_preloads_all_parts_from_the_physical_owner() {
let owner = RegionId::new(1024, 1);
let file = FileMeta {
region_id: owner,
level: if cfg!(feature = "enterprise") {
crate::sst::file::LEVEL_SHARED
} else {
0
},
level: 0,
file_id: FileId::random(),
file_size: 10,
format: crate::sst::file::FileFormat::NarthexSamples(Box::new(
+7 -46
View File
@@ -137,11 +137,11 @@
//! owns the write lock, drops it, and *then* fires the receipt — the hook must
//! never run under the lock. [`ManifestContext::update_manifest`] is the common
//! case: it acquires the lock, delegates to `update_locked`, and fires the
//! receipt in one go. The role-state backfill and the table-compaction publication
//! call `update_locked` directly under their own held guard; a replay of pending
//! tails makes the same write without the Leader lease check, the end of
//! staging builds its receipt in `commit_staged_locked`, and the edit of a catchup
//! builds its receipt in [`ManifestContext::commit_catchup_locked`].
//! receipt in one go. The role-state backfill calls `update_locked` directly
//! under its own held guard; a replay of pending tails makes the same write
//! without the Leader lease check, the end of staging builds its receipt in
//! `commit_staged_locked`, and the edit of a catchup builds its receipt in
//! [`ManifestContext::commit_catchup_locked`].
//!
//! Non-logical writes (GC, staging bookkeeping) call the manager's own methods
//! directly and intentionally do not fire the hook.
@@ -168,20 +168,18 @@
//! [`ManifestContext::update_manifest`]: crate::region::ManifestContext::update_manifest
//! [`ManifestContext::commit_catchup_locked`]: crate::region::ManifestContext::commit_catchup_locked
use std::collections::HashSet;
use std::fmt::Debug;
use std::sync::Arc;
use async_trait::async_trait;
use parquet::file::metadata::ParquetMetaData;
use store_api::ManifestVersion;
use store_api::metadata::RegionMetadataRef;
use store_api::storage::RegionId;
use crate::access_layer::{AccessLayer, AccessLayerRef};
use crate::access_layer::AccessLayerRef;
use crate::error::Result;
use crate::manifest::action::{RegionMetaActionList, RemovedFile};
use crate::sst::file::{FileMeta, RegionFileId};
use crate::sst::file::FileMeta;
use crate::sst::parquet::SstInfo;
/// A deferred [`RegionHook::on_manifest_updated`] notification produced by a
@@ -287,13 +285,6 @@ pub struct SstFileInfo<'a> {
pub file_meta: &'a FileMeta,
}
/// Externally produced SST with its verified footer. Index-builder statistics
/// are deliberately absent: they cannot be reconstructed from FileMeta.
pub struct VerifiedSstFileInfo<'a> {
pub file_meta: &'a FileMeta,
pub footer: &'a Arc<ParquetMetaData>,
}
/// Hook for observing region mutations in mito2.
///
/// Implementations can be registered via the `Plugins` system:
@@ -326,36 +317,6 @@ pub trait RegionHook: Send + Sync + Debug {
let _ = (region_id, region_metadata, files);
}
/// Queries durable file protections immediately before deletion. Implementations
/// must include pending uploads, inputs and undecided outputs, and fail on
/// unavailable/uncertain state. File identities are scoped by the access layer's
/// storage, table directory and PathType; protection covers all index generations.
/// GC rechecks the manifest after this await. This is not `on_region_gc`, which
/// is too late to protect anything. Calls must not retain a manifest lock.
async fn protected_sst_files(
&self,
access: &AccessLayer,
files: &[RegionFileId],
) -> Result<HashSet<RegionFileId>> {
let _ = (access, files);
Ok(HashSet::new())
}
/// Called for verified table-compaction outputs before manifest publication.
/// Unlike `on_sst_files_written`, this carries actual remote footers without
/// fabricating unavailable index-builder statistics. Retries may repeat it;
/// no manifest lock is held and implementations must be idempotent. Publication
/// may still fail after this callback; it is not a publication acknowledgement.
/// Use `on_manifest_updated` to observe a successful manifest commit.
async fn on_sst_files_verified(
&self,
region_id: RegionId,
region_metadata: &RegionMetadataRef,
files: &[VerifiedSstFileInfo<'_>],
) {
let _ = (region_id, region_metadata, files);
}
/// Called after the region manifest is successfully committed to the **live**
/// (normal) manifest directory.
///
-508
View File
@@ -1,508 +0,0 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(feature = "enterprise")]
use std::collections::HashMap;
use store_api::region_engine::RegionEngine;
use store_api::region_request::RegionRequest;
use store_api::storage::{FileId, RegionId};
use crate::config::MitoConfig;
use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList};
use crate::sst::file::{FileMeta, LEVEL_SHARED, SHARED_LEVEL_SLOT};
use crate::test_util::{CreateRequestBuilder, TestEnv};
#[tokio::test]
async fn test_shared_import_preserves_visible_sequence_and_rejects_overwrite() {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
schedule_compaction_after_edit: false,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
engine
.handle_request(
region_id,
RegionRequest::Create(CreateRequestBuilder::new().build()),
)
.await
.unwrap();
let region = engine.get_region(region_id).unwrap();
let source = FileMeta {
region_id: RegionId::new(1, 0),
file_id: FileId::random(),
level: LEVEL_SHARED,
..Default::default()
};
let import = RegionEdit {
files_to_add: vec![source.clone()],
..Default::default()
};
let first = engine.edit_region(region_id, import.clone()).await;
if !cfg!(feature = "enterprise") {
assert!(first.is_err());
assert!(
region.version().ssts.levels()[SHARED_LEVEL_SLOT]
.files
.is_empty()
);
return;
}
first.unwrap();
let admitted = region.version().ssts.levels()[SHARED_LEVEL_SLOT].files[&source.file_id]
.meta_ref()
.clone();
assert_eq!(source.file_id(), admitted.file_id());
assert_eq!(Some(1), admitted.sequence.map(|s| s.get()));
engine.edit_region(region_id, import).await.unwrap();
assert_eq!(1, region.version_control.current().last_sequence);
assert_eq!(
&admitted,
region.version().ssts.levels()[SHARED_LEVEL_SLOT].files[&source.file_id].meta_ref()
);
let manifest_version = region.manifest_ctx.manifest_version().await;
let changed = FileMeta {
num_rows: 1,
..admitted.clone()
};
assert!(
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![changed],
..Default::default()
}
)
.await
.is_err()
);
assert!(
engine
.edit_region(
region_id,
RegionEdit {
files_to_remove: vec![admitted.clone()],
..Default::default()
}
)
.await
.is_err()
);
// A plan captured before a file became shared must also fail at publication,
// even if it bypasses the import queue and still calls the ordinary L0 path.
let stale = FileMeta {
level: 0,
..admitted
};
assert!(
region
.manifest_ctx
.update_manifest_for_compaction(RegionMetaActionList::with_action(
RegionMetaAction::Edit(RegionEdit {
files_to_remove: vec![stale],
..Default::default()
})
))
.await
.is_err()
);
assert_eq!(
manifest_version,
region.manifest_ctx.manifest_version().await
);
assert_eq!(1, region.version_control.current().last_sequence);
}
#[cfg(feature = "enterprise")]
#[tokio::test]
async fn test_shared_reclassification_requires_add_only() {
use api::v1::Rows;
use common_recordbatch::RecordBatches;
use crate::test_util::{build_rows, flush_region, put_rows, reopen_region, rows_schema};
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
schedule_compaction_after_edit: false,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let create = CreateRequestBuilder::new().build();
engine
.handle_request(region_id, RegionRequest::Create(create.clone()))
.await
.unwrap();
put_rows(
&engine,
region_id,
Rows {
schema: rows_schema(&create),
rows: build_rows(0, 3),
},
)
.await;
flush_region(&engine, region_id, None).await;
let scan = || async {
RecordBatches::try_collect(
engine
.scan_to_stream(region_id, Default::default())
.await
.unwrap(),
)
.await
.unwrap()
.pretty_print()
.unwrap()
};
let expected_rows = scan().await;
let region = engine.get_region(region_id).unwrap();
let before = region.manifest_ctx.manifest().await;
let sequence = region.version_control.current().last_sequence;
let source = region.version().ssts.levels()[0]
.files()
.next()
.unwrap()
.meta_ref()
.clone();
let shared = FileMeta {
level: LEVEL_SHARED,
..source.clone()
};
let invalid = RegionEdit {
files_to_add: vec![shared.clone()],
files_to_remove: vec![source.clone()],
..Default::default()
};
assert!(
engine
.edit_region(region_id, invalid.clone())
.await
.is_err()
);
// The final manifest guard must also reject callers that bypass admission.
let error = region
.manifest_ctx
.update_manifest_for_compaction(RegionMetaActionList::with_action(RegionMetaAction::Edit(
invalid,
)))
.await
.unwrap_err();
assert!(matches!(error, crate::error::Error::InvalidRequest { .. }));
let unchanged = region.manifest_ctx.manifest().await;
assert_eq!(before.manifest_version, unchanged.manifest_version);
assert_eq!(before.files, unchanged.files);
assert_eq!(sequence, region.version_control.current().last_sequence);
assert!(std::sync::Arc::ptr_eq(
&region,
&engine.get_region(region_id).unwrap()
));
assert_eq!(
&source,
region.version().ssts.levels()[0].files[&source.file_id].meta_ref()
);
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![shared],
..Default::default()
},
)
.await
.unwrap();
let installed = region.manifest_ctx.manifest().await;
assert_eq!(LEVEL_SHARED, installed.files[&source.file_id].level);
assert!(region.version().ssts.levels()[0].files.is_empty());
assert_eq!(
installed.files[&source.file_id].as_ref(),
region.version().ssts.levels()[SHARED_LEVEL_SLOT].files[&source.file_id].meta_ref()
);
reopen_region(
&engine,
region_id,
create.table_dir,
true,
Default::default(),
)
.await;
let reopened = engine.get_region(region_id).unwrap();
assert_eq!(
installed.files,
reopened.manifest_ctx.manifest().await.files
);
assert!(reopened.version().ssts.levels()[0].files.is_empty());
assert_eq!(
installed.files[&source.file_id].as_ref(),
reopened.version().ssts.levels()[SHARED_LEVEL_SLOT].files[&source.file_id].meta_ref()
);
assert_eq!(expected_rows, scan().await);
}
#[cfg(feature = "enterprise")]
#[tokio::test]
async fn test_shared_adoption_rejects_existing_l1_reference() {
use api::v1::Rows;
use crate::test_util::{build_rows, flush_region, put_rows, rows_schema};
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
schedule_compaction_after_edit: false,
..Default::default()
})
.await;
let region_id = RegionId::new(1, 1);
let create = CreateRequestBuilder::new().build();
engine
.handle_request(region_id, RegionRequest::Create(create.clone()))
.await
.unwrap();
put_rows(
&engine,
region_id,
Rows {
schema: rows_schema(&create),
rows: build_rows(0, 3),
},
)
.await;
flush_region(&engine, region_id, None).await;
let region = engine.get_region(region_id).unwrap();
let source = region.version().ssts.levels()[0]
.files()
.next()
.unwrap()
.meta_ref()
.clone();
// Install the same FileId as an ordinary L1 reference. The manifest is
// keyed by FileId, so this leaves the file classified as L1.
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![FileMeta {
level: 1,
..source.clone()
}],
..Default::default()
},
)
.await
.unwrap();
assert_eq!(
1,
engine
.get_region(region_id)
.unwrap()
.manifest_ctx
.manifest()
.await
.files[&source.file_id]
.level
);
let region = engine.get_region(region_id).unwrap();
let before = region.manifest_ctx.manifest().await;
let sequence = region.version_control.current().last_sequence;
let shared = FileMeta {
level: LEVEL_SHARED,
..source.clone()
};
let error = engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![shared],
..Default::default()
},
)
.await
.unwrap_err();
assert!(matches!(
error,
crate::error::Error::EditRegion { source, .. }
if matches!(*source, crate::error::Error::InvalidRequest { .. })
));
let unchanged = region.manifest_ctx.manifest().await;
assert_eq!(before.manifest_version, unchanged.manifest_version);
assert_eq!(before.files, unchanged.files);
assert_eq!(1, unchanged.files[&source.file_id].level);
assert_eq!(sequence, region.version_control.current().last_sequence);
assert!(std::sync::Arc::ptr_eq(
&region,
&engine.get_region(region_id).unwrap()
));
}
#[cfg(feature = "enterprise")]
#[rstest::rstest]
#[case::all(true)]
#[case::time_range(false)]
#[tokio::test]
async fn test_truncate_shared_references_preserves_other_readers(#[case] truncate_all: bool) {
use api::v1::Rows;
use common_recordbatch::RecordBatches;
use common_time::Timestamp;
use store_api::region_request::RegionTruncateRequest;
use crate::test_util::{build_rows, flush_region, put_rows, reopen_region, rows_schema};
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
schedule_compaction_after_edit: false,
..Default::default()
})
.await;
let owner_id = RegionId::new(1, 0);
let target_id = RegionId::new(1, 1);
let other_id = RegionId::new(1, 2);
let create = CreateRequestBuilder::new().build();
for id in [owner_id, target_id, other_id] {
engine
.handle_request(id, RegionRequest::Create(create.clone()))
.await
.unwrap();
}
for start in [0, 10] {
put_rows(
&engine,
owner_id,
Rows {
schema: rows_schema(&create),
rows: build_rows(start, start + 3),
},
)
.await;
flush_region(&engine, owner_id, None).await;
}
let owner = engine.get_region(owner_id).unwrap();
let shared_files = owner.version().ssts.levels()[0]
.files()
.map(|file| FileMeta {
level: LEVEL_SHARED,
..file.meta_ref().clone()
})
.collect::<Vec<_>>();
assert_eq!(2, shared_files.len());
for id in [owner_id, target_id, other_id] {
engine
.edit_region(
id,
RegionEdit {
files_to_add: shared_files.clone(),
..Default::default()
},
)
.await
.unwrap();
}
let target = engine.get_region(target_id).unwrap();
let before = target.manifest_ctx.manifest().await;
let expected = before
.files
.iter()
.filter(|(_, file)| !truncate_all && file.time_range.0 > Timestamp::new_millisecond(5_000))
.map(|(id, file)| (*id, file.clone()))
.collect::<std::collections::HashMap<_, _>>();
// Pin an actual query before the DDL, not just a copy of its file metadata.
let old_reader = engine
.scan_to_stream(target_id, Default::default())
.await
.unwrap();
let request = if truncate_all {
RegionTruncateRequest::All
} else {
RegionTruncateRequest::ByTimeRanges {
time_ranges: vec![(
Timestamp::new_millisecond(0),
Timestamp::new_millisecond(5_000),
)],
}
};
engine
.handle_request(target_id, RegionRequest::Truncate(request))
.await
.unwrap();
assert_eq!(expected, target.manifest_ctx.manifest().await.files);
let visible = target.version().ssts.levels()[SHARED_LEVEL_SLOT]
.files()
.map(|file| (file.file_id().file_id(), file.meta_ref().clone()))
.collect::<std::collections::HashMap<_, _>>();
assert_eq!(
expected
.iter()
.map(|(id, meta)| (*id, meta.as_ref().clone()))
.collect::<HashMap<_, _>>(),
visible
);
let old_rows = RecordBatches::try_collect(old_reader).await.unwrap();
assert_eq!(
6,
old_rows.iter().map(|batch| batch.num_rows()).sum::<usize>()
);
reopen_region(
&engine,
target_id,
create.table_dir,
true,
Default::default(),
)
.await;
assert_eq!(
expected,
engine
.get_region(target_id)
.unwrap()
.manifest_ctx
.manifest()
.await
.files
);
for (id, expected_rows) in [(target_id, if truncate_all { 0 } else { 3 }), (other_id, 6)] {
let rows = RecordBatches::try_collect(
engine.scan_to_stream(id, Default::default()).await.unwrap(),
)
.await
.unwrap();
assert_eq!(
expected_rows,
rows.iter().map(|batch| batch.num_rows()).sum::<usize>()
);
}
for file in shared_files {
let path = crate::sst::location::sst_file_path(
owner.access_layer.table_dir(),
file.file_id(),
owner.access_layer.path_type(),
);
assert!(
owner
.access_layer
.object_store()
.exists(&path)
.await
.unwrap()
);
}
}
-151
View File
@@ -1,151 +0,0 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
//! One-shot publication of already-admitted shared inputs. Task tracking is external.
pub(crate) mod output;
#[cfg(test)]
mod tests;
use serde::{Deserialize, Serialize};
use snafu::{OptionExt, ResultExt, ensure};
use store_api::metadata::{RegionMetadata, RegionMetadataRef};
use store_api::storage::RegionId;
use tokio::sync::oneshot;
use crate::engine::MitoEngine;
use crate::error::{
Error, InvalidRequestSnafu, RecvSnafu, RegionBusySnafu, RegionNotFoundSnafu, Result,
SerdeJsonSnafu,
};
use crate::manifest::action::RegionEdit;
use crate::region::options::RegionOptions;
use crate::region::{RegionLeaderState, RegionRoleState};
use crate::request::{RegionEditKind, RegionEditRequest, WorkerRequest};
use crate::sst::file::{FileMeta, SHARED_LEVEL_SLOT};
/// A query-visible input snapshot. Callers may select a subset of `inputs` for a job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableCompactionSnapshot {
pub metadata: RegionMetadataRef,
pub options: serde_json::Value,
pub inputs: Vec<FileMeta>,
}
/// Transient publication preconditions, never stored in a manifest.
#[derive(Debug)]
pub(crate) struct PublicationContext {
pub metadata: RegionMetadataRef,
pub options: RegionOptions,
}
/// A result for this publication attempt, not a durable task receipt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PublicationOutcome {
/// This attempt installed the replacement, or its nonempty outputs are still fully visible
/// with all of its inputs absent.
Applied,
/// The schema or file set no longer matches this publication. Re-snapshot and replan.
StaleInputs,
}
/// Returns whether both snapshots describe the same table-compaction target range.
/// ALTER may change the schema while compaction runs. Publication verifies the
/// output footer against the captured schema and checks the input files separately.
pub fn is_table_compaction_metadata_compatible(
captured: &RegionMetadata,
current: &RegionMetadata,
) -> bool {
captured.region_id == current.region_id
&& captured.partition_expr_version == current.partition_expr_version
&& captured.partition_expr == current.partition_expr
}
impl MitoEngine {
/// Reads committed inputs while an ordinary edit or ALTER is in progress.
pub fn table_compaction_snapshot(
&self,
region_id: RegionId,
) -> Result<TableCompactionSnapshot> {
let region = self
.find_region(region_id)
.context(RegionNotFoundSnafu { region_id })?;
ensure!(
match region.state() {
RegionRoleState::Leader(
RegionLeaderState::Writable | RegionLeaderState::Altering,
) => true,
RegionRoleState::Leader(RegionLeaderState::Editing) =>
region.manifest_ctx.staging_partition_info().is_none(),
_ => false,
},
RegionBusySnafu { region_id }
);
let current = region.version_control.current();
Ok(TableCompactionSnapshot {
metadata: current.version.metadata.clone(),
options: serde_json::to_value(&current.version.options).context(SerdeJsonSnafu)?,
inputs: current.version.ssts.levels()[SHARED_LEVEL_SLOT]
.files()
.map(|file| file.meta_ref().clone())
.collect(),
})
}
/// Publishes one region independently, using compaction rather than import sequences.
///
/// Duplicate submissions are allowed. A stale outcome does NOT prove these
/// outputs were never published (an earlier ACK may have been lost). Never
/// blindly delete outputs on stale/error: keep their protection until recovery
/// or manifest-aware GC determines liveness. No input registration is performed.
/// Input admission must be complete/quiescent; a compaction retry must not replay
/// imports. The caller must produce a logically equivalent replacement under this snapshot.
pub async fn publish_table_compaction(
&self,
region_id: RegionId,
snapshot: TableCompactionSnapshot,
outputs: Vec<FileMeta>,
) -> Result<PublicationOutcome> {
ensure!(
snapshot.metadata.region_id == region_id && !snapshot.inputs.is_empty(),
InvalidRequestSnafu {
region_id,
reason: "Publication requires this region's nonempty input snapshot"
}
);
let options = serde_json::from_value(snapshot.options).context(SerdeJsonSnafu)?;
let edit = RegionEdit {
files_to_remove: snapshot.inputs,
files_to_add: outputs,
timestamp_ms: Some(chrono::Utc::now().timestamp_millis()),
..Default::default()
};
let (tx, rx) = oneshot::channel();
let mut request = RegionEditRequest::new(region_id, edit, false, tx);
request.kind = RegionEditKind::Compaction(Box::new(PublicationContext {
metadata: snapshot.metadata,
options,
}));
self.inner
.workers
.submit_to_worker(region_id, WorkerRequest::EditRegion(request))
.await?;
match rx.await.context(RecvSnafu)? {
Ok(()) => Ok(PublicationOutcome::Applied),
Err(Error::EditRegion { source, .. })
if matches!(source.as_ref(), Error::StaleCompactionExecution { .. }) =>
{
Ok(PublicationOutcome::StaleInputs)
}
Err(error) => Err(error),
}
}
}
@@ -1,200 +0,0 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
use std::sync::Arc;
use parquet::file::metadata::ParquetMetaData;
use parquet::file::statistics::Statistics;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::metadata::RegionMetadataRef;
use crate::access_layer::AccessLayer;
use crate::cache::CachedSstMeta;
use crate::engine::region_hook::VerifiedSstFileInfo;
use crate::error::{InvalidRequestSnafu, OpenDalSnafu, Result};
use crate::region::MitoRegionRef;
use crate::sst::file::FileMeta;
use crate::sst::location;
use crate::sst::parquet::metadata::{MetadataLoader, extract_primary_key_range};
use crate::sst::parquet::{max_row_group_decoded_size, max_row_group_uncompressed_size};
/// Verifies every output, then notifies the region hook once if one is registered.
///
/// Without a hook no footer is needed after its own verification, so each one is
/// dropped before the next output is read. With a hook every footer is kept until
/// all outputs verify, because the hook observes them in one call; footers are then
/// released when this returns, before the caller takes the manifest lock. A failed
/// verification notifies nothing.
pub(crate) async fn verify_and_notify(
region: &MitoRegionRef,
metadata: &RegionMetadataRef,
outputs: &[FileMeta],
) -> Result<()> {
let Some(hook) = region.manifest_ctx.hook() else {
for file in outputs {
verify_file(&region.access_layer, metadata, file).await?;
}
return Ok(());
};
let mut footers = Vec::with_capacity(outputs.len());
for file in outputs {
footers.push(verify_file(&region.access_layer, metadata, file).await?);
}
let verified = outputs
.iter()
.zip(&footers)
.map(|(file_meta, footer)| VerifiedSstFileInfo { file_meta, footer })
.collect::<Vec<_>>();
hook.on_sst_files_verified(region.region_id, metadata, &verified)
.await;
Ok(())
}
async fn verify_file(
access: &AccessLayer,
metadata: &RegionMetadataRef,
file: &FileMeta,
) -> Result<Arc<ParquetMetaData>> {
let region_id = metadata.region_id;
let path = location::sst_file_path(access.table_dir(), file.file_id(), access.path_type());
let size = access
.object_store()
.stat(&path)
.await
.context(OpenDalSnafu)?
.content_length();
ensure!(
size == file.file_size,
InvalidRequestSnafu {
region_id,
reason: "Output SST size mismatch"
}
);
let footer = MetadataLoader::new(access.object_store().clone(), &path, size)
.load(&mut Default::default())
.await?;
let cached = CachedSstMeta::try_new_with_region_metadata(&path, footer, None)?;
ensure!(
cached.region_metadata() == *metadata,
InvalidRequestSnafu {
region_id,
reason: "Output footer schema or partition mismatch"
}
);
let footer = cached.parquet_metadata();
verify_statistics(&footer, metadata, file)?;
if file.index_file_size > 0 {
let path =
location::index_file_path(access.table_dir(), file.index_id(), access.path_type());
let index_size = access
.object_store()
.stat(&path)
.await
.context(OpenDalSnafu)?
.content_length();
ensure!(
index_size == file.index_file_size,
InvalidRequestSnafu {
region_id,
reason: "Output index size mismatch"
}
);
} else {
ensure!(
file.available_indexes.is_empty() && file.indexes.is_empty(),
InvalidRequestSnafu {
region_id,
reason: "Output advertises indexes without an index object",
}
);
}
Ok(footer)
}
fn verify_statistics(
footer: &ParquetMetaData,
metadata: &RegionMetadataRef,
file: &FileMeta,
) -> Result<()> {
let max_uncompressed = max_row_group_uncompressed_size(footer);
let pk_range = extract_primary_key_range(footer, metadata);
ensure!(
footer.file_metadata().num_rows() > 0
&& footer.file_metadata().num_rows() as u64 == file.num_rows
&& footer.num_row_groups() as u64 == file.num_row_groups
&& max_uncompressed == file.max_row_group_uncompressed_size
// Writers of older versions leave the decoded size unknown (0).
&& (file.max_row_group_decoded_size == 0
|| file.max_row_group_decoded_size == max_row_group_decoded_size(footer))
&& pk_range.as_ref().map(|range| &range.0) == file.primary_key_min.as_ref()
&& pk_range.as_ref().map(|range| &range.1) == file.primary_key_max.as_ref()
// `num_series` is the writer's caller-reported estimate derived from
// timestamp boundaries, not a footer statistic, so it only bounds the
// count against rows instead of being verified against the footer.
&& file.num_series <= file.num_rows,
InvalidRequestSnafu {
region_id: metadata.region_id,
reason: "Output statistics differ from its footer"
}
);
verify_time_range(footer, metadata, file)
}
fn verify_time_range(
footer: &ParquetMetaData,
metadata: &RegionMetadataRef,
file: &FileMeta,
) -> Result<()> {
let region_id = metadata.region_id;
let column_name = &metadata.time_index_column().column_schema.name;
let index = footer
.file_metadata()
.schema_descr()
.columns()
.iter()
.position(|column| column.path().parts().len() == 1 && column.name() == column_name)
.context(InvalidRequestSnafu {
region_id,
reason: "Output has no timestamp column",
})?;
let mut minimum = i64::MAX;
let mut maximum = i64::MIN;
for group in footer.row_groups() {
let Some(Statistics::Int64(stats)) = group.column(index).statistics() else {
return InvalidRequestSnafu {
region_id,
reason: "Output timestamp statistics missing",
}
.fail();
};
minimum = minimum.min(*stats.min_opt().context(InvalidRequestSnafu {
region_id,
reason: "Output timestamp minimum missing",
})?);
maximum = maximum.max(*stats.max_opt().context(InvalidRequestSnafu {
region_id,
reason: "Output timestamp maximum missing",
})?);
}
let unit = metadata.time_index_type().unit();
ensure!(
file.time_range.0.value() == minimum
&& file.time_range.1.value() == maximum
&& file.time_range.0.unit() == unit
&& file.time_range.1.unit() == unit,
InvalidRequestSnafu {
region_id,
reason: "Output timestamp range mismatch"
}
);
Ok(())
}
File diff suppressed because it is too large. Load diff
-41
View File
@@ -44,40 +44,6 @@ use crate::worker::WorkerId;
#[snafu(visibility(pub))]
#[stack_trace_debug]
pub enum Error {
#[cfg(feature = "enterprise")]
#[snafu(display("Failed to route multi-region compaction input"))]
RouteMultiRegion {
#[snafu(source)]
source: PartitionError,
#[snafu(implicit)]
location: Location,
},
#[cfg(feature = "enterprise")]
#[snafu(display("Invalid multi-region compaction: {reason}"))]
InvalidMultiRegionCompaction {
reason: String,
#[snafu(implicit)]
location: Location,
},
#[cfg(feature = "enterprise")]
#[snafu(display("Multi-region compaction resource limit: {reason}"))]
MultiRegionCompactionResource {
reason: String,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("SST writer {kind} needs {bytes} bytes, budget is {limit}"))]
SstWriteMemoryExceeded {
kind: &'static str,
bytes: usize,
limit: usize,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Unexpected data type"))]
DataTypeMismatch {
source: datatypes::error::Error,
@@ -1720,13 +1686,6 @@ impl ErrorExt for Error {
use Error::*;
match self {
#[cfg(feature = "enterprise")]
RouteMultiRegion { source, .. } => source.status_code(),
#[cfg(feature = "enterprise")]
InvalidMultiRegionCompaction { .. } => StatusCode::InvalidArguments,
#[cfg(feature = "enterprise")]
MultiRegionCompactionResource { .. } => StatusCode::RuntimeResourcesExhausted,
SstWriteMemoryExceeded { .. } => StatusCode::RuntimeResourcesExhausted,
DataTypeMismatch { source, .. } => source.status_code(),
OpenDal { .. }
| MetadataCopyFileNotFound { .. }
+45 -119
View File
@@ -66,6 +66,7 @@ fn should_delete_file(
is_in_tmp_ref: bool,
is_linger: bool,
is_eligible_for_delete: bool,
is_region_dropped: bool,
entry: &Entry,
unknown_file_may_linger_until: chrono::DateTime<chrono::Utc>,
) -> bool {
@@ -78,12 +79,17 @@ fn should_delete_file(
return is_eligible_for_delete;
}
// Unknown file: not in manifest, tmp refs, or known removed records. This also
// covers a directory whose manifest is gone (region dropped or not hosted here):
// there is no version to fence against, so a young object may still belong to an
// unpublished table-compaction attempt. Always require the object to be older
// than `unknown_file_lingering_time`; deleting immediately would race with an
// attempt that has not published yet.
// Unknown file: not in manifest, tmp_ref, or known removed records.
// For dropped regions, unknown files not protected by manifest/tmp refs/cross-region refs
// are deleted immediately. This relies on meta collecting FileRefsManifest from related
// active regions before issuing dropped-region GC; preserving young unknown files would
// also require keeping the table_repart tombstone for retry.
// For active/open regions, only delete if the object's last-modified time exceeds the
// unknown_file_lingering_time TTL.
if is_region_dropped {
return true;
}
entry
.metadata()
.last_modified()
@@ -93,29 +99,6 @@ fn should_delete_file(
.unwrap_or(false)
}
/// Whether an unknown (untracked) entry is withheld only by the young-object
/// rule. Such objects must be revisited later; a dropped region depends on its
/// meta tombstone to be discovered by a later GC pass at all.
fn is_deferred_unknown_file(
is_in_manifest: bool,
is_in_tmp_ref: bool,
is_linger: bool,
is_eligible_for_delete: bool,
entry: &Entry,
unknown_file_may_linger_until: chrono::DateTime<chrono::Utc>,
) -> bool {
let unknown = !is_in_manifest && !is_in_tmp_ref && !is_linger && !is_eligible_for_delete;
unknown
&& !should_delete_file(
is_in_manifest,
is_in_tmp_ref,
is_linger,
is_eligible_for_delete,
entry,
unknown_file_may_linger_until,
)
}
/// Limit the amount of concurrent GC jobs on the datanode
pub struct GcLimiter {
pub gc_job_limit: Arc<tokio::sync::Semaphore>,
@@ -360,7 +343,7 @@ impl LocalGcWorker {
.await?;
let RegionGcOutcome {
removed_files,
needs_retry,
extension_cleanup_failed,
} = outcome;
let index_files = removed_files
.iter()
@@ -373,9 +356,9 @@ impl LocalGcWorker {
RemovedFile::Index(_, _) => None,
})
.collect();
// A deferred deletion batch or failed extension cleanup must not
// acknowledge the region as fully processed.
if needs_retry {
// Don't acknowledge the region as processed until extension cleanup
// succeeds; retry it next pass instead.
if extension_cleanup_failed {
need_retry_regions.insert(*region_id);
} else {
deleted_files.insert(*region_id, data_files);
@@ -404,12 +387,15 @@ impl LocalGcWorker {
/// Per-region outcome of [`LocalGcWorker::do_region_gc`].
///
/// Unfinished deletion or extension cleanup keeps the region in the retry set.
/// `extension_cleanup_failed` records whether a registered extension's
/// [`RegionHook::on_region_gc`] could not finish; the caller must then keep the
/// region un-acknowledged (retry set) so the next GC pass replays the callback.
pub(crate) struct RegionGcOutcome {
/// Files physically deleted this pass.
pub removed_files: Vec<RemovedFile>,
/// The snapshot changed while the protection lookup ran, or extension cleanup failed.
pub needs_retry: bool,
/// `true` if a registered extension's `on_region_gc` returned `Err`; the
/// caller retries the region next pass.
pub extension_cleanup_failed: bool,
}
impl LocalGcWorker {
@@ -485,7 +471,7 @@ impl LocalGcWorker {
.inc();
return Ok(RegionGcOutcome {
removed_files: vec![],
needs_retry: false,
extension_cleanup_failed: false,
});
}
// SSTs written for pending tails but not committed yet, and SSTs of a newer
@@ -503,7 +489,7 @@ impl LocalGcWorker {
);
return Ok(RegionGcOutcome {
removed_files: vec![],
needs_retry: false,
extension_cleanup_failed: false,
});
}
Some(manifest)
@@ -561,9 +547,10 @@ impl LocalGcWorker {
.map(|file_ref| (file_ref.file_id, file_ref.index_version))
.collect::<HashSet<_>>();
let (mut deletable_files, deferred_unknown_files) = self
let deletable_files = self
.list_to_be_deleted_files(
region_id,
is_region_dropped,
&in_manifest,
&in_tmp_ref,
recently_removed_files,
@@ -571,20 +558,6 @@ impl LocalGcWorker {
)
.await?;
let mut hook_deferred_files = false;
if let Some(hook) = &self.hook {
let candidates = deletable_files
.iter()
.map(|file| RegionFileId::new(region_id, file.file_id()))
.collect::<Vec<_>>();
let protected = hook
.protected_sst_files(&self.access_layer, &candidates)
.await?;
let before_filtering = deletable_files.len();
deletable_files
.retain(|file| !protected.contains(&RegionFileId::new(region_id, file.file_id())));
hook_deferred_files = deletable_files.len() < before_filtering;
}
info!(
"gc: for region{}{region_id}: In manifest file cnt: {}, Tmp ref file cnt: {}, recently removed files: {}, Unused files to delete count: {}",
if region.is_none() {
@@ -611,33 +584,13 @@ impl LocalGcWorker {
let _delete_timer = GC_DURATION_SECONDS
.with_label_values(&["delete_files"])
.start_timer();
// The protection lookup above awaits, so a queued publication may have
// changed the region since the candidate set was computed. Recheck once
// without holding the manifest lock across remote deletion. An empty
// candidate set takes neither the lock nor the recheck.
let publication_changed = !deletable_files.is_empty()
&& if let (Some(region), Some(snapshot)) = (&region, &manifest) {
let manifest_guard = region.manifest_ctx.manifest_manager.read().await;
manifest_guard.is_stopped()
|| manifest_guard.manifest().manifest_version != snapshot.manifest_version
|| !matches!(region.state(), RegionRoleState::Leader(_))
} else {
false
};
if publication_changed {
debug!(
"gc: region {} changed during the protection lookup, deferring deletion",
region_id
);
deletable_files.clear();
} else {
self.delete_files(region_id, &deletable_files).await?;
debug!(
"Successfully deleted {} unused files for region {}",
deletable_files.len(),
region_id
);
}
self.delete_files(region_id, &deletable_files).await?;
debug!(
"Successfully deleted {} unused files for region {}",
deletable_files.len(),
region_id
);
// Notify extensions so they can clean up sidecar files. Fire when there
// are removed files, or on a full-listing pass (lets extensions reconcile
@@ -684,16 +637,9 @@ impl LocalGcWorker {
.await?;
}
// A dropped region is rediscovered only through its meta-srv tombstone.
// Young unknown objects and hook-protected candidates must keep that
// tombstone (needs_retry) until they are actually reclaimed; reporting
// success here would let the procedure drop the tombstone and leak them.
let dropped_files_deferred =
region.is_none() && (deferred_unknown_files || hook_deferred_files);
Ok(RegionGcOutcome {
removed_files: deletable_files,
needs_retry: extension_cleanup_failed || publication_changed || dropped_files_deferred,
extension_cleanup_failed,
})
}
@@ -1039,15 +985,15 @@ impl LocalGcWorker {
#[allow(clippy::too_many_arguments)]
fn filter_deletable_files(
&self,
is_region_dropped: bool,
entries: Vec<Entry>,
in_manifest: &HashMap<FileId, Option<IndexVersion>>,
in_tmp_ref: &HashSet<(FileId, Option<IndexVersion>)>,
may_linger_files: &HashSet<&RemovedFile>,
eligible_for_delete: &HashSet<&RemovedFile>,
unknown_file_may_linger_until: chrono::DateTime<chrono::Utc>,
) -> (Vec<RemovedFile>, bool) {
) -> Vec<RemovedFile> {
let mut ready_for_delete = vec![];
let mut deferred_unknown = false;
// Every index-version reader needs the same Parquet file.
let referenced_ssts: HashSet<_> = in_tmp_ref.iter().map(|(file_id, _)| *file_id).collect();
@@ -1076,19 +1022,12 @@ impl LocalGcWorker {
let in_tmp_ref = referenced_ssts.contains(&file_id);
let linger = may_linger_files.contains_key(&file_id);
let eligible = eligible_for_delete.contains_key(&file_id);
deferred_unknown |= is_deferred_unknown_file(
in_manifest,
in_tmp_ref,
linger,
eligible,
&entry,
unknown_file_may_linger_until,
);
let delete = should_delete_file(
in_manifest,
in_tmp_ref,
linger,
eligible,
is_region_dropped,
&entry,
unknown_file_may_linger_until,
);
@@ -1117,19 +1056,12 @@ impl LocalGcWorker {
let is_linger = may_linger_files.contains_key(&file_id);
let is_eligible_for_delete = eligible_for_delete.contains_key(&file_id);
deferred_unknown |= is_deferred_unknown_file(
is_in_manifest,
is_in_tmp_ref,
is_linger,
is_eligible_for_delete,
&entry,
unknown_file_may_linger_until,
);
should_delete_file(
is_in_manifest,
is_in_tmp_ref,
is_linger,
is_eligible_for_delete,
is_region_dropped,
&entry,
unknown_file_may_linger_until,
)
@@ -1146,19 +1078,12 @@ impl LocalGcWorker {
.map(|files| files.contains(&&RemovedFile::Index(file_id, version)))
.unwrap_or(false);
deferred_unknown |= is_deferred_unknown_file(
is_in_manifest,
is_in_tmp_ref,
is_linger,
is_eligible_for_delete,
&entry,
unknown_file_may_linger_until,
);
should_delete_file(
is_in_manifest,
is_in_tmp_ref,
is_linger,
is_eligible_for_delete,
is_region_dropped,
&entry,
unknown_file_may_linger_until,
)
@@ -1185,12 +1110,11 @@ impl LocalGcWorker {
.into_iter()
.filter_map(|(id, eligible)| eligible.then_some(RemovedFile::Narthex(id))),
);
(ready_for_delete, deferred_unknown)
ready_for_delete
}
/// List files to be deleted based on their presence in the manifest, temporary references, and recently removed files.
/// Returns the `RemovedFile`s that are eligible for deletion and whether any
/// unknown object was withheld by the young-object rule and needs a later pass.
/// Returns a vector of `RemovedFile` that are eligible for deletion.
///
/// When `full_file_listing` is false, this method will only delete (subset of) files tracked in
/// `recently_removed_files`, which significantly
@@ -1200,11 +1124,12 @@ impl LocalGcWorker {
pub async fn list_to_be_deleted_files(
&self,
region_id: RegionId,
is_region_dropped: bool,
in_manifest: &HashMap<FileId, Option<IndexVersion>>,
in_tmp_ref: &HashSet<(FileId, Option<IndexVersion>)>,
recently_removed_files: BTreeMap<Timestamp, HashSet<RemovedFile>>,
all_entries: Vec<Entry>,
) -> Result<(Vec<RemovedFile>, bool)> {
) -> Result<Vec<RemovedFile>> {
let now = chrono::Utc::now();
let may_linger_until = self
.opt
@@ -1278,13 +1203,14 @@ impl LocalGcWorker {
files_to_delete.len()
);
return Ok((files_to_delete, false));
return Ok(files_to_delete);
}
// Full file listing mode: get the full list of files from object store
// Step 3: Filter files to determine which ones can be deleted
let all_unused_files_ready_for_delete = self.filter_deletable_files(
is_region_dropped,
all_entries,
in_manifest,
in_tmp_ref,
+27 -388
View File
@@ -219,10 +219,11 @@ async fn test_gc_keeps_sst_across_index_versions(
.into_iter()
.map(|f| (f.file_id, f.index_version))
.collect();
let (deleted, _deferred_unknown) = env
let deleted = env
.worker
.list_to_be_deleted_files(
region_id,
false,
&HashMap::new(),
&tmp_refs,
env.removed_files.clone(),
@@ -262,10 +263,11 @@ async fn test_gc_reference_protects_parquet_and_only_its_index(
} else {
(HashMap::new(), HashSet::from([(file_id, index_version)]))
};
let (deleted, _deferred_unknown) = env
let deleted = env
.worker
.list_to_be_deleted_files(
env.meta.region_id,
false,
&manifest_refs,
&tmp_refs,
env.removed_files.clone(),
@@ -887,7 +889,7 @@ async fn test_unknown_file_within_ttl_not_deleted() {
let threshold = chrono::DateTime::from_timestamp(0, 0).unwrap();
assert!(!should_delete_file(
false, false, false, false, &entry, threshold
false, false, false, false, false, &entry, threshold
));
}
@@ -901,32 +903,21 @@ async fn test_unknown_file_exceeded_ttl_deleted() {
let threshold = chrono::Utc::now() + chrono::Duration::days(1);
assert!(should_delete_file(
false, false, false, false, &entry, threshold
false, false, false, false, false, &entry, threshold
));
}
/// Without a region manifest (dropped, or not hosted here) an unknown file must
/// still pass `unknown_file_lingering_time` instead of being deleted immediately,
/// because a young object may still belong to an unpublished table-compaction
/// attempt.
/// Unknown files in a dropped region are reclaimed immediately, regardless of age.
#[tokio::test]
async fn test_unknown_file_without_region_manifest_lingers() {
let tmp_dir = common_test_util::temp_dir::create_temp_dir("gc_no_manifest");
let root = tmp_dir.path().to_string_lossy().to_string();
let store = ObjectStore::new(services::Fs::default().root(&root)).unwrap();
let entry = write_and_list_entry(&store, "no_manifest.parquet").await;
async fn test_unknown_file_dropped_region_deleted() {
let store = ObjectStore::new(services::Memory::default()).unwrap();
let entry = write_and_list_entry(&store, "test/3.parquet").await;
let young_cutoff = chrono::DateTime::from_timestamp(0, 0).unwrap();
assert!(
!should_delete_file(false, false, false, false, &entry, young_cutoff),
"a young unknown file must be kept even without a region manifest"
);
let old_cutoff = chrono::Utc::now() + chrono::Duration::days(1);
assert!(
should_delete_file(false, false, false, false, &entry, old_cutoff),
"an unknown file older than the lingering window is reclaimed"
);
// Even with a threshold far in the past (epoch), a dropped region deletes immediately.
let threshold = chrono::DateTime::from_timestamp(0, 0).unwrap();
assert!(should_delete_file(
false, false, false, false, true, &entry, threshold
));
}
/// A live or referenced file is never deleted, even when its object is old.
@@ -939,11 +930,11 @@ async fn test_referenced_file_kept_with_old_mtime() {
let threshold = chrono::Utc::now() + chrono::Duration::days(1);
assert!(
!should_delete_file(true, false, false, false, &entry, threshold),
!should_delete_file(true, false, false, false, false, &entry, threshold),
"a file in the manifest must be kept"
);
assert!(
!should_delete_file(false, true, false, false, &entry, threshold),
!should_delete_file(false, true, false, false, false, &entry, threshold),
"a file referenced by a temporary reader must be kept"
);
}
@@ -956,11 +947,11 @@ async fn test_known_removed_file_respects_linger() {
let threshold = chrono::Utc::now() + chrono::Duration::days(1);
assert!(
!should_delete_file(false, false, true, false, &entry, threshold),
!should_delete_file(false, false, true, false, false, &entry, threshold),
"a removed file that is still lingering must be kept"
);
assert!(
should_delete_file(false, false, true, true, &entry, threshold),
should_delete_file(false, false, true, true, false, &entry, threshold),
"a removed file past its lingering period is reclaimed"
);
}
@@ -978,7 +969,7 @@ async fn test_unknown_file_at_cutoff_kept() {
.unwrap();
assert!(
!should_delete_file(false, false, false, false, &entry, threshold),
!should_delete_file(false, false, false, false, false, &entry, threshold),
"a file at the exact cutoff is kept"
);
}
@@ -1018,177 +1009,6 @@ impl RegionHook for GcCountingHook {
}
}
#[derive(Debug, Clone, Copy)]
enum ProtectionOutcome {
Protected,
Unavailable,
PublishedDuringLookup,
Unprotected,
}
#[derive(Debug)]
struct BlockingProtectionHook {
outcome: ProtectionOutcome,
entered: tokio::sync::Notify,
resume: tokio::sync::Notify,
}
#[async_trait]
impl RegionHook for BlockingProtectionHook {
async fn protected_sst_files(
&self,
_access: &crate::access_layer::AccessLayer,
files: &[crate::sst::file::RegionFileId],
) -> crate::error::Result<HashSet<crate::sst::file::RegionFileId>> {
self.entered.notify_one();
self.resume.notified().await;
match self.outcome {
ProtectionOutcome::Protected => Ok(files.iter().copied().collect()),
ProtectionOutcome::Unavailable => UnexpectedSnafu {
reason: "protection service unavailable",
}
.fail(),
_ => Ok(HashSet::new()),
}
}
}
#[rstest::rstest]
#[case::protected(ProtectionOutcome::Protected)]
#[case::unavailable(ProtectionOutcome::Unavailable)]
#[case::published(ProtectionOutcome::PublishedDuringLookup)]
#[case::unprotected(ProtectionOutcome::Unprotected)]
#[tokio::test]
async fn test_gc_protection_and_manifest_recheck(#[case] outcome: ProtectionOutcome) {
let mut env = TestEnv::new().await;
let hook = Arc::new(BlockingProtectionHook {
outcome,
entered: Default::default(),
resume: Default::default(),
});
let plugins = Plugins::new();
plugins.insert(hook.clone() as RegionHookRef);
let engine = env
.create_engine_with_plugins(
MitoConfig {
schedule_compaction_after_edit: false,
gc: GcConfig {
enable: true,
lingering_time: None,
..Default::default()
},
..Default::default()
},
plugins,
)
.await;
let region_id = RegionId::new(1, 1);
env.get_schema_metadata_manager()
.register_region_table_info(
region_id.table_id(),
"test_table",
"test_catalog",
"test_schema",
None,
env.get_kv_backend(),
)
.await;
engine
.handle_request(
region_id,
RegionRequest::Create(CreateRequestBuilder::new().build()),
)
.await
.unwrap();
let region = engine.get_region(region_id).unwrap();
let file = crate::sst::file::FileMeta {
region_id,
file_id: store_api::storage::FileId::random(),
..Default::default()
};
let path = crate::sst::location::sst_file_path(
region.access_layer.table_dir(),
file.file_id(),
region.access_layer.path_type(),
);
region
.access_layer
.object_store()
.write(&path, Bytes::from_static(b"unreferenced SST"))
.await
.unwrap();
engine
.edit_region(
region_id,
crate::manifest::action::RegionEdit {
files_to_add: vec![file.clone()],
..Default::default()
},
)
.await
.unwrap();
engine
.edit_region(
region_id,
crate::manifest::action::RegionEdit {
files_to_remove: vec![file.clone()],
..Default::default()
},
)
.await
.unwrap();
let refs = FileRefsManifest {
manifest_version: [(region_id, region.manifest_ctx.manifest_version().await)].into(),
file_refs: Default::default(),
cross_region_refs: Default::default(),
};
let worker = create_gc_worker(
&engine,
[(region_id, Some(region.clone()))].into(),
&refs,
false,
)
.await;
let temporary_refs = HashSet::new();
let (gc, ()) = tokio::join!(
worker.do_region_gc(region_id, Some(region.clone()), &temporary_refs),
async {
hook.entered.notified().await;
if matches!(outcome, ProtectionOutcome::PublishedDuringLookup) {
engine
.edit_region(
region_id,
crate::manifest::action::RegionEdit {
files_to_add: vec![file],
..Default::default()
},
)
.await
.unwrap();
}
hook.resume.notify_one();
}
);
if matches!(outcome, ProtectionOutcome::Unavailable) {
assert!(gc.is_err());
} else {
let gc = gc.unwrap();
assert_eq!(
usize::from(matches!(outcome, ProtectionOutcome::Unprotected)),
gc.removed_files.len()
);
}
assert_eq!(
!matches!(outcome, ProtectionOutcome::Unprotected),
region
.access_layer
.object_store()
.exists(&path)
.await
.unwrap()
);
}
/// `on_region_gc` is **skipped** for a live region in **fast mode** (no full
/// listing) when the GC pass deleted no files — the common case for a periodic
/// pass — to avoid unnecessary hook overhead/I/O. A freshly-flushed region has
@@ -1455,189 +1275,6 @@ async fn test_on_region_gc_fires_for_dropped_region() {
);
}
/// Protects every candidate it is asked about; used to exercise deferrals on
/// the dropped-region reclamation path.
#[derive(Debug)]
struct ProtectAllHook;
#[async_trait]
impl RegionHook for ProtectAllHook {
async fn protected_sst_files(
&self,
_access: &crate::access_layer::AccessLayer,
files: &[crate::sst::file::RegionFileId],
) -> crate::error::Result<HashSet<crate::sst::file::RegionFileId>> {
Ok(files.iter().copied().collect())
}
}
/// Shared setup: create a region with one flushed SST, then hand its access
/// layer to a dropped-region GC worker (region absent) built from `config` and
/// `hook`. Returns the worker and the region's SST/index object paths.
async fn dropped_region_gc_env(
config: GcConfig,
hook: Option<RegionHookRef>,
) -> (TestEnv, MitoEngine, LocalGcWorker, RegionId, Vec<String>) {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
schedule_compaction_after_edit: false,
gc: config,
..Default::default()
})
.await;
let region_id = RegionId::new(3, 1);
env.get_schema_metadata_manager()
.register_region_table_info(
region_id.table_id(),
"test_table",
"test_catalog",
"test_schema",
None,
env.get_kv_backend(),
)
.await;
let request = CreateRequestBuilder::new().build();
engine
.handle_request(region_id, RegionRequest::Create(request.clone()))
.await
.unwrap();
put_rows(
&engine,
region_id,
Rows {
schema: rows_schema(&request),
rows: build_rows(0, 3),
},
)
.await;
flush_region(&engine, region_id, None).await;
let region = engine.get_region(region_id).unwrap();
let access_layer = region.access_layer.clone();
let manifest = region.manifest_ctx.manifest().await;
let version = manifest.manifest_version;
let store = access_layer.object_store();
let mut paths = Vec::new();
for meta in manifest.files.values() {
for path in [
location::sst_file_path(
access_layer.table_dir(),
crate::sst::file::RegionFileId::new(meta.region_id, meta.file_id),
access_layer.path_type(),
),
location::index_file_path(
access_layer.table_dir(),
meta.index_id(),
access_layer.path_type(),
),
] {
if store.exists(&path).await.unwrap() {
paths.push(path);
}
}
}
assert!(!paths.is_empty(), "the flushed SST objects must be listed");
let file_ref_manifest = FileRefsManifest {
file_refs: Default::default(),
manifest_version: [(region_id, version)].into(),
cross_region_refs: HashMap::new(),
};
let worker = LocalGcWorker::try_new(
access_layer,
Some(engine.cache_manager()),
BTreeMap::from([(region_id, None)]),
engine.mito_config().gc.clone(),
file_ref_manifest,
&engine.gc_limiter(),
true,
hook,
)
.await
.unwrap();
// Keep the env (and its data-home TempDir) alive for the caller: dropping
// it removes the on-disk objects that the dropped-region pass must list.
(env, engine, worker, region_id, paths)
}
/// A dropped region's young unknown objects are deferred by
/// `unknown_file_lingering_time`; the pass must report `needs_retry` so the
/// meta tombstone survives and a later pass can reclaim them.
#[tokio::test]
async fn test_dropped_region_young_unknown_files_need_retry() {
init_default_ut_logging();
let (_env, _engine, worker, region_id, paths) = dropped_region_gc_env(
GcConfig {
enable: true,
..Default::default()
},
None,
)
.await;
let outcome = worker
.do_region_gc(region_id, None, &HashSet::new())
.await
.unwrap();
assert!(outcome.removed_files.is_empty());
assert!(
outcome.needs_retry,
"deferred young unknown objects must keep the dropped-region tombstone"
);
let store = worker.access_layer.object_store();
for path in &paths {
assert!(store.exists(path).await.unwrap(), "{path} must survive");
}
}
/// Hook-protected candidates on a dropped region must also keep the tombstone;
/// once nothing defers the pass any longer the report clears so the procedure
/// can drop the tombstone.
#[tokio::test]
async fn test_dropped_region_hook_deferral_needs_retry_until_reclaimed() {
init_default_ut_logging();
let config = GcConfig {
enable: true,
lingering_time: None,
unknown_file_lingering_time: std::time::Duration::ZERO,
..Default::default()
};
let (_env, _engine, worker, region_id, paths) =
dropped_region_gc_env(config.clone(), Some(Arc::new(ProtectAllHook))).await;
let store = worker.access_layer.object_store();
let protected = worker
.do_region_gc(region_id, None, &HashSet::new())
.await
.unwrap();
assert!(protected.removed_files.is_empty());
assert!(
protected.needs_retry,
"hook-deferred candidates must keep the dropped-region tombstone"
);
for path in &paths {
assert!(store.exists(path).await.unwrap(), "{path} must survive");
}
// Nothing defers any more: objects are old enough and no hook retains them,
// so this pass reclaims them and clears the retry flag.
let (_env, _engine, worker, region_id, paths) = dropped_region_gc_env(config, None).await;
let store = worker.access_layer.object_store();
let reclaimed = worker
.do_region_gc(region_id, None, &HashSet::new())
.await
.unwrap();
assert!(
!reclaimed.needs_retry,
"nothing defers any more, so the tombstone can be dropped"
);
assert!(!reclaimed.removed_files.is_empty());
for path in &paths {
assert!(!store.exists(path).await.unwrap(), "{path} must be gone");
}
}
/// `on_region_gc` **fires** on a full-listing pass even when mito itself deleted
/// no files, so an extension can reconcile sidecar-only orphans (failed writes,
/// leftovers from a previous cleanup). Contrast with the fast-mode skip in
@@ -1931,7 +1568,8 @@ async fn test_narthex_artifact_gc_inventory_and_references() {
(HashMap::from([(id, None)]), HashSet::new()),
(HashMap::new(), HashSet::from([(id, None)])),
] {
let (delete, _) = env.worker.filter_deletable_files(
let delete = env.worker.filter_deletable_files(
false,
entries.clone(),
&manifest,
&readers,
@@ -1941,7 +1579,8 @@ async fn test_narthex_artifact_gc_inventory_and_references() {
);
assert!(delete.is_empty());
}
let (delete, _) = env.worker.filter_deletable_files(
let delete = env.worker.filter_deletable_files(
false,
entries,
&HashMap::new(),
&HashSet::new(),
@@ -1971,9 +1610,10 @@ async fn test_narthex_artifact_gc_requires_age_for_every_object() {
let unknown = write_and_list_entry(&memory, &format!("{prefix}manifest.json")).await;
let threshold = chrono::Utc::now() + chrono::Duration::days(1);
assert!(should_delete_file(
false, false, false, false, &old, threshold
false, false, false, false, false, &old, threshold
));
let (delete, deferred) = env.worker.filter_deletable_files(
let delete = env.worker.filter_deletable_files(
false,
vec![old, unknown],
&HashMap::new(),
&HashSet::new(),
@@ -1982,7 +1622,6 @@ async fn test_narthex_artifact_gc_requires_age_for_every_object() {
threshold,
);
assert!(delete.is_empty());
assert!(deferred);
}
#[tokio::test]
-1
View File
@@ -16,7 +16,6 @@
pub mod action;
mod checkpointer;
mod compat;
pub mod manager;
pub mod storage;
#[cfg(test)]
+2 -31
View File
@@ -173,29 +173,6 @@ impl RegionEdit {
|| !self.series_indexes_to_add.is_empty()
|| !self.series_indexes_to_remove.is_empty()
}
/// Shared reclassification must be add-only for a file ID: the manifest removes
/// by ID, while the in-memory Version removes from the specified level.
pub(crate) fn validate_shared_reclassification(&self, region_id: RegionId) -> Result<()> {
let shared_ids: HashSet<_> = self
.files_to_add
.iter()
.filter(|file| file.level == file::LEVEL_SHARED)
.map(|file| file.file_id)
.collect();
snafu::ensure!(
shared_ids.is_empty()
|| self
.files_to_remove
.iter()
.all(|file| !shared_ids.contains(&file.file_id)),
crate::error::InvalidRequestSnafu {
region_id,
reason: "Cannot add and remove the same shared SST in one edit",
}
);
Ok(())
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
@@ -337,10 +314,7 @@ impl PartialEq for RegionManifest {
}
impl RegionManifest {
/// Rejects prototype task state before deserializing, so callers cannot
/// silently drop recovery evidence that this build cannot interpret.
pub(crate) fn decode(bytes: &[u8]) -> Result<Self> {
crate::manifest::compat::validate_manifest(bytes)?;
serde_json::from_slice(bytes).context(SerdeJsonSnafu)
}
}
@@ -771,7 +745,6 @@ impl RegionCheckpoint {
pub fn decode(bytes: &[u8]) -> Result<Self> {
let data = std::str::from_utf8(bytes).context(Utf8Snafu)?;
crate::manifest::compat::validate_checkpoint(data)?;
serde_json::from_str(data).context(SerdeJsonSnafu)
}
}
@@ -864,7 +837,6 @@ impl RegionMetaActionList {
pub fn decode(bytes: &[u8]) -> Result<Self> {
let data = std::str::from_utf8(bytes).context(Utf8Snafu)?;
crate::manifest::compat::validate_actions(data)?;
serde_json::from_str(data).context(SerdeJsonSnafu)
}
}
@@ -1739,9 +1711,8 @@ mod tests {
let restored = RegionManifest::decode(&serde_json::to_vec(&empty).unwrap()).unwrap();
assert!(restored.series_indexes.is_empty());
assert_eq!(Some(10), restored.series_window_seconds);
let legacy = include_bytes!(
"../../../../tests/compatibility/manifest/table_compaction/legacy-edit.json"
);
let legacy =
include_bytes!("../../../../tests/compatibility/manifest/region_edit/legacy-edit.json");
let (_, _, legacy) = RegionMetaActionList::decode(legacy)
.unwrap()
.split_region_change_and_edit();
-84
View File
@@ -1,84 +0,0 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Reject unpublished prototype task-state records without adding persisted fields.
//! IgnoredAny skips file metadata without allocating a second manifest tree.
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use serde::Deserialize;
use serde::de::IgnoredAny;
use snafu::{ResultExt, ensure};
use crate::error::{Result, SerdeJsonSnafu, UnsupportedOperationSnafu, Utf8Snafu};
/// Serialized tag of [`crate::manifest::action::RegionMetaAction::Edit`].
///
/// The delta guard inspects raw JSON, so serde cannot select the variant for it.
/// Keep in sync with the enum; `compat::tests` fails if the tag drifts.
const EDIT_ACTION_TAG: &str = "Edit";
#[derive(Deserialize)]
struct TaskStateGuard {
table_compaction: Option<IgnoredAny>,
extensions: Option<IgnoredAny>,
}
impl TaskStateGuard {
fn validate(&self) -> Result<()> {
ensure!(self.table_compaction.is_none() && self.extensions.is_none(), UnsupportedOperationSnafu {
err_msg: "Legacy compaction task state requires explicit migration; it cannot be discarded".to_string(),
});
Ok(())
}
}
/// Validates a standalone manifest, such as a staging blob.
///
/// Staging manifests are recovery evidence like checkpoints and deltas, so they
/// must not silently drop prototype task state either.
pub(crate) fn validate_manifest(bytes: &[u8]) -> Result<()> {
let data = std::str::from_utf8(bytes).context(Utf8Snafu)?;
let state: TaskStateGuard = serde_json::from_str(data).context(SerdeJsonSnafu)?;
state.validate()
}
pub(crate) fn validate_checkpoint(json: &str) -> Result<()> {
#[derive(Deserialize)]
struct CheckpointGuard {
checkpoint: Option<TaskStateGuard>,
}
let guard: CheckpointGuard = serde_json::from_str(json).context(SerdeJsonSnafu)?;
if let Some(state) = guard.checkpoint {
state.validate()?;
}
Ok(())
}
pub(crate) fn validate_actions(json: &str) -> Result<()> {
#[derive(Deserialize)]
struct ActionListGuard {
actions: Vec<HashMap<String, TaskStateGuard>>,
}
let guard: ActionListGuard = serde_json::from_str(json).context(SerdeJsonSnafu)?;
for action in guard.actions {
if let Some(edit) = action.get(EDIT_ACTION_TAG) {
edit.validate()?;
}
}
Ok(())
}
-26
View File
@@ -1,26 +0,0 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::manifest::action::{RegionEdit, RegionMetaAction};
#[test]
fn test_edit_action_tag_matches_serialized_enum() {
let encoded = serde_json::to_value(RegionMetaAction::Edit(RegionEdit::default())).unwrap();
let object = encoded.as_object().unwrap();
assert_eq!(1, object.len(), "action must stay externally tagged");
assert!(
object.contains_key(super::EDIT_ACTION_TAG),
"the delta guard reads raw JSON by tag; keep EDIT_ACTION_TAG in sync with RegionMetaAction"
);
}
+6 -49
View File
@@ -14,16 +14,13 @@
use serde_json::json;
use crate::manifest::action::{
RegionCheckpoint, RegionManifest, RegionMetaAction, RegionMetaActionList,
};
use crate::manifest::action::{RegionCheckpoint, RegionMetaAction, RegionMetaActionList};
use crate::sst::file::FileMeta;
const EDIT: &str =
include_str!("../../../../../tests/compatibility/manifest/table_compaction/legacy-edit.json");
const MANIFEST: &str = include_str!(
"../../../../../tests/compatibility/manifest/table_compaction/legacy-manifest.json"
);
include_str!("../../../../../tests/compatibility/manifest/region_edit/legacy-edit.json");
const MANIFEST: &str =
include_str!("../../../../../tests/compatibility/manifest/region_edit/legacy-manifest.json");
#[test]
fn test_file_only_manifest_compatibility() {
@@ -48,8 +45,6 @@ fn test_file_only_manifest_compatibility() {
.collect::<Vec<_>>()
);
assert_eq!(Some(8), edit.committed_sequence);
let encoded = String::from_utf8(actions.encode().unwrap()).unwrap();
assert!(!encoded.contains("table_compaction") && !encoded.contains("extensions"));
let mut manifest: serde_json::Value = serde_json::from_str(MANIFEST).unwrap();
manifest["future_core_option"] = json!(true);
let checkpoint = json!({"last_version":12,"compacted_actions":1,"checkpoint":manifest});
@@ -58,13 +53,11 @@ fn test_file_only_manifest_compatibility() {
assert_eq!(12, manifest.manifest_version);
assert_eq!(5, manifest.flushed_entry_id);
assert_eq!(8, manifest.flushed_sequence);
let encoded = String::from_utf8(decoded.encode().unwrap()).unwrap();
assert!(!encoded.contains("table_compaction") && !encoded.contains("extensions"));
for level in [0, 1, 2, 3, 255] {
for (level, supported) in [(0, true), (1, true), (2, false), (3, false), (255, false)] {
let mut file = serde_json::to_value(&edit.files_to_add[0]).unwrap();
file["level"] = level.into();
assert_eq!(
crate::sst::file::is_supported_level(level),
supported,
serde_json::from_value::<FileMeta>(file).is_ok(),
"level {level}"
);
@@ -138,39 +131,3 @@ fn test_file_meta_row_sequence_provenance_is_optional() {
.is_none()
);
}
#[rstest::rstest]
#[case("table_compaction")]
#[case("extensions")]
#[test]
fn test_staging_manifest_prototype_state_is_rejected(#[case] field: &str) {
// Staging blobs are parsed as standalone manifests, so they need the same gate
// as checkpoints and deltas instead of silently dropping recovery evidence.
assert!(RegionManifest::decode(MANIFEST.as_bytes()).is_ok());
let mut manifest: serde_json::Value = serde_json::from_str(MANIFEST).unwrap();
manifest[field] = json!({"legacy_state": true});
assert!(matches!(
RegionManifest::decode(&serde_json::to_vec(&manifest).unwrap()),
Err(crate::error::Error::UnsupportedOperation { .. })
));
}
#[rstest::rstest]
#[case("table_compaction")]
#[case("extensions")]
#[test]
fn test_prototype_task_state_is_not_silently_discarded(#[case] field: &str) {
let mut actions: serde_json::Value = serde_json::from_str(EDIT).unwrap();
actions["actions"][0]["Edit"][field] = json!({"legacy_state":true});
assert!(matches!(
RegionMetaActionList::decode(&serde_json::to_vec(&actions).unwrap()),
Err(crate::error::Error::UnsupportedOperation { .. })
));
let mut manifest: serde_json::Value = serde_json::from_str(MANIFEST).unwrap();
manifest[field] = json!({"legacy_state":true});
let checkpoint = json!({"last_version":12,"compacted_actions":1,"checkpoint":manifest});
assert!(matches!(
RegionCheckpoint::decode(&serde_json::to_vec(&checkpoint).unwrap()),
Err(crate::error::Error::UnsupportedOperation { .. })
));
}
-2
View File
@@ -39,8 +39,6 @@ pub const STAGING_TYPE: &str = "index_staging";
/// Recycle bin type label.
pub const RECYCLE_TYPE: &str = "recycle_bin";
/// Discard reason when an operation cannot admit extension index work.
pub(crate) const INDEX_DISCARD_ADMISSION_REJECTED: &str = "admission_rejected";
/// Discard reason when a creator exceeds its retained-memory allowance.
pub(crate) const INDEX_DISCARD_MEMORY_BUDGET_EXCEEDED: &str = "memory_budget_exceeded";
-18
View File
@@ -1039,8 +1039,6 @@ pub struct ScanInput {
pub(crate) compaction_read_parallelism: usize,
/// Compaction-only JSON2 physical rewrite targets.
json2_rewrite_targets: Json2RewriteTargets,
/// Override for footer page-index loading. `None` uses the reader default.
page_index_policy: Option<parquet::file::metadata::PageIndexPolicy>,
/// Counters that should receive query-load metrics.
pub(crate) query_stat_counters: Option<RegionQueryStatCounters>,
#[cfg(feature = "enterprise")]
@@ -1082,7 +1080,6 @@ impl ScanInput {
exact_num_rows: None,
row_preserving_request: self.row_preserving_request,
statistics_split: None,
page_index_policy: self.page_index_policy,
access_layer: self.access_layer.clone(),
mapper: self.mapper.clone(),
read_cols: self.read_cols.clone(),
@@ -1132,7 +1129,6 @@ impl ScanInput {
exact_num_rows: None,
row_preserving_request: true,
statistics_split: None,
page_index_policy: None,
access_layer,
read_cols: mapper.read_columns().clone(),
mapper: Arc::new(mapper),
@@ -1365,16 +1361,6 @@ impl ScanInputBuilder {
self
}
/// Selects footer page-index loading for maintenance readers.
#[cfg(feature = "enterprise")]
pub(crate) fn with_page_index_policy(
mut self,
policy: parquet::file::metadata::PageIndexPolicy,
) -> Self {
self.input.page_index_policy = Some(policy);
self
}
/// Sets the scan-wide hint for rows in an execution batch.
#[must_use]
pub(crate) fn with_batch_size(mut self, batch_size: usize) -> Self {
@@ -1748,10 +1734,6 @@ impl ScanInput {
.bloom_filter_index_appliers(self.bloom_filter_index_appliers.clone())
.fulltext_index_appliers(self.fulltext_index_appliers.clone());
let reader = reader.batch_size(self.batch_size);
let reader = match self.page_index_policy {
Some(policy) => reader.page_index_policy(policy),
None => reader,
};
let reader = if !self.compaction && may_build_selective_row_selection {
reader.deferred_optional_page_index()
} else {
+3 -3
View File
@@ -1281,9 +1281,9 @@ pub(crate) fn should_split_flat_batches_for_merge(
let file = &stream_ctx.input.files[file_index];
let file_meta = file.meta_ref();
// Only L1 compaction outputs guarantee a published, non-overlapping layout.
// L0 and shared inputs may carry short series whose tiny batches
// would otherwise be retained by the merge.
if file_meta.level != 1 {
// L0 inputs may carry short series whose tiny batches would otherwise be
// retained by the merge.
if file_meta.level == 0 {
// Short series can leave too many tiny batches retained by the merge.
if file_meta.num_series > 0 {
if !can_split_series(file_meta.num_rows, file_meta.num_series) {
+4 -26
View File
@@ -56,10 +56,9 @@ use crate::access_layer::AccessLayerRef;
use crate::compaction::CompactionStateRef;
use crate::engine::region_hook::{PendingManifestHook, RegionHookRef};
use crate::error::{
EndStagingSnafu, Error, FlushableRegionStateSnafu, InvalidPartitionExprSnafu,
InvalidRequestSnafu, RegionBusySnafu, RegionLeaseExpiredSnafu, RegionLeaseNotReceivedSnafu,
RegionNotFoundSnafu, RegionStateSnafu, RegionStoppedSnafu, RegionTruncatedSnafu, Result,
UnexpectedSnafu, UpdateManifestSnafu,
EndStagingSnafu, Error, FlushableRegionStateSnafu, InvalidPartitionExprSnafu, RegionBusySnafu,
RegionLeaseExpiredSnafu, RegionLeaseNotReceivedSnafu, RegionNotFoundSnafu, RegionStateSnafu,
RegionStoppedSnafu, RegionTruncatedSnafu, Result, UnexpectedSnafu, UpdateManifestSnafu,
};
use crate::lease::{Deadline, NodeLease, lease_nanos};
use crate::manifest::action::{
@@ -70,7 +69,7 @@ use crate::memtable::MemtableId;
use crate::metrics::manifest_size::RegionManifestSizeMetric;
use crate::region::version::{VersionControlRef, VersionRef};
use crate::request::{OnFailure, OptionOutputTx};
use crate::sst::file::{self, FileMeta};
use crate::sst::file::FileMeta;
use crate::sst::file_purger::FilePurgerRef;
use crate::sst::location::index_file_path;
use crate::time_provider::TimeProviderRef;
@@ -2460,27 +2459,6 @@ impl ManifestContext {
continue;
};
edit.validate_shared_reclassification(manifest.metadata.region_id)?;
// Imports may add shared references, but ordinary edits must not retire
// or overwrite them. Table publication performs its own locked input check.
ensure!(
edit.files_to_remove.iter().all(|file| {
file.level != file::LEVEL_SHARED
&& manifest
.files
.get(&file.file_id)
.is_none_or(|current| current.level != file::LEVEL_SHARED)
}) && edit.files_to_add.iter().all(|file| {
manifest.files.get(&file.file_id).is_none_or(|current| {
current.level != file::LEVEL_SHARED || current.as_ref() == file
})
}),
InvalidRequestSnafu {
region_id: manifest.metadata.region_id,
reason: "Ordinary manifest edits cannot modify shared SSTs",
}
);
// Checks whether the region is truncated.
let Some(truncated_entry_id) = manifest.truncated_entry_id else {
continue;
+14 -20
View File
@@ -459,16 +459,13 @@ impl RegionOpener {
.flushed_entry_id(flushed_entry_id)
.build();
let version_control = Arc::new(VersionControl::new(version));
let access_layer = Arc::new(
AccessLayer::new(
self.table_dir.clone(),
self.path_type,
object_store,
self.puffin_manager_factory,
self.intermediate_manager,
)
.with_file_protection(self.hook.clone()),
);
let access_layer = Arc::new(AccessLayer::new(
self.table_dir.clone(),
self.path_type,
object_store,
self.puffin_manager_factory,
self.intermediate_manager,
));
let now = self.time_provider.current_time_millis();
Ok(Arc::new(MitoRegion {
@@ -602,16 +599,13 @@ impl RegionOpener {
region_id, self.table_dir, self.options
);
let access_layer = Arc::new(
AccessLayer::new(
self.table_dir.clone(),
self.path_type,
object_store,
self.puffin_manager_factory.clone(),
self.intermediate_manager.clone(),
)
.with_file_protection(self.hook.clone()),
);
let access_layer = Arc::new(AccessLayer::new(
self.table_dir.clone(),
self.path_type,
object_store,
self.puffin_manager_factory.clone(),
self.intermediate_manager.clone(),
));
let file_purger = create_file_purger(
config.gc.enable,
self.path_type,
+1 -13
View File
@@ -1599,11 +1599,7 @@ impl Waiters {
/// Transient execution semantics; this is never serialized into the manifest.
#[derive(Debug)]
pub(crate) enum RegionEditKind {
Import {
external: bool,
},
#[cfg(feature = "enterprise")]
Compaction(Box<crate::engine::table_compaction::PublicationContext>),
Import { external: bool },
}
/// Request to edit a region directly.
@@ -1644,20 +1640,12 @@ impl RegionEditRequest {
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.
#[derive(Debug)]
pub(crate) enum RegionEditOutcome {
Written,
#[cfg(feature = "enterprise")]
AlreadyApplied,
}
/// Notifies the region of the result of editing its manifest.
+3 -18
View File
@@ -119,26 +119,11 @@ where
/// Type to store SST level.
pub type Level = u8;
/// Shared inputs owned by table compaction, not a deeper region-compaction level.
/// This sentinel is persisted; L0=0 and L1=1 retain their original meanings, and
/// taking the maximum value keeps every future ordinary level below it.
pub const LEVEL_SHARED: Level = Level::MAX;
/// Storage slot that holds shared references inside the fixed level array.
pub(crate) const SHARED_LEVEL_SLOT: usize = 2;
/// Number of level storage slots: L0, L1 and the shared slot.
pub(crate) const LEVEL_SLOT_COUNT: usize = SHARED_LEVEL_SLOT + 1;
/// Maps a persisted level to its storage slot, if the level is representable.
pub(crate) const fn level_slot(level: Level) -> Option<usize> {
match level {
0 | 1 => Some(level as usize),
LEVEL_SHARED => Some(SHARED_LEVEL_SLOT),
_ => None,
}
}
/// Maximum level of SSTs.
pub const MAX_LEVEL: Level = 2;
pub(crate) const fn is_supported_level(level: Level) -> bool {
level <= 1 || (cfg!(feature = "enterprise") && level == LEVEL_SHARED)
level < MAX_LEVEL
}
fn deserialize_level<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Level, D::Error> {
+18 -35
View File
@@ -159,22 +159,19 @@ impl LocalFilePurger {
let sst_layer = self.sst_layer.clone();
let cache_manager = self.cache_manager.clone();
if let Err(e) = self.scheduler.schedule(Box::pin(async move {
match sst_layer.is_file_protected(file_meta.file_id()).await {
Ok(false) => {}
Ok(true) => return,
Err(error) => {
error!(error; "File protection unavailable; retaining SST {}", file_meta.file_id());
return;
}
}
if !matches!(file_meta.format, file::FileFormat::Parquet) {
if let Some(write_cache) = cache_manager.as_ref().and_then(|c| c.write_cache()) {
let dir = sst_layer.build_region_dir(file_meta.region_id);
for (key, _) in crate::cache::file_cache::IndexKey::narthex_objects(&file_meta, &dir) {
for (key, _) in
crate::cache::file_cache::IndexKey::narthex_objects(&file_meta, &dir)
{
write_cache.remove(key).await;
}
}
if let Err(error) = sst_layer.delete_narthex_artifact(file_meta.region_id, file_meta.file_id).await {
if let Err(error) = sst_layer
.delete_narthex_artifact(file_meta.region_id, file_meta.file_id)
.await
{
error!(error; "Failed to delete Narthex artifact {}", file_meta.file_id());
}
return;
@@ -204,9 +201,6 @@ impl FilePurger for LocalFilePurger {
}
fn purge_file(&self, file_meta: FileMeta) {
if file_meta.level == file::LEVEL_SHARED {
return;
}
self.delete_file(file_meta);
}
@@ -260,8 +254,8 @@ mod tests {
use crate::access_layer::AccessLayer;
use crate::schedule::scheduler::{LocalScheduler, Scheduler};
use crate::sst::file::{
ColumnIndexMetadata, FileHandle, FileMeta, FileTimeRange, IndexType, LEVEL_SHARED,
RegionFileId, RegionIndexId,
ColumnIndexMetadata, FileHandle, FileMeta, FileTimeRange, IndexType, RegionFileId,
RegionIndexId,
};
use crate::sst::index::intermediate::IntermediateManager;
use crate::sst::index::puffin_manager::PuffinManagerFactory;
@@ -462,12 +456,12 @@ mod tests {
#[case(false)]
#[case(true)]
#[tokio::test]
async fn test_shared_sst_purge_on_handle_release(
async fn test_sst_purge_on_handle_release(
#[case] gc_enabled: bool,
#[values(false, true)] is_delete: bool,
#[values(false, true)] update_index: bool,
#[values(0, LEVEL_SHARED)] level: u8,
) {
let level = 0;
let env = PurgeTestEnv::new().await;
let object_store = env.layer.object_store();
let path = env.sst_path();
@@ -506,9 +500,7 @@ mod tests {
crate::test_util::memtable_util::metadata_for_test(),
);
version.add_files(file_purger, [meta].into_iter());
let reader = version.levels()[crate::sst::file::level_slot(level).unwrap()].files
[&sst_file_id.file_id()]
.clone();
let reader = version.levels()[level as usize].files[&sst_file_id.file_id()].clone();
if update_index {
for index_version in 1..=2 {
let mut meta = reader.meta_ref().clone();
@@ -540,14 +532,14 @@ mod tests {
assert_eq!(
object_store.exists(&path).await.unwrap(),
gc_enabled || !is_delete || level == LEVEL_SHARED
gc_enabled || !is_delete
);
if update_index {
for index_version in 1..=2 {
let path = env.index_path(index_version);
assert_eq!(
object_store.exists(&path).await.unwrap(),
gc_enabled || !is_delete || level == LEVEL_SHARED
gc_enabled || !is_delete
);
}
}
@@ -555,10 +547,8 @@ mod tests {
#[rstest::rstest]
#[tokio::test]
async fn test_file_purge_with_index(
#[values(0, LEVEL_SHARED)] level: u8,
#[values(false, true)] sketch_only: bool,
) {
async fn test_file_purge_with_index(#[values(false, true)] sketch_only: bool) {
let level = 0;
let env = PurgeTestEnv::new().await;
let object_store = env.layer.object_store();
let sst_file_id = env.file_id;
@@ -618,19 +608,12 @@ mod tests {
.contains(&IndexType::HllIndex),
sketch_only
);
// Shared SSTs and their indexes require global GC even after local release.
handle.mark_deleted();
}
scheduler.stop(true).await.unwrap();
assert_eq!(
level == LEVEL_SHARED,
object_store.exists(&path).await.unwrap()
);
assert_eq!(
level == LEVEL_SHARED,
object_store.exists(&index_path).await.unwrap()
);
assert!(!object_store.exists(&path).await.unwrap());
assert!(!object_store.exists(&index_path).await.unwrap());
}
}
@@ -126,15 +126,6 @@ impl PuffinManagerFactory {
}
/// Overrides only this task's upload buffers, sharing the existing stager.
#[cfg(feature = "enterprise")]
pub(crate) fn with_upload_limits(
mut self,
limits: crate::sst::upload::buffered::UploadLimits,
) -> Self {
self.write_buffer = IndexWriteBuffer::Bounded(limits);
self
}
pub fn build(
&self,
store: ObjectStore,
-66
View File
@@ -14,18 +14,15 @@
//! Ordered registration and planning of index implementations.
use std::collections::HashSet;
use std::sync::Arc;
use common_error::ext::BoxedError;
use common_telemetry::warn;
use snafu::{IntoError, ResultExt};
use store_api::metadata::RegionMetadataRef;
use store_api::storage::RegionId;
use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig, MitoConfig};
use crate::error::{Error, ExternalSnafu, InvalidConfigSnafu};
use crate::metrics::{INDEX_CREATE_DISCARDED_TOTAL, INDEX_DISCARD_ADMISSION_REJECTED};
use crate::sst::file::{FileMeta, IndexType};
use crate::sst::index::IndexBuildType;
use crate::sst::index::handler::builtin::BuiltinIndexHandler;
@@ -365,28 +362,6 @@ impl IndexBuildPlan {
self.planned.iter().any(|plan| plan.needs_input_reuse())
}
/// Omits optional extension work when the caller cannot admit its memory budget.
/// Records each requested kind once per target plan, rather than once per column.
pub fn omit_extensions_for_budget(&mut self, region_id: RegionId) {
let omitted: HashSet<_> = self
.entries()
.filter(|entry| !entry.kind.is_builtin())
.map(|entry| entry.kind)
.collect();
for kind in omitted {
warn!(
"Omitting index before construction, region_id: {}, kind: {}, reason: admission_rejected",
region_id,
kind.as_str()
);
INDEX_CREATE_DISCARDED_TOTAL
.with_label_values(&[kind.as_str(), INDEX_DISCARD_ADMISSION_REJECTED])
.inc();
}
self.planned
.retain(|plan| plan.kinds().iter().all(|kind| kind.is_builtin()));
}
/// Whether every handler considers the published file current.
pub fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool {
let has_removed_extensions = matches!(
@@ -481,47 +456,6 @@ mod tests {
}
}
#[test]
fn test_admission_omission_records_each_requested_kind_once() {
let builtin = IndexKind::Bloom;
let enabled = IndexKind::Extension(ExtensionIndexKind::Mg);
let disabled = IndexKind::Extension(ExtensionIndexKind::Kll);
let entry = |kind, column_id| PlanEntry {
kind,
column_id,
format_version: 1,
};
let mut plan = IndexBuildPlan {
planned: vec![
Arc::new(TestPlan {
kinds: vec![builtin],
entries: vec![entry(builtin, 0)],
}),
Arc::new(TestPlan {
kinds: vec![enabled, disabled],
entries: vec![entry(enabled, 0), entry(enabled, 1)],
}),
],
failure: None,
};
let counter = INDEX_CREATE_DISCARDED_TOTAL
.with_label_values(&[enabled.as_str(), "admission_rejected"]);
let disabled_counter = INDEX_CREATE_DISCARDED_TOTAL
.with_label_values(&[disabled.as_str(), "admission_rejected"]);
let before = counter.get();
let disabled_before = disabled_counter.get();
plan.omit_extensions_for_budget(RegionId::new(1, 1));
assert_eq!(
plan.entries().cloned().collect::<Vec<_>>(),
vec![entry(builtin, 0)]
);
assert_eq!(counter.get(), before + 1);
assert_eq!(disabled_counter.get(), disabled_before);
assert!(plan.check_success().is_ok());
plan.omit_extensions_for_budget(RegionId::new(1, 1));
assert_eq!(counter.get(), before + 1);
}
#[test]
fn test_registration_preserves_grouped_owner_and_rejects_overlap() {
let mut registry =
-31
View File
@@ -20,8 +20,6 @@ use std::task::{Context, Poll};
use async_trait::async_trait;
use bytes::{BufMut, Bytes};
use common_base::range_read::{Metadata, RangeReader, SizeAwareRangeReader};
#[cfg(feature = "enterprise")]
use futures::future::Either;
use futures::{AsyncRead, AsyncSeek, AsyncWrite};
use object_store::{FuturesAsyncWriter, ObjectStore};
use pin_project::pin_project;
@@ -53,11 +51,6 @@ pub(crate) enum IndexWriteBuffer {
/// Requests exact parts of the given size, clamped to the backend's limits,
/// with the store's default concurrency.
Chunk(usize),
/// Requests parts sized by the given limits with one upload at a time, and
/// buffers writes through [`crate::sst::upload::buffered::writer`], which
/// assembles whole parts and rejects writes beyond the object size limit.
#[cfg(feature = "enterprise")]
Bounded(crate::sst::upload::buffered::UploadLimits),
}
impl From<Option<usize>> for IndexWriteBuffer {
@@ -150,24 +143,8 @@ impl InstrumentedStore {
IndexWriteBuffer::Chunk(bytes) => {
self.object_store.writer_with(path).chunk(bytes).await
}
#[cfg(feature = "enterprise")]
IndexWriteBuffer::Bounded(limits) => {
self.object_store
.writer_with(path)
.chunk(limits.chunk_bytes)
.concurrent(1)
.await
}
}
.context(OpenDalSnafu)?;
#[cfg(feature = "enterprise")]
let writer: IndexObjectWriter = match self.write_buffer {
IndexWriteBuffer::Bounded(limits) => Either::Right(Box::new(
crate::sst::upload::buffered::writer(writer, limits),
)),
_ => Either::Left(writer.into_futures_async_write()),
};
#[cfg(not(feature = "enterprise"))]
let writer = writer.into_futures_async_write();
Ok(InstrumentedAsyncWrite::new(
writer,
@@ -250,14 +227,6 @@ impl<R: AsyncSeek + Unpin + Send> AsyncSeek for InstrumentedAsyncRead<'_, R> {
}
/// The [`AsyncWrite`] sink of a Puffin index file.
///
/// The bounded side is boxed because [`crate::sst::upload::buffered::writer`]
/// returns an opaque `impl AsyncWrite`, which keeps that private adapter out of
/// this alias; the plain side stays concrete.
#[cfg(feature = "enterprise")]
pub type IndexObjectWriter = Either<FuturesAsyncWriter, Box<dyn AsyncWrite + Send + Sync + Unpin>>;
/// The [`AsyncWrite`] sink of a Puffin index file.
#[cfg(not(feature = "enterprise"))]
pub type IndexObjectWriter = FuturesAsyncWriter;
/// A wrapper around [`AsyncWrite`] that adds instrumentation for monitoring
+5 -149
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, RowGroupMetaData};
use parquet::file::metadata::{KeyValue, ParquetMetaData, RowGroupMetaData};
use parquet::file::properties::WriterProperties;
use smallvec::smallvec;
use snafu::{IntoError, OptionExt, ResultExt, ensure};
@@ -214,41 +214,6 @@ impl<W: AsyncFileWriter> SstArrowWriter<W> {
}
}
/// Optional limits used by multi-output compaction. A batch may temporarily
/// exceed the working threshold before its check; callers reserve that workspace.
#[derive(Clone, Copy)]
pub(crate) struct SstWriteLimits {
pub(crate) working_bytes: usize,
pub(crate) metadata_bytes: usize,
#[cfg(feature = "enterprise")]
pub(crate) upload_limits: upload::buffered::UploadLimits,
}
/// Tracks retained footer memory across rolled files as well as the current file.
#[derive(Default)]
struct WriteMemory {
limits: Option<SstWriteLimits>,
completed: usize,
current: usize,
row_groups: usize,
}
impl WriteMemory {
fn check(&self, bytes: usize) -> Result<()> {
if let Some(limits) = self.limits {
ensure!(
bytes <= limits.metadata_bytes,
crate::error::SstWriteMemoryExceededSnafu {
kind: "metadata",
bytes,
limit: limits.metadata_bytes,
}
);
}
Ok(())
}
}
/// Parquet SST writer.
pub struct ParquetWriter<'a, F: WriterFactory, I: IndexerBuilder, P: FilePathProvider> {
/// Path provider that creates SST and index file paths according to file id.
@@ -272,7 +237,6 @@ pub struct ParquetWriter<'a, F: WriterFactory, I: IndexerBuilder, P: FilePathPro
metrics: &'a mut Metrics,
write_guard: Option<Arc<dyn SstWriteGuard>>,
cancellation: Option<CancellationToken>,
memory: WriteMemory,
/// Field columns of the current file that skip min/max statistics, picked from its first batch.
large_value_columns: Vec<String>,
/// Decoded value bytes per row group of the current file.
@@ -290,14 +254,11 @@ pub trait SstWriteGuard: Send + Sync {
}
}
/// Optional ownership, cancellation, and resource limits for an SST write.
/// Optional ownership and cancellation for an SST write.
#[derive(Default)]
pub(crate) struct SstWriteContext {
/// Registers output ownership before creating files, including cached files.
pub(crate) guard: Option<Arc<dyn SstWriteGuard>>,
/// Resource bounds enforced by the direct writer, with one upload at a time.
/// The write cache does not enforce these limits, so bounded writes bypass it.
pub(crate) limits: Option<SstWriteLimits>,
/// Signals cancellation; the writer still drains encoders and aborts unfinished output.
pub(crate) cancellation: Option<CancellationToken>,
}
@@ -322,8 +283,6 @@ pub struct ObjectStoreWriter {
inner: Writer,
write_buffer_size: usize,
cancellation: Option<CancellationToken>,
#[cfg(feature = "enterprise")]
buffered_upload: Option<upload::buffered::UploadBuffer>,
}
impl ObjectStoreWriter {
@@ -336,8 +295,6 @@ impl ObjectStoreWriter {
inner,
write_buffer_size,
cancellation,
#[cfg(feature = "enterprise")]
buffered_upload: None,
}
}
@@ -346,13 +303,6 @@ impl ObjectStoreWriter {
}
async fn write_bytes(&mut self, bytes: Bytes) -> parquet::errors::Result<u64> {
#[cfg(feature = "enterprise")]
if let Some(buffer) = &mut self.buffered_upload {
return buffer
.write(&mut self.inner, bytes, self.cancellation.as_ref())
.await
.map_err(map_buffered_upload_error);
}
upload::write(
&mut self.inner,
bytes.into(),
@@ -374,13 +324,6 @@ impl AsyncFileWriter for ObjectStoreWriter {
fn complete(&mut self) -> BoxFuture<'_, parquet::errors::Result<()>> {
Box::pin(async move {
#[cfg(feature = "enterprise")]
if let Some(buffer) = &mut self.buffered_upload {
buffer
.write_tail(&mut self.inner)
.await
.map_err(|error| ParquetError::External(Box::new(error)))?;
}
self.inner
.close()
.await
@@ -399,21 +342,9 @@ fn map_upload_error(error: UploadError) -> ParquetError {
}
}
#[cfg(feature = "enterprise")]
fn map_buffered_upload_error(error: upload::buffered::BufferedWriteError) -> ParquetError {
match error {
upload::buffered::BufferedWriteError::ObjectLimit(error) => {
ParquetError::External(Box::new(error))
}
upload::buffered::BufferedWriteError::Upload(error) => map_upload_error(error),
}
}
pub struct ObjectStoreWriterFactory {
object_store: ObjectStore,
concurrency: usize,
#[cfg(feature = "enterprise")]
upload_limits: Option<upload::buffered::UploadLimits>,
}
impl WriterFactory for ObjectStoreWriterFactory {
@@ -425,25 +356,12 @@ impl WriterFactory for ObjectStoreWriterFactory {
write_buffer_size: usize,
cancellation: Option<&CancellationToken>,
) -> Result<Self::Writer> {
#[cfg(feature = "enterprise")]
let write_buffer_size = self
.upload_limits
.map_or(write_buffer_size, |limits| limits.chunk_bytes);
self.object_store
.writer_with(file_path)
.chunk(write_buffer_size)
.concurrent(self.concurrency)
.await
.map(|writer| {
let writer =
ObjectStoreWriter::new(writer, write_buffer_size, cancellation.cloned());
#[cfg(feature = "enterprise")]
let writer = ObjectStoreWriter {
buffered_upload: self.upload_limits.map(upload::buffered::UploadBuffer::new),
..writer
};
writer
})
.map(|writer| ObjectStoreWriter::new(writer, write_buffer_size, cancellation.cloned()))
.context(OpenDalSnafu)
}
@@ -462,14 +380,6 @@ where
self
}
#[cfg(feature = "enterprise")]
pub(crate) fn with_upload_limits(mut self, limits: upload::buffered::UploadLimits) -> Self {
self.writer_factory.upload_limits = Some(limits);
// Upload admission accounts for the serial OpenDAL writer.
self.writer_factory.concurrency = 1;
self
}
pub async fn new_with_object_store(
object_store: ObjectStore,
metadata: RegionMetadataRef,
@@ -482,8 +392,6 @@ where
ObjectStoreWriterFactory {
object_store,
concurrency: DEFAULT_WRITE_CONCURRENCY,
#[cfg(feature = "enterprise")]
upload_limits: None,
},
metadata,
index_config,
@@ -527,7 +435,6 @@ where
indexer_builder,
// Build lazily with the actual row-group size, after the write guard.
current_indexer: None,
memory: WriteMemory::default(),
bytes_written: Arc::new(AtomicUsize::new(0)),
file_cleaner: None,
metrics,
@@ -559,40 +466,6 @@ where
self
}
pub(crate) fn with_memory_limits(mut self, limits: Option<SstWriteLimits>) -> Self {
self.memory.limits = limits;
self
}
/// Checks encoding state without flushing a partial row group: readers and
/// index row IDs require uniform row-group lengths except for the final one.
/// Only new footer entries are measured, avoiding quadratic footer walks.
async fn check_memory(&mut self) -> Result<()> {
let Some(limits) = self.memory.limits else {
return Ok(());
};
if let Some(SstArrowWriter::Serial(writer)) = &mut self.writer {
ensure!(
writer.memory_size() <= limits.working_bytes,
crate::error::SstWriteMemoryExceededSnafu {
kind: "encoder",
bytes: writer.memory_size(),
limit: limits.working_bytes,
}
);
for group in &writer.flushed_row_groups()[self.memory.row_groups..] {
let file = FileMetaData::new(1, 0, None, None, group.schema_descr_ptr(), None);
// Reuse Parquet's heap estimator; counting the schema per group
// is conservative, including variable-length min/max statistics.
let metadata = ParquetMetaData::new(file, vec![group.clone()]);
self.memory.current = self.memory.current.saturating_add(metadata.memory_size());
}
self.memory.row_groups = writer.flushed_row_groups().len();
}
self.memory
.check(self.memory.completed.saturating_add(self.memory.current))
}
/// Finishes current SST file and index file.
async fn finish_current_file(
&mut self,
@@ -646,15 +519,6 @@ where
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;
if self.memory.limits.is_some() {
self.memory.completed = self.memory.completed.saturating_add(
parquet_metadata.memory_size().saturating_mul(2)
+ std::mem::size_of::<SstInfo>(),
);
self.memory.check(self.memory.completed)?;
self.memory.current = 0;
self.memory.row_groups = 0;
}
// Safety: num rows > 0 so we must have min/max.
let time_range = stats.time_range.unwrap();
@@ -875,7 +739,7 @@ where
.await;
let result = match result {
Ok(()) => self.check_memory().await,
Ok(()) => Ok(()),
Err(error) => Err(error),
};
if result.is_err() {
@@ -963,8 +827,7 @@ where
self.bytes_written.clone(),
);
let schema = maybe_wrap_schema(schema)?;
let arrow_writer = if self.memory.limits.is_none()
&& opts.encode_parallelism > 1
let arrow_writer = if opts.encode_parallelism > 1
&& ParallelArrowWriter::<SizeAwareWriter<F::Writer>>::supports(&writer_props)
{
SstArrowWriter::Parallel(
@@ -1018,13 +881,6 @@ fn map_write_error(error: ParquetError) -> Error {
if source.is::<Cancelled>() {
return crate::error::SstWriteCancelledSnafu.build();
}
#[cfg(feature = "enterprise")]
if let Some(error) = source.downcast_ref::<upload::buffered::UploadObjectLimit>() {
return crate::error::MultiRegionCompactionResourceSnafu {
reason: error.to_string(),
}
.build();
}
}
WriteParquetSnafu.into_error(error)
}
-3
View File
@@ -14,9 +14,6 @@
//! Cooperative byte transfer for SST uploads. Callers own close, abort, and file cleanup.
#[cfg(feature = "enterprise")]
pub(crate) mod buffered;
use futures::{Stream, StreamExt};
use object_store::{Buffer, Error as ObjectStoreError, Result as ObjectStoreResult, Writer};
use snafu::Snafu;
-259
View File
@@ -1,259 +0,0 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
//! Bounded multipart uploads for table compaction SSTs and their Puffin indexes.
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll, ready};
use bytes::{Buf, Bytes, BytesMut};
use futures::{AsyncWrite, Sink, SinkExt};
use object_store::{Buffer, Result as ObjectStoreResult, Writer};
use snafu::Snafu;
use tokio_util::sync::CancellationToken;
use crate::sst::upload::{self, UploadError};
#[derive(Debug, Snafu)]
#[snafu(display("Upload exceeds the backend object limit of {limit} bytes"))]
pub(crate) struct UploadObjectLimit {
pub(crate) limit: u64,
}
/// Part and object limits for the bounded, serial upload path.
#[derive(Clone, Copy)]
pub(crate) struct UploadLimits {
pub(crate) chunk_bytes: usize,
pub(crate) max_object_bytes: u64,
}
/// Owns at most one part while assembling bytes from encoder blocks or index blobs.
/// Sending whole owned parts avoids retaining a large producer allocation or a
/// queue of small fragments in OpenDAL. Only the final part may be short.
/// Both write paths check the remaining object allowance before buffering bytes.
pub(crate) struct UploadBuffer {
limits: UploadLimits,
pending: BytesMut,
object_bytes: u64,
}
/// A bounded write stopped at the object limit or failed in the store writer.
#[derive(Debug)]
pub(crate) enum BufferedWriteError {
ObjectLimit(UploadObjectLimit),
Upload(UploadError),
}
impl UploadBuffer {
pub(crate) fn new(limits: UploadLimits) -> Self {
Self {
limits,
pending: BytesMut::new(),
object_bytes: 0,
}
}
fn check_size(&self, bytes: usize) -> Result<(), UploadObjectLimit> {
if bytes as u64 > self.limits.max_object_bytes - self.object_bytes {
return Err(UploadObjectLimit {
limit: self.limits.max_object_bytes,
});
}
Ok(())
}
fn append(&mut self, bytes: &[u8]) -> usize {
let len = bytes
.len()
.min(self.limits.chunk_bytes - self.pending.len());
if len > 0 {
if self.pending.capacity() == 0 {
self.pending = BytesMut::with_capacity(self.limits.chunk_bytes);
}
self.pending.extend_from_slice(&bytes[..len]);
self.object_bytes += len as u64;
}
len
}
fn is_full(&self) -> bool {
self.pending.len() == self.limits.chunk_bytes
}
fn take_part(&mut self) -> Buffer {
std::mem::take(&mut self.pending).freeze().into()
}
pub(crate) async fn write(
&mut self,
writer: &mut Writer,
mut bytes: Bytes,
cancellation: Option<&CancellationToken>,
) -> Result<u64, BufferedWriteError> {
self.check_size(bytes.len())
.map_err(BufferedWriteError::ObjectLimit)?;
let len = bytes.len() as u64;
let parts = std::iter::from_fn(|| {
let appended = self.append(&bytes);
bytes.advance(appended);
self.is_full().then(|| self.take_part())
});
upload::write_chunks(writer, parts, cancellation)
.await
.map_err(BufferedWriteError::Upload)?;
Ok(len)
}
pub(crate) async fn write_tail(&mut self, writer: &mut Writer) -> ObjectStoreResult<()> {
if !self.pending.is_empty() {
writer.write(self.take_part()).await?;
}
Ok(())
}
}
/// Coalesces writes across blob flushes until a full part or the end of the object.
pub(crate) fn writer(
writer: Writer,
limits: UploadLimits,
) -> impl AsyncWrite + Send + Sync + Unpin {
BufferedUploadWriter {
sink: writer.into_sink().sink_map_err(io::Error::other),
buffer: UploadBuffer::new(limits),
}
}
struct BufferedUploadWriter<S> {
sink: S,
buffer: UploadBuffer,
}
impl<S: Sink<Buffer, Error = io::Error> + Unpin> BufferedUploadWriter<S> {
fn poll_send_part(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
ready!(Pin::new(&mut self.sink).poll_ready(cx))?;
Poll::Ready(Pin::new(&mut self.sink).start_send(self.buffer.take_part()))
}
}
impl<S: Sink<Buffer, Error = io::Error> + Unpin> AsyncWrite for BufferedUploadWriter<S> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bytes: &[u8],
) -> Poll<io::Result<usize>> {
let writer = self.get_mut();
writer
.buffer
.check_size(bytes.len())
.map_err(io::Error::other)?;
if writer.buffer.is_full() {
ready!(writer.poll_send_part(cx))?;
}
// The sink can retain the submitted part. Drain it into OpenDAL before
// allocating the next assembly buffer so admission covers both states.
ready!(Pin::new(&mut writer.sink).poll_ready(cx))?;
Poll::Ready(Ok(writer.buffer.append(bytes)))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let writer = self.get_mut();
// A blob flush must not fragment the upload queue. Flush complete parts;
// close is the file boundary and submits the remaining short part.
if writer.buffer.is_full() {
ready!(writer.poll_send_part(cx))?;
}
Pin::new(&mut writer.sink).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let writer = self.get_mut();
if !writer.buffer.pending.is_empty() {
ready!(writer.poll_send_part(cx))?;
}
Pin::new(&mut writer.sink).poll_close(cx)
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use bytes::Bytes;
use futures::io::AsyncWriteExt;
use object_store::ObjectStore;
use object_store::layers::mock::{MockLayerBuilder, ObservedWriter, WriterObservations};
use object_store::services::Memory;
use super::*;
#[tokio::test]
async fn test_buffered_upload_coalesces_blob_flushes_and_limits_object_size() {
let observations = Arc::new(Mutex::new(WriterObservations::default()));
let observer = observations.clone();
let layer = MockLayerBuilder::default()
.writer_factory(Arc::new(move |_, _, inner| {
Box::new(ObservedWriter::new(inner, observer.clone()))
}))
.build()
.unwrap();
let store = ObjectStore::new(Memory::default()).unwrap().layer(layer);
// Observe adapter boundaries without OpenDAL coalescing them for the test.
let mut writer = writer(
store.writer("index").await.unwrap(),
UploadLimits {
chunk_bytes: 4,
max_object_bytes: 9,
},
);
for byte in b"abcdefghi" {
writer.write_all(std::slice::from_ref(byte)).await.unwrap();
writer.flush().await.unwrap();
}
let error = writer.write_all(b"j").await.unwrap_err();
assert!(error.get_ref().unwrap().is::<UploadObjectLimit>());
writer.close().await.unwrap();
assert_eq!(vec![4, 4, 1], observations.lock().unwrap().write_sizes);
assert_eq!(
b"abcdefghi",
store.read("index").await.unwrap().to_bytes().as_ref()
);
}
#[tokio::test]
async fn test_upload_buffer_accepts_the_object_limit_and_rejects_more() {
let store = ObjectStore::new(Memory::default()).unwrap();
let mut buffer = UploadBuffer::new(UploadLimits {
chunk_bytes: 4,
max_object_bytes: 5,
});
let mut writer = store.writer("sst").await.unwrap();
buffer
.write(&mut writer, Bytes::from_static(b"abcd"), None)
.await
.unwrap();
buffer
.write(&mut writer, Bytes::from_static(b"e"), None)
.await
.unwrap();
let error = buffer
.write(&mut writer, Bytes::from_static(b"f"), None)
.await
.unwrap_err();
assert!(matches!(error, BufferedWriteError::ObjectLimit(_)));
buffer.write_tail(&mut writer).await.unwrap();
writer.close().await.unwrap();
assert_eq!(
b"abcde",
store.read("sst").await.unwrap().to_bytes().as_ref()
);
}
}
+6 -20
View File
@@ -106,7 +106,7 @@ impl SstVersion {
/// it will be overwritten with the new file.
///
/// # Panics
/// Panics if the level of [FileMeta] has no storage slot.
/// Panics if the level of [FileMeta] is outside the fixed level array.
pub(crate) fn add_files(
&mut self,
file_purger: FilePurgerRef,
@@ -132,14 +132,7 @@ impl SstVersion {
}
// A trusted L0 adoption changes classification, not the physical object.
// Detach the old handle without marking it deleted (old readers may hold it).
// Admission rejects an existing L1 reference; see `prepare_region_edit`.
if level == file::LEVEL_SHARED {
levels[0].files.remove(&file.file_id);
}
// Shared references use a sentinel wire level and live in their own slot.
let Some(slot) = file::level_slot(level) else {
panic!("Unsupported SST level {level}");
};
let slot = level as usize;
levels[slot]
.files
.entry(file.file_id)
@@ -183,13 +176,11 @@ impl SstVersion {
/// Remove files from the version.
///
/// # Panics
/// Panics if the level of [FileMeta] has no storage slot.
/// Panics if the level of [FileMeta] is outside the fixed level array.
pub(crate) fn remove_files(&mut self, files_to_remove: impl Iterator<Item = FileMeta>) {
let levels = Arc::make_mut(&mut self.levels);
for file in files_to_remove {
let Some(slot) = file::level_slot(file.level) else {
panic!("Unsupported SST level {}", file.level);
};
let slot = file.level as usize;
if let Some(handle) = levels[slot].files.remove(&file.file_id) {
handle.mark_deleted();
}
@@ -291,7 +282,7 @@ impl SstVersion {
// We only has fixed number of level, so we use array to hold elements. This implementation
// detail of LevelMetaArray should not be exposed to users of [LevelMetas].
type LevelMetaArray = [LevelMeta; file::LEVEL_SLOT_COUNT];
type LevelMetaArray = [LevelMeta; file::MAX_LEVEL as usize];
/// Metadata of files in the same SST level.
#[derive(Clone)]
@@ -345,12 +336,7 @@ impl fmt::Debug for LevelMeta {
}
fn new_level_meta_vec() -> LevelMetaArray {
// Slot 2 keeps the sentinel wire level so level-based filters still see shared files.
[
LevelMeta::new(0),
LevelMeta::new(1),
LevelMeta::new(file::LEVEL_SHARED),
]
[LevelMeta::new(0), LevelMeta::new(1)]
}
#[cfg(test)]
-2
View File
@@ -30,8 +30,6 @@ mod handle_open;
mod handle_rebuild_index;
mod handle_reload;
mod handle_remap;
#[cfg(feature = "enterprise")]
mod handle_table_compaction;
mod handle_tail_replay;
mod handle_truncate;
mod handle_write;
+3 -67
View File
@@ -18,7 +18,6 @@ use std::sync::{Arc, Mutex};
use common_telemetry::{debug, error, info};
use snafu::{OptionExt, ResultExt, ensure};
use store_api::region_engine::MitoCopyRegionFromResponse;
use store_api::region_request::PathType;
use store_api::storage::{FileId, RegionId};
use crate::error::{InvalidRequestSnafu, MissingManifestSnafu, Result};
@@ -29,7 +28,7 @@ use crate::region::{
use crate::request::{
BackgroundNotify, CopyRegionFromFinished, CopyRegionFromRequest, WorkerRequest,
};
use crate::sst::file::{self, FileMeta};
use crate::sst::file::FileMeta;
use crate::sst::location::region_dir_from_table_dir;
use crate::worker::{RegionWorkerLoop, WorkerRequestWithTime};
@@ -143,46 +142,6 @@ impl<S> RegionWorkerLoop<S> {
};
match region_edit {
Some(region_edit)
if region_edit
.files_to_add
.iter()
.any(|file| file.level == file::LEVEL_SHARED) =>
{
// Shared references enter the serialized
// edit lane for destination admission sequences.
// The response lists installed references, including shared SSTs
// whose objects stay in place; it is not a physical COPY count.
let copied_file_ids = region_edit
.files_to_add
.iter()
.map(|file| file.file_id)
.collect();
let (tx, rx) = tokio::sync::oneshot::channel();
if worker_sender
.send(WorkerRequestWithTime::new(WorkerRequest::EditRegion(
crate::request::RegionEditRequest::new(
region_id,
region_edit,
false,
tx,
)
.for_copy_region(),
)))
.await
.is_err()
{
let _ = sender.send(crate::error::RegionNotFoundSnafu { region_id }.fail());
return;
}
let result = match rx.await {
Ok(result) => {
result.map(|_| MitoCopyRegionFromResponse { copied_file_ids })
}
Err(error) => Err(error).context(crate::error::RecvSnafu),
};
let _ = sender.send(result);
}
Some(region_edit) => {
let (tx, rx) = tokio::sync::oneshot::channel();
if let Err(e) = worker_sender
@@ -244,7 +203,7 @@ impl<S> RegionWorkerLoop<S> {
let _ = sender.send(Ok(MitoCopyRegionFromResponse { copied_file_ids }));
}
/// Returns the region edit and source file IDs, including shared logical references.
/// Returns the region edit and source file IDs.
///
/// If no need to copy files, returns (None, source_file_ids).
async fn copy_region_from(
@@ -276,20 +235,6 @@ impl<S> RegionWorkerLoop<S> {
reason: "Cannot copy between Parquet and Narthex regions",
}
);
// Metadata sync transforms copied rows and then removes these references.
// It cannot retire shared inputs through the ordinary edit API, so reject
// them before either physical copying or extending the target manifest.
ensure!(
path_type != PathType::Metadata
|| source_region_manifest
.files
.values()
.all(|file| file.level != file::LEVEL_SHARED),
InvalidRequestSnafu {
region_id: target_region_id,
reason: "Shared SST references are not supported in metadata-region copies",
}
);
let mut new_file_metas = vec![];
let target_region_manifest = region.manifest_ctx.manifest().await;
let source_file_ids = source_region_manifest
@@ -306,9 +251,7 @@ impl<S> RegionWorkerLoop<S> {
if target_region_manifest.files.contains_key(file_id) {
continue;
}
if file_meta.level == file::LEVEL_SHARED {
new_file_metas.push(file_meta.as_ref().clone());
} else if narthex_format {
if narthex_format {
let (copied, objects) = prepare_narthex_copy(region, file_meta).await?;
new_file_metas.push(copied);
file_descriptors.extend(objects);
@@ -344,13 +287,6 @@ impl<S> RegionWorkerLoop<S> {
committed_sequence: None,
..Default::default()
};
if edit
.files_to_add
.iter()
.any(|file| file.level == file::LEVEL_SHARED)
{
return Ok((Some(edit), source_file_ids));
}
let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone()));
info!(
"Applying {:?} to region {target_region_id}, reason: CopyRegionFrom",
+32 -163
View File
@@ -104,11 +104,7 @@ impl RegionEditQueue {
fn dequeue(&mut self) -> Option<RegionEditRequest> {
fn mergeable_import(request: &RegionEditRequest) -> Option<bool> {
let external = match request.kind {
RegionEditKind::Import { external } => external,
#[cfg(feature = "enterprise")]
RegionEditKind::Compaction(_) => return None,
};
let RegionEditKind::Import { external } = request.kind;
let edit = &request.edit;
// Only the `RegionEdit`:
// 1. contains the "raw" (file without a sequence) files to add,
@@ -453,18 +449,8 @@ impl<S: LogStore> RegionWorkerLoop<S> {
preload_sst_cache,
staging_partition_expr: _,
} = request;
#[cfg(feature = "enterprise")]
if matches!(kind, RegionEditKind::Compaction(_)) && region.is_staging() {
waiters.reply_with(|| RegionBusySnafu { region_id }.fail());
return RegionEditDispatch::Rejected;
}
let preparation = match kind {
RegionEditKind::Import { external } => {
prepare_region_edit(&region, &mut edit, external)
}
#[cfg(feature = "enterprise")]
RegionEditKind::Compaction(_) => Ok(()),
};
let RegionEditKind::Import { external } = kind;
let preparation = prepare_region_edit(&region, &mut edit, external);
if let Err(error) = preparation {
let error = Arc::new(error);
waiters.reply_with(|| Err(error.clone()).context(EditRegionSnafu { region_id }));
@@ -494,23 +480,16 @@ impl<S: LogStore> RegionWorkerLoop<S> {
// Now the region is in editing state.
// Updates manifest in background.
common_runtime::spawn_global(async move {
let result = match kind {
RegionEditKind::Import { .. } => edit_region(
&region,
&mut edit,
cache_manager,
listener,
is_staging,
preload_sst_cache,
)
.await
.map(|()| RegionEditOutcome::Written),
#[cfg(feature = "enterprise")]
RegionEditKind::Compaction(context) => {
crate::worker::handle_table_compaction::publish(&region, &context, edit.clone())
.await
}
}
let result = edit_region(
&region,
&mut edit,
cache_manager,
listener,
is_staging,
preload_sst_cache,
)
.await
.map(|()| RegionEditOutcome::Written)
.map_err(Arc::new);
let notify = WorkerRequest::Background {
region_id,
@@ -606,11 +585,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
let written = matches!(edit_result.result, Ok(RegionEditOutcome::Written));
let need_compaction = self.config.schedule_compaction_after_edit
&& written
&& edit_result
.edit
.files_to_add
.iter()
.any(|file| file.level < file::LEVEL_SHARED);
&& !edit_result.edit.files_to_add.is_empty();
if written {
let mut edit = edit_result.edit;
@@ -1058,70 +1033,19 @@ fn prepare_region_edit(
reason: "only a pinned Narthex maintenance build can publish sequence coverage",
}
);
edit.validate_shared_reclassification(region_id)?;
let current = region.version_control.current();
let shared = &current.version.ssts.levels()[file::SHARED_LEVEL_SLOT].files;
// Shared adoption is L0-only. The manifest is keyed by FileId and would
// replace an existing reference, but installing a shared handle detaches
// only the L0 handle, so an existing L1 reference would leave two live
// handles for one file and duplicate its rows until reopen.
let l1_files = &current.version.ssts.levels()[1].files;
snafu::ensure!(
edit.files_to_add
.iter()
.all(|file| file.level != file::LEVEL_SHARED || !l1_files.contains_key(&file.file_id)),
crate::error::InvalidRequestSnafu {
region_id,
reason: "Cannot adopt an existing L1 SST as shared; adoption is L0-only",
}
);
snafu::ensure!(
edit.files_to_remove
.iter()
.all(|file| file.level < file::LEVEL_SHARED && !shared.contains_key(&file.file_id))
&& edit
.files_to_add
.iter()
.all(|file| file::is_supported_level(file.level)
&& (file.level != file::LEVEL_SHARED
|| file.region_id.table_id() == region_id.table_id())),
.chain(&edit.files_to_add)
.all(|file| file::is_supported_level(file.level)),
crate::error::InvalidRequestSnafu {
region_id,
reason: "Invalid shared SST import or removal"
reason: "Unsupported SST level",
}
);
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.sequence;
imported.preserve_row_sequence = false;
imported.dedup_marker_trusted = existing.dedup_marker_trusted;
imported.row_sequence_provenance = existing.row_sequence_provenance;
snafu::ensure!(
&imported == existing,
crate::error::InvalidRequestSnafu {
region_id,
reason: "Shared SST import conflicts with a visible reference",
}
);
}
}
let existing_sequence = |file: &file::FileMeta| {
shared
.get(&file.file_id)
.and_then(|handle| handle.meta_ref().sequence)
};
// A repeat of a still-visible shared import is not a new admission. Retired
// imports are not tracked: compaction retries must never re-import old inputs.
let same_import = !edit.files_to_add.is_empty()
&& edit.files_to_remove.is_empty()
&& edit
.files_to_add
.iter()
.all(|file| existing_sequence(file).is_some());
let sequence =
if same_import || (edit.files_to_add.is_empty() && edit.files_to_remove.is_empty()) {
if edit.files_to_add.is_empty() {
None
} else {
let sequence = current.last_sequence.checked_add(1).context(
@@ -1134,12 +1058,9 @@ fn prepare_region_edit(
NonZeroU64::new(sequence)
};
for file in &mut edit.files_to_add {
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.sequence = 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);
file.dedup_marker_trusted = !external && file.dedup_marker_trusted;
// The proof is a statement about the bytes, so a visible object keeps whatever it already
// states; an external caller proves nothing about an object this region has not seen.
let visible = current
@@ -1328,7 +1249,10 @@ fn preload_narthex_files(
.series_indexes()
.get(&id.file_id())
.or_else(|| {
version.ssts.levels()[file::level_slot(level)?]
version
.ssts
.levels()
.get(level as usize)?
.files
.get(&id.file_id())
})
@@ -1353,7 +1277,7 @@ mod tests {
use store_api::storage::FileId;
use super::*;
use crate::sst::file::{FileMeta, LEVEL_SHARED};
use crate::sst::file::FileMeta;
use crate::test_util::{CreateRequestBuilder, TestEnv};
#[test]
@@ -1452,61 +1376,11 @@ mod tests {
);
}
/// A shared reference reclassifies a file this region already shows without moving its
/// bytes, so the reference keeps the proof the visible object states, not the caller's.
#[cfg(feature = "enterprise")]
#[tokio::test]
async fn test_shared_reclassification_keeps_the_visible_row_sequence_proof() {
use crate::sst::file::RowSequenceProvenance;
let mut env = TestEnv::new().await;
let engine = env.create_engine(Default::default()).await;
let region_id = RegionId::new(1, 1);
engine
.handle_request(
region_id,
RegionRequest::Create(CreateRequestBuilder::new().build()),
)
.await
.unwrap();
let region = engine.get_region(region_id).unwrap();
let file_id = FileId::random();
let produced = FileMeta {
region_id,
file_id,
row_sequence_provenance: Some(RowSequenceProvenance::Original),
..Default::default()
};
region.version_control.apply_edit(
Some(RegionEdit {
files_to_add: vec![produced.clone()],
..Default::default()
}),
&[],
region.file_purger.clone(),
);
let mut reclassified = RegionEdit {
files_to_add: vec![FileMeta {
level: LEVEL_SHARED,
row_sequence_provenance: None,
..produced.clone()
}],
..Default::default()
};
prepare_region_edit(&region, &mut reclassified, true).unwrap();
assert_eq!(
Some(RowSequenceProvenance::Original),
reclassified.files_to_add[0].row_sequence_provenance,
"the visible object keeps its proof; the caller states nothing"
);
}
#[rstest::rstest]
#[case::shared_removal(false)]
#[case::unsupported_level(true)]
#[case(false)]
#[case(true)]
#[tokio::test]
async fn test_rejected_edit_does_not_stop_manifest(#[case] unsupported_level: bool) {
async fn test_rejected_edit_does_not_stop_manifest(#[case] remove: bool) {
let mut env = TestEnv::new().await;
let engine = env.create_engine(Default::default()).await;
let region_id = RegionId::new(1, 1);
@@ -1522,22 +1396,17 @@ mod tests {
let file = FileMeta {
region_id,
file_id: FileId::random(),
level: if unsupported_level {
// An ordinary-looking but unallocated level; rejected in every build.
2
} else {
LEVEL_SHARED
},
level: 2,
..Default::default()
};
let mut edit = if unsupported_level {
let mut edit = if remove {
RegionEdit {
files_to_add: vec![file],
files_to_remove: vec![file],
..Default::default()
}
} else {
RegionEdit {
files_to_remove: vec![file],
files_to_add: vec![file],
..Default::default()
}
};
+2 -6
View File
@@ -35,7 +35,7 @@ use crate::metrics::INDEX_PUBLICATION_STALE_TOTAL;
use crate::region::options::IndexOptions;
use crate::region::{IndexBuildSource, MitoRegionRef, RegionLeaderState, RegionRoleState};
use crate::request::{BuildIndexRequest, IndexBuildFinished, IndexBuildStopped, OptionOutputTx};
use crate::sst::file::{self, FileHandle, FileMeta, FileMetaRef, RegionFileId, RegionIndexId};
use crate::sst::file::{FileHandle, FileMeta, FileMetaRef, RegionFileId, RegionIndexId};
use crate::sst::index::handler::{IndexKindProviderRef, PlanContext};
use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
use crate::sst::index::registry::{IndexRegistry, IndexRegistryRef};
@@ -301,11 +301,7 @@ impl<S> RegionWorkerLoop<S> {
.levels()
.iter()
.flat_map(|level| level.files.iter())
.filter(|(_, handle)| {
!handle.is_deleted()
&& !handle.compacting()
&& handle.level() < file::LEVEL_SHARED
})
.filter(|(_, handle)| !handle.is_deleted() && !handle.compacting())
.map(|(id, handle)| (*id, handle.clone()))
.collect();
let snapshot = IndexBuildSnapshot {
@@ -1,273 +0,0 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
//! At-least-once requests, conditional file publication, no durable task state.
use std::collections::HashSet;
use snafu::ensure;
use store_api::storage::RegionId;
use crate::engine::table_compaction::{
PublicationContext, is_table_compaction_metadata_compatible, output,
};
use crate::error::{InvalidRequestSnafu, RegionBusySnafu, Result, StaleCompactionExecutionSnafu};
use crate::manifest::action::{RegionEdit, RegionManifest, RegionMetaAction, RegionMetaActionList};
use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState};
use crate::request::RegionEditOutcome;
use crate::sst::file::{FileMeta, LEVEL_SHARED};
pub(crate) async fn publish(
region: &MitoRegionRef,
context: &PublicationContext,
edit: RegionEdit,
) -> Result<RegionEditOutcome> {
let snapshot = region.manifest_ctx.manifest().await;
let replay = is_replay(region, context, &edit, &snapshot)?;
validate_files(region, context, &edit)?;
if !replay {
check_sequence_policy(region, context, &edit)?;
output::verify_and_notify(region, &context.metadata, &edit.files_to_add).await?;
}
let mut manager = region.manifest_ctx.manifest_manager.write().await;
ensure!(
matches!(
region.state(),
RegionRoleState::Leader(RegionLeaderState::Editing | RegionLeaderState::Downgrading)
) && !manager.is_stopped(),
RegionBusySnafu {
region_id: region.region_id
}
);
if is_replay(region, context, &edit, &manager.manifest())? {
region
.manifest_ctx
.ensure_leader_lease_or_downgrading(region.region_id)?;
region.manifest_ctx.ensure_commit_deadline(&manager)?;
return Ok(RegionEditOutcome::AlreadyApplied);
}
// A previously satisfied request skipped object verification.
ensure!(
!replay,
StaleCompactionExecutionSnafu {
region_id: region.region_id
}
);
check_sequence_policy(region, context, &edit)?;
let pending = match region
.manifest_ctx
.update_locked(
&mut manager,
RegionMetaActionList::with_action(RegionMetaAction::Edit(edit)),
false,
)
.await
{
Ok(pending) => pending,
Err(error) => {
if error.may_have_persisted_manifest_update() {
// Do not accept another publication against a potentially stale
// in-memory file set. Completion removes this incarnation.
manager.stop().await;
}
return Err(error);
}
};
drop(manager);
pending.fire().await;
Ok(RegionEditOutcome::Written)
}
fn check_sequence_policy(
region: &MitoRegionRef,
context: &PublicationContext,
edit: &RegionEdit,
) -> Result<()> {
// An exact scan can skip an unmarked input below its lower bound, but
// an unmarked replacement can inherit a higher sequence from another input.
if !context.options.preserve_row_sequence && region.version().options.preserve_row_sequence {
ensure!(
edit.files_to_add
.iter()
.all(|file| file.preserve_row_sequence),
StaleCompactionExecutionSnafu {
region_id: region.region_id
}
);
}
Ok(())
}
fn is_replay(
region: &MitoRegionRef,
context: &PublicationContext,
edit: &RegionEdit,
manifest: &RegionManifest,
) -> Result<bool> {
let region_id = region.region_id;
ensure!(
is_table_compaction_metadata_compatible(&context.metadata, &manifest.metadata)
&& !edit.files_to_remove.is_empty(),
StaleCompactionExecutionSnafu { region_id }
);
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()
.all(|file| !manifest.files.contains_key(&file.file_id)),
InvalidRequestSnafu {
region_id,
reason: "Invalid region-local compaction output"
}
);
return Ok(false);
}
// 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_output),
StaleCompactionExecutionSnafu { region_id }
);
Ok(true)
}
fn validate_files(
region: &MitoRegionRef,
context: &PublicationContext,
edit: &RegionEdit,
) -> Result<()> {
let region_id = region.region_id;
let mut inputs = HashSet::new();
ensure!(
edit.files_to_remove
.iter()
.all(|file| file.level == LEVEL_SHARED
&& file.region_id.table_id() == region_id.table_id()
&& inputs.insert(file.file_id)),
InvalidRequestSnafu {
region_id,
reason: "Expected distinct, already-admitted shared inputs"
}
);
let trusted = context.options.preserve_row_sequence
&& edit
.files_to_remove
.iter()
.all(|file| file.is_effective_target_sequence_trusted(region_id));
let partition =
crate::region::parse_partition_expr(context.metadata.partition_expr.as_deref())?;
let sequence = edit
.files_to_remove
.iter()
.map(|file| file.sequence)
.collect::<Option<Vec<_>>>()
.and_then(|sequences| sequences.into_iter().max());
let mut outputs = HashSet::new();
ensure!(
edit.files_to_add
.iter()
.all(|file| file.region_id == region_id
&& file.level == 0
&& 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,
reason: "Invalid region-local compaction output"
}
);
validate_row_sequence_provenance(region_id, &edit.files_to_remove, &edit.files_to_add)
}
/// Rejects an output's original-row-sequence claim unless every pinned input
/// proves it: a router decides per row which input feeds an output.
fn validate_row_sequence_provenance(
region_id: RegionId,
inputs: &[FileMeta],
outputs: &[FileMeta],
) -> Result<()> {
let claimed = outputs
.iter()
.any(|output| output.has_original_row_sequences());
ensure!(
!claimed
|| inputs.iter().all(|input| {
input.region_id == region_id && input.has_original_row_sequences()
}),
InvalidRequestSnafu {
region_id,
reason: "Original row sequences are unprovable for this input inventory"
}
);
Ok(())
}
#[cfg(test)]
mod tests {
use store_api::storage::FileId;
use super::*;
use crate::sst::file::RowSequenceProvenance;
fn proved(region_id: RegionId, prove: bool) -> FileMeta {
let file_id = FileId::random();
FileMeta {
region_id,
file_id,
row_sequence_provenance: prove.then_some(RowSequenceProvenance::Original),
..Default::default()
}
}
#[test]
fn test_unproved_input_rejects_original_output() {
let region_id = RegionId::new(1, 1);
let inputs = [proved(region_id, true), proved(region_id, false)];
let outputs = [proved(region_id, true)];
let error = validate_row_sequence_provenance(region_id, &inputs, &outputs).unwrap_err();
assert!(
matches!(&error, crate::error::Error::InvalidRequest { region_id: id, .. } if *id == region_id),
"{error:?}"
);
}
#[test]
fn test_proved_inputs_allow_original_output() {
let region_id = RegionId::new(1, 1);
let inputs = [proved(region_id, true), proved(region_id, true)];
let outputs = [proved(region_id, true)];
validate_row_sequence_provenance(region_id, &inputs, &outputs).unwrap();
}
}
+1 -4
View File
@@ -1541,10 +1541,7 @@ pub struct MitoCopyRegionFromRequest {
#[derive(Debug, Clone)]
pub struct MitoCopyRegionFromResponse {
/// Source SST IDs installed in the target by this copy. Shared references may
/// be installed without copying their physical objects. If no new references
/// need installation, returns the source IDs already present in the target.
/// This is not a count or inventory of physical object transfers.
/// Source SST IDs installed in the target by this copy.
pub copied_file_ids: Vec<FileId>,
}
+1 -5
View File
@@ -2012,9 +2012,6 @@ pub struct RegionBuildIndexRequest {
#[derive(Debug)]
pub enum RegionTruncateRequest {
/// Truncate all data in the region.
///
/// Mito2 also retires this region's shared SST references. Other regions and
/// existing readers may still retain the physical objects.
All,
/// Discard all unflushed data while preserving persisted SST files.
///
@@ -2026,8 +2023,7 @@ pub enum RegionTruncateRequest {
/// WAL is obsoleted last. Retrying is safe: a request against a region with nothing
/// left to discard only re-attempts the WAL obsoletion.
Unflushed,
/// Retires fully contained SST references, including shared SSTs in Mito2.
/// Physical reclamation still waits for other references and readers.
/// Retires fully contained SST references.
ByTimeRanges {
/// Time ranges to truncate. Both bound are inclusive.
/// only files that are fully contained in the time range will be truncated.
+2 -3
View File
@@ -73,9 +73,8 @@ Frozen objects of the object store WAL are checked byte for byte by the format t
## Manifest fixtures
[Table-compaction fixtures](manifest/table_compaction/README.md) are exercised by
mito2's Rust tests. They cover ordinary file-edit compatibility, supported SST
levels, and explicit rejection of unpublished prototype task-state records.
[Region-edit fixtures](manifest/region_edit/) are exercised by mito2's Rust tests.
They cover ordinary file-edit compatibility and the supported L0/L1 SST levels.
The inline sketch-index fixtures in `src/mito2/src/manifest/action.rs` cover both
file-level and column-level descriptors and mixed builtin/sketch indexes. They run without the enterprise feature:
@@ -1,54 +0,0 @@
# File-only compaction manifest compatibility
The hand-authored frozen fixtures use the JSON schema of `RegionEdit` and
`RegionManifest` at `4092fe6549`. They are schema fixtures, not captures from a
released binary. They preserve L0/L1 metadata, sequences and flush boundaries.
V1 publishes compaction results using ordinary file edits. It adds no task IDs,
phases, receipts, request epochs or extension-state fields to the manifest.
Task retries may be submitted more than once; publication checks current inputs.
The Enterprise `publish_table_compaction` API consumes a query-visible input
snapshot and returns `Applied` or `StaleInputs`. A stale attempt must re-snapshot
and replan, never re-import its old inputs. Even stale/error outcomes must not
trigger blind output deletion: an earlier attempt may already have published
those objects. Callers retain output protection until recovery or GC resolves
liveness.
Publication tests (including partial success, lost ACKs and reopened regions):
```sh
cargo nextest run -p mito2 --features enterprise -E 'test(engine::table_compaction)'
```
```sh
cargo nextest run -p mito2 -E 'test(manifest::tests::compatibility)'
cargo nextest run -p mito2 --features enterprise -E 'test(manifest::tests::compatibility)'
```
The tests exercise legacy delta/checkpoint reads and verify that serialization
still contains no task-state fields. Optional future core fields remain readable.
Unknown SST levels are rejected; the shared sentinel level (the u8 maximum)
requires Enterprise capability.
This does not establish downgrade safety after shared files are introduced.
The earlier, unpublished prototype persisted `table_compaction` / `extensions`
task records. Canonical delta/checkpoint decoders reject those records in both
builds rather than silently dropping recovery evidence. They require explicit
migration; this version does not resume that prototype's Prepare/Commit protocol.
## Optional file facts
`FileMeta` may carry facts that only a producer can prove. Each is optional and
is omitted from the manifest when unproved.
`row_sequence_provenance` describes a Parquet SST's physical `__sequence`
column. `original` states that the file keeps its own region's allocator numbers;
`substituted_up_to` states that only numbers above a cut are known to be original.
The statement is per-file metadata, and admission clears it on copy and external
edit. A missing value is unproved - absence never means "not
original" - and the statement is independent of the target-effective
`preserve_row_sequence` marker, which says nothing about the encoded bytes.
The fixture is a hand-authored schema fixture, not evidence about a released
binary. The test only establishes that a manifest without this new optional field
still decodes and that re-encoding does not invent it.