diff --git a/licenserc-enterprise.toml b/licenserc-enterprise.toml index d11d344b64d..89bc213db30 100644 --- a/licenserc-enterprise.toml +++ b/licenserc-enterprise.toml @@ -15,6 +15,18 @@ headerPath = "licenses/enterprise-header.txt" # with the "# enterprise" block in `licenserc.toml`'s `excludes` — both are # enforced by `make check-enterprise-license`. includes = [ + "src/mito2/src/compaction/scheduler/hybrid.rs", + "src/mito2/src/compaction/compactor/experiment/parallelism.rs", + "src/mito2/src/compaction/multi_region/worker.rs", + "src/mito2/src/compaction/multi_region/spill.rs", + "src/mito2/src/compaction/multi_region/source.rs", + "src/mito2/src/compaction/multi_region/streaming.rs", + "src/mito2/src/compaction/multi_region/tests.rs", + "src/mito2/src/compaction/multi_region/writer.rs", + "src/mito2/src/compaction/multi_region/streaming/writer_block.rs", + "src/mito2/src/compaction/multi_region.rs", + "src/mito2/src/compaction/compactor/experiment.rs", + "src/mito2/src/compaction/compactor/experiment/batch_window.rs", "src/common/meta/src/rpc/ddl/trigger.rs", "src/operator/src/expr_helper/trigger.rs", "src/sql/src/statements/alter/trigger.rs", diff --git a/licenserc.toml b/licenserc.toml index 42e6464017c..535f40d286c 100644 --- a/licenserc.toml +++ b/licenserc.toml @@ -21,6 +21,18 @@ includes = [ ] excludes = [ + "src/mito2/src/compaction/scheduler/hybrid.rs", + "src/mito2/src/compaction/compactor/experiment/parallelism.rs", + "src/mito2/src/compaction/multi_region/worker.rs", + "src/mito2/src/compaction/multi_region/spill.rs", + "src/mito2/src/compaction/multi_region/source.rs", + "src/mito2/src/compaction/multi_region/streaming.rs", + "src/mito2/src/compaction/multi_region/tests.rs", + "src/mito2/src/compaction/multi_region/writer.rs", + "src/mito2/src/compaction/multi_region/streaming/writer_block.rs", + "src/mito2/src/compaction/multi_region.rs", + "src/mito2/src/compaction/compactor/experiment.rs", + "src/mito2/src/compaction/compactor/experiment/batch_window.rs", # copied sources "src/common/base/src/readable_size.rs", "src/common/base/src/secrets.rs", diff --git a/src/index/src/fulltext_index/create/tantivy.rs b/src/index/src/fulltext_index/create/tantivy.rs index 6f05921e3a6..e7a1db44a83 100644 --- a/src/index/src/fulltext_index/create/tantivy.rs +++ b/src/index/src/fulltext_index/create/tantivy.rs @@ -14,9 +14,12 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use async_trait::async_trait; use common_error::ext::BoxedError; +use common_telemetry::warn; use puffin::puffin_manager::{PuffinWriter, PutOptions}; use snafu::{OptionExt, ResultExt}; use tantivy::indexer::NoMergePolicy; @@ -37,6 +40,8 @@ pub const ROWID_FIELD_NAME: &str = "greptime_fulltext_rowid"; pub struct TantivyFulltextIndexCreator { /// The tantivy index writer. writer: Option, + /// Retained across awaits so abort can join a cancelled finish operation. + finishing: Option>>, /// The field for the text. text_field: tantivy::schema::Field, @@ -47,28 +52,94 @@ pub struct TantivyFulltextIndexCreator { /// The current max row id. max_rowid: u64, - /// The directory path in filesystem to store the index. - path: PathBuf, + /// Shared with blocking work so cancellation cannot unlink an active index. + directory: Arc, /// The configuration of the fulltext index. config: Config, } +/// Owns an empty temporary directory, never a pre-existing index. +struct TempIndexDirectory { + path: PathBuf, + removed: AtomicBool, +} + +impl TempIndexDirectory { + fn create(path: PathBuf) -> Result> { + std::fs::create_dir_all(&path).context(IoSnafu)?; + if std::fs::read_dir(&path) + .context(IoSnafu)? + .next() + .transpose() + .context(IoSnafu)? + .is_some() + { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + "Tantivy temporary directory must be empty", + )) + .context(IoSnafu); + } + Ok(Arc::new(Self { + path, + removed: AtomicBool::new(false), + })) + } +} + +impl Drop for TempIndexDirectory { + fn drop(&mut self) { + if self.removed.load(Ordering::Relaxed) { + return; + } + let path = self.path.clone(); + common_runtime::spawn_blocking_global(move || { + if let Err(error) = std::fs::remove_dir_all(&path) + && error.kind() != std::io::ErrorKind::NotFound + { + warn!(error; "Failed to remove temporary Tantivy directory: {}", path.display()); + } + }); + } +} + +impl Drop for TantivyFulltextIndexCreator { + fn drop(&mut self) { + if let Some(writer) = self.writer.take() { + let directory = self.directory.clone(); + // IndexWriter::drop joins its threads; neither that nor directory + // removal may block the async task cancelling this creator. + common_runtime::spawn_blocking_global(move || { + drop(writer); + drop(directory); + }); + } + } +} + impl TantivyFulltextIndexCreator { /// Creates a new `TantivyFulltextIndexCreator`. /// - /// The `path` is the directory path in filesystem to store the index. + /// `path` must be an empty temporary directory. It is removed after the + /// creator and any in-flight blocking work release it. pub async fn new(path: impl AsRef, config: Config, memory_limit: usize) -> Result { - tokio::fs::create_dir_all(path.as_ref()) + let path = path.as_ref().to_path_buf(); + // Keep creation and its guard in the same task: dropping the awaiting + // future must not race mkdir against cleanup. + common_runtime::spawn_blocking_global(move || Self::create(path, config, memory_limit)) .await - .context(IoSnafu)?; + .context(JoinSnafu)? + } + fn create(path: PathBuf, config: Config, memory_limit: usize) -> Result { + let directory = TempIndexDirectory::create(path)?; let mut schema_builder = Schema::builder(); let text_field = schema_builder.add_text_field(TEXT_FIELD_NAME, TEXT); let rowid_field = schema_builder.add_u64_field(ROWID_FIELD_NAME, STORED); let schema = schema_builder.build(); - let mut index = Index::create_in_dir(&path, schema).context(TantivySnafu)?; + let mut index = Index::create_in_dir(&directory.path, schema).context(TantivySnafu)?; index.settings_mut().docstore_compression = Compressor::Zstd(ZstdCompressor::default()); index.set_tokenizers(config.build_tantivy_tokenizer()); @@ -82,14 +153,33 @@ impl TantivyFulltextIndexCreator { Ok(Self { writer: Some(writer), + finishing: None, text_field, rowid_field, max_rowid: 0, - path: path.as_ref().to_path_buf(), + directory, config, }) } + async fn finish_writer(&mut self) -> Result<()> { + if self.finishing.is_none() { + let writer = self.writer.take().context(FinishedSnafu)?; + let directory = self.directory.clone(); + self.finishing = Some(common_runtime::spawn_blocking_global(move || { + let _directory = directory; + // Declare the writer after the lease so error unwinding also + // drops/joins it before releasing the directory. + let mut writer = writer; + writer.commit().context(TantivySnafu)?; + writer.wait_merging_threads().context(TantivySnafu) + })); + } + let completed = self.finishing.as_mut().context(FinishedSnafu)?.await; + self.finishing.take(); + completed.context(JoinSnafu)? + } + fn sanitize_memory_limit(memory_limit: usize) -> usize { // Port from tantivy::indexer::index_writer::{MEMORY_BUDGET_NUM_BYTES_MIN, MEMORY_BUDGET_NUM_BYTES_MAX} const MARGIN_IN_BYTES: usize = 1_000_000; @@ -116,13 +206,7 @@ impl FulltextIndexCreator for TantivyFulltextIndexCreator { blob_key: &str, put_options: PutOptions, ) -> Result { - let mut writer = self.writer.take().context(FinishedSnafu)?; - common_runtime::spawn_blocking_global(move || { - writer.commit().context(TantivySnafu)?; - writer.wait_merging_threads().context(TantivySnafu) - }) - .await - .context(JoinSnafu)??; + self.finish_writer().await?; let property_key = KEY_FULLTEXT_CONFIG.to_string(); let property_value = serde_json::to_string(&self.config).context(SerializeToJsonSnafu)?; @@ -130,7 +214,7 @@ impl FulltextIndexCreator for TantivyFulltextIndexCreator { puffin_writer .put_dir( blob_key, - self.path.clone(), + self.directory.path.clone(), put_options, HashMap::from([(property_key, property_value)]), ) @@ -140,15 +224,15 @@ impl FulltextIndexCreator for TantivyFulltextIndexCreator { } async fn abort(&mut self) -> Result<()> { - let mut writer = self.writer.take().context(FinishedSnafu)?; - common_runtime::spawn_blocking_global(move || { - writer.commit().context(TantivySnafu)?; - writer.wait_merging_threads().context(TantivySnafu) - }) - .await - .context(JoinSnafu)??; - - tokio::fs::remove_dir_all(&self.path).await.context(IoSnafu) + if self.writer.is_some() || self.finishing.is_some() { + self.finish_writer().await?; + } + match tokio::fs::remove_dir_all(&self.directory.path).await { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + removed => removed.context(IoSnafu)?, + } + self.directory.removed.store(true, Ordering::Relaxed); + Ok(()) } fn memory_usage(&self) -> usize { @@ -171,7 +255,10 @@ mod tests { use super::*; use crate::fulltext_index::Analyzer; - struct MockPuffinWriter; + #[derive(Default)] + struct MockPuffinWriter { + blocked: Option>, + } #[async_trait] impl PuffinWriter for MockPuffinWriter { @@ -191,10 +278,15 @@ mod tests { async fn put_dir( &mut self, _key: &str, - _dir: PathBuf, + dir: PathBuf, _options: PutOptions, _properties: HashMap, ) -> puffin::error::Result { + if let Some(blocked) = &self.blocked { + assert!(dir.join("meta.json").exists()); + blocked.notify_one(); + futures::future::pending::<()>().await; + } Ok(0) } fn set_footer_lz4_compressed(&mut self, _lz4_compressed: bool) { @@ -206,6 +298,116 @@ mod tests { } } + async fn assert_directory_removed(path: &Path) { + tokio::time::timeout(std::time::Duration::from_secs(10), async { + while tokio::fs::try_exists(path).await.unwrap() { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("temporary Tantivy directory leaked"); + } + + #[tokio::test] + async fn test_creator_drop_cleans_temporary_files() { + for stage in ["active", "finished", "aborted"] { + let root = create_temp_dir("tantivy-drop-"); + let path = root.path().join("index"); + let mut creator = TantivyFulltextIndexCreator::new(&path, Config::default(), 1) + .await + .unwrap(); + creator.push_text("indexed text").await.unwrap(); + assert!(path.join("meta.json").exists()); + match stage { + "finished" => { + creator + .finish( + &mut MockPuffinWriter::default(), + "index", + PutOptions::default(), + ) + .await + .unwrap(); + } + "aborted" => { + creator.abort().await.unwrap(); + } + _ => {} + } + drop(creator); + assert_directory_removed(&path).await; + assert!(root.path().exists()); + } + } + + #[tokio::test] + async fn test_abort_after_cancelled_finish_cleans_temporary_files() { + let root = create_temp_dir("tantivy-cancel-finish-"); + let path = root.path().join("index"); + let mut creator = TantivyFulltextIndexCreator::new(&path, Config::default(), 1) + .await + .unwrap(); + creator.push_text("indexed text").await.unwrap(); + let blocked = Arc::new(tokio::sync::Notify::new()); + let mut writer = MockPuffinWriter { + blocked: Some(blocked.clone()), + }; + { + let finishing = creator.finish(&mut writer, "index", PutOptions::default()); + tokio::pin!(finishing); + tokio::select! { + _ = blocked.notified() => {} + result = &mut finishing => panic!("finish did not reach the blocked upload: {result:?}"), + _ = tokio::time::sleep(std::time::Duration::from_secs(10)) => panic!("finish stalled"), + } + } + creator.abort().await.unwrap(); + creator.abort().await.unwrap(); + assert!(!path.exists()); + } + + #[tokio::test] + async fn test_detached_initialization_cleans_its_result() { + let root = create_temp_dir("tantivy-detached-init-"); + let path = root.path().join("index"); + let creating_path = path.clone(); + let (ready, initialized) = tokio::sync::oneshot::channel(); + let (release, released) = std::sync::mpsc::channel(); + // The real constructor runs on the blocking pool. Detaching its handle + // must clean even if cancellation happens before the result is delivered. + let creating = common_runtime::spawn_blocking_global(move || { + let creator = + TantivyFulltextIndexCreator::create(creating_path, Config::default(), 1).unwrap(); + ready.send(()).unwrap(); + released.recv().unwrap(); + creator + }); + tokio::time::timeout(std::time::Duration::from_secs(10), initialized) + .await + .unwrap() + .unwrap(); + assert!(path.join("meta.json").exists()); + drop(creating); + release.send(()).unwrap(); + assert_directory_removed(&path).await; + } + + #[tokio::test] + async fn test_initialization_preserves_nonempty_directory() { + let root = create_temp_dir("tantivy-existing-"); + let sentinel = root.path().join("existing"); + tokio::fs::write(&sentinel, "must survive").await.unwrap(); + assert!( + TantivyFulltextIndexCreator::new(root.path(), Config::default(), 1) + .await + .is_err() + ); + assert_eq!( + "must survive", + tokio::fs::read_to_string(&sentinel).await.unwrap() + ); + } + #[tokio::test] async fn test_creator_basic() { let memory_limits = [1, 64_000_000, usize::MAX]; @@ -215,7 +417,7 @@ mod tests { let texts = vec!["hello", "world", "hello, world", "foo!", "Bar"]; let config = Config::default(); - build_index(&texts, temp_dir.path(), config, memory_limit).await; + let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await; let cases = [ ("hello", vec![0u32, 2]), @@ -239,7 +441,7 @@ mod tests { case_sensitive: true, ..Config::default() }; - build_index(&texts, temp_dir.path(), config, memory_limit).await; + let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await; let cases = [ ("hello", vec![0u32, 2]), @@ -267,7 +469,7 @@ mod tests { analyzer: Analyzer::Chinese, ..Config::default() }; - build_index(&texts, temp_dir.path(), config, memory_limit).await; + let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await; let cases = [ ("你好", vec![0u32, 2, 3]), @@ -291,7 +493,7 @@ mod tests { case_sensitive: true, analyzer: Analyzer::Chinese, }; - build_index(&texts, temp_dir.path(), config, memory_limit).await; + let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await; let cases = [ ("你好", vec![0u32, 2, 3]), @@ -307,7 +509,12 @@ mod tests { } } - async fn build_index(texts: &[&str], path: &Path, config: Config, memory_limit: usize) { + async fn build_index( + texts: &[&str], + path: &Path, + config: Config, + memory_limit: usize, + ) -> TantivyFulltextIndexCreator { let mut creator = TantivyFulltextIndexCreator::new(path, config, memory_limit) .await .unwrap(); @@ -315,9 +522,10 @@ mod tests { creator.push_text(text).await.unwrap(); } creator - .finish(&mut MockPuffinWriter, "", PutOptions::default()) + .finish(&mut MockPuffinWriter::default(), "", PutOptions::default()) .await .unwrap(); + creator } async fn query_and_check(path: &Path, config: Config, cases: &[(&str, Vec)]) { diff --git a/src/mito2/src/access_layer.rs b/src/mito2/src/access_layer.rs index 7a80687958b..0d059c9a572 100644 --- a/src/mito2/src/access_layer.rs +++ b/src/mito2/src/access_layer.rs @@ -348,6 +348,29 @@ impl AccessLayer { request: SstWriteRequest, write_opts: &WriteOptions, metrics: &mut Metrics, + ) -> Result { + self.write_sst_inner(request, write_opts, metrics, None) + .await + } + + #[cfg(feature = "enterprise")] + pub(crate) async fn write_sst_with_guard( + &self, + request: SstWriteRequest, + write_opts: &WriteOptions, + metrics: &mut Metrics, + guard: Arc, + ) -> Result { + self.write_sst_inner(request, write_opts, metrics, Some(guard)) + .await + } + + async fn write_sst_inner( + &self, + request: SstWriteRequest, + write_opts: &WriteOptions, + metrics: &mut Metrics, + guard: Option>, ) -> Result { let op_type = request.op_type; let region_id = request.metadata.region_id; @@ -359,7 +382,9 @@ impl AccessLayer { request.max_sequence }; - let sst_info = if let Some(write_cache) = cache_manager.write_cache() { + let sst_info = if let Some(write_cache) = cache_manager.write_cache() + && guard.is_none() + { // Write to the write cache. write_cache .write_and_upload_sst( @@ -405,7 +430,13 @@ impl AccessLayer { metrics, ) .await - .with_file_cleaner(cleaner); + .with_file_cleaner(cleaner) + .with_write_concurrency(if guard.is_some() { + 1 + } else { + crate::sst::DEFAULT_WRITE_CONCURRENCY + }) + .with_write_guard(guard); match request.sst_write_format { FormatType::PrimaryKey => { writer diff --git a/src/mito2/src/compaction.rs b/src/mito2/src/compaction.rs index 0f1b637e096..167559e3972 100644 --- a/src/mito2/src/compaction.rs +++ b/src/mito2/src/compaction.rs @@ -17,6 +17,8 @@ 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 4c89343b61c..7e741c0bf1c 100644 --- a/src/mito2/src/compaction/compactor.rs +++ b/src/mito2/src/compaction/compactor.rs @@ -12,6 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[cfg(feature = "enterprise")] +pub(crate) mod experiment; + use std::num::NonZeroU64; use std::sync::Arc; use std::time::Duration; @@ -434,6 +437,26 @@ impl CompactionContext { &self, merge_output: MergeOutput, ) -> Result<(RegionEdit, ManifestVersion)> { + #[cfg(feature = "enterprise")] + let shared_stats = if experiment::enabled(self.region_id) + && experiment::shared_inputs(merge_output.files_to_remove.iter()) + { + Some(( + merge_output.files_to_add.len(), + merge_output + .files_to_add + .iter() + .map(|f| f.num_rows) + .sum::(), + merge_output + .files_to_add + .iter() + .map(|f| f.file_size) + .sum::(), + )) + } else { + None + }; let edit = RegionEdit { files_to_add: merge_output.files_to_add, files_to_remove: merge_output.files_to_remove, @@ -452,6 +475,18 @@ impl CompactionContext { .update_manifest_for_compaction(action_list) .await?; + #[cfg(feature = "enterprise")] + if let Some((files, rows, bytes)) = shared_stats { + experiment::record_publication(self, &edit.files_to_remove).await?; + common_telemetry::info!( + "hybrid_shared_published region={} files={} rows={} bytes={} manifest={}", + self.region_id, + files, + rows, + bytes, + manifest_version + ); + } Ok((edit, manifest_version)) } } @@ -772,6 +807,12 @@ impl DefaultCompactor { context: &CompactionContext, unit: &CompactionUnit, ) -> Result { + #[cfg(feature = "enterprise")] + if experiment::enabled(context.region_id) + && experiment::shared_inputs(unit.inputs.iter().map(|f| f.meta_ref())) + { + return experiment::merge(context, unit, self.cancel_handle.clone()).await; + } let mut result = MergeOutput { files_to_remove: unit.inputs.iter().map(|f| f.meta_ref().clone()).collect(), compaction_time_window: Some(unit.time_window_size), @@ -857,9 +898,36 @@ where let context = context.clone(); let uncommitted = self.uncommitted.clone(); let fut = async move { + let region_id = context.region_id; + let group = output + .inputs + .first() + .map(|f| f.file_id().to_string()) + .unwrap_or_default(); + let rows = output + .inputs + .iter() + .map(|f| f.meta_ref().num_rows) + .sum::(); + let started = std::time::Instant::now(); + common_telemetry::info!( + "testbed_l1_group_start region={} group={} files={} rows={} encode_parallelism={}", + region_id.as_u64(), + group, + output.inputs.len(), + rows, + write_opts.encode_parallelism + ); let result = merger .merge_single_output(context, output, write_opts) .await; + common_telemetry::info!( + "testbed_l1_group_end region={} group={} elapsed_us={} success={}", + region_id.as_u64(), + group, + started.elapsed().as_micros(), + result.is_ok() + ); if let (Some(uncommitted), Ok((_, infos))) = (&uncommitted, &result) { uncommitted.track(infos); } @@ -1599,14 +1667,26 @@ mod tests { } #[rstest::rstest] - #[case::successful_outputs(false)] - #[case::join_error(true)] + #[case::successful_outputs(false, 2)] + #[case::join_error(true, 2)] + #[case::ordinary_eight(false, 8)] + #[case::scanner_sixteen(false, 16)] + #[case::scanner_twenty_four(false, 24)] #[tokio::test] - async fn test_merge_ssts_cancellation_waits_for_encoders(#[case] panic_merge: bool) { + async fn test_merge_ssts_cancellation_waits_for_encoders( + #[case] panic_merge: bool, + #[case] parallelism: usize, + ) { + // The fixture blocks every encoder before release; all cases need + // enough threads to reach their gates concurrently. + common_runtime::init_global_runtimes(&common_runtime::global::RuntimeOptions { + compact_rt_max_blocking_threads: 32, + ..Default::default() + }); let mut region = new_test_compaction_region().await; - region.max_parallelism = 2; + region.max_parallelism = parallelism; region.region_options.compaction_output_parallelism = Some(2); - let inputs: Vec<_> = (0..3).map(|_| dummy_file_meta()).collect(); + let inputs: Vec<_> = (0..parallelism + 1).map(|_| dummy_file_meta()).collect(); let picker_output = PickerOutput { outputs: inputs .iter() @@ -1638,7 +1718,7 @@ mod tests { }); assert!(futures::poll!(merge.as_mut()).is_pending()); let mut encoders = Vec::new(); - for _ in 0..2 { + for _ in 0..parallelism { encoders.push( timeout(Duration::from_secs(10), started_rx.recv()) .await diff --git a/src/mito2/src/compaction/compactor/experiment.rs b/src/mito2/src/compaction/compactor/experiment.rs new file mode 100644 index 00000000000..e6b2d23a010 --- /dev/null +++ b/src/mito2/src/compaction/compactor/experiment.rs @@ -0,0 +1,658 @@ +// 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. + +//! Fixed-topology two-stage experiment: local shared L0 routing, remote per-region L1. +//! Round objects are immutable; each leader publishes only its own region manifest. +mod batch_window; +mod parallelism; +pub(crate) use parallelism::{automatic_parallelism, merge_parallelism}; + +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use common_base::cancellation::CancellationHandle; +use object_store::{ErrorKind, ObjectStore}; +use partition::multi_dim::MultiDimPartitionRule; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use snafu::{ResultExt, ensure}; +use store_api::metadata::RegionMetadata; +use store_api::region_request::PathType; +use store_api::storage::{FileId, RegionId}; + +use super::{CompactionContext, CompactionRegion, MergeOutput}; +use crate::compaction::CompactionOutput; +use crate::compaction::multi_region::{ + MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, compact_regions, +}; +use crate::compaction::picker::PickerOutput; +use crate::compaction::unit::CompactionUnit; +use crate::error::{ + InvalidMultiRegionCompactionSnafu as Invalid, OpenDalSnafu, Result, SerdeJsonSnafu, +}; +use crate::region::options::RegionOptions; +use crate::sst::file::{FileMeta, RegionFileId}; +use crate::sst::parquet::writer::SstWriteGuard; + +static WIDTH: LazyLock = LazyLock::new(|| { + std::env::var("TESTBED_SHARED_BATCH_FILES") + .unwrap_or_else(|_| "32".into()) + .parse::() + .expect("invalid TESTBED_SHARED_BATCH_FILES") + .get() +}); +static REGIONS: LazyLock = LazyLock::new(|| { + std::env::var("TESTBED_SHARED_TABLE_REGIONS") + .unwrap_or_else(|_| "12".into()) + .parse::() + .expect("invalid TESTBED_SHARED_TABLE_REGIONS") + .get() +}); +static REGION_COUNTS: LazyLock> = LazyLock::new(|| { + std::env::var("TESTBED_SHARED_TABLE_LAYOUT") + .unwrap_or_default() + .split(',') + .filter(|s| !s.trim().is_empty()) + .map(|s| { + let (table, count) = s.split_once(':').expect("expected table_id:region_count"); + ( + table.trim().parse().expect("invalid table id"), + count + .trim() + .parse::() + .expect("invalid region count") + .get(), + ) + }) + .collect() +}); + +fn region_count(id: RegionId) -> u32 { + REGION_COUNTS + .get(&id.table_id()) + .copied() + .unwrap_or(*REGIONS) +} +const DAY: i64 = 86400; +static TABLES: LazyLock> = LazyLock::new(|| { + std::env::var("TESTBED_SHARED_TABLE_ID") + .ok() + .map(|s| { + s.split(',') + .map(|id| id.trim().parse().expect("invalid TESTBED_SHARED_TABLE_ID")) + .collect() + }) + .unwrap_or_default() +}); +static BATCHES: LazyLock = LazyLock::new(|| { + std::env::var("TESTBED_SHARED_TABLE_BATCHES") + .unwrap_or_else(|_| "1".into()) + .parse() + .expect("TESTBED_SHARED_TABLE_BATCHES must be a positive integer") +}); + +pub(crate) fn batch_limit() -> usize { + BATCHES.get() +} + +// Single-batch rounds keep the original object layout for replay. +fn batch_root(root: &str, files: usize, index: usize) -> String { + if files == *WIDTH { + root.into() + } else { + format!("{root}/batch-{index}") + } +} + +static CURSORS: LazyLock>> = LazyLock::new(Default::default); +pub(crate) fn enabled(id: RegionId) -> bool { + uses_shared_compaction(id, &TABLES, region_count(id)) +} + +// A single target has no duplicated scan to share. Keep its picker, merge and +// file lifecycle on the ordinary path, including unpartitioned metric tables. +fn uses_shared_compaction(id: RegionId, tables: &[u32], regions: u32) -> bool { + regions > 1 && id.region_number() < regions && tables.contains(&id.table_id()) +} + +/// Only mixed bulk L0s belong to the shared scan. Routed L1s keep the regular picker. +pub(crate) fn is_shared(file: &FileMeta) -> bool { + file.level == 0 && file.region_id.region_number() == 0 && file.partition_expr.is_none() +} + +pub(crate) fn shared_inputs<'a>(files: impl Iterator) -> bool { + let mut found = false; + for file in files { + if !is_shared(file) { + return false; + } + found = true; + } + found +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_region_uses_ordinary_compaction() { + assert!(!uses_shared_compaction(RegionId::new(42, 0), &[42], 1)); + assert!(!uses_shared_compaction(RegionId::new(42, 1), &[42], 1)); + assert!(!uses_shared_compaction(RegionId::new(42, 0), &[42], 0)); + } + + #[test] + fn shared_compaction_only_matches_selected_data_regions() { + for n in 0..12 { + assert!(uses_shared_compaction(RegionId::new(42, n), &[42], 12)); + } + assert!(!uses_shared_compaction(RegionId::new(42, 12), &[42], 12)); + assert!(!uses_shared_compaction( + RegionId::new(42, 1 << 24), + &[42], + 12 + )); + assert!(!uses_shared_compaction(RegionId::new(43, 0), &[42], 12)); + assert!(!uses_shared_compaction(RegionId::new(42, 0), &[], 12)); + } + + #[test] + fn routed_l1_never_reenters_the_shared_scan() { + use crate::compaction::test_util::new_file_handle; + let input = new_file_handle(FileId::random(), 0, 100, 0); + let mut l0 = input.meta_ref().clone(); + l0.region_id = RegionId::new(42, 0); + l0.partition_expr = None; + assert!(shared_inputs([&l0].into_iter())); + let mut l1 = l0.clone(); + l1.level = 1; + assert!(!shared_inputs([&l1].into_iter())); + assert!(!shared_inputs([&l0, &l1].into_iter())); + assert!(!shared_inputs(std::iter::empty())); + } + + #[test] + fn l1_picker_view_preserves_live_reservations_without_deleting_l0() { + use crate::compaction::test_util::{new_file_handle, primary_key_metadata_for_test}; + use crate::sst::file_purger::NoopFilePurger; + use crate::sst::version::SstVersion; + let l0 = new_file_handle(FileId::random(), 0, 100, 0) + .meta_ref() + .clone(); + let l1 = new_file_handle(FileId::random(), 0, 100, 1) + .meta_ref() + .clone(); + let mut version = SstVersion::new(primary_key_metadata_for_test()); + version.add_files(Arc::new(NoopFilePurger), [l0, l1].into_iter()); + let live_l0 = version.levels()[0].files().next().unwrap().clone(); + let live_l1 = version.levels()[1].files().next().unwrap().clone(); + let filtered = version.without_shared_l0(); + assert_eq!(0, filtered.levels()[0].files().count()); + let selected = filtered.levels()[1].files().next().unwrap(); + assert!(selected.try_set_compacting()); + assert!(live_l1.compacting()); + assert!(!live_l0.is_deleted()); + selected.set_compacting(false); + assert_eq!(1, version.levels()[0].files().count()); + } +} +fn cursor(id: RegionId) -> u64 { + *CURSORS.lock().unwrap().get(&id).unwrap_or(&0) +} +fn prefix(id: RegionId, round: u64) -> String { + format!("_testbed_table_jobs/{}/{round}", id.table_id()) +} + +async fn read(store: &ObjectStore, key: &str) -> Result> { + match store.read(key).await { + Ok(buf) => serde_json::from_slice(&buf.to_bytes()) + .map(Some) + .context(SerdeJsonSnafu), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(None), + Err(e) => Err(e).context(OpenDalSnafu), + } +} + +async fn create(store: &ObjectStore, key: &str, value: &T) -> Result<()> { + let bytes = serde_json::to_vec(&serde_json::to_value(value).context(SerdeJsonSnafu)?) + .context(SerdeJsonSnafu)?; + match store + .write_with(key, bytes.clone()) + .if_not_exists(true) + .await + { + Ok(_) => Ok(()), + Err(e) => { + // OSS reports FileAlreadyExists as a conflict. Verify the exact payload + // also for an ambiguous response to our own successful first write. + if let Ok(buf) = store.read(key).await + && buf.to_bytes().as_ref() == bytes + { + return Ok(()); + } + Err(e).context(OpenDalSnafu) + } + } +} + +#[derive(Serialize, Deserialize)] +struct Reservation { + metadata: RegionMetadata, + options: RegionOptions, + inputs: Vec, +} + +type Outputs = BTreeMap>; + +/// Only a complete, registered shared batch needs a readiness retry. +/// Routed L1, unsequenced files and an undersized tail do not keep polling. +pub(crate) fn has_pending_shared_batch(ssts: &crate::sst::version::SstVersion) -> bool { + ssts.levels()[0] + .files() + .filter(|f| is_shared(f.meta_ref()) && f.meta_ref().sequence.is_some()) + .take(*WIDTH) + .count() + == *WIDTH +} + +pub(crate) async fn pick(region: &CompactionRegion) -> Result> { + let id = region.region_id; + ensure!( + region.access_layer.path_type() == PathType::Data && id.region_number() < region_count(id), + Invalid { + reason: "expected a fixed physical metric data region" + } + ); + let store = region.access_layer.object_store(); + let handles: HashMap<_, _> = region.current_version.ssts.levels()[0] + .files() + .filter(|f| is_shared(f.meta_ref()) && f.meta_ref().sequence.is_some()) + .map(|f| (f.meta_ref().file_id, f)) + .collect(); + let mut round = cursor(id); + loop { + let root = prefix(id, round); + let key = format!("{root}/sources"); + let ids: Vec = if let Some(ids) = read(store, &key).await? { + ids + } else { + if id.region_number() != 0 || handles.len() < *WIDTH { + return Ok(None); + } + let mut files: Vec<_> = handles.values().map(|f| f.meta_ref()).collect(); + files.sort_by(|a, b| { + (a.sequence, a.file_id.as_bytes()).cmp(&(b.sequence, b.file_id.as_bytes())) + }); + let ids = + batch_window::new_roster(files.iter().map(|f| f.file_id), *WIDTH, batch_limit()); + create(store, &key, &ids).await?; + ids + }; + ensure!( + batch_window::valid_roster(&ids, *WIDTH), + Invalid { + reason: "invalid immutable round roster" + } + ); + let mut pending = Vec::new(); + let mut waiting = false; + for (index, batch) in ids.chunks_exact(*WIDTH).enumerate() { + let job = batch_root(&root, ids.len(), index); + // Record successful local publication before allowing L1 compaction. + // Its output may later be replaced by a remote merge, so checking + // the original L1 IDs on every restart would be incorrect. + let applied_key = format!("{job}/applied-{}", id.region_number()); + if read::(store, &applied_key).await? == Some(true) { + continue; + } + let inputs: Vec<_> = batch + .iter() + .filter_map(|k| handles.get(k).map(|f| (**f).clone())) + .collect(); + if inputs.len() == *WIDTH { + pending.push(CompactionOutput { + output_level: 1, + inputs, + filter_deleted: false, + output_time_range: None, + }); + continue; + } + let Some(result): Option = read(store, &format!("{job}/result")).await? else { + waiting = true; + continue; + }; + let expected = result.get(&id).ok_or_else(|| { + Invalid { + reason: "region missing from table result", + } + .build() + })?; + let live: HashMap<_, _> = region.current_version.ssts.levels()[1] + .files() + .map(|f| (f.meta_ref().file_id, f.meta_ref())) + .collect(); + ensure!( + inputs.is_empty() && expected.iter().all(|f| live.get(&f.file_id) == Some(&f)), + Invalid { + reason: "partial or conflicting region publication" + } + ); + create(store, &applied_key, &true).await?; + } + if !pending.is_empty() { + return Ok(Some(PickerOutput { + outputs: pending, + expired_ssts: vec![], + time_window_size: DAY, + max_file_size: Some(256 << 20), + })); + } + if waiting { + return Ok(None); + } + round += 1; + CURSORS.lock().unwrap().insert(id, round); + // L1 has its own scheduling state and no longer needs a turn here. + } +} + +struct Guard { + store: ObjectStore, + root: String, +} +#[async_trait::async_trait] +impl SstWriteGuard for Guard { + async fn before_create(&self, id: RegionFileId) -> Result<()> { + create( + &self.store, + &format!( + "{}/protected/{}/{}", + self.root, + id.region_id().as_u64(), + id.file_id() + ), + &true, + ) + .await + } +} + +pub(crate) async fn merge( + ctx: &CompactionContext, + unit: &CompactionUnit, + cancel: Arc, +) -> Result { + let id = ctx.region_id; + let round = cursor(id); + let root = prefix(id, round); + let store = ctx.access_layer.object_store(); + let ids: Vec = read(store, &format!("{root}/sources")) + .await? + .ok_or_else(|| { + Invalid { + reason: "missing round sources", + } + .build() + })?; + let by_id: HashMap<_, _> = unit + .inputs + .iter() + .map(|f| (f.meta_ref().file_id, f.meta_ref())) + .collect(); + let (index, batch) = batch_window::batch_for_unit(&ids, *WIDTH, &by_id.keys().collect()) + .ok_or_else(|| { + Invalid { + reason: "unit does not own exactly one complete batch", + } + .build() + })?; + let root = batch_root(&root, ids.len(), index); + let ids = batch; + let wait_start = Instant::now(); + let inputs: Vec<_> = ids.iter().map(|k| by_id[k].clone()).collect(); + let reservation = Reservation { + metadata: (*ctx.region_metadata).clone(), + options: ctx.region_options.clone(), + inputs: inputs.clone(), + }; + create( + store, + &format!("{root}/ready-{}", id.region_number()), + &reservation, + ) + .await?; + let result_key = format!("{root}/result"); + let start = Instant::now(); + let mut ready = BTreeMap::new(); + loop { + if cancel.is_cancelled() { + return crate::error::CompactionCancelledSnafu.fail(); + } + ensure!( + start.elapsed() < Duration::from_secs(900), + Invalid { + reason: "timed out waiting for table result" + } + ); + if let Some(outputs) = read::(store, &result_key).await? { + let files = outputs.get(&id).ok_or_else(|| { + Invalid { + reason: "missing region result", + } + .build() + })?; + ensure!( + files.iter().all(|f| f.region_id == id && f.level == 1), + Invalid { + reason: "misrouted region result" + } + ); + return Ok(MergeOutput { + files_to_add: files.clone(), + files_to_remove: inputs, + compaction_time_window: Some(DAY), + ..Default::default() + }); + } + if id.region_number() == 0 { + for n in 0..region_count(id) { + if !ready.contains_key(&n) + && let Some(r) = + read::(store, &format!("{root}/ready-{n}")).await? + { + ready.insert(n, r); + } + } + if ready.len() == region_count(id) as usize { + let ready_wait = wait_start.elapsed(); + let mut targets = BTreeMap::new(); + let mut expressions = Vec::new(); + for (n, r) in &ready { + ensure!( + r.metadata.region_id == RegionId::new(id.table_id(), *n) + && r.inputs.iter().map(|f| f.file_id).eq(ids.iter().copied()), + Invalid { + reason: "conflicting reservation" + } + ); + let expr = + crate::region::parse_partition_expr(r.metadata.partition_expr.as_deref())? + .ok_or_else(|| { + Invalid { + reason: "missing partition expression", + } + .build() + })?; + expressions.push(expr); + targets.insert( + r.metadata.region_id, + MultiRegionTarget { + metadata: Arc::new(r.metadata.clone()), + options: r.options.clone(), + inputs: r.inputs.iter().map(|f| (f.file_id(), f.clone())).collect(), + }, + ); + } + let mut columns = std::collections::HashSet::new(); + for expression in &expressions { + expression.collect_column_names(&mut columns); + } + ensure!( + columns.len() == 1, + Invalid { + reason: "expected one partition tag" + } + ); + let rule = MultiDimPartitionRule::try_new( + columns.into_iter().collect(), + (0..region_count(id)).collect(), + expressions, + true, + ) + .context(crate::error::RouteMultiRegionSnafu)?; + let plan = MultiRegionCompactionPlan { + partition_rule: Arc::new(rule), + sources: inputs.clone(), + targets, + memory_limit: std::env::var("TESTBED_SHARED_COMPACTION_MEMORY_MIB") + .unwrap_or_else(|_| "8192".into()) + .parse::() + .map_err(|_| { + Invalid { + reason: "invalid shared memory MiB", + } + .build() + })? + .checked_mul(1 << 20) + .ok_or_else(|| { + Invalid { + reason: "shared memory MiB overflow", + } + .build() + })?, + max_active_workers: 2, + spill_limit: 0, + max_output_file_size: 256 << 20, + window_seconds: DAY, + }; + let context = MultiRegionCompactionContext { + access_layer: ctx.access_layer.clone(), + cache: ctx.cache_manager.clone(), + config: ctx.engine_config.clone(), + protection: Arc::new(Guard { + store: store.clone(), + root: root.clone(), + }), + cancellation: cancel.clone(), + spill_directory: Default::default(), + }; + common_telemetry::info!( + "table merge start table={} round={} batch={} memory_limit_bytes={} table_batch_limit={}", + id.table_id(), + round, + index, + plan.memory_limit, + batch_limit() + ); + let execution_start = Instant::now(); + let output = compact_regions(plan, context).await?; + let execution = execution_start.elapsed(); + ensure!( + output.stats.source_files == *WIDTH as u64 + && output.stats.source_rows == output.stats.output_rows, + Invalid { + reason: "table scan accounting mismatch" + } + ); + common_telemetry::info!( + "testbed shared compaction table={} round={} batch={} region_ready_wait_ms={} execution_ms={} stats={:?}", + id.table_id(), + round, + index, + ready_wait.as_millis(), + execution.as_millis(), + output.stats + ); + create(store, &result_key, &output.files).await?; + continue; + } + } + tokio::time::sleep(Duration::from_millis(500)).await; + } +} + +/// Persist the completion marker after the manifest edit, before the worker +/// makes the new L1s selectable. This also leaves the old-layout replay intact. +pub(crate) async fn record_publication(ctx: &CompactionContext, inputs: &[FileMeta]) -> Result<()> { + let root = prefix(ctx.region_id, cursor(ctx.region_id)); + let store = ctx.access_layer.object_store(); + let ids: Vec = read(store, &format!("{root}/sources")) + .await? + .ok_or_else(|| { + Invalid { + reason: "missing shared publication roster", + } + .build() + })?; + let input_ids = inputs.iter().map(|f| &f.file_id).collect(); + let (index, _) = batch_window::batch_for_unit(&ids, *WIDTH, &input_ids).ok_or_else(|| { + Invalid { + reason: "missing shared publication batch", + } + .build() + })?; + let batch = batch_root(&root, ids.len(), index); + create( + store, + &format!("{batch}/applied-{}", ctx.region_id.region_number()), + &true, + ) + .await +} + +#[cfg(test)] +mod readiness_tests { + use super::*; + use crate::compaction::test_util::{new_file_handle, primary_key_metadata_for_test}; + use crate::sst::file_purger::NoopFilePurger; + use crate::sst::version::SstVersion; + + #[test] + fn only_a_full_registered_shared_batch_needs_a_retry() { + let mut ssts = SstVersion::new(primary_key_metadata_for_test()); + assert!(!has_pending_shared_batch(&ssts)); + let mut files = Vec::new(); + for _ in 0..*WIDTH { + let mut file = new_file_handle(FileId::random(), 0, 100, 0) + .meta_ref() + .clone(); + file.region_id = RegionId::new(42, 0); + file.partition_expr = None; + file.sequence = std::num::NonZeroU64::new(1); + files.push(file); + } + let last = files.pop().unwrap(); + ssts.add_files(Arc::new(NoopFilePurger), files.into_iter()); + assert!(!has_pending_shared_batch(&ssts)); + let mut l1 = last.clone(); + l1.file_id = FileId::random(); + l1.level = 1; + let mut unregistered = last.clone(); + unregistered.file_id = FileId::random(); + unregistered.sequence = None; + ssts.add_files(Arc::new(NoopFilePurger), [l1, unregistered].into_iter()); + assert!(!has_pending_shared_batch(&ssts)); + ssts.add_files(Arc::new(NoopFilePurger), [last].into_iter()); + assert!(has_pending_shared_batch(&ssts)); + } +} diff --git a/src/mito2/src/compaction/compactor/experiment/batch_window.rs b/src/mito2/src/compaction/compactor/experiment/batch_window.rs new file mode 100644 index 00000000000..77819993100 --- /dev/null +++ b/src/mito2/src/compaction/compactor/experiment/batch_window.rs @@ -0,0 +1,78 @@ +// 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 immutable source roster per round. Position determines the batch on every DN. +use std::collections::HashSet; +use std::hash::Hash; + +pub(super) fn new_roster( + ordered: impl Iterator, + width: usize, + slots: usize, +) -> Vec { + let mut files: Vec<_> = ordered.take(width.saturating_mul(slots)).collect(); + files.truncate(files.len() / width * width); + files +} + +pub(super) fn valid_roster(files: &[T], width: usize) -> bool { + !files.is_empty() + && files.len().is_multiple_of(width) + && files.iter().collect::>().len() == files.len() +} + +pub(super) fn batch_for_unit<'a, T: Eq + Hash>( + roster: &'a [T], + width: usize, + reserved: &HashSet<&T>, +) -> Option<(usize, &'a [T])> { + if reserved.len() != width || !valid_roster(roster, width) { + return None; + } + roster + .chunks_exact(width) + .enumerate() + .find(|(_, batch)| batch.iter().all(|id| reserved.contains(id))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn disjoint_groups_and_retry_keep_identical_ownership() { + for slots in [1, 8, 16, 24, 48] { + let roster = new_roster(0..2053, 32, slots); + let mut completed = HashSet::new(); + for (index, ids) in roster.chunks_exact(32).enumerate().rev() { + let unit = ids.iter().rev().collect(); + assert_eq!(batch_for_unit(&roster, 32, &unit), Some((index, ids))); + assert!(ids.iter().all(|id| completed.insert(*id))); + assert_eq!(batch_for_unit(&roster, 32, &unit), Some((index, ids))); + } + assert_eq!(completed.len(), slots * 32); + let next = new_roster((0..2053).filter(|id| !completed.contains(id)), 32, slots); + assert!(next.iter().all(|id| !completed.contains(id))); + } + } + + #[test] + fn reject_partial_mixed_and_duplicate_reservations() { + let roster = new_roster(0..9, 4, 16); + assert_eq!(roster, (0..8).collect::>()); + assert!(new_roster(0..3, 4, 16).is_empty()); + for invalid in [&roster[1..5], &roster[..3]] { + assert!(batch_for_unit(&roster, 4, &invalid.iter().collect()).is_none()); + } + let duplicate = [0, 1, 2, 3, 3, 5, 6, 7]; + assert!(batch_for_unit(&duplicate, 4, &roster[..4].iter().collect()).is_none()); + } +} diff --git a/src/mito2/src/compaction/compactor/experiment/parallelism.rs b/src/mito2/src/compaction/compactor/experiment/parallelism.rs new file mode 100644 index 00000000000..c9c66ed44bc --- /dev/null +++ b/src/mito2/src/compaction/compactor/experiment/parallelism.rs @@ -0,0 +1,75 @@ +// 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. + +//! Experimental concurrency knobs; unset values retain automatic parallelism 1. +use std::num::NonZeroUsize; +use std::sync::LazyLock; +use store_api::storage::RegionId; + +fn configured(name: &str, fallback: usize) -> usize { + match std::env::var(name) { + Ok(value) => value + .parse::() + .expect("compaction parallelism must be positive") + .get(), + Err(_) => fallback, + } +} + +static AUTOMATIC: LazyLock = + LazyLock::new(|| configured("TESTBED_AUTO_COMPACTION_PARALLELISM", 1)); +static SHARED: LazyLock = + LazyLock::new(|| configured("TESTBED_SHARED_SCAN_PARALLELISM", *AUTOMATIC)); + +pub(crate) fn automatic_parallelism() -> usize { + *AUTOMATIC +} + +pub(crate) fn merge_parallelism(region: RegionId, shared: bool, ordinary: usize) -> usize { + select(region.region_number(), shared, ordinary, *SHARED) +} + +fn select(_number: u32, shared: bool, ordinary: usize, scanner: usize) -> usize { + // Every participant holds an execution slot from ready to publication. + // Followers must admit the same number of batches as the scanning Region. + if shared { scanner } else { ordinary } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn all_shared_participants_get_scanner_parallelism() { + for number in 0..12 { + assert_eq!(16, select(number, true, 8, 16)); + assert_eq!(24, select(number, true, 8, 24)); + } + } + + #[test] + fn ordinary_l1_keeps_its_own_limit_on_every_region() { + for number in 0..12 { + assert_eq!(8, select(number, false, 8, 16)); + assert_eq!(8, select(number, false, 8, 24)); + assert_eq!(4, select(number, false, 4, 32)); + } + } + + #[test] + fn defaults_keep_previous_execution_width() { + for shared in [false, true] { + for number in 0..12 { + assert_eq!(1, select(number, shared, 1, 1)); + } + } + } +} diff --git a/src/mito2/src/compaction/multi_region.rs b/src/mito2/src/compaction/multi_region.rs new file mode 100644 index 00000000000..344152eaa85 --- /dev/null +++ b/src/mito2/src/compaction/multi_region.rs @@ -0,0 +1,198 @@ +// 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 persisted levels, publish manifests, or fold row +//! versions. Output protection and eventual publication belong to its caller. + +mod source; +mod spill; +mod streaming; +#[cfg(test)] +mod tests; +mod worker; +mod writer; + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::AtomicU64; + +use common_base::cancellation::{CancellableFuture, CancellationHandle}; +use partition::PartitionRuleRef; +use snafu::{OptionExt, ensure}; +use store_api::metadata::RegionMetadataRef; +use store_api::storage::RegionId; + +use crate::access_layer::AccessLayerRef; +use crate::cache::CacheManagerRef; +use crate::config::MitoConfig; +use crate::error::{InvalidMultiRegionCompactionSnafu, Result}; +use crate::region::options::RegionOptions; +use crate::sst::file::{FileMeta, RegionFileId}; +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 in stable tie-breaking order. The caller retains their GC protection. + pub sources: Vec, + /// Metadata and routing must belong to the same physical-table snapshot. + pub targets: BTreeMap, + /// Shared byte budget for queued/cached runs and working batches, not a process RSS cap. + /// Reader page decoding and SST/index writer memory also depend on the supplied MitoConfig. + pub memory_limit: usize, + /// One or two simultaneous run operations or SST writers. The upper bound limits + /// uncharged working batches; idle region workers hold no slot. + pub max_active_workers: usize, + pub spill_limit: u64, + pub max_output_file_size: usize, + pub window_seconds: i64, +} + +/// Shared storage services and attempt-owned output/spill resources. +pub struct MultiRegionCompactionContext { + pub access_layer: AccessLayerRef, + pub cache: CacheManagerRef, + pub config: Arc, + pub spill_directory: PathBuf, + pub protection: Arc, + pub cancellation: Arc, +} + +/// 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, + pub spilled_bytes: u64, + /// Peak bytes reserved by queued and cached Arrow batches, including batch metadata. + pub peak_buffered_bytes: u64, + /// Critical-path wall time for reading, merging and routing, including scheduling. + pub merge_route_us: u64, + /// Producer blocked by a full destination writer channel. + pub write_wait_us: u64, + /// Time from closing writer channels until all final writes finish. + pub write_drain_us: u64, +} + +/// Complete per-target outputs, including explicit empty partitions. +pub struct MultiRegionCompactionOutput { + 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. +pub async fn compact_regions( + plan: MultiRegionCompactionPlan, + context: MultiRegionCompactionContext, +) -> Result { + let metadata = validate_plan(&plan)?; + if context.cancellation.is_cancelled() { + return crate::error::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?; + if plan.spill_limit == 0 { + streaming::execute(plan, context, source, counters).await + } else { + worker::execute(plan, context, source, counters).await + } + }; + CancellableFuture::new(execution, cancellation) + .await + .map_err(|_| crate::error::CompactionCancelledSnafu.build())? +} + +fn validate_plan(plan: &MultiRegionCompactionPlan) -> Result { + ensure!( + !plan.sources.is_empty() + && plan.memory_limit >= 1024 * 1024 + && plan.max_active_workers > 0 + && plan.max_active_workers <= 2 + && plan.max_output_file_size > 0 + && plan.window_seconds > 0, + InvalidMultiRegionCompactionSnafu { + reason: "Invalid sources or execution budgets" + } + ); + let first = plan + .targets + .values() + .next() + .context(InvalidMultiRegionCompactionSnafu { + reason: "No routing targets", + })?; + let mut sources = HashSet::new(); + for file in &plan.sources { + 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 { + 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/source.rs b/src/mito2/src/compaction/multi_region/source.rs new file mode 100644 index 00000000000..571a9f3c7f4 --- /dev/null +++ b/src/mito2/src/compaction/multi_region/source.rs @@ -0,0 +1,493 @@ +// 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; +use std::fmt; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY; +use common_time::{Timestamp, timestamp::TimeUnit}; +use datatypes::arrow::array::{Array, UInt64Array}; +use datatypes::arrow::compute::take_record_batch; +use datatypes::arrow::datatypes::SchemaRef; +use datatypes::arrow::record_batch::RecordBatch; +use parquet::file::metadata::PageIndexPolicy; +use partition::PartitionRuleRef; +use snafu::{OptionExt, ResultExt, ensure}; +use store_api::codec::PrimaryKeyEncoding; +use store_api::metadata::RegionMetadataRef; +use store_api::storage::RegionId; + +use crate::access_layer::AccessLayerRef; +use crate::cache::CacheStrategy; +use crate::compaction::json2::collect_json2_rewrite_plans_from_parquet; +use crate::compaction::multi_region::{ + MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, SourceCounters, +}; +use crate::error::{ + ComputeArrowSnafu, InvalidMultiRegionCompactionSnafu, MultiRegionCompactionResourceSnafu, + NewRecordBatchSnafu, Result, +}; +use crate::read::compat::FlatCompatBatch; +use crate::read::flat_projection::FlatProjectionMapper; +use crate::read::read_columns::ReadColumns; +use crate::read::timestamp_array_to_i64_slice; +use crate::sst::file::{FileHandle, FileMeta}; +use crate::sst::file_purger::NoopFilePurger; +use crate::sst::parquet::flat_format::{sequence_column_index, time_index_column_index}; +use crate::sst::parquet::format::need_override_sequence; +use crate::sst::parquet::reader::{MetadataCacheMetrics, ParquetReader, ReaderMetrics}; +use crate::sst::parquet::{Json2RewriteTargets, Json2TargetLayout}; + +struct SourceBatch { + batch: RecordBatch, + source: FileMeta, + legacy_override: bool, +} + +/// Retains only the input batch and row destinations, never future output arrays. +/// Row indices break destination ties so each fragment preserves source order. +struct RoutedBatch { + input: SourceBatch, + rows: Vec<(RegionId, i64, usize)>, + offset: usize, +} + +impl RoutedBatch { + /// Materializes one fragment on the blocking pool, only when dispatch pulls it. + fn next_fragment(&mut self, router: &SharedSource) -> Result> { + router.check_cancelled()?; + let Some(&(region_id, window, _)) = self.rows.get(self.offset) else { + return Ok(None); + }; + let remaining = &self.rows[self.offset..]; + let len = remaining + .partition_point(|(id, time_window, _)| (*id, *time_window) == (region_id, window)); + let indices = + UInt64Array::from_iter_values(remaining[..len].iter().map(|(_, _, row)| *row as u64)); + let batch = router.target_batch(&self.input, region_id, &indices)?; + self.offset += len; + Ok(Some(SourceEvent::Batch { + region_id, + window, + batch, + })) + } +} + +/// Source boundaries are ordered after all routed fragments of that source. +pub(crate) enum SourceEvent { + Batch { + region_id: RegionId, + window: i64, + batch: RecordBatch, + }, + SourceEnd, +} + +pub(crate) struct SharedSource { + layer: AccessLayerRef, + cache: CacheStrategy, + sources: Vec, + targets: BTreeMap, + metadata: RegionMetadataRef, + mapper: FlatProjectionMapper, + json2_targets: Json2RewriteTargets, + schema: SchemaRef, + partition_rule: PartitionRuleRef, + window_seconds: i64, + batch_memory_limit: usize, + cancellation: Arc, + counters: Arc, +} + +impl fmt::Debug for SharedSource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SharedTableSource") + .field("source_files", &self.sources.len()) + .finish() + } +} + +impl SharedSource { + pub(crate) async fn build( + plan: &MultiRegionCompactionPlan, + context: &MultiRegionCompactionContext, + metadata: RegionMetadataRef, + counters: Arc, + ) -> Result> { + 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()); + for file in &plan.sources { + if context.cancellation.is_cancelled() { + return crate::error::CompactionCancelledSnafu.fail(); + } + 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?; + footers.push(sst.parquet_metadata()); + } + let layouts = collect_json2_rewrite_plans_from_parquet(&metadata, &footers)?; + let mut json2 = BTreeMap::new(); + for (name, layout) in layouts { + let column = + metadata + .column_by_name(&name) + .context(InvalidMultiRegionCompactionSnafu { + reason: "JSON2 layout names an unknown column", + })?; + let extension_metadata = column + .column_schema + .metadata() + .get(EXTENSION_TYPE_METADATA_KEY) + .cloned() + .context(InvalidMultiRegionCompactionSnafu { + reason: "JSON2 extension metadata missing", + })?; + json2.insert( + column.column_id, + Json2TargetLayout { + extension_metadata, + target_layout: layout.target_layout, + }, + ); + } + let json2_targets = Arc::new(json2); + // Sparse SSTs retain every tag in __primary_key. Materialize only the + // routing tags; expanding all physical-table tags makes merge/take + // proportional to schema width, then the writer discards them again. + let projection: Vec<_> = metadata + .column_metadatas + .iter() + .enumerate() + .filter(|(_, column)| { + metadata.primary_key_encoding != PrimaryKeyEncoding::Sparse + || column.semantic_type != api::v1::SemanticType::Tag + || plan + .partition_rule + .partition_columns() + .contains(&column.column_schema.name) + }) + .map(|(index, _)| index) + .collect(); + let read_columns = ReadColumns::new( + projection + .iter() + .map(|index| metadata.column_metadatas[*index].column_id), + ); + let mapper = FlatProjectionMapper::new_with_json2_rewrite_targets( + &metadata, + projection, + read_columns, + &json2_targets, + )?; + let schema = mapper.input_arrow_schema(false); + Ok(Arc::new(Self { + layer: context.access_layer.clone(), + cache, + sources: plan.sources.clone(), + targets: plan.targets.clone(), + metadata, + mapper, + json2_targets, + schema, + partition_rule: plan.partition_rule.clone(), + window_seconds: plan.window_seconds, + batch_memory_limit: plan.memory_limit / 8, + cancellation: context.cancellation.clone(), + counters, + })) + } + + pub(crate) fn schema(&self) -> SchemaRef { + self.schema.clone() + } + + fn raw_batches( + self: Arc, + file: FileMeta, + ) -> futures::stream::BoxStream<'static, Result> { + Box::pin(async_stream::try_stream! { + self.check_cancelled()?; + // Preserve physical source sequences. Target-domain overrides are applied only after routing. + 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 builder = self.layer.read_sst(handle).cache(self.cache.clone()).batch_size(1024) + .projection(Some(self.mapper.read_columns().clone())) + .expected_metadata(Some(self.metadata.clone())).json2_rewrite_targets(self.json2_targets.clone()) + .compaction(false).page_index_policy(PageIndexPolicy::Skip); + let Some((context, selection)) = builder.build_reader_input(&mut ReaderMetrics::default()).await? else { + self.counters.files.fetch_add(1, Ordering::Relaxed); + return; + }; + let compat = FlatCompatBatch::try_new(&self.mapper, context.read_format(), false)?; + let mut reader = ParquetReader::new(Arc::new(context), selection).await?; + let expected_rows = u64::try_from(reader.parquet_metadata().file_metadata().num_rows()) + .map_err(|_| InvalidMultiRegionCompactionSnafu { reason: "Negative source footer row count" }.build())?; + let mut read_rows = 0_u64; + let legacy_override = need_override_sequence(&reader.parquet_metadata()); + while let Some(batch) = reader.next_record_batch().await? { + self.check_cancelled()?; + let batch = if let Some(compat) = &compat { compat.compat(batch)? } else { batch }; + if batch.get_array_memory_size() > self.batch_memory_limit { + Err(MultiRegionCompactionResourceSnafu { reason: "Decoded source batch exceeds the shared reader budget" }.build())?; + } + self.counters.rows.fetch_add(batch.num_rows() as u64, Ordering::Relaxed); + read_rows += batch.num_rows() as u64; + yield SourceBatch { batch, source: file.clone(), legacy_override }; + } + if read_rows != expected_rows { + Err(InvalidMultiRegionCompactionSnafu { reason: "Shared source scan did not cover its complete footer row count" }.build())?; + } + let page_bytes = reader.fetched_store_page_bytes()?; + self.counters.store_page_bytes.fetch_add(page_bytes, Ordering::Relaxed); + self.counters.files.fetch_add(1, Ordering::Relaxed); + }) + } + pub(crate) fn batches( + self: Arc, + ) -> futures::stream::BoxStream<'static, Result> { + Box::pin(async_stream::try_stream! { + for file in &self.sources { + let mut input = self.clone().raw_batches(file.clone()); + while let Some(batch) = futures::TryStreamExt::try_next(&mut input).await? { + let router=self.clone(); + let mut routed=common_runtime::spawn_blocking_compact(move || router.route(batch)).await.context(crate::error::JoinSnafu)??; + loop { + let router = self.clone(); + let (event, remaining) = common_runtime::spawn_blocking_compact(move || { + let event = routed.next_fragment(&router)?; + Ok::<_, crate::error::Error>((event, routed)) + }).await.context(crate::error::JoinSnafu)??; + routed = remaining; + let Some(event) = event else { break; }; + // Dispatch reserves/spills and sends this fragment before + // polling again. No work slot is held across the yield. + yield event; + } + } + yield SourceEvent::SourceEnd; + } + }) + } + + /// A sorted source with target-domain sequences applied before the shared merge. + /// This mode only accepts key-based partitioning: equal PKs in one source have + /// the same target and substitution therefore preserves source ordering. + pub(crate) fn ordered_input( + self: Arc, + file: FileMeta, + ) -> crate::read::BoxedRecordBatchStream { + Box::pin(async_stream::try_stream! { + let mut raw=self.clone().raw_batches(file); + while let Some(input)=futures::TryStreamExt::try_next(&mut raw).await? { + let idx=sequence_column_index(input.batch.num_columns()); + let sequences=input.batch.column(idx).as_any().downcast_ref::().context(InvalidMultiRegionCompactionSnafu{reason:"Expected non-null UInt64 sequence column"})?; + let mut replacements=Vec::with_capacity(input.batch.num_rows()); + for (row,owner) in self.row_owners(&input.batch)?.into_iter().enumerate() { + let f=&self.targets[&owner].inputs[&input.source.file_id()]; + let value=if owner!=f.region_id || (!f.preserve_row_sequence && input.legacy_override) { f.sequence } else { None }; + replacements.push(value.map_or_else(||sequences.value(row),|v|v.get())); + } + let mut cols=input.batch.columns().to_vec(); + cols[idx]=Arc::new(UInt64Array::from(replacements)); + yield RecordBatch::try_new(self.schema.clone(),cols).context(NewRecordBatchSnafu)?; + } + }) + } + fn route(&self, input: SourceBatch) -> Result { + self.check_cancelled()?; + let owners = self.row_owners(&input.batch)?; + let windows = self.time_windows(&input.batch)?; + let mut rows: Vec<_> = owners + .into_iter() + .zip(windows) + .enumerate() + .map(|(row, (region_id, window))| (region_id, window, row)) + .collect(); + rows.sort_unstable(); + Ok(RoutedBatch { + input, + rows, + offset: 0, + }) + } + + fn target_batch( + &self, + source: &SourceBatch, + region_id: RegionId, + indices: &UInt64Array, + ) -> Result { + let target = self + .targets + .get(®ion_id) + .context(InvalidMultiRegionCompactionSnafu { + reason: "Routed fragment names an unknown region", + })?; + let input = target.inputs.get(&source.source.file_id()).context( + InvalidMultiRegionCompactionSnafu { + reason: "Target has no effective metadata for the selected source", + }, + )?; + let filtered = take_record_batch(&source.batch, indices).context(ComputeArrowSnafu)?; + let override_sequence = if input.region_id != region_id + || (!input.preserve_row_sequence && source.legacy_override) + { + input.sequence + } else { + None + }; + let mut columns = filtered.columns().to_vec(); + if let Some(sequence) = override_sequence { + columns[sequence_column_index(filtered.num_columns())] = + Arc::new(UInt64Array::from_value(sequence.get(), filtered.num_rows())); + } + RecordBatch::try_new(self.schema.clone(), columns).context(NewRecordBatchSnafu) + } + + pub(super) fn time_windows(&self, filtered: &RecordBatch) -> Result> { + let time_index = filtered.column(time_index_column_index(filtered.num_columns())); + ensure!( + time_index.null_count() == 0, + InvalidMultiRegionCompactionSnafu { + reason: "Null timestamp in shared source" + } + ); + let unit = self + .metadata + .time_index_column() + .column_schema + .data_type + .as_timestamp() + .context(InvalidMultiRegionCompactionSnafu { + reason: "Time index is not a timestamp", + })? + .unit(); + timestamp_array_to_i64_slice(time_index) + .iter() + .map(|value| { + Timestamp::new(*value, unit) + .convert_to(TimeUnit::Second) + .map(|value| value.value().div_euclid(self.window_seconds)) + .context(InvalidMultiRegionCompactionSnafu { + reason: "Timestamp window overflow", + }) + }) + .collect::>>() + } + + pub(super) fn row_owners(&self, batch: &RecordBatch) -> Result> { + 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(()); + } + // Nullable vector predicates can leave unknown masks. Resolve only those + // rows through the same rule's scalar API, including its default region. + 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<()> { + if self.cancellation.is_cancelled() { + return crate::error::CompactionCancelledSnafu.fail(); + } + Ok(()) + } +} diff --git a/src/mito2/src/compaction/multi_region/spill.rs b/src/mito2/src/compaction/multi_region/spill.rs new file mode 100644 index 00000000000..6a7c33024e7 --- /dev/null +++ b/src/mito2/src/compaction/multi_region/spill.rs @@ -0,0 +1,455 @@ +// 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. + +//! Attempt-local ordered runs. All encoding, iteration and file I/O methods are +//! synchronous and must be called on the blocking compaction pool. Drop only +//! schedules cleanup, so cancelling an async owner never performs file I/O inline. + +use std::collections::{HashSet, VecDeque}; +use std::fs::{File, OpenOptions}; +use std::io::{Cursor, Read, Write}; +use std::path::PathBuf; +use std::ptr::NonNull; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use common_base::cancellation::CancellationHandle; +use common_telemetry::warn; +use datatypes::arrow::array::ArrayData; +use datatypes::arrow::ipc::reader::StreamReader; +use datatypes::arrow::ipc::writer::StreamWriter; +use datatypes::arrow::record_batch::RecordBatch; +use snafu::{OptionExt, ResultExt, ensure}; +use tokio_util::sync::CancellationToken; + +use crate::compaction::multi_region::{MultiRegionCompactionContext, MultiRegionCompactionPlan}; +use crate::error::{ + ComputeArrowSnafu, MultiRegionCompactionResourceSnafu, MultiRegionCompactionSpillSnafu, Result, +}; +use crate::memtable::BoxedRecordBatchIterator; + +pub(crate) struct RunStore { + memory: Arc, + metadata: Arc, + disk: Arc, + directory: Arc, + cancellation: Arc, + stop: CancellationToken, + batch_limit: usize, +} + +impl RunStore { + pub(crate) async fn new( + plan: &MultiRegionCompactionPlan, + context: &MultiRegionCompactionContext, + stop: CancellationToken, + ) -> Result> { + let path = context + .spill_directory + .join(uuid::Uuid::new_v4().to_string()); + // Install the guard before awaiting creation: cancellation must not leak a directory. + let directory = Arc::new(SpillDirectory(path)); + let creating = directory.clone(); + common_runtime::spawn_blocking_compact(move || { + std::fs::create_dir_all(&creating.0).context(MultiRegionCompactionSpillSnafu) + }) + .await + .context(crate::error::JoinSnafu)??; + Ok(Arc::new(Self { + memory: Budget::new( + (plan.memory_limit / 2) as u64, + "Routed batch cache exhausted", + ), + metadata: Budget::new( + (plan.memory_limit / 8) as u64, + "Too many regions or time windows", + ), + disk: Budget::new( + plan.spill_limit, + "Multi-region temporary disk quota exhausted", + ), + directory, + cancellation: context.cancellation.clone(), + stop, + batch_limit: plan.memory_limit / 8, + })) + } + + pub(crate) fn reserve_metadata(&self, bytes: usize) -> Result { + self.metadata + .reserve(bytes as u64) + .context(MultiRegionCompactionResourceSnafu { + reason: self.metadata.reason, + }) + } + + pub(crate) fn check_cancelled(&self) -> Result<()> { + ensure!( + !self.stop.is_cancelled() && !self.cancellation.is_cancelled(), + crate::error::CompactionCancelledSnafu + ); + Ok(()) + } + + pub(crate) fn spilled_bytes(&self) -> u64 { + self.disk.total.load(Ordering::Relaxed) + } + + pub(crate) fn peak_buffered_bytes(&self) -> u64 { + self.memory.peak.load(Ordering::Relaxed) + } +} + +struct Budget { + limit: u64, + used: AtomicU64, + peak: AtomicU64, + total: AtomicU64, + reason: &'static str, +} + +impl Budget { + fn new(limit: u64, reason: &'static str) -> Arc { + Arc::new(Self { + limit, + used: AtomicU64::new(0), + peak: AtomicU64::new(0), + total: AtomicU64::new(0), + reason, + }) + } + + fn reserve(self: &Arc, bytes: u64) -> Option { + let previous = self + .used + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |used| { + used.checked_add(bytes).filter(|next| *next <= self.limit) + }) + .ok()?; + self.peak.fetch_max(previous + bytes, Ordering::Relaxed); + self.total.fetch_add(bytes, Ordering::Relaxed); + Some(Reservation { + budget: self.clone(), + bytes, + }) + } +} + +pub(crate) struct Reservation { + budget: Arc, + bytes: u64, +} + +impl Reservation { + fn grow(&mut self, bytes: u64) -> Result<()> { + let mut extra = self + .budget + .reserve(bytes) + .context(MultiRegionCompactionResourceSnafu { + reason: self.budget.reason, + })?; + self.bytes += extra.bytes; + extra.bytes = 0; + Ok(()) + } +} + +impl Drop for Reservation { + fn drop(&mut self) { + self.budget.used.fetch_sub(self.bytes, Ordering::Relaxed); + } +} + +struct SpillDirectory(PathBuf); + +impl Drop for SpillDirectory { + fn drop(&mut self) { + let path = self.0.clone(); + common_runtime::spawn_blocking_compact(move || { + if let Err(error) = std::fs::remove_dir_all(&path) + && error.kind() != std::io::ErrorKind::NotFound + { + warn!(error; "Failed to remove multi-region spill directory: {}", path.display()); + } + }); + } +} + +pub(crate) struct BufferedBatch { + batch: RecordBatch, + _reservation: Reservation, +} + +/// A single sorted stream, not an arbitrary concatenation of different sources. +pub(crate) enum Run { + Memory(VecDeque), + Disk(DiskRun), +} + +impl Default for Run { + fn default() -> Self { + Self::Memory(VecDeque::new()) + } +} + +impl Run { + pub(crate) fn from_batch(batch: RecordBatch, store: &RunStore) -> Result { + let mut run = Self::default(); + run.push(batch, store)?; + Ok(run) + } + + pub(crate) fn is_empty(&self) -> bool { + matches!(self, Self::Memory(batches) if batches.is_empty()) + } + + pub(crate) fn push(&mut self, batch: RecordBatch, store: &RunStore) -> Result<()> { + store.check_cancelled()?; + if batch.num_rows() == 0 { + return Ok(()); + } + let bytes = batch_memory_size(&batch); + ensure!( + bytes <= store.batch_limit, + MultiRegionCompactionResourceSnafu { + reason: format!( + "Run batch of {} rows uses {bytes} bytes, exceeding working-batch budget {}", + batch.num_rows(), + store.batch_limit + ), + } + ); + if let Self::Memory(batches) = self { + // Account for both Arrow storage and per-batch queue/lease metadata. + if let Some(reservation) = store.memory.reserve((bytes + 128) as u64) { + batches.push_back(BufferedBatch { + batch, + _reservation: reservation, + }); + return Ok(()); + } + let mut disk = DiskRun::new(store); + while let Some(buffered) = batches.pop_front() { + disk.append(&buffered.batch, store)?; + } + *self = Self::Disk(disk); + } + if let Self::Disk(disk) = self { + disk.append(&batch, store)?; + } + Ok(()) + } + + /// Appends fragments from the same source, in source order. + pub(crate) fn append(&mut self, other: Self, store: &RunStore) -> Result<()> { + if self.is_empty() { + *self = other; + return Ok(()); + } + for batch in other.into_iter()? { + self.push(batch?, store)?; + } + Ok(()) + } + + pub(crate) fn into_iter(self) -> Result { + match self { + Self::Memory(batches) => Ok(Box::new( + batches.into_iter().map(|buffered| Ok(buffered.batch)), + )), + Self::Disk(run) => { + let file = File::open(&run.path).context(MultiRegionCompactionSpillSnafu)?; + let remaining = run.reservation.as_ref().map_or(0, |lease| lease.bytes); + Ok(Box::new(DiskIterator { + file: Some(file), + run, + remaining, + })) + } + } + } +} + +/// IPC readers can share one allocation across several column buffers. Arrow's +/// per-array estimate charges that entire allocation for every slice, rejecting +/// valid batches after spilling. Deduplicate allocations within this batch, but +/// retain Arrow's metadata cost and conservatively charge shared batches separately. +fn batch_memory_size(batch: &RecordBatch) -> usize { + let mut seen = HashSet::new(); + let duplicated: usize = batch + .columns() + .iter() + .map(|array| duplicated_buffer_bytes(&array.to_data(), &mut seen)) + .sum(); + batch.get_array_memory_size() - duplicated +} + +fn duplicated_buffer_bytes(data: &ArrayData, seen: &mut HashSet>) -> usize { + let duplicated: usize = data + .buffers() + .iter() + .chain(data.nulls().map(|nulls| nulls.buffer())) + .filter(|buffer| !seen.insert(buffer.data_ptr())) + .map(|buffer| buffer.capacity()) + .sum(); + duplicated + + data + .child_data() + .iter() + .map(|child| duplicated_buffer_bytes(child, seen)) + .sum::() +} + +pub(crate) struct DiskRun { + path: PathBuf, + reservation: Option, + max_frame_size: usize, + directory: Arc, +} + +impl DiskRun { + fn new(store: &RunStore) -> Self { + Self { + path: store.directory.0.join(uuid::Uuid::new_v4().to_string()), + reservation: Some(Reservation { + budget: store.disk.clone(), + bytes: 0, + }), + max_frame_size: store.batch_limit * 2, + directory: store.directory.clone(), + } + } + + /// Frames standalone Arrow IPC streams so appending doesn't retain one open + /// descriptor or one batch-offset entry for every source/window combination. + fn append(&mut self, batch: &RecordBatch, store: &RunStore) -> Result<()> { + store.check_cancelled()?; + let mut bytes = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut bytes, batch.schema().as_ref()) + .context(ComputeArrowSnafu)?; + writer.write(batch).context(ComputeArrowSnafu)?; + writer.finish().context(ComputeArrowSnafu)?; + } + ensure!( + bytes.len() <= store.batch_limit * 2, + MultiRegionCompactionResourceSnafu { + reason: "Encoded run batch exceeds the compaction working-batch budget", + } + ); + self.reservation + .as_mut() + .context(MultiRegionCompactionResourceSnafu { + reason: "Cannot append to a released spill run", + })? + .grow(bytes.len() as u64 + 8)?; + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(&self.path) + .context(MultiRegionCompactionSpillSnafu)?; + file.write_all(&(bytes.len() as u64).to_le_bytes()) + .context(MultiRegionCompactionSpillSnafu)?; + file.write_all(&bytes) + .context(MultiRegionCompactionSpillSnafu)?; + Ok(()) + } + + fn remove(&mut self) -> Result<()> { + std::fs::remove_file(&self.path).context(MultiRegionCompactionSpillSnafu)?; + self.reservation.take(); + Ok(()) + } +} + +impl Drop for DiskRun { + fn drop(&mut self) { + let Some(reservation) = self.reservation.take() else { + return; + }; + let path = self.path.clone(); + let directory = self.directory.clone(); + // Keep disk quota and the directory alive until deletion has completed. + common_runtime::spawn_blocking_compact(move || { + if let Err(error) = std::fs::remove_file(&path) + && error.kind() != std::io::ErrorKind::NotFound + { + warn!(error; "Failed to remove multi-region spill run: {}", path.display()); + } + drop(reservation); + drop(directory); + }); + } +} + +struct DiskIterator { + file: Option, + run: DiskRun, + remaining: u64, +} + +impl DiskIterator { + fn next_batch(&mut self) -> Result> { + if self.remaining == 0 { + // Close before unlinking, including on Windows. + if self.file.take().is_some() { + self.run.remove()?; + } + return Ok(None); + } + let file = self + .file + .as_mut() + .context(MultiRegionCompactionResourceSnafu { + reason: "Spill run closed before EOF", + })?; + let mut length = [0; 8]; + file.read_exact(&mut length) + .context(MultiRegionCompactionSpillSnafu)?; + let length = u64::from_le_bytes(length); + ensure!( + self.remaining >= 8 + && length <= self.remaining - 8 + && length <= self.run.max_frame_size as u64, + MultiRegionCompactionResourceSnafu { + reason: "Invalid spill frame length", + } + ); + let length = usize::try_from(length).map_err(|_| { + MultiRegionCompactionResourceSnafu { + reason: "Spill frame length overflow", + } + .build() + })?; + let mut bytes = vec![0; length]; + file.read_exact(&mut bytes) + .context(MultiRegionCompactionSpillSnafu)?; + self.remaining -= length as u64 + 8; + let mut reader = + StreamReader::try_new(Cursor::new(bytes), None).context(ComputeArrowSnafu)?; + let batch = reader + .next() + .transpose() + .context(ComputeArrowSnafu)? + .context(MultiRegionCompactionResourceSnafu { + reason: "Empty spill frame", + })?; + Ok(Some(batch)) + } +} + +impl Iterator for DiskIterator { + type Item = Result; + + fn next(&mut self) -> Option { + self.next_batch().transpose() + } +} diff --git a/src/mito2/src/compaction/multi_region/streaming.rs b/src/mito2/src/compaction/multi_region/streaming.rs new file mode 100644 index 00000000000..e4d4999cbe0 --- /dev/null +++ b/src/mito2/src/compaction/multi_region/streaming.rs @@ -0,0 +1,175 @@ +// 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. + +//! Experimental key-partitioned streaming merge. Each input has one forward-only +//! reader. Each nonempty destination has one bounded channel to its final SST writer. +use super::{ + MultiRegionCompactionContext, MultiRegionCompactionOutput, MultiRegionCompactionPlan, + MultiRegionCompactionStats, SourceCounters, source::SharedSource, writer, +}; +use crate::error::{self, InvalidMultiRegionCompactionSnafu as Invalid, Result}; +use crate::read::{FlatSource, flat_merge::FlatMergeReader}; +use datatypes::arrow::array::UInt64Array; +use datatypes::arrow::compute::take_record_batch; +use snafu::{ResultExt, ensure}; +use std::collections::BTreeMap; +use std::sync::{Arc, atomic::Ordering}; +use store_api::storage::RegionId; +use tokio::sync::mpsc; +use tokio::task::JoinSet; + +mod writer_block; +use writer_block::{Packet, Sink}; + +pub(super) async fn execute( + plan: MultiRegionCompactionPlan, + context: MultiRegionCompactionContext, + source: Arc, + counters: Arc, +) -> Result { + let metadata = &plan.targets.first_key_value().unwrap().1.metadata; + ensure!( + plan.partition_rule + .partition_columns() + .iter() + .all(|name| metadata + .column_by_name(name) + .is_some_and(|col| col.semantic_type == api::v1::SemanticType::Tag)), + Invalid { + reason: "Streaming compaction requires key-based partitioning" + } + ); + let target_rows = std::env::var("TESTBED_SHARED_WRITER_BLOCK_ROWS") + .map_or(Ok(1usize), |s| s.parse()) + .map_err(|_| { + Invalid { + reason: "invalid writer block row target", + } + .build() + })?; + let limit = plan.targets.len() * 2; + let batch_limit = plan.memory_limit / (plan.sources.len() + limit * 3 + 2); + let mut output = MultiRegionCompactionOutput { + files: plan.targets.keys().map(|id| (*id, vec![])).collect(), + sst_infos: plan.targets.keys().map(|id| (*id, vec![])).collect(), + stats: MultiRegionCompactionStats::default(), + }; + let start = std::time::Instant::now(); + let mut writer_wait = std::time::Duration::ZERO; + let mut merge = FlatMergeReader::new_stable( + source.schema(), + plan.sources + .iter() + .map(|f| source.clone().ordered_input(f.clone())) + .collect(), + 1024, + ) + .await?; + let plan = Arc::new(plan); + let context = Arc::new(context); + let mut sinks = BTreeMap::new(); + let mut workers = JoinSet::new(); + while let Some(batch) = merge.next_batch().await? { + if context.cancellation.is_cancelled() { + return error::CompactionCancelledSnafu.fail(); + } + ensure!( + batch.get_array_memory_size() <= batch_limit, + Invalid { + reason: "Streaming merge batch exceeds resident slot budget" + } + ); + let mut groups: BTreeMap<(RegionId, i64), Vec> = BTreeMap::new(); + for (row, key) in source + .row_owners(&batch)? + .into_iter() + .zip(source.time_windows(&batch)?) + .enumerate() + { + groups.entry(key).or_default().push(row as u64); + } + for (key, rows) in groups { + if !sinks.contains_key(&key) { + ensure!( + sinks.len() < limit, + Invalid { + reason: "Too many active region/window streams" + } + ); + let (tx, mut rx) = mpsc::channel::(1); + let schema = source.schema(); + let plan = plan.clone(); + let context = context.clone(); + workers.spawn(async move { + let batches=async_stream::try_stream! { while let Some(packet)=rx.recv().await { for batch in packet { yield batch; } } }; + let source=FlatSource::new_stream(schema,Box::pin(batches)); + let (files,infos)=writer::write_target_group(&plan.targets[&key.0],source,&plan,&context).await?; + Ok::<_,error::Error>((key.0,files,infos)) + }); + sinks.insert(key, Sink::new(tx, target_rows, batch_limit)); + } + let fragment = take_record_batch(&batch, &UInt64Array::from(rows)) + .context(error::ComputeArrowSnafu)?; + if !sinks + .get_mut(&key) + .unwrap() + .push(fragment, &mut writer_wait) + .await + { + if let Some(done) = workers.join_next().await { + done.context(error::JoinSnafu)??; + } + return Invalid { + reason: "Output writer stopped before end of input", + } + .fail(); + } + } + } + for sink in sinks.values_mut() { + if !sink.flush(&mut writer_wait).await { + if let Some(done) = workers.join_next().await { + done.context(error::JoinSnafu)??; + } + return Invalid { + reason: "Output writer stopped before end of input", + } + .fail(); + } + } + let drain = std::time::Instant::now(); + drop(sinks); + while let Some(done) = workers.join_next().await { + let (id, files, infos) = done.context(error::JoinSnafu)??; + output.stats.output_rows += files.iter().map(|f| f.num_rows).sum::(); + output.stats.output_bytes += files + .iter() + .map(|f| f.file_size + f.index_file_size) + .sum::(); + output.files.get_mut(&id).unwrap().extend(files); + output.sst_infos.get_mut(&id).unwrap().extend(infos); + } + let writer_drain = drain.elapsed(); + output.stats.write_wait_us = writer_wait.as_micros() as u64; + output.stats.write_drain_us = writer_drain.as_micros() as u64; + output.stats.merge_route_us = (start.elapsed() - writer_drain - writer_wait).as_micros() as u64; + 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); + ensure!( + output.stats.source_rows == output.stats.output_rows + && output.stats.source_files == plan.sources.len() as u64, + Invalid { + reason: "Streaming compaction did not account for all input" + } + ); + Ok(output) +} diff --git a/src/mito2/src/compaction/multi_region/streaming/writer_block.rs b/src/mito2/src/compaction/multi_region/streaming/writer_block.rs new file mode 100644 index 00000000000..a19ea14e84a --- /dev/null +++ b/src/mito2/src/compaction/multi_region/streaming/writer_block.rs @@ -0,0 +1,134 @@ +// 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 writer messages. Individual Arrow batches retain their dictionaries and order. +use datatypes::arrow::record_batch::RecordBatch; +use smallvec::SmallVec; +use std::time::{Duration, Instant}; +use tokio::sync::mpsc; + +pub(super) type Packet = SmallVec<[RecordBatch; 1]>; + +pub(super) struct Sink { + sender: mpsc::Sender, + pending: Packet, + bytes: usize, + rows: usize, + target_rows: usize, + max_bytes: usize, +} + +impl Sink { + pub(super) fn new(sender: mpsc::Sender, target_rows: usize, slot_bytes: usize) -> Self { + Self { + sender, + pending: Packet::new(), + bytes: 0, + rows: 0, + target_rows, + max_bytes: slot_bytes.min(4 << 20), + } + } + + async fn send(&mut self, packet: Packet, wait: &mut Duration) -> bool { + match self.sender.try_send(packet) { + Ok(()) => true, + Err(mpsc::error::TrySendError::Full(packet)) => { + let start = Instant::now(); + let sent = self.sender.send(packet).await.is_ok(); + *wait += start.elapsed(); + sent + } + Err(mpsc::error::TrySendError::Closed(_)) => false, + } + } + + pub(super) async fn flush(&mut self, wait: &mut Duration) -> bool { + if self.pending.is_empty() { + return true; + } + self.rows = 0; + self.bytes = 0; + let packet = std::mem::take(&mut self.pending); + self.send(packet, wait).await + } + + pub(super) async fn push(&mut self, fragment: RecordBatch, wait: &mut Duration) -> bool { + if self.target_rows <= 1 { + return self.send(smallvec::smallvec![fragment], wait).await; + } + let bytes = fragment.get_array_memory_size(); + if bytes > self.max_bytes.saturating_sub(self.bytes) && !self.flush(wait).await { + return false; + } + self.bytes += bytes; + self.rows += fragment.num_rows(); + self.pending.push(fragment); + if self.rows >= self.target_rows || self.bytes >= self.max_bytes || self.pending.len() == 16 + { + return self.flush(wait).await; + } + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + use datatypes::arrow::array::{ArrayRef, UInt64Array}; + use std::sync::Arc; + + fn fragment(value: u64) -> RecordBatch { + RecordBatch::try_from_iter([("n", Arc::new(UInt64Array::from(vec![value])) as ArrayRef)]) + .unwrap() + } + + #[tokio::test] + async fn retains_order_and_delivers_last_partial_packet() { + let (tx, mut rx) = mpsc::channel(3); + let mut sink = Sink::new(tx, 3, 65536); + let mut wait = Duration::ZERO; + for i in 0..7 { + assert!(sink.push(fragment(i), &mut wait).await); + } + assert!(sink.flush(&mut wait).await); + drop(sink); + let mut values = vec![]; + let mut sizes = vec![]; + while let Some(packet) = rx.recv().await { + sizes.push(packet.len()); + for f in packet { + values.push( + f.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + ); + } + } + assert_eq!(sizes, [3, 3, 1]); + assert_eq!(values, (0..7).collect::>()); + } + + #[tokio::test] + async fn caps_bytes_and_reports_closed_writer_on_tail() { + let (tx, mut rx) = mpsc::channel(1); + let bytes = fragment(0).get_array_memory_size(); + let mut sink = Sink::new(tx, 8192, bytes + 1); + let mut wait = Duration::ZERO; + assert!(sink.push(fragment(1), &mut wait).await); + assert!(sink.push(fragment(2), &mut wait).await); + assert_eq!(rx.recv().await.unwrap().len(), 1); + drop(rx); + assert!(!sink.flush(&mut wait).await); + } +} diff --git a/src/mito2/src/compaction/multi_region/tests.rs b/src/mito2/src/compaction/multi_region/tests.rs new file mode 100644 index 00000000000..f5a077e6c1d --- /dev/null +++ b/src/mito2/src/compaction/multi_region/tests.rs @@ -0,0 +1,1723 @@ +// 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::{Arc, Mutex}; +use std::time::Duration; + +use api::v1::OpType; +use datatypes::arrow::array::{ + Array, BinaryArray, BinaryDictionaryBuilder, DictionaryArray, StringArray, + TimestampMillisecondArray, UInt8Array, UInt64Array, +}; +use datatypes::arrow::compute::cast; +use datatypes::arrow::datatypes::{DataType, UInt32Type}; +use datatypes::arrow::record_batch::RecordBatch; +use datatypes::value::Value; +use futures::TryStreamExt; +use object_store::layers::mock::{self, MockLayerBuilder, oio}; +use partition::expr::col; +use partition::multi_dim::MultiDimPartitionRule; +use store_api::codec::PrimaryKeyEncoding; +use store_api::region_request::PathType; +use store_api::storage::RegionId; + +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}; +use crate::sst::file_purger::NoopFilePurger; +use crate::sst::index::intermediate::IntermediateManager; +use crate::sst::index::puffin_manager::PuffinManagerFactory; +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::{ + new_flat_source_from_record_batches, 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, +} + +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 env = SchedulerEnv::new().await; + let aux = env.path.path().join("table-index"); + let layer = Arc::new(AccessLayer::new( + "table/", + if 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(), + )); + let mut metadata = sst_region_metadata_with_encoding(encoding); + metadata.region_id = RegionId::new(1, 0); + let metadata = Arc::new(metadata); + let mut config = MitoConfig::default(); + config.index.aux_path = aux.display().to_string(); + let config = Arc::new(config); + let mut batches = batches(&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 source = new_flat_source_from_record_batches(batches); + let info = layer + .write_sst( + write_request(metadata.clone(), source, &config, format), + &WriteOptions::default(), + &mut Metrics::new(WriteType::Flush), + ) + .await + .unwrap() + .remove(0); + let source = FileMeta { + region_id: metadata.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() + }; + Self { + env, + layer, + metadata, + source, + config, + } + } + + async fn write_additional_source(&self, batches: Vec) -> FileMeta { + let info = self + .layer + .write_sst( + write_request( + self.metadata.clone(), + new_flat_source_from_record_batches(batches), + &self.config, + FormatType::Flat, + ), + &WriteOptions::default(), + &mut Metrics::new(WriteType::Flush), + ) + .await + .unwrap() + .remove(0); + FileMeta { + file_id: info.file_id, + 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, + ..self.source.clone() + } + } + + fn plan(&self, regions: u32) -> 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 mut input = self.source.clone(); + input.sequence = NonZeroU64::new(100 + region as u64); + 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: [(input.file_id(), input)].into_iter().collect(), + }, + ); + } + 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: vec![self.source.clone()], + targets, + memory_limit: 16 * 1024 * 1024, + max_active_workers: 2, + spill_limit: 64 * 1024 * 1024, + max_output_file_size: 1024 * 1024, + 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 { + access_layer: self.layer.clone(), + cache: Arc::new(CacheManager::default()), + config: self.config.clone(), + spill_directory: self.env.path.path().join("spill"), + protection: protection.clone(), + cancellation: Arc::new(CancellationHandle::default()), + }, + protection, + ) + } + + async fn read_output( + &self, + mut file: FileMeta, + metadata: RegionMetadataRef, + ) -> Vec { + let expected_region = file.region_id; + let expected_rows = file.num_rows; + // 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); + let mut reader = self + .layer + .read_sst(FileHandle::new(file, Arc::new(NoopFilePurger))) + .expected_metadata(Some(Arc::new(unfiltered))) + .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 + } +} + +fn write_request( + metadata: RegionMetadataRef, + source: FlatSource, + config: &MitoConfig, + format: FormatType, +) -> SstWriteRequest { + SstWriteRequest { + 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, 3_600_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 single_scan_routes_all_versions_without_folding( + #[case] encoding: PrimaryKeyEncoding, + #[case] format: FormatType, + #[case] sequence: u64, + #[values(false, true)] preload_only: bool, +) { + 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); + if preload_only { + plan.spill_limit = 0; + } + let targets = plan.targets.clone(); + let (mut context, protected) = fixture.context(None); + if preload_only { + // This file cannot be used as a spill directory. + let poison = fixture.env.path.path().join("no-spill-file"); + std::fs::write(&poison, b"guard").unwrap(); + context.spill_directory = poison.join("forbidden"); + } + let output = compact_regions(plan, context).await.unwrap(); + if preload_only { + assert_eq!(0, output.stats.spilled_bytes); + } + 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); + } + 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!(1, file.level); + assert_eq!(id, file.region_id); + assert_eq!(id != fixture.metadata.region_id, file.preserve_row_sequence); + for batch in fixture.read_output(file, target.metadata.clone()).await { + let sequences = batch + .column(sequence_column_index(batch.num_columns())) + .as_any() + .downcast_ref::() + .unwrap(); + let expected = if id == fixture.metadata.region_id && sequence != 0 { + sequence + } else { + 100 + id.region_sequence() as u64 + }; + assert!(sequences.values().iter().all(|actual| *actual == expected)); + let operations = batch + .column(batch.num_columns() - 1) + .as_any() + .downcast_ref::() + .unwrap(); + total_deletes += operations + .values() + .iter() + .filter(|op| **op == OpType::Delete as u8) + .count(); + 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 encoding == PrimaryKeyEncoding::Sparse { + new_sparse_primary_key( + &[tags.value(row), "series"], + &fixture.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)); + actual_rows.push(( + series, + *timestamp, + sequences.value(row), + operations.value(row), + values.is_valid(row).then(|| values.value(row)), + )); + } + } + } + let expected_sequence = if id == fixture.metadata.region_id && sequence != 0 { + sequence + } else { + 100 + id.region_sequence() as u64 + }; + let mut expected_rows = Vec::new(); + 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 + ); + expected_rows.extend([ + (series, 0, expected_sequence, OpType::Put as u8, Some(10)), + (series, 0, expected_sequence, OpType::Put as u8, Some(20)), + (series, 0, expected_sequence, OpType::Delete as u8, None), + ( + series, + 3_600_000, + expected_sequence, + OpType::Put as u8, + Some(30), + ), + ]); + } + actual_rows.sort(); + expected_rows.sort(); + assert_eq!(expected_rows, actual_rows); + } + assert_eq!(31, total_deletes); + } +} + +#[rstest::rstest] +#[case::sparse(PrimaryKeyEncoding::Sparse)] +#[case::dense(PrimaryKeyEncoding::Dense)] +#[tokio::test] +async fn source_materializes_only_required_sparse_tags(#[case] encoding: PrimaryKeyEncoding) { + let fixture = Fixture::new(encoding, FormatType::Flat, 7).await; + let mut plan = fixture.plan(8); + plan.spill_limit = 0; + let (context, _) = fixture.context(None); + let metadata = validate_plan(&plan).unwrap(); + let source = source::SharedSource::build( + &plan, + &context, + metadata, + Arc::new(SourceCounters::default()), + ) + .await + .unwrap(); + let mut stream = source.clone().ordered_input(fixture.source.clone()); + let batch = stream.try_next().await.unwrap().unwrap(); + assert!(batch.column_by_name("tag_0").is_some()); + assert_eq!( + encoding == PrimaryKeyEncoding::Dense, + batch.column_by_name("tag_1").is_some() + ); + assert!(batch.column_by_name("field_0").is_some()); + assert_eq!(source.schema(), batch.schema()); + // Existing end-to-end cases compare the full encoded key (including tag_1), + // values, sequence, delete markers, routing and output readback for both modes. +} + +#[tokio::test] +async fn 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()); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; +} + +#[rstest::rstest] +#[case(crate::region::options::MergeMode::LastRow)] +#[case(crate::region::options::MergeMode::LastNonNull)] +#[tokio::test] +async fn table_stage_does_not_apply_target_merge_mode( + #[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 = false; + target.options.preserve_row_sequence = false; + target.options.merge_mode = Some(merge_mode); + } + let output = compact_regions(plan, fixture.context(None).0) + .await + .unwrap(); + assert_eq!(124, output.stats.output_rows); +} + +#[tokio::test] +async fn routed_runs_spill_and_exhaustion_fails_without_outputs() { + 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); + plan.memory_limit = 2 * 1024 * 1024; + for target in plan.targets.values_mut() { + Arc::make_mut(&mut target.metadata).set_partition_expr(None); + } + let output = compact_regions(plan, fixture.context(None).0) + .await + .unwrap(); + assert_eq!(102400, output.stats.output_rows); + assert!(output.stats.spilled_bytes > 0); + // Regression: IPC column buffers can share an allocation. Reusing spilled + // long-tag batches must not exhaust the budget through duplicate charges. + 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 = 2 * 1024 * 1024; + plan.spill_limit = 1; + 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 { reason, .. } + if reason == "Multi-region temporary disk quota exhausted" + ), + "{error:?}" + ); + assert!(protected.files.lock().unwrap().is_empty()); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; +} + +#[tokio::test] +async fn 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 = compact_regions(plan, fixture.context(None).0) + .await + .unwrap(); + 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] +#[tokio::test] +async fn multiple_sources_merge_versions_in_each_target_sequence_domain( + #[values(false, true)] preload_only: 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); + if preload_only { + plan.spill_limit = 0; + } + plan.sources.push(second.clone()); + for (id, target) in &mut plan.targets { + let mut input = second.clone(); + input.sequence = NonZeroU64::new(200 + id.region_sequence() as u64); + target.inputs.insert(input.file_id(), input); + } + let targets = plan.targets.clone(); + let output = compact_regions(plan, fixture.context(None).0) + .await + .unwrap(); + 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, 201] + }; + let mut observed = HashSet::new(); + for file in files { + for batch in fixture + .read_output(file, targets[&id].metadata.clone()) + .await + { + let sequence = batch + .column(sequence_column_index(batch.num_columns())) + .as_any() + .downcast_ref::() + .unwrap(); + observed.extend(sequence.values().iter().copied()); + let keys = cast( + batch.column(primary_key_column_index(batch.num_columns())), + &DataType::Binary, + ) + .unwrap(); + let keys = keys.as_any().downcast_ref::().unwrap(); + let times = crate::read::timestamp_array_to_i64_slice( + batch.column(time_index_column_index(batch.num_columns())), + ); + for row in 1..batch.num_rows() { + if keys.value(row - 1) == keys.value(row) && times[row - 1] == times[row] { + assert!(sequence.value(row - 1) >= sequence.value(row)); + } + } + } + } + assert_eq!(expected.into_iter().collect::>(), observed); + } +} + +#[tokio::test] +async fn 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 = compact_regions(plan, fixture.context(None).0) + .await + .unwrap(); + assert_eq!(124, output.stats.output_rows); + for (id, files) in output.files { + let mut series = HashSet::new(); + for file in files { + for batch in fixture + .read_output(file, targets[&id].metadata.clone()) + .await + { + let tags = cast(batch.column_by_name("tag_0").unwrap(), &DataType::Utf8).unwrap(); + let tags = tags.as_any().downcast_ref::().unwrap(); + series.extend(tags.iter().flatten().map(|tag| tag.parse::().unwrap())); + } + } + let range = if id.region_sequence() == 0 { + 0..20 + } else { + 20..31 + }; + assert_eq!(range.collect::>(), series); + } +} + +#[tokio::test] +async fn 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 = compact_regions(plan, fixture.context(None).0) + .await + .unwrap(); + assert_eq!(124, output.stats.output_rows); + for (id, files) in output.files { + let mut counts = (0, 0); + for file in files { + for batch in fixture + .read_output(file, targets[&id].metadata.clone()) + .await + { + counts.0 += batch.num_rows(); + let values = batch + .column_by_name("field_0") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + counts.1 += values.null_count(); + for value in values.iter().flatten() { + 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 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()); +} + +/// One decoded batch fans out into 1024 windows, with 32 extra columns +/// materialized by schema compatibility before routing. +async fn wide_window_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_iter_values( + (0..1024).map(|row| (row - 512) * 3_600_000), + )); + vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] + }) + .await; + let mut plan = fixture.plan(1); + plan.memory_limit = 4 * 1024 * 1024; + for target in plan.targets.values_mut() { + 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(), + }); + } + target.metadata = Arc::new(builder.build().unwrap()); + } + (fixture, plan) +} + +#[tokio::test] +async fn wide_source_routes_windows_without_retaining_future_fragments() { + let (fixture, plan) = wide_window_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(); + for row in 0..1024 { + let Some(source::SourceEvent::Batch { + region_id, + window, + batch, + }) = stream.try_next().await.unwrap() + else { + panic!("source ended before all windows were routed"); + }; + assert_eq!(RegionId::new(1, 0), region_id); + assert_eq!(row - 512, window); + assert_eq!(1, batch.num_rows()); + assert_eq!(39, batch.num_columns()); + let keys = batch + .column(primary_key_column_index(batch.num_columns())) + .as_any() + .downcast_ref::>() + .unwrap(); + // Each eagerly filtered fragment retains the shared dictionary. This + // checks live ownership while the consumer is paused, not a cache-only + // counter or process RSS. Allow fixed reader/cursor ownership overhead, + // but not one reference per future window (1024 in the regression). + assert!( + Arc::strong_count(keys.values()) < 16, + "future fragments retained {} dictionary references", + Arc::strong_count(keys.values()) + ); + assert_eq!( + row as u64, + batch + .column_by_name("field_0") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0) + ); + for column in 0..32 { + let values = batch + .column_by_name(&format!("wide_{column}")) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(0, values.null_count()); + assert_eq!(1000 + column as u64, values.value(0)); + } + } + assert!(matches!( + stream.try_next().await.unwrap(), + Some(source::SourceEvent::SourceEnd) + )); + assert!(stream.try_next().await.unwrap().is_none()); + 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 cancelling_between_routed_fragments_stops_the_source() { + let (fixture, plan) = wide_window_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!(matches!( + stream.try_next().await.unwrap(), + Some(source::SourceEvent::Batch { .. }) + )); + context.cancellation.cancel(); + let error = stream + .try_next() + .await + .err() + .expect("cancelled source yielded another fragment"); + assert!(matches!( + error, + crate::error::Error::CompactionCancelled { .. } + )); +} + +#[rstest::rstest] +#[case(1)] +#[case(2)] +#[tokio::test] +async fn many_windows_exhaust_metadata_without_outputs(#[case] workers: usize) { + let (fixture, mut plan) = wide_window_fixture().await; + plan.max_active_workers = workers; + let (context, protected) = fixture.context(None); + let error = tokio::time::timeout(Duration::from_secs(60), compact_regions(plan, context)) + .await + .expect("window admission failure stalled the pipeline") + .err() + .unwrap(); + assert!( + matches!( + &error, + crate::error::Error::MultiRegionCompactionResource { reason, .. } + if reason == "Too many regions or time windows" + ), + "{error:?}" + ); + assert!(protected.files.lock().unwrap().is_empty()); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; + 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()); +} + +#[test] +fn stable_merge_keeps_tied_source_order_across_empty_batches_and_refills() { + fn tied_batch(start: usize, end: usize) -> RecordBatch { + let batch = new_record_batch_with_custom_sequence(&["000", "series"], start, end, 7); + let mut columns = batch.columns().to_vec(); + columns[3] = Arc::new(TimestampMillisecondArray::from(vec![0; end - start])); + RecordBatch::try_new(batch.schema(), columns).unwrap() + } + let schema = tied_batch(0, 1).schema(); + let inputs: Vec = vec![ + Box::new( + vec![tied_batch(0, 0), tied_batch(0, 2), tied_batch(2, 5)] + .into_iter() + .map(Ok), + ), + Box::new( + vec![tied_batch(100, 102), tied_batch(102, 105)] + .into_iter() + .map(Ok), + ), + ]; + let merge = crate::read::flat_merge::FlatMergeIterator::new_stable(schema, inputs, 3).unwrap(); + let mut payloads = Vec::new(); + for batch in merge { + let batch = batch.unwrap(); + let values = batch + .column_by_name("field_0") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + payloads.extend(values.values().iter().copied()); + } + assert_eq!(vec![0, 1, 2, 3, 4, 100, 101, 102, 103, 104], payloads); +} + +/// Five overlapping sources exercise both binary carries and the final merge +/// of unequal levels. Every timestamp has tied puts and a tombstone. +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 / 128 * 3_600_000 + row % 128 / 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); + plan.memory_limit = 2 * 1024 * 1024; + plan.max_output_file_size = 16 * 1024; + 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_single_work_slot(1, false)] +#[case::range_parallel_workers(2, false)] +#[case::multi_column_single_work_slot(1, true)] +#[case::multi_column_parallel_workers(2, true)] +#[tokio::test] +async fn bounded_workers_merge_overlapping_sources_without_deadlock_or_reordering( + #[case] workers: usize, + #[case] multi_column: bool, +) { + let (fixture, mut plan) = overlapping_fixture().await; + plan.max_active_workers = workers; + 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.spilled_bytes > 0); + assert!(output.stats.peak_buffered_bytes <= (memory_limit / 2) as u64); + assert_eq!( + targets.keys().collect::>(), + output.files.keys().collect::>() + ); + common_telemetry::info!( + "workers={workers}, 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() >= 4, + "each target must produce all four windows" + ); + let file_count = files.len(); + let mut windows = BTreeMap::>::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!(1, 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 + ); + for batch in fixture + .read_output(file, targets[&id].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 timestamps = crate::read::timestamp_array_to_i64_slice( + batch.column(time_index_column_index(batch.num_columns())), + ); + 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 values = batch + .column_by_name("field_0") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for (row, timestamp) in timestamps.iter().copied().enumerate() { + assert_eq!(file_window, timestamp.div_euclid(3_600_000)); + windows.entry(file_window).or_default().push(( + tags.value(row).parse::().unwrap(), + timestamp, + sequences.value(row), + operations.value(row), + values.is_valid(row).then(|| values.value(row)), + )); + } + } + } + let mut expected = BTreeMap::new(); + for window in 0..4 { + let mut rows = Vec::new(); + for series in 0..31 { + for tick in 0..32 { + for source in 0..5 { + for version in 0..4 { + let ordinal = window * 128 + 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; + } + rows.push(( + series, + window * 3_600_000 + tick, + if id.region_sequence() == 0 { 5 } else { 777 }, + if version == 2 { + OpType::Delete as u8 + } else { + OpType::Put as u8 + }, + payload, + )); + } + } + } + } + expected.insert(window, rows); + } + // Do not sort actual rows: this checks stability across input batches, + // merge passes, output batches and SST file boundaries, not just a multiset. + assert_eq!(expected, windows, "incorrect rows or ordering for {id}"); + common_telemetry::info!( + "verified region={id}, files={file_count}, rows={}", + windows.values().map(Vec::len).sum::() + ); + } + for path in source_paths { + assert!(fixture.layer.object_store().exists(&path).await.unwrap()); + } + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; +} + +async fn assert_spill_cleaned(path: &std::path::Path) { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + match tokio::fs::read_dir(path).await { + Ok(mut entries) => { + if entries.next_entry().await.unwrap().is_none() { + return; + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return, + Err(error) => panic!("cannot inspect spill cleanup: {error}"), + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("attempt spill resources leaked"); +} + +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 + } +} + +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 interrupted_indexed_worker_cleans_tantivy_files(#[case] fail_sibling: bool) { + use datatypes::data_type::ConcreteDataType; + use datatypes::schema::{ + ColumnDefaultConstraint, ColumnSchema, FulltextAnalyzer, FulltextBackend, FulltextOptions, + }; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + + let mut fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + ["000", "020"] + .into_iter() + .map(|tag| { + let rows = if tag == "000" { 262_144 } else { 1 }; + 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); + plan.memory_limit = 1024 * 1024; + 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: 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(), + }); + target.metadata = Arc::new(builder.build().unwrap()); + } + 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"); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; + // 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(Arc); + +#[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 cancelling_a_blocked_writer_cleans_spills_and_preserves_sources() { + let (fixture, mut plan) = overlapping_fixture().await; + plan.max_active_workers = 1; + 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 { .. } + )); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; + 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 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()); +} + +#[rstest::rstest] +#[case::default(None)] +#[case::small(Some(1024))] +#[case::sixteen_k(Some(16 * 1024))] +#[case::thirty_two_k(Some(32 * 1024))] +#[tokio::test] +async fn shared_output_honors_table_row_group_size(#[case] configured: Option) { + // More than one large row group per target; the two tags route to different regions. + const ROWS: usize = 40_001; + let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + ["000", "016"] + .into_iter() + .map(|tag| new_record_batch_with_custom_sequence(&[tag, "series"], 0, ROWS, 7)) + .collect() + }) + .await; + let mut plan = fixture.plan(2); + plan.memory_limit = 64 * 1024 * 1024; + plan.max_output_file_size = 64 * 1024 * 1024; + plan.spill_limit = 0; + for target in plan.targets.values_mut() { + target.options.max_row_group_row_count = configured; + } + let targets = plan.targets.clone(); + let (context, _) = fixture.context(None); + let output = compact_regions(plan, context).await.unwrap(); + assert_eq!((2 * ROWS) as u64, output.stats.output_rows); + assert_eq!(0, output.stats.spilled_bytes); + let row_group_size = configured.unwrap_or(crate::sst::parquet::DEFAULT_ROW_GROUP_SIZE); + for (id, files) in output.files { + assert_eq!(1, files.len()); + let footer = output.sst_infos[&id][0].file_metadata.as_ref().unwrap(); + assert_eq!(ROWS.div_ceil(row_group_size), footer.num_row_groups()); + assert_eq!(ROWS as i64, footer.file_metadata().num_rows()); + for (index, group) in footer.row_groups().iter().enumerate() { + let expected = (ROWS - index * row_group_size).min(row_group_size); + assert_eq!(expected as i64, group.num_rows()); + } + let batches = fixture + .read_output(files[0].clone(), targets[&id].metadata.clone()) + .await; + let mut actual = Vec::with_capacity(ROWS); + for batch in batches { + let time = batch + .column(time_index_column_index(batch.num_columns())) + .as_any() + .downcast_ref::() + .unwrap(); + actual.extend(time.values().iter().copied()); + } + actual.sort_unstable(); + assert_eq!((0..ROWS as i64).collect::>(), actual); + } +} diff --git a/src/mito2/src/compaction/multi_region/worker.rs b/src/mito2/src/compaction/multi_region/worker.rs new file mode 100644 index 00000000000..e2beddc2bd3 --- /dev/null +++ b/src/mito2/src/compaction/multi_region/worker.rs @@ -0,0 +1,384 @@ +// 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. + +//! Workers only merge sealed source runs. A work-slot holder never waits for +//! another source head or channel message: cache pressure spills or fails instead +//! of waiting for a consumer. This keeps capacity-one channels live even with a +//! single work slot. Binary carries merge contiguous source intervals so equal +//! row keys retain the plan's source order across every merge pass. + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use datatypes::arrow::datatypes::SchemaRef; +use futures::stream::FuturesUnordered; +use futures::{StreamExt, TryStreamExt}; +use snafu::{OptionExt, ResultExt, ensure}; +use store_api::storage::RegionId; +use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc}; +use tokio_util::sync::CancellationToken; +use tokio_util::task::AbortOnDropHandle; + +use crate::compaction::multi_region::source::{SharedSource, SourceEvent}; +use crate::compaction::multi_region::spill::{Reservation, Run, RunStore}; +use crate::compaction::multi_region::{ + MultiRegionCompactionContext, MultiRegionCompactionOutput, MultiRegionCompactionPlan, + MultiRegionCompactionStats, SourceCounters, writer, +}; +use crate::error::{InvalidMultiRegionCompactionSnafu, Result}; +use crate::read::FlatSource; +use crate::read::flat_merge::FlatMergeIterator; +use crate::sst::file::FileMeta; +use crate::sst::parquet::SstInfo; + +/// A closed channel is an error, not a substitute for either explicit boundary. +enum Message { + Batch { window: i64, run: Run }, + SourceEnd, + Finish, +} + +struct RegionOutput { + region_id: RegionId, + files: Vec, + infos: Vec, +} + +pub(crate) async fn execute( + plan: MultiRegionCompactionPlan, + context: MultiRegionCompactionContext, + source: Arc, + counters: Arc, +) -> Result { + let stop = CancellationToken::new(); + let _cancel_on_drop = stop.clone().drop_guard(); + let store = RunStore::new(&plan, &context, stop).await?; + let slots = Arc::new(Semaphore::new(plan.max_active_workers)); + let plan = Arc::new(plan); + let context = Arc::new(context); + let resources = Arc::new(WorkerResources { + plan: plan.clone(), + context, + slots: slots.clone(), + }); + let mut senders = BTreeMap::new(); + let mut workers = FuturesUnordered::new(); + for ®ion_id in plan.targets.keys() { + let (sender, receiver) = mpsc::channel(1); + let state = RegionWorker { + windows: BTreeMap::new(), + completed_sources: 0, + schema: source.schema(), + // Includes the task and the channel's block-based allocation. + _reservation: store.reserve_metadata(8 * 1024)?, + store: store.clone(), + }; + senders.insert(region_id, sender); + workers.push(AbortOnDropHandle::new(common_runtime::spawn_compact( + run_worker(region_id, state, receiver, resources.clone()), + ))); + } + let scan = dispatch(source, senders, store.clone(), slots); + 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 result = result.context(crate::error::JoinSnafu)??; + output.stats.output_rows += result.files.iter().map(|file| file.num_rows).sum::(); + output.stats.output_bytes += result.files.iter().map(|file| file.file_size + file.index_file_size).sum::(); + output.files.insert(result.region_id, result.files); + output.sst_infos.insert(result.region_id, result.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.spilled_bytes = store.spilled_bytes(); + output.stats.peak_buffered_bytes = store.peak_buffered_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>, + store: Arc, + slots: Arc, +) -> Result<()> { + let mut batches = source.batches(); + while let Some(event) = batches.try_next().await? { + store.check_cancelled()?; + match event { + SourceEvent::Batch { + region_id, + window, + batch, + } => { + let buffer_store = store.clone(); + let run = + blocking(slots.clone(), move || Run::from_batch(batch, &buffer_store)).await?; + let sender = + senders + .get(®ion_id) + .context(InvalidMultiRegionCompactionSnafu { + reason: "Routed fragment names an unknown region", + })?; + send(sender, Message::Batch { window, run }).await; + } + SourceEvent::SourceEnd => { + for sender in senders.values() { + send(sender, Message::SourceEnd).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 polls every worker concurrently with dispatch. Let it + // report the worker's original error/panic, not a racing channel error. + futures::future::pending::<()>().await; + } +} + +async fn acquire_slot(slots: &Arc) -> Result { + slots.clone().acquire_owned().await.map_err(|_| { + InvalidMultiRegionCompactionSnafu { + reason: "Compaction work semaphore closed", + } + .build() + }) +} + +async fn blocking( + slots: Arc, + operation: impl FnOnce() -> Result + Send + 'static, +) -> Result { + let permit = acquire_slot(&slots).await?; + common_runtime::spawn_blocking_compact(move || { + let _permit = permit; + operation() + }) + .await + .context(crate::error::JoinSnafu)? +} + +struct RegionWorker { + windows: BTreeMap, + completed_sources: usize, + schema: SchemaRef, + _reservation: Reservation, + store: Arc, +} + +impl RegionWorker { + fn accept(&mut self, message: Message) -> Result<()> { + self.store.check_cancelled()?; + match message { + Message::Batch { window, run } => { + let window = match self.windows.entry(window) { + std::collections::btree_map::Entry::Vacant(entry) => { + entry.insert(WindowRuns::new(&self.store)?) + } + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + }; + window.current.append(run, &self.store)?; + } + Message::SourceEnd => { + for window in self.windows.values_mut() { + window.seal(&self.schema, &self.store)?; + } + self.completed_sources += 1; + } + Message::Finish => {} + } + Ok(()) + } +} + +struct WindowRuns { + current: Run, + /// Occupied higher levels precede lower levels in the source order. + levels: Vec>, + _reservation: Reservation, +} + +impl WindowRuns { + fn new(store: &RunStore) -> Result { + // Includes all binary merge levels, not just the current run. + let bytes = std::mem::size_of::() + + 128 + + usize::BITS as usize * std::mem::size_of::>(); + Ok(Self { + current: Run::default(), + levels: Vec::new(), + _reservation: store.reserve_metadata(bytes)?, + }) + } + + fn seal(&mut self, schema: &SchemaRef, store: &RunStore) -> Result<()> { + let mut run = std::mem::take(&mut self.current); + if run.is_empty() { + return Ok(()); + } + for level in &mut self.levels { + let Some(previous) = level.take() else { + *level = Some(run); + return Ok(()); + }; + run = merge(previous, run, schema, store)?; + } + self.levels.push(Some(run)); + Ok(()) + } + + fn finish(self, schema: &SchemaRef, store: &RunStore) -> Result { + ensure!( + self.current.is_empty(), + InvalidMultiRegionCompactionSnafu { + reason: "Cannot merge an unfinished source", + } + ); + let mut result = None; + for run in self.levels.into_iter().rev().flatten() { + result = Some(match result { + None => run, + Some(previous) => merge(previous, run, schema, store)?, + }); + } + result.context(InvalidMultiRegionCompactionSnafu { + reason: "Empty output window", + }) + } +} + +fn merge(left: Run, right: Run, schema: &SchemaRef, store: &RunStore) -> Result { + store.check_cancelled()?; + let iterator = FlatMergeIterator::new_stable( + schema.clone(), + vec![left.into_iter()?, right.into_iter()?], + 1024, + )?; + let mut output = Run::default(); + for batch in iterator { + output.push(batch?, store)?; + } + Ok(output) +} + +struct WorkerResources { + plan: Arc, + context: Arc, + slots: Arc, +} + +async fn run_worker( + region_id: RegionId, + mut state: RegionWorker, + mut receiver: mpsc::Receiver, + resources: Arc, +) -> Result { + let WorkerResources { + plan, + context, + slots, + } = resources.as_ref(); + loop { + let message = receiver + .recv() + .await + .context(InvalidMultiRegionCompactionSnafu { + reason: "Source channel closed without Finish", + })?; + if matches!(message, Message::Finish) { + break; + } + state = blocking(slots.clone(), move || { + state.accept(message)?; + Ok(state) + }) + .await?; + } + ensure!( + state.completed_sources == plan.sources.len(), + InvalidMultiRegionCompactionSnafu { + reason: "Region worker did not receive every source boundary", + } + ); + let target = plan + .targets + .get(®ion_id) + .context(InvalidMultiRegionCompactionSnafu { + reason: "Missing worker target", + })?; + let mut output = RegionOutput { + region_id, + files: Vec::new(), + infos: Vec::new(), + }; + while let Some((_, window)) = state.windows.pop_first() { + let schema = state.schema.clone(); + let store = state.store.clone(); + let run = blocking(slots.clone(), move || window.finish(&schema, &store)).await?; + // Writers share work slots with merges. No holder ever waits for a + // channel or a not-yet-sealed source, even when there is only one slot. + let permit = acquire_slot(slots).await?; + let (mut iterator, permit) = common_runtime::spawn_blocking_compact(move || { + Ok::<_, crate::error::Error>((run.into_iter()?, permit)) + }) + .await + .context(crate::error::JoinSnafu)??; + let store = state.store.clone(); + let stream = async_stream::try_stream! { + loop { + let checking = store.clone(); + let (next, returned) = common_runtime::spawn_blocking_compact(move || { + checking.check_cancelled()?; + let next = iterator.next().transpose()?; + Ok::<_, crate::error::Error>((next, iterator)) + }).await.context(crate::error::JoinSnafu)??; + iterator = returned; + let Some(batch) = next else { break; }; + yield batch; + } + }; + let source = FlatSource::new_stream(state.schema.clone(), Box::pin(stream)); + let (files, infos) = writer::write_target_group(target, source, plan, context).await?; + drop(permit); + output.files.extend(files); + output.infos.extend(infos); + } + Ok(output) +} diff --git a/src/mito2/src/compaction/multi_region/writer.rs b/src/mito2/src/compaction/multi_region/writer.rs new file mode 100644 index 00000000000..13fc34a7c8a --- /dev/null +++ b/src/mito2/src/compaction/multi_region/writer.rs @@ -0,0 +1,175 @@ +// 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 common_base::readable_size::ReadableSize; +use snafu::{ResultExt, ensure}; +use store_api::codec::PrimaryKeyEncoding; + +use crate::access_layer::{Metrics, OperationType, SstWriteRequest, WriteType}; +use crate::compaction::multi_region::{ + MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, +}; +use crate::error::{ComputeArrowSnafu, Result}; +use crate::read::FlatSource; +use crate::sst::FormatType; +use crate::sst::file::FileMeta; +use crate::sst::parquet::metadata::extract_primary_key_range; +use crate::sst::parquet::parallel_writer::EncodeRuntime; +use crate::sst::parquet::{SstInfo, WriteOptions}; + +pub(crate) async fn write_target_group( + target: &MultiRegionTarget, + source: FlatSource, + plan: &MultiRegionCompactionPlan, + context: &MultiRegionCompactionContext, +) -> Result<(Vec, Vec)> { + if context.cancellation.is_cancelled() { + return crate::error::CompactionCancelledSnafu.fail(); + } + let minimum_chunk = context + .access_layer + .object_store() + .info() + .capability() + .write_multi_min_size + .unwrap_or(0); + let write_buffer = if plan.spill_limit == 0 { + (plan.memory_limit / (8 * plan.targets.len())).min(16 << 20) + } else { + plan.memory_limit / 8 + }; + ensure!( + minimum_chunk <= write_buffer, + crate::error::MultiRegionCompactionResourceSnafu { + reason: "Storage multipart minimum exceeds the table writer budget", + } + ); + let source = output_projection(target, source, context.cancellation.clone())?; + let trusted = target.options.preserve_row_sequence + && target.inputs.values().all(|file| { + if file.region_id == target.metadata.region_id { + file.preserve_row_sequence + } else { + file.sequence.is_some() + } + }); + let request = SstWriteRequest { + op_type: OperationType::Compact, + metadata: target.metadata.clone(), + source, + cache_manager: context.cache.clone(), + max_sequence: None, + sst_write_format: target.options.sst_format.unwrap_or( + if context.config.default_flat_format { + FormatType::Flat + } else { + FormatType::PrimaryKey + }, + ), + preserve_row_sequence: trusted, + index_options: target.options.index_options.clone(), + index_config: context.config.index.clone(), + inverted_index_config: context.config.inverted_index.clone(), + fulltext_index_config: context.config.fulltext_index.clone(), + bloom_filter_index_config: context.config.bloom_filter_index.clone(), + }; + let options = WriteOptions { + write_buffer_size: ReadableSize(write_buffer as u64), + max_file_size: Some(plan.max_output_file_size), + row_group_size: target.options.row_group_size(), + float_field_encoding: target.options.float_field_encoding, + // Work slots bound active writers; extra encoding tasks are not budgeted. + encode_parallelism: 1, + encode_runtime: EncodeRuntime::Compact, + }; + let mut metrics = Metrics::new(WriteType::Compaction); + let infos = context + .access_layer + .write_sst_with_guard(request, &options, &mut metrics, context.protection.clone()) + .await?; + metrics.observe(); + let sequence = target + .inputs + .values() + .map(|file| file.sequence) + .collect::>>() + .and_then(|values| values.into_iter().max()); + let partition_expr = + crate::region::parse_partition_expr(target.metadata.partition_expr.as_deref())?; + let files = infos + .iter() + .map(|info| { + let range = info + .file_metadata + .as_ref() + .and_then(|footer| extract_primary_key_range(footer, &target.metadata)); + FileMeta { + region_id: target.metadata.region_id, + file_id: info.file_id, + time_range: info.time_range, + level: 1, + file_size: info.file_size, + max_row_group_uncompressed_size: info.max_row_group_uncompressed_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, + partition_expr: partition_expr.clone(), + 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: trusted, + } + }) + .collect(); + Ok((files, infos.into_iter().collect())) +} + +fn output_projection( + target: &MultiRegionTarget, + mut source: FlatSource, + cancellation: Arc, +) -> Result { + let projection: Vec<_> = source + .schema() + .fields() + .iter() + .enumerate() + .filter(|(_, field)| { + target.metadata.primary_key_encoding != PrimaryKeyEncoding::Sparse + || !target.metadata.primary_key.iter().any(|id| { + target + .metadata + .column_by_id(*id) + .is_some_and(|column| column.column_schema.name == *field.name()) + }) + }) + .map(|(index, _)| index) + .collect(); + let schema = Arc::new( + source + .schema() + .project(&projection) + .context(ComputeArrowSnafu)?, + ); + 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.project(&projection).context(ComputeArrowSnafu)?; + } + }; + Ok(FlatSource::new_stream(schema, Box::pin(stream))) +} diff --git a/src/mito2/src/compaction/scheduler.rs b/src/mito2/src/compaction/scheduler.rs index 22df8c094ab..e8067e1dd8d 100644 --- a/src/mito2/src/compaction/scheduler.rs +++ b/src/mito2/src/compaction/scheduler.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[cfg(feature = "enterprise")] +mod hybrid; mod local; mod planning; mod state; @@ -35,6 +37,7 @@ use tokio::sync::mpsc::Sender; use crate::access_layer::AccessLayerRef; use crate::cache::CacheManagerRef; use crate::compaction::memory_manager::CompactionMemoryManager; +#[cfg(not(feature = "enterprise"))] use crate::compaction::task::MAX_PARALLEL_COMPACTION; use crate::config::MitoConfig; use crate::error::{ @@ -100,6 +103,12 @@ pub(crate) struct CompactionScheduler { /// Scheduler-wide generation counter for compaction plans and executions. /// It outlives region statuses so close/reopen cannot reuse an old identity. next_plan_id: u64, + #[cfg(feature = "enterprise")] + shared: Option>, + #[cfg(feature = "enterprise")] + shared_lane: bool, + #[cfg(feature = "enterprise")] + ddl_blocked: std::collections::HashSet, } /// Describes the immediate action produced by a compaction terminal transition. @@ -172,6 +181,12 @@ impl CompactionScheduler { listener, plugins, next_plan_id: 0, + #[cfg(feature = "enterprise")] + shared: None, + #[cfg(feature = "enterprise")] + shared_lane: false, + #[cfg(feature = "enterprise")] + ddl_blocked: Default::default(), } } @@ -182,6 +197,11 @@ impl CompactionScheduler { access_layer: &AccessLayerRef, ) { let region_id = version_control.region_id(); + #[cfg(feature = "enterprise")] + if !self.shared_lane && crate::compaction::compactor::experiment::enabled(region_id) { + self.shared_scheduler() + .register_region(version_control, access_layer); + } if let Some(status) = self.region_status.get_mut(®ion_id) { if Arc::ptr_eq(&status.version_control, version_control) { return; @@ -224,7 +244,21 @@ impl CompactionScheduler { manifest_ctx: &ManifestContextRef, schema_metadata_manager: SchemaMetadataManagerRef, ) -> Result { - self.schedule_compaction( + #[cfg(feature = "enterprise")] + let shared_started = if !self.shared_lane + && crate::compaction::compactor::experiment::enabled(version_control.region_id()) + { + self.shared_scheduler().schedule_automatic_compaction( + compact_options.clone(), + version_control, + access_layer, + manifest_ctx, + schema_metadata_manager.clone(), + )? + } else { + false + }; + let started = self.schedule_compaction( CompactionTrigger::Automatic, compact_options, version_control, @@ -232,9 +266,26 @@ impl CompactionScheduler { OptionOutputTx::none(), manifest_ctx, schema_metadata_manager, - 1, // Default for automatic compaction + { + #[cfg(feature = "enterprise")] + { + crate::compaction::compactor::experiment::automatic_parallelism() + } + #[cfg(not(feature = "enterprise"))] + { + 1 + } + }, None, - ) + )?; + #[cfg(feature = "enterprise")] + { + return Ok(started || shared_started); + } + #[cfg(not(feature = "enterprise"))] + { + Ok(started) + } } /// Accepts a manual compaction request for a region. @@ -266,6 +317,21 @@ impl CompactionScheduler { max_parallelism: usize, time_range: Option, ) -> Result { + #[cfg(feature = "enterprise")] + if !self.shared_lane + && crate::compaction::compactor::experiment::enabled(version_control.region_id()) + { + return self.shared_scheduler().schedule_manual_compaction( + compact_options, + version_control, + access_layer, + waiter, + manifest_ctx, + schema_metadata_manager, + max_parallelism, + time_range, + ); + } self.schedule_compaction( CompactionTrigger::Manual, compact_options, @@ -299,6 +365,38 @@ impl CompactionScheduler { manifest_ctx: &ManifestContextRef, schema_metadata_manager: SchemaMetadataManagerRef, ) -> CompactionTransition { + #[cfg(feature = "enterprise")] + if hybrid::is_shared_plan(finished.plan_id) && !self.shared_lane { + let region_id = finished.region_id; + let retry = matches!( + &finished.result, + planning::CompactionPlanningResult::RetryShared + ); + let Some(shared) = self.shared.as_mut() else { + return CompactionTransition::NoAction; + }; + let transition = shared + .handle_compaction_pick_finished_inner( + finished, + manifest_ctx, + schema_metadata_manager.clone(), + ) + .await; + if retry + && !self + .region_status + .get(®ion_id) + .is_some_and(|s| s.has_ddl()) + { + return transition; + } + return self.after_shared_event( + region_id, + manifest_ctx, + schema_metadata_manager, + transition, + ); + } self.handle_compaction_pick_finished_inner(finished, manifest_ctx, schema_metadata_manager) .await } @@ -422,6 +520,10 @@ impl CompactionScheduler { /// /// The owning worker must invoke this after truncate completes. pub(crate) fn on_region_truncated(&mut self, region_id: RegionId) { + #[cfg(feature = "enterprise")] + if let Some(shared) = &mut self.shared { + shared.on_region_truncated(region_id); + } self.fail_compaction( region_id, Arc::new(RegionTruncatedSnafu { region_id }.build()), @@ -453,7 +555,23 @@ impl CompactionScheduler { let Some(status) = self.region_status.get_mut(®ion_id) else { return Err((sender, request)); }; - if !status.is_compacting() { + #[cfg(feature = "enterprise")] + let shared_running = self.shared.as_mut().is_some_and(|shared| { + let running = shared + .region_status + .get(®ion_id) + .is_some_and(CompactionStatus::is_compacting); + if running || status.is_compacting() { + shared.ddl_blocked.insert(region_id); + if let Some(s) = shared.region_status.get_mut(®ion_id) { + s.request_cancel(); + } + } + running + }); + #[cfg(not(feature = "enterprise"))] + let shared_running = false; + if !status.is_compacting() && !shared_running { return Err((sender, request)); } status.request_cancel(); @@ -509,6 +627,11 @@ impl CompactionScheduler { return Ok(false); } let region_id = version_control.region_id(); + #[cfg(feature = "enterprise")] + if self.ddl_blocked.contains(®ion_id) { + waiter.send(CompactionCancelledSnafu.fail()); + return Ok(false); + } let status = self.region_status.entry(region_id).or_insert_with(|| { CompactionStatus::new(region_id, version_control.clone(), access_layer.clone()) }); @@ -686,6 +809,10 @@ impl CompactionScheduler { if self.disable_compaction { return false; } + #[cfg(feature = "enterprise")] + if self.ddl_blocked.contains(®ion_id) { + return false; + } let Some(status) = self.region_status.get_mut(®ion_id) else { return false; }; @@ -697,7 +824,16 @@ impl CompactionScheduler { manifest_ctx, self.listener.clone(), schema_metadata_manager, - MAX_PARALLEL_COMPACTION, + { + #[cfg(feature = "enterprise")] + { + crate::compaction::compactor::experiment::automatic_parallelism() + } + #[cfg(not(feature = "enterprise"))] + { + MAX_PARALLEL_COMPACTION + } + }, ); // Bump the counter through a disjoint field borrow so the `status` // borrow stays alive; nothing could have removed the status since it @@ -763,6 +899,13 @@ impl CompactionScheduler { /// Unregisters a closed or dropped region and fails its queued requests. fn remove_region(&mut self, region_id: RegionId, err: Arc) { + #[cfg(feature = "enterprise")] + { + self.ddl_blocked.remove(®ion_id); + if let Some(shared) = &mut self.shared { + shared.remove_region(region_id, err.clone()); + } + } if let Some(mut status) = self.region_status.remove(®ion_id) { status.on_failure(err); } @@ -773,6 +916,10 @@ impl CompactionScheduler { if let Some(status) = self.region_status.get_mut(®ion_id) { status.on_failure(err); } + #[cfg(feature = "enterprise")] + if let Some(shared) = &mut self.shared { + shared.ddl_blocked.remove(®ion_id); + } } /// Returns the cycle to idle and records any DDL handoff in the same resident entry. @@ -795,6 +942,17 @@ impl CompactionScheduler { { return None; } + #[cfg(feature = "enterprise")] + if self.shared_running(region_id) { + // This lane has terminated; the other lane will hand off the DDL. + if let Some(status) = self.region_status.get_mut(®ion_id) { + for waiter in status.take_waiters() { + waiter.send(CompactionCancelledSnafu.fail()); + } + status.become_idle(); + } + return Some(Vec::new()); + } Some(self.finish_compaction_on_cancel(region_id)) } @@ -877,6 +1035,10 @@ impl CompactionScheduler { && ddl.complete(generation, request_index) { status.executing_ddl = None; + #[cfg(feature = "enterprise")] + if let Some(shared) = &mut self.shared { + shared.ddl_blocked.remove(®ion_id); + } } } } diff --git a/src/mito2/src/compaction/scheduler/hybrid.rs b/src/mito2/src/compaction/scheduler/hybrid.rs new file mode 100644 index 00000000000..a31824c9a69 --- /dev/null +++ b/src/mito2/src/compaction/scheduler/hybrid.rs @@ -0,0 +1,380 @@ +// 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. + +//! Independent shared-L0 scheduling, reusing the ordinary scheduler and file leases. +use super::*; + +// Plans and units share the existing monotonic counter. Separate ID ranges let +// existing worker notifications reach the right scheduler without wire changes. +const SHARED_PLAN: u64 = 1 << 63; + +pub(super) fn is_shared_plan(id: u64) -> bool { + id & SHARED_PLAN != 0 +} + +impl CompactionScheduler { + pub(super) fn shared_scheduler(&mut self) -> &mut Self { + if self.shared.is_none() { + let mut child = Self::new( + self.scheduler.clone(), + self.request_sender.clone(), + self.cache_manager.clone(), + self.engine_config.clone(), + self.listener.clone(), + self.plugins.clone(), + self.memory_manager.clone(), + self.memory_policy, + ); + child.shared_lane = true; + child.next_plan_id = SHARED_PLAN; + child.disable_compaction = self.disable_compaction; + self.shared = Some(Box::new(child)); + } + self.shared.as_mut().unwrap() + } + + pub(super) fn shared_running(&self, region_id: RegionId) -> bool { + self.shared + .as_ref() + .and_then(|s| s.region_status.get(®ion_id)) + .is_some_and(CompactionStatus::is_compacting) + } + + /// A shared publication wakes L1 selection immediately, even while other + /// shared units remain active. A remote L1 execution coalesces this wakeup. + pub(super) fn after_shared_event( + &mut self, + region_id: RegionId, + manifest: &ManifestContextRef, + schemas: SchemaMetadataManagerRef, + transition: CompactionTransition, + ) -> CompactionTransition { + let Some(status) = self.region_status.get(®ion_id) else { + return transition; + }; + if status.has_ddl() { + if !status.is_compacting() && !self.shared_running(region_id) { + return CompactionTransition::from_pending_ddls( + self.take_ready_ddls(region_id).unwrap_or_default(), + ); + } + return transition; + } + let version = status.version_control.clone(); + let access = status.access_layer.clone(); + if let Err(err) = self.schedule_compaction( + CompactionTrigger::Automatic, + compact_request::Options::Regular(Default::default()), + &version, + &access, + OptionOutputTx::none(), + manifest, + schemas, + crate::compaction::compactor::experiment::automatic_parallelism(), + None, + ) { + warn!(err; "Failed to schedule L1 after shared publication for region {}", region_id); + } + transition + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::compaction::scheduler::planning::CompactionPlanningResult; + use crate::test_util::version_util::VersionControlBuilder; + use crate::test_util::{mock_schema_metadata_manager, scheduler_util::SchedulerEnv}; + use tokio::sync::{mpsc, oneshot}; + + #[tokio::test] + async fn shared_planning_finishes_while_remote_l1_stays_active() { + let env = SchedulerEnv::new().await; + let (tx, _rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = Arc::new(VersionControlBuilder::new().build()); + let id = version.region_id(); + scheduler.register_region(&version, &env.access_layer); + scheduler + .region_status + .get_mut(&id) + .unwrap() + .start_remote_task(); + let remote = CompactionExecution::for_test(0); + let shared = scheduler.shared_scheduler(); + shared.register_region(&version, &env.access_layer); + shared + .region_status + .get_mut(&id) + .unwrap() + .start_picking(SHARED_PLAN); + assert!(scheduler.shared_running(id)); + assert!(scheduler.is_current_execution(id, &remote)); + let manifest = env + .mock_manifest_context(version.current().version.metadata.clone()) + .await; + let (schemas, _) = mock_schema_metadata_manager(); + scheduler + .handle_compaction_pick_finished( + CompactionPickFinished { + region_id: id, + plan_id: SHARED_PLAN, + result: CompactionPlanningResult::NoPlan, + }, + &manifest, + schemas, + ) + .await; + assert!(!scheduler.shared_running(id)); + assert!( + scheduler.is_current_execution(id, &remote), + "shared completion must not clear L1" + ); + } + + #[tokio::test] + async fn remote_completion_does_not_end_shared_work_and_close_clears_both() { + let env = SchedulerEnv::new().await; + let (tx, _rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = Arc::new(VersionControlBuilder::new().build()); + let id = version.region_id(); + scheduler.register_region(&version, &env.access_layer); + scheduler + .region_status + .get_mut(&id) + .unwrap() + .start_remote_task(); + let shared = scheduler.shared_scheduler(); + shared.register_region(&version, &env.access_layer); + shared + .region_status + .get_mut(&id) + .unwrap() + .start_picking(SHARED_PLAN); + let manifest = env + .mock_manifest_context(version.current().version.metadata.clone()) + .await; + let (schemas, _) = mock_schema_metadata_manager(); + let remote = CompactionExecution::for_test(0); + scheduler + .on_execution_finished(id, &remote, &manifest, schemas, false) + .await; + assert!(scheduler.shared_running(id)); + assert!(!scheduler.is_current_execution(id, &remote)); + scheduler.on_region_closed(id); + assert!(!scheduler.region_status.contains_key(&id)); + assert!( + !scheduler + .shared + .as_ref() + .unwrap() + .region_status + .contains_key(&id) + ); + assert!(!scheduler.can_apply_unit(id, SHARED_PLAN)); + } + + #[tokio::test] + async fn ddl_waits_for_both_lanes_without_blocking_their_terminal_callbacks() { + let env = SchedulerEnv::new().await; + let (tx, _rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = Arc::new(VersionControlBuilder::new().build()); + let id = version.region_id(); + scheduler.register_region(&version, &env.access_layer); + scheduler + .region_status + .get_mut(&id) + .unwrap() + .start_remote_task(); + let shared = scheduler.shared_scheduler(); + shared.register_region(&version, &env.access_layer); + shared + .region_status + .get_mut(&id) + .unwrap() + .start_picking(SHARED_PLAN); + let (reply, _response) = oneshot::channel(); + assert!( + scheduler + .try_cancel_and_add_ddl(id, reply.into(), (), |_| { + DdlRequest::Truncate(store_api::region_request::RegionTruncateRequest::All) + }) + .is_ok() + ); + let manifest = env + .mock_manifest_context(version.current().version.metadata.clone()) + .await; + let (schemas, _) = mock_schema_metadata_manager(); + let first = scheduler + .on_execution_finished( + id, + &CompactionExecution::for_test(0), + &manifest, + schemas.clone(), + false, + ) + .await; + assert!( + first.is_empty(), + "DDL must not execute while shared planning still owns inputs" + ); + let last = scheduler + .handle_compaction_pick_finished( + CompactionPickFinished { + region_id: id, + plan_id: SHARED_PLAN, + result: CompactionPlanningResult::NoPlan, + }, + &manifest, + schemas, + ) + .await; + assert_eq!(last.len(), 1); + assert!(scheduler.shared.as_ref().unwrap().ddl_blocked.contains(&id)); + } +} + +#[cfg(test)] +mod readiness_tests { + use super::*; + use crate::compaction::scheduler::planning::CompactionPlanningResult; + use crate::test_util::version_util::VersionControlBuilder; + use crate::test_util::{mock_schema_metadata_manager, scheduler_util::SchedulerEnv}; + use tokio::sync::{mpsc, oneshot}; + + #[tokio::test] + async fn retry_reselects_without_a_write_and_keeps_remote_l1_active() { + let env = SchedulerEnv::new().await; + let (tx, _rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = Arc::new(VersionControlBuilder::new().build()); + let id = version.region_id(); + scheduler.register_region(&version, &env.access_layer); + scheduler + .region_status + .get_mut(&id) + .unwrap() + .start_remote_task(); + let shared = scheduler.shared_scheduler(); + shared.register_region(&version, &env.access_layer); + shared + .region_status + .get_mut(&id) + .unwrap() + .start_picking(SHARED_PLAN); + shared.next_plan_id = SHARED_PLAN + 1; + let manifest = env + .mock_manifest_context(version.current().version.metadata.clone()) + .await; + let (schemas, _) = mock_schema_metadata_manager(); + let transition = scheduler + .handle_compaction_pick_finished( + CompactionPickFinished { + region_id: id, + plan_id: SHARED_PLAN, + result: CompactionPlanningResult::RetryShared, + }, + &manifest, + schemas, + ) + .await; + assert!(matches!( + transition, + CompactionTransition::AutomaticFollowupScheduled + )); + assert!(scheduler.shared.as_ref().unwrap().region_status[&id].is_picking(SHARED_PLAN + 1)); + assert!(scheduler.is_current_execution(id, &CompactionExecution::for_test(0))); + } + + #[tokio::test] + async fn retry_releases_ddl_instead_of_restarting_canceled_selection() { + let env = SchedulerEnv::new().await; + let (tx, _rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = Arc::new(VersionControlBuilder::new().build()); + let id = version.region_id(); + scheduler.register_region(&version, &env.access_layer); + let shared = scheduler.shared_scheduler(); + shared.register_region(&version, &env.access_layer); + shared + .region_status + .get_mut(&id) + .unwrap() + .start_picking(SHARED_PLAN); + let (reply, _response) = oneshot::channel(); + assert!( + scheduler + .try_cancel_and_add_ddl(id, reply.into(), (), |_| { + DdlRequest::Truncate(store_api::region_request::RegionTruncateRequest::All) + }) + .is_ok() + ); + let manifest = env + .mock_manifest_context(version.current().version.metadata.clone()) + .await; + let (schemas, _) = mock_schema_metadata_manager(); + let transition = scheduler + .handle_compaction_pick_finished( + CompactionPickFinished { + region_id: id, + plan_id: SHARED_PLAN, + result: CompactionPlanningResult::RetryShared, + }, + &manifest, + schemas, + ) + .await; + assert_eq!(transition.len(), 1); + assert!(!scheduler.shared_running(id)); + } + + #[tokio::test] + async fn stale_retry_cannot_restart_a_closed_and_reopened_region() { + let env = SchedulerEnv::new().await; + let (tx, _rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = Arc::new(VersionControlBuilder::new().build()); + let id = version.region_id(); + scheduler.register_region(&version, &env.access_layer); + let shared = scheduler.shared_scheduler(); + shared.register_region(&version, &env.access_layer); + shared + .region_status + .get_mut(&id) + .unwrap() + .start_picking(SHARED_PLAN); + scheduler.on_region_closed(id); + scheduler.register_region(&version, &env.access_layer); + scheduler + .shared_scheduler() + .register_region(&version, &env.access_layer); + let manifest = env + .mock_manifest_context(version.current().version.metadata.clone()) + .await; + let (schemas, _) = mock_schema_metadata_manager(); + let transition = scheduler + .handle_compaction_pick_finished( + CompactionPickFinished { + region_id: id, + plan_id: SHARED_PLAN, + result: CompactionPlanningResult::RetryShared, + }, + &manifest, + schemas, + ) + .await; + assert!(matches!(transition, CompactionTransition::NoAction)); + assert!(!scheduler.shared_running(id)); + assert!(!scheduler.region_status[&id].is_compacting()); + } +} diff --git a/src/mito2/src/compaction/scheduler/local.rs b/src/mito2/src/compaction/scheduler/local.rs index 8ff2a6cb150..c0e2422c29b 100644 --- a/src/mito2/src/compaction/scheduler/local.rs +++ b/src/mito2/src/compaction/scheduler/local.rs @@ -211,6 +211,13 @@ impl CompactionScheduler { /// Accepts an edit from any current unit that has started committing and is not finished. pub(crate) fn can_apply_unit(&self, region_id: RegionId, id: u64) -> bool { + #[cfg(feature = "enterprise")] + if super::hybrid::is_shared_plan(id) && !self.shared_lane { + return self + .shared + .as_ref() + .is_some_and(|s| s.can_apply_unit(region_id, id)); + } self.region_status.get(®ion_id).is_some_and(|status| { matches!(&status.active.phase, CompactionPhase::Units(local) if local.can_apply(id)) @@ -224,6 +231,13 @@ impl CompactionScheduler { id: u64, result: std::result::Result>, ) { + #[cfg(feature = "enterprise")] + if super::hybrid::is_shared_plan(id) && !self.shared_lane { + if let Some(s) = &mut self.shared { + s.on_unit_finished(region_id, id, result); + } + return; + } if let Some(local) = self.local_units_mut(region_id) { local.finish(id, result); } @@ -236,6 +250,27 @@ impl CompactionScheduler { id: u64, manifest: &ManifestContextRef, schemas: SchemaMetadataManagerRef, + ) -> CompactionTransition { + #[cfg(feature = "enterprise")] + if super::hybrid::is_shared_plan(id) && !self.shared_lane { + let Some(shared) = self.shared.as_mut() else { + return CompactionTransition::NoAction; + }; + let transition = shared + .on_unit_released_inner(region_id, id, manifest, schemas.clone()) + .await; + return self.after_shared_event(region_id, manifest, schemas, transition); + } + self.on_unit_released_inner(region_id, id, manifest, schemas) + .await + } + + async fn on_unit_released_inner( + &mut self, + region_id: RegionId, + id: u64, + manifest: &ManifestContextRef, + schemas: SchemaMetadataManagerRef, ) -> CompactionTransition { let Some(local) = self.local_units_mut(region_id) else { return CompactionTransition::NoAction; diff --git a/src/mito2/src/compaction/scheduler/planning.rs b/src/mito2/src/compaction/scheduler/planning.rs index 2cc620ebbd1..1dddb7aaeda 100644 --- a/src/mito2/src/compaction/scheduler/planning.rs +++ b/src/mito2/src/compaction/scheduler/planning.rs @@ -79,6 +79,9 @@ impl CompactionRequest { pub(crate) enum CompactionPlanningResult { Prepared(PreparedCompaction), NoPlan, + /// A shared roster/readiness miss while a full batch remains registered. + #[cfg(feature = "enterprise")] + RetryShared, Error(Arc), } @@ -90,6 +93,8 @@ impl fmt::Debug for CompactionPlanningResult { .field(&prepared.compaction_region.region_id) .finish(), Self::NoPlan => f.write_str("NoPlan"), + #[cfg(feature = "enterprise")] + Self::RetryShared => f.write_str("RetryShared"), Self::Error(err) => f.debug_tuple("Error").field(err).finish(), } } @@ -131,6 +136,8 @@ impl CompactionScheduler { max_background_compactions, time_range, trigger, + #[cfg(feature = "enterprise")] + super::hybrid::is_shared_plan(plan_id), ); Self::notify_planning_result(region_id, plan_id, request_sender, planning).await; }); @@ -185,6 +192,7 @@ impl CompactionScheduler { max_background_compactions: usize, time_range: Option, trigger: CompactionTrigger, + #[cfg(feature = "enterprise")] shared_lane: bool, ) -> CompactionPlanningResult { let region_id = request.region_id(); let (dynamic_compaction_opts, ttl) = find_dynamic_options( @@ -253,12 +261,46 @@ impl CompactionScheduler { let _pick_timer = COMPACTION_STAGE_ELAPSED .with_label_values(&["pick"]) .start_timer(); - let picker_output = match picker.pick(&compaction_region).await { + #[cfg(feature = "enterprise")] + let picked = if crate::compaction::compactor::experiment::enabled(region_id) { + if shared_lane { + crate::compaction::compactor::experiment::pick(&compaction_region).await + } else { + let mut local_only = compaction_region.clone(); + local_only.current_version.ssts = + Arc::new(local_only.current_version.ssts.without_shared_l0()); + picker.pick(&local_only).await + } + } else { + picker.pick(&compaction_region).await + }; + #[cfg(not(feature = "enterprise"))] + let picked = picker.pick(&compaction_region).await; + let picker_output = match picked { Ok(output) => output, Err(err) => return CompactionPlanningResult::Error(Arc::new(err)), }; let Some(picker_output) = picker_output else { + #[cfg(feature = "enterprise")] + if shared_lane + && crate::compaction::compactor::experiment::has_pending_shared_batch( + &compaction_region.current_version.ssts, + ) + { + // Remain in Picking, so writes coalesce and close/DDL retain the + // existing generation/cancellation handling. No compaction slot + // or SST snapshot is held during the delay. + drop(compaction_region); + drop(current_version); + drop(_pick_timer); + common_telemetry::debug!( + "hybrid_shared_ready_retry region={} delay_ms=500", + region_id + ); + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + return CompactionPlanningResult::RetryShared; + } return CompactionPlanningResult::NoPlan; }; @@ -302,6 +344,19 @@ impl CompactionScheduler { } match finished.result { + #[cfg(feature = "enterprise")] + CompactionPlanningResult::RetryShared => { + if let Some(status) = self.region_status.get_mut(®ion_id) { + status.mark_automatic_trigger(); + } + self.finish_compaction_planning( + region_id, + None, + manifest_ctx, + schema_metadata_manager, + ) + .await + } CompactionPlanningResult::Prepared(mut prepared) => { let current = status.version_control.current().version; let Some(picker_output) = @@ -444,11 +499,38 @@ impl CompactionScheduler { ttl, } = prepared; let region_id = compaction_region.region_id; - let dynamic_compaction_opts = &compaction_region.region_options.compaction; // If specified to run compaction remotely, we schedule the compaction job remotely. // It will fall back to local compaction if there is no remote job scheduler. - let waiters = if dynamic_compaction_opts.remote_compaction() { + #[cfg(feature = "enterprise")] + let shared_local = crate::compaction::compactor::experiment::enabled(region_id) + && crate::compaction::compactor::experiment::shared_inputs( + picker_output + .outputs + .iter() + .flat_map(|o| o.inputs.iter().map(|f| f.meta_ref())), + ); + #[cfg(not(feature = "enterprise"))] + let shared_local = false; + #[cfg(feature = "enterprise")] + let compaction_region = { + let mut region = compaction_region; + region.max_parallelism = crate::compaction::compactor::experiment::merge_parallelism( + region_id, + shared_local, + region.max_parallelism, + ); + common_telemetry::info!( + "hybrid_parallelism region={} shared={} max_parallelism={} outputs={}", + region_id, + shared_local, + region.max_parallelism, + picker_output.outputs.len() + ); + region + }; + let dynamic_compaction_opts = &compaction_region.region_options.compaction; + let waiters = if dynamic_compaction_opts.remote_compaction() && !shared_local { if let Some(remote_job_scheduler) = &self.plugins.get::() { let execution = CompactionExecution::new(plan_id, files.clone()); let remote_compaction_job = CompactionJob { diff --git a/src/mito2/src/compaction/twcs.rs b/src/mito2/src/compaction/twcs.rs index bcbb3314525..e382e47a767 100644 --- a/src/mito2/src/compaction/twcs.rs +++ b/src/mito2/src/compaction/twcs.rs @@ -135,7 +135,7 @@ pub struct TwcsPicker { } impl TwcsPicker { - /// Picks at most one compaction input per window and schedules them across + /// Picks disjoint active L1 groups, retaining one closed-window pick, across /// windows by [`PickClass`], newer windows first within a class. async fn build_output( &self, @@ -186,7 +186,7 @@ impl TwcsPicker { let time_windows = time_windows.clone(); let primary_key_mapper = primary_key_mapper.clone(); handles.push(common_runtime::spawn_blocking_compact(move || { - let pick = time_windows.get(&window).and_then(|files| { + let pick = time_windows.get(&window).map_or_else(Vec::new, |files| { picker.pick_window( region_id, files, @@ -194,6 +194,7 @@ impl TwcsPicker { time_window_size, region_sequence, &primary_key_mapper, + max_outputs, ) }); (window, pick) @@ -202,7 +203,7 @@ impl TwcsPicker { } for result in futures::future::join_all(handles).await { let (window, pick) = result.context(JoinSnafu)?; - picks.extend(pick.map(|pick| (window, pick))); + picks.extend(pick.into_iter().map(|pick| (window, pick))); } // Windows are visited newest first, so older windows cannot displace // a full set of picks of the first class. @@ -256,7 +257,7 @@ impl TwcsPicker { Ok(output) } - /// Picks the compaction inputs of one window, or `None` if it needs none. + /// Picks inputs of one window; closed-window overlap rules stay unchanged. fn pick_window( &self, region_id: RegionId, @@ -265,7 +266,8 @@ impl TwcsPicker { time_window_size: Option, region_sequence: u64, mapper: &PrimaryKeyRangeMapper, - ) -> Option { + max_outputs: usize, + ) -> Vec { let mut files: Vec<_> = window.files().cloned().collect(); let quiet = is_quiet_window(&files, region_sequence); @@ -290,11 +292,11 @@ impl TwcsPicker { let (l0_files, l1_files): (Vec<_>, Vec<_>) = files.into_iter().partition(|file| file.level() == 0); if !self.all_windows_inactive && active_window == Some(window.time_window) { - self.pick_active_window(l0_files, l1_files, mapper) + self.pick_active_window(l0_files, l1_files, mapper, max_outputs) } else if window.files.len() < self.inactive_window_trigger_file_num && l1_files.len() < self.inactive_window_l1_merge_trigger { - None + Vec::new() } else { let settling = !self.all_windows_inactive && is_settling_window(window.time_window, active_window, time_window_size); @@ -316,6 +318,8 @@ impl TwcsPicker { found_runs: pick.units, }) }) + .into_iter() + .collect() } } @@ -334,7 +338,8 @@ impl TwcsPicker { l0_files: Vec, l1_files: Vec, mapper: &PrimaryKeyRangeMapper, - ) -> Option { + max_outputs: usize, + ) -> Vec { if l0_files.len() >= self.trigger_file_num { let (inputs, found_runs) = pick_candidate_files( l0_files, @@ -343,24 +348,34 @@ impl TwcsPicker { mapper, ); if !inputs.is_empty() { - return Some(WindowPick { + return vec![WindowPick { class: PickClass::L0Merge, branch: "active:pick_count_first", inputs, found_runs, - }); + }]; } } if l1_files.len() < self.active_window_l1_merge_trigger { - return None; + return Vec::new(); } - let pick = units::pick_active_l1(&l1_files, mapper, self.pick_limits())?; - Some(WindowPick { - class: PickClass::FileReduction, - branch: "active:pick_l1_file_reduction", - inputs: pick.inputs, - found_runs: pick.units, - }) + // LastNonNull requires its existing overlap closure. LastRow groups + // may share key ranges but never input files; full-window tombstone + // checks below retain markers needed by sibling groups. + let limit = if self.merge_mode == MergeMode::LastRow { + max_outputs + } else { + 1 + }; + units::pick_active_l1_many(&l1_files, mapper, self.pick_limits(), limit) + .into_iter() + .map(|pick| WindowPick { + class: PickClass::FileReduction, + branch: "active:pick_l1_file_reduction", + inputs: pick.inputs, + found_runs: pick.units, + }) + .collect() } /// An inactive window should converge at a bounded rewrite cost: @@ -3379,6 +3394,87 @@ mod tests { assert!(output.is_empty()); } + #[tokio::test] + async fn test_active_l1_many_same_window_preserves_deletes() { + let files = (0..128) + .map(|idx| { + new_file_handle_with_size_and_sequence(FileId::random(), 0, 999, 1, idx + 1, 100) + }) + .collect::>(); + let windows = assign_to_windows(files.iter(), 1); + let active = windows.keys().next().copied(); + let picker = TwcsPicker { + trigger_file_num: 16, + active_window_l1_merge_trigger: 8, + inactive_window_trigger_file_num: 2, + inactive_window_l1_merge_trigger: 8, + time_window_seconds: Some(1), + max_output_file_size: None, + append_mode: false, + merge_mode: MergeMode::LastRow, + max_background_tasks: Some(8), + time_range: None, + all_windows_inactive: false, + }; + let outputs = picker + .build_output_with_time_range(RegionId::from_u64(1), windows, active, None) + .await + .unwrap(); + assert_eq!(8, outputs.len()); + let mut seen = HashSet::new(); + for output in outputs { + assert_eq!(16, output.inputs.len()); + // Sibling groups still contain old versions and deletion markers. + assert!(!output.filter_deleted); + for file in output.inputs { + assert!(seen.insert(file.file_id())); + } + } + assert_eq!(128, seen.len()); + } + + #[tokio::test] + async fn test_active_l1_many_keeps_l0_priority_and_last_non_null() { + let l1 = (0..128) + .map(|idx| { + new_file_handle_with_size_and_sequence(FileId::random(), 0, 999, 1, idx + 1, 100) + }) + .collect::>(); + let mut picker = TwcsPicker { + trigger_file_num: 2, + active_window_l1_merge_trigger: 8, + inactive_window_trigger_file_num: 2, + inactive_window_l1_merge_trigger: 8, + time_window_seconds: Some(1), + max_output_file_size: None, + append_mode: false, + merge_mode: MergeMode::LastRow, + max_background_tasks: Some(8), + time_range: None, + all_windows_inactive: false, + }; + let mut mixed = l1.clone(); + mixed.extend((0..2).map(|_| { + new_file_handle_with_size_and_sequence(FileId::random(), 0, 999, 0, 1000, 100) + })); + let windows = assign_to_windows(mixed.iter(), 1); + let active = windows.keys().next().copied(); + let output = picker + .build_output_with_time_range(RegionId::from_u64(1), windows, active, None) + .await + .unwrap(); + assert_eq!(1, output.len()); + assert!(output[0].inputs.iter().all(|f| f.level() == 0)); + picker.merge_mode = MergeMode::LastNonNull; + let windows = assign_to_windows(l1.iter(), 1); + let active = windows.keys().next().copied(); + let output = picker + .build_output_with_time_range(RegionId::from_u64(1), windows, active, None) + .await + .unwrap(); + assert_eq!(1, output.len()); + } + #[tokio::test] async fn test_active_window_l1_safety_trigger_is_independent_of_l0_trigger() { let files = (0..8) diff --git a/src/mito2/src/compaction/twcs/units.rs b/src/mito2/src/compaction/twcs/units.rs index eeb60153614..030af7e843e 100644 --- a/src/mito2/src/compaction/twcs/units.rs +++ b/src/mito2/src/compaction/twcs/units.rs @@ -175,6 +175,79 @@ fn pick_active_l1_with_budget( pick_reducing_interval(&mut units, l1_files, options) } +/// Picks disjoint input groups in one search for an active L1 window. +/// The original reduction and rewrite-cost rules apply to every group. Output +/// overlap is allowed for LastRow; tombstone filtering still uses the full +/// original window in TwcsPicker, including the other selected groups. +pub(crate) fn pick_active_l1_many( + files: &[FileHandle], + mapper: &PrimaryKeyRangeMapper, + options: PickLimits, + max_picks: usize, +) -> Vec { + if max_picks == 0 { + return Vec::new(); + } + if max_picks == 1 { + return pick_active_l1(files, mapper, options).into_iter().collect(); + } + let extents = extents_of(files, mapper); + let index = ExtentIndex::new(&extents); + let mut units = conflict_units(files, &extents, &index, CONFLICT_GRAPH_BUDGET) + .unwrap_or_else(|| single_file_units(files, &extents)); + split_oversized_units(&mut units, files, &extents, options.max_input_files); + let picks = pick_reducing_intervals(&mut units, files, options, max_picks); + if !picks.is_empty() || units.len() == files.len() { + return picks; + } + // Retain the original fallback when a large peer prevents an entire unit + // from satisfying the reduction cost, but smaller files can be merged. + split_oversized_units(&mut units, files, &extents, 1); + pick_reducing_intervals(&mut units, files, options, max_picks) +} + +fn pick_reducing_intervals( + units: &mut [Unit], + files: &[FileHandle], + options: PickLimits, + max_picks: usize, +) -> Vec { + sort_units(units); + let mut candidates = Vec::new(); + for_each_interval(units, &[], options.max_input_files, |range, stats| { + let reduction = stats + .num_files + .saturating_sub(options.predicted_outputs(stats)); + if stats.num_files >= 2 + && reduction > 0 + && options.within_reduction_cost(stats.size, reduction) + && stats.largest_file_size <= stats.size - stats.largest_file_size + { + candidates.push((Reverse(reduction), stats.size, range)); + } + }); + // Stable ordering preserves the original best pick when scores tie. + candidates.sort_by_key(|(reduction, size, _)| (*reduction, *size)); + let mut selected = vec![false; units.len()]; + let mut picks = Vec::new(); + for (_, _, range) in candidates { + if selected[range.clone()].iter().any(|used| *used) { + continue; + } + selected[range.clone()].fill(true); + picks.push(UnitPick { + inputs: collect_inputs(&units[range], files), + reduces_files: true, + units: units.len(), + dense_fallback: false, + }); + if picks.len() == max_picks { + break; + } + } + picks +} + /// Picks the interval of `units` that removes the most files within the /// rewrite budget, then rewrites the fewest bytes. fn pick_reducing_interval( @@ -1185,6 +1258,112 @@ mod tests { const MAX_OUTPUT: u64 = 16; + fn uniform_l1_files(count: usize) -> Vec { + (0..count).map(|_| file(0, 100, b"a", b"z", 2)).collect() + } + + #[test] + fn test_active_l1_many_owns_each_file_once() { + let files = uniform_l1_files(128); + let mapper = primary_key_mapper_for_test(); + let picks = pick_active_l1_many(&files, &mapper, limits(512), 8); + assert_eq!(8, picks.len()); + let mut seen = HashSet::new(); + for pick in picks { + assert_eq!(16, pick.inputs.len()); + assert!(pick.reduces_files); + for file in pick.inputs { + assert!( + seen.insert(file.file_id().file_id()), + "same input in two groups" + ); + } + } + assert_eq!(ids(&files), seen); + } + + #[test] + fn test_active_l1_many_matches_original_first_pick_and_limit() { + let files = uniform_l1_files(128); + let mapper = primary_key_mapper_for_test(); + let first = pick_active_l1(&files, &mapper, limits(512)).unwrap(); + for count in [1, 2, 4, 8] { + let picks = pick_active_l1_many(&files, &mapper, limits(512), count); + assert_eq!(count, picks.len()); + assert_eq!(ids(&first.inputs), ids(&picks[0].inputs)); + } + assert!(pick_active_l1_many(&files, &mapper, limits(512), 0).is_empty()); + } + + #[test] + fn test_active_l1_many_keeps_unmergeable_tail_and_large_peer() { + let mapper = primary_key_mapper_for_test(); + let files = uniform_l1_files(33); + let picks = pick_active_l1_many(&files, &mapper, limits(512), 8); + assert_eq!(2, picks.len()); + assert_eq!(32, picks.iter().map(|p| p.inputs.len()).sum::()); + let mut files = vec![file(0, 1000, b"a", b"z", 1 << 20)]; + files.extend(uniform_l1_files(32)); + let picks = pick_active_l1_many(&files, &mapper, limits(512), 8); + assert_eq!(2, picks.len()); + assert!( + picks + .iter() + .flat_map(|p| &p.inputs) + .all(|f| f.file_id() != files[0].file_id()) + ); + } + + #[test] + fn test_active_l1_many_rejects_nonreducing_files() { + let mapper = primary_key_mapper_for_test(); + let files = (0..32) + .map(|_| file(0, 100, b"a", b"z", 1024)) + .collect::>(); + assert!(pick_active_l1_many(&files, &mapper, limits(512), 8).is_empty()); + } + + #[test] + fn test_active_l1_many_random_windows_reduce_file_count() { + let mapper = primary_key_mapper_for_test(); + let mut rng = Rng(731); + let mut total_groups = 0; + for _ in 0..100 { + let mut files = oversized_window(&mut rng); + loop { + let handles = files.iter().map(|f| f.handle.clone()).collect::>(); + let picks = pick_active_l1_many(&handles, &mapper, limits(MAX_OUTPUT), 8); + if picks.is_empty() { + break; + } + assert!(picks.len() <= 8); + let old_count = files.len(); + let mut selected = HashSet::new(); + let mut outputs = Vec::new(); + for pick in picks { + assert!((2..=16).contains(&pick.inputs.len())); + let input_ids = ids(&pick.inputs); + for id in &input_ids { + assert!(selected.insert(*id)); + } + let inputs = files + .iter() + .filter(|f| input_ids.contains(&f.handle.file_id().file_id())) + .cloned() + .collect::>(); + let group_outputs = merge(&inputs, &mut rng); + assert!(group_outputs.len() < inputs.len()); + outputs.extend(group_outputs); + total_groups += 1; + } + files.retain(|f| !selected.contains(&f.handle.file_id().file_id())); + files.extend(outputs); + assert!(files.len() < old_count); + } + } + assert!(total_groups > 0); + } + fn file(start: i64, end: i64, min: &[u8], max: &[u8], size: u64) -> FileHandle { new_file_handle_with_size_sequence_and_primary_key_range( FileId::random(), diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index 91402711136..af81c43675c 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -44,6 +44,39 @@ 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, + }, + + #[cfg(feature = "enterprise")] + #[snafu(display("Multi-region compaction temporary run I/O failed"))] + MultiRegionCompactionSpill { + #[snafu(source)] + error: std::io::Error, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Unexpected data type"))] DataTypeMismatch { source: datatypes::error::Error, @@ -1503,6 +1536,14 @@ 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, + #[cfg(feature = "enterprise")] + MultiRegionCompactionSpill { .. } => StatusCode::Internal, DataTypeMismatch { source, .. } => source.status_code(), OpenDal { .. } | ManifestDeltaNotFound { .. } | ReadParquet { .. } => { StatusCode::StorageUnavailable diff --git a/src/mito2/src/gc.rs b/src/mito2/src/gc.rs index 8d917fbcffb..5659461f1bb 100644 --- a/src/mito2/src/gc.rs +++ b/src/mito2/src/gc.rs @@ -425,6 +425,13 @@ impl LocalGcWorker { region: Option, tmp_ref_files: &HashSet, ) -> Result { + #[cfg(feature = "enterprise")] + if crate::compaction::compactor::experiment::enabled(region_id) { + return Ok(RegionGcOutcome { + removed_files: vec![], + extension_cleanup_failed: false, + }); + } let mode = if self.full_file_listing { "full_listing" } else { diff --git a/src/mito2/src/read/flat_merge.rs b/src/mito2/src/read/flat_merge.rs index db368aedff6..c5ff1b85eb1 100644 --- a/src/mito2/src/read/flat_merge.rs +++ b/src/mito2/src/read/flat_merge.rs @@ -47,6 +47,19 @@ use crate::sst::parquet::flat_format::{ }; use crate::sst::parquet::format::{FIXED_POS_COLUMN_NUM, PrimaryKeyArray}; +macro_rules! pipeline_time { + ($name:expr, $future:expr) => {{ + #[cfg(all(test, target_os = "linux"))] + { + crate::sst::index::pipeline_profile::measure($name, $future).await + } + #[cfg(not(all(test, target_os = "linux")))] + { + $future.await + } + }}; +} + /// Checks whether interleaving the selected rows from byte columns would overflow /// i32 offsets. Similar to arrow-rs `interleave_bytes()`, accumulates offsets and /// returns an error if the capacity exceeds `i32::MAX`. @@ -361,6 +374,8 @@ impl BatchBuilder { /// /// Returns `None` if no pending rows pub fn build_record_batch(&mut self) -> Result> { + #[cfg(all(test, target_os = "linux"))] + let _timing = crate::sst::index::pipeline_profile::SyncScope::new("merge_materialize"); if self.is_empty() { return Ok(None); } @@ -796,6 +811,26 @@ impl FlatMergeIterator { schema: SchemaRef, iters: Vec, batch_size: usize, + ) -> Result { + Self::build(schema, iters, batch_size, |_| 0) + } + + /// Breaks equal row keys by input order, preserving source order across batches. + /// Callers performing multiple merge passes must supply contiguous source intervals. + #[cfg(feature = "enterprise")] + pub(crate) fn new_stable( + schema: SchemaRef, + iters: Vec, + batch_size: usize, + ) -> Result { + Self::build(schema, iters, batch_size, |index| index) + } + + fn build( + schema: SchemaRef, + iters: Vec, + batch_size: usize, + source_rank: fn(usize) -> usize, ) -> Result { let mut in_progress = BatchBuilder::new(schema, iters.len(), batch_size); let mut nodes = Vec::with_capacity(iters.len()); @@ -803,6 +838,7 @@ impl FlatMergeIterator { for (node_index, iter) in iters.into_iter().enumerate() { let mut node = IterNode { node_index, + stable_rank: source_rank(node_index), iter, cursor: None, }; @@ -943,6 +979,25 @@ impl FlatMergeReader { iters: Vec, batch_size: usize, metrics_reporter: Option>, + ) -> Result { + Self::with_source_rank(schema, iters, batch_size, metrics_reporter, |_| 0).await + } + + #[cfg(feature = "enterprise")] + pub(crate) async fn new_stable( + schema: SchemaRef, + iters: Vec, + batch_size: usize, + ) -> Result { + Self::with_source_rank(schema, iters, batch_size, None, |n| n).await + } + + async fn with_source_rank( + schema: SchemaRef, + iters: Vec, + batch_size: usize, + metrics_reporter: Option>, + rank: fn(usize) -> usize, ) -> Result { let start = Instant::now(); let metrics = MergeMetrics::default(); @@ -952,6 +1007,7 @@ impl FlatMergeReader { for (node_index, iter) in iters.into_iter().enumerate() { let mut node = StreamNode { node_index, + stable_rank: rank(node_index), iter, cursor: None, }; @@ -1010,7 +1066,7 @@ impl FlatMergeReader { /// Converts the reader into a stream. pub fn into_stream(mut self) -> impl Stream> { try_stream! { - while let Some(batch) = self.next_batch().await? { + while let Some(batch) = pipeline_time!("merge_kernel", self.next_batch())? { yield batch; } } @@ -1105,6 +1161,8 @@ impl Drop for FlatMergeReader { struct GenericNode { /// Index of the node. node_index: usize, + /// Optional source-order tie breaker; zero retains the original comparison. + stable_rank: usize, /// Iterator of this `Node`. iter: T, /// Current batch to be read. The node should ensure the batch is not empty (The @@ -1140,7 +1198,7 @@ impl NodeCmp for GenericNode { impl PartialEq for GenericNode { fn eq(&self, other: &GenericNode) -> bool { - self.cursor == other.cursor + self.cursor == other.cursor && self.stable_rank == other.stable_rank } } @@ -1156,7 +1214,10 @@ impl Ord for GenericNode { fn cmp(&self, other: &GenericNode) -> Ordering { // The std binary heap is a max heap, but we want the nodes are ordered in // ascend order, so we compare the nodes in reverse order. - other.cursor.cmp(&self.cursor) + other + .cursor + .cmp(&self.cursor) + .then_with(|| other.stable_rank.cmp(&self.stable_rank)) } } @@ -1236,7 +1297,7 @@ impl GenericNode { /// Fetches a non-empty batch from the iter. async fn advance_inner_iter(&mut self) -> Result> { - while let Some(batch) = self.iter.try_next().await? { + while let Some(batch) = pipeline_time!("merge_input_next", self.iter.try_next())? { if batch.num_rows() > 0 { return Ok(Some(batch)); } diff --git a/src/mito2/src/read/stream.rs b/src/mito2/src/read/stream.rs index 19ed37cf65f..45daac93bb7 100644 --- a/src/mito2/src/read/stream.rs +++ b/src/mito2/src/read/stream.rs @@ -35,6 +35,19 @@ use crate::read::flat_projection::FlatProjectionMapper; use crate::read::scan_util::PartitionMetrics; use crate::read::series_scan::SeriesBatch; +macro_rules! pipeline_time { + ($name:expr, $future:expr) => {{ + #[cfg(all(test, target_os = "linux"))] + { + crate::sst::index::pipeline_profile::measure($name, $future).await + } + #[cfg(not(all(test, target_os = "linux")))] + { + $future.await + } + }}; +} + /// All kinds of [`Batch`]es to produce in scanner. pub enum ScanBatch { Series(SeriesBatch), @@ -140,11 +153,12 @@ pub(crate) fn spawn_compact_stream( semaphore: Option>, ) -> BoxedRecordBatchStream { let (sender, mut receiver) = mpsc::channel(capacity); + let read_source = semaphore.is_some(); let task = common_runtime::spawn_compact(async move { loop { // Releases the permit before sending, so a full channel never holds it. let permit = match &semaphore { - Some(semaphore) => match semaphore.acquire().await { + Some(semaphore) => match pipeline_time!("read_slot_wait", semaphore.acquire()) { Ok(permit) => Some(permit), Err(e) => { let reason = format!("Failed to acquire a stream permit: {e}"); @@ -154,14 +168,31 @@ pub(crate) fn spawn_compact_stream( }, None => None, }; - let next = stream.next().await; + let next = pipeline_time!( + if read_source { + "read_produce" + } else { + "merge_produce" + }, + stream.next() + ); drop(permit); let Some(result) = next else { break; }; // Stops after forwarding the first error or once the consumer is gone. let failed = result.is_err(); - if sender.send(result).await.is_err() || failed { + if pipeline_time!( + if read_source { + "read_send_wait" + } else { + "merge_send_wait" + }, + sender.send(result) + ) + .is_err() + || failed + { break; } } @@ -170,7 +201,9 @@ pub(crate) fn spawn_compact_stream( let abort = AbortOnDrop(task.abort_handle()); Box::pin(try_stream! { let _abort = abort; - while let Some(batch) = receiver.recv().await { + while let Some(batch) = pipeline_time!( + if read_source { "merge_receive_input" } else { "writer_receive_merged" }, + receiver.recv()) { yield batch?; } task.await.context(JoinSnafu)?; diff --git a/src/mito2/src/sst/file_purger.rs b/src/mito2/src/sst/file_purger.rs index ad44c5bcc05..3eef53644c2 100644 --- a/src/mito2/src/sst/file_purger.rs +++ b/src/mito2/src/sst/file_purger.rs @@ -163,6 +163,10 @@ impl LocalFilePurger { /// Deletes the file(and it's index, if any) from cache and storage. fn delete_file(&self, file_meta: FileMeta) { + #[cfg(feature = "enterprise")] + if crate::compaction::compactor::experiment::enabled(file_meta.region_id) { + return; + } 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 { diff --git a/src/mito2/src/sst/index.rs b/src/mito2/src/sst/index.rs index 881a72ead83..9d99ab4141c 100644 --- a/src/mito2/src/sst/index.rs +++ b/src/mito2/src/sst/index.rs @@ -12,6 +12,22 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[cfg(all(test, target_os = "linux"))] +pub(crate) mod flat_profile; + +macro_rules! profile_flat { + ($name:expr, $future:expr) => {{ + #[cfg(all(test, target_os = "linux"))] + { + crate::sst::index::flat_profile::measure($name, $future).await + } + #[cfg(not(all(test, target_os = "linux")))] + { + $future.await + } + }}; +} + pub(crate) mod bloom_filter; mod column; #[cfg(test)] @@ -341,8 +357,11 @@ impl Indexer { /// Updates the index with the given flat format RecordBatch. pub async fn update_flat(&mut self, batch: &RecordBatch) { - self.do_update_flat(batch).await; + profile_flat!("update_flat", self.do_update_flat(batch)); + #[cfg(all(test, target_os = "linux"))] + flat_profile::sync("flush_mem_metrics", || self.flush_mem_metrics()); + #[cfg(not(all(test, target_os = "linux")))] self.flush_mem_metrics(); } @@ -3071,3 +3090,6 @@ mod tests { } } } + +#[cfg(all(test, target_os = "linux"))] +pub(crate) mod pipeline_profile; diff --git a/src/mito2/src/sst/index/flat_profile.rs b/src/mito2/src/sst/index/flat_profile.rs new file mode 100644 index 00000000000..564aa15195f --- /dev/null +++ b/src/mito2/src/sst/index/flat_profile.rs @@ -0,0 +1,129 @@ +// 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. + +//! Linux test-only timing. No changes to production index policy or scheduling. +//! CPU is measured around each poll, so migration between polls is safe. +use std::collections::BTreeMap; +use std::future::{Future, poll_fn}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Instant; + +use serde::Serialize; + +static ENABLED: AtomicBool = AtomicBool::new(false); +static DATA: Mutex> = Mutex::new(BTreeMap::new()); + +#[derive(Default, Serialize)] +struct Stage { + calls: u64, + polls: u64, + pending_polls: u64, + elapsed_ns: u64, + poll_wall_ns: u64, + thread_cpu_ns: u64, +} + +fn cpu_ns() -> u64 { + let mut t = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: valid writable timespec; this clock measures only the polling thread. + assert_eq!( + unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut t) }, + 0 + ); + t.tv_sec as u64 * 1_000_000_000 + t.tv_nsec as u64 +} + +pub(crate) fn start() { + DATA.lock().unwrap().clear(); + ENABLED.store(true, Ordering::Relaxed); +} + +pub(crate) fn finish() -> serde_json::Value { + ENABLED.store(false, Ordering::Relaxed); + serde_json::to_value(&*DATA.lock().unwrap()).unwrap() +} + +fn record(name: &'static str, value: Stage) { + let mut data = DATA.lock().unwrap(); + let s = data.entry(name).or_default(); + s.calls += 1; + s.polls += value.polls; + s.pending_polls += value.pending_polls; + s.elapsed_ns += value.elapsed_ns; + s.poll_wall_ns += value.poll_wall_ns; + s.thread_cpu_ns += value.thread_cpu_ns; +} + +pub(crate) async fn measure(name: &'static str, future: F) -> F::Output { + if !ENABLED.load(Ordering::Relaxed) { + return future.await; + } + let mut future = std::pin::pin!(future); + let start = Instant::now(); + let mut s = Stage::default(); + let result = poll_fn(|cx| { + let wall = Instant::now(); + let cpu = cpu_ns(); + let result = future.as_mut().poll(cx); + s.thread_cpu_ns += cpu_ns() - cpu; + s.poll_wall_ns += wall.elapsed().as_nanos() as u64; + s.polls += 1; + s.pending_polls += u64::from(result.is_pending()); + result + }) + .await; + s.elapsed_ns = start.elapsed().as_nanos() as u64; + record(name, s); + result +} + +pub(crate) fn sync(name: &'static str, f: impl FnOnce() -> T) -> T { + if !ENABLED.load(Ordering::Relaxed) { + return f(); + } + let start = Instant::now(); + let cpu = cpu_ns(); + let result = f(); + let cpu = cpu_ns() - cpu; + let elapsed = start.elapsed().as_nanos() as u64; + record( + name, + Stage { + polls: 1, + elapsed_ns: elapsed, + poll_wall_ns: elapsed, + thread_cpu_ns: cpu, + ..Default::default() + }, + ); + result +} + +#[tokio::test] +async fn pending_time_is_not_thread_cpu() { + start(); + measure( + "sleep", + tokio::time::sleep(std::time::Duration::from_millis(20)), + ) + .await; + let result = finish(); + let s = &result["sleep"]; + assert!(s["pending_polls"].as_u64().unwrap() > 0); + assert!(s["elapsed_ns"].as_u64().unwrap() > s["poll_wall_ns"].as_u64().unwrap()); +} diff --git a/src/mito2/src/sst/index/indexer/update.rs b/src/mito2/src/sst/index/indexer/update.rs index 7e2e1e35022..5351d432056 100644 --- a/src/mito2/src/sst/index/indexer/update.rs +++ b/src/mito2/src/sst/index/indexer/update.rs @@ -154,7 +154,7 @@ impl Indexer { return true; }; - let Err(err) = creator.update_flat(batch).await else { + let Err(err) = profile_flat!("inverted", creator.update_flat(batch)) else { return true; }; @@ -179,7 +179,7 @@ impl Indexer { return true; }; - let Err(err) = creator.update_flat(batch).await else { + let Err(err) = profile_flat!("fulltext", creator.update_flat(batch)) else { return true; }; @@ -204,7 +204,7 @@ impl Indexer { return true; }; - let Err(err) = creator.update_flat(batch).await else { + let Err(err) = profile_flat!("bloom", creator.update_flat(batch)) else { return true; }; diff --git a/src/mito2/src/sst/index/inverted_index/creator.rs b/src/mito2/src/sst/index/inverted_index/creator.rs index 8c12eba6348..e4795a6cf84 100644 --- a/src/mito2/src/sst/index/inverted_index/creator.rs +++ b/src/mito2/src/sst/index/inverted_index/creator.rs @@ -239,9 +239,7 @@ impl InvertedIndexer { .index_creator .push_with_name_n(target_key, value, count) { - self.index_creator - .spill() - .await + profile_flat!("inverted_spill", self.index_creator.spill()) .context(PushIndexValueSnafu)?; } } @@ -263,9 +261,7 @@ impl InvertedIndexer { .index_creator .push_with_name_n(target_key, value, count) { - self.index_creator - .spill() - .await + profile_flat!("inverted_spill", self.index_creator.spill()) .context(PushIndexValueSnafu)?; } } diff --git a/src/mito2/src/sst/index/pipeline_profile.rs b/src/mito2/src/sst/index/pipeline_profile.rs new file mode 100644 index 00000000000..a9be5e5ed83 --- /dev/null +++ b/src/mito2/src/sst/index/pipeline_profile.rs @@ -0,0 +1,183 @@ +// 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. + +//! Linux test-only pipeline timers. Parent/child and parallel durations overlap. +use std::collections::BTreeMap; +use std::future::{Future, poll_fn}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use serde::Serialize; + +static ENABLED: AtomicBool = AtomicBool::new(false); +static DATA: Mutex> = Mutex::new(BTreeMap::new()); + +#[derive(Default, Serialize)] +struct Stage { + calls: u64, + polls: u64, + pending_polls: u64, + elapsed_ns: u64, + poll_wall_ns: u64, + thread_cpu_ns: u64, + max_elapsed_ns: u64, + active: u64, + peak_active: u64, +} + +fn cpu_ns() -> u64 { + let mut t = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: valid writable timespec, sampled on the current polling thread. + assert_eq!( + unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut t) }, + 0 + ); + t.tv_sec as u64 * 1_000_000_000 + t.tv_nsec as u64 +} + +pub(crate) fn start(enabled: bool) { + DATA.lock().unwrap().clear(); + ENABLED.store(enabled, Ordering::Relaxed); +} + +pub(crate) fn finish() -> serde_json::Value { + ENABLED.store(false, Ordering::Relaxed); + serde_json::to_value(&*DATA.lock().unwrap()).unwrap() +} + +fn enter(name: &'static str) { + let mut data = DATA.lock().unwrap(); + let s = data.entry(name).or_default(); + s.active += 1; + s.peak_active = s.peak_active.max(s.active); +} + +fn record(name: &'static str, v: Stage, leave: bool) { + let mut data = DATA.lock().unwrap(); + let s = data.entry(name).or_default(); + s.calls += 1; + s.polls += v.polls; + s.pending_polls += v.pending_polls; + s.elapsed_ns += v.elapsed_ns; + s.poll_wall_ns += v.poll_wall_ns; + s.thread_cpu_ns += v.thread_cpu_ns; + s.max_elapsed_ns = s.max_elapsed_ns.max(v.elapsed_ns); + if leave { + s.active -= 1; + } +} + +pub(crate) async fn measure(name: &'static str, future: F) -> F::Output { + if !ENABLED.load(Ordering::Relaxed) { + return future.await; + } + let mut future = std::pin::pin!(future); + enter(name); + let start = Instant::now(); + let mut v = Stage::default(); + let result = poll_fn(|cx| { + let wall = Instant::now(); + let cpu = cpu_ns(); + let result = future.as_mut().poll(cx); + v.thread_cpu_ns += cpu_ns() - cpu; + v.poll_wall_ns += wall.elapsed().as_nanos() as u64; + v.polls += 1; + v.pending_polls += u64::from(result.is_pending()); + result + }) + .await; + v.elapsed_ns = start.elapsed().as_nanos() as u64; + record(name, v, true); + result +} + +/// Only use within synchronous code; never retain across `.await` or migrate threads. +pub(crate) struct SyncScope(Option<(&'static str, Instant, u64)>); + +impl SyncScope { + pub(crate) fn new(name: &'static str) -> Self { + if ENABLED.load(Ordering::Relaxed) { + enter(name); + Self(Some((name, Instant::now(), cpu_ns()))) + } else { + Self(None) + } + } +} + +impl Drop for SyncScope { + fn drop(&mut self) { + if let Some((name, wall, cpu)) = self.0 { + let cpu = cpu_ns() - cpu; + let elapsed = wall.elapsed().as_nanos() as u64; + record( + name, + Stage { + polls: 1, + elapsed_ns: elapsed, + poll_wall_ns: elapsed, + thread_cpu_ns: cpu, + ..Default::default() + }, + true, + ); + } + } +} + +pub(crate) fn queue_wait(name: &'static str, duration: Duration) { + if ENABLED.load(Ordering::Relaxed) { + record( + name, + Stage { + elapsed_ns: duration.as_nanos() as u64, + ..Default::default() + }, + false, + ); + } +} + +pub(crate) fn field_stage(field: usize) -> &'static str { + match field { + 0 => "encode_field_0", + 1 => "encode_field_1", + 2 => "encode_field_2", + 3 => "encode_field_3", + 4 => "encode_field_4", + _ => "encode_field_other", + } +} + +#[tokio::test] +async fn distinguishes_pending_from_cpu() { + start(true); + measure("test_wait", tokio::time::sleep(Duration::from_millis(20))).await; + { + let _scope = SyncScope::new("test_sync"); + std::hint::black_box(42); + } + let v = finish(); + assert!(v["test_wait"]["pending_polls"].as_u64().unwrap() > 0); + assert!( + v["test_wait"]["elapsed_ns"].as_u64().unwrap() + > v["test_wait"]["poll_wall_ns"].as_u64().unwrap() + ); + assert_eq!(v["test_sync"]["calls"], 1); + assert_eq!(v["test_sync"]["active"], 0); +} diff --git a/src/mito2/src/sst/parquet/parallel_writer.rs b/src/mito2/src/sst/parquet/parallel_writer.rs index d257574cb79..982b5165507 100644 --- a/src/mito2/src/sst/parquet/parallel_writer.rs +++ b/src/mito2/src/sst/parquet/parallel_writer.rs @@ -32,6 +32,19 @@ use parquet::file::metadata::ParquetMetaData; use parquet::file::properties::WriterProperties; use parquet::file::writer::SerializedFileWriter; +macro_rules! pipeline_time { + ($name:expr, $future:expr) => {{ + #[cfg(all(test, target_os = "linux"))] + { + crate::sst::index::pipeline_profile::measure($name, $future).await + } + #[cfg(not(all(test, target_os = "linux")))] + { + $future.await + } + }}; +} + /// Runtime whose blocking pool encodes the columns of a writer. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum EncodeRuntime { @@ -209,8 +222,19 @@ impl ParallelArrowWriter { .map(|fields| { let batches = batches.clone(); let schema = self.arrow_schema.clone(); - self.runtime - .spawn(move || encode_fields(&schema, &batches, fields)) + #[cfg(all(test, target_os = "linux"))] + let submitted = Instant::now(); + self.runtime.spawn(move || { + #[cfg(all(test, target_os = "linux"))] + crate::sst::index::pipeline_profile::queue_wait( + "encode_queue_wait", + submitted.elapsed(), + ); + #[cfg(all(test, target_os = "linux"))] + let _timing = + crate::sst::index::pipeline_profile::SyncScope::new("encode_task"); + encode_fields(&schema, &batches, fields) + }) }) .collect(); Ok(()) @@ -224,8 +248,7 @@ impl ParallelArrowWriter { let mut chunks = Vec::with_capacity(self.leaf_fields.len()); let mut tasks = mem::take(&mut self.encoding).into_iter(); while let Some(task) = tasks.next() { - let encoded = task - .await + let encoded = pipeline_time!("encode_join_wait", task) .map_err(|e| ParquetError::External(Box::new(e))) .and_then(|encoded| encoded); let (task_chunks, costs) = match encoded { @@ -240,12 +263,17 @@ impl ParallelArrowWriter { self.field_costs[field] = cost; } } + #[cfg(all(test, target_os = "linux"))] + let assembly_timing = + crate::sst::index::pipeline_profile::SyncScope::new("encode_assemble"); chunks.sort_unstable_by_key(|(leaf, _)| *leaf); let mut row_group = self.file_writer.next_row_group()?; for (_, chunk) in chunks { chunk.append_to_row_group(&mut row_group)?; } row_group.close()?; + #[cfg(all(test, target_os = "linux"))] + drop(assembly_timing); self.write_buffered_bytes().await } @@ -255,7 +283,10 @@ impl ParallelArrowWriter { if bytes.is_empty() { return Ok(()); } - self.async_writer.write(Bytes::from(bytes)).await + pipeline_time!( + "sst_output_write", + self.async_writer.write(Bytes::from(bytes)) + ) } } @@ -310,6 +341,10 @@ fn encode_fields( let mut chunks = Vec::new(); let mut costs = Vec::with_capacity(fields.len()); for (field, mut writers) in fields { + #[cfg(all(test, target_os = "linux"))] + let _timing = crate::sst::index::pipeline_profile::SyncScope::new( + crate::sst::index::pipeline_profile::field_stage(field), + ); let start = Instant::now(); for batch in batches { let leaves = compute_leaves(schema.field(field), batch.column(field))?; diff --git a/src/mito2/src/sst/parquet/reader.rs b/src/mito2/src/sst/parquet/reader.rs index 2ddb66a53f8..83f2315399f 100644 --- a/src/mito2/src/sst/parquet/reader.rs +++ b/src/mito2/src/sst/parquet/reader.rs @@ -2453,6 +2453,20 @@ impl ParquetReader { pub fn parquet_metadata(&self) -> Arc { self.context.reader_builder().parquet_meta.clone() } + + #[cfg(feature = "enterprise")] + pub(crate) fn fetched_store_page_bytes(&self) -> Result { + self.fetch_metrics + .data + .lock() + .map(|m| m.page_size_to_fetch_store) + .map_err(|_| { + crate::error::UnexpectedSnafu { + reason: "Source fetch metrics lock poisoned", + } + .build() + }) + } } /// Reader to read a row group of a parquet file in flat format, returning RecordBatch. diff --git a/src/mito2/src/sst/parquet/writer.rs b/src/mito2/src/sst/parquet/writer.rs index d7656d8c354..5647c82cc4c 100644 --- a/src/mito2/src/sst/parquet/writer.rs +++ b/src/mito2/src/sst/parquet/writer.rs @@ -214,6 +214,13 @@ pub struct ParquetWriter<'a, F: WriterFactory, I: IndexerBuilder, P: FilePathPro file_cleaner: Option, /// Write metrics metrics: &'a mut Metrics, + write_guard: Option>, +} + +/// Registers durable ownership before either an SST or its index is published to storage. +#[async_trait::async_trait] +pub trait SstWriteGuard: Send + Sync { + async fn before_create(&self, file_id: RegionFileId) -> Result<()>; } pub trait WriterFactory { @@ -227,6 +234,7 @@ pub trait WriterFactory { pub struct ObjectStoreWriterFactory { object_store: ObjectStore, + concurrency: usize, } impl WriterFactory for ObjectStoreWriterFactory { @@ -236,7 +244,7 @@ impl WriterFactory for ObjectStoreWriterFactory { self.object_store .writer_with(file_path) .chunk(write_buffer_size) - .concurrent(DEFAULT_WRITE_CONCURRENCY) + .concurrent(self.concurrency) .await .map(|v| v.into_futures_async_write().compat_write()) .context(OpenDalSnafu) @@ -248,6 +256,11 @@ where P: FilePathProvider, I: IndexerBuilder, { + pub(crate) fn with_write_concurrency(mut self, concurrency: usize) -> Self { + self.writer_factory.concurrency = concurrency; + self + } + pub async fn new_with_object_store( object_store: ObjectStore, metadata: RegionMetadataRef, @@ -257,7 +270,10 @@ where metrics: &'a mut Metrics, ) -> ParquetWriter<'a, ObjectStoreWriterFactory, I, P> { ParquetWriter::new( - ObjectStoreWriterFactory { object_store }, + ObjectStoreWriterFactory { + object_store, + concurrency: DEFAULT_WRITE_CONCURRENCY, + }, metadata, index_config, indexer_builder, @@ -289,9 +305,6 @@ where metrics: &'a mut Metrics, ) -> ParquetWriter<'a, F, I, P> { let init_file = FileId::random(); - let indexer = indexer_builder - .build(RegionFileId::new(metadata.region_id, init_file), 0, None) - .await; ParquetWriter { path_provider, @@ -301,13 +314,20 @@ where metadata, index_config, indexer_builder, - current_indexer: Some(indexer), + // Build lazily with the actual row-group size, after the write guard. + current_indexer: None, bytes_written: Arc::new(AtomicUsize::new(0)), file_cleaner: None, metrics, + write_guard: None, } } + pub(crate) fn with_write_guard(mut self, guard: Option>) -> Self { + self.write_guard = guard; + self + } + /// Finishes current SST file and index file. async fn finish_current_file( &mut self, @@ -601,6 +621,14 @@ where self.metadata.region_id, self.current_file, )); + if let Some(guard) = &self.write_guard { + guard + .before_create(RegionFileId::new( + self.metadata.region_id, + self.current_file, + )) + .await?; + } let writer = SizeAwareWriter::new( self.writer_factory .create(&sst_file_path, opts.write_buffer_size.as_bytes() as usize) diff --git a/src/mito2/src/sst/version.rs b/src/mito2/src/sst/version.rs index 5351195eefb..e2805af94ca 100644 --- a/src/mito2/src/sst/version.rs +++ b/src/mito2/src/sst/version.rs @@ -59,6 +59,17 @@ impl SstVersion { self.levels.as_ref() } + #[cfg(feature = "enterprise")] + pub(crate) fn without_shared_l0(&self) -> Self { + let mut filtered = self.clone(); + for level in Arc::make_mut(&mut filtered.levels) { + level + .files + .retain(|_, f| !crate::compaction::compactor::experiment::is_shared(f.meta_ref())); + } + filtered + } + /// Returns the current handle matching the selected file's identity in its immutable level. pub(crate) fn file_for_compaction(&self, selected: &FileHandle) -> Option<&FileHandle> { let current = self diff --git a/src/mito2/src/worker/handle_manifest.rs b/src/mito2/src/worker/handle_manifest.rs index 9510b484d84..d654d3edcc1 100644 --- a/src/mito2/src/worker/handle_manifest.rs +++ b/src/mito2/src/worker/handle_manifest.rs @@ -686,6 +686,10 @@ async fn edit_region( && preload_sst_cache { for file_meta in &edit.files_to_add { + #[cfg(feature = "enterprise")] + if crate::compaction::compactor::experiment::enabled(region_id) { + continue; + } let write_cache = write_cache.clone(); let layer = region.access_layer.clone(); let listener = listener.clone();