diff --git a/licenserc-enterprise.toml b/licenserc-enterprise.toml index 979f8d13fda..af1ce399f33 100644 --- a/licenserc-enterprise.toml +++ b/licenserc-enterprise.toml @@ -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", diff --git a/licenserc.toml b/licenserc.toml index f004568e9d2..0b100662a55 100644 --- a/licenserc.toml +++ b/licenserc.toml @@ -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", diff --git a/src/cmd/src/datanode/sst_replace.rs b/src/cmd/src/datanode/sst_replace.rs index 9d880dfac52..4b7d743270b 100644 --- a/src/cmd/src/datanode/sst_replace.rs +++ b/src/cmd/src/datanode/sst_replace.rs @@ -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(); } diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index d3eb11dbf2c..8156e640bc5 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -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. diff --git a/src/mito2/Cargo.toml b/src/mito2/Cargo.toml index 1070958b8d9..6fff89447a9 100644 --- a/src/mito2/Cargo.toml +++ b/src/mito2/Cargo.toml @@ -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] diff --git a/src/mito2/src/access_layer.rs b/src/mito2/src/access_layer.rs index 5c24d29f65e..64fe937c3c0 100644 --- a/src/mito2/src/access_layer.rs +++ b/src/mito2/src/access_layer.rs @@ -145,7 +145,6 @@ pub struct AccessLayer { puffin_manager_factory: PuffinManagerFactory, /// Intermediate manager for inverted index. intermediate_manager: IntermediateManager, - file_protection: Option, } 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, - ) -> Self { - self.file_protection = hook; - self - } - - pub(crate) async fn is_file_protected(&self, file: RegionFileId) -> crate::error::Result { - 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; diff --git a/src/mito2/src/compaction.rs b/src/mito2/src/compaction.rs index af18906ce19..ec1994fae4b 100644 --- a/src/mito2/src/compaction.rs +++ b/src/mito2/src/compaction.rs @@ -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; diff --git a/src/mito2/src/compaction/compactor.rs b/src/mito2/src/compaction/compactor.rs index 3da16d8bb36..b1638b9e510 100644 --- a/src/mito2/src/compaction/compactor.rs +++ b/src/mito2/src/compaction/compactor.rs @@ -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, Vec)> { 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 { - 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; diff --git a/src/mito2/src/compaction/last_non_null.rs b/src/mito2/src/compaction/last_non_null.rs index 5e6c2bb1102..efbd56bb197 100644 --- a/src/mito2/src/compaction/last_non_null.rs +++ b/src/mito2/src/compaction/last_non_null.rs @@ -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); diff --git a/src/mito2/src/compaction/multi_region.rs b/src/mito2/src/compaction/multi_region.rs deleted file mode 100644 index 0854f33e69e..00000000000 --- a/src/mito2/src/compaction/multi_region.rs +++ /dev/null @@ -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, -} - -/// 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, - /// Metadata and routing must belong to the same physical-table snapshot. - pub targets: BTreeMap, - /// 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, - pub access_layer: AccessLayerRef, - pub cache: CacheManagerRef, - pub config: Arc, - pub protection: Arc, - 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>, - /// Complete footer/index statistics for target hook delivery; not fabricated from FileMeta. - pub sst_infos: BTreeMap>, - 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 { - 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 { - 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::()), - ); - 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()) -} diff --git a/src/mito2/src/compaction/multi_region/memory.rs b/src/mito2/src/compaction/multi_region/memory.rs deleted file mode 100644 index efc84227de0..00000000000 --- a/src/mito2/src/compaction/multi_region/memory.rs +++ /dev/null @@ -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, - pub(crate) writer: SstWriteLimits, - pub(crate) estimated: u64, -} - -impl MemoryLimits { - pub(crate) fn new( - plan: &MultiRegionCompactionPlan, - schema: &SchemaRef, - upload: UploadBudget, - ) -> Result { - 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], - 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], - ) -> Result { - // 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 { - 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::()) 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 { - 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, - max_object_bytes: u64, -} - -impl UploadBudget { - pub(crate) fn new(plan: &MultiRegionCompactionPlan, store: &ObjectStore) -> Result { - 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 { - 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 { - 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, - 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, - #[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 - } - ); - } -} diff --git a/src/mito2/src/compaction/multi_region/source.rs b/src/mito2/src/compaction/multi_region/source.rs deleted file mode 100644 index 73f0e1de844..00000000000 --- a/src/mito2/src/compaction/multi_region/source.rs +++ /dev/null @@ -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, usize)>, - offset: usize, -} - -impl RoutedBatch { - fn next_fragment(&mut self, source: &SharedSource) -> Result> { - 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, - legacy_overrides: Vec, - expected_rows: Vec, - targets: BTreeMap, - metadata: RegionMetadataRef, - scan_input: ScanInput, - routing_codec: Arc, - schema: SchemaRef, - merge_schema: SchemaRef, - partition_rule: PartitionRuleRef, - window: (Timestamp, Timestamp), - pub(crate) limits: MemoryLimits, - pub(crate) index_plans: BTreeMap>, - /// 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, - /// 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, -} - -impl SharedSource { - pub(crate) async fn build( - plan: &MultiRegionCompactionPlan, - context: &MultiRegionCompactionContext, - metadata: RegionMetadataRef, - counters: Arc, - ) -> Result> { - 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 = 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::>(); - 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::>(); - 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, - ) -> std::pin::Pin> + 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, - batches: Vec, - ) -> std::pin::Pin> + 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, 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, i64, Reverse)>, - ) -> 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::() - .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 { - // 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::() - .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) -> Result { - self.check_cancelled()?; - let batch = concat_batches(&self.merge_schema, &batches).context(ComputeArrowSnafu)?; - let owners = batch - .column(0) - .as_any() - .downcast_ref::() - .context(InvalidMultiRegionCompactionSnafu { - reason: "Missing routing annotation", - })?; - let sequences = batch - .column(1) - .as_any() - .downcast_ref::() - .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> { - 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], - ) -> 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::>>()?; - for (row, owner) in owners - .iter_mut() - .enumerate() - .filter(|(_, owner)| owner.is_none()) - { - let values = columns - .iter() - .map(|column| column.get(row)) - .collect::>(); - 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, - 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>> { - 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::()); - 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 { - 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 { - 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 { - 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 { - 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::(array), - DataType::Binary => compact_dictionary::(array), - _ => Ok(array.clone()), - }, - _ => Ok(array.clone()), - }) - .collect::>>()?; - RecordBatch::try_new(batch.schema(), columns).context(NewRecordBatchSnafu) -} - -fn compact_dictionary(array: &ArrayRef) -> Result { - let decoded = cast(array, &T::DATA_TYPE).context(ComputeArrowSnafu)?; - let values = decoded - .as_any() - .downcast_ref::>() - .context(InvalidMultiRegionCompactionSnafu { - reason: "Invalid decoded dictionary", - })?; - let mut builder = GenericByteDictionaryBuilder::::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::() - .context(InvalidMultiRegionCompactionSnafu { - reason: "Invalid primary-key column", - })?; - let values = keys - .values() - .as_any() - .downcast_ref::() - .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, limit: usize) -> MemoryThreshold { - MemoryThreshold::Size(ReadableSize(configured.unwrap_or(limit).min(limit) as u64)) -} diff --git a/src/mito2/src/compaction/multi_region/tests.rs b/src/mito2/src/compaction/multi_region/tests.rs deleted file mode 100644 index 894516bfe4d..00000000000 --- a/src/mito2/src/compaction/multi_region/tests.rs +++ /dev/null @@ -1,3400 +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::collections::{BTreeMap, HashSet}; -use std::num::NonZeroU64; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use api::v1::{OpType, SemanticType}; -use common_error::ext::BoxedError; -use datatypes::arrow::array::{ - Array, ArrayRef, BinaryArray, BinaryDictionaryBuilder, BooleanArray, DictionaryArray, - StringArray, StringDictionaryBuilder, TimestampMillisecondArray, UInt8Array, UInt64Array, -}; -use datatypes::arrow::compute::cast; -use datatypes::arrow::datatypes::{DataType, Field, UInt32Type}; -use datatypes::arrow::record_batch::RecordBatch; -use datatypes::extension::json::{Json2ExtensionType, Json2PhysicalLayout, JsonMetadata}; -use datatypes::json::{JsonSettings, JsonTypeHint}; -use datatypes::prelude::ConcreteDataType; -use datatypes::schema::ColumnSchema; -use datatypes::types::json_type::JsonNativeType; -use datatypes::types::parse_string_to_jsonb; -use datatypes::value::Value; -use datatypes::vectors::json::array::JsonArray; -use datatypes::vectors::json::json2_physical_data_type; -use futures::TryStreamExt; -use futures::io::{self, AsyncReadExt}; -use object_store::layers::CapabilityOverrideLayer; -use object_store::layers::mock::oio::Write as _; -use object_store::layers::mock::{self, MockLayerBuilder, oio}; -use partition::expr::col; -use partition::multi_dim::MultiDimPartitionRule; -use puffin::puffin_manager::{PuffinManager, PuffinReader, PuffinWriter}; -use rand::{RngCore, SeedableRng, rngs::SmallRng}; -use serde_json::json; -use store_api::codec::PrimaryKeyEncoding; -use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataBuilder}; -use store_api::region_request::PathType; -use store_api::storage::RegionId; -use tokio::sync::watch; - -use super::*; -use crate::access_layer::{AccessLayer, Metrics, OperationType, SstWriteRequest, WriteType}; -use crate::cache::{CacheManager, CacheStrategy}; -use crate::error::InvalidMultiRegionCompactionSnafu; -use crate::read::FlatSource; -use crate::sst::file::{FileHandle, RegionFileId, RowSequenceProvenance}; -use crate::sst::file_purger::NoopFilePurger; -use crate::sst::index::CompletedEntry; -use crate::sst::index::handler::{ - BuildContext, IndexCreator, IndexKindHandler, IndexKindProvider, PlanContext, PlanEntry, - PlannedIndex, -}; -use crate::sst::index::intermediate::IntermediateManager; -use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; -use crate::sst::index::puffin_manager::{PuffinManagerFactory, SstPuffinWriter}; -use crate::sst::location; -use crate::sst::parquet::WriteOptions; -use crate::sst::parquet::flat_format::{ - primary_key_column_index, sequence_column_index, time_index_column_index, -}; -use crate::sst::{FlatSchemaOptions, FormatType, to_flat_sst_arrow_schema}; -use crate::test_util::scheduler_util::SchedulerEnv; -use crate::test_util::sst_util::{ - build_test_binary_test_region_metadata, new_flat_source_from_record_batches, - new_record_batch_with_binary_values, new_record_batch_with_custom_sequence, - new_sparse_primary_key, sst_region_metadata_with_encoding, -}; - -struct Protection { - layer: AccessLayerRef, - files: Mutex>, - fail_region: Option, - first_protected: tokio::sync::Notify, -} - -#[async_trait::async_trait] -impl SstWriteGuard for Protection { - async fn before_create(&self, file_id: RegionFileId) -> Result<()> { - let path = crate::sst::location::sst_file_path( - self.layer.table_dir(), - file_id, - self.layer.path_type(), - ); - assert!( - !self.layer.object_store().exists(&path).await.unwrap(), - "SST already existed before protection" - ); - if self.fail_region == Some(file_id.region_id()) { - // Failure must occur after another worker has protected an output; - // worker scheduling no longer follows region-id order. - self.first_protected.notified().await; - return InvalidMultiRegionCompactionSnafu { - reason: "injected output protection failure", - } - .fail(); - } - assert!(self.files.lock().unwrap().insert(file_id)); - self.first_protected.notify_one(); - Ok(()) - } -} - -struct Fixture { - env: SchedulerEnv, - layer: AccessLayerRef, - metadata: RegionMetadataRef, - source: FileMeta, - config: Arc, -} - -type TestRow = (u32, i64, u64, u8, Option); - -impl Fixture { - async fn new(encoding: PrimaryKeyEncoding, format: FormatType, physical_sequence: u64) -> Self { - Self::with_source(encoding, format, |metadata| { - (0..31) - .map(|series| source_batch(metadata, series, physical_sequence)) - .collect() - }) - .await - } - - async fn with_source( - encoding: PrimaryKeyEncoding, - format: FormatType, - batches: impl FnOnce(&RegionMetadataRef) -> Vec, - ) -> Self { - let mut fixture = Self::without_source(sst_region_metadata_with_encoding(encoding)).await; - let mut batches = batches(&fixture.metadata); - batches.sort_by_cached_key(|batch| { - let keys = cast( - batch.column(primary_key_column_index(batch.num_columns())), - &DataType::Binary, - ) - .unwrap(); - keys.as_any() - .downcast_ref::() - .unwrap() - .value(0) - .to_vec() - }); - let info = fixture - .write_source(fixture.metadata.clone(), batches, format) - .await; - fixture.source = file_meta(info, fixture.metadata.region_id); - fixture - } - - async fn without_source(mut metadata: RegionMetadata) -> Self { - let env = SchedulerEnv::new().await; - let aux = env.path.path().join("table-index"); - let layer = Arc::new(AccessLayer::new( - "table/", - if metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse { - PathType::Data - } else { - PathType::Bare - }, - env.access_layer.object_store().clone(), - PuffinManagerFactory::new(&aux, 1024 * 1024, None, None) - .await - .unwrap(), - IntermediateManager::init_fs(aux.to_str().unwrap()) - .await - .unwrap(), - )); - metadata.region_id = RegionId::new(1, 0); - let mut config = MitoConfig::default(); - config.index.aux_path = aux.display().to_string(); - Self { - env, - layer, - metadata: Arc::new(metadata), - source: FileMeta::default(), - config: Arc::new(config), - } - } - - async fn write_source( - &self, - metadata: RegionMetadataRef, - batches: Vec, - format: FormatType, - ) -> SstInfo { - self.write_source_with_options(metadata, batches, format, &WriteOptions::default()) - .await - } - - async fn write_source_with_options( - &self, - metadata: RegionMetadataRef, - batches: Vec, - format: FormatType, - options: &WriteOptions, - ) -> SstInfo { - self.layer - .write_sst( - write_request( - metadata, - new_flat_source_from_record_batches(batches), - &self.config, - format, - ), - options, - &mut Metrics::new(WriteType::Flush), - ) - .await - .unwrap() - .remove(0) - } - - async fn write_additional_source(&self, batches: Vec) -> FileMeta { - let info = self - .write_source(self.metadata.clone(), batches, FormatType::Flat) - .await; - file_meta(info, self.metadata.region_id) - } - - fn plan(&self, regions: u32) -> MultiRegionCompactionPlan { - self.plan_with_sources(regions, vec![self.source.clone()]) - } - - fn plan_with_sources(&self, regions: u32, sources: Vec) -> MultiRegionCompactionPlan { - let mut targets = BTreeMap::new(); - for region in 0..regions { - let id = RegionId::new(1, region); - let mut metadata = (*self.metadata).clone(); - metadata.region_id = id; - let start = format!("{:03}", region * 32 / regions); - let end = format!("{:03}", (region + 1) * 32 / regions); - metadata.set_partition_expr(Some( - col("tag_0") - .gt_eq(Value::String(start.into())) - .and(col("tag_0").lt(Value::String(end.into()))) - .as_json_str() - .unwrap(), - )); - let inputs = sources - .iter() - .cloned() - .map(|mut input| { - input.sequence = NonZeroU64::new(100 + region as u64); - (input.file_id(), input) - }) - .collect(); - let options = RegionOptions { - append_mode: true, - preserve_row_sequence: true, - sst_format: Some(FormatType::Flat), - ..Default::default() - }; - targets.insert( - id, - MultiRegionTarget { - metadata: Arc::new(metadata), - options, - inputs, - }, - ); - } - let exprs = targets - .values() - .map(|target| { - crate::region::parse_partition_expr(target.metadata.partition_expr.as_deref()) - .unwrap() - .unwrap() - }) - .collect(); - let partition_rule = Arc::new( - MultiDimPartitionRule::try_new( - vec!["tag_0".into()], - (0..regions).collect(), - exprs, - false, - ) - .unwrap(), - ); - MultiRegionCompactionPlan { - partition_rule, - sources, - targets, - // Includes the fixed Parquet encoder allocations of every resident - // target, unlike the old run-cache-only budget. - memory_limit: (128 + regions as usize * 32) * 1024 * 1024, - max_output_file_size: 1024 * 1024, - window_start: 0, - window_seconds: 3600, - } - } - - fn context( - &self, - fail_region: Option, - ) -> (MultiRegionCompactionContext, Arc) { - let protection = Arc::new(Protection { - layer: self.layer.clone(), - files: Mutex::default(), - fail_region, - first_protected: tokio::sync::Notify::new(), - }); - ( - MultiRegionCompactionContext { - index_kind_provider: None, - access_layer: self.layer.clone(), - cache: Arc::new(CacheManager::default()), - config: self.config.clone(), - protection: protection.clone(), - cancellation: CancellationToken::new(), - }, - protection, - ) - } - - async fn compact(&self, plan: MultiRegionCompactionPlan) -> MultiRegionCompactionOutput { - compact_regions(plan, self.context(None).0).await.unwrap() - } - - /// Reads an output exactly as the owning region will once the returned - /// metadata is published: partition filtering and sequence override are - /// both derived from that metadata. - async fn read_published_output( - &self, - file: FileMeta, - metadata: RegionMetadataRef, - ) -> Vec { - let expected_region = file.region_id; - let expected_rows = file.num_rows; - let mut reader = self - .layer - .read_sst(FileHandle::new(file, Arc::new(NoopFilePurger))) - .expected_metadata(Some(metadata.clone())) - .cache(CacheStrategy::Disabled) - .build() - .await - .unwrap() - .unwrap(); - assert_eq!(expected_region, reader.metadata().region_id); - assert_eq!( - metadata.column_metadatas, - reader.metadata().column_metadatas - ); - assert_eq!( - expected_rows, - reader.parquet_metadata().file_metadata().num_rows() as u64 - ); - let mut batches = Vec::new(); - while let Some(batch) = reader.next_record_batch().await.unwrap() { - batches.push(batch); - } - assert_eq!( - expected_rows, - batches - .iter() - .map(|batch| batch.num_rows() as u64) - .sum::() - ); - batches - } - - async fn read_published_output_rows( - &self, - file: FileMeta, - metadata: RegionMetadataRef, - ) -> Vec { - self.decode_base_rows(self.read_published_output(file, metadata).await) - } - - async fn read_output( - &self, - mut file: FileMeta, - metadata: RegionMetadataRef, - ) -> Vec { - // Inspect the physical contents: a partition filter or sequence override - // on read must not hide incorrectly routed/written records. - file.sequence = None; - file.preserve_row_sequence = true; - let mut unfiltered = (*metadata).clone(); - unfiltered.set_partition_expr(None); - self.read_published_output(file, Arc::new(unfiltered)).await - } - - async fn read_output_rows(&self, file: FileMeta, metadata: RegionMetadataRef) -> Vec { - self.decode_base_rows(self.read_output(file, metadata).await) - } - - fn decode_base_rows(&self, batches: Vec) -> Vec { - let mut decoded = Vec::new(); - for batch in batches { - let sequences = batch - .column(sequence_column_index(batch.num_columns())) - .as_any() - .downcast_ref::() - .unwrap(); - let operations = batch - .column(batch.num_columns() - 1) - .as_any() - .downcast_ref::() - .unwrap(); - let keys = cast( - batch.column(primary_key_column_index(batch.num_columns())), - &DataType::Binary, - ) - .unwrap(); - let keys = keys.as_any().downcast_ref::().unwrap(); - let tags = cast(batch.column_by_name("tag_0").unwrap(), &DataType::Utf8).unwrap(); - let tags = tags.as_any().downcast_ref::().unwrap(); - let times = crate::read::timestamp_array_to_i64_slice( - batch.column(time_index_column_index(batch.num_columns())), - ); - let values = batch - .column_by_name("field_0") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - for (row, timestamp) in times.iter().enumerate() { - let series: u32 = tags.value(row).parse().unwrap(); - let expected_key = - if self.metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse { - new_sparse_primary_key( - &[tags.value(row), "series"], - &self.metadata, - 1000 + series % 2, - series as u64, - ) - } else { - crate::test_util::sst_util::new_primary_key(&[tags.value(row), "series"]) - }; - assert_eq!(expected_key, keys.value(row)); - decoded.push(( - series, - *timestamp, - sequences.value(row), - operations.value(row), - values.is_valid(row).then(|| values.value(row)), - )); - } - } - decoded - } -} - -fn expected_source_rows(regions: u32, id: RegionId, sequence: u64) -> Vec { - let mut rows = Vec::new(); - for series in - (id.region_sequence() * 32 / regions)..(((id.region_sequence() + 1) * 32 / regions).min(31)) - { - rows.extend([ - (series, 0, sequence, OpType::Put as u8, Some(10)), - (series, 0, sequence, OpType::Put as u8, Some(20)), - (series, 0, sequence, OpType::Delete as u8, None), - (series, 1_000, sequence, OpType::Put as u8, Some(30)), - ]); - } - rows -} - -fn file_meta(info: SstInfo, region_id: RegionId) -> FileMeta { - FileMeta { - region_id, - file_id: info.file_id, - time_range: info.time_range, - file_size: info.file_size, - num_rows: info.num_rows as u64, - num_row_groups: info.num_row_groups, - max_row_group_uncompressed_size: info.max_row_group_uncompressed_size, - ..Default::default() - } -} - -fn write_request( - metadata: RegionMetadataRef, - source: FlatSource, - config: &MitoConfig, - format: FormatType, -) -> SstWriteRequest { - SstWriteRequest { - index_build_inputs: None, - op_type: OperationType::Flush, - metadata, - source, - cache_manager: Arc::new(CacheManager::default()), - max_sequence: None, - sst_write_format: format, - preserve_row_sequence: false, - index_options: Default::default(), - 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(), - } -} - -fn source_batch(metadata: &RegionMetadataRef, series: u32, sequence: u64) -> RecordBatch { - let tag = format!("{series:03}"); - let batch = new_record_batch_with_custom_sequence(&[&tag, "series"], 0, 4, sequence); - let mut arrays = batch.columns().to_vec(); - arrays[2] = Arc::new(UInt64Array::from(vec![Some(10), Some(20), None, Some(30)])); - arrays[3] = Arc::new(TimestampMillisecondArray::from(vec![0, 0, 0, 1_000])); - arrays[6] = Arc::new(UInt8Array::from(vec![ - OpType::Put as u8, - OpType::Put as u8, - OpType::Delete as u8, - OpType::Put as u8, - ])); - if metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse { - let pk = new_sparse_primary_key( - &[&tag, "series"], - metadata, - 1000 + series % 2, - series as u64, - ); - let mut keys = BinaryDictionaryBuilder::::new(); - for _ in 0..4 { - keys.append(&pk).unwrap(); - } - arrays[4] = Arc::new(keys.finish()); - arrays.drain(..2); - } - RecordBatch::try_new( - to_flat_sst_arrow_schema( - metadata, - &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding), - ), - arrays, - ) - .unwrap() -} - -#[rstest::rstest] -#[case::dense_flat_zero(PrimaryKeyEncoding::Dense, FormatType::Flat, 0)] -#[case::dense_primary_native(PrimaryKeyEncoding::Dense, FormatType::PrimaryKey, 7)] -#[case::sparse_flat_zero(PrimaryKeyEncoding::Sparse, FormatType::Flat, 0)] -#[case::sparse_flat_native(PrimaryKeyEncoding::Sparse, FormatType::Flat, 7)] -#[tokio::test] -async fn test_single_scan_routes_all_versions_without_folding( - #[case] encoding: PrimaryKeyEncoding, - #[case] format: FormatType, - #[case] sequence: u64, -) { - let fixture = Fixture::new(encoding, format, sequence).await; - let mut fetched_bytes = None; - for regions in [1, 8, 32] { - let mut plan = fixture.plan(regions); - for target in plan.targets.values_mut() { - target.options.sst_format = Some(format); - } - let targets = plan.targets.clone(); - let (context, protected) = fixture.context(None); - let output = compact_regions(plan, context).await.unwrap(); - assert_eq!(1, output.stats.source_files); - assert_eq!(124, output.stats.source_rows); - assert_eq!(124, output.stats.output_rows); - assert!(output.stats.source_store_page_bytes > 0); - if let Some(bytes) = fetched_bytes { - assert_eq!(bytes, output.stats.source_store_page_bytes); - } - fetched_bytes = Some(output.stats.source_store_page_bytes); - let mut total_deletes = 0; - for (id, files) in output.files { - assert_eq!(files.len(), output.sst_infos[&id].len()); - for (file, footer) in files.iter().zip(&output.sst_infos[&id]) { - assert_eq!(file.file_id, footer.file_id); - assert_eq!(file.file_size, footer.file_size); - assert_eq!(file.num_rows, footer.num_rows as u64); - assert!(file.max_row_group_decoded_size > 0); - assert_eq!( - file.max_row_group_decoded_size, - footer.max_row_group_decoded_size - ); - } - let target = &targets[&id]; - let mut actual_rows = Vec::new(); - if regions == 32 && id.region_sequence() == 31 { - assert!(files.is_empty()); - } - for file in files { - assert!(protected.files.lock().unwrap().contains(&file.file_id())); - assert_eq!(0, file.level); - assert_eq!(id, file.region_id); - assert_eq!(id != fixture.metadata.region_id, file.preserve_row_sequence); - let rows = fixture - .read_output_rows(file, target.metadata.clone()) - .await; - let expected = if id == fixture.metadata.region_id && sequence != 0 { - sequence - } else { - 100 + id.region_sequence() as u64 - }; - assert!(rows.iter().all(|row| row.2 == expected)); - total_deletes += rows - .iter() - .filter(|row| row.3 == OpType::Delete as u8) - .count(); - actual_rows.extend(rows); - } - let expected_sequence = if id == fixture.metadata.region_id && sequence != 0 { - sequence - } else { - 100 + id.region_sequence() as u64 - }; - let mut expected_rows = expected_source_rows(regions, id, expected_sequence); - for series in (id.region_sequence() * 32 / regions) - ..(((id.region_sequence() + 1) * 32 / regions).min(31)) - { - let tied = actual_rows - .iter() - .filter(|row| row.0 == series && row.1 == 0) - .map(|row| (row.3, row.4)) - .collect::>(); - assert_eq!( - vec![ - (OpType::Put as u8, Some(10)), - (OpType::Put as u8, Some(20)), - (OpType::Delete as u8, None) - ], - tied - ); - } - actual_rows.sort(); - expected_rows.sort(); - assert_eq!(expected_rows, actual_rows); - } - assert_eq!(31, total_deletes); - } -} - -#[tokio::test] -async fn test_failed_target_never_returns_a_partial_table_result() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let (context, protection) = fixture.context(Some(RegionId::new(1, 1))); - assert!(compact_regions(fixture.plan(8), context).await.is_err()); - assert!( - !protection.files.lock().unwrap().is_empty(), - "earlier target wrote protected outputs" - ); - let path = crate::sst::location::sst_file_path( - fixture.layer.table_dir(), - fixture.source.file_id(), - fixture.layer.path_type(), - ); - assert!(fixture.layer.object_store().exists(&path).await.unwrap()); -} - -#[rstest::rstest] -#[case::last_row(false, crate::region::options::MergeMode::LastRow)] -#[case::last_non_null(false, crate::region::options::MergeMode::LastNonNull)] -#[case::preserve_row_sequence(true, crate::region::options::MergeMode::LastRow)] -#[tokio::test] -async fn test_table_stage_does_not_fold_versions( - #[case] preserve_sequence: bool, - #[case] merge_mode: crate::region::options::MergeMode, -) { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(8); - for target in plan.targets.values_mut() { - target.options.append_mode = preserve_sequence; - target.options.preserve_row_sequence = preserve_sequence; - target.options.merge_mode = Some(merge_mode); - } - let targets = plan.targets.clone(); - let output = fixture.compact(plan).await; - assert_eq!(124, output.stats.output_rows); - for (id, files) in output.files { - let mut rows = Vec::new(); - for file in files { - assert_eq!( - preserve_sequence && id != fixture.metadata.region_id, - file.preserve_row_sequence - ); - rows.extend( - fixture - .read_output_rows(file, targets[&id].metadata.clone()) - .await, - ); - } - let mut expected = expected_source_rows(8, id, 100 + id.region_sequence() as u64); - rows.sort(); - expected.sort(); - assert_eq!(expected, rows); - } -} - -#[tokio::test] -async fn test_long_tag_stream_is_lossless_and_insufficient_admission_creates_no_output() { - let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { - (0..200) - .map(|series| { - new_record_batch_with_custom_sequence( - &[&format!("{series:03}{}", "x".repeat(96)), "series"], - 0, - 512, - 0, - ) - }) - .collect() - }) - .await; - let mut plan = fixture.plan(1); - for target in plan.targets.values_mut() { - Arc::make_mut(&mut target.metadata).set_partition_expr(None); - } - let output = fixture.compact(plan).await; - assert_eq!(102400, output.stats.output_rows); - assert!(output.stats.estimated_memory_bytes <= 128 * 1024 * 1024); - let mut ordinal = 0; - for file in output.files.into_values().flatten() { - for batch in fixture.read_output(file, fixture.metadata.clone()).await { - let tags = cast(batch.column_by_name("tag_0").unwrap(), &DataType::Utf8).unwrap(); - let tags = tags.as_any().downcast_ref::().unwrap(); - let values = batch - .column_by_name("field_0") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - for row in 0..batch.num_rows() { - assert_eq!( - format!("{:03}{}", ordinal / 512, "x".repeat(96)), - tags.value(row) - ); - assert_eq!(ordinal % 512, values.value(row)); - ordinal += 1; - } - } - } - assert_eq!(102400, ordinal); - let mut plan = fixture.plan(1); - plan.memory_limit = 1024 * 1024; - for target in plan.targets.values_mut() { - Arc::make_mut(&mut target.metadata).set_partition_expr(None); - } - let (context, protected) = fixture.context(None); - let error = compact_regions(plan, context).await.err().unwrap(); - assert!( - matches!( - &error, - crate::error::Error::MultiRegionCompactionResource { .. } - ), - "{error:?}" - ); - assert!(protected.files.lock().unwrap().is_empty()); -} - -#[tokio::test] -async fn test_schema_defaults_are_materialized_without_losing_old_versions() { - use api::v1::SemanticType; - use datatypes::data_type::ConcreteDataType; - use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema}; - use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::PrimaryKey, 7).await; - let mut plan = fixture.plan(8); - for target in plan.targets.values_mut() { - let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone()); - builder.push_column_metadata(ColumnMetadata { - column_id: 10, - semantic_type: SemanticType::Field, - column_schema: ColumnSchema::new("added", ConcreteDataType::uint64_datatype(), false) - .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::UInt64(42)))) - .unwrap(), - }); - target.metadata = Arc::new(builder.build().unwrap()); - } - let targets = plan.targets.clone(); - let output = fixture.compact(plan).await; - assert_eq!(124, output.stats.output_rows); - for (region_id, files) in output.files { - for file in files { - for batch in fixture - .read_output(file, targets[®ion_id].metadata.clone()) - .await - { - let added = batch - .column_by_name("added") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(0, added.null_count()); - assert!(added.values().iter().all(|value| *value == 42)); - } - } - } -} - -#[rstest::rstest] -#[case::known_bounds(false)] -#[case::unknown_bound(true)] -#[tokio::test] -async fn test_multiple_sources_merge_versions_in_each_target_sequence_domain( - #[case] unknown_bound: bool, -) { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 3).await; - let batches = (0..31) - .map(|series| source_batch(&fixture.metadata, series, 7)) - .collect(); - let second = fixture.write_additional_source(batches).await; - let mut plan = fixture.plan(2); - plan.sources.push(second.clone()); - for (id, target) in &mut plan.targets { - let mut input = second.clone(); - input.sequence = if unknown_bound && id.region_sequence() == 1 { - None - } else { - NonZeroU64::new(200 + id.region_sequence() as u64) - }; - target.inputs.insert(input.file_id(), input); - } - let targets = plan.targets.clone(); - let output = fixture.compact(plan).await; - assert_eq!(2, output.stats.source_files); - assert_eq!(248, output.stats.source_rows); - assert_eq!(248, output.stats.output_rows); - for (id, files) in output.files { - let expected = if id.region_sequence() == 0 { - [3, 7] - } else { - [101, if unknown_bound { 7 } else { 201 }] - }; - let mut observed = Vec::new(); - let mut published = Vec::new(); - let files_for_publish = files.clone(); - let published_row_count: u64 = files.iter().map(|file| file.num_rows).sum(); - for file in files { - assert_eq!( - if unknown_bound && id.region_sequence() == 1 { - None - } else { - NonZeroU64::new(200 + id.region_sequence() as u64) - }, - file.sequence - ); - assert_eq!( - id.region_sequence() != 0 && !unknown_bound, - file.preserve_row_sequence - ); - observed.extend( - fixture - .read_output_rows(file, targets[&id].metadata.clone()) - .await, - ); - } - assert_eq!( - expected.into_iter().collect::>(), - observed.iter().map(|row| row.2).collect::>() - ); - for pair in observed.windows(2) { - if pair[0].0 == pair[1].0 && pair[0].1 == pair[1].1 { - assert!(pair[0].2 >= pair[1].2); - } - } - // Publishing the returned metadata must not change any complete row, - // including duplicate versions and their payload association. - for file in files_for_publish { - published.extend( - fixture - .read_published_output_rows(file, targets[&id].metadata.clone()) - .await, - ); - } - assert_eq!( - published_row_count, - published.len() as u64, - "published metadata drops rows of region {id}" - ); - observed.sort(); - published.sort(); - assert_eq!( - observed, published, - "published metadata changes rows of region {id}" - ); - } -} - -#[tokio::test] -async fn test_overlapping_partition_masks_are_rejected_before_creating_outputs() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(3); - // Tags "010".."019" satisfy both predicates. `check_exprs = false` keeps - // the rule as the caller supplied it, so only the executor can reject it. - plan.partition_rule = Arc::new( - MultiDimPartitionRule::try_new( - vec!["tag_0".into()], - vec![1, 2], - vec![ - col("tag_0").gt_eq(Value::String("010".into())), - col("tag_0").lt(Value::String("020".into())), - ], - false, - ) - .unwrap(), - ); - let (context, protection) = fixture.context(None); - let error = compact_regions(plan, context).await.err().unwrap(); - assert!( - matches!(&error, crate::error::Error::InvalidMultiRegionCompaction { reason, .. } - if reason.contains("matches multiple target partitions")), - "{error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); -} - -/// Partition rule whose mask length cannot be produced by a real rule. -struct WrongMaskSizeRule; - -impl partition::PartitionRule for WrongMaskSizeRule { - fn as_any(&self) -> &dyn std::any::Any { - self - } - - fn partition_columns(&self) -> &[String] { - &[] - } - - fn find_region( - &self, - _values: &[Value], - ) -> partition::error::Result { - Ok(0) - } - - fn split_record_batch( - &self, - _batch: &RecordBatch, - ) -> partition::error::Result< - std::collections::HashMap< - store_api::storage::RegionNumber, - partition::partition::RegionMask, - >, - > { - Ok(std::collections::HashMap::from([( - 0, - partition::partition::RegionMask::new(BooleanArray::from(vec![true]), 1), - )])) - } -} - -#[tokio::test] -async fn test_wrong_length_partition_mask_is_rejected_before_creating_outputs() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(2); - plan.partition_rule = Arc::new(WrongMaskSizeRule); - let (context, protection) = fixture.context(None); - let error = compact_regions(plan, context).await.err().unwrap(); - assert!( - matches!(&error, crate::error::Error::InvalidMultiRegionCompaction { reason, .. } - if reason.contains("wrong row count")), - "{error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); -} - -struct Json2Column { - name: &'static str, - column_id: u32, - source_layout: JsonSettings, - target_layout: JsonSettings, - rows: [serde_json::Value; 2], -} - -impl Json2Column { - fn source_array(&self) -> ArrayRef { - let jsonb = Arc::new(BinaryArray::from_iter_values( - self.rows - .iter() - .map(|row| parse_string_to_jsonb(&row.to_string()).unwrap()) - .collect::>() - .iter() - .map(|value| value.as_slice()), - )) as ArrayRef; - let field = Field::new(self.name, DataType::Binary, true) - .with_extension_type(Json2ExtensionType::default()); - JsonArray::from(&jsonb) - .rewrite_to_v2(&field, &self.source_layout, &self.source_layout) - .unwrap() - } - - fn expected_rows(&self) -> [serde_json::Value; 2] { - self.rows.clone().map(|mut row| { - for hint in self.target_layout.type_hints() { - row.as_object_mut() - .unwrap() - .entry(hint.path[0].clone()) - .or_insert(serde_json::Value::Null); - } - row - }) - } -} - -/// Builds dense-encoded metadata with JSON2 fields before `ts`, so the -/// time index stays the last user column as the flat format requires. -fn json2_compaction_metadata( - columns: &[Json2Column], - region_id: RegionId, - target_layout: bool, -) -> RegionMetadataRef { - let mut metadata = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Dense); - metadata.region_id = region_id; - let json_start = metadata.column_metadatas.len() - 1; - for (offset, column) in columns.iter().enumerate() { - let settings = if target_layout { - &column.target_layout - } else { - &column.source_layout - }; - let mut schema = ColumnSchema::new( - column.name, - ConcreteDataType::json2(JsonNativeType::object()), - true, - ); - schema.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( - settings.clone(), - )))); - metadata.column_metadatas.insert( - json_start + offset, - ColumnMetadata { - column_schema: schema, - semantic_type: SemanticType::Field, - column_id: column.column_id, - }, - ); - } - Arc::new( - RegionMetadataBuilder::from_existing(metadata) - .build() - .unwrap(), - ) -} - -fn json2_settings(hints: Vec) -> JsonSettings { - JsonSettings::try_new(hints, Some(0)).unwrap() -} - -fn json2_hint(path: &str, data_type: ConcreteDataType) -> JsonTypeHint { - JsonTypeHint { - path: vec![path.to_string()], - data_type, - inverted_index: false, - skipping_index: None, - fulltext_index: None, - } -} - -fn read_json2_row(batch: &RecordBatch, column: &Json2Column) -> serde_json::Value { - let field = batch.schema_ref().field_with_name(column.name).unwrap(); - assert!( - Json2PhysicalLayout::try_from_root(field) - .unwrap() - .is_version_2() - ); - assert_eq!( - &json2_physical_data_type(&column.target_layout), - field.data_type() - ); - let projected = JsonArray::from(batch.column_by_name(column.name).unwrap()) - .project_to_v2(field, &DataType::Binary) - .unwrap(); - assert_eq!(1, projected.len()); - JsonArray::from(&projected).try_get_value(0).unwrap() -} - -/// A source SST written with an older JSON2 layout must be rewritten into the -/// target layout, keeping values that lived in the remainder field. -#[tokio::test] -async fn test_json2_rewrite_preserves_values_through_multiregion_compaction() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let json_columns = [ - Json2Column { - name: "j", - column_id: 4, - source_layout: json2_settings(vec![json2_hint( - "a", - ConcreteDataType::int64_datatype(), - )]), - target_layout: json2_settings(vec![ - json2_hint("a", ConcreteDataType::int64_datatype()), - json2_hint("b", ConcreteDataType::string_datatype()), - ]), - rows: [json!({"a": 1, "b": "x"}), json!({"a": 2})], - }, - Json2Column { - name: "k", - column_id: 5, - source_layout: json2_settings(vec![json2_hint( - "left", - ConcreteDataType::string_datatype(), - )]), - target_layout: json2_settings(vec![ - json2_hint("left", ConcreteDataType::string_datatype()), - json2_hint("right", ConcreteDataType::int64_datatype()), - ]), - rows: [ - json!({"left": "first", "right": 7}), - json!({"left": "second"}), - ], - }, - ]; - let source_region = RegionId::new(1, 0); - let source_metadata = json2_compaction_metadata(&json_columns, source_region, false); - let base = new_record_batch_with_custom_sequence(&["000", "series"], 0, 2, 100); - let mut columns = base.columns().to_vec(); - let mut tags = StringDictionaryBuilder::::new(); - let mut primary_keys = BinaryDictionaryBuilder::::new(); - for tag in ["000", "020"] { - tags.append_value(tag); - primary_keys - .append(crate::test_util::sst_util::new_primary_key(&[ - tag, "series", - ])) - .unwrap(); - } - columns[0] = Arc::new(tags.finish()); - columns[4] = Arc::new(primary_keys.finish()); - let mut options = FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Dense); - for (index, column) in json_columns.iter().enumerate() { - let physical = column.source_array(); - options - .concretized_json_types - .insert(column.name.to_string(), physical.data_type().clone()); - columns.insert(3 + index, physical); - } - let source_batch = RecordBatch::try_new( - to_flat_sst_arrow_schema(&source_metadata, &options), - columns, - ) - .unwrap(); - let info = fixture - .write_source(source_metadata, vec![source_batch], FormatType::Flat) - .await; - let mut source = file_meta(info, source_region); - source.sequence = NonZeroU64::new(100); - - let mut plan = fixture.plan(2); - plan.sources = vec![source.clone()]; - for target in plan.targets.values_mut() { - target.metadata = json2_compaction_metadata(&json_columns, target.metadata.region_id, true); - target.inputs = [(source.file_id(), source.clone())].into_iter().collect(); - } - plan.memory_limit = 256 * 1024 * 1024; - let targets = plan.targets.clone(); - let output = fixture.compact(plan).await; - - for (id, files) in &output.files { - let mut rows = 0; - for file in files { - for batch in fixture - .read_output(file.clone(), targets[id].metadata.clone()) - .await - { - rows += batch.num_rows(); - for column in &json_columns { - assert_eq!( - column.expected_rows()[id.region_sequence() as usize], - read_json2_row(&batch, column) - ); - } - } - } - assert_eq!(1, rows, "one row must route to {id}"); - } - assert_eq!(2, output.stats.output_rows); -} - -#[tokio::test] -async fn test_unmatched_partition_values_use_the_table_default_region() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(2); - let exprs = vec![ - col("tag_0").lt(Value::String("010".into())), - col("tag_0").gt_eq(Value::String("020".into())), - ]; - plan.partition_rule = Arc::new( - MultiDimPartitionRule::try_new(vec!["tag_0".into()], vec![0, 1], exprs.clone(), false) - .unwrap(), - ); - for (id, target) in &mut plan.targets { - Arc::make_mut(&mut target.metadata).set_partition_expr(if id.region_sequence() == 0 { - None - } else { - Some(exprs[1].as_json_str().unwrap()) - }); - } - let targets = plan.targets.clone(); - let output = fixture.compact(plan).await; - assert_eq!(124, output.stats.output_rows); - for (id, files) in output.files { - let mut series = HashSet::new(); - for file in files { - series.extend( - fixture - .read_output_rows(file, targets[&id].metadata.clone()) - .await - .into_iter() - .map(|row| row.0), - ); - } - let range = if id.region_sequence() == 0 { - 0..20 - } else { - 20..31 - }; - assert_eq!(range.collect::>(), series); - } -} - -#[tokio::test] -async fn test_nullable_field_partitioning_preserves_delete_records() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(2); - let exprs = vec![ - col("field_0").lt(Value::UInt64(20)), - col("field_0").gt_eq(Value::UInt64(20)), - ]; - plan.partition_rule = Arc::new( - MultiDimPartitionRule::try_new(vec!["field_0".into()], vec![0, 1], exprs.clone(), false) - .unwrap(), - ); - for (id, target) in &mut plan.targets { - Arc::make_mut(&mut target.metadata).set_partition_expr(if id.region_sequence() == 0 { - None - } else { - Some(exprs[1].as_json_str().unwrap()) - }); - } - let targets = plan.targets.clone(); - let output = fixture.compact(plan).await; - assert_eq!(124, output.stats.output_rows); - for (id, files) in output.files { - let mut counts = (0, 0); - for file in files { - let rows = fixture - .read_output_rows(file, targets[&id].metadata.clone()) - .await; - counts.0 += rows.len(); - counts.1 += rows.iter().filter(|row| row.4.is_none()).count(); - for value in rows.iter().filter_map(|row| row.4) { - assert_eq!(id.region_sequence() == 0, value < 20); - } - } - assert_eq!(62, counts.0); - assert_eq!(if id.region_sequence() == 0 { 31 } else { 0 }, counts.1); - } -} - -#[tokio::test] -async fn test_unknown_partition_target_fails_before_creating_output() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(2); - plan.partition_rule = Arc::new( - MultiDimPartitionRule::try_new(vec!["tag_0".into()], vec![99], vec![], false).unwrap(), - ); - let (context, protection) = fixture.context(None); - let error = compact_regions(plan, context).await.err().unwrap(); - assert!( - format!("{error:?}").contains("Partition rule selected a region outside"), - "{error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); -} - -/// A version group crossing reader batches with 32 schema-default columns. -async fn wide_source_fixture() -> (Fixture, MultiRegionCompactionPlan) { - use api::v1::SemanticType; - use datatypes::data_type::ConcreteDataType; - use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema}; - use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; - - let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { - let batch = new_record_batch_with_custom_sequence(&["000", "series"], 0, 1024, 5); - let mut columns = batch.columns().to_vec(); - columns[3] = Arc::new(TimestampMillisecondArray::from(vec![0; 1024])); - vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] - }) - .await; - let mut plan = fixture.plan(2); - let expressions = vec![ - col("field_0").lt(Value::UInt64(512)), - col("field_0").gt_eq(Value::UInt64(512)), - ]; - plan.partition_rule = Arc::new( - MultiDimPartitionRule::try_new( - vec!["field_0".into()], - vec![0, 1], - expressions.clone(), - false, - ) - .unwrap(), - ); - for (id, target) in &mut plan.targets { - let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone()); - for column in 0..32 { - builder.push_column_metadata(ColumnMetadata { - column_id: 10 + column, - semantic_type: SemanticType::Field, - column_schema: ColumnSchema::new( - format!("wide_{column}"), - ConcreteDataType::uint64_datatype(), - false, - ) - .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::UInt64( - 1000 + column as u64, - )))) - .unwrap(), - }); - } - let mut metadata = builder.build().unwrap(); - metadata.set_partition_expr(Some( - expressions[id.region_sequence() as usize] - .as_json_str() - .unwrap(), - )); - target.metadata = Arc::new(metadata); - } - (fixture, plan) -} - -#[tokio::test] -async fn test_wide_version_group_routes_lazily_without_retaining_fragment_dictionaries() { - let (fixture, plan) = wide_source_fixture().await; - let (context, _) = fixture.context(None); - let counters = Arc::new(SourceCounters::default()); - let source = source::SharedSource::build( - &plan, - &context, - validate_plan(&plan).unwrap(), - counters.clone(), - ) - .await - .unwrap(); - let mut stream = source.batches(); - let mut next_row = 0; - while let Some(source::SourceEvent { region_id, batch }) = stream.try_next().await.unwrap() { - assert_eq!(39, batch.num_columns()); - let keys = batch - .column(primary_key_column_index(batch.num_columns())) - .as_any() - .downcast_ref::>() - .unwrap(); - // Regression R1-C1: a paused consumer must not retain one dictionary - // reference per future fragment. This is ownership, not an RSS metric. - assert!(Arc::strong_count(keys.values()) < 16); - let values = batch - .column_by_name("field_0") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - for row in 0..batch.num_rows() { - assert_eq!(next_row, values.value(row)); - assert_eq!((next_row / 512) as u32, region_id.region_sequence()); - for column in 0..32 { - let defaults = batch - .column_by_name(&format!("wide_{column}")) - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(0, defaults.null_count()); - assert_eq!(1000 + column as u64, defaults.value(row)); - } - next_row += 1; - } - } - assert_eq!(1024, next_row); - assert_eq!(1, counters.files.load(std::sync::atomic::Ordering::Relaxed)); - assert_eq!( - 1024, - counters.rows.load(std::sync::atomic::Ordering::Relaxed) - ); -} - -#[tokio::test] -async fn test_cancelling_between_routed_fragments_stops_the_source() { - let (fixture, plan) = wide_source_fixture().await; - let (context, _) = fixture.context(None); - let source = source::SharedSource::build( - &plan, - &context, - validate_plan(&plan).unwrap(), - Arc::new(SourceCounters::default()), - ) - .await - .unwrap(); - let mut stream = source.batches(); - assert!(stream.try_next().await.unwrap().is_some()); - context.cancellation.cancel(); - assert!(matches!( - stream.try_next().await, - Err(crate::error::Error::CompactionCancelled { .. }) - )); -} - -#[rstest::rstest] -#[case::metadata(false)] -#[case::actual_rows(true)] -#[tokio::test] -async fn test_cross_window_source_is_rejected_without_filtering_away_rows( - #[case] stale_metadata: bool, -) { - let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { - let batch = new_record_batch_with_custom_sequence(&["000", "series"], 0, 2, 0); - let mut columns = batch.columns().to_vec(); - columns[3] = Arc::new(TimestampMillisecondArray::from(vec![0, 3_600_000])); - vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] - }) - .await; - let mut plan = fixture.plan(1); - if stale_metadata { - plan.sources[0].time_range.1 = plan.sources[0].time_range.0; - } - let (context, protection) = fixture.context(None); - let error = compact_regions(plan, context).await.err().unwrap(); - assert!( - matches!( - error, - crate::error::Error::InvalidMultiRegionCompaction { .. } - ), - "{error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); - let path = crate::sst::location::sst_file_path( - fixture.layer.table_dir(), - fixture.source.file_id(), - fixture.layer.path_type(), - ); - assert!(fixture.layer.object_store().exists(&path).await.unwrap()); -} - -#[tokio::test] -async fn test_negative_subsecond_timestamp_stays_in_its_half_open_window() { - let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { - let batch = new_record_batch_with_custom_sequence(&["000", "series"], 0, 2, 0); - let mut columns = batch.columns().to_vec(); - columns[3] = Arc::new(TimestampMillisecondArray::from(vec![-3_600_000, -1])); - vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] - }) - .await; - let mut plan = fixture.plan(1); - plan.window_start = -3600; - let output = fixture.compact(plan).await; - assert_eq!(2, output.stats.output_rows); - let mut times = Vec::new(); - for file in output.files.into_values().flatten() { - times.extend( - fixture - .read_output_rows(file, fixture.metadata.clone()) - .await - .into_iter() - .map(|row| row.1), - ); - } - assert_eq!(vec![-3_600_000, -1], times); -} - -#[tokio::test] -async fn test_equal_key_group_crosses_batches_and_preserves_opposite_target_admission_orders() { - fn versions(start: usize) -> Vec { - let batch = - new_record_batch_with_custom_sequence(&["000", "series"], start, start + 256, 0); - let mut columns = batch.columns().to_vec(); - columns[3] = Arc::new(TimestampMillisecondArray::from(vec![0; 256])); - vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] - } - let fixture = - Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| versions(0)).await; - let second = fixture.write_additional_source(versions(256)).await; - let mut plan = fixture.plan(2); - plan.sources.push(second.clone()); - // Both files put the same PK/time into both targets. Source order is not - // a valid version order: R0 installs F1 then F2, R1 installs F2 then F1. - let expressions = vec![ - partition::expr::PartitionExpr::new( - partition::expr::Operand::Expr(col("field_0").lt(Value::UInt64(128))), - partition::expr::RestrictedOp::Or, - partition::expr::Operand::Expr(col("field_0").gt_eq(Value::UInt64(384))), - ), - col("field_0") - .gt_eq(Value::UInt64(128)) - .and(col("field_0").lt(Value::UInt64(384))), - ]; - plan.partition_rule = Arc::new( - MultiDimPartitionRule::try_new( - vec!["field_0".into()], - vec![0, 1], - expressions.clone(), - false, - ) - .unwrap(), - ); - for (id, target) in &mut plan.targets { - let first_sequence = if id.region_sequence() == 0 { 11 } else { 22 }; - target - .inputs - .get_mut(&fixture.source.file_id()) - .unwrap() - .sequence = NonZeroU64::new(first_sequence); - let mut input = second.clone(); - input.sequence = NonZeroU64::new(33 - first_sequence); - target.inputs.insert(input.file_id(), input); - Arc::make_mut(&mut target.metadata).set_partition_expr(Some( - expressions[id.region_sequence() as usize] - .as_json_str() - .unwrap(), - )); - } - let targets = plan.targets.clone(); - let output = fixture.compact(plan).await; - assert_eq!(512, output.stats.output_rows); - for (id, files) in output.files { - let mut rows = Vec::new(); - for file in files { - assert_eq!(NonZeroU64::new(22), file.sequence); - let decoded = fixture - .read_output_rows(file, targets[&id].metadata.clone()) - .await; - rows.extend(decoded.into_iter().map(|row| { - let payload = row.4.unwrap(); - let expected = match (id.region_sequence(), payload < 256) { - (0, true) | (1, false) => 11, - _ => 22, - }; - assert_eq!(expected, row.2); - (row.2, payload) - })); - } - assert!(rows.windows(2).all(|pair| pair[0].0 >= pair[1].0)); - let mut payloads = rows.into_iter().map(|row| row.1).collect::>(); - payloads.sort(); - let expected = (0..512) - .filter(|value| { - if id.region_sequence() == 0 { - *value < 128 || *value >= 384 - } else { - (128..384).contains(value) - } - }) - .collect::>(); - assert_eq!(expected, payloads); - } -} - -/// Five overlapping sources share one window. Every timestamp has tied puts -/// and a tombstone; source-order tie breaking is deliberately not required. -fn overlapping_batches(source: u64) -> Vec { - (0..31) - .map(|series| { - let batch = new_record_batch_with_custom_sequence( - &[&format!("{series:03}"), "series"], - 0, - 512, - 5, - ); - let mut columns = batch.columns().to_vec(); - columns[2] = Arc::new(UInt64Array::from( - (0..512) - .map(|row| (row % 4 != 2).then_some(source * 1000 + row)) - .collect::>(), - )); - columns[3] = Arc::new(TimestampMillisecondArray::from( - (0..512).map(|row| row / 4).collect::>(), - )); - columns[6] = Arc::new(UInt8Array::from( - (0..512) - .map(|row| { - if row % 4 == 2 { - OpType::Delete as u8 - } else { - OpType::Put as u8 - } - }) - .collect::>(), - )); - RecordBatch::try_new(batch.schema(), columns).unwrap() - }) - .collect() -} - -async fn overlapping_fixture() -> (Fixture, MultiRegionCompactionPlan) { - let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { - overlapping_batches(0) - }) - .await; - let mut plan = fixture.plan(3); - // Force rolling inside one window; a series must still stay in one SST. - plan.max_output_file_size = 1; - for source in 1..5 { - let file = fixture - .write_additional_source(overlapping_batches(source)) - .await; - for target in plan.targets.values_mut() { - target.inputs.insert(file.file_id(), file.clone()); - } - plan.sources.push(file); - } - for target in plan.targets.values_mut() { - for input in target.inputs.values_mut() { - input.sequence = NonZeroU64::new(777); - } - } - (fixture, plan) -} - -#[rstest::rstest] -#[case::range(false)] -#[case::multi_column(true)] -#[tokio::test] -async fn test_streaming_merge_preserves_overlapping_versions_and_field_routing( - #[case] multi_column: bool, -) { - let (fixture, mut plan) = overlapping_fixture().await; - if multi_column { - // A single primary key can route to different targets across sources - // and versions. Unmatched rows, including tombstones, go to region 0. - let expressions = vec![ - col("tag_0") - .lt(Value::String("010".into())) - .and(col("field_0").gt_eq(Value::UInt64(2000))), - col("tag_0").gt_eq(Value::String("010".into())).and( - col("field_0") - .gt_eq(Value::UInt64(0)) - .and(col("field_0").lt(Value::UInt64(2000))), - ), - ]; - plan.partition_rule = Arc::new( - MultiDimPartitionRule::try_new( - vec!["tag_0".into(), "field_0".into()], - vec![1, 2], - expressions.clone(), - false, - ) - .unwrap(), - ); - for (id, target) in &mut plan.targets { - let expression = id - .region_sequence() - .checked_sub(1) - .map(|index| expressions[index as usize].as_json_str().unwrap()); - Arc::make_mut(&mut target.metadata).set_partition_expr(expression); - } - } - let source_paths: HashSet<_> = plan - .sources - .iter() - .map(|file| { - crate::sst::location::sst_file_path( - fixture.layer.table_dir(), - file.file_id(), - fixture.layer.path_type(), - ) - }) - .collect(); - let targets = plan.targets.clone(); - let memory_limit = plan.memory_limit; - let (context, protection) = fixture.context(None); - let output = tokio::time::timeout(Duration::from_secs(60), compact_regions(plan, context)) - .await - .expect("bounded worker pipeline stalled") - .unwrap(); - assert_eq!(5, output.stats.source_files); - assert_eq!(5 * 31 * 512, output.stats.source_rows); - assert_eq!(output.stats.source_rows, output.stats.output_rows); - assert!(output.stats.estimated_memory_bytes <= memory_limit as u64); - assert!(output.stats.peak_group_bytes <= (memory_limit / 16) as u64); - assert!( - output.stats.peak_group_bytes > 0, - "retained equal-key groups were never charged" - ); - let expected_output_bytes: u64 = output - .files - .values() - .flatten() - .map(|file| file.file_size + file.index_file_size) - .sum(); - assert_eq!(expected_output_bytes, output.stats.output_bytes); - assert_eq!( - targets.keys().collect::>(), - output.files.keys().collect::>() - ); - common_telemetry::info!("multi_column={multi_column}, stats={:?}", output.stats); - let mut output_paths = HashSet::new(); - for (id, files) in output.files { - assert_eq!(files.len(), output.sst_infos[&id].len()); - assert!(files.len() > 1, "expected single-window SST rollover"); - for pair in files.windows(2) { - assert!( - pair[0].primary_key_max.as_ref().unwrap() - < pair[1].primary_key_min.as_ref().unwrap(), - "SST rollover split a series or reordered primary-key ranges" - ); - } - let file_count = files.len(); - let mut actual_rows = Vec::new(); - for (file, info) in files.into_iter().zip(&output.sst_infos[&id]) { - assert!(protection.files.lock().unwrap().contains(&file.file_id())); - assert_eq!(id, file.region_id); - assert_eq!(0, file.level); - assert_eq!(info.file_id, file.file_id); - assert_eq!(info.num_rows as u64, file.num_rows); - assert_eq!(info.file_size, file.file_size); - assert_eq!(info.time_range, file.time_range); - let file_window = file.time_range.0.value().div_euclid(3_600_000); - assert_eq!(file_window, file.time_range.1.value().div_euclid(3_600_000)); - let path = crate::sst::location::sst_file_path( - fixture.layer.table_dir(), - file.file_id(), - fixture.layer.path_type(), - ); - assert!( - !source_paths.contains(&path), - "output overwrote source {path}" - ); - assert!( - output_paths.insert(path.clone()), - "shared output file {path}" - ); - common_telemetry::info!( - "region={id}, window={file_window}, rows={}, file={path}", - file.num_rows - ); - let rows = fixture - .read_output_rows(file, targets[&id].metadata.clone()) - .await; - assert!( - rows.iter() - .all(|row| row.1.div_euclid(3_600_000) == file_window) - ); - actual_rows.extend(rows); - } - let mut expected = Vec::new(); - for series in 0..31 { - for tick in 0..128 { - for source in 0..5 { - for version in 0..4 { - let ordinal = tick * 4 + version; - let payload = (version != 2).then_some(source * 1000 + ordinal as u64); - // Independent oracle: do not reuse PartitionRule to - // compute the expected routing of the physical rows. - let owner = if multi_column { - if series < 10 && payload.is_some_and(|value| value >= 2000) { - 1 - } else if series >= 10 && payload.is_some_and(|value| value < 2000) { - 2 - } else { - 0 - } - } else if series < 10 { - 0 - } else if series < 21 { - 1 - } else { - 2 - }; - if owner != id.region_sequence() { - continue; - } - expected.push(( - series, - tick, - if id.region_sequence() == 0 { 5 } else { 777 }, - if version == 2 { - OpType::Delete as u8 - } else { - OpType::Put as u8 - }, - payload, - )); - } - } - } - } - // Check the actual order before comparing multisets. Equal full keys - // can interleave sources; unequal keys must remain ordered across SSTs. - for pair in actual_rows.windows(2) { - let key = |row: &TestRow| (row.0, row.1, std::cmp::Reverse(row.2)); - assert!(key(&pair[0]) <= key(&pair[1]), "unordered output for {id}"); - } - actual_rows.sort(); - expected.sort(); - assert_eq!(expected, actual_rows, "missing or changed rows for {id}"); - common_telemetry::info!( - "verified region={id}, files={file_count}, rows={}", - actual_rows.len() - ); - } - for path in source_paths { - assert!(fixture.layer.object_store().exists(&path).await.unwrap()); - } -} - -struct BlockIndexedSstWrite { - inner: oio::Writer, - started: Arc, -} - -impl oio::Write for BlockIndexedSstWrite { - async fn write(&mut self, buffer: mock::Buffer) -> mock::Result<()> { - self.inner.write(buffer).await?; - self.started.notify_one(); - futures::future::pending().await - } - - async fn close(&mut self) -> mock::Result { - self.inner.close().await - } - - async fn abort(&mut self) -> mock::Result<()> { - self.inner.abort().await - } -} - -fn add_fulltext_column(plan: &mut MultiRegionCompactionPlan) { - use datatypes::data_type::ConcreteDataType; - use datatypes::schema::{ - ColumnDefaultConstraint, ColumnSchema, FulltextAnalyzer, FulltextBackend, FulltextOptions, - }; - use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; - let column = ColumnMetadata { - column_id: 10, - semantic_type: api::v1::SemanticType::Field, - column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), false) - .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::String( - "indexed text".into(), - )))) - .unwrap() - .with_fulltext_options(FulltextOptions::new_unchecked( - true, - FulltextAnalyzer::English, - false, - FulltextBackend::Tantivy, - 1, - 0.01, - )) - .unwrap(), - }; - for target in plan.targets.values_mut() { - let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone()); - builder.push_column_metadata(column.clone()); - target.metadata = Arc::new(builder.build().unwrap()); - } -} - -struct FailIndexSibling { - protection: Arc, - fail: Arc, -} - -#[async_trait::async_trait] -impl SstWriteGuard for FailIndexSibling { - async fn before_create(&self, file_id: RegionFileId) -> Result<()> { - if file_id.region_id().region_sequence() == 1 { - self.fail.notified().await; - return InvalidMultiRegionCompactionSnafu { - reason: "injected indexed sibling failure", - } - .fail(); - } - self.protection.before_create(file_id).await - } -} - -#[rstest::rstest] -#[case::cancel(false)] -#[case::sibling_failure(true)] -#[tokio::test] -async fn test_interrupted_indexed_worker_cleans_tantivy_files(#[case] fail_sibling: bool) { - let mut fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { - ["000", "020"] - .into_iter() - .map(|tag| { - let rows = if tag == "000" { 1 } else { 262_144 }; - let batch = new_record_batch_with_custom_sequence(&[tag, "series"], 0, rows, 5); - let mut columns = batch.columns().to_vec(); - // Exceed both the Arrow writer's internal buffer and the object - // store chunk, forcing a write before EOF/index finish. - let mut rng = 0x1234_5678_9abc_def0_u64; - columns[2] = Arc::new(UInt64Array::from_iter_values((0..rows).map(|_| { - rng ^= rng << 13; - rng ^= rng >> 7; - rng ^= rng << 17; - rng - }))); - RecordBatch::try_new(batch.schema(), columns).unwrap() - }) - .collect() - }) - .await; - let started = Arc::new(tokio::sync::Notify::new()); - let notifying = started.clone(); - let layer = MockLayerBuilder::default() - .writer_factory(Arc::new(move |path, _, inner| { - if path.contains("1_0000000000/") && path.ends_with(".parquet") { - Box::new(BlockIndexedSstWrite { - inner, - started: notifying.clone(), - }) as oio::Writer - } else { - inner - } - })) - .build() - .unwrap(); - fixture.layer = Arc::new(AccessLayer::new( - fixture.layer.table_dir(), - fixture.layer.path_type(), - fixture.layer.object_store().clone().layer(layer), - fixture.layer.puffin_manager_factory().clone(), - fixture.layer.intermediate_manager().clone(), - )); - let mut plan = fixture.plan(2); - // R1 receives its first row before R0 blocks in object storage. This lets - // the sibling fail independently even though input is now consumed online. - let expressions = vec![ - col("tag_0").gt_eq(Value::String("010".into())), - col("tag_0").lt(Value::String("010".into())), - ]; - plan.partition_rule = Arc::new( - MultiDimPartitionRule::try_new( - vec!["tag_0".into()], - vec![0, 1], - expressions.clone(), - false, - ) - .unwrap(), - ); - for (id, target) in &mut plan.targets { - Arc::make_mut(&mut target.metadata).set_partition_expr(Some( - expressions[id.region_sequence() as usize] - .as_json_str() - .unwrap(), - )); - } - // Admission now includes both resident Tantivy writers and finish space. - plan.memory_limit = 256 * 1024 * 1024; - add_fulltext_column(&mut plan); - let (mut context, protection) = fixture.context(None); - let cancellation = context.cancellation.clone(); - let fail = Arc::new(tokio::sync::Notify::new()); - context.protection = Arc::new(FailIndexSibling { - protection: protection.clone(), - fail: fail.clone(), - }); - let execution = compact_regions(plan, context); - tokio::pin!(execution); - tokio::select! { - _ = started.notified() => {} - result = &mut execution => panic!("writer did not block: {}", result.err().map_or("success".into(), |error| error.to_string())), - _ = tokio::time::sleep(Duration::from_secs(60)) => panic!("indexed writer did not reach object storage"), - } - let protected = protection - .files - .lock() - .unwrap() - .iter() - .copied() - .collect::>(); - assert_eq!(1, protected.len()); - let file = protected[0]; - let intm_dir = fixture - .env - .path - .path() - .join("table-index/__intm") - .join(file.region_id().as_u64().to_string()) - .join(file.file_id().to_string()); - let mut entries = tokio::fs::read_dir(&intm_dir).await.unwrap(); - let mut tantivy_dirs = Vec::new(); - while let Some(entry) = entries.next_entry().await.unwrap() { - if entry.file_name().to_string_lossy().starts_with("fulltext-") { - assert!( - tokio::fs::try_exists(entry.path().join("meta.json")) - .await - .unwrap() - ); - tantivy_dirs.push(entry.path()); - } - } - assert_eq!( - 1, - tantivy_dirs.len(), - "the test must cancel AFTER Tantivy initialization" - ); - if fail_sibling { - fail.notify_one(); - } else { - cancellation.cancel(); - } - let error = tokio::time::timeout(Duration::from_secs(60), execution) - .await - .unwrap() - .err() - .unwrap(); - if fail_sibling { - assert!( - matches!(&error, crate::error::Error::InvalidMultiRegionCompaction { reason, .. } if reason == "injected indexed sibling failure"), - "{error:?}" - ); - } else { - assert!(matches!( - error, - crate::error::Error::CompactionCancelled { .. } - )); - } - tokio::time::timeout(Duration::from_secs(10), async { - for path in &tantivy_dirs { - while tokio::fs::try_exists(path).await.unwrap() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - } - }) - .await - .expect("cancelled worker leaked Tantivy intermediate files"); - // Attempt cleanup must not delete sources or protected SSTs owned by the caller. - for id in [fixture.source.file_id(), file] { - let path = crate::sst::location::sst_file_path( - fixture.layer.table_dir(), - id, - fixture.layer.path_type(), - ); - assert!(fixture.layer.object_store().exists(&path).await.unwrap()); - } -} - -struct CancelBeforeCreate(CancellationToken); - -#[async_trait::async_trait] -impl SstWriteGuard for CancelBeforeCreate { - async fn before_create(&self, _file_id: RegionFileId) -> Result<()> { - self.0.cancel(); - // The coordinator must interrupt a worker waiting on external I/O, - // rather than waiting for its next cooperative batch check. - futures::future::pending().await - } -} - -#[tokio::test] -async fn test_cancelling_a_blocked_writer_preserves_sources() { - let (fixture, plan) = overlapping_fixture().await; - let sources = plan.sources.clone(); - let (mut context, _) = fixture.context(None); - context.protection = Arc::new(CancelBeforeCreate(context.cancellation.clone())); - let error = tokio::time::timeout(Duration::from_secs(60), compact_regions(plan, context)) - .await - .expect("cancellation did not interrupt the worker") - .err() - .unwrap(); - assert!(matches!( - error, - crate::error::Error::CompactionCancelled { .. } - )); - for file in sources { - let path = crate::sst::location::sst_file_path( - fixture.layer.table_dir(), - file.file_id(), - fixture.layer.path_type(), - ); - assert!(fixture.layer.object_store().exists(&path).await.unwrap()); - } -} - -#[tokio::test] -async fn test_private_routing_annotations_do_not_shadow_user_columns() { - use datatypes::data_type::ConcreteDataType; - use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema}; - use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(2); - let expressions = vec![ - col("__compaction_region").lt(Value::UInt64(40)), - col("__compaction_region").gt_eq(Value::UInt64(40)), - ]; - plan.partition_rule = Arc::new( - MultiDimPartitionRule::try_new( - vec!["__compaction_region".into()], - vec![0, 1], - expressions.clone(), - false, - ) - .unwrap(), - ); - for (id, target) in &mut plan.targets { - let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone()); - builder.push_column_metadata(ColumnMetadata { - column_id: 10, - semantic_type: api::v1::SemanticType::Field, - column_schema: ColumnSchema::new( - "__compaction_region", - ConcreteDataType::uint64_datatype(), - false, - ) - .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::UInt64(42)))) - .unwrap(), - }); - let mut metadata = builder.build().unwrap(); - metadata.set_partition_expr(Some( - expressions[id.region_sequence() as usize] - .as_json_str() - .unwrap(), - )); - target.metadata = Arc::new(metadata); - } - let target = plan.targets[&RegionId::new(1, 1)].metadata.clone(); - let output = fixture.compact(plan).await; - assert!(output.files[&RegionId::new(1, 0)].is_empty()); - assert_eq!(124, output.stats.output_rows); - for file in output.files[&RegionId::new(1, 1)].iter().cloned() { - for batch in fixture.read_output(file, target.clone()).await { - let values = batch - .column_by_name("__compaction_region") - .unwrap() - .as_any() - .downcast_ref::() - .unwrap(); - assert!(values.values().iter().all(|value| *value == 42)); - } - } -} - -#[rstest::rstest] -#[case::trusted_zero(true)] -#[case::legacy_override(false)] -#[tokio::test] -async fn test_zero_versions_follow_trust_and_legacy_override(#[case] trusted: bool) { - let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { - vec![ - new_record_batch_with_custom_sequence(&["000", "series"], 0, 1, 0), - new_record_batch_with_custom_sequence(&["020", "series"], 0, 1, 7), - ] - }) - .await; - let mut plan = fixture.plan(2); - if trusted { - for target in plan.targets.values_mut() { - for input in target.inputs.values_mut() { - input.preserve_row_sequence = true; - } - } - } - let target = plan.targets[&RegionId::new(1, 0)].clone(); - let input = target.inputs[&fixture.source.file_id()].clone(); - let mut original = fixture - .layer - .read_sst(FileHandle::new(input, Arc::new(NoopFilePurger))) - .expected_metadata(Some(target.metadata.clone())) - .cache(CacheStrategy::Disabled) - .build() - .await - .unwrap() - .unwrap(); - let batch = original.next_record_batch().await.unwrap().unwrap(); - let sequences = batch - .column(sequence_column_index(batch.num_columns())) - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!( - 0, - sequences.value(0), - "the original target really observes version zero" - ); - if trusted { - let output = fixture.compact(plan).await; - let mut rows = Vec::new(); - for file in &output.files[&RegionId::new(1, 0)] { - assert!(file.preserve_row_sequence); - rows.extend( - fixture - .read_published_output_rows(file.clone(), target.metadata.clone()) - .await, - ); - } - assert_eq!( - vec![(0, 0, 0, OpType::Put as u8, Some(0))], - rows, - "trusted zero versions must survive publication" - ); - return; - } - let error = compact_regions(plan, fixture.context(None).0) - .await - .err() - .expect("must not publish an output that reads version zero as version100"); - assert!( - matches!(&error, crate::error::Error::InvalidMultiRegionCompaction { reason, .. } if reason.contains("zero output versions")), - "{error:?}" - ); - let path = crate::sst::location::sst_file_path( - fixture.layer.table_dir(), - fixture.source.file_id(), - fixture.layer.path_type(), - ); - assert!(fixture.layer.object_store().exists(&path).await.unwrap()); -} - -/// Neither a creator-local input whose own numbers are unproved nor a foreign input -/// re-based at a target barrier lets an output state `Original`, even when every -/// input is effective-target trusted. -#[tokio::test] -async fn test_unproved_inputs_never_state_original_row_sequences() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 7).await; - let mut plan = fixture.plan(2); - for target in plan.targets.values_mut() { - for input in target.inputs.values_mut() { - input.preserve_row_sequence = true; - } - } - let output = fixture.compact(plan).await; - for (id, files) in &output.files { - for file in files { - assert_eq!(None, file.row_sequence_provenance); - assert!( - !file.has_original_row_sequences(), - "target {id} stated original row sequences without proof" - ); - } - } -} - -/// A target-owned source that proves its own numbers lets the target's output state -/// `Original`, and the reader keeps those numbers. -#[tokio::test] -async fn test_proved_target_owned_source_states_original_row_sequences() { - let mut fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 7).await; - fixture.source.row_sequence_provenance = Some(RowSequenceProvenance::Original); - let mut plan = fixture.plan(1); - for target in plan.targets.values_mut() { - for input in target.inputs.values_mut() { - input.preserve_row_sequence = true; - } - } - let target = plan.targets[&RegionId::new(1, 0)].clone(); - let output = fixture.compact(plan).await; - let files = &output.files[&RegionId::new(1, 0)]; - assert!(!files.is_empty()); - let mut rows = Vec::new(); - for file in files { - assert!( - file.has_original_row_sequences(), - "a proved target-owned source lets its output state original row sequences" - ); - rows.extend( - fixture - .read_published_output_rows(file.clone(), target.metadata.clone()) - .await, - ); - } - assert_eq!(124, rows.len()); - assert!( - rows.iter().all(|row| row.2 == 7), - "the stated numbers are the ones the bytes carry" - ); -} - -struct ObserveOnlineOutput { - protection: Arc, - counters: Arc, - expected_rows: u64, - observed: std::sync::atomic::AtomicBool, -} - -#[async_trait::async_trait] -impl SstWriteGuard for ObserveOnlineOutput { - async fn before_create(&self, file: RegionFileId) -> Result<()> { - use std::sync::atomic::Ordering; - if !self.observed.swap(true, Ordering::Relaxed) { - assert_eq!(0, self.counters.files.load(Ordering::Relaxed)); - assert!(self.counters.rows.load(Ordering::Relaxed) < self.expected_rows); - } - self.protection.before_create(file).await - } -} - -#[tokio::test] -async fn test_output_starts_before_the_shared_source_is_exhausted() { - let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { - vec![new_record_batch_with_custom_sequence( - &["000", "series"], - 0, - 4096, - 0, - )] - }) - .await; - let plan = fixture.plan(1); - let (mut context, protection) = fixture.context(None); - let counters = Arc::new(SourceCounters::default()); - let observer = Arc::new(ObserveOnlineOutput { - protection, - counters: counters.clone(), - expected_rows: fixture.source.num_rows, - observed: std::sync::atomic::AtomicBool::new(false), - }); - context.protection = observer.clone(); - let source = source::SharedSource::build( - &plan, - &context, - validate_plan(&plan).unwrap(), - counters.clone(), - ) - .await - .unwrap(); - let output = worker::execute(plan, context, source, counters) - .await - .unwrap(); - assert_eq!(4096, output.stats.output_rows); - assert!(observer.observed.load(std::sync::atomic::Ordering::Relaxed)); -} - -#[tokio::test] -async fn test_invalid_target_options_are_rejected_before_creating_outputs() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(2); - plan.targets - .get_mut(&RegionId::new(1, 1)) - .unwrap() - .options - .max_row_group_row_count = Some(0); - let (context, protection) = fixture.context(None); - let error = compact_regions(plan, context).await.err().unwrap(); - assert!( - matches!(error, crate::error::Error::InvalidRegionOptions { .. }), - "{error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); -} - -#[tokio::test] -async fn test_all_resident_writers_are_admitted_before_creating_outputs() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(32); - plan.memory_limit = 128 * 1024 * 1024; - let (context, protection) = fixture.context(None); - let error = compact_regions(plan, context).await.err().unwrap(); - assert!( - matches!(&error, crate::error::Error::MultiRegionCompactionResource { reason, .. } if reason.contains("minimum working set")), - "{error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); -} - -const MIB: usize = 1024 * 1024; -const MULTIPART_CHUNK: usize = 5 * MIB; -const MULTIPART_INPUTS: usize = 8; -const ROWS_PER_INPUT_PER_TARGET: usize = 4096; -const PAYLOAD_BYTES: usize = 640; -const MULTIPART_TAGS: [&str; 2] = ["000", "020"]; - -#[tokio::test] -async fn test_table_budget_below_legacy_floor_writes_multipart_outputs_losslessly() { - let metadata = build_test_binary_test_region_metadata(); - let mut fixture = Fixture::without_source((*metadata).clone()).await; - let row_group_size = 256; - let options = WriteOptions { - row_group_size, - ..Default::default() - }; - // Each SST has both tags and a disjoint timestamp range: 40 MiB of - // incompressible payload overall, but only 40 KiB of payload per 64 rows. - let mut sources = Vec::new(); - for input in 0..MULTIPART_INPUTS { - let info = fixture - .write_source_with_options( - fixture.metadata.clone(), - multipart_input_batches(input), - FormatType::Flat, - &options, - ) - .await; - sources.push(info); - } - // The final source row group contains the last batches for the second target. - let tail = Arc::new(InputTailGate::new( - &fixture, - sources.last().unwrap(), - RegionId::new(1, 1), - )); - let sources = sources - .into_iter() - .map(|info| file_meta(info, fixture.metadata.region_id)) - .collect(); - let mut plan = fixture.plan_with_sources(2, sources); - // The old per-Arrow-buffer minimum rejected this even at 1 GiB. Each - // target now gets a separate upload chunk and writes one ~20 MiB SST. - let budget = 512 * MIB; - plan.memory_limit = budget; - plan.max_output_file_size = 32 * MIB; - for target in plan.targets.values_mut() { - target.options.max_row_group_row_count = Some(row_group_size); - } - let targets = plan.targets.clone(); - let uploads = install_multipart_backend(&mut fixture, MULTIPART_CHUNK, Some(tail.clone())); - let (mut context, _) = fixture.context(None); - context.index_kind_provider = Some(Arc::new(UploadProbeIndex)); - - let output = tokio::time::timeout(Duration::from_secs(60), compact_regions(plan, context)) - .await - .expect("the target must upload a part before reading its final input group") - .unwrap(); - assert!( - tail.requested.load(Ordering::Relaxed), - "input never reached the gated row group" - ); - assert!(output.stats.estimated_memory_bytes <= budget as u64); - assert_eq!(targets.len(), output.files.len()); - let layer = &fixture.layer; - for (id, target) in targets { - let files = &output.files[&id]; - assert_eq!(1, files.len()); - let file = &files[0]; - let path = location::sst_file_path(layer.table_dir(), file.file_id(), layer.path_type()); - uploads.assert_completed(&path, file.file_size); - let path = location::index_file_path(layer.table_dir(), file.index_id(), layer.path_type()); - uploads.assert_completed(&path, file.index_file_size); - let puffin = layer - .build_puffin_manager() - .reader(&file.index_id()) - .await - .unwrap(); - assert!(puffin.metadata().await.unwrap().blobs.iter().any(|blob| { - blob.blob_type == UPLOAD_PROBE_BLOB && blob.length as u64 == UPLOAD_PROBE_BYTES - })); - - check_multipart_rows( - fixture - .read_published_output(file.clone(), target.metadata) - .await, - id.region_sequence() as usize, - MULTIPART_INPUTS * ROWS_PER_INPUT_PER_TARGET, - ); - } -} - -#[rstest::rstest] -#[case::budget_cannot_cover_both_targets(8 * MIB, 92 * MIB)] -#[case::backend_disallows_all_part_sizes(0, 512 * MIB)] -#[tokio::test] -async fn test_multipart_admission_rejects_before_protection_or_write( - #[case] chunk: usize, - #[case] budget: usize, -) { - let mut fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(2); - plan.memory_limit = budget; - let uploads = install_multipart_backend(&mut fixture, chunk, None); - let (context, protection) = fixture.context(None); - let error = compact_regions(plan, context) - .await - .err() - .expect("must reject before writing"); - assert!( - matches!( - error, - crate::error::Error::MultiRegionCompactionResource { .. } - ), - "{error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); - assert!(uploads.files.lock().unwrap().is_empty()); -} - -fn multipart_input_batches(input: usize) -> Vec { - let start = input * ROWS_PER_INPUT_PER_TARGET; - let end = start + ROWS_PER_INPUT_PER_TARGET; - MULTIPART_TAGS - .iter() - .enumerate() - .map(|(target, tag)| { - let values = (start..end) - .map(|timestamp| multipart_payload(target, timestamp).to_vec()) - .collect::>(); - let batch = new_record_batch_with_binary_values(tag, &values); - let mut columns = batch.columns().to_vec(); - let time_index = time_index_column_index(columns.len()); - columns[time_index] = Arc::new(TimestampMillisecondArray::from_iter_values( - start as i64..end as i64, - )); - RecordBatch::try_new(batch.schema(), columns).unwrap() - }) - .collect() -} - -fn multipart_payload(target: usize, timestamp: usize) -> [u8; PAYLOAD_BYTES] { - let mut bytes = [0; PAYLOAD_BYTES]; - SmallRng::seed_from_u64((timestamp * MULTIPART_TAGS.len() + target) as u64) - .fill_bytes(&mut bytes); - bytes -} - -fn check_multipart_rows(batches: Vec, target: usize, rows: usize) { - let mut seen = vec![false; rows]; - // The input owner keeps physical versions; the other region uses its - // admitted file version (see plan_with_sources). - let expected_sequence = if target == 0 { 1000 } else { 101 }; - for batch in batches { - let tags = cast(batch.column_by_name("tag_0").unwrap(), &DataType::Utf8).unwrap(); - let tags = tags.as_any().downcast_ref::().unwrap(); - let values = cast(batch.column_by_name("field_0").unwrap(), &DataType::Binary).unwrap(); - let values = values.as_any().downcast_ref::().unwrap(); - let timestamps = - crate::read::timestamp_array_to_i64_slice(batch.column_by_name("ts").unwrap()); - let sequences = batch - .column(sequence_column_index(batch.num_columns())) - .as_any() - .downcast_ref::() - .unwrap(); - for (row, ×tamp) in timestamps.iter().enumerate() { - assert_eq!(expected_sequence, sequences.value(row)); - assert!(tags.is_valid(row) && tags.value(row) == MULTIPART_TAGS[target]); - let timestamp = timestamp as usize; - assert!(!seen[timestamp], "duplicate timestamp {timestamp}"); - seen[timestamp] = true; - assert!( - values.is_valid(row) - && values.value(row) == &multipart_payload(target, timestamp)[..], - "wrong payload for target {target}, timestamp {timestamp}" - ); - } - } - assert!( - seen.into_iter().all(|row| row), - "missing rows in target {target}" - ); -} - -/// Withholds the payload of the last input row group until its target's SST starts uploading. -struct InputTailGate { - source_path: String, - source_size: usize, - payload_offset: usize, - target_dir: String, - first_part: watch::Sender, - requested: AtomicBool, -} - -impl InputTailGate { - fn new(fixture: &Fixture, source: &SstInfo, target: RegionId) -> Self { - let footer = source.file_metadata.as_ref().unwrap(); - let payload = footer - .row_groups() - .last() - .unwrap() - .columns() - .iter() - .find(|column| column.column_path().string() == "field_0") - .unwrap(); - let layer = &fixture.layer; - Self { - source_path: location::sst_file_path( - layer.table_dir(), - RegionFileId::new(fixture.metadata.region_id, source.file_id), - layer.path_type(), - ), - source_size: source.file_size as usize, - payload_offset: payload.byte_range().0 as usize, - target_dir: location::region_dir_from_table_dir( - layer.table_dir(), - target, - layer.path_type(), - ), - first_part: watch::channel(false).0, - requested: AtomicBool::new(false), - } - } - - async fn wait_for_part(&self, range: mock::BytesRange) -> mock::Result<()> { - if range - .to_content_range(self.source_size)? - .contains(&self.payload_offset) - { - self.requested.store(true, Ordering::Relaxed); - self.first_part - .subscribe() - .wait_for(|&started| started) - .await - .unwrap(); - } - Ok(()) - } -} - -struct TailReader { - inner: oio::Reader, - gate: Arc, -} - -impl oio::Read for TailReader { - async fn open( - &self, - range: mock::BytesRange, - ) -> mock::Result<(mock::RpRead, Box)> { - self.gate.wait_for_part(range).await?; - self.inner.open(range).await - } - - async fn read(&self, range: mock::BytesRange) -> mock::Result<(mock::RpRead, mock::Buffer)> { - self.gate.wait_for_part(range).await?; - self.inner.read(range).await - } -} - -struct MultipartUploads { - files: Mutex>, - tail: Option>, -} - -#[derive(Default)] -struct MultipartUpload { - parts: Vec, - completed: bool, -} - -impl MultipartUploads { - fn assert_completed(&self, path: &str, size: u64) { - let uploads = self.files.lock().unwrap(); - let upload = uploads - .get(path) - .unwrap_or_else(|| panic!("no upload for {path}")); - assert!( - upload.completed, - "multipart upload did not complete for {path}" - ); - let (last, full) = upload.parts.split_last().unwrap(); - assert!( - full.len() >= 2 - && full.iter().all(|&part| part == MULTIPART_CHUNK as u64) - && (1..=MULTIPART_CHUNK as u64).contains(last), - "wrong multipart sizes for {path}: {:?}", - upload.parts - ); - assert_eq!(size, upload.parts.iter().sum::(), "{path}"); - } -} - -/// Uses the same OpenDAL chunker and multipart state machine as S3. Only the -/// service's part requests are replaced, appending to an FS writer with no -/// whole-file buffer in the fake backend. -fn install_multipart_backend( - fixture: &mut Fixture, - chunk: usize, - tail: Option>, -) -> Arc { - let mut mock = MockLayerBuilder::default(); - if let Some(gate) = tail.clone() { - mock.reader_factory(Arc::new(move |path, _, inner| { - if path == gate.source_path { - Box::new(TailReader { - inner, - gate: gate.clone(), - }) - } else { - inner - } - })); - } - let uploads = Arc::new(MultipartUploads { - files: Mutex::default(), - tail, - }); - let layer = &fixture.layer; - let store = layer.object_store().clone(); - let executor = store.context().executor().clone(); - let observed = uploads.clone(); - let mock = mock - .writer_factory(Arc::new(move |path, args, inner| { - assert_eq!(1, args.concurrent(), "multipart concurrency for {path}"); - let previous = observed - .files - .lock() - .unwrap() - .insert(path.to_string(), MultipartUpload::default()); - assert!(previous.is_none(), "opened multiple writers for {path}"); - Box::new(oio::MultipartWriter::new( - executor.clone(), - FsMultipartSink { - inner: tokio::sync::Mutex::new(inner), - path: path.to_string(), - uploads: observed.clone(), - }, - args.concurrent(), - )) as oio::Writer - })) - .build() - .unwrap(); - let store = store - .layer(mock) - .layer(CapabilityOverrideLayer::new(move |mut caps| { - caps.write_multi_min_size = Some(chunk); - caps.write_multi_max_size = Some(chunk); - caps - })); - fixture.layer = Arc::new(AccessLayer::new( - layer.table_dir(), - layer.path_type(), - store, - layer.puffin_manager_factory().clone(), - layer.intermediate_manager().clone(), - )); - uploads -} - -struct FsMultipartSink { - inner: tokio::sync::Mutex, - path: String, - uploads: Arc, -} - -impl oio::MultipartWrite for FsMultipartSink { - async fn write_once(&self, _size: u64, body: mock::Buffer) -> mock::Result { - let mut writer = self.inner.lock().await; - writer.write(body).await?; - writer.close().await - } - - async fn initiate_part(&self) -> mock::Result { - Ok(self.path.clone()) - } - - async fn write_part( - &self, - _: &str, - part_number: usize, - size: u64, - body: mock::Buffer, - ) -> mock::Result { - { - let mut files = self.uploads.files.lock().unwrap(); - let parts = &mut files.get_mut(&self.path).unwrap().parts; - assert_eq!( - parts.len(), - part_number, - "out-of-order part for {}", - self.path - ); - parts.push(size); - } - if part_number == 0 - && let Some(tail) = &self.uploads.tail - && self.path.starts_with(&tail.target_dir) - && self.path.ends_with(".parquet") - { - assert!( - !tail.first_part.send_replace(true), - "multiple SSTs released the same input tail" - ); - } - self.inner.lock().await.write(body).await?; - Ok(oio::MultipartPart { - part_number, - size: Some(size), - etag: part_number.to_string(), - checksum: None, - }) - } - - async fn complete_part( - &self, - _: &str, - _: &[oio::MultipartPart], - ) -> mock::Result { - let metadata = self.inner.lock().await.close().await?; - self.uploads - .files - .lock() - .unwrap() - .get_mut(&self.path) - .unwrap() - .completed = true; - Ok(metadata) - } - - async fn abort_part(&self, _: &str) -> mock::Result<()> { - self.inner.lock().await.abort().await - } -} - -const UPLOAD_PROBE_BLOB: &str = "test.upload-budget"; -const UPLOAD_PROBE_BYTES: u64 = (2 * MULTIPART_CHUNK + 123) as u64; -const UPLOAD_PROBE_ENTRY: PlanEntry = PlanEntry { - column_id: 0, - kind: IndexKind::Extension(ExtensionIndexKind::Hll), - format_version: 1, -}; - -/// An uncompressed streaming blob drives the real Puffin writer across two -/// parts without inflating a built-in index or retaining a large creator state. -#[derive(Debug)] -struct UploadProbeIndex; - -impl IndexKindProvider for UploadProbeIndex { - fn handlers(&self) -> Vec> { - vec![Arc::new(Self)] - } -} - -impl IndexKindHandler for UploadProbeIndex { - fn kinds(&self) -> &[IndexKind] { - &[UPLOAD_PROBE_ENTRY.kind] - } - - fn validate(&self, _: &PlanContext<'_>) -> std::result::Result<(), BoxedError> { - Ok(()) - } - - fn plan( - &self, - _: &PlanContext<'_>, - ) -> std::result::Result>, BoxedError> { - Ok(Some(Arc::new(Self))) - } -} - -#[async_trait::async_trait] -impl PlannedIndex for UploadProbeIndex { - fn kinds(&self) -> &[IndexKind] { - IndexKindHandler::kinds(self) - } - - fn entries(&self) -> &[PlanEntry] { - &[UPLOAD_PROBE_ENTRY] - } - - async fn build( - &self, - _: &BuildContext<'_>, - ) -> std::result::Result>, BoxedError> { - Ok(Some(Box::new(Self))) - } - - fn is_current(&self, _: &FileMeta, _: &PlanContext<'_>) -> bool { - false - } -} - -#[async_trait::async_trait] -impl IndexCreator for UploadProbeIndex { - async fn update(&mut self, _: &mut crate::read::Batch) -> std::result::Result<(), BoxedError> { - Ok(()) - } - - async fn update_flat(&mut self, _: &RecordBatch) -> std::result::Result<(), BoxedError> { - Ok(()) - } - - async fn finish( - &mut self, - writer: &mut SstPuffinWriter, - ) -> std::result::Result, BoxedError> { - writer - .put_blob( - UPLOAD_PROBE_BLOB, - io::repeat(0x5a).take(UPLOAD_PROBE_BYTES), - Default::default(), - Default::default(), - ) - .await - .map_err(BoxedError::new)?; - Ok(vec![CompletedEntry { - column_id: Some(UPLOAD_PROBE_ENTRY.column_id), - kind: UPLOAD_PROBE_ENTRY.kind, - format_version: UPLOAD_PROBE_ENTRY.format_version, - }]) - } - - async fn abort(&mut self) -> std::result::Result<(), BoxedError> { - Ok(()) - } - - fn memory_usage(&self) -> usize { - 0 - } -} - -#[rstest::rstest] -#[case::sync(crate::config::IndexBuildMode::Sync)] -#[case::async_mode(crate::config::IndexBuildMode::Async)] -#[tokio::test] -async fn test_admission_includes_each_tantivy_creator_even_in_async_mode( - #[case] mode: crate::config::IndexBuildMode, -) { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut baseline = fixture.plan(2); - baseline.memory_limit = 64 * 1024 * 1024; - assert_eq!(124, fixture.compact(baseline).await.stats.output_rows); - let mut plan = fixture.plan(2); - plan.memory_limit = 64 * 1024 * 1024; - add_fulltext_column(&mut plan); - let (mut context, protection) = fixture.context(None); - Arc::make_mut(&mut context.config).index.build_mode = mode; - let error = compact_regions(plan, context).await.err().unwrap(); - assert!( - matches!(&error, crate::error::Error::MultiRegionCompactionResource { reason, .. } if reason.contains("minimum working set")), - "{error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); -} - -#[tokio::test] -async fn test_oversized_equal_key_group_fails_without_partial_outputs() { - let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { - let batch = new_record_batch_with_custom_sequence(&["000", "series"], 0, 262_144, 0); - let mut columns = batch.columns().to_vec(); - columns[3] = Arc::new(TimestampMillisecondArray::from(vec![0; 262_144])); - vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] - }) - .await; - let (context, protection) = fixture.context(None); - let error = compact_regions(fixture.plan(1), context) - .await - .err() - .unwrap(); - assert!( - matches!(&error, crate::error::Error::MultiRegionCompactionResource { reason, .. } if reason.contains("Equal-key version group")), - "{error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); -} - -#[tokio::test] -async fn test_target_writer_sizes_row_groups_from_source_size() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let plan = fixture.plan(1); - let (context, _protection) = fixture.context(None); - let source = new_flat_source_from_record_batches(vec![source_batch(&fixture.metadata, 0, 100)]); - let upload = memory::UploadBudget::new(&plan, context.access_layer.object_store()).unwrap(); - let limits = memory::MemoryLimits::new(&plan, source.schema(), upload).unwrap(); - // 64 decoded rows of 4 MiB: 32 rows fill the 128 MiB target. The target's `FileMeta` inputs - // describe the narrow fixture rows, which would allow the full cap. - let writer = writer::TargetWriter::new( - &plan.targets[&RegionId::new(1, 0)], - &context, - &limits, - plan.max_output_file_size, - (64, 256 << 20), - Arc::default(), - false, - ); - assert_eq!(32, writer.options().row_group_size); -} - -#[tokio::test] -async fn test_reader_admission_counts_decoded_values() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - // 2048 copies of one 64 KiB value: tiny once dictionary-encoded, 128 MiB decoded. - let batch = new_record_batch_with_binary_values("a", &vec![vec![7u8; 64 * 1024]; 2048]); - let info = fixture - .write_source( - build_test_binary_test_region_metadata(), - vec![batch], - FormatType::Flat, - ) - .await; - let footer = info.file_metadata.unwrap(); - assert!( - footer - .row_groups() - .iter() - .all(|group| group.total_byte_size() < 1 << 20) - ); - assert!(memory::reader_bytes(&footer) >= 128 << 20); -} - -#[rstest::rstest] -#[case::encoder("encoder")] -#[case::metadata("metadata")] -#[case::upload("upload")] -#[tokio::test] -async fn test_limited_writer_fails_instead_of_returning_over_budget_output( - #[case] kind: &'static str, -) { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let plan = fixture.plan(1); - let (context, protection) = fixture.context(None); - let source = new_flat_source_from_record_batches(vec![source_batch(&fixture.metadata, 0, 100)]); - let upload = memory::UploadBudget::new(&plan, context.access_layer.object_store()).unwrap(); - let mut limits = memory::MemoryLimits::new(&plan, source.schema(), upload).unwrap(); - match kind { - "encoder" => limits.writer.working_bytes = 1, - "metadata" => limits.writer.metadata_bytes = 1, - "upload" => limits.writer.upload_limits.max_object_bytes = 1, - _ => unreachable!(), - } - let error = writer::TargetWriter::new( - &plan.targets[&RegionId::new(1, 0)], - &context, - &limits, - plan.max_output_file_size, - (0, 0), - Arc::default(), - false, - ) - .write(source) - .await - .err() - .unwrap(); - match error { - crate::error::Error::MultiRegionCompactionResource { .. } if kind == "upload" => {} - crate::error::Error::SstWriteMemoryExceeded { kind: actual, .. } if actual == kind => {} - _ => panic!("unexpected {kind} limit error: {error:?}"), - } - assert_eq!(1, protection.files.lock().unwrap().len()); -} - -#[tokio::test] -async fn test_cancelled_execution_does_not_create_output() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let (context, protection) = fixture.context(None); - context.cancellation.cancel(); - assert!(matches!( - compact_regions(fixture.plan(2), context).await, - Err(crate::error::Error::CompactionCancelled { .. }) - )); - assert!(protection.files.lock().unwrap().is_empty()); -} - -/// Mutations applied to a valid plan to reach each `validate_plan` rejection. -#[derive(Clone, Copy, Debug)] -enum InvalidPlan { - NoSources, - TinyBudget, - ZeroFileSize, - ZeroWindow, - NegativeWindow, - OversizedControl, - NoTargets, - WindowOverflow, - UnalignedWindow, - SourceOutsideWindow, - DuplicateSource, - ForeignTable, - MissingInput, - InconsistentSchema, -} - -#[rstest::rstest] -#[case(InvalidPlan::NoSources, "sources must not be empty")] -#[case(InvalidPlan::TinyBudget, "memory_limit must be at least 1 MiB")] -#[case( - InvalidPlan::ZeroFileSize, - "max_output_file_size must be greater than 0" -)] -#[case(InvalidPlan::ZeroWindow, "window_seconds must be greater than 0")] -#[case(InvalidPlan::NegativeWindow, "window_seconds must be greater than 0")] -#[case(InvalidPlan::OversizedControl, "control state exceeds the task budget")] -#[case(InvalidPlan::NoTargets, "No routing targets")] -#[case(InvalidPlan::WindowOverflow, "Task window overflow")] -#[case(InvalidPlan::UnalignedWindow, "not aligned")] -#[case(InvalidPlan::SourceOutsideWindow, "not wholly inside the task window")] -#[case( - InvalidPlan::DuplicateSource, - "unique source files from one physical table" -)] -#[case( - InvalidPlan::ForeignTable, - "unique source files from one physical table" -)] -#[case( - InvalidPlan::MissingInput, - "effective metadata of every selected source" -)] -#[case(InvalidPlan::InconsistentSchema, "consistent physical-table snapshot")] -#[tokio::test] -async fn test_invalid_plan_is_rejected_before_creating_outputs( - #[case] invalid: InvalidPlan, - #[case] reason: &'static str, -) { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let mut plan = fixture.plan(2); - match invalid { - InvalidPlan::NoSources => plan.sources.clear(), - InvalidPlan::TinyBudget => plan.memory_limit = 1024 * 1024 - 1, - InvalidPlan::ZeroFileSize => plan.max_output_file_size = 0, - InvalidPlan::ZeroWindow => plan.window_seconds = 0, - InvalidPlan::NegativeWindow => plan.window_seconds = -1, - InvalidPlan::OversizedControl => { - plan.memory_limit = 1024 * 1024; - let source = plan.sources[0].clone(); - let extra = plan.memory_limit / std::mem::size_of::() + 1; - plan.sources = vec![source; extra]; - } - InvalidPlan::NoTargets => plan.targets.clear(), - InvalidPlan::WindowOverflow => { - plan.window_start = i64::MAX - plan.window_seconds + 1; - } - InvalidPlan::UnalignedWindow => plan.window_start += 1, - InvalidPlan::SourceOutsideWindow => { - plan.sources[0].time_range = ( - Timestamp::new_second(plan.window_seconds), - Timestamp::new_second(plan.window_seconds + 1), - ); - } - InvalidPlan::DuplicateSource => { - let source = plan.sources[0].clone(); - plan.sources.push(source); - } - InvalidPlan::ForeignTable => { - plan.sources[0].region_id = RegionId::new(2, 0); - } - InvalidPlan::MissingInput => { - let target = plan.targets.values_mut().next().unwrap(); - target.inputs.clear(); - } - InvalidPlan::InconsistentSchema => { - let target = plan.targets.values_mut().next().unwrap(); - Arc::make_mut(&mut target.metadata).column_metadatas.pop(); - } - } - let (context, protection) = fixture.context(None); - let error = tokio::time::timeout(Duration::from_secs(30), compact_regions(plan, context)) - .await - .expect("invalid plan hung instead of failing") - .err() - .expect("invalid plan must be rejected"); - assert!( - format!("{error:?}").contains(reason), - "expected `{reason}`, got {error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); -} - -#[derive(Debug)] -struct InvalidOptionalIndexHandler; - -impl IndexKindProvider for InvalidOptionalIndexHandler { - fn handlers(&self) -> Vec> { - vec![Arc::new(Self)] - } -} - -impl IndexKindHandler for InvalidOptionalIndexHandler { - fn validate(&self, context: &PlanContext<'_>) -> std::result::Result<(), BoxedError> { - self.plan(context).map(|_| ()) - } - - fn kinds(&self) -> &[IndexKind] { - &[IndexKind::Extension(ExtensionIndexKind::Hll)] - } - - fn plan( - &self, - context: &PlanContext<'_>, - ) -> std::result::Result>, BoxedError> { - assert!( - context.metadata.column_metadatas[0] - .column_schema - .hll_options() - .is_err() - ); - Err(BoxedError::new( - crate::error::InvalidConfigSnafu { - reason: "invalid optional index configuration", - } - .build(), - )) - } -} - -#[derive(Debug, Default)] -struct ConflictingRegistrationProvider(std::sync::atomic::AtomicUsize); - -impl IndexKindProvider for ConflictingRegistrationProvider { - fn handlers(&self) -> Vec> { - // Preflight succeeds; source preparation must propagate its own failure too. - let calls = self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let handler: Arc = Arc::new(InvalidOptionalIndexHandler); - if calls == 0 { - vec![handler] - } else { - vec![handler.clone(), handler] - } - } -} - -#[tokio::test] -async fn test_source_index_registration_failure_does_not_fall_back() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - let (mut context, protection) = fixture.context(None); - context.index_kind_provider = Some(Arc::new(ConflictingRegistrationProvider::default())); - let error = compact_regions(fixture.plan(2), context) - .await - .err() - .expect("conflicting registration must fail"); - assert!( - format!("{error:?}").contains("registering index handlers"), - "unexpected registration error: {error:?}" - ); - assert!(protection.files.lock().unwrap().is_empty()); -} - -#[tokio::test] -async fn test_invalid_optional_index_options_do_not_block_routed_compaction() { - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - for invalid_value in ["missing-column", "bad-capacity"] { - let mut plan = fixture.plan(2); - for target in plan.targets.values_mut() { - Arc::make_mut(&mut target.metadata).column_metadatas[0] - .column_schema - .mut_metadata() - .insert(datatypes::schema::HLL_KEY.into(), invalid_value.into()); - } - let (mut context, _) = fixture.context(None); - context.index_kind_provider = Some(Arc::new(InvalidOptionalIndexHandler)); - let output = compact_regions(plan, context).await.unwrap(); - assert_eq!(output.stats.source_rows, output.stats.output_rows); - assert!(output.stats.output_rows > 0); - assert!( - output - .files - .values() - .flatten() - .all(|file| file - .indexes - .iter() - .all(|index| index.created_indexes.iter().all(|kind| !matches!( - kind, - crate::sst::file::IndexType::HllIndex - | crate::sst::file::IndexType::KllIndex - | crate::sst::file::IndexType::MgIndex - )))) - ); - } -} - -#[tokio::test] -async fn test_missing_index_handler_does_not_block_routed_compaction() { - use crate::sst::file::{ColumnIndexMetadata, IndexType}; - - let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; - for required_by in ["schema", "file", "column", "target"] { - let mut plan = fixture.plan(2); - match required_by { - "schema" => { - for target in plan.targets.values_mut() { - Arc::make_mut(&mut target.metadata).column_metadatas[0] - .column_schema - .set_hll_options(&datatypes::schema::HllOptions::default()) - .unwrap(); - } - } - "file" => plan.sources[0].available_indexes.push(IndexType::HllIndex), - "column" => plan.sources[0].indexes.push(ColumnIndexMetadata { - column_id: 0, - created_indexes: [IndexType::HllIndex].into_iter().collect(), - ..Default::default() - }), - _ => { - plan.targets - .values_mut() - .next() - .unwrap() - .inputs - .values_mut() - .next() - .unwrap() - .available_indexes - .push(IndexType::HllIndex); - } - } - let (context, _) = fixture.context(None); - let output = compact_regions(plan, context) - .await - .unwrap_or_else(|error| panic!("{required_by}: {error}")); - assert_eq!(output.stats.source_rows, output.stats.output_rows); - assert!(output.stats.output_rows > 0); - assert!(!output.files.is_empty()); - for file in output.files.values().flatten() { - assert!(file.num_rows > 0); - assert!(file.available_indexes.iter().all(|kind| !matches!( - kind, - IndexType::HllIndex | IndexType::KllIndex | IndexType::MgIndex - ))); - assert!( - file.indexes - .iter() - .all(|index| index.created_indexes.iter().all(|kind| !matches!( - kind, - IndexType::HllIndex | IndexType::KllIndex | IndexType::MgIndex - ))) - ); - } - } -} - -#[rstest::rstest] -#[case::borrowed(PrimaryKeyEncoding::Dense)] -#[case::materialized(PrimaryKeyEncoding::Sparse)] -#[tokio::test] -async fn test_routing_at_source_batch_budget(#[case] encoding: PrimaryKeyEncoding) { - let fixture = Fixture::new(encoding, FormatType::Flat, 7).await; - let plan = fixture.plan(2); - let (context, _) = fixture.context(None); - let mut source = source::SharedSource::build( - &plan, - &context, - validate_plan(&plan).unwrap(), - Arc::new(SourceCounters::default()), - ) - .await - .unwrap(); - let source = Arc::get_mut(&mut source).unwrap(); - let batch = source_batch(&fixture.metadata, 0, 7); - source.limits.arrow_batch_bytes = batch.get_array_memory_size(); - let owners = source.row_owners(&batch); - if encoding == PrimaryKeyEncoding::Dense { - assert_eq!( - owners.unwrap(), - vec![fixture.metadata.region_id; batch.num_rows()] - ); - } else { - assert!(matches!( - owners, - Err(crate::error::Error::MultiRegionCompactionResource { .. }) - )); - } -} - -// Exercise persisted sparse inputs, schema alignment, routing and output readback -// together: unrelated nullable tags must never become merge columns. -#[rstest::rstest] -#[case(2)] -#[case(40)] -#[case(3600)] -#[tokio::test] -async fn test_sparse_routing_with_wide_target_schema(#[case] target_tag_count: u32) { - let fixture = Fixture::new(PrimaryKeyEncoding::Sparse, FormatType::Flat, 7).await; - let mut plan = fixture.plan(8); - for target in plan.targets.values_mut() { - let mut keys = target.metadata.primary_key.clone(); - let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone()); - // Sparse keys also contain the internal table ID and TSID. - let existing_tags = keys.len() as u32 - 2; - for offset in 0..target_tag_count - existing_tags { - let id = 4 + offset; - builder.push_column_metadata(ColumnMetadata { - column_schema: datatypes::schema::ColumnSchema::new( - format!("tag_{id}"), - datatypes::data_type::ConcreteDataType::string_datatype(), - true, - ), - semantic_type: api::v1::SemanticType::Tag, - column_id: id, - }); - keys.push(id); - } - assert_eq!(keys.len(), target_tag_count as usize + 2); - builder.primary_key(keys); - target.metadata = Arc::new(builder.build().unwrap()); - } - let targets = plan.targets.clone(); - let (context, _) = fixture.context(None); - let metadata = targets.values().next().unwrap().metadata.clone(); - let source = super::source::SharedSource::build( - &plan, - &context, - metadata, - Arc::new(super::SourceCounters::default()), - ) - .await - .unwrap(); - assert!( - source - .schema() - .fields() - .iter() - .all(|field| !field.name().starts_with("tag_")) - ); - drop(source); - let output = compact_regions(plan, context).await.unwrap(); - assert_eq!(124, output.stats.source_rows); - assert_eq!(124, output.stats.output_rows); - for (id, files) in output.files { - let mut rows = Vec::new(); - for file in files { - rows.extend( - fixture - .read_output_rows(file, targets[&id].metadata.clone()) - .await, - ); - } - let sequence = if id == fixture.metadata.region_id { - 7 - } else { - 100 + id.region_sequence() as u64 - }; - let mut expected = expected_source_rows(8, id, sequence); - rows.sort(); - expected.sort(); - assert_eq!(expected, rows); - } -} diff --git a/src/mito2/src/compaction/multi_region/worker.rs b/src/mito2/src/compaction/multi_region/worker.rs deleted file mode 100644 index 848f001de38..00000000000 --- a/src/mito2/src/compaction/multi_region/worker.rs +++ /dev/null @@ -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, - counters: Arc, -) -> Result { - 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::(); - output.stats.output_bytes += files - .iter() - .map(|file| file.file_size + file.index_file_size) - .sum::(); - 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, - senders: BTreeMap>, -) -> 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) { - 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; - } -} diff --git a/src/mito2/src/compaction/multi_region/writer.rs b/src/mito2/src/compaction/multi_region/writer.rs deleted file mode 100644 index 1e177001cd2..00000000000 --- a/src/mito2/src/compaction/multi_region/writer.rs +++ /dev/null @@ -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, - max_file_size: usize, - /// Rows and decoded bytes of the shared sources. - input_size: (u64, u64), - sequence: Option, - 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, - 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, Vec)> { - 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::>>()?; - Ok((files, infos.into_iter().collect())) - } - - fn request(&self, source: FlatSource) -> Result { - 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, - ) -> Result { - 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)) -} diff --git a/src/mito2/src/compaction/picker.rs b/src/mito2/src/compaction/picker.rs index d0f32212eb5..f841e8aff07 100644 --- a/src/mito2/src/compaction/picker.rs +++ b/src/mito2/src/compaction/picker.rs @@ -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() } diff --git a/src/mito2/src/compaction/twcs.rs b/src/mito2/src/compaction/twcs.rs index ac981b1d701..40e88fe993f 100644 --- a/src/mito2/src/compaction/twcs.rs +++ b/src/mito2/src/compaction/twcs.rs @@ -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(|| { diff --git a/src/mito2/src/compaction/window.rs b/src/mito2/src/compaction/window.rs index 03a452fa636..ce84a86952b 100644 --- a/src/mito2/src/compaction/window.rs +++ b/src/mito2/src/compaction/window.rs @@ -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) }) { diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 1826bdc0ce6..021dd9a5387 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -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)] diff --git a/src/mito2/src/engine/copy_region_from_test.rs b/src/mito2/src/engine/copy_region_from_test.rs index 4365fc09751..a5024dfbb6c 100644 --- a/src/mito2/src/engine/copy_region_from_test.rs +++ b/src/mito2/src/engine/copy_region_from_test.rs @@ -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::>(); - assert_eq!( - expected_ids, - result - .unwrap() - .copied_file_ids - .into_iter() - .collect::>() - ); - let installed = target.manifest_ctx.manifest().await; - assert_eq!( - expected_ids, - installed.files.keys().copied().collect::>() - ); - 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::>() - ); - 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::() - ); -} - /// 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] diff --git a/src/mito2/src/engine/edit_region_test.rs b/src/mito2/src/engine/edit_region_test.rs index 200a1d19c0f..20cfc29095a 100644 --- a/src/mito2/src/engine/edit_region_test.rs +++ b/src/mito2/src/engine/edit_region_test.rs @@ -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( diff --git a/src/mito2/src/engine/region_hook.rs b/src/mito2/src/engine/region_hook.rs index 332a1eb16ba..d96f44be041 100644 --- a/src/mito2/src/engine/region_hook.rs +++ b/src/mito2/src/engine/region_hook.rs @@ -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, -} - /// 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> { - 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. /// diff --git a/src/mito2/src/engine/shared_file_test.rs b/src/mito2/src/engine/shared_file_test.rs deleted file mode 100644 index 14fe2afac3a..00000000000 --- a/src/mito2/src/engine/shared_file_test.rs +++ /dev/null @@ -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( - ®ion, - &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( - ®ion, - &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::>(); - 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::>(); - // 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::>(); - assert_eq!( - expected - .iter() - .map(|(id, meta)| (*id, meta.as_ref().clone())) - .collect::>(), - visible - ); - let old_rows = RecordBatches::try_collect(old_reader).await.unwrap(); - assert_eq!( - 6, - old_rows.iter().map(|batch| batch.num_rows()).sum::() - ); - 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::() - ); - } - 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() - ); - } -} diff --git a/src/mito2/src/engine/table_compaction.rs b/src/mito2/src/engine/table_compaction.rs deleted file mode 100644 index e9eddd00f46..00000000000 --- a/src/mito2/src/engine/table_compaction.rs +++ /dev/null @@ -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, -} - -/// 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 { - 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(¤t.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, - ) -> Result { - 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), - } - } -} diff --git a/src/mito2/src/engine/table_compaction/output.rs b/src/mito2/src/engine/table_compaction/output.rs deleted file mode 100644 index f2560d4c2a4..00000000000 --- a/src/mito2/src/engine/table_compaction/output.rs +++ /dev/null @@ -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(®ion.access_layer, metadata, file).await?; - } - return Ok(()); - }; - - let mut footers = Vec::with_capacity(outputs.len()); - for file in outputs { - footers.push(verify_file(®ion.access_layer, metadata, file).await?); - } - let verified = outputs - .iter() - .zip(&footers) - .map(|(file_meta, footer)| VerifiedSstFileInfo { file_meta, footer }) - .collect::>(); - hook.on_sst_files_verified(region.region_id, metadata, &verified) - .await; - Ok(()) -} - -async fn verify_file( - access: &AccessLayer, - metadata: &RegionMetadataRef, - file: &FileMeta, -) -> Result> { - 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(()) -} diff --git a/src/mito2/src/engine/table_compaction/tests.rs b/src/mito2/src/engine/table_compaction/tests.rs deleted file mode 100644 index 0b6bea5e789..00000000000 --- a/src/mito2/src/engine/table_compaction/tests.rs +++ /dev/null @@ -1,1549 +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::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Weak}; -use std::time::{Duration, Instant}; - -use api::v1::{Rows, SemanticType}; -use bytes::Bytes; -use common_base::Plugins; -use common_recordbatch::RecordBatches; -use common_time::Timestamp; -use common_time::timestamp::TimeUnit; -use datatypes::prelude::ConcreteDataType; -use datatypes::schema::ColumnSchema; -use parquet::file::metadata::ParquetMetaData; -use store_api::metadata::ColumnMetadata; -use store_api::region_engine::{RegionEngine, RegionRole}; -use store_api::region_request::{ - AddColumn, AlterKind, RegionAlterRequest, RegionRequest, RegionTruncateRequest, - SetRegionOption, UnsetRegionOption, -}; -use store_api::storage::{FileId, RegionId}; - -use super::{PublicationOutcome, TableCompactionSnapshot, is_table_compaction_metadata_compatible}; -use crate::config::MitoConfig; -use crate::engine::MitoEngine; -use crate::engine::lease_test::promote_to_await_leader_lease; -use crate::engine::region_hook::{RegionHook, RegionHookRef, VerifiedSstFileInfo}; -use crate::error::Error; -use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList}; -use crate::region::{MitoRegionRef, RegionLeaderState}; -use crate::request::{RegionEditRequest, WorkerRequest}; -use crate::sst::file::{ColumnIndexMetadata, FileMeta, IndexType, LEVEL_SHARED, SHARED_LEVEL_SLOT}; -use crate::sst::location; -use crate::test_util::sst_util::new_sparse_primary_key; -use crate::test_util::{ - CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows, reopen_region, rows_schema, - sparse_metric_create_request, sparse_metric_put, -}; - -fn config() -> MitoConfig { - MitoConfig { - schedule_compaction_after_edit: false, - manifest_checkpoint_distance: 0, - ..Default::default() - } -} - -async fn copy_sst(region: &MitoRegionRef, source: &FileMeta, level: u8) -> FileMeta { - let mut output = source.clone(); - output.file_id = FileId::random(); - output.level = level; - output.dedup_marker_trusted = false; - let access = ®ion.access_layer; - let path = |file: &FileMeta| { - location::sst_file_path(access.table_dir(), file.file_id(), access.path_type()) - }; - access - .object_store() - .copy(&path(source), &path(&output)) - .await - .unwrap(); - if source.index_file_size > 0 { - let path = |file: &FileMeta| { - location::index_file_path(access.table_dir(), file.index_id(), access.path_type()) - }; - access - .object_store() - .copy(&path(source), &path(&output)) - .await - .unwrap(); - } - output -} - -/// Input admission is deliberately separate from the compaction API. -async fn seed(engine: &MitoEngine, region_id: RegionId) -> (TableCompactionSnapshot, FileMeta) { - let (snapshot, outputs) = seed_shared_inputs(engine, region_id, &[(0, 3)], false).await; - let output = outputs.into_iter().next().unwrap(); - (snapshot, output) -} - -/// Writes each row range as a flushed SST, promotes the flushed files to shared -/// level, and returns one region-local output per shared input under the snapshot. -async fn seed_shared_inputs( - engine: &MitoEngine, - region_id: RegionId, - row_ranges: &[(usize, usize)], - trusted_inputs: bool, -) -> (TableCompactionSnapshot, Vec) { - let create = CreateRequestBuilder::new().build(); - engine - .handle_request(region_id, RegionRequest::Create(create.clone())) - .await - .unwrap(); - for &(start, end) in row_ranges { - put_rows( - engine, - region_id, - Rows { - schema: rows_schema(&create), - rows: build_rows(start, end), - }, - ) - .await; - flush_region(engine, region_id, None).await; - } - promote_flushed_files(engine, region_id, row_ranges.len(), trusted_inputs).await -} - -async fn promote_flushed_files( - engine: &MitoEngine, - region_id: RegionId, - file_count: usize, - trusted_inputs: bool, -) -> (TableCompactionSnapshot, Vec) { - let region = engine.get_region(region_id).unwrap(); - let originals = region.version().ssts.levels()[0] - .files() - .map(|file| file.meta_ref().clone()) - .collect::>(); - assert_eq!(file_count, originals.len()); - let mut shared = Vec::with_capacity(originals.len()); - for original in &originals { - let mut file = copy_sst(®ion, original, LEVEL_SHARED).await; - file.dedup_marker_trusted = trusted_inputs && original.dedup_marker_trusted; - shared.push(file); - } - let edit = RegionEdit { - files_to_add: shared, - files_to_remove: originals, - ..Default::default() - }; - if trusted_inputs { - let (tx, rx) = tokio::sync::oneshot::channel(); - let request = RegionEditRequest::new(region_id, edit, false, tx).for_copy_region(); - engine - .inner - .workers - .submit_to_worker(region_id, WorkerRequest::EditRegion(request)) - .await - .unwrap(); - rx.await.unwrap().unwrap(); - } else { - engine.edit_region(region_id, edit).await.unwrap(); - } - let snapshot = engine.table_compaction_snapshot(region_id).unwrap(); - assert_eq!(file_count, snapshot.inputs.len()); - let mut outputs = Vec::with_capacity(snapshot.inputs.len()); - for input in &snapshot.inputs { - outputs.push(copy_sst(®ion, input, 0).await); - } - (snapshot, outputs) -} - -#[rstest::rstest] -#[case::older_snapshot(true, false, false, PublicationOutcome::Applied)] -#[case::unproven_manifest(false, true, false, PublicationOutcome::StaleInputs)] -#[case::changed_rows(true, false, true, PublicationOutcome::StaleInputs)] -#[tokio::test] -async fn test_table_compaction_snapshot_dedup_marker_compatibility( - #[case] manifest_trusted: bool, - #[case] snapshot_trusted: bool, - #[case] changed_rows: bool, - #[case] expected: PublicationOutcome, -) { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let (mut snapshot, outputs) = - seed_shared_inputs(&engine, region_id, &[(0, 3)], manifest_trusted).await; - let region = engine.get_region(region_id).unwrap(); - let manifest = region.manifest_ctx.manifest().await; - let input = &mut snapshot.inputs[0]; - assert_eq!(input, manifest.files[&input.file_id].as_ref()); - assert_eq!(input.dedup_marker_trusted, manifest_trusted); - input.dedup_marker_trusted = snapshot_trusted; - if changed_rows { - input.num_rows += 1; - } - assert_eq!( - engine - .publish_table_compaction(region_id, snapshot, outputs) - .await - .unwrap(), - expected - ); - assert_eq!(row_count(&engine, region_id).await, 3); -} - -async fn row_count(engine: &MitoEngine, region_id: RegionId) -> usize { - RecordBatches::try_collect( - engine - .scan_to_stream(region_id, Default::default()) - .await - .unwrap(), - ) - .await - .unwrap() - .iter() - .map(|batch| batch.num_rows()) - .sum() -} - -#[rstest::rstest] -#[case::fresh(false)] -#[case::replay(true)] -#[tokio::test] -async fn test_publication_refused_awaiting_leader_lease(#[case] replay: bool) { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let (snapshot, output) = seed(&engine, region_id).await; - if replay { - assert_eq!( - PublicationOutcome::Applied, - engine - .publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]) - .await - .unwrap() - ); - } - engine.require_write_lease(); - engine.freeze_lease_clock(Instant::now()); - promote_to_await_leader_lease(&engine, region_id).await; - let region = engine.get_region(region_id).unwrap(); - let version = region.manifest_ctx.manifest_version().await; - - let err = engine - .publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]) - .await - .unwrap_err(); - assert!( - matches!(&err, Error::EditRegion { source, .. } - if matches!(source.as_ref(), Error::RegionLeaseNotReceived { .. })), - "{err:?}" - ); - assert_eq!(region.manifest_ctx.manifest_version().await, version); - - engine - .set_region_role_with_lease( - region_id, - RegionRole::Leader, - Instant::now(), - Instant::now() + Duration::from_secs(10), - None, - ) - .unwrap(); - assert_eq!( - PublicationOutcome::Applied, - engine - .publish_table_compaction(region_id, snapshot, vec![output]) - .await - .unwrap() - ); -} - -#[tokio::test] -async fn test_duplicate_publication_and_later_replacement_do_not_readmit_inputs() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let (snapshot, output) = seed(&engine, region_id).await; - let region = engine.get_region(region_id).unwrap(); - let sequence = region.version_control.committed_sequence(); - let version = region.manifest_ctx.manifest_version().await; - let (first, second) = tokio::join!( - engine.publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]), - engine.publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]) - ); - assert_eq!( - [PublicationOutcome::Applied; 2], - [first.unwrap(), second.unwrap()] - ); - assert_eq!(version + 1, region.manifest_ctx.manifest_version().await); - assert_eq!(sequence, region.version_control.committed_sequence()); - assert_eq!(sequence, region.version_control.current().last_sequence); - assert_eq!(3, row_count(&engine, region_id).await); - let manifest = region.manifest_ctx.manifest().await; - let encoded = serde_json::to_value(manifest.as_ref()).unwrap(); - assert!(encoded.get("table_compaction").is_none() && encoded.get("extensions").is_none()); - - // Publish a later ordinary compaction, then remove the old output object. - // A late retry must reject its obsolete inputs before trying to verify C. - let replacement = copy_sst(®ion, &output, 0).await; - let edit = RegionEdit { - files_to_remove: vec![output.clone()], - files_to_add: vec![FileMeta { - dedup_marker_trusted: true, - ..replacement.clone() - }], - ..Default::default() - }; - region - .manifest_ctx - .update_manifest_for_compaction(RegionMetaActionList::with_action(RegionMetaAction::Edit( - edit.clone(), - ))) - .await - .unwrap(); - region - .version_control - .apply_edit(Some(edit), &[], region.file_purger.clone()); - let store = region.access_layer.object_store(); - let path = location::sst_file_path( - region.access_layer.table_dir(), - output.file_id(), - region.path_type(), - ); - // `apply_edit` drops the retired version, whose purger deletes this same - // object concurrently, so whichever delete runs second sees it absent. - if let Err(err) = store.delete(&path).await { - assert_eq!( - object_store::ErrorKind::NotFound, - err.kind(), - "unexpected error deleting the retired output {path}: {err:?}" - ); - } - let replacement_path = location::sst_file_path( - region.access_layer.table_dir(), - replacement.file_id(), - region.path_type(), - ); - assert!(!store.exists(&path).await.unwrap(), "{path} still exists"); - assert!( - store.exists(&replacement_path).await.unwrap(), - "{replacement_path} is missing" - ); - // Neither the removed file nor the new file with its proof omitted matches a replay. - for retry_output in [output.clone(), replacement.clone()] { - assert_eq!( - PublicationOutcome::StaleInputs, - engine - .publish_table_compaction(region_id, snapshot.clone(), vec![retry_output]) - .await - .unwrap() - ); - } - let manifest = region.manifest_ctx.manifest().await; - assert_eq!(1, manifest.files.len()); - assert!(manifest.files[&replacement.file_id].dedup_marker_trusted); - assert!(!manifest.files.contains_key(&output.file_id)); - reopen_region(&engine, region_id, "test".into(), true, Default::default()).await; - assert_eq!(3, row_count(&engine, region_id).await); -} - -#[tokio::test] -async fn test_replay_requires_all_inputs_absent_and_all_outputs_matching() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let (snapshot, outputs) = - seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)], false).await; - let mut subset = snapshot.clone(); - subset.inputs.truncate(1); - let output = outputs[0].clone(); - assert_eq!( - PublicationOutcome::Applied, - engine - .publish_table_compaction(region_id, subset.clone(), vec![output.clone()]) - .await - .unwrap() - ); - let region = engine.get_region(region_id).unwrap(); - let version = region.manifest_ctx.manifest_version().await; - let different = FileMeta { - file_size: output.file_size + 1, - ..output.clone() - }; - for (request, expected_outputs) in [ - (snapshot, vec![output]), - (subset.clone(), outputs), - (subset, vec![different]), - ] { - assert_eq!( - PublicationOutcome::StaleInputs, - engine - .publish_table_compaction(region_id, request, expected_outputs) - .await - .unwrap() - ); - } - assert_eq!(version, region.manifest_ctx.manifest_version().await); - assert_eq!(6, row_count(&engine, region_id).await); -} - -#[tokio::test] -async fn test_partial_success_can_retry_both_regions_without_duplicate_files() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let a = RegionId::new(1, 1); - let b = RegionId::new(1, 2); - let (snapshot_a, output_a) = seed(&engine, a).await; - let (snapshot_b, output_b) = seed(&engine, b).await; - let invalid = FileMeta { - file_size: output_b.file_size + 1, - ..output_b.clone() - }; - let (first_a, first_b) = tokio::join!( - engine.publish_table_compaction(a, snapshot_a.clone(), vec![output_a.clone()]), - engine.publish_table_compaction(b, snapshot_b.clone(), vec![invalid]) - ); - assert_eq!(PublicationOutcome::Applied, first_a.unwrap()); - assert!(first_b.is_err()); - assert_eq!( - snapshot_b.inputs, - engine.table_compaction_snapshot(b).unwrap().inputs - ); - let (retry_a, retry_b) = tokio::join!( - engine.publish_table_compaction(a, snapshot_a, vec![output_a.clone()]), - engine.publish_table_compaction(b, snapshot_b, vec![output_b.clone()]) - ); - assert_eq!(PublicationOutcome::Applied, retry_a.unwrap()); - assert_eq!(PublicationOutcome::Applied, retry_b.unwrap()); - for (id, output) in [(a, output_a), (b, output_b)] { - let region = engine.get_region(id).unwrap(); - let manifest = region.manifest_ctx.manifest().await; - assert_eq!(1, manifest.files.len()); - assert_eq!(&output, manifest.files[&output.file_id].as_ref()); - assert_eq!(3, row_count(&engine, id).await); - } -} - -#[tokio::test] -async fn test_invalid_results_preserve_inputs_and_reopen_can_replan() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let (snapshot, output) = seed(&engine, region_id).await; - let region = engine.get_region(region_id).unwrap(); - let version = region.manifest_ctx.manifest_version().await; - // Snapshot-level and footer-derived mutations must all fail output admission - // with the specific reason, leaving the manifest, inputs and rows untouched. - #[derive(Clone, Copy)] - enum ExpectedError { - InvalidRequest(&'static str), - OpenDal, - } - let statistics_mismatch = - ExpectedError::InvalidRequest("Output statistics differ from its footer"); - let invalid_output = ExpectedError::InvalidRequest("Invalid region-local compaction output"); - let timestamp_mismatch = ExpectedError::InvalidRequest("Output timestamp range mismatch"); - let cases = [ - ( - FileMeta { - file_size: output.file_size + 1, - ..output.clone() - }, - ExpectedError::InvalidRequest("Output SST size mismatch"), - ), - ( - FileMeta { - num_rows: output.num_rows + 1, - ..output.clone() - }, - statistics_mismatch, - ), - ( - FileMeta { - num_row_groups: output.num_row_groups + 1, - ..output.clone() - }, - statistics_mismatch, - ), - ( - FileMeta { - max_row_group_uncompressed_size: output.max_row_group_uncompressed_size + 1, - ..output.clone() - }, - statistics_mismatch, - ), - ( - FileMeta { - max_row_group_decoded_size: output.max_row_group_decoded_size + 1, - ..output.clone() - }, - statistics_mismatch, - ), - ( - FileMeta { - primary_key_min: Some(Bytes::from_static(b"not-the-footer-minimum")), - ..output.clone() - }, - statistics_mismatch, - ), - ( - FileMeta { - primary_key_max: Some(Bytes::from_static(b"not-the-footer-maximum")), - ..output.clone() - }, - statistics_mismatch, - ), - ( - FileMeta { - time_range: ( - Timestamp::new(output.time_range.0.value() + 1, output.time_range.0.unit()), - output.time_range.1, - ), - ..output.clone() - }, - timestamp_mismatch, - ), - ( - FileMeta { - time_range: ( - output.time_range.0, - Timestamp::new(output.time_range.1.value(), TimeUnit::Second), - ), - ..output.clone() - }, - timestamp_mismatch, - ), - ( - FileMeta { - file_id: FileId::random(), - ..output.clone() - }, - ExpectedError::OpenDal, - ), - ( - FileMeta { - sequence: None, - ..output.clone() - }, - invalid_output, - ), - ( - FileMeta { - dedup_marker_trusted: true, - ..output.clone() - }, - invalid_output, - ), - ( - FileMeta { - available_indexes: smallvec::smallvec![IndexType::InvertedIndex], - ..output.clone() - }, - ExpectedError::InvalidRequest("Output advertises indexes without an index object"), - ), - ( - FileMeta { - indexes: vec![ColumnIndexMetadata { - column_id: 0, - created_indexes: smallvec::smallvec![IndexType::InvertedIndex], - ..Default::default() - }], - ..output.clone() - }, - ExpectedError::InvalidRequest("Output advertises indexes without an index object"), - ), - ( - FileMeta { - file_id: snapshot.inputs[0].file_id, - ..output.clone() - }, - invalid_output, - ), - ]; - for (invalid, expected) in cases { - let error = engine - .publish_table_compaction(region_id, snapshot.clone(), vec![invalid]) - .await - .unwrap_err(); - let source = match error { - crate::error::Error::EditRegion { source, .. } => source, - other => panic!("unexpected error: {other}"), - }; - match expected { - ExpectedError::InvalidRequest(reason) => assert!( - matches!(source.as_ref(), crate::error::Error::InvalidRequest { reason: actual, .. } if actual == reason), - "unexpected error: {source}" - ), - ExpectedError::OpenDal => assert!( - matches!(source.as_ref(), crate::error::Error::OpenDal { .. }), - "unexpected error: {source}" - ), - } - assert_eq!(version, region.manifest_ctx.manifest_version().await); - assert_eq!( - snapshot.inputs, - engine.table_compaction_snapshot(region_id).unwrap().inputs - ); - assert_eq!(3, row_count(&engine, region_id).await); - } - // A real footer written for another region's metadata must reach the footer - // check; the stale-input shortcut must not mask it. - let foreign_region_id = RegionId::new(1, 2); - let (_, foreign_output) = seed(&engine, foreign_region_id).await; - let foreign_region = engine.get_region(foreign_region_id).unwrap(); - let mut foreign = foreign_output; - assert_eq!(0, foreign.index_file_size); - let foreign_path = location::sst_file_path( - foreign_region.access_layer.table_dir(), - foreign.file_id(), - foreign_region.access_layer.path_type(), - ); - foreign.file_id = FileId::random(); - foreign.region_id = region_id; - foreign.sequence = output.sequence; - let target_path = location::sst_file_path( - region.access_layer.table_dir(), - foreign.file_id(), - region.access_layer.path_type(), - ); - foreign_region - .access_layer - .object_store() - .copy(&foreign_path, &target_path) - .await - .unwrap(); - let error = engine - .publish_table_compaction(region_id, snapshot.clone(), vec![foreign]) - .await - .unwrap_err(); - let source = match error { - crate::error::Error::EditRegion { source, .. } => source, - other => panic!("unexpected error: {other}"), - }; - assert!( - matches!(source.as_ref(), crate::error::Error::InvalidRequest { reason, .. } - if reason == "Output footer schema or partition mismatch"), - "unexpected error: {source}" - ); - assert_eq!(version, region.manifest_ctx.manifest_version().await); - assert_eq!( - snapshot.inputs, - engine.table_compaction_snapshot(region_id).unwrap().inputs - ); - assert_eq!(3, row_count(&engine, region_id).await); - let mut stale_input = snapshot.clone(); - stale_input.inputs[0].index_version += 1; - assert_eq!( - PublicationOutcome::StaleInputs, - engine - .publish_table_compaction(region_id, stale_input, vec![output.clone()]) - .await - .unwrap() - ); - let mut duplicate = snapshot.clone(); - duplicate.inputs.push(snapshot.inputs[0].clone()); - assert!( - engine - .publish_table_compaction(region_id, duplicate, vec![output.clone()]) - .await - .is_err() - ); - let mut malformed = snapshot.clone(); - malformed.options = serde_json::json!({ "append_mode": "not-a-bool" }); - let error = engine - .publish_table_compaction(region_id, malformed, vec![output.clone()]) - .await - .unwrap_err(); - assert!(matches!(error, crate::error::Error::SerdeJson { .. })); - assert_eq!(version, region.manifest_ctx.manifest_version().await); - assert_eq!( - snapshot.inputs, - engine.table_compaction_snapshot(region_id).unwrap().inputs - ); - reopen_region(&engine, region_id, "test".into(), true, Default::default()).await; - // V1 refreshes the snapshot after restart instead of resuming a Prepared task. - // The public snapshot contract is JSON, so a serde round trip must still publish. - let fresh = engine.table_compaction_snapshot(region_id).unwrap(); - let mut fresh: TableCompactionSnapshot = - serde_json::from_value(serde_json::to_value(&fresh).unwrap()).unwrap(); - fresh.options["append_mode"] = serde_json::json!(true); - // Writers of older versions leave the decoded size unknown. - assert!(output.max_row_group_decoded_size > 0); - let legacy_output = FileMeta { - max_row_group_decoded_size: 0, - ..output - }; - assert_eq!( - PublicationOutcome::Applied, - engine - .publish_table_compaction(region_id, fresh, vec![legacy_output]) - .await - .unwrap() - ); - assert_eq!(3, row_count(&engine, region_id).await); -} - -/// An output carrying a real index object written by flush is accepted. -#[tokio::test] -async fn test_indexed_output_with_real_index_object_publishes() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let create = CreateRequestBuilder::new().build_with_index(); - 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 original = region.version().ssts.levels()[0] - .files() - .next() - .unwrap() - .meta_ref() - .clone(); - assert!(original.index_file_size > 0); - assert!(!original.available_indexes.is_empty()); - assert!(!original.indexes.is_empty()); - let shared = copy_sst(®ion, &original, LEVEL_SHARED).await; - engine - .edit_region( - region_id, - RegionEdit { - files_to_add: vec![shared], - files_to_remove: vec![original], - ..Default::default() - }, - ) - .await - .unwrap(); - let snapshot = engine.table_compaction_snapshot(region_id).unwrap(); - let output = copy_sst(®ion, &snapshot.inputs[0], 0).await; - assert!(output.index_file_size > 0); - assert!(!output.available_indexes.is_empty()); - assert!(!output.indexes.is_empty()); - assert_eq!( - PublicationOutcome::Applied, - engine - .publish_table_compaction(region_id, snapshot, vec![output.clone()]) - .await - .unwrap() - ); - let manifest = region.manifest_ctx.manifest().await; - assert_eq!( - Some(&output), - manifest.files.get(&output.file_id).map(AsRef::as_ref) - ); - assert_eq!(3, row_count(&engine, region_id).await); -} - -async fn set_sequence_preservation(engine: &MitoEngine, region_id: RegionId, enabled: bool) { - engine - .handle_request( - region_id, - RegionRequest::Alter(RegionAlterRequest { - kind: AlterKind::SetRegionOptions { - options: vec![SetRegionOption::PreserveRowSequence(enabled)], - }, - }), - ) - .await - .unwrap(); -} - -async fn seed_sequence_inputs(engine: &MitoEngine, region_id: RegionId, mixed: bool) { - let create = CreateRequestBuilder::new() - .insert_option("append_mode", "true") - .insert_option( - "preserve_row_sequence", - if mixed { "false" } else { "true" }, - ) - .build(); - engine - .handle_request(region_id, RegionRequest::Create(create.clone())) - .await - .unwrap(); - let flush_rows = async |start, end| { - put_rows( - engine, - region_id, - Rows { - schema: rows_schema(&create), - rows: build_rows(start, end), - }, - ) - .await; - flush_region(engine, region_id, None).await; - }; - if mixed { - flush_rows(0, 5).await; - set_sequence_preservation(engine, region_id, true).await; - flush_rows(5, 10).await; - } else { - flush_rows(0, 3).await; - } - let region = engine.get_region(region_id).unwrap(); - let originals: Vec<_> = region.version().ssts.levels()[0] - .files() - .map(|file| file.meta_ref().clone()) - .collect(); - // A generic import clears the trust marker. Keep both the marker and the flush sequence. - let mut shared = Vec::new(); - for original in &originals { - shared.push(copy_sst(®ion, original, LEVEL_SHARED).await); - } - let edit = RegionEdit { - files_to_add: shared, - files_to_remove: originals, - ..Default::default() - }; - region - .manifest_ctx - .update_manifest_for_compaction(RegionMetaActionList::with_action(RegionMetaAction::Edit( - edit.clone(), - ))) - .await - .unwrap(); - region - .version_control - .apply_edit(Some(edit), &[], region.file_purger.clone()); -} - -#[tokio::test] -async fn test_preserve_row_sequence_option_drives_output_admission() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - seed_sequence_inputs(&engine, region_id, false).await; - let region = engine.get_region(region_id).unwrap(); - let snapshot = engine.table_compaction_snapshot(region_id).unwrap(); - assert_eq!( - Some(true), - snapshot.options["preserve_row_sequence"].as_bool() - ); - let output = copy_sst(®ion, &snapshot.inputs[0], 0).await; - assert!(output.preserve_row_sequence); - let untrusted = FileMeta { - preserve_row_sequence: false, - ..output.clone() - }; - let version = region.manifest_ctx.manifest_version().await; - let error = engine - .publish_table_compaction(region_id, snapshot.clone(), vec![untrusted]) - .await - .unwrap_err(); - assert!(matches!( - error, - crate::error::Error::EditRegion { source, .. } - if matches!(source.as_ref(), crate::error::Error::InvalidRequest { reason, .. } - if reason == "Invalid region-local compaction output") - )); - assert_eq!(version, region.manifest_ctx.manifest_version().await); - assert_eq!( - snapshot.inputs, - engine.table_compaction_snapshot(region_id).unwrap().inputs - ); - assert_eq!( - PublicationOutcome::Applied, - engine - .publish_table_compaction(region_id, snapshot, vec![output.clone()]) - .await - .unwrap() - ); - let manifest = region.manifest_ctx.manifest().await; - assert_eq!( - Some(&output), - manifest.files.get(&output.file_id).map(AsRef::as_ref) - ); - assert_eq!(3, row_count(&engine, region_id).await); -} - -#[rstest::rstest] -#[case::fresh(false, false)] -#[case::mixed(false, true)] -#[case::replay(true, false)] -#[case::mixed_replay(true, true)] -#[tokio::test] -async fn test_publication_after_enabling_sequence_preservation( - #[case] replay: bool, - #[case] mixed: bool, -) { - use store_api::storage::ScanRequest; - - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - seed_sequence_inputs(&engine, region_id, mixed).await; - let region = engine.get_region(region_id).unwrap(); - set_sequence_preservation(&engine, region_id, false).await; - let snapshot = engine.table_compaction_snapshot(region_id).unwrap(); - let max_sequence = snapshot - .inputs - .iter() - .map(|file| file.sequence.unwrap()) - .max() - .unwrap(); - let mut outputs = Vec::new(); - for input in &snapshot.inputs { - let mut output = copy_sst(®ion, input, 0).await; - output.preserve_row_sequence = false; - output.sequence = Some(max_sequence); - outputs.push(output); - } - let publish = || engine.publish_table_compaction(region_id, snapshot.clone(), outputs.clone()); - if replay { - assert_eq!(PublicationOutcome::Applied, publish().await.unwrap()); - } - set_sequence_preservation(&engine, region_id, true).await; - let version = region.manifest_ctx.manifest_version().await; - if replay { - assert_eq!(PublicationOutcome::Applied, publish().await.unwrap()); - } else { - let scan = async || { - let stream = engine - .scan_to_stream( - region_id, - ScanRequest { - exact_sequence_range: true, - memtable_min_sequence: Some(if mixed { 5 } else { 0 }), - memtable_max_sequence: Some(max_sequence.get()), - ..Default::default() - }, - ) - .await - .unwrap(); - RecordBatches::try_collect(stream).await.unwrap() - }; - let before = scan().await; - assert_eq!( - if mixed { 5 } else { 3 }, - before.iter().map(|batch| batch.num_rows()).sum::() - ); - assert_eq!(PublicationOutcome::StaleInputs, publish().await.unwrap()); - - // A stale job must be told to replan even if its output object is gone. - let access = ®ion.access_layer; - let path = - location::sst_file_path(access.table_dir(), outputs[0].file_id(), access.path_type()); - access.object_store().delete(&path).await.unwrap(); - assert_eq!(PublicationOutcome::StaleInputs, publish().await.unwrap()); - assert_eq!( - before.pretty_print().unwrap(), - scan().await.pretty_print().unwrap() - ); - } - assert_eq!(version, region.manifest_ctx.manifest_version().await); -} - -#[tokio::test] -async fn test_empty_target_replacement_preserves_other_shared_reference() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let source = RegionId::new(1, 1); - let target = RegionId::new(1, 2); - let (source_snapshot, _) = seed(&engine, source).await; - let expr = - partition::expr::col("tag_0").eq(datatypes::value::Value::String("not-in-source".into())); - let create = CreateRequestBuilder::new() - .partition_expr_json(Some(expr.as_json_str().unwrap())) - .build(); - engine - .handle_request(target, RegionRequest::Create(create)) - .await - .unwrap(); - let copy = store_api::region_engine::MitoCopyRegionFromRequest { - source_region_id: source, - parallelism: 1, - }; - engine.copy_region_from(target, copy.clone()).await.unwrap(); - engine.copy_region_from(target, copy).await.unwrap(); - let snapshot = engine.table_compaction_snapshot(target).unwrap(); - assert_eq!(1, snapshot.inputs.len()); - assert_eq!( - source_snapshot.inputs[0].file_id(), - snapshot.inputs[0].file_id() - ); - let region = engine.get_region(target).unwrap(); - assert_eq!(1, region.version_control.current().last_sequence); - assert_eq!(0, row_count(&engine, target).await); - assert_eq!( - PublicationOutcome::Applied, - engine - .publish_table_compaction(target, snapshot.clone(), vec![]) - .await - .unwrap() - ); - assert_eq!( - PublicationOutcome::StaleInputs, - engine - .publish_table_compaction(target, snapshot, vec![]) - .await - .unwrap() - ); - assert_eq!(1, region.version_control.current().last_sequence); - assert_eq!(0, row_count(&engine, target).await); - assert_eq!(3, row_count(&engine, source).await); -} - -#[tokio::test] -async fn test_snapshot_during_edit_and_alter() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let (expected, _) = seed(&engine, region_id).await; - let region = engine.get_region(region_id).unwrap(); - - region.set_editing(RegionLeaderState::Writable).unwrap(); - assert_eq!( - expected.inputs, - engine.table_compaction_snapshot(region_id).unwrap().inputs - ); - region.switch_state_to_writable(RegionLeaderState::Editing); - - region.set_altering().unwrap(); - assert_eq!( - expected.inputs, - engine.table_compaction_snapshot(region_id).unwrap().inputs - ); - region.switch_state_to_writable(RegionLeaderState::Altering); -} - -#[tokio::test] -async fn test_staging_rejects_publication_without_changing_files() { - use store_api::region_request::{EnterStagingRequest, StagingPartitionDirective}; - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let (snapshot, output) = seed(&engine, region_id).await; - engine - .handle_request( - region_id, - RegionRequest::EnterStaging(EnterStagingRequest { - partition_directive: StagingPartitionDirective::RejectAllWrites, - }), - ) - .await - .unwrap(); - let region = engine.get_region(region_id).unwrap(); - let version = region.manifest_ctx.manifest_version().await; - assert!( - engine - .publish_table_compaction(region_id, snapshot, vec![output]) - .await - .is_err() - ); - assert!(region.is_staging()); - region.set_editing(RegionLeaderState::Staging).unwrap(); - assert!(matches!( - engine.table_compaction_snapshot(region_id), - Err(Error::RegionBusy { .. }) - )); - region.switch_state_to_staging(RegionLeaderState::Editing); - assert_eq!(version, region.manifest_ctx.manifest_version().await); - assert_eq!( - 1, - region.version().ssts.levels()[SHARED_LEVEL_SLOT] - .files - .len() - ); -} - -#[rstest::rstest] -#[case::before_persist(false)] -#[case::lost_ack(true)] -#[tokio::test] -async fn test_uncertain_write_recovers_files_before_retry(#[case] persisted: bool) { - use object_store::layers::mock::{ - Buffer, Error, ErrorKind, Metadata, MockLayerBuilder, Result, oio, - }; - struct FailManifestWrite { - inner: oio::Writer, - pending: Vec, - armed: Arc, - persisted: bool, - } - impl oio::Write for FailManifestWrite { - async fn write(&mut self, bytes: Buffer) -> Result<()> { - // Buffer at the I/O boundary so the pre-persist case never depends - // on whether the backing filesystem supports aborting a writer. - self.pending.push(bytes); - Ok(()) - } - async fn close(&mut self) -> Result { - let fail = self.armed.swap(false, Ordering::SeqCst); - if fail && !self.persisted { - return Err(Error::new( - ErrorKind::Unexpected, - "injected failure before persistence", - )); - } - for bytes in self.pending.drain(..) { - self.inner.write(bytes).await?; - } - let metadata = self.inner.close().await?; - if fail { - Err(Error::new( - ErrorKind::Unexpected, - "lost manifest acknowledgement", - )) - } else { - Ok(metadata) - } - } - async fn abort(&mut self) -> Result<()> { - self.inner.abort().await - } - } - let armed = Arc::new(AtomicBool::new(false)); - let fault = armed.clone(); - let layer = MockLayerBuilder::default() - .writer_factory(Arc::new(move |path, _, inner| { - if path.contains("/manifest/") { - Box::new(FailManifestWrite { - inner, - pending: Vec::new(), - armed: fault.clone(), - persisted, - }) as oio::Writer - } else { - inner - } - })) - .build() - .unwrap(); - let mut env = TestEnv::new().await.with_mock_layer(layer); - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let (snapshot, output) = seed(&engine, region_id).await; - let access = engine.get_region(region_id).unwrap().access_layer.clone(); - armed.store(true, Ordering::SeqCst); - assert!( - engine - .publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]) - .await - .is_err() - ); - assert!(!armed.load(Ordering::SeqCst)); - assert!(engine.get_region(region_id).is_none()); - let path = location::sst_file_path(access.table_dir(), output.file_id(), access.path_type()); - assert!(access.object_store().exists(&path).await.unwrap()); - reopen_region(&engine, region_id, "test".into(), true, Default::default()).await; - let fresh = engine.table_compaction_snapshot(region_id).unwrap(); - assert_eq!(!persisted, !fresh.inputs.is_empty()); - let region = engine.get_region(region_id).unwrap(); - let version = region.manifest_ctx.manifest_version().await; - assert_eq!( - PublicationOutcome::Applied, - engine - .publish_table_compaction(region_id, snapshot, vec![output]) - .await - .unwrap() - ); - assert_eq!( - version + u64::from(!persisted), - region.manifest_ctx.manifest_version().await - ); - assert_eq!(3, row_count(&engine, region_id).await); -} - -#[derive(Debug)] -struct PublicationBarrier { - after_commit: bool, - armed: AtomicBool, - entered: tokio::sync::Notify, - resume: tokio::sync::Notify, -} - -impl PublicationBarrier { - async fn pause(&self) { - if self.armed.swap(false, Ordering::SeqCst) { - self.entered.notify_one(); - self.resume.notified().await; - } - } -} - -#[async_trait::async_trait] -impl RegionHook for PublicationBarrier { - async fn on_sst_files_verified( - &self, - _: RegionId, - _: &store_api::metadata::RegionMetadataRef, - _: &[VerifiedSstFileInfo<'_>], - ) { - if !self.after_commit { - self.pause().await; - } - } - async fn on_manifest_updated( - &self, - _: RegionId, - actions: &RegionMetaActionList, - _: store_api::ManifestVersion, - ) { - if self.after_commit && actions.actions.iter().any(|action| matches!(action, - RegionMetaAction::Edit(edit) if edit.files_to_remove.iter().any(|file| file.level == LEVEL_SHARED))) { - self.pause().await; - } - } -} - -#[rstest::rstest] -#[case::verification(false)] -#[case::completion(true)] -#[tokio::test] -async fn test_close_reopen_fences_old_publication(#[case] after_commit: bool) { - let hook = Arc::new(PublicationBarrier { - after_commit, - armed: AtomicBool::new(false), - entered: Default::default(), - resume: Default::default(), - }); - let plugins = Plugins::new(); - plugins.insert(hook.clone() as RegionHookRef); - let mut env = TestEnv::new().await; - let engine = env.create_engine_with_plugins(config(), plugins).await; - let region_id = RegionId::new(1, 1); - let (snapshot, output) = seed(&engine, region_id).await; - hook.armed.store(true, Ordering::SeqCst); - let (late, ()) = tokio::time::timeout(std::time::Duration::from_secs(10), async { - tokio::join!( - engine.publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]), - async { - hook.entered.notified().await; - reopen_region(&engine, region_id, "test".into(), true, Default::default()).await; - engine - .handle_request( - region_id, - RegionRequest::Truncate(RegionTruncateRequest::All), - ) - .await - .unwrap(); - hook.resume.notify_one(); - } - ) - }) - .await - .unwrap(); - assert!(late.is_err()); - let region = engine.get_region(region_id).unwrap(); - assert!(region.manifest_ctx.manifest().await.files.is_empty()); - assert!( - region - .version() - .ssts - .levels() - .iter() - .all(|level| level.files.is_empty()) - ); - assert_eq!( - PublicationOutcome::StaleInputs, - engine - .publish_table_compaction(region_id, snapshot, vec![output]) - .await - .unwrap() - ); - assert_eq!(0, row_count(&engine, region_id).await); -} - -/// Records one notification per verification, keeping verified footers only as -/// weak references, and checks those references again when the publication's -/// manifest update is announced. `on_manifest_updated` runs after the commit, so -/// this catches footers retained across it; it does not claim the hook fires -/// before the commit. Nothing else in the test keeps the footers alive. -#[derive(Debug, Default)] -struct VerificationRecorder { - verified_files: AtomicUsize, - notifications: AtomicUsize, - manifest_updates: AtomicUsize, - released_by_commit: AtomicBool, - footers: std::sync::Mutex>>, -} - -#[async_trait::async_trait] -impl RegionHook for VerificationRecorder { - async fn on_sst_files_verified( - &self, - _: RegionId, - _: &store_api::metadata::RegionMetadataRef, - files: &[VerifiedSstFileInfo<'_>], - ) { - let mut footers = self.footers.lock().unwrap(); - footers.extend(files.iter().map(|file| Arc::downgrade(file.footer))); - self.verified_files.fetch_add(files.len(), Ordering::SeqCst); - self.notifications.fetch_add(1, Ordering::SeqCst); - } - - async fn on_manifest_updated( - &self, - _: RegionId, - actions: &RegionMetaActionList, - _: store_api::ManifestVersion, - ) { - let is_compaction = actions.actions.iter().any(|action| matches!(action, - RegionMetaAction::Edit(edit) if edit.files_to_remove.iter().any(|file| file.level == LEVEL_SHARED))); - if !is_compaction { - return; - } - let footers = self.footers.lock().unwrap(); - self.released_by_commit.store( - !footers.is_empty() && footers.iter().all(|footer| footer.upgrade().is_none()), - Ordering::SeqCst, - ); - self.manifest_updates.fetch_add(1, Ordering::SeqCst); - } -} - -#[rstest::rstest] -#[case::without_hook(false)] -#[case::with_hook(true)] -#[tokio::test] -async fn test_multiple_outputs_verify_notify_once_and_release_footers(#[case] with_hook: bool) { - let recorder = Arc::new(VerificationRecorder::default()); - let mut env = TestEnv::new().await; - let engine = if with_hook { - let plugins = Plugins::new(); - plugins.insert(recorder.clone() as RegionHookRef); - env.create_engine_with_plugins(config(), plugins).await - } else { - env.create_engine(config()).await - }; - let region_id = RegionId::new(1, 1); - let (snapshot, outputs) = - seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)], false).await; - let publish = || engine.publish_table_compaction(region_id, snapshot.clone(), outputs.clone()); - assert_eq!(PublicationOutcome::Applied, publish().await.unwrap()); - let region = engine.get_region(region_id).unwrap(); - let installed = region.version(); - assert_eq!(PublicationOutcome::Applied, publish().await.unwrap()); - assert!(Arc::ptr_eq(&installed, ®ion.version())); - let expected_notifications = usize::from(with_hook); - assert_eq!( - expected_notifications * outputs.len(), - recorder.verified_files.load(Ordering::SeqCst) - ); - assert_eq!( - expected_notifications, - recorder.notifications.load(Ordering::SeqCst) - ); - if with_hook { - assert_eq!(1, recorder.manifest_updates.load(Ordering::SeqCst)); - assert!(recorder.released_by_commit.load(Ordering::SeqCst)); - assert!( - recorder - .footers - .lock() - .unwrap() - .iter() - .all(|footer| footer.upgrade().is_none()) - ); - } else { - assert_eq!(0, recorder.manifest_updates.load(Ordering::SeqCst)); - } - let manifest = region.manifest_ctx.manifest().await; - assert_eq!(outputs.len(), manifest.files.len()); - for output in &outputs { - assert_eq!( - Some(output), - manifest.files.get(&output.file_id).map(AsRef::as_ref) - ); - } - assert_eq!(6, row_count(&engine, region_id).await); -} - -#[tokio::test] -async fn test_failed_verification_does_not_notify_hook() { - let recorder = Arc::new(VerificationRecorder::default()); - let plugins = Plugins::new(); - plugins.insert(recorder.clone() as RegionHookRef); - let mut env = TestEnv::new().await; - let engine = env.create_engine_with_plugins(config(), plugins).await; - let region_id = RegionId::new(1, 1); - let (snapshot, outputs) = - seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)], false).await; - let region = engine.get_region(region_id).unwrap(); - let version = region.manifest_ctx.manifest_version().await; - let invalid = FileMeta { - file_size: outputs[1].file_size + 1, - ..outputs[1].clone() - }; - let error = engine - .publish_table_compaction( - region_id, - snapshot.clone(), - vec![outputs[0].clone(), invalid], - ) - .await - .unwrap_err(); - assert!(matches!( - error, - crate::error::Error::EditRegion { source, .. } - if matches!(source.as_ref(), crate::error::Error::InvalidRequest { reason, .. } - if reason == "Output SST size mismatch") - )); - assert_eq!(0, recorder.verified_files.load(Ordering::SeqCst)); - assert_eq!(0, recorder.notifications.load(Ordering::SeqCst)); - assert_eq!(version, region.manifest_ctx.manifest_version().await); - assert_eq!( - snapshot.inputs, - engine.table_compaction_snapshot(region_id).unwrap().inputs - ); - assert_eq!(6, row_count(&engine, region_id).await); -} - -#[tokio::test] -async fn test_table_compaction_publication_after_nullable_tag_added() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - engine - .handle_request( - region_id, - RegionRequest::Create(sparse_metric_create_request("flat")), - ) - .await - .unwrap(); - let region = engine.get_region(region_id).unwrap(); - let key = new_sparse_primary_key(&["old"], ®ion.metadata(), 42, 7); - engine - .handle_request(region_id, sparse_metric_put(key, 1000, Some(1.0))) - .await - .unwrap(); - flush_region(&engine, region_id, None).await; - let (snapshot, outputs) = promote_flushed_files(&engine, region_id, 1, false).await; - engine - .handle_request( - region_id, - RegionRequest::Alter(RegionAlterRequest { - kind: AlterKind::AddColumns { - columns: vec![AddColumn { - column_metadata: ColumnMetadata { - column_schema: ColumnSchema::new( - "new_tag", - ConcreteDataType::string_datatype(), - true, - ), - semantic_type: SemanticType::Tag, - column_id: 3, - }, - location: None, - }], - }, - }), - ) - .await - .unwrap(); - // The second publication models a lost acknowledgement after installing the output. - for _ in 0..2 { - assert_eq!( - PublicationOutcome::Applied, - engine - .publish_table_compaction(region_id, snapshot.clone(), outputs.clone()) - .await - .unwrap() - ); - } - let batches = RecordBatches::try_collect( - engine - .scan_to_stream(region_id, Default::default()) - .await - .unwrap(), - ) - .await - .unwrap(); - assert_eq!( - 1, - batches.iter().map(|batch| batch.num_rows()).sum::() - ); - for batch in batches.iter() { - let tag = batch.column_by_name("new_tag").unwrap(); - assert_eq!(tag.len(), tag.null_count()); - } - engine.stop().await.unwrap(); -} - -#[tokio::test] -async fn test_publication_after_drop_field_and_option_changes() { - let mut env = TestEnv::new().await; - let engine = env.create_engine(config()).await; - let region_id = RegionId::new(1, 1); - let (snapshot, output) = seed(&engine, region_id).await; - let alter = - |kind| engine.handle_request(region_id, RegionRequest::Alter(RegionAlterRequest { kind })); - alter(AlterKind::DropColumns { - names: vec!["field_0".into()], - }) - .await - .unwrap(); - alter(AlterKind::SetRegionOptions { - options: vec![SetRegionOption::CompactionOutputParallelism(Some(2))], - }) - .await - .unwrap(); - - let scan = || async { - RecordBatches::try_collect( - engine - .scan_to_stream(region_id, Default::default()) - .await - .unwrap(), - ) - .await - .unwrap() - }; - let before = scan().await; - assert_eq!( - 3, - before.iter().map(|batch| batch.num_rows()).sum::() - ); - assert!( - before - .iter() - .all(|batch| batch.column_by_name("field_0").is_none()) - ); - let publish = - || engine.publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]); - assert_eq!(PublicationOutcome::Applied, publish().await.unwrap()); - alter(AlterKind::UnsetRegionOptions { - keys: vec![UnsetRegionOption::CompactionOutputParallelism], - }) - .await - .unwrap(); - assert_eq!(PublicationOutcome::Applied, publish().await.unwrap()); - assert_eq!( - before.pretty_print().unwrap(), - scan().await.pretty_print().unwrap() - ); - - let mut changed = (*snapshot.metadata).clone(); - changed.set_partition_expr(Some("changed".into())); - assert!(!is_table_compaction_metadata_compatible( - &snapshot.metadata, - &changed - )); - let mut stale = snapshot; - stale.metadata = Arc::new(changed); - assert_eq!( - PublicationOutcome::StaleInputs, - engine - .publish_table_compaction(region_id, stale, vec![output]) - .await - .unwrap() - ); - engine.stop().await.unwrap(); -} diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index c06f04fca43..2415886c571 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -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 { .. } diff --git a/src/mito2/src/gc.rs b/src/mito2/src/gc.rs index e8ed3c760a6..e828c7e18fe 100644 --- a/src/mito2/src/gc.rs +++ b/src/mito2/src/gc.rs @@ -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, ) -> 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, -) -> 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, @@ -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, - /// 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::>(); - 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::>(); - 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)) = (®ion, &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, in_manifest: &HashMap>, in_tmp_ref: &HashSet<(FileId, Option)>, may_linger_files: &HashSet<&RemovedFile>, eligible_for_delete: &HashSet<&RemovedFile>, unknown_file_may_linger_until: chrono::DateTime, - ) -> (Vec, bool) { + ) -> Vec { 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>, in_tmp_ref: &HashSet<(FileId, Option)>, recently_removed_files: BTreeMap>, all_entries: Vec, - ) -> Result<(Vec, bool)> { + ) -> Result> { 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, diff --git a/src/mito2/src/gc/worker_test.rs b/src/mito2/src/gc/worker_test.rs index 9b383ed2b48..7755a8ce5ed 100644 --- a/src/mito2/src/gc/worker_test.rs +++ b/src/mito2/src/gc/worker_test.rs @@ -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> { - 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> { - 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, -) -> (TestEnv, MitoEngine, LocalGcWorker, RegionId, Vec) { - 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] diff --git a/src/mito2/src/manifest.rs b/src/mito2/src/manifest.rs index 3eb66053575..99cd93282cb 100644 --- a/src/mito2/src/manifest.rs +++ b/src/mito2/src/manifest.rs @@ -16,7 +16,6 @@ pub mod action; mod checkpointer; -mod compat; pub mod manager; pub mod storage; #[cfg(test)] diff --git a/src/mito2/src/manifest/action.rs b/src/mito2/src/manifest/action.rs index 6388cfca889..649940d886d 100644 --- a/src/mito2/src/manifest/action.rs +++ b/src/mito2/src/manifest/action.rs @@ -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 { - 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 { 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 { 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(); diff --git a/src/mito2/src/manifest/compat.rs b/src/mito2/src/manifest/compat.rs deleted file mode 100644 index a81656e0e49..00000000000 --- a/src/mito2/src/manifest/compat.rs +++ /dev/null @@ -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, - extensions: Option, -} - -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, - } - 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>, - } - 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(()) -} diff --git a/src/mito2/src/manifest/compat/tests.rs b/src/mito2/src/manifest/compat/tests.rs deleted file mode 100644 index 52a115a6727..00000000000 --- a/src/mito2/src/manifest/compat/tests.rs +++ /dev/null @@ -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" - ); -} diff --git a/src/mito2/src/manifest/tests/compatibility.rs b/src/mito2/src/manifest/tests/compatibility.rs index d365c918103..9dff04e7717 100644 --- a/src/mito2/src/manifest/tests/compatibility.rs +++ b/src/mito2/src/manifest/tests/compatibility.rs @@ -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::>() ); 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::(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 { .. }) - )); -} diff --git a/src/mito2/src/metrics.rs b/src/mito2/src/metrics.rs index 02d4cb7021d..f76d5cae476 100644 --- a/src/mito2/src/metrics.rs +++ b/src/mito2/src/metrics.rs @@ -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"; diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index e343c0afd12..e74a429baf3 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -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, /// Counters that should receive query-load metrics. pub(crate) query_stat_counters: Option, #[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 { diff --git a/src/mito2/src/read/scan_util.rs b/src/mito2/src/read/scan_util.rs index 905f7c17095..afff26b118c 100644 --- a/src/mito2/src/read/scan_util.rs +++ b/src/mito2/src/read/scan_util.rs @@ -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) { diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index e8fbf123fed..f3e081a55b1 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -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; diff --git a/src/mito2/src/region/opener.rs b/src/mito2/src/region/opener.rs index 7e0469b8aa5..3eeda751de1 100644 --- a/src/mito2/src/region/opener.rs +++ b/src/mito2/src/region/opener.rs @@ -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, diff --git a/src/mito2/src/request.rs b/src/mito2/src/request.rs index b6661bed007..e46afd68250 100644 --- a/src/mito2/src/request.rs +++ b/src/mito2/src/request.rs @@ -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), + 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. diff --git a/src/mito2/src/sst/file.rs b/src/mito2/src/sst/file.rs index 0c3350b37b6..23dd5aad9a8 100644 --- a/src/mito2/src/sst/file.rs +++ b/src/mito2/src/sst/file.rs @@ -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 { - 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 { diff --git a/src/mito2/src/sst/file_purger.rs b/src/mito2/src/sst/file_purger.rs index a93e4677e92..f509ef21cbd 100644 --- a/src/mito2/src/sst/file_purger.rs +++ b/src/mito2/src/sst/file_purger.rs @@ -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()); } } diff --git a/src/mito2/src/sst/index/puffin_manager.rs b/src/mito2/src/sst/index/puffin_manager.rs index 26b7c56d198..1577f3a13b7 100644 --- a/src/mito2/src/sst/index/puffin_manager.rs +++ b/src/mito2/src/sst/index/puffin_manager.rs @@ -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, diff --git a/src/mito2/src/sst/index/registry.rs b/src/mito2/src/sst/index/registry.rs index fb9bcb07311..415638b415d 100644 --- a/src/mito2/src/sst/index/registry.rs +++ b/src/mito2/src/sst/index/registry.rs @@ -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![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 = diff --git a/src/mito2/src/sst/index/store.rs b/src/mito2/src/sst/index/store.rs index f84e457ae60..a2abeec3a8f 100644 --- a/src/mito2/src/sst/index/store.rs +++ b/src/mito2/src/sst/index/store.rs @@ -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> 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 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>; -/// 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 diff --git a/src/mito2/src/sst/parquet/writer.rs b/src/mito2/src/sst/parquet/writer.rs index 3ee0f94ebc2..29b6b5cce7d 100644 --- a/src/mito2/src/sst/parquet/writer.rs +++ b/src/mito2/src/sst/parquet/writer.rs @@ -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 SstArrowWriter { } } -/// 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, - 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>, cancellation: Option, - memory: WriteMemory, /// Field columns of the current file that skip min/max statistics, picked from its first batch. large_value_columns: Vec, /// 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>, - /// 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, /// Signals cancellation; the writer still drains encoders and aborts unfinished output. pub(crate) cancellation: Option, } @@ -322,8 +283,6 @@ pub struct ObjectStoreWriter { inner: Writer, write_buffer_size: usize, cancellation: Option, - #[cfg(feature = "enterprise")] - buffered_upload: Option, } 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 { - #[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, } impl WriterFactory for ObjectStoreWriterFactory { @@ -425,25 +356,12 @@ impl WriterFactory for ObjectStoreWriterFactory { write_buffer_size: usize, cancellation: Option<&CancellationToken>, ) -> Result { - #[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) -> 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::(), - ); - 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::>::supports(&writer_props) { SstArrowWriter::Parallel( @@ -1018,13 +881,6 @@ fn map_write_error(error: ParquetError) -> Error { if source.is::() { return crate::error::SstWriteCancelledSnafu.build(); } - #[cfg(feature = "enterprise")] - if let Some(error) = source.downcast_ref::() { - return crate::error::MultiRegionCompactionResourceSnafu { - reason: error.to_string(), - } - .build(); - } } WriteParquetSnafu.into_error(error) } diff --git a/src/mito2/src/sst/upload.rs b/src/mito2/src/sst/upload.rs index ac22ee6b578..f5c83ccac06 100644 --- a/src/mito2/src/sst/upload.rs +++ b/src/mito2/src/sst/upload.rs @@ -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; diff --git a/src/mito2/src/sst/upload/buffered.rs b/src/mito2/src/sst/upload/buffered.rs deleted file mode 100644 index 3d46a375e71..00000000000 --- a/src/mito2/src/sst/upload/buffered.rs +++ /dev/null @@ -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 { - 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 { - sink: S, - buffer: UploadBuffer, -} - -impl + Unpin> BufferedUploadWriter { - fn poll_send_part(&mut self, cx: &mut Context<'_>) -> Poll> { - ready!(Pin::new(&mut self.sink).poll_ready(cx))?; - Poll::Ready(Pin::new(&mut self.sink).start_send(self.buffer.take_part())) - } -} - -impl + Unpin> AsyncWrite for BufferedUploadWriter { - fn poll_write( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - bytes: &[u8], - ) -> Poll> { - 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> { - 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> { - 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::()); - 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() - ); - } -} diff --git a/src/mito2/src/sst/version.rs b/src/mito2/src/sst/version.rs index 3498bed07e3..40388173e3a 100644 --- a/src/mito2/src/sst/version.rs +++ b/src/mito2/src/sst/version.rs @@ -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) { 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)] diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index 1c2b9e454e6..9dab9c3725c 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -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; diff --git a/src/mito2/src/worker/handle_copy_region.rs b/src/mito2/src/worker/handle_copy_region.rs index 88684f124ec..8fae0322ea2 100644 --- a/src/mito2/src/worker/handle_copy_region.rs +++ b/src/mito2/src/worker/handle_copy_region.rs @@ -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 RegionWorkerLoop { }; 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 RegionWorkerLoop { 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 RegionWorkerLoop { 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 RegionWorkerLoop { 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 RegionWorkerLoop { 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", diff --git a/src/mito2/src/worker/handle_manifest.rs b/src/mito2/src/worker/handle_manifest.rs index ae1e6749e8b..d0c0003ebbc 100644 --- a/src/mito2/src/worker/handle_manifest.rs +++ b/src/mito2/src/worker/handle_manifest.rs @@ -104,11 +104,7 @@ impl RegionEditQueue { fn dequeue(&mut self) -> Option { fn mergeable_import(request: &RegionEditRequest) -> Option { - 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 RegionWorkerLoop { 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(®ion, &mut edit, external) - } - #[cfg(feature = "enterprise")] - RegionEditKind::Compaction(_) => Ok(()), - }; + let RegionEditKind::Import { external } = kind; + let preparation = prepare_region_edit(®ion, &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 RegionWorkerLoop { // 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( - ®ion, - &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(®ion, &context, edit.clone()) - .await - } - } + let result = edit_region( + ®ion, + &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 RegionWorkerLoop { 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 = ¤t.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 = ¤t.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(®ion, &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() } }; diff --git a/src/mito2/src/worker/handle_rebuild_index.rs b/src/mito2/src/worker/handle_rebuild_index.rs index 76892409322..289dd05699a 100644 --- a/src/mito2/src/worker/handle_rebuild_index.rs +++ b/src/mito2/src/worker/handle_rebuild_index.rs @@ -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 RegionWorkerLoop { .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 { diff --git a/src/mito2/src/worker/handle_table_compaction.rs b/src/mito2/src/worker/handle_table_compaction.rs deleted file mode 100644 index 1a7bc9b83f4..00000000000 --- a/src/mito2/src/worker/handle_table_compaction.rs +++ /dev/null @@ -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 { - 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 { - 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::>>() - .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(); - } -} diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index cfe357e4cb3..3cd995e22ac 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -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, } diff --git a/src/store-api/src/region_request.rs b/src/store-api/src/region_request.rs index d58871f8af1..3bfe06264ff 100644 --- a/src/store-api/src/region_request.rs +++ b/src/store-api/src/region_request.rs @@ -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. diff --git a/tests/compatibility/README.md b/tests/compatibility/README.md index dc5466f8ef8..e9adaf4a81f 100644 --- a/tests/compatibility/README.md +++ b/tests/compatibility/README.md @@ -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: diff --git a/tests/compatibility/manifest/table_compaction/legacy-edit.json b/tests/compatibility/manifest/region_edit/legacy-edit.json similarity index 100% rename from tests/compatibility/manifest/table_compaction/legacy-edit.json rename to tests/compatibility/manifest/region_edit/legacy-edit.json diff --git a/tests/compatibility/manifest/table_compaction/legacy-manifest.json b/tests/compatibility/manifest/region_edit/legacy-manifest.json similarity index 100% rename from tests/compatibility/manifest/table_compaction/legacy-manifest.json rename to tests/compatibility/manifest/region_edit/legacy-manifest.json diff --git a/tests/compatibility/manifest/table_compaction/README.md b/tests/compatibility/manifest/table_compaction/README.md deleted file mode 100644 index 993704fe27b..00000000000 --- a/tests/compatibility/manifest/table_compaction/README.md +++ /dev/null @@ -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.