From 77cb39b5d18d39410e2fcab89fb3954b994b7b83 Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Tue, 10 Nov 2026 12:21:17 +0000 Subject: [PATCH 01/63] feat(mito2): record pending WAL tails in region manifests (#10308) * feat(mito2): record pending WAL tails in the region manifest Adds `pending_tails` and `handoff_floors` to the region manifest and its checkpoint, and an optional `pending_tails` / `handoff_floor` pair to `RegionEdit`. An edit without them leaves the records unchanged. A floor is dropped once the flushed entry id reaches it; a tail stays until a commit removes it. Neither is written when empty, so manifests without them encode as before. Opening a region replays its WAL after this node's tails and floor, and WAL releases at open and after a flush stay below this node's tails. Nothing writes these records yet, so every region behaves as before. Signed-off-by: jeremyhi * feat(mito2): hold back reads and region changes while WAL tails are pending A region with pending WAL tails is missing data that only those tails hold. Until they are recovered, scans and memtable and SST stats fail with the retryable `RegionPendingTails` error. Truncate, entering staging, a repartition flush, a close-time flush on request, and ALTERs other than adding nullable columns without a default or changing options are rejected before they change any region state. Compaction pauses. A full-listing GC pass skips the region while it has pending tails, or while a newer manifest may exist or the manifest listing fails. Signed-off-by: jeremyhi * docs(mito2): name the WAL releases that keep pending tails Signed-off-by: jeremyhi * fix(mito2): reject no-op ALTERs of restricted kinds while WAL tails are pending Signed-off-by: jeremyhi * test(mito2): check that reopening restores the pending-tail read gate Signed-off-by: jeremyhi * test(mito2): pin what the pending-tail fixtures and rejections promise Signed-off-by: jeremyhi * refactor(mito2): name the replay start in the open log and share the pending-tail check Signed-off-by: jeremyhi * docs(mito2): state the per-node order of pending tails and who keeps later writes out of them Signed-off-by: jeremyhi * test(mito2): check that a cancelled compaction starts nothing while WAL tails are pending When a compaction cancelled by task id finishes, the queued manual request goes through handle_pending_compaction_request, whose pending-tails check replies Ok(0). The reply is read with try_recv so that a dispatched request fails the test at once instead of hanging it. Signed-off-by: jeremyhi * fix(mito2): drop the pending compaction task state when WAL tails skip it Skipping a pending manual compaction while WAL tails are pending replied Ok(0) but left its task state in place, so task inspection kept listing it as queued and cancelling it by id still succeeded. Clear the pending task state and publish before replying. Signed-off-by: jeremyhi --------- Signed-off-by: jeremyhi --- .../src/bin/query_perf_fixture/direct_sst.rs | 2 + src/cmd/src/datanode/sst_replace.rs | 1 + .../src/region_server/catalog/inspect.rs | 1 + .../region_server/catalog/tests/manifest.rs | 2 + src/metric-engine/src/engine/sync/region.rs | 1 + src/mito2/AGENTS.md | 20 +- src/mito2/src/compaction/compactor.rs | 2 + src/mito2/src/compaction/scheduler.rs | 17 + src/mito2/src/compaction/scheduler/state.rs | 5 + src/mito2/src/compaction/scheduler_test.rs | 109 ++++- src/mito2/src/engine.rs | 28 +- .../src/engine/apply_staging_manifest_test.rs | 1 + src/mito2/src/engine/basic_test.rs | 1 + .../engine/bump_committed_sequence_test.rs | 1 + src/mito2/src/engine/catchup_test.rs | 1 + src/mito2/src/engine/edit_region_test.rs | 4 + src/mito2/src/engine/file_ref_test.rs | 2 + src/mito2/src/engine/flush_test.rs | 1 + src/mito2/src/engine/index_build_test.rs | 1 + src/mito2/src/engine/merge_mode_test.rs | 1 + src/mito2/src/engine/pending_tail_test.rs | 434 ++++++++++++++++++ src/mito2/src/engine/scan_test.rs | 3 + src/mito2/src/engine/staging_test.rs | 6 + src/mito2/src/engine/sync_test.rs | 1 + src/mito2/src/error.rs | 9 + src/mito2/src/flush.rs | 5 + src/mito2/src/gc.rs | 21 +- src/mito2/src/gc/worker_test.rs | 87 ++++ src/mito2/src/manifest/action.rs | 391 +++++++++++++++- src/mito2/src/manifest/manager.rs | 2 + src/mito2/src/manifest/tests/checkpoint.rs | 54 ++- src/mito2/src/region.rs | 3 + src/mito2/src/region/catchup.rs | 1 + src/mito2/src/region/opener.rs | 22 +- src/mito2/src/region/version.rs | 36 +- src/mito2/src/remap_manifest.rs | 4 + src/mito2/src/series_index/task.rs | 1 + src/mito2/src/series_index/tests.rs | 3 + src/mito2/src/sst/file_ref.rs | 3 +- src/mito2/src/sst/index.rs | 1 + src/mito2/src/sst/primary_key.rs | 1 + src/mito2/src/test_util.rs | 1 + src/mito2/src/test_util/version_util.rs | 1 + src/mito2/src/worker/handle_alter.rs | 20 + src/mito2/src/worker/handle_apply_staging.rs | 1 + src/mito2/src/worker/handle_close.rs | 7 + src/mito2/src/worker/handle_copy_region.rs | 1 + src/mito2/src/worker/handle_enter_staging.rs | 4 + src/mito2/src/worker/handle_flush.rs | 17 +- src/mito2/src/worker/handle_manifest.rs | 3 + src/mito2/src/worker/handle_rebuild_index.rs | 1 + src/mito2/src/worker/handle_truncate.rs | 5 + tests/compatibility/README.md | 3 + .../manifest/pending_tails/README.md | 27 ++ .../manifest/pending_tails/checkpoint.json | 1 + .../manifest/pending_tails/delta.json | 1 + 56 files changed, 1362 insertions(+), 20 deletions(-) create mode 100644 src/mito2/src/engine/pending_tail_test.rs create mode 100644 tests/compatibility/manifest/pending_tails/README.md create mode 100644 tests/compatibility/manifest/pending_tails/checkpoint.json create mode 100644 tests/compatibility/manifest/pending_tails/delta.json diff --git a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs index 0b09d1634ca..fc004c2af13 100644 --- a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs +++ b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs @@ -512,6 +512,8 @@ pub(super) async fn run_direct_sst(args: DirectArgs) { compaction_time_window: None, sst_format: format, append_mode: table.append_mode, + pending_tails: Default::default(), + handoff_floors: Default::default(), }; let checkpoint = RegionCheckpoint { last_version: args.checkpoint_version, diff --git a/src/cmd/src/datanode/sst_replace.rs b/src/cmd/src/datanode/sst_replace.rs index df13fcd6f25..d72a12a6002 100644 --- a/src/cmd/src/datanode/sst_replace.rs +++ b/src/cmd/src/datanode/sst_replace.rs @@ -208,6 +208,7 @@ impl SstReplaceCommand { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; let version = manifest_manager .update( diff --git a/src/datanode/src/region_server/catalog/inspect.rs b/src/datanode/src/region_server/catalog/inspect.rs index da3ebdb130b..875d7271b37 100644 --- a/src/datanode/src/region_server/catalog/inspect.rs +++ b/src/datanode/src/region_server/catalog/inspect.rs @@ -426,6 +426,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/datanode/src/region_server/catalog/tests/manifest.rs b/src/datanode/src/region_server/catalog/tests/manifest.rs index 91b9f757a3d..81288b506a6 100644 --- a/src/datanode/src/region_server/catalog/tests/manifest.rs +++ b/src/datanode/src/region_server/catalog/tests/manifest.rs @@ -74,6 +74,7 @@ async fn manifest_engine(regions: u32, files_per_region: usize) -> (TestEnv, Mit flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await @@ -189,6 +190,7 @@ async fn test_manifest_referring_region_and_origin_path() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/metric-engine/src/engine/sync/region.rs b/src/metric-engine/src/engine/sync/region.rs index c7b3ac8682c..dbf696db9ec 100644 --- a/src/metric-engine/src/engine/sync/region.rs +++ b/src/metric-engine/src/engine/sync/region.rs @@ -122,6 +122,7 @@ impl MetricEngineInner { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; self.mito .edit_region(target_metadata_region_id, edit) diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index 9f12cd750cd..ffd674917a2 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -82,7 +82,8 @@ pending. DDL cancellation retains its existing scheduling fence and priority. follower replay. Keep it backward compatible. Compaction task state does not belong in the manifest; publication uses ordinary file edits after locked input checks. Shared SSTs require Enterprise capability. Compatibility fixtures: - `tests/compatibility/manifest/table_compaction/`. + `tests/compatibility/manifest/table_compaction/` and + `tests/compatibility/manifest/pending_tails/`. - **SST/Parquet layout** (`sst/`): readers must stay compatible with existing files. - **Series-index disk limit**: tasks estimate usage from entry sizes in open-region snapshots and defer new builds when the shared estimate is full. Cleanup still prunes obsolete @@ -111,8 +112,21 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes depend on this. Do not change assignment lightly. - Manifest version is monotonic — never reset or skip it. - In regions whose writes require a lease and whose WAL is the object store WAL, - each manifest version has one fixed object name and only one writer can create - it (`manifest/storage.rs`). + each manifest version has one fixed object name, created conditionally. A late + create can succeed again once checkpoint cleanup frees the name, so a commit + checks its result (`ensure_version_not_checkpointed` in `manifest/storage.rs`). +- Pending tails (`RegionManifest::pending_tails`) are WAL ranges a region still has + to recover; the flushed entry id never prunes them. Opening a region replays its + WAL after `RegionManifest::wal_replay_start`. The WAL releases at open and after + a flush stay below this node's tails (`cap_wal_release`); truncate, drop, offline + cleanup and catchup release without that cap. Handoff floors are dropped once the + flushed entry id reaches them, in `RegionManifestBuilder::try_build`. While a + region has pending tails, scans and memtable/SST stats fail with + `RegionPendingTails`, and so do truncate, entering staging, a repartition flush, + a close with `flush_on_close`, and every ALTER other than adding nullable columns + without a default or changing options; compaction pauses. These checks run + before any region state changes. Full-listing GC skips a region that has pending + tails or whose manifest `has_update()` reports newer, or fails to check. - Lock ordering: take the manifest lock before updating `version_control`; the reverse deadlocks against concurrent flush/compaction. - All region I/O runs on tokio workers; never `block_on` inside a worker. diff --git a/src/mito2/src/compaction/compactor.rs b/src/mito2/src/compaction/compactor.rs index d0d2950018b..6cd51dae9a1 100644 --- a/src/mito2/src/compaction/compactor.rs +++ b/src/mito2/src/compaction/compactor.rs @@ -452,6 +452,7 @@ impl CompactionContext { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone())); @@ -1144,6 +1145,7 @@ mod tests { compaction_time_window: None, flushed_entry_id: None, flushed_sequence: None, + wal_recovery: Default::default(), })), false, ) diff --git a/src/mito2/src/compaction/scheduler.rs b/src/mito2/src/compaction/scheduler.rs index 44886f6ccdb..c7a370df623 100644 --- a/src/mito2/src/compaction/scheduler.rs +++ b/src/mito2/src/compaction/scheduler.rs @@ -577,6 +577,14 @@ impl CompactionScheduler { waiter.send(Ok(0)); return Ok(false); } + if status.has_pending_tails() { + info!( + "Skipping compaction for region {} with pending WAL tails, options: {:?}", + region_id, compact_options + ); + waiter.send(Ok(0)); + return Ok(false); + } if status.is_compacting() { match trigger { @@ -644,6 +652,12 @@ impl CompactionScheduler { let Some(pending_request) = std::mem::take(&mut status.pending_request) else { return false; }; + if status.has_pending_tails() { + status.pending_task_state = None; + status.publish_state(); + pending_request.waiter.send(Ok(0)); + return false; + } let PendingCompaction { options, @@ -737,6 +751,9 @@ impl CompactionScheduler { let Some(status) = self.region_status.get_mut(®ion_id) else { return false; }; + if status.has_pending_tails() { + return false; + } // An external automatic trigger requires one unrestricted follow-up pick. let request = status.new_compaction_request( self.request_sender.clone(), diff --git a/src/mito2/src/compaction/scheduler/state.rs b/src/mito2/src/compaction/scheduler/state.rs index 3e232138610..f0afea33b7e 100644 --- a/src/mito2/src/compaction/scheduler/state.rs +++ b/src/mito2/src/compaction/scheduler/state.rs @@ -483,6 +483,11 @@ impl CompactionStatus { !self.pending_ddl_requests.is_empty() || self.executing_ddl.is_some() } + /// Compaction pauses while the region has WAL tails to recover. + pub(crate) fn has_pending_tails(&self) -> bool { + self.version_control.current().version.has_pending_tails() + } + /// Ends the current cycle without losing region or DDL execution state. pub(crate) fn become_idle(&mut self) { self.active = ActiveCompaction::idle(); diff --git a/src/mito2/src/compaction/scheduler_test.rs b/src/mito2/src/compaction/scheduler_test.rs index a14cf1afa88..a4d310a688f 100644 --- a/src/mito2/src/compaction/scheduler_test.rs +++ b/src/mito2/src/compaction/scheduler_test.rs @@ -41,6 +41,7 @@ use crate::compaction::test_util::new_file_handle; use crate::compaction::twcs::PickClass; use crate::compaction::{CompactionOutput, find_dynamic_options}; use crate::config::MitoConfig; +use crate::engine::pending_tail_test::{pending_tails_edit, tail}; use crate::error::InvalidSchedulerStateSnafu; use crate::manifest::manager::{RegionManifestManager, RegionManifestOptions}; use crate::metrics::COMPACTION_MEMORY_REJECTED; @@ -51,9 +52,9 @@ use crate::schedule::remote_job_scheduler::{RemoteJob, RemoteJobSchedulerRef}; use crate::schedule::scheduler::{Job, Scheduler}; use crate::sst::FormatType; use crate::sst::file::FileHandle; -use crate::test_util::mock_schema_metadata_manager; use crate::test_util::scheduler_util::{SchedulerEnv, VecScheduler}; use crate::test_util::version_util::{VersionControlBuilder, apply_edit}; +use crate::test_util::{mock_schema_metadata_manager, new_noop_file_purger}; struct FailingScheduler; @@ -1193,6 +1194,7 @@ async fn test_pick_result_refreshes_replaced_selected_file() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), &[], stale.file_purger(), @@ -3360,6 +3362,7 @@ async fn test_compaction_tasks_partial_memory_admission() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), &[], builder.file_purger(), @@ -3664,6 +3667,110 @@ async fn test_compaction_tasks_linear_local_publication(#[case] reject_after_fir assert!(!scheduler.is_compacting(region_id)); } +#[tokio::test] +async fn test_finishing_compaction_with_pending_tails_starts_nothing() { + let env = SchedulerEnv::new().await; + let (tx, _rx) = mpsc::channel(4); + let mut scheduler = env.mock_compaction_scheduler(tx); + let builder = VersionControlBuilder::new(); + let version_control = Arc::new(builder.build()); + let region_id = builder.region_id(); + let manifest_ctx = env + .mock_manifest_context(version_control.current().version.metadata.clone()) + .await; + let (schema_metadata_manager, _kv_backend) = mock_schema_metadata_manager(); + let (waiter_tx, mut waiter_rx) = oneshot::channel(); + let mut status = + CompactionStatus::for_test(region_id, version_control.clone(), env.access_layer.clone()); + status.start_local_task(); + status.set_pending_request(PendingCompaction { + options: Options::Regular(Default::default()), + waiter: OptionOutputTx::from(waiter_tx), + max_parallelism: 1, + time_range: None, + }); + scheduler.region_status.insert(region_id, status); + let pending_id = scheduler.inspect_tasks(&MetadataFilter::default(), None)[0] + .task_id + .clone(); + version_control.apply_edit( + Some(pending_tails_edit(vec![tail(1, 0, 1)])), + &[], + builder.file_purger(), + ); + + scheduler + .on_compaction_finished(region_id, &manifest_ctx, schema_metadata_manager, true) + .await; + + assert_eq!(0, waiter_rx.try_recv().unwrap().unwrap()); + assert!(!scheduler.is_compacting(region_id)); + assert!( + scheduler + .inspect_tasks(&MetadataFilter::default(), None) + .is_empty() + ); + assert_eq!( + scheduler.cancel_task(region_id, &pending_id), + CancelCompactionResult::NotFound + ); +} + +#[tokio::test] +async fn test_cancelled_compaction_with_pending_tails_starts_nothing() { + let env = SchedulerEnv::new().await; + let (tx, mut rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = compactable_version(); + let region_id = version.region_id(); + let (finished, manifest, schemas) = + begin_pick_result(&env, &mut scheduler, &mut rx, &version).await; + let active_id = scheduler.inspect_tasks(&MetadataFilter::default(), None)[0] + .task_id + .clone(); + let (sender, mut receiver) = oneshot::channel(); + scheduler + .schedule_manual_compaction( + Options::Regular(Default::default()), + &version, + &env.access_layer, + sender.into(), + &manifest, + schemas.clone(), + 1, + None, + ) + .unwrap(); + let pending_id = scheduler.inspect_tasks(&MetadataFilter::default(), None)[1] + .task_id + .clone(); + assert_eq!( + scheduler.cancel_task(region_id, &active_id), + CancelCompactionResult::CancelIssued + ); + version.apply_edit( + Some(pending_tails_edit(vec![tail(1, 0, 1)])), + &[], + new_noop_file_purger(), + ); + + scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas) + .await; + + assert_eq!(0, receiver.try_recv().unwrap().unwrap()); + assert!(!scheduler.is_compacting(region_id)); + assert!( + scheduler + .inspect_tasks(&MetadataFilter::default(), None) + .is_empty() + ); + assert_eq!( + scheduler.cancel_task(region_id, &pending_id), + CancelCompactionResult::NotFound + ); +} + /// Pending task identity survives promotion, but replacement invalidates the old identity. #[tokio::test] async fn test_cancel_compaction_task_identity_and_pending() { diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 7c426c5e63b..8ff2b0f6ce0 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -63,6 +63,8 @@ mod open_test; #[cfg(test)] mod parallel_test; #[cfg(test)] +pub(crate) mod pending_tail_test; +#[cfg(test)] mod projection_test; #[cfg(test)] mod prune_test; @@ -159,7 +161,7 @@ use crate::error::{ #[cfg(feature = "enterprise")] use crate::extension::BoxedExtensionRangeProviderFactory; use crate::gc::GcLimiterRef; -use crate::manifest::action::RegionEdit; +use crate::manifest::action::{RegionEdit, WalRecoveryEdit}; use crate::memtable::MemtableStats; use crate::metrics::{ HANDLE_REQUEST_ELAPSED, SCAN_MEMORY_EXHAUSTED_TOTAL, SCAN_MEMORY_USAGE_BYTES, @@ -586,6 +588,7 @@ impl MitoEngine { .context(RegionNotFoundSnafu { region_id })?; let version = region.version(); + version.ensure_no_pending_tails()?; let memtable_stats = version .memtables .list_memtables() @@ -841,6 +844,7 @@ fn is_valid_region_edit(edit: &RegionEdit) -> bool { .. } ) + && edit.wal_recovery == WalRecoveryEdit::default() } /// Inner struct of [MitoEngine]. @@ -1172,6 +1176,7 @@ impl EngineInner { }); let version_data = region.version_control.current(); let version = version_data.version; + version.ensure_no_pending_tails()?; if request.snapshot_on_scan && request.memtable_max_sequence.is_none() { request.memtable_max_sequence = Some(version_data.committed_sequence); @@ -1889,6 +1894,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; assert!(is_valid_region_edit(&edit)); @@ -1901,6 +1907,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; assert!(!is_valid_region_edit(&edit)); @@ -1913,6 +1920,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; assert!(is_valid_region_edit(&edit)); @@ -1925,6 +1933,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; assert!(is_valid_region_edit(&edit)); @@ -1937,6 +1946,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; assert!(!is_valid_region_edit(&edit)); let edit = RegionEdit { @@ -1947,6 +1957,7 @@ mod tests { flushed_entry_id: Some(1), flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; assert!(!is_valid_region_edit(&edit)); let edit = RegionEdit { @@ -1957,6 +1968,21 @@ mod tests { flushed_entry_id: None, flushed_sequence: Some(1), committed_sequence: None, + wal_recovery: Default::default(), + }; + assert!(!is_valid_region_edit(&edit)); + let edit = RegionEdit { + files_to_add: vec![FileMeta::default()], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + wal_recovery: WalRecoveryEdit { + pending_tails: Some(vec![]), + handoff_floor: None, + }, }; assert!(!is_valid_region_edit(&edit)); } diff --git a/src/mito2/src/engine/apply_staging_manifest_test.rs b/src/mito2/src/engine/apply_staging_manifest_test.rs index e6ac2bc24b4..be6d651b48e 100644 --- a/src/mito2/src/engine/apply_staging_manifest_test.rs +++ b/src/mito2/src/engine/apply_staging_manifest_test.rs @@ -861,6 +861,7 @@ async fn test_apply_staging_manifest_change_edit_different_columns_fails_with_fo flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), ]), true, diff --git a/src/mito2/src/engine/basic_test.rs b/src/mito2/src/engine/basic_test.rs index ebc9647adc8..72f4949b12d 100644 --- a/src/mito2/src/engine/basic_test.rs +++ b/src/mito2/src/engine/basic_test.rs @@ -2216,6 +2216,7 @@ async fn add_manifest_scan_region( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; region .manifest_ctx diff --git a/src/mito2/src/engine/bump_committed_sequence_test.rs b/src/mito2/src/engine/bump_committed_sequence_test.rs index 23a5af88650..b5b7c23b8e4 100644 --- a/src/mito2/src/engine/bump_committed_sequence_test.rs +++ b/src/mito2/src/engine/bump_committed_sequence_test.rs @@ -84,6 +84,7 @@ async fn test_bump_committed_sequence_with_format(flat_format: bool) { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/mito2/src/engine/catchup_test.rs b/src/mito2/src/engine/catchup_test.rs index b470db5e12a..2e2cdad014e 100644 --- a/src/mito2/src/engine/catchup_test.rs +++ b/src/mito2/src/engine/catchup_test.rs @@ -270,6 +270,7 @@ async fn test_catchup_preserves_region_edit_sequence( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/mito2/src/engine/edit_region_test.rs b/src/mito2/src/engine/edit_region_test.rs index 68db3def4cf..f58daa55d34 100644 --- a/src/mito2/src/engine/edit_region_test.rs +++ b/src/mito2/src/engine/edit_region_test.rs @@ -137,6 +137,7 @@ async fn test_edit_region_schedule_compaction_with_format( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; engine .edit_region(region.region_id, new_edit(&[0, 10, 50, 80])) @@ -266,6 +267,7 @@ async fn test_edit_region_fill_cache( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; engine.edit_region(region.region_id, edit).await.unwrap(); @@ -775,6 +777,7 @@ fn test_region_edit(region_id: RegionId, file_id: FileId) -> RegionEdit { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), } } @@ -864,6 +867,7 @@ async fn test_edit_region_concurrently_with_format(flat_format: bool) { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; engine .edit_region(self.region.region_id, edit) diff --git a/src/mito2/src/engine/file_ref_test.rs b/src/mito2/src/engine/file_ref_test.rs index 3979c14553c..3bc1829c86b 100644 --- a/src/mito2/src/engine/file_ref_test.rs +++ b/src/mito2/src/engine/file_ref_test.rs @@ -114,6 +114,7 @@ async fn get_snapshot_preserves_related_region_old_index_readers() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })), false, ) @@ -219,6 +220,7 @@ async fn get_snapshot_preserves_old_index_readers_until_release( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })), false, ) diff --git a/src/mito2/src/engine/flush_test.rs b/src/mito2/src/engine/flush_test.rs index 399b5857700..8435a38c4a3 100644 --- a/src/mito2/src/engine/flush_test.rs +++ b/src/mito2/src/engine/flush_test.rs @@ -426,6 +426,7 @@ async fn test_ingested_parquet_bytes() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/mito2/src/engine/index_build_test.rs b/src/mito2/src/engine/index_build_test.rs index 2877ac109d9..36ae38330ae 100644 --- a/src/mito2/src/engine/index_build_test.rs +++ b/src/mito2/src/engine/index_build_test.rs @@ -700,6 +700,7 @@ async fn test_index_build_uses_physical_file_region_and_logical_manifest_region( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/mito2/src/engine/merge_mode_test.rs b/src/mito2/src/engine/merge_mode_test.rs index f5dd078103d..b628e2bab4e 100644 --- a/src/mito2/src/engine/merge_mode_test.rs +++ b/src/mito2/src/engine/merge_mode_test.rs @@ -127,6 +127,7 @@ async fn test_admitted_sst_compaction_preserves_intermediate_memtable( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/mito2/src/engine/pending_tail_test.rs b/src/mito2/src/engine/pending_tail_test.rs new file mode 100644 index 00000000000..5f2627f0633 --- /dev/null +++ b/src/mito2/src/engine/pending_tail_test.rs @@ -0,0 +1,434 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use api::v1::region::StrictWindow; +use api::v1::region::compact_request::Options; +use api::v1::{Rows, SemanticType}; +use common_error::ext::{BoxedError, ErrorExt, RetryHint}; +use common_error::status_code::StatusCode; +use common_time::Timestamp; +use datatypes::prelude::ConcreteDataType; +use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema}; +use rstest::rstest; +use store_api::logstore::provider::RaftEngineProvider; +use store_api::metadata::ColumnMetadata; +use store_api::region_engine::RegionEngine; +use store_api::region_request::{ + AddColumn, AlterKind, EnterStagingRequest, RegionAlterRequest, RegionCloseRequest, + RegionCompactRequest, RegionCreateRequest, RegionDropRequest, RegionFlushReason, + RegionFlushRequest, RegionRequest, RegionTruncateRequest, SetRegionOption, + StagingPartitionDirective, +}; +use store_api::storage::{RegionId, ScanRequest}; + +use crate::config::MitoConfig; +use crate::engine::MitoEngine; +use crate::error::Error; +use crate::manifest::action::{ + HandoffFloor, PendingTail, RegionEdit, RegionMetaAction, RegionMetaActionList, UptoKind, + WalRecoveryEdit, +}; +use crate::region::RegionLeaderState; +use crate::test_util::{ + CreateRequestBuilder, LogStoreImpl, TestEnv, build_rows, flush_region, put_rows, reopen_region, + rows_schema, +}; +use crate::wal::EntryId; + +const NODE_ID: u64 = 1; + +pub(crate) fn tail(node_id: u64, after: EntryId, upto: EntryId) -> PendingTail { + PendingTail { + node_id, + after, + upto, + upto_kind: UptoKind::Reported, + } +} + +/// Creates a region and writes one row in each of WAL entries `1..=num_entries`. +async fn create_region_with_entries( + engine: &MitoEngine, + region_id: RegionId, + num_entries: usize, +) -> RegionCreateRequest { + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request.clone())) + .await + .unwrap(); + for i in 0..num_entries { + let rows = Rows { + schema: schema.clone(), + rows: build_rows(i, i + 1), + }; + put_rows(engine, region_id, rows).await; + } + request +} + +pub(crate) fn pending_tails_edit(pending_tails: Vec) -> RegionEdit { + RegionEdit { + files_to_add: vec![], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + wal_recovery: WalRecoveryEdit { + pending_tails: Some(pending_tails), + handoff_floor: None, + }, + } +} + +async fn commit_edit(engine: &MitoEngine, region_id: RegionId, edit: RegionEdit) { + let region = engine.get_region(region_id).unwrap(); + region + .manifest_ctx + .update_manifest( + RegionLeaderState::Writable, + RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone())), + false, + ) + .await + .unwrap(); + region + .version_control + .apply_edit(Some(edit), &[], region.file_purger.clone()); +} + +pub(crate) async fn set_pending_tails( + engine: &MitoEngine, + region_id: RegionId, + pending_tails: Vec, +) { + commit_edit(engine, region_id, pending_tails_edit(pending_tails)).await; +} + +async fn reopen(engine: &MitoEngine, region_id: RegionId, request: RegionCreateRequest) { + reopen_region(engine, region_id, request.table_dir, true, request.options).await; +} + +fn wal_span(env: &TestEnv, region_id: RegionId) -> (Option, Option) { + let Some(LogStoreImpl::RaftEngine(log_store)) = env.get_log_store() else { + unreachable!() + }; + log_store.span(&RaftEngineProvider::new(region_id.into())) +} + +#[rstest] +#[case::own_tail(vec![tail(NODE_ID, 0, 2)], None, 1)] +#[case::other_node_tail(vec![tail(NODE_ID + 1, 0, 2)], None, 3)] +#[case::own_floor(vec![], Some(NODE_ID), 1)] +#[case::other_node_floor(vec![], Some(NODE_ID + 1), 3)] +#[tokio::test] +async fn test_open_replays_wal_after_own_tails_and_floor( + #[case] pending_tails: Vec, + #[case] floor_node_id: Option, + #[case] replayed_rows: u64, +) { + let mut env = TestEnv::new().await.with_node_id(NODE_ID); + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + let request = create_region_with_entries(&engine, region_id, 3).await; + let has_pending_tails = !pending_tails.is_empty(); + let mut edit = pending_tails_edit(pending_tails); + edit.wal_recovery.handoff_floor = floor_node_id.map(|node_id| HandoffFloor { + node_id, + entry_id: 2, + }); + commit_edit(&engine, region_id, edit).await; + + reopen(&engine, region_id, request).await; + + let region = engine.get_region(region_id).unwrap(); + assert_eq!(replayed_rows, region.version().memtables.num_rows()); + let scan = engine.scanner(region_id, ScanRequest::default()).await; + assert_eq!( + has_pending_tails, + matches!(scan, Err(Error::RegionPendingTails { .. })) + ); +} + +#[tokio::test] +async fn test_open_keeps_last_entry_id_at_flushed_entry_id() { + let mut env = TestEnv::new().await.with_node_id(NODE_ID); + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + let request = create_region_with_entries(&engine, region_id, 3).await; + flush_region(&engine, region_id, None).await; + let listed = PendingTail { + node_id: NODE_ID, + after: 3, + upto: 100, + upto_kind: UptoKind::Listed, + }; + set_pending_tails(&engine, region_id, vec![listed]).await; + + reopen(&engine, region_id, request).await; + + let region = engine.get_region(region_id).unwrap(); + assert_eq!(3, region.version_control.current().last_entry_id); +} + +#[tokio::test] +async fn test_flush_keeps_wal_after_own_tails() { + let mut env = TestEnv::new().await.with_node_id(NODE_ID); + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + create_region_with_entries(&engine, region_id, 3).await; + set_pending_tails(&engine, region_id, vec![tail(NODE_ID, 1, 2)]).await; + + flush_region(&engine, region_id, None).await; + + assert_eq!((Some(2), Some(3)), wal_span(&env, region_id)); +} + +#[tokio::test] +async fn test_open_keeps_wal_after_own_tails() { + let mut env = TestEnv::new().await.with_node_id(NODE_ID); + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + let request = create_region_with_entries(&engine, region_id, 3).await; + set_pending_tails(&engine, region_id, vec![tail(NODE_ID, 1, 3)]).await; + + reopen(&engine, region_id, request).await; + + assert_eq!((Some(2), Some(3)), wal_span(&env, region_id)); +} + +#[tokio::test] +async fn test_drop_releases_wal_with_pending_tails() { + let mut env = TestEnv::new().await.with_node_id(NODE_ID); + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + create_region_with_entries(&engine, region_id, 3).await; + set_pending_tails(&engine, region_id, vec![tail(NODE_ID, 0, 3)]).await; + + engine + .handle_request( + region_id, + RegionRequest::Drop(RegionDropRequest { + fast_path: false, + force: false, + partial_drop: false, + }), + ) + .await + .unwrap(); + + assert_eq!((None, None), wal_span(&env, region_id)); +} + +/// Creates a region with rows in WAL entries `1..=num_entries` and one pending tail. +async fn region_with_pending_tails(num_entries: usize) -> (TestEnv, MitoEngine, RegionId) { + let mut env = TestEnv::new().await.with_node_id(NODE_ID); + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + create_region_with_entries(&engine, region_id, num_entries).await; + set_pending_tails(&engine, region_id, vec![tail(NODE_ID, 0, 1)]).await; + (env, engine, region_id) +} + +fn assert_pending_tails_error(err: &BoxedError) { + let err = err.as_any().downcast_ref::(); + assert!( + matches!(err, Some(Error::RegionPendingTails { .. })), + "{err:?}" + ); +} + +fn add_field(default_constraint: Option) -> AlterKind { + let column_schema = ColumnSchema::new("field_1", ConcreteDataType::float64_datatype(), true) + .with_default_constraint(default_constraint) + .unwrap(); + AlterKind::AddColumns { + columns: vec![AddColumn { + column_metadata: ColumnMetadata { + column_schema, + semantic_type: SemanticType::Field, + column_id: 10, + }, + location: None, + }], + } +} + +#[tokio::test] +async fn test_scan_rejects_region_with_pending_tails() { + let (_env, engine, region_id) = region_with_pending_tails(1).await; + + let Err(err) = engine.scanner(region_id, ScanRequest::default()).await else { + panic!("scan succeeded with pending tails"); + }; + + assert!(matches!(err, Error::RegionPendingTails { .. }), "{err:?}"); + assert_eq!(StatusCode::RegionNotReady, err.status_code()); + assert_eq!(RetryHint::Retryable, err.retry_hint()); +} + +#[tokio::test] +async fn test_memtable_and_sst_stats_reject_region_with_pending_tails() { + let (_env, engine, region_id) = region_with_pending_tails(1).await; + + let result = engine.find_memtable_and_sst_stats(region_id); + + assert!(matches!(result, Err(Error::RegionPendingTails { .. }))); +} + +#[tokio::test] +async fn test_manual_compaction_skips_region_with_pending_tails() { + let (_env, engine, region_id) = region_with_pending_tails(1).await; + flush_region(&engine, region_id, None).await; + let rows = Rows { + schema: rows_schema(&CreateRequestBuilder::new().build()), + rows: build_rows(1, 2), + }; + put_rows(&engine, region_id, rows).await; + flush_region(&engine, region_id, None).await; + + let request = RegionCompactRequest { + options: Options::StrictWindow(StrictWindow { + window_seconds: 3600, + }), + ..Default::default() + }; + engine + .handle_request(region_id, RegionRequest::Compact(request)) + .await + .unwrap(); + + let region = engine.get_region(region_id).unwrap(); + assert_eq!(2, region.version().ssts.owned_num_files(region_id)); +} + +#[rstest] +#[case::all(RegionTruncateRequest::All)] +#[case::unflushed(RegionTruncateRequest::Unflushed)] +#[case::by_time_ranges(RegionTruncateRequest::ByTimeRanges { + time_ranges: vec![(Timestamp::new_millisecond(0), Timestamp::new_millisecond(1000))], +})] +#[tokio::test] +async fn test_truncate_rejects_region_with_pending_tails(#[case] request: RegionTruncateRequest) { + let (_env, engine, region_id) = region_with_pending_tails(1).await; + + let err = engine + .handle_request(region_id, RegionRequest::Truncate(request)) + .await + .unwrap_err(); + + assert_pending_tails_error(&err); + let region = engine.get_region(region_id).unwrap(); + assert_eq!(1, region.version().memtables.num_rows()); +} + +#[rstest] +#[case::nullable_column(add_field(None), true)] +#[case::region_options(AlterKind::SetRegionOptions { + options: vec![SetRegionOption::AppendMode(true)], +}, true)] +#[case::default_null_column(add_field(Some(ColumnDefaultConstraint::null_value())), false)] +#[case::drop_column(AlterKind::DropColumns { + names: vec!["field_0".to_string()], +}, false)] +#[tokio::test] +async fn test_alter_with_pending_tails(#[case] kind: AlterKind, #[case] allowed: bool) { + let (_env, engine, region_id) = region_with_pending_tails(1).await; + let metadata = engine.get_region(region_id).unwrap().metadata(); + + let result = engine + .handle_request(region_id, RegionRequest::Alter(RegionAlterRequest { kind })) + .await; + + if allowed { + result.unwrap(); + } else { + assert_pending_tails_error(&result.unwrap_err()); + let region = engine.get_region(region_id).unwrap(); + assert_eq!(metadata, region.metadata()); + assert_eq!(1, region.version().memtables.num_rows()); + } +} + +#[tokio::test] +async fn test_alter_rejects_no_op_with_pending_tails() { + let (_env, engine, region_id) = region_with_pending_tails(1).await; + let column_metadatas = engine + .get_region(region_id) + .unwrap() + .metadata() + .column_metadatas + .clone(); + + let kind = AlterKind::SyncColumns { column_metadatas }; + let err = engine + .handle_request(region_id, RegionRequest::Alter(RegionAlterRequest { kind })) + .await + .unwrap_err(); + + assert_pending_tails_error(&err); +} + +#[tokio::test] +async fn test_enter_staging_rejects_region_with_pending_tails() { + let (_env, engine, region_id) = region_with_pending_tails(1).await; + + let request = EnterStagingRequest { + partition_directive: StagingPartitionDirective::RejectAllWrites, + }; + let err = engine + .handle_request(region_id, RegionRequest::EnterStaging(request)) + .await + .unwrap_err(); + + assert_pending_tails_error(&err); + let region = engine.get_region(region_id).unwrap(); + assert!(!region.is_staging()); + assert_eq!(1, region.version().memtables.num_rows()); +} + +#[tokio::test] +async fn test_repartition_flush_rejects_region_with_pending_tails() { + let (_env, engine, region_id) = region_with_pending_tails(0).await; + + let request = RegionFlushRequest { + reason: Some(RegionFlushReason::Repartition), + ..Default::default() + }; + let err = engine + .handle_request(region_id, RegionRequest::Flush(request)) + .await + .unwrap_err(); + + assert_pending_tails_error(&err); +} + +#[tokio::test] +async fn test_close_with_flush_rejects_region_with_pending_tails() { + let (_env, engine, region_id) = region_with_pending_tails(1).await; + + let request = RegionCloseRequest { + flush_on_close: true, + }; + let err = engine + .handle_request(region_id, RegionRequest::Close(request)) + .await + .unwrap_err(); + + assert_pending_tails_error(&err); + assert!(engine.get_region(region_id).is_some()); +} diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index e495184b112..8324e3a03e5 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -3057,6 +3057,7 @@ async fn test_exact_sequence_range_unsupported_when_legacy_file() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; engine.edit_region(region_id, edit).await.unwrap(); @@ -3144,6 +3145,7 @@ async fn test_exact_sequence_range_accepts_foreign_file_with_target_barrier() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await @@ -4244,6 +4246,7 @@ async fn test_compaction_output_non_preserve_not_laundered_from_legacy_input( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/mito2/src/engine/staging_test.rs b/src/mito2/src/engine/staging_test.rs index 10351f918d9..a0501362ea8 100644 --- a/src/mito2/src/engine/staging_test.rs +++ b/src/mito2/src/engine/staging_test.rs @@ -769,6 +769,7 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await @@ -907,6 +908,7 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })]), true, ) @@ -1147,6 +1149,7 @@ async fn test_staging_exit_conflict_partition_expr_change_and_change_with_format flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), ]), true, @@ -1627,6 +1630,7 @@ fn edit_adding(file: FileMeta) -> RegionEdit { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), } } @@ -1986,6 +1990,7 @@ async fn test_successful_staging_end_keeps_rows_of_rejected_flush() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await @@ -2410,6 +2415,7 @@ async fn test_close_after_end_of_staging_is_queued_keeps_committed_result() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/mito2/src/engine/sync_test.rs b/src/mito2/src/engine/sync_test.rs index ee0cd7ebe64..1d3fff9216e 100644 --- a/src/mito2/src/engine/sync_test.rs +++ b/src/mito2/src/engine/sync_test.rs @@ -210,6 +210,7 @@ async fn test_sync_after_flush_region_with_format(flat_format: bool) { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index 5085ca8f78c..18cc8fcf814 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -730,6 +730,13 @@ pub enum Error { location: Location, }, + #[snafu(display("Region {} still has WAL tails to recover", region_id))] + RegionPendingTails { + region_id: RegionId, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Region {} does not hold a valid leader lease", region_id))] RegionLeaseExpired { region_id: RegionId, @@ -1693,6 +1700,7 @@ impl ErrorExt for Error { InvalidRegionRequest { source, .. } => source.status_code(), RegionState { .. } | UpdateManifest { .. } => StatusCode::RegionNotReady, RegionLeaseExpired { .. } | UnacknowledgedWrite { .. } => StatusCode::RegionNotReady, + RegionPendingTails { .. } => StatusCode::RegionNotReady, JsonOptions { .. } => StatusCode::InvalidArguments, EmptyRegionDir { .. } | EmptyManifestDir { .. } => StatusCode::RegionNotFound, ConvertValue { source, .. } => source.status_code(), @@ -1805,6 +1813,7 @@ impl ErrorExt for Error { | UpdateManifest { .. } | RegionStopped { .. } | RegionBusy { .. } + | RegionPendingTails { .. } | ManualCompactionAlreadyRunning { .. } | FlushableRegionState { .. } | ManifestDeltaNotFound { .. } diff --git a/src/mito2/src/flush.rs b/src/mito2/src/flush.rs index 97bdf6dbb47..d0c19c13ec8 100644 --- a/src/mito2/src/flush.rs +++ b/src/mito2/src/flush.rs @@ -533,6 +533,7 @@ impl RegionFlushTask { flushed_entry_id: Some(version_data.last_entry_id), flushed_sequence: Some(version_data.committed_sequence), committed_sequence: None, + wal_recovery: Default::default(), }; info!("Applying {edit:?} to region {}", self.region_id); @@ -1940,6 +1941,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, memtables_to_remove: smallvec![], }), @@ -2194,6 +2196,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), &[0], builder.file_purger(), @@ -2502,6 +2505,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), &[0], builder.file_purger(), @@ -2576,6 +2580,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), &[0], builder.file_purger(), diff --git a/src/mito2/src/gc.rs b/src/mito2/src/gc.rs index 227875ef3ff..3541485c25f 100644 --- a/src/mito2/src/gc.rs +++ b/src/mito2/src/gc.rs @@ -464,7 +464,8 @@ impl LocalGcWorker { ); let manifest = if let Some(region) = ®ion { - let manifest = region.manifest_ctx.manifest().await; + let manager = region.manifest_ctx.manifest_manager.read().await; + let manifest = manager.manifest(); // If the manifest version does not match, skip GC for this region to avoid deleting files that are still in use. let file_ref_manifest_version = self .file_ref_manifest @@ -487,6 +488,24 @@ impl LocalGcWorker { needs_retry: false, }); } + // SSTs written for pending tails but not committed yet, and SSTs of a newer + // manifest, are not in this snapshot, so a full listing would take them for orphans. + if self.full_file_listing + && (!manifest.pending_tails.is_empty() + || manager.has_update().await.unwrap_or_else(|e| { + warn!(e; "Failed to check manifest updates of region {}", region_id); + true + })) + { + info!( + "Skip full listing GC for region {}: it has pending WAL tails or a newer manifest may exist", + region_id + ); + return Ok(RegionGcOutcome { + removed_files: vec![], + needs_retry: false, + }); + } Some(manifest) } else { None diff --git a/src/mito2/src/gc/worker_test.rs b/src/mito2/src/gc/worker_test.rs index 55a04dbad5e..d7e41561d29 100644 --- a/src/mito2/src/gc/worker_test.rs +++ b/src/mito2/src/gc/worker_test.rs @@ -20,9 +20,13 @@ use api::v1::Rows; use async_trait::async_trait; use bytes::Bytes; use common_base::Plugins; +use common_datasource::compression::CompressionType; use common_telemetry::init_default_ut_logging; use common_time::Timestamp; use futures::TryStreamExt; +use object_store::layers::mock::{ + Error as MockError, ErrorKind, MockLayerBuilder, Result as MockResult, oio, +}; use object_store::{Entry, ObjectStore, services}; use store_api::metadata::RegionMetadataRef; use store_api::region_engine::{RegionEngine as _, RegionRole}; @@ -33,10 +37,12 @@ use crate::access_layer::AccessLayerRef; use crate::config::MitoConfig; use crate::engine::MitoEngine; use crate::engine::compaction_test::{delete_and_flush, put_and_flush}; +use crate::engine::pending_tail_test::{set_pending_tails, tail}; use crate::engine::region_hook::{RegionGcInfo, RegionHook, RegionHookRef}; use crate::error::UnexpectedSnafu; use crate::gc::{GcConfig, LocalGcWorker, should_delete_file}; use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList, RemovedFile}; +use crate::manifest::storage::{delta_file, gen_path}; use crate::metrics::GC_SKIPPED_UNPARSABLE_FILES; use crate::region::{MitoRegionRef, RegionLeaderState}; use crate::sst::file::{ColumnIndexMetadata, FileHandle, FileMeta, IndexType, RegionIndexId}; @@ -319,6 +325,7 @@ async fn test_gc_reclaims_obsolete_index_after_readers_and_linger_release( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })), false, ) @@ -1788,3 +1795,83 @@ async fn test_on_region_gc_failure_routes_region_to_retry() { "a failed extension cleanup must not report deleted_files for the region" ); } + +struct FailingLister; + +impl oio::List for FailingLister { + async fn next(&mut self) -> MockResult> { + Err(MockError::new(ErrorKind::Unexpected, "mock list failure")) + } +} + +#[rstest::rstest] +#[case::pending_tails("pending_tails")] +#[case::newer_manifest("newer_manifest")] +#[case::manifest_list_failure("manifest_list_failure")] +#[tokio::test] +async fn test_full_listing_gc_skips_region(#[case] cause: &str) { + let fail_manifest_lists = Arc::new(AtomicBool::new(false)); + let fail = fail_manifest_lists.clone(); + let mock_layer = MockLayerBuilder::default() + .lister_factory(Arc::new(move |path, _, inner| { + if fail.load(Ordering::Relaxed) && path.contains("/manifest/") { + Box::new(FailingLister) + } else { + inner + } + })) + .build() + .unwrap(); + let mut env = TestEnv::new().await.with_mock_layer(mock_layer); + let hook = Arc::new(GcCountingHook::default()); + let plugins = Plugins::new(); + plugins.insert(hook.clone() as RegionHookRef); + let config = MitoConfig { + gc: GcConfig { + enable: true, + ..Default::default() + }, + ..Default::default() + }; + let engine = env.create_engine_with_plugins(config, plugins).await; + let region_id = RegionId::new(1, 1); + engine + .handle_request( + region_id, + RegionRequest::Create(CreateRequestBuilder::new().build()), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let run_gc = async || { + let file_ref_manifest = FileRefsManifest { + file_refs: Default::default(), + manifest_version: [(region_id, region.manifest_ctx.manifest_version().await)].into(), + cross_region_refs: HashMap::new(), + }; + let regions = BTreeMap::from([(region_id, Some(region.clone()))]); + let gc_worker = create_gc_worker(&engine, regions, &file_ref_manifest, true).await; + gc_worker.run().await.unwrap(); + }; + run_gc().await; + assert_eq!(1, hook.gc_calls.load(Ordering::Relaxed)); + + match cause { + "pending_tails" => set_pending_tails(&engine, region_id, vec![tail(1, 0, 1)]).await, + "newer_manifest" => { + let store = region.manifest_ctx.manifest_manager.read().await.store(); + let version = region.manifest_ctx.manifest_version().await; + let path = gen_path( + store.manifest_dir(), + &delta_file(version + 1), + CompressionType::Uncompressed, + ); + let object_store = region.access_layer.object_store(); + object_store.write(&path, b"".as_slice()).await.unwrap(); + } + _ => fail_manifest_lists.store(true, Ordering::Relaxed), + } + run_gc().await; + + assert_eq!(1, hook.gc_calls.load(Ordering::Relaxed)); +} diff --git a/src/mito2/src/manifest/action.rs b/src/mito2/src/manifest/action.rs index 5d5620bdab8..cd00237087a 100644 --- a/src/mito2/src/manifest/action.rs +++ b/src/mito2/src/manifest/action.rs @@ -14,7 +14,7 @@ //! Defines [RegionMetaAction] related structs and [RegionCheckpoint]. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::time::Duration; use chrono::Utc; @@ -95,6 +95,62 @@ pub struct RegionEdit { pub flushed_entry_id: Option, pub flushed_sequence: Option, pub committed_sequence: Option, + #[serde(flatten)] + pub wal_recovery: WalRecoveryEdit, +} + +/// Changes an edit makes to the WAL ranges the region still has to recover. +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] +pub struct WalRecoveryEdit { + /// The new [RegionManifest::pending_tails], whose segments of each node keep the + /// order and bounds described there. `None` keeps them unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pending_tails: Option>, + /// Replaces the handoff floor of one node. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub handoff_floor: Option, +} + +/// WAL entries of one node in `(after, upto]` that the region still has to recover. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct PendingTail { + /// Id of the datanode whose WAL holds the entries. + pub node_id: u64, + pub after: EntryId, + pub upto: EntryId, + pub upto_kind: UptoKind, +} + +/// Where the upper bound of a [PendingTail] comes from. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum UptoKind { + /// The last entry id the node reported, which names an entry that can be replayed. + Reported, + /// An upper bound found by listing the WAL objects of the node, which may name no entry. + Listed, +} + +/// Entries of a node at or below `entry_id` are never recovered from its WAL, except +/// those in a pending tail of the node. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +pub struct HandoffFloor { + pub node_id: u64, + pub entry_id: EntryId, +} + +/// Caps a release of the WAL of node `node_id` at `entry_id`, so that it keeps every +/// pending tail of the node. +pub(crate) fn cap_wal_release( + pending_tails: &[PendingTail], + node_id: Option, + entry_id: EntryId, +) -> EntryId { + pending_tails + .iter() + .filter(|tail| Some(tail.node_id) == node_id) + .map(|tail| tail.after) + .fold(entry_id, EntryId::min) } impl RegionEdit { @@ -191,6 +247,38 @@ pub struct RegionManifest { /// Whether the region is in append mode. #[serde(default)] pub append_mode: Option, + /// WAL ranges the region still has to recover, in the order they were added. + /// + /// The segments of one node are increasing and do not overlap, and each has + /// `after < upto`: a new segment of a node takes as `after` the largest of the + /// flushed entry id, the `upto`s of the node's existing segments and its handoff + /// floor, and is added only if that is below its `upto`. So the entries of a node + /// between two of its segments are flushed or at or below a handoff floor of the + /// node, and need no replay. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub pending_tails: Vec, + /// The [HandoffFloor] of each node, removed once the flushed entry id reaches it. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub handoff_floors: BTreeMap, +} + +impl RegionManifest { + /// Returns the entry id after which node `node_id` replays its WAL when it opens + /// the region. Entries up to it are flushed, left to the pending tails, or below + /// the handoff floor of the node. + /// + /// Entries of the node in `(after, upto]` of one of its tails belong to that tail. + /// Whoever adds a tail ensures that every entry id the node allocates afterwards is + /// above the tail's `upto`, so no later write of the node falls in a skipped range. + pub(crate) fn wal_replay_start(&self, node_id: Option) -> EntryId { + let floor = node_id.and_then(|node_id| self.handoff_floors.get(&node_id).copied()); + self.pending_tails + .iter() + .filter(|tail| Some(tail.node_id) == node_id) + .map(|tail| tail.upto) + .chain(floor) + .fold(self.flushed_entry_id, EntryId::max) + } } #[cfg(test)] @@ -204,6 +292,8 @@ impl PartialEq for RegionManifest { && self.truncated_entry_id == other.truncated_entry_id && self.compaction_time_window == other.compaction_time_window && self.committed_sequence == other.committed_sequence + && self.pending_tails == other.pending_tails + && self.handoff_floors == other.handoff_floors } } @@ -229,6 +319,8 @@ pub struct RegionManifestBuilder { committed_sequence: Option, sst_format: FormatType, append_mode: Option, + pending_tails: Vec, + handoff_floors: BTreeMap, } impl RegionManifestBuilder { @@ -256,6 +348,8 @@ impl RegionManifestBuilder { committed_sequence: s.committed_sequence, sst_format: s.sst_format, append_mode: s.append_mode, + pending_tails: s.pending_tails, + handoff_floors: s.handoff_floors, } } else { Default::default() @@ -335,6 +429,12 @@ impl RegionManifestBuilder { if let Some(window) = edit.compaction_time_window { self.compaction_time_window = Some(window); } + if let Some(pending_tails) = edit.wal_recovery.pending_tails { + self.pending_tails = pending_tails; + } + if let Some(floor) = edit.wal_recovery.handoff_floor { + self.handoff_floors.insert(floor.node_id, floor.entry_id); + } } pub fn apply_truncate(&mut self, manifest_version: ManifestVersion, truncate: RegionTruncate) { @@ -389,8 +489,11 @@ impl RegionManifestBuilder { self.metadata.is_some() } - pub fn try_build(self) -> Result { + pub fn try_build(mut self) -> Result { let metadata = self.metadata.context(RegionMetadataNotFoundSnafu)?; + // A floor at or below the flushed entry id no longer raises the replay start. + self.handoff_floors + .retain(|_, floor| *floor > self.flushed_entry_id); Ok(RegionManifest { metadata, files: self.files, @@ -403,6 +506,8 @@ impl RegionManifestBuilder { compaction_time_window: self.compaction_time_window, sst_format: self.sst_format, append_mode: self.append_mode, + pending_tails: self.pending_tails, + handoff_floors: self.handoff_floors, }) } } @@ -597,6 +702,7 @@ impl RegionMetaActionList { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; let mut partition_expr_change = None; let mut region_change = None; @@ -655,6 +761,7 @@ impl RegionMetaActionList { #[cfg(test)] mod tests { + use std::sync::Arc; use common_time::Timestamp; @@ -991,6 +1098,8 @@ mod tests { }, sst_format: FormatType::PrimaryKey, append_mode: None, + pending_tails: Default::default(), + handoff_floors: Default::default(), }; let json = serde_json::to_string(&manifest).unwrap(); @@ -1026,6 +1135,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ); builder.apply_edit( @@ -1038,6 +1148,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ); @@ -1057,6 +1168,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ); builder.apply_truncate( @@ -1171,6 +1283,8 @@ mod tests { compaction_time_window: None, sst_format: FormatType::PrimaryKey, append_mode: None, + pending_tails: Default::default(), + handoff_floors: Default::default(), } ); @@ -1186,6 +1300,8 @@ mod tests { compaction_time_window: None, sst_format: FormatType::PrimaryKey, append_mode: None, + pending_tails: Default::default(), + handoff_floors: Default::default(), }; let json = serde_json::to_string(&new_manifest).unwrap(); let old_from_new: RegionManifestV1 = serde_json::from_str(&json).unwrap(); @@ -1230,6 +1346,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, new_from_old ); @@ -1243,6 +1360,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; let new_json = serde_json::to_string(&new).unwrap(); @@ -1403,4 +1521,273 @@ mod tests { .contains(&RemovedFile::File(file_id, None)) ); } + + fn tail(node_id: u64, after: EntryId, upto: EntryId) -> PendingTail { + PendingTail { + node_id, + after, + upto, + upto_kind: UptoKind::Reported, + } + } + + fn wal_recovery_edit( + flushed_entry_id: Option, + wal_recovery: WalRecoveryEdit, + ) -> RegionEdit { + RegionEdit { + files_to_add: vec![], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id, + flushed_sequence: None, + committed_sequence: None, + wal_recovery, + } + } + + fn manifest_builder() -> RegionManifestBuilder { + let mut builder = RegionManifestBuilder::default(); + builder.apply_change( + 0, + RegionChange { + metadata: Arc::new(crate::manifest::tests::utils::basic_region_metadata()), + sst_format: FormatType::PrimaryKey, + append_mode: None, + }, + ); + builder + } + + #[test] + fn test_pending_tails_change_only_when_set() { + let mut builder = manifest_builder(); + builder.apply_edit( + 1, + wal_recovery_edit( + None, + WalRecoveryEdit { + pending_tails: Some(vec![tail(1, 10, 20)]), + handoff_floor: None, + }, + ), + ); + builder.apply_edit(2, wal_recovery_edit(Some(5), WalRecoveryEdit::default())); + assert_eq!(builder.pending_tails, vec![tail(1, 10, 20)]); + + builder.apply_edit( + 3, + wal_recovery_edit( + None, + WalRecoveryEdit { + pending_tails: Some(vec![]), + handoff_floor: None, + }, + ), + ); + assert!(builder.pending_tails.is_empty()); + } + + #[test] + fn test_flushed_entry_id_drops_reached_floors_and_keeps_tails() { + let mut builder = manifest_builder(); + for (node_id, entry_id) in [(1, 20), (2, 30)] { + builder.apply_edit( + 1, + wal_recovery_edit( + None, + WalRecoveryEdit { + pending_tails: Some(vec![tail(1, 10, 20)]), + handoff_floor: Some(HandoffFloor { node_id, entry_id }), + }, + ), + ); + } + builder.apply_edit(2, wal_recovery_edit(Some(20), WalRecoveryEdit::default())); + + let manifest = builder.try_build().unwrap(); + assert_eq!(manifest.pending_tails, vec![tail(1, 10, 20)]); + assert_eq!(manifest.handoff_floors, BTreeMap::from([(2, 30)])); + } + + #[test] + fn test_truncate_drops_reached_floors() { + let mut builder = manifest_builder(); + builder.apply_edit( + 1, + wal_recovery_edit( + None, + WalRecoveryEdit { + pending_tails: None, + handoff_floor: Some(HandoffFloor { + node_id: 1, + entry_id: 20, + }), + }, + ), + ); + builder.apply_truncate( + 2, + RegionTruncate { + region_id: RegionId::new(1, 1), + kind: TruncateKind::All { + truncated_entry_id: 20, + truncated_sequence: 20, + }, + timestamp_ms: None, + }, + ); + + assert!(builder.try_build().unwrap().handoff_floors.is_empty()); + } + + #[test] + fn test_wal_replay_start() { + let mut builder = manifest_builder(); + // Node 1 was handed off at 40 after its first tail, so its second tail starts + // there and entries in (20, 40] belong to no tail. + builder.apply_edit( + 1, + wal_recovery_edit( + Some(10), + WalRecoveryEdit { + pending_tails: Some(vec![tail(1, 10, 20), tail(2, 30, 60), tail(1, 40, 50)]), + handoff_floor: Some(HandoffFloor { + node_id: 1, + entry_id: 40, + }), + }, + ), + ); + builder.apply_edit( + 2, + wal_recovery_edit( + None, + WalRecoveryEdit { + pending_tails: None, + handoff_floor: Some(HandoffFloor { + node_id: 3, + entry_id: 40, + }), + }, + ), + ); + let manifest = builder.try_build().unwrap(); + + assert_eq!(manifest.wal_replay_start(Some(1)), 50); + assert_eq!(manifest.wal_replay_start(Some(2)), 60); + assert_eq!(manifest.wal_replay_start(Some(3)), 40); + assert_eq!(manifest.wal_replay_start(Some(4)), 10); + assert_eq!(manifest.wal_replay_start(None), 10); + } + + #[test] + fn test_cap_wal_release() { + let tails = [tail(1, 20, 25), tail(2, 5, 60), tail(1, 30, 40)]; + + assert_eq!(cap_wal_release(&tails, Some(1), 50), 20); + assert_eq!(cap_wal_release(&tails, Some(1), 10), 10); + assert_eq!(cap_wal_release(&tails, Some(3), 50), 50); + assert_eq!(cap_wal_release(&tails, None, 50), 50); + } + + const PENDING_TAILS_DELTA: &str = + include_str!("../../../../tests/compatibility/manifest/pending_tails/delta.json"); + const PENDING_TAILS_CHECKPOINT: &str = + include_str!("../../../../tests/compatibility/manifest/pending_tails/checkpoint.json"); + + fn fixture_pending_tails() -> Vec { + vec![ + tail(1, 1 << 32, (1 << 32) + 5), + PendingTail { + upto_kind: UptoKind::Listed, + ..tail(2, 2 << 32, 3 << 32) + }, + ] + } + + #[test] + fn test_pending_tails_fixtures() { + let delta = PENDING_TAILS_DELTA.trim_end(); + let actions = RegionMetaActionList::decode(delta.as_bytes()).unwrap(); + let [RegionMetaAction::Edit(edit)] = actions.actions.as_slice() else { + panic!("unexpected actions: {actions:?}"); + }; + let expected = WalRecoveryEdit { + pending_tails: Some(fixture_pending_tails()), + handoff_floor: Some(HandoffFloor { + node_id: 3, + entry_id: 4 << 32, + }), + }; + assert_eq!(edit.wal_recovery, expected); + assert_eq!(actions.encode().unwrap(), delta.as_bytes()); + + let checkpoint = PENDING_TAILS_CHECKPOINT.trim_end(); + let decoded = RegionCheckpoint::decode(checkpoint.as_bytes()).unwrap(); + let manifest = decoded.checkpoint.as_ref().unwrap(); + assert_eq!(manifest.pending_tails, fixture_pending_tails()); + assert_eq!(manifest.handoff_floors, BTreeMap::from([(3, 4 << 32)])); + let encoded: serde_json::Value = + serde_json::from_slice(&decoded.encode().unwrap()).unwrap(); + let frozen: serde_json::Value = serde_json::from_str(checkpoint).unwrap(); + for key in ["pending_tails", "handoff_floors"] { + assert_eq!(encoded["checkpoint"][key], frozen["checkpoint"][key]); + } + } + + /// Checks the fixtures against the shapes before pending tails were added. + #[test] + fn test_pending_tails_old_shape_compat() { + #[derive(Serialize, Deserialize)] + struct OldRegionEdit { + files_to_add: Vec, + files_to_remove: Vec, + #[serde(default)] + timestamp_ms: Option, + #[serde(with = "humantime_serde")] + compaction_time_window: Option, + flushed_entry_id: Option, + flushed_sequence: Option, + committed_sequence: Option, + } + + #[derive(Serialize, Deserialize)] + struct OldRegionManifest { + metadata: RegionMetadataRef, + files: HashMap, + #[serde(default)] + removed_files: RemovedFilesRecord, + flushed_entry_id: EntryId, + flushed_sequence: SequenceNumber, + committed_sequence: Option, + manifest_version: ManifestVersion, + truncated_entry_id: Option, + #[serde(with = "humantime_serde")] + compaction_time_window: Option, + #[serde(default)] + sst_format: FormatType, + #[serde(default)] + append_mode: Option, + } + + let delta: serde_json::Value = serde_json::from_str(PENDING_TAILS_DELTA).unwrap(); + let old_edit: OldRegionEdit = + serde_json::from_value(delta["actions"][0]["Edit"].clone()).unwrap(); + assert_eq!(old_edit.committed_sequence, Some((1 << 40) + 5)); + let old_json = serde_json::to_string(&old_edit).unwrap(); + let edit: RegionEdit = serde_json::from_str(&old_json).unwrap(); + assert_eq!(edit.wal_recovery, WalRecoveryEdit::default()); + assert_eq!(serde_json::to_string(&edit).unwrap(), old_json); + + let checkpoint: serde_json::Value = serde_json::from_str(PENDING_TAILS_CHECKPOINT).unwrap(); + let old_manifest: OldRegionManifest = + serde_json::from_value(checkpoint["checkpoint"].clone()).unwrap(); + assert_eq!(old_manifest.flushed_entry_id, 1 << 32); + let old_json = serde_json::to_string(&old_manifest).unwrap(); + let manifest: RegionManifest = serde_json::from_str(&old_json).unwrap(); + assert!(manifest.pending_tails.is_empty() && manifest.handoff_floors.is_empty()); + assert_eq!(serde_json::to_string(&manifest).unwrap(), old_json); + } } diff --git a/src/mito2/src/manifest/manager.rs b/src/mito2/src/manifest/manager.rs index 7531c433191..5cebfbc9b11 100644 --- a/src/mito2/src/manifest/manager.rs +++ b/src/mito2/src/manifest/manager.rs @@ -234,6 +234,7 @@ impl RegionManifestManager { flushed_entry_id: Some(flushed_entry_id), flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })); } @@ -1067,6 +1068,7 @@ mod test { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })]), false, ) diff --git a/src/mito2/src/manifest/tests/checkpoint.rs b/src/mito2/src/manifest/tests/checkpoint.rs index 72f4377221f..708ca51ceb4 100644 --- a/src/mito2/src/manifest/tests/checkpoint.rs +++ b/src/mito2/src/manifest/tests/checkpoint.rs @@ -28,7 +28,8 @@ use strum::IntoEnumIterator; use crate::error::Error::{ChecksumMismatch, ManifestDeltaNotFound}; use crate::manifest::action::{ - RegionCheckpoint, RegionEdit, RegionMetaAction, RegionMetaActionList, + HandoffFloor, PendingTail, RegionCheckpoint, RegionEdit, RegionMetaAction, + RegionMetaActionList, UptoKind, WalRecoveryEdit, }; use crate::manifest::manager::RegionManifestManager; use crate::manifest::storage::checkpoint::CheckpointMetadata; @@ -185,6 +186,55 @@ async fn manager_with_checkpoint_distance_1() { assert_eq!(10, manager.manifest().manifest_version); } +#[rstest::rstest] +#[case::delta(0)] +#[case::checkpoint(1)] +#[tokio::test] +async fn wal_recovery_records_survive_reopen(#[case] checkpoint_distance: u64) { + let (env, mut manager) = + build_manager(checkpoint_distance, CompressionType::Uncompressed).await; + let pending_tails = vec![PendingTail { + node_id: 1, + after: 10, + upto: 20, + upto_kind: UptoKind::Listed, + }]; + let edit = RegionEdit { + files_to_add: vec![], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: Some(1 << 40), + wal_recovery: WalRecoveryEdit { + pending_tails: Some(pending_tails.clone()), + handoff_floor: Some(HandoffFloor { + node_id: 1, + entry_id: 30, + }), + }, + }; + manager + .update( + RegionMetaActionList::with_action(RegionMetaAction::Edit(edit)), + false, + ) + .await + .unwrap(); + wait_for_manifest_checkpoint(&manager).await; + let checkpoint = manager.store().load_last_checkpoint().await.unwrap(); + assert_eq!(checkpoint.is_some(), checkpoint_distance > 0); + manager.stop().await; + + let manifest = reopen_manager(&env, checkpoint_distance, CompressionType::Uncompressed) + .await + .manifest(); + assert_eq!(manifest.pending_tails, pending_tails); + assert_eq!(manifest.handoff_floors, [(1, 30)].into()); + assert_eq!(manifest.committed_sequence, Some(1 << 40)); +} + #[tokio::test] async fn test_corrupted_data_causing_checksum_error() { // Initialize manager @@ -266,6 +316,7 @@ async fn checkpoint_with_different_compression_types() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })]); actions.push(action); } @@ -332,6 +383,7 @@ fn generate_action_lists(num: usize) -> (Vec, Vec) flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })]); actions.push(action); } diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index c092c7ef4e7..2282eba0036 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -1509,6 +1509,7 @@ impl ManifestContext { flushed_entry_id: None, committed_sequence: None, compaction_time_window: None, + wal_recovery: Default::default(), }; let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit)); let manifest_version = self.update_and_fire(manager, action_list, false).await?; @@ -2526,6 +2527,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), } } @@ -2567,6 +2569,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })); region diff --git a/src/mito2/src/region/catchup.rs b/src/mito2/src/region/catchup.rs index 4b8f1288c4b..144dbc0e23e 100644 --- a/src/mito2/src/region/catchup.rs +++ b/src/mito2/src/region/catchup.rs @@ -107,6 +107,7 @@ impl RegionCatchupTask { wal_entry_reader, region_id, replay_from_entry_id, + replay_from_entry_id, &self.region.version_control, self.allow_stale_entries, on_region_opened, diff --git a/src/mito2/src/region/opener.rs b/src/mito2/src/region/opener.rs index 85881028ab9..c306c9198c9 100644 --- a/src/mito2/src/region/opener.rs +++ b/src/mito2/src/region/opener.rs @@ -56,7 +56,7 @@ use crate::error::{ ObjectStoreNotFoundSnafu, RegionCorruptedSnafu, Result, StaleLogEntrySnafu, }; use crate::lease::NodeLease; -use crate::manifest::action::RegionManifest; +use crate::manifest::action::{RegionManifest, cap_wal_release}; use crate::manifest::manager::{RegionManifestManager, RegionManifestOptions}; use crate::memtable::bulk::part::BulkPart; use crate::memtable::time_partition::TimePartitions; @@ -627,10 +627,13 @@ impl RegionOpener { .max(flushed_entry_id); let topic_latest_entry_id = if !self.skip_wal_replay { check_wal_history(wal, &provider, &version_control.current().version).await?; + let node_id = self.file_ref_manager.node_id(); + let replay_start = replay_from_entry_id.max(manifest.wal_replay_start(node_id)); info!( - "Start replaying memtable at replay_from_entry_id: {} for region {}, manifest version: {}, flushed entry id: {}, elapsed: {:?}", - replay_from_entry_id, + "Start replaying memtable at replay_start: {} for region {}, replay_from_entry_id: {}, manifest version: {}, flushed entry id: {}, elapsed: {:?}", + replay_start, region_id, + replay_from_entry_id, manifest.manifest_version, flushed_entry_id, now.elapsed() @@ -639,7 +642,8 @@ impl RegionOpener { &provider, wal_entry_reader, region_id, - replay_from_entry_id, + replay_start, + cap_wal_release(&manifest.pending_tails, node_id, replay_start), &version_control, config.allow_stale_entries, on_region_opened, @@ -813,6 +817,7 @@ pub(crate) fn version_builder_from_manifest( .truncated_entry_id(manifest.truncated_entry_id) .compaction_time_window(manifest.compaction_time_window) .options(region_options) + .pending_tails(manifest.pending_tails.clone()) } /// Updates region options by persistent options. @@ -972,12 +977,15 @@ pub(crate) async fn check_wal_history( .await } -/// Replays the mutations from WAL and inserts mutations to memtable of given region. +/// Replays the mutations from WAL and inserts mutations to memtable of given region, +/// then releases the WAL up to `release_entry_id`. +#[allow(clippy::too_many_arguments)] pub(crate) async fn replay_memtable( provider: &Provider, mut wal_entry_reader: Box, region_id: RegionId, flushed_entry_id: EntryId, + release_entry_id: EntryId, version_control: &VersionControlRef, allow_stale_entries: bool, on_region_opened: F, @@ -1072,7 +1080,7 @@ where // TODO(weny): We need to update `flushed_entry_id` in the region manifest // to avoid reading potentially incomplete entries in the future. - (on_region_opened)(region_id, flushed_entry_id, provider).await?; + (on_region_opened)(region_id, release_entry_id, provider).await?; let series_count = version_control.current().series_count(); info!( @@ -1539,6 +1547,8 @@ mod tests { compaction_time_window: None, sst_format, append_mode: None, + pending_tails: Default::default(), + handoff_floors: Default::default(), } } diff --git a/src/mito2/src/region/version.rs b/src/mito2/src/region/version.rs index c1940b31ab0..a9866ecd748 100644 --- a/src/mito2/src/region/version.rs +++ b/src/mito2/src/region/version.rs @@ -27,11 +27,12 @@ use std::sync::{Arc, RwLock}; use std::time::Duration; use common_telemetry::info; +use snafu::ensure; use store_api::metadata::RegionMetadataRef; use store_api::storage::{RegionId, SequenceNumber}; -use crate::error::Result; -use crate::manifest::action::{RegionEdit, TruncateKind}; +use crate::error::{RegionPendingTailsSnafu, Result}; +use crate::manifest::action::{PendingTail, RegionEdit, TruncateKind}; use crate::memtable::time_partition::TimePartitions; use crate::memtable::version::{MemtableVersion, MemtableVersionRef}; use crate::memtable::{MemtableBuilderRef, MemtableId}; @@ -399,6 +400,24 @@ pub(crate) struct Version { pub(crate) compaction_time_window: Option, /// Options of the region. pub(crate) options: RegionOptions, + /// WAL ranges the region still has to recover. + pub(crate) pending_tails: Vec, +} + +impl Version { + pub(crate) fn has_pending_tails(&self) -> bool { + !self.pending_tails.is_empty() + } + + pub(crate) fn ensure_no_pending_tails(&self) -> Result<()> { + ensure!( + !self.has_pending_tails(), + RegionPendingTailsSnafu { + region_id: self.metadata.region_id, + } + ); + Ok(()) + } } pub(crate) type VersionRef = Arc; @@ -413,6 +432,7 @@ pub(crate) struct VersionBuilder { truncated_entry_id: Option, compaction_time_window: Option, options: RegionOptions, + pending_tails: Vec, } impl VersionBuilder { @@ -427,6 +447,7 @@ impl VersionBuilder { truncated_entry_id: None, compaction_time_window: None, options: RegionOptions::default(), + pending_tails: Vec::new(), } } @@ -441,6 +462,7 @@ impl VersionBuilder { truncated_entry_id: version.truncated_entry_id, compaction_time_window: version.compaction_time_window, options: version.options.clone(), + pending_tails: version.pending_tails.clone(), } } @@ -489,6 +511,11 @@ impl VersionBuilder { self } + pub(crate) fn pending_tails(mut self, pending_tails: Vec) -> Self { + self.pending_tails = pending_tails; + self + } + /// Apply edit to the builder. pub(crate) fn apply_edit(mut self, edit: RegionEdit, file_purger: FilePurgerRef) -> Self { if let Some(entry_id) = edit.flushed_entry_id { @@ -500,6 +527,9 @@ impl VersionBuilder { if let Some(window) = edit.compaction_time_window { self.compaction_time_window = Some(window); } + if let Some(pending_tails) = edit.wal_recovery.pending_tails { + self.pending_tails = pending_tails; + } if !edit.files_to_add.is_empty() || !edit.files_to_remove.is_empty() { let mut ssts = (*self.ssts).clone(); ssts.add_files(file_purger, edit.files_to_add.into_iter()); @@ -573,6 +603,7 @@ impl VersionBuilder { truncated_entry_id: self.truncated_entry_id, compaction_time_window, options: self.options, + pending_tails: self.pending_tails, } } } @@ -621,6 +652,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: Some(sequence), + wal_recovery: Default::default(), }), &[], builder.file_purger(), diff --git a/src/mito2/src/remap_manifest.rs b/src/mito2/src/remap_manifest.rs index 596e60c6ddf..fec0cad0547 100644 --- a/src/mito2/src/remap_manifest.rs +++ b/src/mito2/src/remap_manifest.rs @@ -116,6 +116,8 @@ impl RemapManifest { compaction_time_window: None, sst_format, append_mode: None, + pending_tails: Default::default(), + handoff_floors: Default::default(), }; new_manifests.insert(*region_id, manifest); @@ -467,6 +469,8 @@ mod tests { committed_sequence: None, sst_format: FormatType::PrimaryKey, append_mode: None, + pending_tails: Default::default(), + handoff_floors: Default::default(), } } diff --git a/src/mito2/src/series_index/task.rs b/src/mito2/src/series_index/task.rs index 6ce340827a1..eeb8ef50de6 100644 --- a/src/mito2/src/series_index/task.rs +++ b/src/mito2/src/series_index/task.rs @@ -813,6 +813,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), &[], crate::test_util::new_noop_file_purger(), diff --git a/src/mito2/src/series_index/tests.rs b/src/mito2/src/series_index/tests.rs index 5f13d0b4b2d..feb8962ecf9 100644 --- a/src/mito2/src/series_index/tests.rs +++ b/src/mito2/src/series_index/tests.rs @@ -294,6 +294,7 @@ async fn test_reconcile_range_index_disabled( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), &[], crate::test_util::new_noop_file_purger(), @@ -403,6 +404,7 @@ async fn test_reconcile_range_only_build_and_removal() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), &[], crate::test_util::new_noop_file_purger(), @@ -455,6 +457,7 @@ async fn test_reconcile_replaces_whole_bucket_after_failure(#[case] failure: &st flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; region.version_control.apply_edit( Some(edit(false)), diff --git a/src/mito2/src/sst/file_ref.rs b/src/mito2/src/sst/file_ref.rs index 68b0facaab4..b82a7b9c217 100644 --- a/src/mito2/src/sst/file_ref.rs +++ b/src/mito2/src/sst/file_ref.rs @@ -34,7 +34,8 @@ struct RegionFileRefs { /// Tracks reader references to SST metadata views in one datanode for object-store GC. #[derive(Debug)] pub struct FileReferenceManager { - /// Datanode id. used to determine tmp ref file name. + /// Id of this datanode. Names the tmp ref files and identifies the WAL ranges of + /// this node in region manifests. node_id: Option, files_per_region: DashMap, /// Whether global GC is enabled. diff --git a/src/mito2/src/sst/index.rs b/src/mito2/src/sst/index.rs index 4fb0f08e217..635d21f1cb4 100644 --- a/src/mito2/src/sst/index.rs +++ b/src/mito2/src/sst/index.rs @@ -1527,6 +1527,7 @@ mod tests { flushed_entry_id: None, committed_sequence: None, compaction_time_window: None, + wal_recovery: Default::default(), })), false, ) diff --git a/src/mito2/src/sst/primary_key.rs b/src/mito2/src/sst/primary_key.rs index 2d3f8c90e3b..eafa8473c14 100644 --- a/src/mito2/src/sst/primary_key.rs +++ b/src/mito2/src/sst/primary_key.rs @@ -741,6 +741,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, new_noop_file_purger(), ) diff --git a/src/mito2/src/test_util.rs b/src/mito2/src/test_util.rs index 29718163528..be8f3b64003 100644 --- a/src/mito2/src/test_util.rs +++ b/src/mito2/src/test_util.rs @@ -105,6 +105,7 @@ pub(crate) fn nop_action() -> RegionMetaActionList { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), })]) } diff --git a/src/mito2/src/test_util/version_util.rs b/src/mito2/src/test_util/version_util.rs index 44827b35cc1..136bf11db28 100644 --- a/src/mito2/src/test_util/version_util.rs +++ b/src/mito2/src/test_util/version_util.rs @@ -226,6 +226,7 @@ pub(crate) fn apply_edit( flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }), &[], purger, diff --git a/src/mito2/src/worker/handle_alter.rs b/src/mito2/src/worker/handle_alter.rs index 935dbd39413..592b508249e 100644 --- a/src/mito2/src/worker/handle_alter.rs +++ b/src/mito2/src/worker/handle_alter.rs @@ -167,6 +167,13 @@ impl RegionWorkerLoop { return; } + if !is_allowed_with_pending_tails(&request.kind) + && let Err(e) = version.ensure_no_pending_tails() + { + sender.send(Err(e)); + return; + } + // Checks whether we need to alter the region. if !request.need_alter(&version.metadata) { warn!( @@ -425,6 +432,19 @@ impl RegionWorkerLoop { } } +/// Returns true if `kind` only changes region options or only adds nullable columns +/// without a default value, which rows replayed from a pending tail can lack. +fn is_allowed_with_pending_tails(kind: &AlterKind) -> bool { + match kind { + AlterKind::AddColumns { columns } => columns.iter().all(|column| { + let schema = &column.column_metadata.column_schema; + schema.is_nullable() && schema.default_constraint().is_none() + }), + AlterKind::SetRegionOptions { .. } | AlterKind::UnsetRegionOptions { .. } => true, + _ => false, + } +} + fn skip_wal_value(kind: &AlterKind) -> Option { let AlterKind::SetRegionOptions { options } = kind else { return None; diff --git a/src/mito2/src/worker/handle_apply_staging.rs b/src/mito2/src/worker/handle_apply_staging.rs index 2598640b9f2..73b9decd128 100644 --- a/src/mito2/src/worker/handle_apply_staging.rs +++ b/src/mito2/src/worker/handle_apply_staging.rs @@ -124,6 +124,7 @@ impl RegionWorkerLoop { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; let (tx, rx) = oneshot::channel(); diff --git a/src/mito2/src/worker/handle_close.rs b/src/mito2/src/worker/handle_close.rs index c10ac761f43..1e447e3ea54 100644 --- a/src/mito2/src/worker/handle_close.rs +++ b/src/mito2/src/worker/handle_close.rs @@ -36,6 +36,13 @@ impl RegionWorkerLoop { info!("Try to close region {}, worker: {}", region_id, self.id); + if request.flush_on_close + && let Err(e) = region.version().ensure_no_pending_tails() + { + sender.send(Err(e)); + return; + } + if region.is_staging_or_staged_edit() { // A staging region cannot flush, so it leaves staging before the close-time flush // below. The manifest lock lets a successful end of staging in progress finish first, diff --git a/src/mito2/src/worker/handle_copy_region.rs b/src/mito2/src/worker/handle_copy_region.rs index 2204cec8e1c..fbd02e8210b 100644 --- a/src/mito2/src/worker/handle_copy_region.rs +++ b/src/mito2/src/worker/handle_copy_region.rs @@ -264,6 +264,7 @@ impl RegionWorkerLoop { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }; if edit .files_to_add diff --git a/src/mito2/src/worker/handle_enter_staging.rs b/src/mito2/src/worker/handle_enter_staging.rs index e5b0674aaac..119f07241f6 100644 --- a/src/mito2/src/worker/handle_enter_staging.rs +++ b/src/mito2/src/worker/handle_enter_staging.rs @@ -63,6 +63,10 @@ impl RegionWorkerLoop { sender.send(Ok(0)); return; } + if let Err(e) = region.version().ensure_no_pending_tails() { + sender.send(Err(e)); + return; + } // Retain the compaction fence while the DDL later waits for flush. let (sender, partition_directive) = match self.compaction_scheduler.try_cancel_and_add_ddl( diff --git a/src/mito2/src/worker/handle_flush.rs b/src/mito2/src/worker/handle_flush.rs index 984b551d7bb..32cd19a4142 100644 --- a/src/mito2/src/worker/handle_flush.rs +++ b/src/mito2/src/worker/handle_flush.rs @@ -27,6 +27,7 @@ use store_api::storage::RegionId; use crate::config::{IndexBuildMode, MitoConfig}; use crate::error::{RegionBusySnafu, RegionNotFoundSnafu, Result}; use crate::flush::{FlushReason, RegionFlushTask}; +use crate::manifest::action::cap_wal_release; use crate::region::version::VersionRef; use crate::region::{MitoRegion, MitoRegionRef}; use crate::request::{BuildIndexRequest, FlushFailed, FlushFinished, OnFailure, OptionOutputTx}; @@ -364,6 +365,13 @@ impl RegionWorkerLoop { } }; + if request.reason == Some(RegionFlushReason::Repartition) + && let Err(e) = region.version().ensure_no_pending_tails() + { + sender.send(Err(e)); + return; + } + // `update_topic_latest_entry_id` updates `topic_latest_entry_id` when memtables are empty. // But the flush is skipped if memtables are empty. Thus should update the `topic_latest_entry_id` // when handling flush request instead of in `schedule_flush` or `flush_finished`. @@ -484,13 +492,18 @@ impl RegionWorkerLoop { self.update_topic_latest_entry_id(®ion); // Delete wal. + let obsolete_entry_id = cap_wal_release( + ®ion.version().pending_tails, + self.file_ref_manager.node_id(), + request.flushed_entry_id, + ); info!( "Region {} flush finished, tries to bump wal to {}", - region_id, request.flushed_entry_id + region_id, obsolete_entry_id ); if let Err(e) = self .wal - .obsolete(region_id, request.flushed_entry_id, ®ion.provider) + .obsolete(region_id, obsolete_entry_id, ®ion.provider) .await { error!(e; "Failed to write wal, region: {}", region_id); diff --git a/src/mito2/src/worker/handle_manifest.rs b/src/mito2/src/worker/handle_manifest.rs index d8f4ecf8c16..f1a575d4433 100644 --- a/src/mito2/src/worker/handle_manifest.rs +++ b/src/mito2/src/worker/handle_manifest.rs @@ -35,6 +35,7 @@ use crate::error::{ }; use crate::manifest::action::{ RegionChange, RegionEdit, RegionMetaAction, RegionMetaActionList, RegionTruncate, TruncateKind, + WalRecoveryEdit, }; use crate::memtable::MemtableBuilderProvider; use crate::metrics::WRITE_CACHE_INFLIGHT_DOWNLOAD; @@ -115,6 +116,7 @@ impl RegionEditQueue { && edit.flushed_entry_id.is_none() && edit.flushed_sequence.is_none() && edit.committed_sequence.is_none() + && edit.wal_recovery == WalRecoveryEdit::default() } let mut merged = self.requests.pop_front()?; @@ -693,6 +695,7 @@ impl RegionWorkerLoop { flushed_entry_id: Some(discarded_entry_id), flushed_sequence: Some(discarded_sequence), committed_sequence: None, + wal_recovery: Default::default(), }; let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit)); let result = match durability_barrier.wait(discarded_entry_id).await { diff --git a/src/mito2/src/worker/handle_rebuild_index.rs b/src/mito2/src/worker/handle_rebuild_index.rs index 10f55c78943..917a58d0c68 100644 --- a/src/mito2/src/worker/handle_rebuild_index.rs +++ b/src/mito2/src/worker/handle_rebuild_index.rs @@ -399,6 +399,7 @@ impl RegionWorkerLoop { flushed_entry_id: None, committed_sequence: None, compaction_time_window: None, + wal_recovery: Default::default(), }), &[], region.file_purger.clone(), diff --git a/src/mito2/src/worker/handle_truncate.rs b/src/mito2/src/worker/handle_truncate.rs index 409998592d1..a21bb0578e3 100644 --- a/src/mito2/src/worker/handle_truncate.rs +++ b/src/mito2/src/worker/handle_truncate.rs @@ -39,6 +39,11 @@ impl RegionWorkerLoop { return; } }; + // Truncating releases the WAL without keeping the pending tails. + if let Err(e) = region.version().ensure_no_pending_tails() { + sender.send(Err(e)); + return; + } // Fence compaction before any later flush wait so handed-off DDLs keep admission paused. let (sender, req) = match self.compaction_scheduler.try_cancel_and_add_ddl( diff --git a/tests/compatibility/README.md b/tests/compatibility/README.md index b84b55c92e5..0dfcba20215 100644 --- a/tests/compatibility/README.md +++ b/tests/compatibility/README.md @@ -48,6 +48,9 @@ writer that emits these descriptors; downgrade only to readers that recognize th The OSS build does not generate sketch payloads, so SQL restart cases cannot create these descriptors through an OSS writer. +Frozen region manifests that carry pending WAL tails are checked by the manifest tests of `mito2`. +No SQL statement records a pending tail. See the [fixture notes](manifest/pending_tails/README.md). + ## Quick Start ```shell diff --git a/tests/compatibility/manifest/pending_tails/README.md b/tests/compatibility/manifest/pending_tails/README.md new file mode 100644 index 00000000000..b788ad35bbf --- /dev/null +++ b/tests/compatibility/manifest/pending_tails/README.md @@ -0,0 +1,27 @@ +# Pending tail manifest fixtures + +Frozen region manifests with pending WAL tails and a handoff floor, checked by the manifest tests +in `src/mito2/src/manifest/action.rs`, which never rewrite them: + +```shell +cargo nextest run -p mito2 -E 'test(test_pending_tails_fixtures) | test(test_pending_tails_old_shape_compat)' +``` + +The first test decodes both files. It requires the encoder to reproduce `delta.json` byte for byte, +and the `pending_tails` and `handoff_floors` of `checkpoint.json` exactly; the rest of the checkpoint +embeds region metadata, whose encoding may gain compatible fields. The second test decodes both +files with the shapes from before pending tails existed, which must ignore the new fields, and +requires a manifest without pending tails to encode exactly as those shapes do. + +## `delta.json` + +A delta with one edit. It carries committed sequence `(1 << 40) + 5`, two pending tails, and the +handoff floor `4 << 32` of node 3. The tails are node 1, entries `(1 << 32, (1 << 32) + 5]` with a +reported upper bound, and node 2, entries `(2 << 32, 3 << 32]` with a listed upper bound. 424 bytes, +SHA-256 `520cbdc2cf51de4fb960d3c2f2194c126e3d23f02b4c511ed687705f48073c80`. + +## `checkpoint.json` + +A checkpoint of version 7 holding the same two tails and floor, flushed entry id `1 << 32`, no +files, and the region metadata of `basic_region_metadata` in `src/mito2/src/manifest/tests/utils.rs`. +1,245 bytes, SHA-256 `088f3f4caf04dbbf2734739aeb72a9a742e5ba8fb20f840dfd24123fb4027dd7`. diff --git a/tests/compatibility/manifest/pending_tails/checkpoint.json b/tests/compatibility/manifest/pending_tails/checkpoint.json new file mode 100644 index 00000000000..a58882debcb --- /dev/null +++ b/tests/compatibility/manifest/pending_tails/checkpoint.json @@ -0,0 +1 @@ +{"last_version":7,"compacted_actions":7,"checkpoint":{"metadata":{"column_metadatas":[{"column_schema":{"name":"ts","data_type":{"Timestamp":{"Millisecond":null}},"is_nullable":false,"is_time_index":false,"default_constraint":null,"metadata":{}},"semantic_type":"Timestamp","column_id":45},{"column_schema":{"name":"pk","data_type":{"String":{"size_type":"Utf8"}},"is_nullable":false,"is_time_index":false,"default_constraint":null,"metadata":{}},"semantic_type":"Tag","column_id":36},{"column_schema":{"name":"val","data_type":{"Float64":{}},"is_nullable":false,"is_time_index":false,"default_constraint":null,"metadata":{}},"semantic_type":"Field","column_id":251}],"primary_key":[36],"region_id":98784247841,"schema_version":0,"primary_key_encoding":"dense","partition_expr":null},"files":{},"removed_files":{"removed_files":[]},"flushed_entry_id":4294967296,"flushed_sequence":100,"committed_sequence":1099511627781,"manifest_version":7,"truncated_entry_id":null,"compaction_time_window":null,"sst_format":"primary_key","append_mode":null,"pending_tails":[{"node_id":1,"after":4294967296,"upto":4294967301,"upto_kind":"reported"},{"node_id":2,"after":8589934592,"upto":12884901888,"upto_kind":"listed"}],"handoff_floors":{"3":17179869184}}} diff --git a/tests/compatibility/manifest/pending_tails/delta.json b/tests/compatibility/manifest/pending_tails/delta.json new file mode 100644 index 00000000000..2305629cab9 --- /dev/null +++ b/tests/compatibility/manifest/pending_tails/delta.json @@ -0,0 +1 @@ +{"actions":[{"Edit":{"files_to_add":[],"files_to_remove":[],"timestamp_ms":1762732800000,"compaction_time_window":null,"flushed_entry_id":null,"flushed_sequence":null,"committed_sequence":1099511627781,"pending_tails":[{"node_id":1,"after":4294967296,"upto":4294967301,"upto_kind":"reported"},{"node_id":2,"after":8589934592,"upto":12884901888,"upto_kind":"listed"}],"handoff_floor":{"node_id":3,"entry_id":17179869184}}}]} From 54b6bd5b444333fbeff6af6cc4cbd2b0c575e02c Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Tue, 10 Nov 2026 14:02:48 +0000 Subject: [PATCH 02/63] feat(mito2): support extension index providers and input reuse (#10297) * feat(mito2): register extension index providers Signed-off-by: WenyXu * feat(mito2): support index input reuse and extension budgets Signed-off-by: WenyXu --------- Signed-off-by: WenyXu --- src/cmd/src/datanode/objbench.rs | 1 + src/mito2/src/access_layer.rs | 6 + src/mito2/src/cache/write_cache.rs | 4 + src/mito2/src/compaction/compactor.rs | 1 + .../src/compaction/multi_region/tests.rs | 1 + .../src/compaction/multi_region/writer.rs | 1 + src/mito2/src/flush.rs | 1 + src/mito2/src/metrics.rs | 15 +- src/mito2/src/sst/file.rs | 2 +- src/mito2/src/sst/index.rs | 1107 ++++++++++++++++- src/mito2/src/sst/index/build.rs | 46 + src/mito2/src/sst/index/column_test.rs | 1 + src/mito2/src/sst/index/handler.rs | 95 +- src/mito2/src/sst/index/handler/builtin.rs | 30 +- .../src/sst/index/handler/builtin/bloom.rs | 25 +- .../src/sst/index/handler/builtin/fulltext.rs | 30 +- .../src/sst/index/handler/builtin/inverted.rs | 28 +- src/mito2/src/sst/index/indexer/abort.rs | 4 +- src/mito2/src/sst/index/indexer/finish.rs | 11 +- src/mito2/src/sst/index/indexer/update.rs | 37 +- src/mito2/src/sst/index/kind.rs | 58 +- src/mito2/src/sst/index/registry.rs | 453 ++++++- src/mito2/src/sst/index/sparse_test.rs | 1 + src/mito2/src/sst/parquet.rs | 3 + src/mito2/src/worker/handle_rebuild_index.rs | 1 + 25 files changed, 1844 insertions(+), 118 deletions(-) create mode 100644 src/mito2/src/sst/index/build.rs diff --git a/src/cmd/src/datanode/objbench.rs b/src/cmd/src/datanode/objbench.rs index 248acc09bf6..aa26491c351 100644 --- a/src/cmd/src/datanode/objbench.rs +++ b/src/cmd/src/datanode/objbench.rs @@ -203,6 +203,7 @@ impl ObjbenchCommand { max_sequence: None, sst_write_format: FormatType::PrimaryKey, index_options: Default::default(), + index_build_inputs: None, index_config: mito_engine_config.index.clone(), inverted_index_config: MitoConfig::default().inverted_index, fulltext_index_config, diff --git a/src/mito2/src/access_layer.rs b/src/mito2/src/access_layer.rs index 55e564fb4e7..3a572b395bd 100644 --- a/src/mito2/src/access_layer.rs +++ b/src/mito2/src/access_layer.rs @@ -44,6 +44,7 @@ use crate::metrics::{COMPACTION_STAGE_ELAPSED, FLUSH_ELAPSED}; use crate::read::FlatSource; use crate::region::options::IndexOptions; use crate::sst::file::{FileHandle, RegionFileId, RegionIndexId}; +use crate::sst::index::build::IndexBuildInputs; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::{PuffinManagerFactory, SstPuffinManager}; use crate::sst::index::registry::IndexRegistry; @@ -441,6 +442,7 @@ impl AccessLayer { self.puffin_manager_factory.clone() }; let indexer_builder = IndexerBuilderImpl { + index_build_inputs: request.index_build_inputs, build_type: request.op_type.into(), metadata: request.metadata.clone(), puffin_manager: puffin_factory.build(store, path_provider.clone()), @@ -671,6 +673,8 @@ pub enum OperationType { /// Contents to build a SST. pub struct SstWriteRequest { + /// Optional preplanned index work and physical input files. + pub index_build_inputs: Option, pub op_type: OperationType, pub metadata: RegionMetadataRef, pub source: FlatSource, @@ -707,6 +711,7 @@ impl EncodedSstIndexBuildParams { intermediate_manager: IntermediateManager, ) -> IndexerBuilderImpl { IndexerBuilderImpl { + index_build_inputs: None, build_type: OperationType::Flush.into(), metadata: self.metadata, puffin_manager, @@ -1026,6 +1031,7 @@ mod tests { access_layer .write_sst( SstWriteRequest { + index_build_inputs: None, op_type, metadata, source: new_flat_source_from_record_batches(vec![ diff --git a/src/mito2/src/cache/write_cache.rs b/src/mito2/src/cache/write_cache.rs index 534f0a8c076..37a4964a20e 100644 --- a/src/mito2/src/cache/write_cache.rs +++ b/src/mito2/src/cache/write_cache.rs @@ -301,6 +301,7 @@ impl WriteCache { let store = self.file_cache.local_store(); let path_provider = WriteCachePathProvider::new(self.file_cache.clone()); let indexer = IndexerBuilderImpl { + index_build_inputs: write_request.index_build_inputs, build_type: write_request.op_type.into(), metadata: write_request.metadata.clone(), puffin_manager: self @@ -746,6 +747,7 @@ mod tests { ]); let write_request = SstWriteRequest { + index_build_inputs: None, op_type, metadata, source, @@ -863,6 +865,7 @@ mod tests { // Write to local cache and upload sst to mock remote store let write_request = SstWriteRequest { + index_build_inputs: None, op_type: OperationType::Flush, metadata, source, @@ -955,6 +958,7 @@ mod tests { // Write to local cache and upload sst to mock remote store let write_request = SstWriteRequest { + index_build_inputs: None, op_type: OperationType::Flush, metadata, source, diff --git a/src/mito2/src/compaction/compactor.rs b/src/mito2/src/compaction/compactor.rs index 6cd51dae9a1..5074dcedadb 100644 --- a/src/mito2/src/compaction/compactor.rs +++ b/src/mito2/src/compaction/compactor.rs @@ -653,6 +653,7 @@ impl SstMerger for DefaultSstMerger { .access_layer .write_sst( SstWriteRequest { + index_build_inputs: None, op_type: OperationType::Compact, metadata: region_metadata.clone(), source, diff --git a/src/mito2/src/compaction/multi_region/tests.rs b/src/mito2/src/compaction/multi_region/tests.rs index 11829dcca2e..3aadc435cb5 100644 --- a/src/mito2/src/compaction/multi_region/tests.rs +++ b/src/mito2/src/compaction/multi_region/tests.rs @@ -447,6 +447,7 @@ fn write_request( format: FormatType, ) -> SstWriteRequest { SstWriteRequest { + index_build_inputs: None, op_type: OperationType::Flush, metadata, source, diff --git a/src/mito2/src/compaction/multi_region/writer.rs b/src/mito2/src/compaction/multi_region/writer.rs index 3c266584167..737fae51e44 100644 --- a/src/mito2/src/compaction/multi_region/writer.rs +++ b/src/mito2/src/compaction/multi_region/writer.rs @@ -105,6 +105,7 @@ impl<'a> TargetWriter<'a> { bloom.mem_threshold_on_create = self.index_threshold(bloom.mem_threshold_on_create()); let source = output_projection(self.target, source, self.context.cancellation.clone())?; Ok(SstWriteRequest { + index_build_inputs: None, op_type: OperationType::Compact, metadata: self.target.metadata.clone(), source, diff --git a/src/mito2/src/flush.rs b/src/mito2/src/flush.rs index d0c19c13ec8..1857997fd64 100644 --- a/src/mito2/src/flush.rs +++ b/src/mito2/src/flush.rs @@ -851,6 +851,7 @@ impl RegionFlushTask { .map(|f| f == FormatType::Flat) .unwrap_or(self.engine_config.default_flat_format); SstWriteRequest { + index_build_inputs: None, op_type: OperationType::Flush, metadata: version.metadata.clone(), source, diff --git a/src/mito2/src/metrics.rs b/src/mito2/src/metrics.rs index 18903abc661..1a445b56faa 100644 --- a/src/mito2/src/metrics.rs +++ b/src/mito2/src/metrics.rs @@ -38,6 +38,11 @@ pub const STAGING_TYPE: &str = "index_staging"; /// Recycle bin type label. pub const RECYCLE_TYPE: &str = "recycle_bin"; +/// Discard reason when an operation cannot admit extension index work. +pub(crate) const INDEX_DISCARD_ADMISSION_REJECTED: &str = "admission_rejected"; +/// Discard reason when a creator exceeds its retained-memory allowance. +pub(crate) const INDEX_DISCARD_MEMORY_BUDGET_EXCEEDED: &str = "memory_budget_exceeded"; + // Write metrics. lazy_static! { /// Global write buffer size in bytes. @@ -505,7 +510,15 @@ lazy_static! { &[TYPE_LABEL], ) .unwrap(); - /// Gauge of index create memory usage. + /// Optional index kinds discarded by a resource policy, not a build error. + pub static ref INDEX_CREATE_DISCARDED_TOTAL: IntCounterVec = register_int_counter_vec!( + "greptime_index_create_discarded_total", + "index kinds omitted or discarded by resource policy", + &[TYPE_LABEL, "reason"], + ).unwrap(); + /// Gauge of index create memory usage. The `extension` type aggregates retained + /// memory across optional creators, not individual algorithms: one creator may + /// share state across several algorithms. pub static ref INDEX_CREATE_MEMORY_USAGE: IntGaugeVec = register_int_gauge_vec!( "greptime_index_create_memory_usage", "index create memory usage", diff --git a/src/mito2/src/sst/file.rs b/src/mito2/src/sst/file.rs index ba29db1736f..a29cc33af0c 100644 --- a/src/mito2/src/sst/file.rs +++ b/src/mito2/src/sst/file.rs @@ -147,7 +147,7 @@ fn deserialize_level<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Resul } /// Type to store index types for a column. -pub type IndexTypes = SmallVec<[IndexType; 4]>; +pub type IndexTypes = SmallVec<[IndexType; 6]>; /// Cross-region file id. /// diff --git a/src/mito2/src/sst/index.rs b/src/mito2/src/sst/index.rs index 635d21f1cb4..47f7834235f 100644 --- a/src/mito2/src/sst/index.rs +++ b/src/mito2/src/sst/index.rs @@ -13,18 +13,19 @@ // limitations under the License. pub(crate) mod bloom_filter; +pub mod build; mod column; #[cfg(test)] mod column_test; pub(crate) mod fulltext_index; -pub(crate) mod handler; +pub mod handler; mod indexer; pub mod intermediate; pub(crate) mod inverted_index; -pub(crate) mod kind; +pub mod kind; mod primary_key; pub mod puffin_manager; -pub(crate) mod registry; +pub mod registry; #[cfg(test)] mod sparse_test; mod statistics; @@ -36,6 +37,7 @@ use std::ops::ControlFlow; use std::sync::Arc; use bytes::Bytes; +use common_error::ext::BoxedError; use common_telemetry::{debug, error, info, warn}; use datatypes::arrow::record_batch::RecordBatch; use index::target::IndexTarget; @@ -44,7 +46,7 @@ use object_store::ObjectStore; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; use puffin_manager::SstPuffinManager; use smallvec::SmallVec; -use snafu::ResultExt; +use snafu::{IntoError, ResultExt}; #[cfg(feature = "enterprise")] pub use statistics::{Statistics, TimerGuard}; use store_api::codec::PrimaryKeyEncoding; @@ -61,11 +63,12 @@ use crate::cache::{CacheManagerRef, CacheStrategy}; #[cfg(test)] use crate::config::{BloomFilterConfig, InvertedIndexConfig}; use crate::error::{ - BuildIndexAsyncSnafu, Error, InvalidConfigSnafu, JoinSnafu, RegionClosedSnafu, + BuildIndexAsyncSnafu, Error, ExternalSnafu, InvalidConfigSnafu, JoinSnafu, RegionClosedSnafu, RegionDroppedSnafu, RegionTruncatedSnafu, Result, }; use crate::metrics::{ - INDEX_ARTIFACT_CLEANUP_FAILURE_TOTAL, INDEX_CREATE_MEMORY_USAGE, INDEX_PUBLICATION_STALE_TOTAL, + INDEX_ARTIFACT_CLEANUP_FAILURE_TOTAL, INDEX_CREATE_DISCARDED_TOTAL, INDEX_CREATE_MEMORY_USAGE, + INDEX_DISCARD_MEMORY_BUDGET_EXCEEDED, INDEX_PUBLICATION_STALE_TOTAL, }; use crate::read::Batch; use crate::region::options::IndexOptions; @@ -78,7 +81,9 @@ use crate::request::{ WorkerRequestWithTime, }; use crate::schedule::scheduler::{Job, SchedulerRef}; -use crate::sst::file::{ColumnIndexMetadata, FileHandle, IndexType, RegionFileId, RegionIndexId}; +use crate::sst::file::{ + ColumnIndexMetadata, FileHandle, IndexType, IndexTypes, RegionFileId, RegionIndexId, +}; use crate::sst::file_purger::FilePurgerRef; #[cfg(feature = "testing")] use crate::sst::index::bloom_filter::creator::BloomFilterIndexer; @@ -90,6 +95,7 @@ use crate::sst::index::inverted_index::creator::InvertedIndexer; use crate::sst::parquet::SstInfo; use crate::worker::WorkerListener; +pub(crate) const TYPE_EXTENSION_INDEX: &str = "extension"; pub(crate) const TYPE_INVERTED_INDEX: &str = kind::IndexKind::Inverted.as_str(); pub(crate) const TYPE_FULLTEXT_INDEX: &str = kind::IndexKind::Fulltext.as_str(); pub(crate) const TYPE_BLOOM_FILTER_INDEX: &str = kind::IndexKind::Bloom.as_str(); @@ -161,13 +167,14 @@ pub(crate) fn trigger_index_background_download( /// One index successfully written into the enclosing Puffin file. #[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct CompletedEntry { +pub struct CompletedEntry { /// Indexed column. `None` is reserved for file-level built-in indexes, such as /// JSON-path-only indexes; these appear only in `available_indexes`. pub column_id: Option, /// Registered index identity. pub kind: crate::sst::index::kind::IndexKind, - /// Fulltext bloom version published in column metadata. + /// Fulltext bloom version published in column metadata. Extension format + /// versions belong to their Puffin blob properties and are not published here. pub format_version: u32, } @@ -182,6 +189,12 @@ impl CompletedEntry { } fn validate(&self) -> Result<()> { + if self.column_id.is_none() && !self.kind.is_builtin() { + return InvalidConfigSnafu { + reason: "extension index completion requires a column id".to_string(), + } + .fail(); + } if self.kind.index_type() == IndexType::FulltextIndex { self.fulltext_bloom_version()?; } @@ -197,24 +210,19 @@ pub struct IndexOutput { /// Index version. pub version: u64, /// Successfully written column indexes. - pub(crate) entries: Vec, + pub entries: Vec, } impl IndexOutput { - pub fn build_available_indexes(&self) -> SmallVec<[IndexType; 4]> { - // Preserve the established order independently of handler registration. - [ - IndexType::InvertedIndex, - IndexType::FulltextIndex, - IndexType::BloomFilterIndex, - ] - .into_iter() - .filter(|kind| { - self.entries - .iter() - .any(|entry| entry.kind.index_type() == *kind) - }) - .collect() + pub fn build_available_indexes(&self) -> IndexTypes { + let mut kinds = SmallVec::<[kind::IndexKind; 6]>::new(); + for entry in &self.entries { + if !kinds.contains(&entry.kind) { + kinds.push(entry.kind); + } + } + kinds.sort_unstable(); + kinds.into_iter().map(kind::IndexKind::index_type).collect() } /// Builds column metadata, rejecting values that cannot be represented on disk. @@ -251,11 +259,34 @@ pub struct Indexer { puffin_manager: Option, write_cache_enabled: bool, creators: Vec, + /// Shared retained-memory ceiling for all injected creators. + extension_memory_limit: Option, dense_pk_decoder: Option, intermediate_manager: Option, + /// First failure retained even if best-effort execution discards a creator. + failure: Option>, + /// Optional index kinds dropped by the operation's resource policy. + discarded: Vec, } impl Indexer { + /// Reports failures even when surviving creators produced a partial result. + pub fn check_success(&self) -> Result<(), Arc> { + self.failure.clone().map_or(Ok(()), Err) + } + + /// Index kinds intentionally discarded because their memory budget was exceeded. + pub fn discarded(&self) -> &[kind::IndexKind] { + &self.discarded + } + + /// Whether any active creator requires decoded rows. + pub fn requires_row_scan(&self) -> bool { + self.creators + .iter() + .any(|active| active.creator.requires_row_scan()) + } + /// Returns true if no index creator is active. pub(crate) fn is_empty(&self) -> bool { self.creators.is_empty() @@ -263,17 +294,23 @@ impl Indexer { #[cfg(test)] fn has_kind(&self, kind: kind::IndexKind) -> bool { - self.creators.iter().any(|active| active.kind == kind) + self.creators + .iter() + .any(|active| active.kinds.contains(&kind)) } - fn push_creator(&mut self, kind: kind::IndexKind, creator: Box) { + fn push_creator( + &mut self, + kinds: Vec, + creator: Box, + memory_limit: Option, + label: &'static str, + ) { self.creators.push(ActiveIndex { - kind, + kinds, creator, - memory: IndexMemoryUsage { - label: kind.as_str(), - bytes: 0, - }, + memory_limit, + memory: IndexMemoryUsage { label, bytes: 0 }, }); } @@ -289,10 +326,20 @@ impl Indexer { ..Default::default() }; if let Some(creator) = inverted_indexer { - indexer.push_creator(kind::IndexKind::Inverted, Box::new(creator)); + indexer.push_creator( + vec![kind::IndexKind::Inverted], + Box::new(creator), + None, + TYPE_INVERTED_INDEX, + ); } if let Some(creator) = bloom_filter_indexer { - indexer.push_creator(kind::IndexKind::Bloom, Box::new(creator)); + indexer.push_creator( + vec![kind::IndexKind::Bloom], + Box::new(creator), + None, + TYPE_BLOOM_FILTER_INDEX, + ); } indexer.prepare_dense_pk_decoder(metadata); indexer @@ -326,15 +373,17 @@ impl Indexer { Ok(()) } - /// Updates all active creators using the borrowed batch. + /// Updates creators that require rows using the borrowed batch. pub async fn update(&mut self, batch: &mut Batch) { self.do_update(batch).await; + self.enforce_memory_limits().await; self.flush_mem_metrics(); } - /// Updates all active creators using the borrowed flat batch. + /// Updates creators that require rows using the borrowed flat batch. pub async fn update_flat(&mut self, batch: &RecordBatch) { self.do_update_flat(batch).await; + self.enforce_memory_limits().await; self.flush_mem_metrics(); } @@ -351,6 +400,57 @@ impl Indexer { self.flush_mem_metrics(); } + fn record_failure(&mut self, source: BoxedError) { + self.failure.get_or_insert_with(|| { + Arc::new( + ExternalSnafu { + context: "index creation".to_string(), + } + .into_error(source), + ) + }); + } + + async fn enforce_memory_limits(&mut self) { + let mut position = 0; + let mut extension_bytes = 0usize; + while position < self.creators.len() { + let active = &self.creators[position]; + if active.memory_limit.is_none() + && (active.is_builtin() || self.extension_memory_limit.is_none()) + { + position += 1; + continue; + } + let bytes = active.creator.memory_usage(); + let retained = extension_bytes.saturating_add(bytes); + let exceeds_shared_limit = !active.is_builtin() + && self + .extension_memory_limit + .is_some_and(|limit| retained > limit); + if exceeds_shared_limit || active.memory_limit.is_some_and(|limit| bytes > limit) { + warn!( + "Discarding index exceeding memory budget, region_id: {}, file_id: {}, kinds: {:?}", + self.region_id, self.file_id, active.kinds + ); + for kind in &active.kinds { + INDEX_CREATE_DISCARDED_TOTAL + .with_label_values(&[kind.as_str(), INDEX_DISCARD_MEMORY_BUDGET_EXCEEDED]) + .inc(); + if !self.discarded.contains(kind) { + self.discarded.push(*kind); + } + } + self.abort_creator(position).await; + } else { + if !active.is_builtin() { + extension_bytes = retained; + } + position += 1; + } + } + } + fn flush_mem_metrics(&mut self) { for active in &mut self.creators { let bytes = active.creator.memory_usage(); @@ -364,11 +464,18 @@ impl Indexer { /// One handler's active creator and its shared memory accounting. struct ActiveIndex { - kind: kind::IndexKind, + kinds: Vec, creator: Box, + memory_limit: Option, memory: IndexMemoryUsage, } +impl ActiveIndex { + fn is_builtin(&self) -> bool { + self.kinds.iter().all(|kind| kind.is_builtin()) + } +} + /// Releases each creator's gauge contribution on completion or cancellation. struct IndexMemoryUsage { label: &'static str, @@ -393,9 +500,9 @@ pub trait IndexerBuilder { row_group_size: Option, ) -> Indexer; } - #[derive(Clone)] pub(crate) struct IndexerBuilderImpl { + pub(crate) index_build_inputs: Option, pub(crate) registry: registry::IndexRegistryRef, pub(crate) build_type: IndexBuildType, pub(crate) metadata: RegionMetadataRef, @@ -423,29 +530,98 @@ impl IndexerBuilder for IndexerBuilderImpl { ..Default::default() }; - let context = handler::PlanContext { - metadata: &self.metadata, - index_options: &self.index_options, - build_type: self.build_type.clone(), + let plan = if let Some(inputs) = &self.index_build_inputs { + inputs.plan.clone() + } else { + let context = handler::PlanContext { + metadata: &self.metadata, + index_options: &self.index_options, + build_type: self.build_type.clone(), + existing_indexes: &[], + }; + Arc::new(self.registry.plan(&context)) }; - let plan = self.registry.plan(&context); - let context = handler::BuildContext { + indexer.failure = plan.check_success().err(); + let mut context = handler::BuildContext { metadata: &self.metadata, output: RegionIndexId::new(region_file_id, index_version), + puffin_manager: &self.puffin_manager, intermediate_manager: &self.intermediate_manager, + inputs: self + .index_build_inputs + .as_ref() + .map_or(&[], |inputs| &inputs.inputs), + input_puffin_manager: self + .index_build_inputs + .as_ref() + .map_or(&self.puffin_manager, |inputs| &inputs.input_puffin_manager), + can_merge_inputs: self + .index_build_inputs + .as_ref() + .is_some_and(|inputs| inputs.can_merge_inputs), + memory_limit: self + .index_build_inputs + .as_ref() + .and_then(|inputs| inputs.memory_limit), row_group_size, + output_rows: self + .index_build_inputs + .as_ref() + .and_then(|inputs| inputs.output_rows), }; + indexer.extension_memory_limit = context.memory_limit; for planned in plan.planned() { + let Some(first_kind) = planned.kinds().first() else { + let err = BoxedError::new( + InvalidConfigSnafu { + reason: "index plan must own at least one kind", + } + .build(), + ); + warn!(err; "Failed to create index, region_id: {}", self.metadata.region_id); + indexer.record_failure(err); + continue; + }; + let builtin = planned.kinds().iter().all(|kind| kind.is_builtin()); + // Optional creators share the operation allocation. Pass only the + // remaining retained budget before allowing another creator to build. + context.memory_limit = if builtin { + indexer.extension_memory_limit + } else { + let remaining = indexer.extension_memory_limit.map(|limit| { + let retained = indexer + .creators + .iter() + .filter(|active| !active.is_builtin()) + .fold(0usize, |bytes, active| { + bytes.saturating_add(active.creator.memory_usage()) + }); + limit.saturating_sub(retained) + }); + remaining.into_iter().chain(planned.memory_limit()).min() + }; match planned.build(&context).await { Ok(Some(creator)) => { - indexer.push_creator(planned.kind(), creator); + let label = if builtin { + first_kind.as_str() + } else { + TYPE_EXTENSION_INDEX + }; + let limit = if builtin { None } else { context.memory_limit }; + indexer.push_creator(planned.kinds().to_vec(), creator, limit, label); + if !builtin { + indexer.enforce_memory_limits().await; + } } Ok(None) => {} Err(err) => { - if cfg!(any(test, feature = "test")) { + if planned.kinds().iter().all(|kind| kind.is_builtin()) + && cfg!(any(test, feature = "test")) + { panic!("Failed to create index: {err:?}"); } - warn!(err; "Failed to create index, region_id: {}, kind: {:?}", self.metadata.region_id, planned.kind()); + warn!(err; "Failed to create index, region_id: {}, kinds: {:?}", self.metadata.region_id, planned.kinds()); + indexer.record_failure(err); } } } @@ -1649,6 +1825,7 @@ mod tests { let mut index_config = MitoConfig::default().index; index_config.build_mode = build_mode; let write_request = SstWriteRequest { + index_build_inputs: None, op_type: OperationType::Flush, metadata: metadata.clone(), source, @@ -1701,6 +1878,7 @@ mod tests { ), ); Arc::new(IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata, puffin_manager, @@ -1715,6 +1893,786 @@ mod tests { }) } + #[tokio::test] + async fn test_builtin_output_with_missing_or_failing_provider() { + use datatypes::arrow::array::{ + Float64Array, Int64Array, StringArray, TimestampMillisecondArray, UInt8Array, + UInt64Array, + }; + + for failure in [ + None, + Some(ProviderFailure::Plan), + Some(ProviderFailure::Finish), + ] { + let (dir, factory) = + PuffinManagerFactory::new_for_test_async("builtin_provider_failure").await; + let mut metadata = mock_region_metadata(MetaConfig { + with_inverted: true, + with_fulltext: true, + with_skipping_bloom: true, + }); + Arc::make_mut(&mut metadata).column_metadatas[0] + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + "{\"precision\":10}".into(), + ); + let registry = + registry::IndexRegistry::new( + Default::default(), + Default::default(), + Default::default(), + ) + .with_provider(failure.map(|failure| { + Arc::new(FailingProvider(failure)) as handler::IndexKindProviderRef + })) + .unwrap(); + let builder = IndexerBuilderImpl { + index_build_inputs: None, + build_type: IndexBuildType::Compact, + metadata, + puffin_manager: factory.build( + mock_object_store(), + RegionFilePathFactory::new( + "builtin-provider-test/".into(), + store_api::region_request::PathType::Bare, + ), + ), + write_cache_enabled: false, + intermediate_manager: mock_intm_mgr(dir.path().to_string_lossy()).await, + index_options: IndexOptions::default(), + registry: Arc::new(registry), + }; + let mut indexer = builder.build(random_region_file_id(), 0, Some(1024)).await; + let mut batch = crate::read::BatchBuilder::new(Vec::new()); + batch + .push_field_array(1, Arc::new(Int64Array::from(vec![42]))) + .unwrap(); + batch + .push_field_array(2, Arc::new(Float64Array::from(vec![1.0]))) + .unwrap(); + batch + .push_field_array(4, Arc::new(StringArray::from(vec!["hello world"]))) + .unwrap(); + batch + .push_field_array(5, Arc::new(StringArray::from(vec!["hello"]))) + .unwrap(); + batch + .timestamps_array(Arc::new(TimestampMillisecondArray::from(vec![0]))) + .unwrap(); + batch + .sequences_array(Arc::new(UInt64Array::from(vec![0]))) + .unwrap(); + batch + .op_types_array(Arc::new(UInt8Array::from(vec![0]))) + .unwrap(); + indexer.update(&mut batch.build().unwrap()).await; + let output = indexer.finish().await; + assert_eq!( + indexer.check_success().is_err(), + failure.is_some(), + "{failure:?}" + ); + if failure == Some(ProviderFailure::Finish) { + assert_eq!(output.file_size, 0); + assert!(output.entries.is_empty()); + } else { + assert!(output.file_size > 0, "{failure:?}"); + assert_eq!( + output.build_available_indexes().as_slice(), + &[ + crate::sst::file::IndexType::InvertedIndex, + crate::sst::file::IndexType::FulltextIndex, + crate::sst::file::IndexType::BloomFilterIndex, + ], + "{failure:?}" + ); + assert!(!output.build_indexes().unwrap().is_empty()); + } + } + } + + #[rstest::rstest] + #[case::batch(false)] + #[case::flat(true)] + #[tokio::test] + async fn test_mixed_reused_and_scanning_creators(#[case] flat: bool) { + use datatypes::arrow::array::{ArrayRef, Int64Array}; + use datatypes::vectors::{TimestampMillisecondVector, UInt8Vector, UInt64Vector}; + use index::inverted_index::format::reader::InvertedIndexBlobReader; + + let (dir, factory) = PuffinManagerFactory::new_for_test_async("mixed_reuse").await; + let manager = factory.build( + mock_object_store(), + RegionFilePathFactory::new( + "mixed-reuse/".into(), + store_api::region_request::PathType::Bare, + ), + ); + let builder = IndexerBuilderImpl { + index_build_inputs: None, + build_type: IndexBuildType::Compact, + metadata: mock_region_metadata(MetaConfig { + with_inverted: true, + with_fulltext: false, + with_skipping_bloom: false, + }), + puffin_manager: manager.clone(), + write_cache_enabled: false, + intermediate_manager: mock_intm_mgr(dir.path().to_string_lossy()).await, + index_options: IndexOptions::default(), + registry: Arc::new( + registry::IndexRegistry::new( + Default::default(), + Default::default(), + Default::default(), + ) + .with_provider(Some(Arc::new(FailingProvider(ProviderFailure::Reused)))) + .unwrap(), + ), + }; + let file = random_region_file_id(); + let mut indexer = builder.build(file, 0, Some(1024)).await; + assert!(indexer.requires_row_scan()); + let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3])); + if flat { + let batch = RecordBatch::try_from_iter([("a", values)]).unwrap(); + indexer.update_flat(&batch).await; + } else { + let mut batch = crate::read::BatchBuilder::with_required_columns( + Vec::new(), + Arc::new(TimestampMillisecondVector::from_vec(vec![0, 1, 2])), + Arc::new(UInt64Vector::from_vec(vec![0; 3])), + Arc::new(UInt8Vector::from_vec(vec![0; 3])), + ); + batch.push_field_array(1, values).unwrap(); + indexer.update(&mut batch.build().unwrap()).await; + } + indexer.check_success().unwrap(); + let output = indexer.finish().await; + indexer.check_success().unwrap(); + assert_eq!( + output.build_available_indexes().as_slice(), + &[IndexType::InvertedIndex, IndexType::HllIndex] + ); + let reader = manager.reader(&RegionIndexId::new(file, 0)).await.unwrap(); + reader.blob("test-sketch").await.unwrap(); + let blob = reader.blob("greptime-inverted-index-v1").await.unwrap(); + let inverted = InvertedIndexBlobReader::new(blob.reader().await.unwrap()); + let metadata = inverted.metadata(None).await.unwrap(); + assert_eq!(metadata.total_row_count, 3); + } + + #[derive(Debug, Default, Clone)] + struct TestProvider { + build_calls: Arc, + kind: Option, + received_limits: Arc>>>, + hard_limit: Option, + } + + impl handler::IndexKindProvider for TestProvider { + fn handlers(&self) -> Vec> { + vec![Arc::new(self.clone())] + } + } + + impl handler::IndexKindHandler for TestProvider { + fn kinds(&self) -> &[kind::IndexKind] { + match self.kind { + Some(kind::ExtensionIndexKind::Kll) => { + &[kind::IndexKind::Extension(kind::ExtensionIndexKind::Kll)] + } + _ => &[kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll)], + } + } + fn plan( + &self, + _context: &handler::PlanContext<'_>, + ) -> std::result::Result< + Option>, + common_error::ext::BoxedError, + > { + Ok(Some(Arc::new(self.clone()))) + } + } + + #[async_trait::async_trait] + impl handler::PlannedIndex for TestProvider { + fn kinds(&self) -> &[kind::IndexKind] { + handler::IndexKindHandler::kinds(self) + } + fn entries(&self) -> &[handler::PlanEntry] { + match self.kind { + Some(kind::ExtensionIndexKind::Kll) => &[handler::PlanEntry { + column_id: 0, + kind: kind::IndexKind::Extension(kind::ExtensionIndexKind::Kll), + format_version: 2, + }], + _ => &[handler::PlanEntry { + column_id: 0, + kind: kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll), + format_version: 2, + }], + } + } + + fn memory_limit(&self) -> Option { + self.hard_limit + } + + async fn build( + &self, + context: &handler::BuildContext<'_>, + ) -> std::result::Result< + Option>, + common_error::ext::BoxedError, + > { + self.build_calls + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.received_limits + .lock() + .unwrap() + .push(context.memory_limit); + Ok(Some(Box::new(TestCreator))) + } + } + + #[derive(Debug)] + struct TestCreator; + + #[async_trait::async_trait] + impl handler::IndexCreator for TestCreator { + async fn update( + &mut self, + _batch: &mut Batch, + ) -> std::result::Result<(), common_error::ext::BoxedError> { + Ok(()) + } + + async fn update_flat( + &mut self, + _batch: &RecordBatch, + ) -> std::result::Result<(), common_error::ext::BoxedError> { + Ok(()) + } + + async fn finish( + &mut self, + _writer: &mut puffin_manager::SstPuffinWriter, + ) -> std::result::Result, common_error::ext::BoxedError> { + Ok(Vec::new()) + } + + async fn abort(&mut self) -> std::result::Result<(), common_error::ext::BoxedError> { + Ok(()) + } + + fn memory_usage(&self) -> usize { + 17 + } + } + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum ProviderFailure { + None, + Plan, + EmptyKinds, + Reused, + Budget, + Create, + Update, + UpdateFlat, + Finish, + Close, + } + + #[derive(Debug, Clone)] + struct FailingProvider(ProviderFailure); + + fn provider_test_error() -> common_error::ext::BoxedError { + common_error::ext::BoxedError::new(common_error::ext::PlainError::new( + "injected provider failure".into(), + common_error::status_code::StatusCode::Internal, + )) + } + + impl handler::IndexKindProvider for FailingProvider { + fn handlers(&self) -> Vec> { + vec![Arc::new(self.clone())] + } + } + + impl handler::IndexKindHandler for FailingProvider { + fn kinds(&self) -> &[kind::IndexKind] { + &[kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll)] + } + fn plan( + &self, + context: &handler::PlanContext<'_>, + ) -> std::result::Result< + Option>, + common_error::ext::BoxedError, + > { + if self.0 == ProviderFailure::Plan { + return Err(provider_test_error()); + } + if context.build_type == IndexBuildType::Flush { + return Ok(None); + } + Ok(Some(Arc::new(self.clone()))) + } + } + + #[async_trait::async_trait] + impl handler::PlannedIndex for FailingProvider { + fn kinds(&self) -> &[kind::IndexKind] { + if self.0 == ProviderFailure::EmptyKinds { + return &[]; + } + handler::IndexKindHandler::kinds(self) + } + fn entries(&self) -> &[handler::PlanEntry] { + &[handler::PlanEntry { + column_id: 0, + kind: kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll), + format_version: 2, + }] + } + + fn memory_limit(&self) -> Option { + (self.0 == ProviderFailure::Budget).then_some(16) + } + + async fn build( + &self, + _context: &handler::BuildContext<'_>, + ) -> std::result::Result< + Option>, + common_error::ext::BoxedError, + > { + if self.0 == ProviderFailure::Create { + return Err(provider_test_error()); + } + Ok(Some(Box::new(FailingCreator(self.0)))) + } + } + + #[derive(Debug)] + struct FailingCreator(ProviderFailure); + + #[async_trait::async_trait] + impl handler::IndexCreator for FailingCreator { + fn requires_row_scan(&self) -> bool { + self.0 != ProviderFailure::Reused + } + + async fn update( + &mut self, + _batch: &mut Batch, + ) -> std::result::Result<(), common_error::ext::BoxedError> { + if matches!(self.0, ProviderFailure::Update | ProviderFailure::Reused) { + Err(provider_test_error()) + } else { + Ok(()) + } + } + + async fn update_flat( + &mut self, + _batch: &RecordBatch, + ) -> std::result::Result<(), common_error::ext::BoxedError> { + if matches!( + self.0, + ProviderFailure::UpdateFlat | ProviderFailure::Reused + ) { + Err(provider_test_error()) + } else { + Ok(()) + } + } + + async fn finish( + &mut self, + writer: &mut puffin_manager::SstPuffinWriter, + ) -> std::result::Result, common_error::ext::BoxedError> { + use puffin::puffin_manager::PuffinWriter; + + writer + .put_blob( + "test-sketch", + futures::io::Cursor::new(vec![1_u8, 2, 3]), + puffin::puffin_manager::PutOptions::default(), + Default::default(), + ) + .await + .map_err(common_error::ext::BoxedError::new)?; + if self.0 == ProviderFailure::Finish { + // Fail after writing to exercise partially written artifact handling. + return Err(provider_test_error()); + } + Ok(vec![CompletedEntry { + column_id: Some(0), + kind: kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll), + format_version: 2, + }]) + } + + async fn abort(&mut self) -> std::result::Result<(), common_error::ext::BoxedError> { + Ok(()) + } + + fn memory_usage(&self) -> usize { + 17 + } + } + + struct FailingIndexClose { + inner: object_store::layers::mock::Writer, + attempts: Arc, + } + + impl object_store::layers::mock::Write for FailingIndexClose { + async fn write( + &mut self, + bytes: object_store::layers::mock::Buffer, + ) -> object_store::layers::mock::Result<()> { + self.inner.write(bytes).await + } + + async fn close( + &mut self, + ) -> object_store::layers::mock::Result { + self.attempts + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Err(object_store::layers::mock::Error::new( + object_store::layers::mock::ErrorKind::Unexpected, + "injected Puffin close failure", + )) + } + + async fn abort(&mut self) -> object_store::layers::mock::Result<()> { + self.inner.abort().await + } + } + + #[tokio::test] + async fn test_provider_failures_do_not_publish_sketch_descriptors() { + for failure in [ + ProviderFailure::None, + ProviderFailure::Plan, + ProviderFailure::EmptyKinds, + ProviderFailure::Create, + ProviderFailure::Update, + ProviderFailure::UpdateFlat, + ProviderFailure::Finish, + ProviderFailure::Close, + ] { + let (dir, factory) = PuffinManagerFactory::new_for_test_async("provider_failure").await; + let close_attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let store = if failure == ProviderFailure::Close { + let attempts = close_attempts.clone(); + let layer = object_store::layers::mock::MockLayerBuilder::default() + .writer_factory(Arc::new(move |_, _, inner| { + Box::new(FailingIndexClose { + inner, + attempts: attempts.clone(), + }) + })) + .build() + .unwrap(); + mock_object_store().layer(layer) + } else { + mock_object_store() + }; + let manager = factory.build( + store, + crate::access_layer::RegionFilePathFactory::new( + "provider-test/".into(), + store_api::region_request::PathType::Bare, + ), + ); + let builder = IndexerBuilderImpl { + index_build_inputs: None, + build_type: IndexBuildType::Compact, + metadata: mock_region_metadata(MetaConfig { + with_inverted: false, + with_fulltext: false, + with_skipping_bloom: false, + }), + puffin_manager: manager, + write_cache_enabled: false, + intermediate_manager: mock_intm_mgr(dir.path().to_string_lossy()).await, + index_options: IndexOptions::default(), + registry: Arc::new( + registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + ) + .with_provider(Some(Arc::new(FailingProvider(failure)))) + .unwrap(), + ), + }; + let mut indexer = builder.build(random_region_file_id(), 0, Some(1024)).await; + if failure == ProviderFailure::Update { + let mut batch = crate::read::BatchBuilder::with_required_columns( + Vec::new(), + Arc::new(datatypes::vectors::TimestampMillisecondVector::from_vec( + vec![0], + )), + Arc::new(datatypes::vectors::UInt64Vector::from_vec(vec![0])), + Arc::new(datatypes::vectors::UInt8Vector::from_vec(vec![0])), + ) + .build() + .unwrap(); + indexer.update(&mut batch).await; + } else { + indexer + .update_flat(&new_record_batch_by_range(&["a", "b"], 0, 1)) + .await; + } + let output = indexer.finish().await; + if failure == ProviderFailure::None { + assert_eq!( + output + .entries + .iter() + .filter(|entry| !entry.kind.is_builtin()) + .count(), + 1 + ); + assert!(output.file_size > 0); + assert!(output.build_indexes().unwrap().iter().any(|index| { + index.created_indexes.iter().any(|kind| { + matches!( + kind, + crate::sst::file::IndexType::HllIndex + | crate::sst::file::IndexType::KllIndex + | crate::sst::file::IndexType::MgIndex + ) + }) + })); + } else { + assert!( + output.entries.iter().all(|entry| entry.kind.is_builtin()), + "{failure:?}" + ); + assert!(output.build_indexes().unwrap().is_empty(), "{failure:?}"); + assert_eq!(output.file_size, 0, "{failure:?}"); + } + assert!(indexer.creators.is_empty()); + assert_eq!( + indexer.check_success().is_err(), + failure != ProviderFailure::None + ); + assert_eq!( + close_attempts.load(std::sync::atomic::Ordering::Relaxed), + usize::from(failure == ProviderFailure::Close) + ); + } + } + + #[tokio::test] + async fn test_provider_compaction_only_and_per_output() { + let (dir, factory) = PuffinManagerFactory::new_for_test_async("provider_scope").await; + let provider = Arc::new(TestProvider { + hard_limit: Some(17), + ..Default::default() + }); + let mut builder = IndexerBuilderImpl { + index_build_inputs: None, + build_type: IndexBuildType::Flush, + metadata: mock_region_metadata(MetaConfig { + with_inverted: false, + with_fulltext: false, + with_skipping_bloom: false, + }), + puffin_manager: factory.build(mock_object_store(), NoopPathProvider), + write_cache_enabled: false, + intermediate_manager: mock_intm_mgr(dir.path().to_string_lossy()).await, + index_options: IndexOptions::default(), + registry: Arc::new( + registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + ) + .with_provider(Some(provider.clone())) + .unwrap(), + ), + }; + let flush = builder.build(random_region_file_id(), 0, Some(1024)).await; + assert!(flush.creators.is_empty()); + assert_eq!( + provider + .build_calls + .load(std::sync::atomic::Ordering::Relaxed), + 0 + ); + + builder.build_type = IndexBuildType::Compact; + let mut first = builder.build(random_region_file_id(), 0, Some(1024)).await; + let mut second = builder.build(random_region_file_id(), 0, Some(1024)).await; + assert_eq!( + provider + .build_calls + .load(std::sync::atomic::Ordering::Relaxed), + 2 + ); + assert!(!first.is_empty()); + assert!(!second.is_empty()); + assert_eq!(first.creators[0].creator.memory_usage(), 17); + first.abort().await; + assert!(first.creators.is_empty()); + assert!(!second.creators.is_empty()); + second.abort().await; + + // Reject a creator at preparation when its retained state already exceeds + // the caller's allocation; equality is allowed. + let plan = builder.registry.plan(&handler::PlanContext { + metadata: &builder.metadata, + index_options: &builder.index_options, + build_type: builder.build_type.clone(), + existing_indexes: &[], + }); + builder.index_build_inputs = Some(build::IndexBuildInputs { + output_rows: None, + plan: Arc::new(plan), + inputs: Arc::from([]), + input_puffin_manager: builder.puffin_manager.clone(), + can_merge_inputs: false, + memory_limit: Some(16), + }); + let rejected = builder.build(random_region_file_id(), 0, Some(1024)).await; + assert!(rejected.is_empty()); + builder.index_build_inputs.as_mut().unwrap().memory_limit = Some(17); + let mut bounded = builder.build(random_region_file_id(), 0, Some(1024)).await; + assert!(!bounded.creators.is_empty()); + bounded.creators[0].memory_limit = Some(16); + bounded.enforce_memory_limits().await; + bounded.flush_mem_metrics(); + assert!(bounded.creators.is_empty()); + + // A larger operation allocation must not relax the handler's ceiling. + builder.index_build_inputs.as_mut().unwrap().memory_limit = Some(34); + let mut bounded = builder.build(random_region_file_id(), 0, Some(1024)).await; + assert_eq!(bounded.creators[0].memory_limit, Some(17)); + bounded.abort().await; + } + + #[tokio::test] + async fn test_builder_passes_remaining_extension_budget() { + let (dir, factory) = PuffinManagerFactory::new_for_test_async("build_budget").await; + for (operation_limit, ceiling, expected, retained) in [ + (Some(30), None, vec![Some(30), Some(13)], 1), + (Some(17), None, vec![Some(17), Some(0)], 1), + (Some(30), Some(20), vec![Some(20), Some(13)], 1), + (Some(40), Some(20), vec![Some(20), Some(20)], 2), + (Some(16), None, vec![Some(16), Some(16)], 0), + (None, None, vec![None, None], 2), + (None, Some(17), vec![Some(17), Some(17)], 2), + ] { + let observed = Arc::new(std::sync::Mutex::new(Vec::new())); + let mut registry = registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + ); + for kind in [kind::ExtensionIndexKind::Hll, kind::ExtensionIndexKind::Kll] { + registry + .register(Arc::new(TestProvider { + kind: Some(kind), + received_limits: observed.clone(), + hard_limit: ceiling, + ..Default::default() + })) + .unwrap(); + } + let mut builder = IndexerBuilderImpl { + index_build_inputs: None, + build_type: IndexBuildType::Compact, + metadata: mock_region_metadata(MetaConfig { + with_inverted: false, + with_fulltext: false, + with_skipping_bloom: false, + }), + puffin_manager: factory.build(mock_object_store(), NoopPathProvider), + write_cache_enabled: false, + intermediate_manager: mock_intm_mgr(dir.path().to_string_lossy()).await, + index_options: IndexOptions::default(), + registry: Arc::new(registry), + }; + let plan = builder.registry.plan(&handler::PlanContext { + metadata: &builder.metadata, + index_options: &builder.index_options, + build_type: builder.build_type.clone(), + existing_indexes: &[], + }); + builder.index_build_inputs = Some(build::IndexBuildInputs { + output_rows: None, + plan: Arc::new(plan), + inputs: Arc::from([]), + input_puffin_manager: builder.puffin_manager.clone(), + can_merge_inputs: false, + memory_limit: operation_limit, + }); + let mut indexer = builder.build(random_region_file_id(), 0, Some(1024)).await; + assert_eq!(*observed.lock().unwrap(), expected); + assert_eq!(indexer.creators.len(), retained); + indexer.abort().await; + } + } + + #[tokio::test] + async fn test_extension_creators_share_memory_budget() { + for (limit, expected_extensions) in [(34, 2), (33, 1), (16, 0)] { + let mut indexer = Indexer { + extension_memory_limit: Some(limit), + ..Default::default() + }; + // Built-in state uses its own spill budget and does not consume the + // optional extension allocation. Each test creator retains 17 bytes. + indexer.push_creator( + vec![kind::IndexKind::Inverted], + Box::new(TestCreator), + None, + TYPE_INVERTED_INDEX, + ); + for kind in [kind::ExtensionIndexKind::Hll, kind::ExtensionIndexKind::Kll] { + indexer.push_creator( + vec![kind::IndexKind::Extension(kind)], + Box::new(TestCreator), + Some(34), + TYPE_EXTENSION_INDEX, + ); + } + let before = INDEX_CREATE_DISCARDED_TOTAL + .with_label_values(&["kll_index", "memory_budget_exceeded"]) + .get(); + indexer.enforce_memory_limits().await; + assert_eq!(indexer.creators.len(), 1 + expected_extensions); + assert!(indexer.check_success().is_ok()); + assert_eq!(indexer.discarded().len(), 2 - expected_extensions); + let kinds = [ + kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll), + kind::IndexKind::Extension(kind::ExtensionIndexKind::Kll), + ]; + assert_eq!(indexer.discarded(), &kinds[expected_extensions..]); + if expected_extensions < 2 { + assert!( + INDEX_CREATE_DISCARDED_TOTAL + .with_label_values(&["kll_index", "memory_budget_exceeded"]) + .get() + > before + ); + } + assert!(indexer.creators[0].is_builtin()); + } + } + #[test] fn test_file_level_completion_preserves_json_only_index() { let output = IndexOutput { @@ -1732,6 +2690,50 @@ mod tests { assert!(output.build_indexes().unwrap().is_empty()); } + #[test] + fn test_completed_entries_preserve_all_kinds_in_order() { + use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; + + let output = IndexOutput { + entries: [ + IndexKind::Extension(ExtensionIndexKind::Mg), + IndexKind::Fulltext, + IndexKind::Extension(ExtensionIndexKind::Kll), + IndexKind::Bloom, + IndexKind::Extension(ExtensionIndexKind::Hll), + IndexKind::Inverted, + IndexKind::Extension(ExtensionIndexKind::Hll), + ] + .into_iter() + .enumerate() + .map(|(position, kind)| CompletedEntry { + column_id: Some(if position == 6 { 2 } else { 1 }), + kind, + format_version: 0, + }) + .collect(), + ..Default::default() + }; + let expected = [ + IndexType::InvertedIndex, + IndexType::FulltextIndex, + IndexType::BloomFilterIndex, + IndexType::HllIndex, + IndexType::KllIndex, + IndexType::MgIndex, + ]; + let available = output.build_available_indexes(); + assert_eq!(available.as_slice(), &expected); + assert!(!available.spilled()); + let columns = output.build_indexes().unwrap(); + assert_eq!(columns.len(), 2); + assert_eq!(columns[0].created_indexes.as_slice(), &expected); + assert_eq!( + columns[1].created_indexes.as_slice(), + &[IndexType::HllIndex] + ); + } + #[test] fn test_completed_entries_preserve_builtin_metadata() { use crate::sst::index::kind::IndexKind; @@ -1822,6 +2824,10 @@ mod tests { assert!(entry.validate().is_ok()); entry.format_version += 1; assert!(entry.validate().is_err()); + entry.kind = kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll); + assert!(entry.validate().is_ok()); // Extension versions belong to Puffin. + entry.column_id = None; + assert!(entry.validate().is_err()); } #[tokio::test] @@ -1836,6 +2842,7 @@ mod tests { with_skipping_bloom: true, }); let indexer = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata, puffin_manager: factory.build(mock_object_store(), NoopPathProvider), @@ -1868,6 +2875,7 @@ mod tests { with_skipping_bloom: true, }); let indexer = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata: metadata.clone(), puffin_manager: factory.build(mock_object_store(), NoopPathProvider), @@ -1891,6 +2899,7 @@ mod tests { assert!(indexer.has_kind(kind::IndexKind::Bloom)); let indexer = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Compact, metadata: metadata.clone(), puffin_manager: factory.build(mock_object_store(), NoopPathProvider), @@ -1914,6 +2923,7 @@ mod tests { assert!(indexer.has_kind(kind::IndexKind::Bloom)); let indexer = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Compact, metadata, puffin_manager: factory.build(mock_object_store(), NoopPathProvider), @@ -1949,6 +2959,7 @@ mod tests { with_skipping_bloom: true, }); let indexer = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata: metadata.clone(), puffin_manager: factory.build(mock_object_store(), NoopPathProvider), @@ -1974,6 +2985,7 @@ mod tests { with_skipping_bloom: true, }); let indexer = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata: metadata.clone(), puffin_manager: factory.build(mock_object_store(), NoopPathProvider), @@ -1999,6 +3011,7 @@ mod tests { with_skipping_bloom: false, }); let indexer = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata: metadata.clone(), puffin_manager: factory.build(mock_object_store(), NoopPathProvider), @@ -2031,6 +3044,7 @@ mod tests { with_skipping_bloom: true, }); let indexer = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata, puffin_manager: factory.build(mock_object_store(), NoopPathProvider), @@ -2433,6 +3447,7 @@ mod tests { ); // Indexer builder built from write cache. let indexer_builder = Arc::new(IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata: metadata.clone(), puffin_manager: write_cache.build_puffin_manager().clone(), diff --git a/src/mito2/src/sst/index/build.rs b/src/mito2/src/sst/index/build.rs new file mode 100644 index 00000000000..863aa84b7a4 --- /dev/null +++ b/src/mito2/src/sst/index/build.rs @@ -0,0 +1,46 @@ +// 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. + +//! Shared index plans and physical inputs carried into SST writers. + +use std::sync::Arc; + +use crate::sst::file::FileHandle; +use crate::sst::index::puffin_manager::SstPuffinManager; +use crate::sst::index::registry::IndexBuildPlan; + +/// An immutable plan with operation-scoped input files and output constraints. +/// Currently compaction and explicit rebuild supply these inputs; flush does not +/// inject extension handlers and builds only the existing built-in indexes. +#[derive(Clone)] +pub struct IndexBuildInputs { + /// Typed plans shared by output files of this operation. + pub plan: Arc, + /// Pinned physical input files; flushes have no inputs. + pub inputs: Arc<[FileHandle]>, + /// Reads persisted inputs even when output uses a local write cache. + /// Input availability is determined by `inputs.is_empty()`, not this manager. + pub input_puffin_manager: SstPuffinManager, + /// Allows coarse input reuse only for the complete input scope without slicing. + /// The caller that owns the output plan validates this scope. + /// This is not a promise that input rows equal live output rows: deduplication + /// or deletion may remove rows. Handlers must record input-derived coverage + /// separately from actual output counts when reusing approximate summaries. + pub can_merge_inputs: bool, + /// Existing allocation available to optional index creators; `None` sets no limit here. + /// Single-region compaction and rebuild currently provide no shared total limit. + pub memory_limit: Option, + /// Exact row count of an unchanged SST during rebuild, otherwise unknown. + pub output_rows: Option, +} diff --git a/src/mito2/src/sst/index/column_test.rs b/src/mito2/src/sst/index/column_test.rs index db6e3f58dd4..a9d3ef9cf1b 100644 --- a/src/mito2/src/sst/index/column_test.rs +++ b/src/mito2/src/sst/index/column_test.rs @@ -188,6 +188,7 @@ async fn materialized_runs_match_legacy_index_bytes_and_bloom_lookups() { let mut options = IndexOptions::default(); options.inverted_index.segment_row_count = 3; let builder = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata: metadata.clone(), puffin_manager: puffin.clone(), diff --git a/src/mito2/src/sst/index/handler.rs b/src/mito2/src/sst/index/handler.rs index 31ff82d3bb5..dba75c143ce 100644 --- a/src/mito2/src/sst/index/handler.rs +++ b/src/mito2/src/sst/index/handler.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Planning and creation contracts for built-in indexes. +//! Planning and creation contracts for built-in and injected indexes. pub(crate) mod builtin; @@ -24,63 +24,128 @@ use common_error::ext::BoxedError; use datatypes::arrow::record_batch::RecordBatch; use index::target::IndexTarget; use store_api::metadata::RegionMetadataRef; +use store_api::storage::ColumnId; use crate::read::Batch; use crate::region::options::IndexOptions; -use crate::sst::file::RegionIndexId; +use crate::sst::file::{ColumnIndexMetadata, FileHandle, RegionIndexId}; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::kind::IndexKind; -use crate::sst::index::puffin_manager::SstPuffinWriter; +use crate::sst::index::puffin_manager::{SstPuffinManager, SstPuffinWriter}; use crate::sst::index::{CompletedEntry, IndexBuildType}; +/// A requested column format; typed implementation parameters stay in its plan. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlanEntry { + /// Column to index. + pub column_id: ColumnId, + /// Implementation owning this entry. + pub kind: IndexKind, + /// Requested format version. The manifest records extension types, not versions. + /// A format upgrade requires a forced rebuild; the provider validates Puffin + /// properties and payload compatibility before reusing input state. + pub format_version: u32, +} + /// Schema and options used to prepare work without reading input files. -pub(crate) struct PlanContext<'a> { +pub struct PlanContext<'a> { /// Shared region schema. pub metadata: &'a RegionMetadataRef, /// Region index options. pub index_options: &'a IndexOptions, /// Lifecycle event requesting the build. pub build_type: IndexBuildType, + /// Existing column descriptors of the target SST during rebuild. + /// Empty for new outputs, including compaction; input descriptors are available + /// through [`BuildContext::inputs`] when constructing a creator. + pub existing_indexes: &'a [ColumnIndexMetadata], } /// Inputs for constructing all of one handler's indexes in a single output file. -pub(crate) struct BuildContext<'a> { +pub struct BuildContext<'a> { /// Shared output schema. pub metadata: &'a RegionMetadataRef, /// Physical output index identity. pub output: RegionIndexId, + /// Output manager, possibly backed by a local write cache. + pub puffin_manager: &'a SstPuffinManager, /// Existing intermediate-file facility shared by built-in creators. pub intermediate_manager: &'a IntermediateManager, + /// Pinned physical input files. + pub inputs: &'a [FileHandle], + /// Manager for reading persisted input indexes. With no inputs this falls back + /// to the output manager; determine input availability from `inputs.is_empty()`. + pub input_puffin_manager: &'a SstPuffinManager, + /// Permits coarse input-summary reuse only for a complete single output. + /// The caller that owns the output plan verifies this scope before construction. + pub can_merge_inputs: bool, + /// Retained-memory allowance for an injected creator, capped by the remaining + /// operation budget and its plan ceiling. `None` applies no limit at this layer. + /// Built-in creators use spill budgets. + pub memory_limit: Option, /// Actual output row-group size used to align inverted-index segments. pub row_group_size: Option, + /// Exact row count when rebuilding an existing SST; unknown for compaction outputs. + pub output_rows: Option, } -/// Prepares one built-in index implementation. -pub(crate) trait IndexKindHandler: Send + Sync + Debug { - /// Built-in implementation owned by this handler. - fn kind(&self) -> IndexKind; +/// Shared plugin installed by the embedding application. +pub type IndexKindProviderRef = Arc; - /// Prepares typed parameters. `None` means no work. +/// Supplies extension handlers while the engine retains the complete lifecycle. +pub trait IndexKindProvider: Send + Sync + Debug { + /// Related algorithms may share one handler to reuse row traversal. + fn handlers(&self) -> Vec>; +} + +/// Owns one or more related kinds that can share preparation and row traversal. +pub trait IndexKindHandler: Send + Sync + Debug { + /// Nonempty, unique kinds exclusively owned by this handler. A group must be + /// entirely built-in or entirely extension kinds. + fn kinds(&self) -> &[IndexKind]; + + /// Prepares typed parameters. `None` means no work; an empty entry list may + /// still request removal of obsolete descriptors during maintenance. fn plan(&self, context: &PlanContext<'_>) -> Result>, BoxedError>; } /// An immutable typed plan shared by output files of an operation. #[async_trait] -pub(crate) trait PlannedIndex: Send + Sync + Debug { - /// Built-in implementation owned by this plan. - fn kind(&self) -> IndexKind; +pub trait PlannedIndex: Send + Sync + Debug { + /// Nonempty, unique subset of the handler's kinds, including removal plans. + fn kinds(&self) -> &[IndexKind]; - /// Creates a per-file index creator before any output batch is consumed. + /// Requested column formats. Every entry kind must belong to this plan. + fn entries(&self) -> &[PlanEntry]; + + /// Prepares input reuse before any output batch is consumed. async fn build( &self, context: &BuildContext<'_>, ) -> Result>, BoxedError>; + + /// Whether building this plan can reuse persisted input summaries. + /// Row-only plans do not require checking input object existence. + fn needs_input_reuse(&self) -> bool { + false + } + + /// Optional hard ceiling; built-in creators use their existing spill budgets. + fn memory_limit(&self) -> Option { + None + } } /// Accumulates rows and writes blobs into the engine-owned Puffin lifecycle. /// Implementations release retained state on drop, including cancellation. #[async_trait] -pub(crate) trait IndexCreator: Send { +pub trait IndexCreator: Send { + /// Whether rebuilding this index requires scanning SST rows after preparation. + /// A creator reusing persisted state must account for output rows without updates. + fn requires_row_scan(&self) -> bool { + true + } + /// Borrows a batch and its reusable primary-key decode cache. async fn update(&mut self, batch: &mut Batch) -> Result<(), BoxedError>; diff --git a/src/mito2/src/sst/index/handler/builtin.rs b/src/mito2/src/sst/index/handler/builtin.rs index ec21eaf00f2..c814cb4b43b 100644 --- a/src/mito2/src/sst/index/handler/builtin.rs +++ b/src/mito2/src/sst/index/handler/builtin.rs @@ -27,7 +27,7 @@ use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig} use crate::sst::index::handler::builtin::bloom::BloomPlan; use crate::sst::index::handler::builtin::fulltext::FulltextPlan; use crate::sst::index::handler::builtin::inverted::InvertedPlan; -use crate::sst::index::handler::{IndexKindHandler, PlanContext, PlannedIndex}; +use crate::sst::index::handler::{IndexKindHandler, PlanContext, PlanEntry, PlannedIndex}; use crate::sst::index::kind::IndexKind; /// Configuration for one of the existing file-level built-in creators. @@ -39,11 +39,11 @@ pub(crate) enum BuiltinIndexHandler { } impl IndexKindHandler for BuiltinIndexHandler { - fn kind(&self) -> IndexKind { + fn kinds(&self) -> &[IndexKind] { match self { - Self::Inverted(_) => IndexKind::Inverted, - Self::Fulltext(_) => IndexKind::Fulltext, - Self::Bloom(_) => IndexKind::Bloom, + Self::Inverted(_) => &[IndexKind::Inverted], + Self::Fulltext(_) => &[IndexKind::Fulltext], + Self::Bloom(_) => &[IndexKind::Bloom], } } @@ -57,6 +57,13 @@ impl IndexKindHandler for BuiltinIndexHandler { } } +fn target_column_id(target: &IndexTarget) -> store_api::storage::ColumnId { + match target { + IndexTarget::ColumnId(id) => *id, + IndexTarget::JsonPath(path) => path.column_id(), + } +} + fn column_target_id(target: &IndexTarget) -> Option { match target { IndexTarget::ColumnId(id) => Some(*id), @@ -64,6 +71,18 @@ fn column_target_id(target: &IndexTarget) -> Option) { + entries.sort_by_key(|entry| (entry.column_id, entry.format_version)); + entries.dedup_by(|a, b| { + if a.column_id == b.column_id { + b.format_version = b.format_version.max(a.format_version); + true + } else { + false + } + }); +} + #[cfg(test)] mod tests { use super::*; @@ -103,6 +122,7 @@ mod tests { metadata: &metadata, index_options: &options, build_type: IndexBuildType::Flush, + existing_indexes: &[], }; assert!(handler.plan(&context).is_err()); } diff --git a/src/mito2/src/sst/index/handler/builtin/bloom.rs b/src/mito2/src/sst/index/handler/builtin/bloom.rs index 1b011b79086..aff50955bb8 100644 --- a/src/mito2/src/sst/index/handler/builtin/bloom.rs +++ b/src/mito2/src/sst/index/handler/builtin/bloom.rs @@ -25,8 +25,10 @@ use index::target::IndexTarget; use crate::config::BloomFilterConfig; use crate::read::Batch; use crate::sst::index::bloom_filter::creator::BloomFilterIndexer; -use crate::sst::index::handler::builtin::column_target_id; -use crate::sst::index::handler::{BuildContext, IndexCreator, PlanContext, PlannedIndex}; +use crate::sst::index::handler::builtin::{column_target_id, normalize_entries, target_column_id}; +use crate::sst::index::handler::{ + BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex, +}; use crate::sst::index::kind::IndexKind; use crate::sst::index::puffin_manager::SstPuffinWriter; use crate::sst::index::{CompletedEntry, IndexBuildType}; @@ -35,6 +37,7 @@ use crate::sst::index::{CompletedEntry, IndexBuildType}; #[derive(Debug)] pub(crate) struct BloomPlan { config: BloomFilterConfig, + entries: Vec, targets: Vec<(IndexTarget, SkippingIndexOptions)>, } @@ -53,18 +56,26 @@ impl BloomPlan { return Ok(None); } let mut targets = Vec::new(); + let mut entries = Vec::new(); for column in &context.metadata.column_metadatas { for (target, options) in BloomFilterIndexer::targets(column, &context.build_type).map_err(BoxedError::new)? { + entries.push(PlanEntry { + column_id: target_column_id(&target), + kind: IndexKind::Bloom, + format_version: 0, + }); targets.push((target, options)); } } - if targets.is_empty() { + normalize_entries(&mut entries); + if entries.is_empty() { return Ok(None); } Ok(Some(Arc::new(Self { config: config.clone(), + entries, targets, }))) } @@ -72,8 +83,12 @@ impl BloomPlan { #[async_trait] impl PlannedIndex for BloomPlan { - fn kind(&self) -> IndexKind { - IndexKind::Bloom + fn kinds(&self) -> &[IndexKind] { + &[IndexKind::Bloom] + } + + fn entries(&self) -> &[PlanEntry] { + &self.entries } async fn build( diff --git a/src/mito2/src/sst/index/handler/builtin/fulltext.rs b/src/mito2/src/sst/index/handler/builtin/fulltext.rs index 160b7923f49..4a287ef4017 100644 --- a/src/mito2/src/sst/index/handler/builtin/fulltext.rs +++ b/src/mito2/src/sst/index/handler/builtin/fulltext.rs @@ -19,14 +19,17 @@ use std::sync::Arc; use async_trait::async_trait; use common_error::ext::BoxedError; use datatypes::arrow::record_batch::RecordBatch; +use datatypes::schema::FulltextBackend; use index::target::IndexTarget; use crate::config::FulltextIndexConfig; use crate::read::Batch; use crate::sst::index::fulltext_index; use crate::sst::index::fulltext_index::creator::{FulltextIndexer, FulltextTarget}; -use crate::sst::index::handler::builtin::column_target_id; -use crate::sst::index::handler::{BuildContext, IndexCreator, PlanContext, PlannedIndex}; +use crate::sst::index::handler::builtin::{column_target_id, normalize_entries, target_column_id}; +use crate::sst::index::handler::{ + BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex, +}; use crate::sst::index::kind::IndexKind; use crate::sst::index::puffin_manager::SstPuffinWriter; use crate::sst::index::{CompletedEntry, IndexBuildType}; @@ -35,6 +38,7 @@ use crate::sst::index::{CompletedEntry, IndexBuildType}; #[derive(Debug)] pub(crate) struct FulltextPlan { config: FulltextIndexConfig, + entries: Vec, targets: Vec, } @@ -53,10 +57,20 @@ impl FulltextPlan { return Ok(None); } let mut targets = Vec::new(); + let mut entries = Vec::new(); for column in &context.metadata.column_metadatas { for (target, options) in FulltextIndexer::targets(column, &context.build_type).map_err(BoxedError::new)? { + entries.push(PlanEntry { + column_id: target_column_id(&target), + kind: IndexKind::Fulltext, + format_version: if options.backend == FulltextBackend::Bloom { + u32::from(fulltext_index::FULLTEXT_BLOOM_VERSION) + } else { + 0 + }, + }); targets.push(( column.column_id, column.column_schema.name.clone(), @@ -65,11 +79,13 @@ impl FulltextPlan { )); } } - if targets.is_empty() { + normalize_entries(&mut entries); + if entries.is_empty() { return Ok(None); } Ok(Some(Arc::new(Self { config: config.clone(), + entries, targets, }))) } @@ -77,8 +93,12 @@ impl FulltextPlan { #[async_trait] impl PlannedIndex for FulltextPlan { - fn kind(&self) -> IndexKind { - IndexKind::Fulltext + fn kinds(&self) -> &[IndexKind] { + &[IndexKind::Fulltext] + } + + fn entries(&self) -> &[PlanEntry] { + &self.entries } async fn build( diff --git a/src/mito2/src/sst/index/handler/builtin/inverted.rs b/src/mito2/src/sst/index/handler/builtin/inverted.rs index baf87f93258..353afd5cff9 100644 --- a/src/mito2/src/sst/index/handler/builtin/inverted.rs +++ b/src/mito2/src/sst/index/handler/builtin/inverted.rs @@ -27,8 +27,10 @@ use index::target::IndexTarget; use crate::config::InvertedIndexConfig; use crate::read::Batch; -use crate::sst::index::handler::builtin::column_target_id; -use crate::sst::index::handler::{BuildContext, IndexCreator, PlanContext, PlannedIndex}; +use crate::sst::index::handler::builtin::{column_target_id, normalize_entries, target_column_id}; +use crate::sst::index::handler::{ + BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex, +}; use crate::sst::index::inverted_index::creator::InvertedIndexer; use crate::sst::index::kind::IndexKind; use crate::sst::index::puffin_manager::SstPuffinWriter; @@ -38,6 +40,7 @@ use crate::sst::index::{CompletedEntry, IndexBuildType}; #[derive(Debug)] pub(crate) struct InvertedPlan { config: InvertedIndexConfig, + entries: Vec, targets: Vec, segment_row_count: NonZeroUsize, } @@ -78,11 +81,21 @@ impl InvertedPlan { ); return Ok(None); }; - if targets.is_empty() { + let mut entries: Vec<_> = targets + .iter() + .map(|target| PlanEntry { + column_id: target_column_id(target), + kind: IndexKind::Inverted, + format_version: 0, + }) + .collect(); + normalize_entries(&mut entries); + if entries.is_empty() { return Ok(None); } Ok(Some(Arc::new(Self { config: config.clone(), + entries, targets, segment_row_count, }))) @@ -91,8 +104,12 @@ impl InvertedPlan { #[async_trait] impl PlannedIndex for InvertedPlan { - fn kind(&self) -> IndexKind { - IndexKind::Inverted + fn kinds(&self) -> &[IndexKind] { + &[IndexKind::Inverted] + } + + fn entries(&self) -> &[PlanEntry] { + &self.entries } async fn build( @@ -250,6 +267,7 @@ mod tests { metadata: &metadata, index_options: &options, build_type: build_type.clone(), + existing_indexes: &[], }; let plan = InvertedPlan::plan(&config, &context).unwrap().unwrap(); let columns: Vec<_> = plan diff --git a/src/mito2/src/sst/index/indexer/abort.rs b/src/mito2/src/sst/index/indexer/abort.rs index e34b8ba4e7f..0bc659666b1 100644 --- a/src/mito2/src/sst/index/indexer/abort.rs +++ b/src/mito2/src/sst/index/indexer/abort.rs @@ -22,10 +22,10 @@ impl Indexer { pub(crate) async fn abort_creator(&mut self, position: usize) { let mut active = self.creators.remove(position); if let Err(err) = active.creator.abort().await { - if cfg!(any(test, feature = "test")) { + if active.is_builtin() && cfg!(any(test, feature = "test")) { panic!("Failed to abort index: {err:?}"); } - warn!(err; "Failed to abort index, region_id: {}, file_id: {}, kind: {:?}", self.region_id, self.file_id, active.kind); + warn!(err; "Failed to abort index, region_id: {}, file_id: {}, kinds: {:?}", self.region_id, self.file_id, active.kinds); } } diff --git a/src/mito2/src/sst/index/indexer/finish.rs b/src/mito2/src/sst/index/indexer/finish.rs index 366bde9a196..30c3064c9fe 100644 --- a/src/mito2/src/sst/index/indexer/finish.rs +++ b/src/mito2/src/sst/index/indexer/finish.rs @@ -12,6 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::sync::Arc; + +use common_error::ext::BoxedError; use common_telemetry::warn; use puffin::puffin_manager::{PuffinManager, PuffinWriter}; @@ -37,6 +40,7 @@ impl Indexer { Ok(entries) => { if let Err(err) = entries.iter().try_for_each(|entry| entry.validate()) { warn!(err; "Invalid index completion, region_id: {}, file_id: {}", self.region_id, self.file_id); + self.failure.get_or_insert_with(|| Arc::new(err)); drop(active); self.do_abort().await; return IndexOutput::default(); @@ -44,10 +48,11 @@ impl Indexer { output.entries.extend(entries); } Err(err) => { - if cfg!(any(test, feature = "test")) { + if active.is_builtin() && cfg!(any(test, feature = "test")) { panic!("Failed to finish index: {err:?}"); } - warn!(err; "Failed to finish index, region_id: {}, file_id: {}, kind: {:?}", self.region_id, self.file_id, active.kind); + warn!(err; "Failed to finish index, region_id: {}, file_id: {}, kinds: {:?}", self.region_id, self.file_id, active.kinds); + self.record_failure(err); drop(active); self.do_abort().await; return IndexOutput::default(); @@ -89,6 +94,7 @@ impl Indexer { ); } + self.record_failure(BoxedError::new(err)); None } @@ -105,6 +111,7 @@ impl Indexer { self.region_id, self.file_id, ); + self.record_failure(BoxedError::new(err)); 0 } diff --git a/src/mito2/src/sst/index/indexer/update.rs b/src/mito2/src/sst/index/indexer/update.rs index 54cdf254586..98fcbd3949b 100644 --- a/src/mito2/src/sst/index/indexer/update.rs +++ b/src/mito2/src/sst/index/indexer/update.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::sync::Arc; + use common_telemetry::warn; use datatypes::arrow::record_batch::RecordBatch; @@ -28,20 +30,30 @@ impl Indexer { panic!("Failed to decode primary key for indexes: {err:?}"); } warn!(err; "Failed to decode primary key for indexes, region_id: {}, file_id: {}", self.region_id, self.file_id); + self.failure.get_or_insert_with(|| Arc::new(err)); self.do_abort().await; return; } let mut position = 0; while position < self.creators.len() { + if !self.creators[position].creator.requires_row_scan() { + position += 1; + continue; + } match self.creators[position].creator.update(batch).await { Ok(()) => position += 1, Err(err) => { - if cfg!(any(test, feature = "test")) { + let builtin = self.creators[position].is_builtin(); + if builtin && cfg!(any(test, feature = "test")) { panic!("Failed to update index: {err:?}"); } - warn!(err; "Failed to update index, region_id: {}, file_id: {}, kind: {:?}", self.region_id, self.file_id, self.creators[position].kind); - self.do_abort().await; - return; + warn!(err; "Failed to update index, region_id: {}, file_id: {}, kinds: {:?}", self.region_id, self.file_id, self.creators[position].kinds); + self.record_failure(err); + if builtin { + self.do_abort().await; + return; + } + self.abort_creator(position).await; } } } @@ -53,15 +65,24 @@ impl Indexer { } let mut position = 0; while position < self.creators.len() { + if !self.creators[position].creator.requires_row_scan() { + position += 1; + continue; + } match self.creators[position].creator.update_flat(batch).await { Ok(()) => position += 1, Err(err) => { - if cfg!(any(test, feature = "test")) { + let builtin = self.creators[position].is_builtin(); + if builtin && cfg!(any(test, feature = "test")) { panic!("Failed to update flat index: {err:?}"); } - warn!(err; "Failed to update flat index, region_id: {}, file_id: {}, kind: {:?}", self.region_id, self.file_id, self.creators[position].kind); - self.do_abort().await; - return; + warn!(err; "Failed to update flat index, region_id: {}, file_id: {}, kinds: {:?}", self.region_id, self.file_id, self.creators[position].kinds); + self.record_failure(err); + if builtin { + self.do_abort().await; + return; + } + self.abort_creator(position).await; } } } diff --git a/src/mito2/src/sst/index/kind.rs b/src/mito2/src/sst/index/kind.rs index e55c837bc55..a997bd7ed8f 100644 --- a/src/mito2/src/sst/index/kind.rs +++ b/src/mito2/src/sst/index/kind.rs @@ -16,30 +16,78 @@ use crate::sst::file::IndexType; -/// Index implementations supplied by the storage engine. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub(crate) enum IndexKind { +/// An index implementation known to the storage engine or supplied by a plugin. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum IndexKind { + /// Inverted index. Inverted, + /// Full-text index. Fulltext, + /// Bloom filter index. Bloom, + /// An index whose implementation is supplied by the embedding application. + Extension(ExtensionIndexKind), +} + +/// Extension algorithm identities; implementations remain outside mito2. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ExtensionIndexKind { + /// HyperLogLog distinct-value estimate. + Hll, + /// KLL rank estimate. + Kll, + /// Misra–Gries frequency estimate. + Mg, +} + +impl ExtensionIndexKind { + /// Known extension algorithms checked by operation-level provider validation. + pub const ALL: [Self; 3] = [Self::Hll, Self::Kll, Self::Mg]; + + /// Column metadata key that requires this algorithm's provider. + pub const fn required_metadata_key(self) -> &'static str { + match self { + Self::Hll => datatypes::schema::HLL_KEY, + Self::Kll => datatypes::schema::KLL_KEY, + Self::Mg => datatypes::schema::MG_KEY, + } + } + + /// Stable label used by index diagnostics and metrics. + pub const fn as_str(self) -> &'static str { + match self { + Self::Hll => "hll_index", + Self::Kll => "kll_index", + Self::Mg => "mg_index", + } + } } impl IndexKind { /// Stable label used by the existing index metrics. - pub(crate) const fn as_str(self) -> &'static str { + pub const fn as_str(self) -> &'static str { match self { Self::Inverted => "inverted_index", Self::Fulltext => "fulltext_index", Self::Bloom => "bloom_filter_index", + Self::Extension(kind) => kind.as_str(), } } /// Returns the identity recorded in file and column index metadata. - pub(crate) fn index_type(self) -> IndexType { + pub fn index_type(self) -> IndexType { match self { Self::Inverted => IndexType::InvertedIndex, Self::Fulltext => IndexType::FulltextIndex, Self::Bloom => IndexType::BloomFilterIndex, + Self::Extension(ExtensionIndexKind::Hll) => IndexType::HllIndex, + Self::Extension(ExtensionIndexKind::Kll) => IndexType::KllIndex, + Self::Extension(ExtensionIndexKind::Mg) => IndexType::MgIndex, } } + + /// Whether this kind is implemented by the storage engine. + pub fn is_builtin(self) -> bool { + !matches!(self, Self::Extension(_)) + } } diff --git a/src/mito2/src/sst/index/registry.rs b/src/mito2/src/sst/index/registry.rs index 7f7c43f3671..7b9da2e51dd 100644 --- a/src/mito2/src/sst/index/registry.rs +++ b/src/mito2/src/sst/index/registry.rs @@ -12,29 +12,40 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Ordered planning of built-in index implementations. +//! Ordered registration and planning of index implementations. +use std::collections::HashSet; use std::sync::Arc; use common_error::ext::BoxedError; use common_telemetry::warn; +use snafu::IntoError; +use store_api::metadata::RegionMetadataRef; +use store_api::storage::RegionId; use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig}; +use crate::error::{Error, ExternalSnafu, InvalidConfigSnafu}; +use crate::metrics::{INDEX_CREATE_DISCARDED_TOTAL, INDEX_DISCARD_ADMISSION_REJECTED}; +use crate::sst::file::{FileMeta, IndexType}; +use crate::sst::index::IndexBuildType; use crate::sst::index::handler::builtin::BuiltinIndexHandler; -use crate::sst::index::handler::{IndexKindHandler, PlanContext, PlannedIndex}; +use crate::sst::index::handler::{ + IndexKindHandler, IndexKindProviderRef, PlanContext, PlanEntry, PlannedIndex, +}; +use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; -/// Shared registry installed by the engine. -pub(crate) type IndexRegistryRef = Arc; +/// Shared registry installed by the engine and its embedding application. +pub type IndexRegistryRef = Arc; -/// Built-in handlers in index creation order. +/// One handler per owner; related algorithms may share one creator and row traversal. #[derive(Debug, Clone)] -pub(crate) struct IndexRegistry { +pub struct IndexRegistry { handlers: Vec>, } impl IndexRegistry { /// Registers the existing built-in creators in their established order. - pub(crate) fn new( + pub fn new( inverted: InvertedIndexConfig, fulltext: FulltextIndexConfig, bloom: BloomFilterConfig, @@ -48,46 +59,452 @@ impl IndexRegistry { } } - /// Prepares each handler once, retaining the existing test panic and - /// production log-and-skip policy for construction failures. - pub(crate) fn plan(&self, context: &PlanContext<'_>) -> IndexBuildPlan { + /// Adds the embedding application's handlers after the built-in configuration. + pub fn with_provider( + mut self, + provider: Option, + ) -> Result { + if let Some(provider) = provider { + for handler in provider.handlers() { + self.register(handler)?; + } + } + Ok(self) + } + + /// Installs a handler, rejecting empty or overlapping kind ownership. + pub fn register(&mut self, handler: Arc) -> Result<(), BoxedError> { + self.validate_registration(handler.kinds())?; + self.handlers.push(handler); + self.handlers + .sort_by_key(|handler| handler.kinds().iter().min().copied()); + Ok(()) + } + + /// Rejects required extension indexes whose implementation is unavailable. + /// Checks current schema options and both file-level and column-level metadata. + pub fn validate_required_kinds<'a>( + &self, + metadata: &RegionMetadataRef, + files: impl IntoIterator, + ) -> Result<(), BoxedError> { + self.validate_schema_kinds(metadata)?; + for file in files { + for kind in file.available_indexes.iter().chain( + file.indexes + .iter() + .flat_map(|column| &column.created_indexes), + ) { + self.validate_required_kind(*kind)?; + } + } + Ok(()) + } + + /// Prepares each handler once. Construction failures retain the existing + /// built-in test panic and production skip policy. Other failures are retained + /// for the caller to check before publishing rebuilt indexes. Required-provider + /// validation belongs to the operation entry point, before calling this method. + pub fn plan(&self, context: &PlanContext<'_>) -> IndexBuildPlan { let mut planned = Vec::new(); + let mut failure = None; for handler in &self.handlers { - match handler.plan(context) { + if context.build_type == IndexBuildType::Flush + && !handler.kinds().iter().all(|kind| kind.is_builtin()) + { + continue; + } + let result = handler.plan(context).and_then(|plan| { + if let Some(plan) = &plan { + Self::validate_plan(handler.as_ref(), plan.as_ref())?; + } + Ok(plan) + }); + match result { Ok(Some(plan)) => planned.push(plan), Ok(None) => {} Err(err) => { - Self::record_planning_error(handler.as_ref(), context, err); + Self::record_planning_error(handler.as_ref(), context, err, &mut failure); } } } - IndexBuildPlan { planned } + IndexBuildPlan { planned, failure } + } + + fn validate_registration(&self, kinds: &[IndexKind]) -> Result<(), BoxedError> { + if kinds.is_empty() + || kinds + .iter() + .enumerate() + .any(|(i, kind)| kinds[..i].contains(kind)) + { + return Err(BoxedError::new( + InvalidConfigSnafu { + reason: "index handler kinds must be nonempty and unique", + } + .build(), + )); + } + if kinds.iter().any(|kind| kind.is_builtin()) && kinds.iter().any(|kind| !kind.is_builtin()) + { + return Err(BoxedError::new( + InvalidConfigSnafu { + reason: "index handler cannot mix built-in and extension kinds", + } + .build(), + )); + } + if kinds.iter().any(|kind| self.has_handler(kind.index_type())) { + return Err(BoxedError::new( + InvalidConfigSnafu { + reason: "index handler kind is already registered", + } + .build(), + )); + } + Ok(()) + } + + fn has_handler(&self, kind: IndexType) -> bool { + self.handlers.iter().any(|handler| { + handler + .kinds() + .iter() + .any(|owned| owned.index_type() == kind) + }) + } + + fn validate_plan( + handler: &dyn IndexKindHandler, + plan: &dyn PlannedIndex, + ) -> Result<(), BoxedError> { + let kinds = plan.kinds(); + if kinds.is_empty() + || kinds + .iter() + .enumerate() + .any(|(i, kind)| kinds[..i].contains(kind) || !handler.kinds().contains(kind)) + || plan + .entries() + .iter() + .any(|entry| !kinds.contains(&entry.kind)) + { + return Err(BoxedError::new( + InvalidConfigSnafu { + reason: "index plan kinds must be nonempty, unique, owned by the handler, and include every entry kind", + } + .build(), + )); + } + Ok(()) } fn record_planning_error( handler: &dyn IndexKindHandler, context: &PlanContext<'_>, err: BoxedError, + failure: &mut Option>, ) { - if cfg!(any(test, feature = "test")) { + if handler.kinds().iter().all(|kind| kind.is_builtin()) && cfg!(any(test, feature = "test")) + { panic!( "Failed to prepare built-in index, region_id: {}, err: {err}", context.metadata.region_id ); } - warn!(err; "Failed to prepare index, region_id: {}, kind: {:?}", context.metadata.region_id, handler.kind()); + warn!(err; "Failed to prepare index, region_id: {}, kinds: {:?}", context.metadata.region_id, handler.kinds()); + failure.get_or_insert_with(|| { + Arc::new( + ExternalSnafu { + context: "index planning".to_string(), + } + .into_error(err), + ) + }); + } + + fn validate_schema_kinds(&self, metadata: &RegionMetadataRef) -> Result<(), BoxedError> { + for column in &metadata.column_metadatas { + let schema = &column.column_schema; + for kind in ExtensionIndexKind::ALL { + if schema.metadata().contains_key(kind.required_metadata_key()) { + self.validate_required_kind(IndexKind::Extension(kind).index_type())?; + } + } + } + Ok(()) + } + + fn validate_required_kind(&self, kind: IndexType) -> Result<(), BoxedError> { + if ExtensionIndexKind::ALL + .iter() + .any(|extension| IndexKind::Extension(*extension).index_type() == kind) + && !self.has_handler(kind) + { + return Err(BoxedError::new( + InvalidConfigSnafu { + reason: format!("required index {kind:?} has no registered handler"), + } + .build(), + )); + } + Ok(()) } } /// Typed plans retained across output files of one operation. #[derive(Debug, Clone, Default)] -pub(crate) struct IndexBuildPlan { +pub struct IndexBuildPlan { planned: Vec>, + failure: Option>, } impl IndexBuildPlan { - /// Plans in index creation order. - pub(crate) fn planned(&self) -> &[Arc] { + /// Reports preparation failure separately from a successful empty plan. + pub fn check_success(&self) -> Result<(), Arc> { + self.failure.clone().map_or(Ok(()), Err) + } + + /// Plans in execution order, grouped by owner rather than by column. + pub fn planned(&self) -> &[Arc] { &self.planned } + + /// All requested column formats. + pub fn entries(&self) -> impl Iterator { + self.planned.iter().flat_map(|plan| plan.entries()) + } + + /// Whether any planned implementation can reuse persisted input indexes. + pub fn needs_input_reuse(&self) -> bool { + self.planned.iter().any(|plan| plan.needs_input_reuse()) + } + + /// Omits optional extension work when the caller cannot admit its memory budget. + /// Records each requested kind once per target plan, rather than once per column. + pub fn omit_extensions_for_budget(&mut self, region_id: RegionId) { + let omitted: HashSet<_> = self + .entries() + .filter(|entry| !entry.kind.is_builtin()) + .map(|entry| entry.kind) + .collect(); + for kind in omitted { + warn!( + "Omitting index before construction, region_id: {}, kind: {}, reason: admission_rejected", + region_id, + kind.as_str() + ); + INDEX_CREATE_DISCARDED_TOTAL + .with_label_values(&[kind.as_str(), INDEX_DISCARD_ADMISSION_REJECTED]) + .inc(); + } + self.planned + .retain(|plan| plan.kinds().iter().all(|kind| kind.is_builtin())); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sst::index::kind::ExtensionIndexKind; + + #[derive(Debug)] + struct TestHandler(Vec); + + impl IndexKindHandler for TestHandler { + fn kinds(&self) -> &[IndexKind] { + &self.0 + } + fn plan(&self, _: &PlanContext<'_>) -> Result>, BoxedError> { + Ok(None) + } + } + + #[derive(Debug)] + struct TestPlan { + kinds: Vec, + entries: Vec, + } + + #[async_trait::async_trait] + impl PlannedIndex for TestPlan { + fn kinds(&self) -> &[IndexKind] { + &self.kinds + } + fn entries(&self) -> &[PlanEntry] { + &self.entries + } + async fn build( + &self, + _: &crate::sst::index::handler::BuildContext<'_>, + ) -> Result>, BoxedError> { + unreachable!("admission must not construct creators") + } + } + + #[test] + fn test_admission_omission_records_each_requested_kind_once() { + let builtin = IndexKind::Bloom; + let enabled = IndexKind::Extension(ExtensionIndexKind::Mg); + let disabled = IndexKind::Extension(ExtensionIndexKind::Kll); + let entry = |kind, column_id| PlanEntry { + kind, + column_id, + format_version: 1, + }; + let mut plan = IndexBuildPlan { + planned: vec![ + Arc::new(TestPlan { + kinds: vec![builtin], + entries: vec![entry(builtin, 0)], + }), + Arc::new(TestPlan { + kinds: vec![enabled, disabled], + entries: vec![entry(enabled, 0), entry(enabled, 1)], + }), + ], + failure: None, + }; + let counter = INDEX_CREATE_DISCARDED_TOTAL + .with_label_values(&[enabled.as_str(), "admission_rejected"]); + let disabled_counter = INDEX_CREATE_DISCARDED_TOTAL + .with_label_values(&[disabled.as_str(), "admission_rejected"]); + let before = counter.get(); + let disabled_before = disabled_counter.get(); + plan.omit_extensions_for_budget(RegionId::new(1, 1)); + assert_eq!( + plan.entries().cloned().collect::>(), + vec![entry(builtin, 0)] + ); + assert_eq!(counter.get(), before + 1); + assert_eq!(disabled_counter.get(), disabled_before); + assert!(plan.check_success().is_ok()); + plan.omit_extensions_for_budget(RegionId::new(1, 1)); + assert_eq!(counter.get(), before + 1); + } + + #[test] + fn test_registration_preserves_grouped_owner_and_rejects_overlap() { + let mut registry = + IndexRegistry::new(Default::default(), Default::default(), Default::default()); + let kinds = vec![ + IndexKind::Extension(ExtensionIndexKind::Hll), + IndexKind::Extension(ExtensionIndexKind::Kll), + IndexKind::Extension(ExtensionIndexKind::Mg), + ]; + registry + .register(Arc::new(TestHandler(kinds.clone()))) + .unwrap(); + assert_eq!(registry.handlers.len(), 4); + assert_eq!(registry.handlers[3].kinds(), kinds); + for invalid in [vec![], vec![kinds[0]], vec![IndexKind::Fulltext]] { + assert!(registry.register(Arc::new(TestHandler(invalid))).is_err()); + assert_eq!(registry.handlers.len(), 4); + } + } + + #[test] + fn test_registration_rejects_duplicates_within_one_owner() { + let mut registry = + IndexRegistry::new(Default::default(), Default::default(), Default::default()); + let kind = IndexKind::Extension(ExtensionIndexKind::Hll); + assert!( + registry + .register(Arc::new(TestHandler(vec![kind, kind]))) + .is_err() + ); + assert_eq!(registry.handlers.len(), 3); + } + + #[derive(Debug)] + struct PlannedHandler { + owned: Vec, + plan: Arc, + } + + impl IndexKindHandler for PlannedHandler { + fn kinds(&self) -> &[IndexKind] { + &self.owned + } + + fn plan(&self, _: &PlanContext<'_>) -> Result>, BoxedError> { + Ok(Some(self.plan.clone())) + } + } + + #[test] + fn test_plans_validate_ownership_without_removing_valid_plans() { + let hll = IndexKind::Extension(ExtensionIndexKind::Hll); + let kll = IndexKind::Extension(ExtensionIndexKind::Kll); + let metadata = Arc::new(crate::test_util::sst_util::sst_region_metadata()); + let options = Default::default(); + let context = PlanContext { + metadata: &metadata, + index_options: &options, + build_type: crate::sst::index::IndexBuildType::Compact, + existing_indexes: &[], + }; + for (kinds, entry_kind, invalid) in [ + (vec![], hll, true), + (vec![hll, hll], hll, true), + (vec![kll], kll, true), + (vec![hll], kll, true), + (vec![hll], hll, false), + ] { + let mut registry = + IndexRegistry::new(Default::default(), Default::default(), Default::default()); + registry + .register(Arc::new(PlannedHandler { + owned: vec![hll, IndexKind::Extension(ExtensionIndexKind::Mg)], + plan: Arc::new(TestPlan { + kinds, + entries: vec![PlanEntry { + column_id: 0, + kind: entry_kind, + format_version: 1, + }], + }), + })) + .unwrap(); + registry + .register(Arc::new(PlannedHandler { + owned: vec![kll], + plan: Arc::new(TestPlan { + kinds: vec![kll], + entries: vec![PlanEntry { + column_id: 0, + kind: kll, + format_version: 1, + }], + }), + })) + .unwrap(); + let plan = registry.plan(&context); + assert_eq!(plan.check_success().is_err(), invalid); + assert_eq!( + plan.entries() + .filter(|entry| !entry.kind.is_builtin()) + .map(|entry| entry.kind) + .collect::>(), + if invalid { vec![kll] } else { vec![hll, kll] } + ); + assert_eq!(registry.handlers.len(), 5); + } + } + + #[test] + fn test_registration_rejects_mixed_builtin_and_extension_owner() { + let mut registry = IndexRegistry { + handlers: Vec::new(), + }; + assert!( + registry + .register(Arc::new(TestHandler(vec![ + IndexKind::Inverted, + IndexKind::Extension(ExtensionIndexKind::Hll), + ]))) + .is_err() + ); + assert!(registry.handlers.is_empty()); + } } diff --git a/src/mito2/src/sst/index/sparse_test.rs b/src/mito2/src/sst/index/sparse_test.rs index e12d77f7903..1c2ba260ba9 100644 --- a/src/mito2/src/sst/index/sparse_test.rs +++ b/src/mito2/src/sst/index/sparse_test.rs @@ -130,6 +130,7 @@ async fn sparse_and_materialized_tags_produce_identical_indexes() { let mut options = IndexOptions::default(); options.inverted_index.segment_row_count = 3; let builder = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata: metadata.clone(), puffin_manager: puffin.clone(), diff --git a/src/mito2/src/sst/parquet.rs b/src/mito2/src/sst/parquet.rs index b8a8395088b..911e02cbf76 100644 --- a/src/mito2/src/sst/parquet.rs +++ b/src/mito2/src/sst/parquet.rs @@ -1560,6 +1560,7 @@ mod tests { let intermediate_manager = env.get_intermediate_manager(); let indexer_builder = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata: metadata.clone(), puffin_manager, @@ -2106,6 +2107,7 @@ mod tests { let intermediate_manager = env.get_intermediate_manager(); IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata, puffin_manager, @@ -2227,6 +2229,7 @@ mod tests { let intermediate_manager = env.get_intermediate_manager(); let indexer_builder = IndexerBuilderImpl { + index_build_inputs: None, build_type: IndexBuildType::Flush, metadata: metadata.clone(), puffin_manager, diff --git a/src/mito2/src/worker/handle_rebuild_index.rs b/src/mito2/src/worker/handle_rebuild_index.rs index 917a58d0c68..c17008bab27 100644 --- a/src/mito2/src/worker/handle_rebuild_index.rs +++ b/src/mito2/src/worker/handle_rebuild_index.rs @@ -76,6 +76,7 @@ impl RegionWorkerLoop { let indexer_builder_ref = Arc::new(IndexerBuilderImpl { build_type: build_type.clone(), metadata: snapshot.metadata.clone(), + index_build_inputs: None, registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( self.config.inverted_index.clone(), self.config.fulltext_index.clone(), From d061e0871746662f23722e1e50815cf5091c3ce1 Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Tue, 10 Nov 2026 16:06:17 +0000 Subject: [PATCH 03/63] feat: flush regions under object store WAL retention pressure (#10309) * feat(store-api): expose advisory WAL flush candidates Signed-off-by: WenyXu * feat(log-store): select regions blocking WAL object reclamation Signed-off-by: WenyXu * feat(mito): schedule region flushes under WAL retention pressure Signed-off-by: WenyXu * test(mito): cover WAL pressure reclamation and recovery Signed-off-by: WenyXu * fix(log-store): prioritize oldest WAL reclamation blockers Signed-off-by: WenyXu * test(mito): deterministically exhaust range cache admission budget Signed-off-by: WenyXu --------- Signed-off-by: WenyXu --- src/log-store/src/object_store_wal/catalog.rs | 83 ++- src/log-store/src/object_store_wal/store.rs | 13 + src/mito2/src/engine/flush_test.rs | 98 +++- src/mito2/src/engine/listener.rs | 3 + .../engine/object_store_wal_recovery_test.rs | 543 +++++++++++++++++- src/mito2/src/flush.rs | 2 + src/mito2/src/read/range_cache.rs | 32 +- src/mito2/src/test_util.rs | 26 + src/mito2/src/wal.rs | 88 ++- src/mito2/src/worker.rs | 39 +- src/mito2/src/worker/handle_flush.rs | 21 + src/store-api/src/logstore.rs | 11 + 12 files changed, 939 insertions(+), 20 deletions(-) diff --git a/src/log-store/src/object_store_wal/catalog.rs b/src/log-store/src/object_store_wal/catalog.rs index 49567db3060..d93dc5a0ed6 100644 --- a/src/log-store/src/object_store_wal/catalog.rs +++ b/src/log-store/src/object_store_wal/catalog.rs @@ -14,7 +14,7 @@ //! In-memory index over the footers of the objects of one WAL prefix. -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::ops::Bound::{Excluded, Included, Unbounded}; use snafu::{OptionExt, ensure}; @@ -294,6 +294,24 @@ impl ObjectCatalog { Ok(next_object_seq) } + /// Returns live regions blocking reclamation of objects older than the + /// newest `limit` objects. Already reclaimable objects awaiting deletion + /// do not cause more flushes. Sequence gaps do not count as objects. + /// Regions are deduplicated in order of the oldest object they pin. + pub(crate) fn flush_candidates(&self, limit: usize) -> Vec { + let Some((&last, _)) = self.objects.iter().rev().nth(limit) else { + return Vec::new(); + }; + let mut seen = HashSet::new(); + self.live_segments + .range(..=last) + .flat_map(|(seq, _)| self.objects[seq].iter()) + .filter(|entry| self.is_live(entry)) + .map(|entry| entry.region_id) + .filter(|region_id| seen.insert(*region_id)) + .collect() + } + /// Iterates over the indexed objects ordered by object sequence. pub(crate) fn objects_in_order(&self) -> impl Iterator + '_ { self.objects @@ -324,6 +342,69 @@ mod tests { use crate::error::Error; use crate::object_store_wal::batch::entry_id; + #[test] + fn test_flush_candidates_follow_retention_not_sequence_or_delete_backlog() { + let a = RegionId::new(1, 1); + let b = RegionId::new(1, 2); + let mut catalog = ObjectCatalog::default(); + assert!(catalog.flush_candidates(2).is_empty()); + catalog + .insert_object(100, vec![footer_entry(a, 1, 2), footer_entry(b, 1, 1)]) + .unwrap(); + catalog + .insert_object(1_000, vec![footer_entry(b, 3, 3)]) + .unwrap(); + // Sequence gaps are not objects, and equality does not trigger flush. + assert!(catalog.flush_candidates(2).is_empty()); + catalog + .insert_object(10_000, vec![footer_entry(b, 4, 4)]) + .unwrap(); + assert_eq!(vec![a, b], catalog.flush_candidates(2)); + catalog.obsolete(b, 1); + assert_eq!(vec![a], catalog.flush_candidates(2)); + // A partially obsolete segment still pins the oldest object. + catalog.obsolete(a, 1); + assert_eq!(vec![a], catalog.flush_candidates(2)); + catalog.obsolete(a, 2); + // Three physical objects remain, but only two need retention. + assert!(catalog.flush_candidates(2).is_empty()); + catalog.obsolete(b, 4); + assert!(catalog.flush_candidates(0).is_empty()); + catalog + .insert_object(20_000, vec![footer_entry(RELEASE_REGION_ID, 5, 5)]) + .unwrap(); + assert!(catalog.flush_candidates(0).is_empty()); + } + + #[test] + fn test_flush_candidates_include_all_blockers_before_retention_target() { + // Region IDs run opposite to the oldest objects they pin. + let a = RegionId::new(1, 3); + let b = RegionId::new(1, 2); + let c = RegionId::new(1, 1); + let mut catalog = ObjectCatalog::default(); + for (seq, region, id) in [(10, a, 1), (20, b, 1), (30, a, 2), (40, c, 1), (50, c, 2)] { + catalog + .insert_object(seq, vec![footer_entry(region, id, id)]) + .unwrap(); + } + // Only the newest two objects may remain. A and B pin different old + // objects, while A appears twice and C only pins the retained suffix. + assert_eq!(vec![a, b], catalog.flush_candidates(2)); + assert_eq!(vec![a, b, c], catalog.flush_candidates(0)); + // Once A releases its oldest segment, B must precede A. + catalog.obsolete(a, 1); + assert_eq!(vec![b, a], catalog.flush_candidates(2)); + assert_eq!(vec![b, a, c], catalog.flush_candidates(0)); + catalog.obsolete(a, 2); + assert_eq!(vec![b], catalog.flush_candidates(2)); + catalog.obsolete(b, 1); + // The old objects still exist until deletion completes. + assert!(catalog.flush_candidates(2).is_empty()); + assert_eq!(vec![c], catalog.flush_candidates(1)); + assert!(catalog.flush_candidates(usize::MAX).is_empty()); + } + #[test] fn test_catalog_indexes_objects_and_queries_ranges() { let region_one = RegionId::new(1, 1); diff --git a/src/log-store/src/object_store_wal/store.rs b/src/log-store/src/object_store_wal/store.rs index b1020978893..6da8721891d 100644 --- a/src/log-store/src/object_store_wal/store.rs +++ b/src/log-store/src/object_store_wal/store.rs @@ -851,6 +851,19 @@ impl ObjectStoreLogStore { impl LogStore for ObjectStoreLogStore { type Error = Error; + fn flush_candidates(&self) -> Vec { + // A soft threshold: closed regions and recovery retention can still + // pin objects. The engine decides which candidates it can flush. + const FLUSH_OBJECT_THRESHOLD: usize = 1_200; + if self.stopped.load(Ordering::Acquire) { + return Vec::new(); + } + self.catalog + .read() + .unwrap_or_else(PoisonError::into_inner) + .flush_candidates(FLUSH_OBJECT_THRESHOLD) + } + /// Stops the store. Creates in flight run to completion and acknowledge /// their entries if they succeed; in the `enqueued` mode the remaining /// backlog is uploaded first, and a failure of that upload is returned. diff --git a/src/mito2/src/engine/flush_test.rs b/src/mito2/src/engine/flush_test.rs index 8435a38c4a3..d01b77ddbd9 100644 --- a/src/mito2/src/engine/flush_test.rs +++ b/src/mito2/src/engine/flush_test.rs @@ -17,7 +17,7 @@ use std::assert_matches; use std::collections::HashMap; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; use std::time::Duration; use api::v1::Rows; @@ -59,6 +59,7 @@ use crate::test_util::{ prepare_test_for_kafka_log_store, put_rows, raft_engine_log_store_factory, reopen_region, rows_schema, single_kafka_log_store_factory, }; +use crate::time_provider::TimeProvider; use crate::time_provider::mock::MockTimeProvider; use crate::worker::MAX_INITIAL_CHECK_DELAY_SECS; @@ -2227,3 +2228,98 @@ async fn test_bulk_last_non_null_merge_and_flush(#[values(false, true)] encoded: .await; assert_eq!(expected, scan_bulk_test_keys(&engine, region_id).await); } + +/// Controls elapsed time while preserving the production worker sleep duration. +/// Shortening that sleep would hide starvation by another worker's notifications. +#[derive(Debug)] +struct PeriodicFlushClock { + now: AtomicI64, +} + +impl TimeProvider for PeriodicFlushClock { + fn current_time_millis(&self) -> i64 { + self.now.load(Ordering::Relaxed) + } + + fn elapsed_since(&self, since: i64) -> i64 { + self.current_time_millis() - since + } +} + +#[tokio::test] +async fn test_empty_wal_notifications_do_not_defer_auto_flush() { + let mut env = TestEnv::new().await; + let now = current_time_millis(); + let clock = Arc::new(PeriodicFlushClock { + now: AtomicI64::new(now), + }); + // The default Raft WAL publishes empty pressure snapshots. A and B map to + // different workers; only B receives requests after both have written. + let engine = env + .create_engine_with_time( + MitoConfig { + num_workers: 2, + auto_flush_interval: Duration::from_secs(60), + ..Default::default() + }, + None, + None, + clock.clone(), + ) + .await; + let idle_id = RegionId::new(1, 1); + let active_id = RegionId::new(1, 2); + let mut active_schema = Vec::new(); + for region_id in [idle_id, active_id] { + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_rows( + &engine, + region_id, + Rows { + schema: schema.clone(), + rows: build_rows_for_key("a", 0, 2, 0), + }, + ) + .await; + if region_id == active_id { + active_schema = schema; + } + } + let idle = engine.get_region(idle_id).unwrap(); + assert_eq!(0, idle.version().flushed_entry_id); + // Each request lets the active worker refresh and publish an empty snapshot. + // Wall time stays well below the idle worker's real 60-second timeout. + for tick in 0..3 { + clock + .now + .store(now + 600_000 + tick * 60_000, Ordering::Relaxed); + put_rows( + &engine, + active_id, + Rows { + schema: active_schema.clone(), + rows: build_rows_for_key("b", 0, 1, 0), + }, + ) + .await; + } + tokio::time::timeout(Duration::from_secs(3), async { + while idle.version().flushed_entry_id == 0 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("empty WAL notifications must also check ordinary periodic flushing"); + let scanner = engine + .scanner(idle_id, ScanRequest::default()) + .await + .unwrap(); + assert_eq!(0, scanner.num_memtables()); + assert_eq!(1, scanner.num_files()); + engine.stop().await.unwrap(); +} diff --git a/src/mito2/src/engine/listener.rs b/src/mito2/src/engine/listener.rs index f754d4faf00..1aa6dbb3053 100644 --- a/src/mito2/src/engine/listener.rs +++ b/src/mito2/src/engine/listener.rs @@ -47,6 +47,9 @@ pub trait EventListener: Send + Sync { let _ = region_id; } + /// Observes scheduler admission after a worker handles a WAL pressure snapshot. + fn on_wal_pressure_checked(&self, _region_id: RegionId, _flush_requested: bool) {} + /// Notifies the listener after a flush becomes non-cancellable and before commit. async fn on_flush_commit_begin(&self, _region_id: RegionId) {} diff --git a/src/mito2/src/engine/object_store_wal_recovery_test.rs b/src/mito2/src/engine/object_store_wal_recovery_test.rs index d5ae88b1d9b..279014e1e9b 100644 --- a/src/mito2/src/engine/object_store_wal_recovery_test.rs +++ b/src/mito2/src/engine/object_store_wal_recovery_test.rs @@ -56,7 +56,7 @@ use store_api::storage::{RegionId, ScanRequest}; use crate::config::MitoConfig; use crate::engine::MitoEngine; -use crate::region::MitoRegionRef; +use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState}; use crate::test_util::{ CreateRequestBuilder, TestEnv, build_rows, build_rows_for_key, flush_region, put_rows, rows_schema, @@ -1974,3 +1974,544 @@ async fn test_enqueued_writes_fail_fast_while_the_object_store_refuses_the_backl region_recovery_state(&engine, REGION_A).await ); } + +/// Reports the actual scheduler state before the worker can process flush +/// completion. This distinguishes skipped admission from a later commit failure. +struct PressureAdmissionListener { + checked: tokio::sync::mpsc::UnboundedSender<(RegionId, bool)>, +} + +#[async_trait::async_trait] +impl crate::engine::listener::EventListener for PressureAdmissionListener { + fn on_wal_pressure_checked(&self, region_id: RegionId, flush_requested: bool) { + let _ = self.checked.send((region_id, flush_requested)); + } +} + +async fn wait_for_pressure_admission( + checked: &mut tokio::sync::mpsc::UnboundedReceiver<(RegionId, bool)>, + region_id: RegionId, +) -> bool { + tokio::time::timeout(WAIT, async { + loop { + let (id, requested) = checked.recv().await.unwrap(); + if id == region_id { + return requested; + } + } + }) + .await + .expect("worker must process the pressure snapshot") +} + +/// Exercises the production threshold, worker timers, flush and WAL release. +/// Both regions pin the oldest object and belong to different workers. +#[rstest] +#[case::writable(RegionRoleState::Leader(RegionLeaderState::Writable))] +#[case::follower(RegionRoleState::Follower)] +#[case::staging(RegionRoleState::Leader(RegionLeaderState::Staging))] +#[tokio::test] +async fn test_wal_pressure_flushes_blockers_across_workers(#[case] state: RegionRoleState) { + use crate::time_provider::mock::MockTimeProvider; + + let mut env = TestEnv::new().await; + let object_store = memory_store(); + let store = open_store(&object_store, AckMode::Durable).await; + let clock = Arc::new(MockTimeProvider::new( + common_time::util::current_time_millis(), + )); + let (checked, mut observations) = tokio::sync::mpsc::unbounded_channel(); + let listener = Arc::new(PressureAdmissionListener { checked }); + let engine = env + .create_engine_with_log_store_and_time( + MitoConfig { + num_workers: 2, + auto_flush_interval: Duration::from_secs(3600), + ..Default::default() + }, + store.clone(), + clock.clone(), + Some(listener), + ) + .await; + let (_, schema_a) = create_region(&engine, REGION_A, &[]).await; + let (_, schema_b) = create_region(&engine, REGION_B, &[]).await; + let mut writer = SealedWriter::new(&store); + writer + .put_and_seal( + &engine, + vec![ + ( + REGION_A, + Rows { + schema: schema_a, + rows: build_rows(0, 1), + }, + ), + ( + REGION_B, + Rows { + schema: schema_b.clone(), + rows: build_rows(0, 1), + }, + ), + ], + ) + .await; + // Fill the retained suffix without advancing the periodic clock. + for i in 1..1_200 { + writer + .put_and_seal( + &engine, + vec![( + REGION_B, + Rows { + schema: schema_b.clone(), + rows: build_rows(i, i + 1), + }, + )], + ) + .await; + } + assert!(store.flush_candidates().is_empty()); + let now = common_time::util::current_time_millis(); + clock.set_now(now + 120_000); + clock.set_elapsed(120_000); + let premature_flush = tokio::time::timeout(Duration::from_millis(200), async { + loop { + if [REGION_A, REGION_B] + .iter() + .any(|&id| region(&engine, id).version().flushed_entry_id != 0) + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + assert!( + premature_flush.is_err(), + "the threshold itself must not trigger a flush" + ); + writer + .put_and_seal( + &engine, + vec![( + REGION_B, + Rows { + schema: schema_b.clone(), + rows: build_rows(1_200, 1_201), + }, + )], + ) + .await; + assert_eq!(vec![REGION_A, REGION_B], store.flush_candidates()); + for id in [REGION_A, REGION_B] { + assert_eq!(0, region(&engine, id).version().flushed_entry_id); + } + let expected_a = latest(&store, REGION_A); + let expected_b = latest(&store, REGION_B); + let region_a = region(&engine, REGION_A); + match state { + RegionRoleState::Follower => engine + .set_region_role(REGION_A, RegionRole::Follower) + .unwrap(), + RegionRoleState::Leader(RegionLeaderState::Staging) => { + let mut manager = region_a.manifest_ctx.manifest_manager.write().await; + region_a.set_staging(&mut manager).await.unwrap(); + } + RegionRoleState::Leader(RegionLeaderState::Writable) => {} + _ => unreachable!(), + } + clock.set_now(now + 240_000); + if state != RegionRoleState::Leader(RegionLeaderState::Writable) { + // Observe admission itself: a failed manifest commit would also leave + // the watermark unchanged, but must not make this assertion pass. + assert!(!wait_for_pressure_admission(&mut observations, REGION_A).await); + // The other worker must make progress while A is not eligible. + tokio::time::timeout(WAIT, async { + while region(&engine, REGION_B).version().flushed_entry_id != expected_b { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + // Publish distinct snapshots and wait for A's worker to process each. + for offset in [360_000, 480_000] { + clock.set_now(now + offset); + assert!(!wait_for_pressure_admission(&mut observations, REGION_A).await); + } + assert_eq!(0, region_a.version().flushed_entry_id); + assert_eq!(vec![REGION_A], store.flush_candidates()); + if region_a.is_staging() { + region_a.exit_staging().unwrap(); + } else { + engine + .set_region_role(REGION_A, RegionRole::Leader) + .unwrap(); + } + // A previously skipped candidate is retried on the next refresh. + clock.set_now(now + 600_000); + assert!(wait_for_pressure_admission(&mut observations, REGION_A).await); + } + tokio::time::timeout(WAIT, async { + loop { + if region(&engine, REGION_A).version().flushed_entry_id == expected_a + && region(&engine, REGION_B).version().flushed_entry_id == expected_b + && store.flush_candidates().is_empty() + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + // A subsequent object persists the new reclaim boundary, allowing the + // store to delete the whole old suffix without an explicit flush request. + writer + .put_and_seal(&engine, vec![(REGION_B, rows(&schema_b, 1_201, 1_202))]) + .await; + wait_for_collection(&store).await; + assert_eq!(vec![1_202], wal_object_seqs(&object_store).await); + assert_eq!( + expected_a, + region_recovery_state(&engine, REGION_A) + .await + .manifest_flushed_entry_id + ); + assert_eq!( + expected_b, + region_recovery_state(&engine, REGION_B) + .await + .manifest_flushed_entry_id + ); + engine.stop().await.unwrap(); + store.stop().await.unwrap(); +} + +/// Different regions pin successive old objects. One refresh must flush all +/// blockers, including while new objects arrive, rather than advance one pin +/// per minute. Repeat after reclamation to exercise ongoing pressure. +#[tokio::test] +async fn test_wal_pressure_flushes_separate_objects_under_continued_writes() { + use crate::time_provider::mock::MockTimeProvider; + + let mut env = TestEnv::new().await; + let objects = memory_store(); + let store = open_store(&objects, AckMode::Durable).await; + let now = common_time::util::current_time_millis(); + let clock = Arc::new(MockTimeProvider::new(now)); + let engine = env + .create_engine_with_log_store_and_time( + pressure_config(), + store.clone(), + clock.clone(), + None, + ) + .await; + let ids = [REGION_A, REGION_B, RegionId::new(1, 3), RegionId::new(1, 4)]; + let mut schemas = Vec::new(); + for id in ids { + schemas.push(create_region(&engine, id, &[]).await.1); + } + let mut writer = SealedWriter::new(&store); + for round in 0..2 { + for i in 0..1_204 { + let index = if i < 3 { i } else { 3 }; + let row = round * 2_000 + i; + writer + .put_and_seal( + &engine, + vec![(ids[index], rows(&schemas[index], row, row + 1))], + ) + .await; + } + let expected = ids.map(|id| latest(&store, id)); + clock.set_now(now + (round as i64 + 1) * 120_000); + clock.set_elapsed((round as i64 + 1) * 120_000); + // Continue appending after publishing pressure, without another clock + // advance: recovery must not require another candidate refresh. + for i in 1_204..1_236 { + let row = round * 2_000 + i; + writer + .put_and_seal(&engine, vec![(ids[3], rows(&schemas[3], row, row + 1))]) + .await; + } + tokio::time::timeout(WAIT, async { + loop { + if ids + .iter() + .zip(expected) + .all(|(&id, upto)| region(&engine, id).version().flushed_entry_id >= upto) + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("one refresh must flush all old-object blockers"); + for (id, upto) in ids.into_iter().zip(expected) { + assert!( + region_recovery_state(&engine, id) + .await + .manifest_flushed_entry_id + >= upto + ); + } + // Persist the advanced reclaim boundary and wait for physical deletion. + let row = round * 2_000 + 1_236; + writer + .put_and_seal(&engine, vec![(ids[3], rows(&schemas[3], row, row + 1))]) + .await; + wait_for_collection(&store).await; + assert!(wal_object_seqs(&objects).await.len() <= 1_200); + assert!(store.flush_candidates().is_empty()); + } + engine.stop().await.unwrap(); + store.stop().await.unwrap(); +} + +/// Builds actual WAL objects without allowing the ordinary hourly flush to run. +async fn fill_pressure_objects( + engine: &MitoEngine, + store: &Arc, + schema: &[api::v1::ColumnSchema], +) { + let mut writer = SealedWriter::new(store); + for i in 0..1_201 { + writer + .put_and_seal(engine, vec![(REGION_A, rows(schema, i, i + 1))]) + .await; + } + assert_eq!(vec![REGION_A], store.flush_candidates()); + assert_eq!(0, region(engine, REGION_A).version().flushed_entry_id); +} + +fn pressure_config() -> MitoConfig { + MitoConfig { + num_workers: 2, + auto_flush_interval: Duration::from_secs(3600), + ..Default::default() + } +} + +async fn wait_for_pressure_flush(engine: &MitoEngine, store: &ObjectStoreLogStore, expected: u64) { + tokio::time::timeout(WAIT, async { + while region(engine, REGION_A).version().flushed_entry_id != expected + || !store.flush_candidates().is_empty() + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("WAL pressure must flush the region"); + assert_eq!( + expected, + region_recovery_state(engine, REGION_A) + .await + .manifest_flushed_entry_id + ); +} + +#[rstest] +#[case::sst(".parquet")] +#[case::manifest(".json")] +#[tokio::test] +async fn test_wal_pressure_retries_failed_persistence(#[case] suffix: &'static str) { + use crate::time_provider::mock::MockTimeProvider; + + let denied = Arc::new(AtomicBool::new(false)); + let failed = Arc::new(tokio::sync::Notify::new()); + let layer = MockLayerBuilder::default() + .writer_factory(Arc::new({ + let denied = denied.clone(); + let failed = failed.clone(); + move |path, _, inner| { + if path.contains(suffix) && denied.load(Ordering::SeqCst) { + failed.notify_one(); + Box::new(DeniedWriter) + } else { + inner + } + } + })) + .build() + .unwrap(); + let mut env = TestEnv::new().await.with_mock_layer(layer); + let objects = memory_store(); + let store = open_store(&objects, AckMode::Durable).await; + let now = common_time::util::current_time_millis(); + let clock = Arc::new(MockTimeProvider::new(now)); + let engine = env + .create_engine_with_log_store_and_time( + pressure_config(), + store.clone(), + clock.clone(), + None, + ) + .await; + let (_, schema) = create_region(&engine, REGION_A, &[]).await; + fill_pressure_objects(&engine, &store, &schema).await; + let expected = latest(&store, REGION_A); + let before = wal_object_seqs(&objects).await; + let expected_rows = scan_rows(&engine, REGION_A).await; + denied.store(true, Ordering::SeqCst); + clock.set_now(now + 120_000); + clock.set_elapsed(120_000); + tokio::time::timeout(WAIT, failed.notified()) + .await + .expect("pressure flush must reach the failing persistence layer"); + assert_eq!( + 0, + region_recovery_state(&engine, REGION_A) + .await + .manifest_flushed_entry_id + ); + assert_eq!(0, region(&engine, REGION_A).version().flushed_entry_id); + assert_eq!(vec![REGION_A], store.flush_candidates()); + assert_eq!(before, wal_object_seqs(&objects).await); + denied.store(false, Ordering::SeqCst); + // Advance subsequent refreshes until the worker has processed the failure. + // No manual flush or additional user write may drive the retry. + tokio::time::timeout(WAIT, async { + let mut tick = now + 240_000; + while region(&engine, REGION_A).version().flushed_entry_id != expected { + clock.set_now(tick); + // Stay below the hourly automatic flush even on a slow machine. + tick = (tick + 60_000).min(now + 1_800_000); + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("a later pressure refresh must retry the failed flush"); + wait_for_pressure_flush(&engine, &store, expected).await; + assert!(store.flush_candidates().is_empty()); + assert_eq!(expected_rows, scan_rows(&engine, REGION_A).await); + engine.stop().await.unwrap(); + store.stop().await.unwrap(); +} + +#[rstest] +#[case(AckMode::Durable)] +#[case(AckMode::Enqueued)] +#[tokio::test] +async fn test_wal_pressure_survives_restart(#[case] ack_mode: AckMode) { + use crate::time_provider::mock::MockTimeProvider; + + let mut env = TestEnv::new().await; + let objects = memory_store(); + let store = open_store(&objects, ack_mode).await; + let now = common_time::util::current_time_millis(); + let clock = Arc::new(MockTimeProvider::new(now)); + let engine = env + .create_engine_with_log_store_and_time( + pressure_config(), + store.clone(), + clock.clone(), + None, + ) + .await; + let (table_dir, schema) = create_region(&engine, REGION_A, &[]).await; + fill_pressure_objects(&engine, &store, &schema).await; + let expected = latest(&store, REGION_A); + let expected_rows = scan_rows(&engine, REGION_A).await; + crash(engine, store).await; + + let store = open_store(&objects, ack_mode).await; + assert_eq!(vec![REGION_A], store.flush_candidates()); + let engine = env + .create_engine_with_log_store_and_time( + pressure_config(), + store.clone(), + clock.clone(), + None, + ) + .await; + open_region(&engine, REGION_A, &table_dir, &[]) + .await + .unwrap(); + assert_eq!(expected_rows, scan_rows(&engine, REGION_A).await); + assert_eq!(0, region(&engine, REGION_A).version().flushed_entry_id); + clock.set_now(now + 120_000); + clock.set_elapsed(120_000); + wait_for_pressure_flush(&engine, &store, expected).await; + assert!(store.flush_candidates().is_empty()); + assert_eq!(expected_rows, scan_rows(&engine, REGION_A).await); + engine.stop().await.unwrap(); + store.stop().await.unwrap(); +} + +#[derive(Default)] +struct PressureFlushGate { + started: tokio::sync::Notify, + resume: tokio::sync::Notify, +} + +#[async_trait::async_trait] +impl crate::engine::listener::EventListener for PressureFlushGate { + async fn on_flush_begin(&self, _: RegionId) { + self.started.notify_one(); + self.resume.notified().await; + } +} + +#[tokio::test] +async fn test_wal_pressure_flush_races_with_close() { + use crate::time_provider::mock::MockTimeProvider; + + let mut env = TestEnv::new().await; + let objects = memory_store(); + let store = open_store(&objects, AckMode::Durable).await; + let now = common_time::util::current_time_millis(); + let clock = Arc::new(MockTimeProvider::new(now)); + let gate = Arc::new(PressureFlushGate::default()); + let engine = env + .create_engine_with_log_store_and_time( + pressure_config(), + store.clone(), + clock.clone(), + Some(gate.clone()), + ) + .await; + let (table_dir, schema) = create_region(&engine, REGION_A, &[]).await; + fill_pressure_objects(&engine, &store, &schema).await; + let expected_rows = scan_rows(&engine, REGION_A).await; + let region_a = region(&engine, REGION_A); + clock.set_now(now + 120_000); + clock.set_elapsed(120_000); + tokio::time::timeout(WAIT, gate.started.notified()) + .await + .unwrap(); + tokio::time::timeout(WAIT, close_region(&engine, REGION_A)) + .await + .unwrap(); + assert!(!engine.is_region_exists(REGION_A)); + gate.resume.notify_one(); + assert_eq!( + 0, + region_a + .manifest_ctx + .manifest_manager + .read() + .await + .manifest() + .flushed_entry_id + ); + assert_eq!(vec![REGION_A], store.flush_candidates()); + // Reopening must replay every row retained by the cancelled flush. + open_region(&engine, REGION_A, &table_dir, &[]) + .await + .unwrap(); + assert_eq!(expected_rows, scan_rows(&engine, REGION_A).await); + clock.set_now(now + 240_000); + tokio::time::timeout(WAIT, gate.started.notified()) + .await + .unwrap(); + gate.resume.notify_one(); + wait_for_pressure_flush(&engine, &store, latest(&store, REGION_A)).await; + assert!(store.flush_candidates().is_empty()); + engine.stop().await.unwrap(); + store.stop().await.unwrap(); +} diff --git a/src/mito2/src/flush.rs b/src/mito2/src/flush.rs index 1857997fd64..2951d109d54 100644 --- a/src/mito2/src/flush.rs +++ b/src/mito2/src/flush.rs @@ -220,6 +220,8 @@ pub enum FlushReason { EngineFull, /// Region reaches its write buffer threshold. RegionFull, + /// Flush to relieve retained WAL pressure. + WalPressure, /// Manual flush. Manual, /// Flush to alter table. diff --git a/src/mito2/src/read/range_cache.rs b/src/mito2/src/read/range_cache.rs index ded0230f4b9..4caf4636695 100644 --- a/src/mito2/src/read/range_cache.rs +++ b/src/mito2/src/read/range_cache.rs @@ -897,11 +897,10 @@ mod tests { } #[rstest::rstest] - #[case(1024 * 1024, true)] - #[case(1, false)] + #[case(true)] + #[case(false)] #[tokio::test] async fn test_shared_range_read_preserves_batches_when_admission_budget_is_exhausted( - #[case] capacity: u64, #[case] cached: bool, ) { use std::sync::atomic::{AtomicUsize, Ordering}; @@ -910,9 +909,25 @@ mod tests { new_stream_context(vec![col("k0").eq(lit("a"))], None, FileTimeRange::default()).await; ctx.input.cache_strategy = CacheStrategy::EnableAll(Arc::new( CacheManager::builder() - .range_result_cache_size(capacity) + .range_result_cache_size(1024 * 1024) .build(), )); + let memory = ctx + .input + .cache_strategy + .range_result_cache() + .unwrap() + .retention_memory(); + let available = memory.available_permits(); + // A tiny cache still has one rounded-up permit. Hold the entire budget + // so compaction cannot reacquire it and admit the small test batches. + let blocker = (!cached).then(|| { + let permit = memory + .try_acquire(available * memory.permit_bytes()) + .unwrap(); + assert_eq!(0, memory.available_permits()); + permit + }); let key = build_range_cache_key(&ctx, &range, None).unwrap(); let (_, metrics) = test_cache_context(&ctx.input.cache_strategy); let calls = Arc::new(AtomicUsize::new(0)); @@ -945,14 +960,9 @@ mod tests { ctx.input.cache_strategy.get_range_result(&key).is_some(), cached ); - let memory = &ctx - .input - .cache_strategy - .range_result_cache() - .unwrap() - .retention_memory(); + drop(blocker); tokio::time::timeout(std::time::Duration::from_secs(5), async { - while memory.available_permits() != (capacity as usize).div_ceil(1024) { + while memory.available_permits() != available { tokio::task::yield_now().await; } }) diff --git a/src/mito2/src/test_util.rs b/src/mito2/src/test_util.rs index be8f3b64003..75d6d575f6e 100644 --- a/src/mito2/src/test_util.rs +++ b/src/mito2/src/test_util.rs @@ -558,6 +558,32 @@ impl TestEnv { .unwrap() } + /// Creates an engine on the supplied WAL with a controllable periodic clock. + pub(crate) async fn create_engine_with_log_store_and_time( + &mut self, + config: MitoConfig, + log_store: Arc, + time_provider: TimeProviderRef, + listener: Option, + ) -> MitoEngine { + let object_store_manager = Arc::new(self.create_object_store_manager()); + self.object_store_manager = Some(object_store_manager.clone()); + MitoEngine::new_for_test( + &self.data_home().display().to_string(), + config, + log_store, + object_store_manager, + None, + listener, + time_provider, + self.schema_metadata_manager.clone(), + self.file_ref_manager.clone(), + self.partition_expr_fetcher.clone(), + ) + .await + .unwrap() + } + /// Creates a new engine with specific config on an [ObjectStoreLogStore] that /// keeps its objects in memory, opened as datanode 0 in the standalone /// generation. Returns the store so that a test can drive its testing hooks. diff --git a/src/mito2/src/wal.rs b/src/mito2/src/wal.rs index bae0556a4fa..e8123988853 100644 --- a/src/mito2/src/wal.rs +++ b/src/mito2/src/wal.rs @@ -21,7 +21,8 @@ pub(crate) mod raw_entry_reader; use std::collections::HashMap; use std::mem; -use std::sync::Arc; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; use api::v1::WalEntry; use common_error::ext::BoxedError; @@ -35,6 +36,7 @@ use store_api::logstore::entry::Entry; use store_api::logstore::provider::Provider; use store_api::logstore::{AppendBatchResponse, LogStore}; use store_api::storage::RegionId; +use tokio::sync::watch; use crate::error::{ BuildEntrySnafu, CheckWalHistorySnafu, DeleteWalSnafu, Result, WaitWalDurableSnafu, @@ -85,12 +87,17 @@ impl std::fmt::Debug for DurabilityBarrier { pub struct Wal { /// The underlying log store. store: Arc, + /// One pressure snapshot shared by all workers using this WAL. + flush_candidates: Arc>, } impl Wal { /// Creates a new [Wal] from the log store. pub fn new(store: Arc) -> Self { - Self { store } + Self { + store, + flush_candidates: Arc::default(), + } } pub fn store(&self) -> &Arc { @@ -102,11 +109,30 @@ impl Clone for Wal { fn clone(&self) -> Self { Self { store: Arc::clone(&self.store), + flush_candidates: self.flush_candidates.clone(), } } } impl Wal { + /// Subscribes to shared WAL pressure snapshots. Notifications only advise + /// workers to check their current region state, and never wait for flush. + pub(crate) fn subscribe_flush_candidates(&self) -> watch::Receiver> { + self.flush_candidates + .lock() + .unwrap_or_else(PoisonError::into_inner) + .sender + .subscribe() + } + + /// Refreshes and publishes candidates at most once per interval for all workers. + pub(crate) fn refresh_flush_candidates(&self, now: i64, interval: Duration) { + self.flush_candidates + .lock() + .unwrap_or_else(PoisonError::into_inner) + .refresh(now, interval, || self.store.flush_candidates()); + } + /// Returns a writer to write to the WAL. pub fn writer(&self) -> WalWriter { WalWriter { @@ -333,6 +359,38 @@ impl WalWriter { } } +/// A periodically refreshed advisory snapshot. Publishing wakes every worker, +/// so a worker whose periodic timer just ran does not wait another interval. +#[derive(Debug)] +struct FlushCandidates { + /// Wall-clock milliseconds of the last refresh, using the worker clock. + refreshed_at: Option, + /// Latest candidates; intermediate snapshots can be coalesced safely. + sender: watch::Sender>, +} + +impl Default for FlushCandidates { + fn default() -> Self { + let (sender, _) = watch::channel(Arc::default()); + Self { + refreshed_at: None, + sender, + } + } +} + +impl FlushCandidates { + fn refresh(&mut self, now: i64, interval: Duration, load: impl FnOnce() -> Vec) { + if self + .refreshed_at + .is_none_or(|last| now.saturating_sub(last) >= interval.as_millis() as i64) + { + self.sender.send_replace(load().into()); + self.refreshed_at = Some(now); + } + } +} + #[cfg(test)] mod tests { use api::v1::helper::{tag_column_schema, time_index_column_schema}; @@ -354,6 +412,32 @@ mod tests { use super::*; + #[test] + fn test_flush_candidates_share_refresh_and_retry_without_progress() { + let a = RegionId::new(1, 1); + let interval = Duration::from_millis(60); + let mut candidates = FlushCandidates::default(); + let mut first = candidates.sender.subscribe(); + let mut second = candidates.sender.subscribe(); + candidates.refresh(0, interval, || vec![a]); + assert!(first.has_changed().unwrap()); + assert!(second.has_changed().unwrap()); + let first_snapshot = first.borrow_and_update().clone(); + let second_snapshot = second.borrow_and_update().clone(); + assert!(Arc::ptr_eq(&first_snapshot, &second_snapshot)); + assert_eq!(&[a], first_snapshot.as_ref()); + candidates.refresh(59, interval, || panic!("must share the snapshot")); + candidates.refresh(-1, interval, || panic!("clock rolled back")); + assert!(!first.has_changed().unwrap()); + // A failed or skipped flush must still be retried with the same candidates. + candidates.refresh(60, interval, || vec![a]); + assert!(first.has_changed().unwrap()); + assert_eq!(&[a], first.borrow_and_update().as_ref()); + candidates.refresh(120, interval, Vec::new); + assert!(first.borrow_and_update().is_empty()); + assert!(second.borrow_and_update().is_empty()); + } + struct WalEnv { _wal_dir: TempDir, log_store: Option>, diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index 31a2aa0f515..79398a6d219 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -260,13 +260,14 @@ impl WorkerGroup { .then(|| Arc::new(Semaphore::new(config.gc.max_concurrent_gc_job))); let node_lease = Arc::new(NodeLease::default()); let staging_regions = StagingRegionsRef::default(); + let wal = Wal::new(log_store); let workers = (0..config.num_workers) .map(|id| { WorkerStarter { id: id as WorkerId, config: config.clone(), - log_store: log_store.clone(), + wal: wal.clone(), object_store_manager: object_store_manager.clone(), write_buffer_manager: write_buffer_manager.clone(), index_build_job_pool: index_build_job_pool.clone(), @@ -533,12 +534,13 @@ impl WorkerGroup { .then(|| Arc::new(Semaphore::new(config.gc.max_concurrent_gc_job))); let node_lease = Arc::new(NodeLease::default()); let staging_regions = StagingRegionsRef::default(); + let wal = Wal::new(log_store); let workers = (0..config.num_workers) .map(|id| { WorkerStarter { id: id as WorkerId, config: config.clone(), - log_store: log_store.clone(), + wal: wal.clone(), object_store_manager: object_store_manager.clone(), write_buffer_manager: write_buffer_manager.clone(), index_build_job_pool: index_build_job_pool.clone(), @@ -652,7 +654,7 @@ pub(crate) fn worker_init_check_delay() -> Duration { struct WorkerStarter { id: WorkerId, config: Arc, - log_store: Arc, + wal: Wal, object_store_manager: ObjectStoreManagerRef, write_buffer_manager: WriteBufferManagerRef, compact_job_pool: Arc, @@ -738,7 +740,8 @@ impl WorkerStarter { opening_regions: opening_regions.clone(), sender: sender.clone(), receiver, - wal: Wal::new(self.log_store), + wal_flush_receiver: self.wal.subscribe_flush_candidates(), + wal: self.wal, object_store_manager: self.object_store_manager.clone(), running: running.clone(), memtable_builder_provider: MemtableBuilderProvider::new( @@ -1065,6 +1068,8 @@ struct RegionWorkerLoop { receiver: Receiver, /// WAL of the engine. wal: Wal, + /// Shared WAL pressure candidates, independently of memory-pressure wakeups. + wal_flush_receiver: watch::Receiver>, /// Manages object stores for manifest and SSTs. object_store_manager: ObjectStoreManagerRef, /// Whether the worker thread is still running. @@ -1218,6 +1223,30 @@ impl RegionWorkerLoop { continue; } } + result = self.wal_flush_receiver.changed() => { + if result.is_err() { + break; + } + let candidates = self.wal_flush_receiver.borrow_and_update().clone(); + if let Err(e) = self.flush_for_wal_pressure(&candidates) { + error!(e; "Failed to flush regions under WAL pressure"); + } + #[cfg(any(test, feature = "test"))] + if let Some(listener) = &self.listener.listener { + for ®ion_id in candidates.iter() { + if self.regions.get_region(region_id).is_some() { + listener.on_wal_pressure_checked( + region_id, + self.flush_scheduler.is_flush_requested(region_id), + ); + } + } + } + // Notifications reset the loop's sleep, so they must also + // check periodic work even when the candidate list is empty. + self.handle_periodical_tasks(); + continue; + } _ = &mut sleep => { // Timeout. Checks periodical tasks. self.handle_periodical_tasks(); @@ -1498,6 +1527,8 @@ impl RegionWorkerLoop { self.last_periodical_check_millis = self.time_provider.current_time_millis(); + self.wal + .refresh_flush_candidates(self.last_periodical_check_millis, CHECK_REGION_INTERVAL); if let Err(e) = self.flush_periodically() { error!(e; "Failed to flush regions periodically"); } diff --git a/src/mito2/src/worker/handle_flush.rs b/src/mito2/src/worker/handle_flush.rs index 32cd19a4142..f68b85bc190 100644 --- a/src/mito2/src/worker/handle_flush.rs +++ b/src/mito2/src/worker/handle_flush.rs @@ -401,6 +401,27 @@ impl RegionWorkerLoop { } } + /// Flushes locally writable candidates selected by the WAL. + pub(crate) fn flush_for_wal_pressure(&mut self, candidates: &[RegionId]) -> Result<()> { + for ®ion_id in candidates.iter() { + let Some(region) = self.regions.get_region(region_id) else { + continue; + }; + if !region.is_writable() + || region.is_staging() + || self.flush_scheduler.is_flush_requested(region_id) + || region_memtable_usage(®ion.version()) == 0 + { + continue; + } + let task = + self.new_flush_task(®ion, FlushReason::WalPressure, None, self.config.clone()); + self.flush_scheduler + .schedule_flush(region_id, ®ion.version_control, task)?; + } + Ok(()) + } + /// Flushes regions periodically. pub(crate) fn flush_periodically(&mut self) -> Result<()> { let regions = self.regions.list_regions(); diff --git a/src/store-api/src/logstore.rs b/src/store-api/src/logstore.rs index 88abd9809a5..934ae3d3d17 100644 --- a/src/store-api/src/logstore.rs +++ b/src/store-api/src/logstore.rs @@ -35,6 +35,17 @@ use crate::storage::RegionId; pub trait LogStore: Send + Sync + 'static + std::fmt::Debug { type Error: ErrorExt + Send + Sync + 'static; + /// Returns regions whose retained WAL is under storage pressure and may be + /// released by flushing. This is an advisory snapshot, not permission to + /// flush or delete entries. The caller checks the current region state and + /// uses [`Self::obsolete`] only after persisting its data. + /// + /// Implementations inspect local metadata without I/O. Backends without + /// pressure-driven flushing return no candidates. + fn flush_candidates(&self) -> Vec { + Vec::new() + } + /// Stops components of the logstore. async fn stop(&self) -> Result<(), Self::Error>; From 97c8136c3c4f881b06fc825dcddd2bad385b61b6 Mon Sep 17 00:00:00 2001 From: discord9 Date: Tue, 10 Nov 2026 18:17:24 +0000 Subject: [PATCH 04/63] chore(deps): bump datafusion to ae04160b (#10320) * chore(deps): bump datafusion to ae04160b Move all 16 `[patch.crates-io]` DataFusion pins from `cc5534492` to `ae04160b`, the merge commit of GreptimeTeam/datafusion#42. That fork commit backports six upstream apache/datafusion fixes: - #26452 timestamp-to-time casts no longer drive statistics pruning - #24675 memory-limited NLJ fallback refuses left-emission joins with a multi-partition probe side instead of emitting wrong unmatched rows - #24891 RepartitionExec spill-pool deadlock with two open files - #25076 null-aware anti join no longer emits rows after a sibling probe partition saw NULL - #25339 correlated NOT IN with a non-equality correlation - #26578 null-aware anti join drops build rows with a dictionary NULL key The first three are faithful backports. The last three are re-implementations: upstream restructured `hash_join/stream.rs` before writing them, so the patches do not apply to this fork's older copy of that file. `#25339` covers the single-equi-key plus residual-filter shape; multi-key correlated `NOT IN` still fails at planning as before. `Cargo.lock` is regenerated (35 `datafusion*` packages). No runtime acceptance has been run against this pin; see the PR description for the three checks worth doing before shipping. Signed-off-by: discord9 * fix(common-query): pass the pruning bitmap to HashTableLookupExpr::new #39 added a fifth parameter to `HashTableLookupExpr::new`; the dynamic-filter payload round-trip test still constructed it with four arguments, which breaks `--all-targets` builds even though the library itself compiles. Signed-off-by: discord9 * chore(deps): bump datafusion to 70f84c5b Move the pins from `ae04160b` to `70f84c5b`, the head of `greptimedb-55.1-thin-fork` after GreptimeTeam/datafusion#37 was merged on top of #39/#41/#42. `ae04160b` did not contain #37, so the reverse-cast constraint propagation guard was lost and `tests/cases/distributed/optimizer/partition_pruning_cast` failed: the filter `CAST(k AS BIGINT) = 1` made the planner treat the float column `k` as a singleton and drop the requested `ORDER BY k DESC`. The new pin carries both the reverse-cast guard and the six release backports, so the regression is covered again. Signed-off-by: discord9 --------- Signed-off-by: discord9 --- Cargo.lock | 70 ++++++++++++++++----------------- Cargo.toml | 32 +++++++-------- src/common/query/src/request.rs | 1 + 3 files changed, 52 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index de81ed58d7a..3d06e3a59d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3770,7 +3770,7 @@ checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" [[package]] name = "datafusion" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -3822,7 +3822,7 @@ dependencies = [ [[package]] name = "datafusion-catalog" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3846,7 +3846,7 @@ dependencies = [ [[package]] name = "datafusion-catalog-listing" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3869,7 +3869,7 @@ dependencies = [ [[package]] name = "datafusion-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-ipc 59.2.0", @@ -3895,7 +3895,7 @@ dependencies = [ [[package]] name = "datafusion-common-runtime" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "futures", "log", @@ -3905,7 +3905,7 @@ dependencies = [ [[package]] name = "datafusion-datasource" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "async-compression", @@ -3941,7 +3941,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-arrow" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-ipc 59.2.0", @@ -3965,7 +3965,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-csv" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3988,7 +3988,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-json" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "async-trait", @@ -4011,7 +4011,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-parquet" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -4043,12 +4043,12 @@ dependencies = [ [[package]] name = "datafusion-doc" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" [[package]] name = "datafusion-execution" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-buffer 59.2.0", @@ -4073,7 +4073,7 @@ dependencies = [ [[package]] name = "datafusion-expr" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -4097,7 +4097,7 @@ dependencies = [ [[package]] name = "datafusion-expr-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4108,7 +4108,7 @@ dependencies = [ [[package]] name = "datafusion-functions" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-buffer 59.2.0", @@ -4139,7 +4139,7 @@ dependencies = [ [[package]] name = "datafusion-functions-aggregate" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4159,7 +4159,7 @@ dependencies = [ [[package]] name = "datafusion-functions-aggregate-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4170,7 +4170,7 @@ dependencies = [ [[package]] name = "datafusion-functions-nested" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-ord 59.2.0", @@ -4194,7 +4194,7 @@ dependencies = [ [[package]] name = "datafusion-functions-table" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "async-trait", @@ -4209,7 +4209,7 @@ dependencies = [ [[package]] name = "datafusion-functions-window" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4225,7 +4225,7 @@ dependencies = [ [[package]] name = "datafusion-functions-window-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "datafusion-common", "datafusion-physical-expr-common", @@ -4234,7 +4234,7 @@ dependencies = [ [[package]] name = "datafusion-macros" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "datafusion-doc", "quote", @@ -4244,7 +4244,7 @@ dependencies = [ [[package]] name = "datafusion-optimizer" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "chrono", @@ -4292,7 +4292,7 @@ dependencies = [ [[package]] name = "datafusion-physical-expr" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -4315,7 +4315,7 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-adapter" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4329,7 +4329,7 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "chrono", @@ -4346,7 +4346,7 @@ dependencies = [ [[package]] name = "datafusion-physical-optimizer" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4365,7 +4365,7 @@ dependencies = [ [[package]] name = "datafusion-physical-plan" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "arrow-data 59.2.0", @@ -4402,7 +4402,7 @@ dependencies = [ [[package]] name = "datafusion-proto" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "datafusion-catalog", @@ -4428,7 +4428,7 @@ dependencies = [ [[package]] name = "datafusion-proto-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4438,7 +4438,7 @@ dependencies = [ [[package]] name = "datafusion-proto-models" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "datafusion-common", "datafusion-proto-common", @@ -4448,7 +4448,7 @@ dependencies = [ [[package]] name = "datafusion-pruning" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4463,7 +4463,7 @@ dependencies = [ [[package]] name = "datafusion-session" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow-schema 59.2.0", "async-trait", @@ -4477,7 +4477,7 @@ dependencies = [ [[package]] name = "datafusion-sql" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "arrow 59.2.0", "bigdecimal 0.4.8", @@ -4496,7 +4496,7 @@ dependencies = [ [[package]] name = "datafusion-substrait" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=70f84c5bf2511d40ee4a4036fa086ba36f207a85#70f84c5bf2511d40ee4a4036fa086ba36f207a85" dependencies = [ "async-recursion", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 48e39ada226..7578ac0c118 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -371,22 +371,22 @@ rev = "f743c3a5fe8c1f57363eac5866c356b7d91f9b39" [patch.crates-io] substrait = { git = "https://github.com/GreptimeTeam/substrait-rs.git", rev = "91ec978b0649417ad3da8390e7a515baec723b1b" } -datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } -datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } +datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "70f84c5bf2511d40ee4a4036fa086ba36f207a85" } datafusion-pg-catalog = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" } arrow-pg = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" } sqlparser = { git = "https://github.com/GreptimeTeam/sqlparser-rs.git", rev = "9e9019bb1c7040ed956f654e39378dd42ab17884" } diff --git a/src/common/query/src/request.rs b/src/common/query/src/request.rs index 86c6758aa25..c682cf81e02 100644 --- a/src/common/query/src/request.rs +++ b/src/common/query/src/request.rs @@ -525,6 +525,7 @@ mod tests { SeededRandomState::with_seed(0), Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(0)))), "hash_lookup".to_string(), + None, )) as Arc; let expr = Arc::new(BinaryExpr::new(lower_bound, Operator::And, lookup)) as Arc; From ddc16bafe8d32cca69e6ef68870f3afa158cfd6e Mon Sep 17 00:00:00 2001 From: dennis zhuang Date: Wed, 11 Nov 2026 03:46:56 +0000 Subject: [PATCH 05/63] fix(datatypes): render jsonb stored as JSON text without panics or wrong values (#10197) * fix(datatypes): decode jsonb before rendering it as text jsonb_to_string serialized the bytes through RawJsonb's Serialize impl, which panics with an out-of-range slice index on JSON text such as "hello world" or " null" (stored by COPY FROM and MySQL text parameters) and on truncated jsonb. Its text fallback was also stricter than the extended parser reads used before. Decode with jsonb::from_slice, as reads did before #10112, then write the value out with serde_json escaping for keys and strings. Signed-off-by: Dennis Zhuang * perf(datatypes): keep streaming jsonb serialization in jsonb_to_string Decoding into a jsonb::Value tree allocates per array, object and key on every JSON cell returned over PostgreSQL and MySQL. Go back to serializing the raw bytes with RawJsonb's Serialize impl, and bump jsonb to a rev whose Serialize returns an error instead of panicking on out-of-range payloads (GreptimeTeam/jsonb#2). Bytes that fail to serialize are parsed as JSON text with the extended parser, as jsonb::from_slice does. Signed-off-by: Dennis Zhuang * test(datatypes): pin text values that used to read back as false Signed-off-by: Dennis Zhuang * chore: bump jsonb to reject scalar headers with non-zero length bits JSON text over ~2 MB could still pass the payload bounds check and read back as a wrong value (GreptimeTeam/jsonb#2). Signed-off-by: Dennis Zhuang * fix(datatypes): report the text parse error when JSON bytes are neither jsonb nor text Also pin jsonb_to_serde_json on JSON text scalars that used to decode as false. Signed-off-by: Dennis Zhuang * chore: pin jsonb to the merged commit on main GreptimeTeam/jsonb#2 reached main through GreptimeTeam/jsonb#3. Signed-off-by: Dennis Zhuang --------- Signed-off-by: Dennis Zhuang --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/datatypes/src/types/json_type.rs | 66 +++++++++++++++++++++------- 3 files changed, 51 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3d06e3a59d5..a7d236a8941 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7584,7 +7584,7 @@ dependencies = [ [[package]] name = "jsonb" version = "0.5.6" -source = "git+https://github.com/GreptimeTeam/jsonb?rev=dd1e2341e3df35e9de38959328caa7628e81b6b1#dd1e2341e3df35e9de38959328caa7628e81b6b1" +source = "git+https://github.com/GreptimeTeam/jsonb?rev=5a6472858d860ac034075c17253f41617bdfa956#5a6472858d860ac034075c17253f41617bdfa956" dependencies = [ "byteorder", "ethnum", diff --git a/Cargo.toml b/Cargo.toml index 7578ac0c118..4bbb4453ae4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -176,7 +176,7 @@ hyper-util = "0.1" icu_properties = "2.0.1" indicatif = "0.17" itertools = "0.14" -jsonb = { git = "https://github.com/GreptimeTeam/jsonb", rev = "dd1e2341e3df35e9de38959328caa7628e81b6b1", default-features = false, features = [ +jsonb = { git = "https://github.com/GreptimeTeam/jsonb", rev = "5a6472858d860ac034075c17253f41617bdfa956", default-features = false, features = [ "databend", ] } lazy_static = "1.4" diff --git a/src/datatypes/src/types/json_type.rs b/src/datatypes/src/types/json_type.rs index dea46d07e06..f7f51b74016 100644 --- a/src/datatypes/src/types/json_type.rs +++ b/src/datatypes/src/types/json_type.rs @@ -389,34 +389,33 @@ impl Display for JsonType { /// Converts a json type value to string /// -/// The binary jsonb is serialized directly with `serde_json`, so both object keys and -/// string values are escaped by `serde_json`. `RawJsonb::to_string()` is deliberately -/// avoided, since it falls back to the lossy raw bytes when serialization fails. +/// The binary jsonb is serialized directly with `serde_json`, so object keys and string +/// values are escaped by `serde_json`. `RawJsonb::to_string()` is avoided, since it falls +/// back to the lossy raw bytes when serialization fails. /// -/// Some write paths (e.g. `COPY FROM` csv/json/parquet files, or a JSON parameter bound -/// as text through the MySQL protocol) currently store the JSON *text* as the column -/// bytes instead of binary jsonb, and such data may already be persisted. When the bytes -/// are not valid jsonb but are valid JSON text, they are re-encoded as jsonb and then -/// serialized the same way, so the output is still escaped by `serde_json`. Anything else -/// is reported as an error. +/// Some write paths (e.g. `COPY FROM` files, or a JSON parameter bound as text through +/// the MySQL protocol) store JSON text in place of binary jsonb. Bytes that fail to +/// serialize are parsed as text with the extended parser, as `jsonb::from_slice` does. pub fn jsonb_to_string(val: &[u8]) -> Result { if val.is_empty() { return Ok("".to_string()); } match serde_json::to_string(&jsonb::RawJsonb::new(val)) { Ok(s) => Ok(s), - Err(e) => match jsonb::parse_value_standard_mode(val) { - Ok(json) => serde_json::to_string(&jsonb::RawJsonb::new(&json.to_vec())).map_err(|e| { + Err(jsonb_err) => { + let value = jsonb::parse_value(val).map_err(|text_err| { + InvalidJsonSnafu { + value: format!("neither jsonb ({jsonb_err}) nor JSON text ({text_err})"), + } + .build() + })?; + serde_json::to_string(&jsonb::RawJsonb::new(&value.to_vec())).map_err(|e| { InvalidJsonSnafu { value: e.to_string(), } .build() - }), - Err(_) => InvalidJsonSnafu { - value: e.to_string(), - } - .fail(), - }, + }) + } } } @@ -453,6 +452,21 @@ mod tests { Ok(()) } + #[test] + fn test_jsonb_to_serde_json_scalars() { + for input in [r#""2026-11-05""#, "1730800000000", "false", "null"] { + let expected: serde_json::Value = serde_json::from_str(input).unwrap(); + let jsonb = parse_string_to_jsonb(input).unwrap(); + assert_eq!(jsonb_to_serde_json(&jsonb).unwrap(), expected, "{input}"); + // Stored as JSON text, the first two used to decode as `false`. + assert_eq!( + jsonb_to_serde_json(input.as_bytes()).unwrap(), + expected, + "{input}" + ); + } + } + #[test] fn test_jsonb_to_string_escapes_object_keys() -> std::result::Result<(), Box> { @@ -514,6 +528,10 @@ mod tests { fn test_jsonb_to_string_rejects_invalid_jsonb() { assert!(jsonb_to_string(&[1, 2, 3, 4]).is_err()); assert_eq!(jsonb_to_string(&[]).unwrap(), ""); + + let mut truncated = parse_string_to_jsonb(r#"{"k":"value"}"#).unwrap(); + truncated.pop(); + assert!(jsonb_to_string(&truncated).is_err()); } #[test] @@ -532,6 +550,20 @@ mod tests { jsonb_to_string(br#"{"a\"b":"c\u0000d"}"#).unwrap(), r#"{"a\"b":"c\u0000d"}"# ); + // These start with bytes that also read as a jsonb scalar header. + assert_eq!( + jsonb_to_string(br#""hello world""#).unwrap(), + r#""hello world""# + ); + assert_eq!(jsonb_to_string(b" null").unwrap(), "null"); + // Without the bounds check, these read back as `false`. + assert_eq!( + jsonb_to_string(br#""2026-11-05""#).unwrap(), + r#""2026-11-05""# + ); + assert_eq!(jsonb_to_string(b"1730800000000").unwrap(), "1730800000000"); + // Extended syntax is accepted, as text was read before. + assert_eq!(jsonb_to_string(b"[+1,,2]").unwrap(), "[1,null,2]"); assert!(jsonb_to_string(b"{not json").is_err()); } From c8e0d29df20824eeaaff8ed0b5ee35ca1e9bf116 Mon Sep 17 00:00:00 2001 From: "Lei, HUANG" <6406592+v0y4g3r@users.noreply.github.com> Date: Wed, 11 Nov 2026 05:42:51 +0000 Subject: [PATCH 06/63] feat(mito2): publish table compaction results conditionally (#10310) * feat(mito2): publish table compaction results conditionally Publish one region from a live input snapshot using an ordinary file-only edit. Permit repeated submissions and partial success without manifest task state, while preserving sequence, GC protection and uncertain-write recovery. Signed-off-by: Lei, HUANG * refactor(mito2): write table compaction outputs to level 0 Route split outputs into the ordinary L0 pipeline so window merges and semantic folding stay with region compaction. Update publication validation and tests accordingly. Signed-off-by: Lei, HUANG * fix(mito2): release verified footers before manifest publication Signed-off-by: Lei, HUANG * refactor(mito2): compare typed table compaction options Signed-off-by: Lei, HUANG * test(mito2): cover table compaction output validation failures Signed-off-by: Lei, HUANG * docs(mito2): clarify series count verification limits Signed-off-by: Lei, HUANG * fix(mito2): reject index declarations without output index objects Signed-off-by: Lei, HUANG * docs(mito2): document table compaction outputs as L0 Signed-off-by: Lei, HUANG * docs(mito2): map the table compaction publication module Signed-off-by: Lei, HUANG --------- Signed-off-by: Lei, HUANG --- licenserc-enterprise.toml | 4 + licenserc.toml | 4 + src/mito2/AGENTS.md | 1 + src/mito2/src/compaction/multi_region.rs | 6 +- .../src/compaction/multi_region/tests.rs | 4 +- .../src/compaction/multi_region/writer.rs | 4 +- src/mito2/src/engine.rs | 2 + src/mito2/src/engine/region_hook.rs | 23 + src/mito2/src/engine/table_compaction.rs | 131 ++ .../src/engine/table_compaction/output.rs | 207 ++++ .../src/engine/table_compaction/tests.rs | 1086 +++++++++++++++++ src/mito2/src/request.rs | 10 + src/mito2/src/worker.rs | 2 + src/mito2/src/worker/handle_manifest.rs | 54 +- .../src/worker/handle_table_compaction.rs | 151 +++ .../manifest/table_compaction/README.md | 12 + 16 files changed, 1677 insertions(+), 24 deletions(-) create mode 100644 src/mito2/src/engine/table_compaction.rs create mode 100644 src/mito2/src/engine/table_compaction/output.rs create mode 100644 src/mito2/src/engine/table_compaction/tests.rs create mode 100644 src/mito2/src/worker/handle_table_compaction.rs diff --git a/licenserc-enterprise.toml b/licenserc-enterprise.toml index 939346f5cba..22b35ded3e8 100644 --- a/licenserc-enterprise.toml +++ b/licenserc-enterprise.toml @@ -26,6 +26,10 @@ includes = [ "src/sql/src/parsers/create_parser/trigger.rs", "src/sql/src/parsers/show_parser/trigger.rs", "src/mito2/src/extension.rs", + "src/mito2/src/engine/table_compaction.rs", + "src/mito2/src/engine/table_compaction/output.rs", + "src/mito2/src/engine/table_compaction/tests.rs", + "src/mito2/src/worker/handle_table_compaction.rs", "src/mito2/src/compaction/multi_region.rs", "src/mito2/src/compaction/multi_region/source.rs", "src/mito2/src/compaction/multi_region/memory.rs", diff --git a/licenserc.toml b/licenserc.toml index e601ca6f7c1..172a6af5d61 100644 --- a/licenserc.toml +++ b/licenserc.toml @@ -42,6 +42,10 @@ excludes = [ "src/sql/src/parsers/create_parser/trigger.rs", "src/sql/src/parsers/show_parser/trigger.rs", "src/mito2/src/extension.rs", + "src/mito2/src/engine/table_compaction.rs", + "src/mito2/src/engine/table_compaction/output.rs", + "src/mito2/src/engine/table_compaction/tests.rs", + "src/mito2/src/worker/handle_table_compaction.rs", "src/mito2/src/compaction/multi_region.rs", "src/mito2/src/compaction/multi_region/source.rs", "src/mito2/src/compaction/multi_region/memory.rs", diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index ffd674917a2..9dc57b3f1fc 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -25,6 +25,7 @@ snapshot isolation). It implements the `RegionEngine` trait from `store-api`. | `flush` | `src/mito2/src/flush.rs` | `FlushScheduler`, `WriteBufferManager`, memtable → SST | | `compaction` | `src/mito2/src/compaction/` | Compaction scheduler (`scheduler.rs` + `scheduler/`), TWCS picker, strict-window manual picker, compactor, memory control | | `compaction/multi_region` | `src/mito2/src/compaction/multi_region.rs` | Enterprise lossless routing by a captured table partition rule; selected SSTs to per-region outputs, without manifest publication | +| `engine/table_compaction` | `src/mito2/src/engine/table_compaction.rs` | Enterprise conditional publication of table-compaction results: shared-input snapshot, verified-output checks, and the manifest-locked swap of shared inputs for L0 outputs | | `access_layer` | `src/mito2/src/access_layer.rs` | SST read/write over the object store | | `sst` | `src/mito2/src/sst/` | Parquet format, file metadata, index layout | | `series_index` | `src/mito2/src/series_index/` | Series index writer/searcher, bucket planning, catalogs, worker-owned reconciliation (`maintenance.rs`), shared approximate usage (`task.rs`), catalogs, and index lifecycle | diff --git a/src/mito2/src/compaction/multi_region.rs b/src/mito2/src/compaction/multi_region.rs index 2fa6ab1b737..de4549a4c5c 100644 --- a/src/mito2/src/compaction/multi_region.rs +++ b/src/mito2/src/compaction/multi_region.rs @@ -102,10 +102,10 @@ pub struct MultiRegionCompactionStats { /// Complete per-target outputs, including explicit empty partitions. pub struct MultiRegionCompactionOutput { - /// Output files, initially assigned to level 1 (L1). + /// Output files, already assigned to region-local L0. /// - /// The caller owns publication and must set [FileMeta::level] before - /// publishing if its intended output level differs from L1. + /// Window merging and semantic folding stay with ordinary region compaction, + /// which runs after publication; the caller does not adjust the level. pub files: BTreeMap>, /// Complete footer/index statistics for target hook delivery; not fabricated from FileMeta. pub sst_infos: BTreeMap>, diff --git a/src/mito2/src/compaction/multi_region/tests.rs b/src/mito2/src/compaction/multi_region/tests.rs index 3aadc435cb5..67709443086 100644 --- a/src/mito2/src/compaction/multi_region/tests.rs +++ b/src/mito2/src/compaction/multi_region/tests.rs @@ -543,7 +543,7 @@ async fn test_single_scan_routes_all_versions_without_folding( } for file in files { assert!(protected.files.lock().unwrap().contains(&file.file_id())); - assert_eq!(1, file.level); + assert_eq!(0, file.level); assert_eq!(id, file.region_id); assert_eq!(id != fixture.metadata.region_id, file.preserve_row_sequence); let rows = fixture @@ -1665,7 +1665,7 @@ async fn test_streaming_merge_preserves_overlapping_versions_and_field_routing( 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!(0, file.level); assert_eq!(info.file_id, file.file_id); assert_eq!(info.num_rows as u64, file.num_rows); assert_eq!(info.file_size, file.file_size); diff --git a/src/mito2/src/compaction/multi_region/writer.rs b/src/mito2/src/compaction/multi_region/writer.rs index 737fae51e44..0d2ce6ea838 100644 --- a/src/mito2/src/compaction/multi_region/writer.rs +++ b/src/mito2/src/compaction/multi_region/writer.rs @@ -183,7 +183,9 @@ impl<'a> TargetWriter<'a> { region_id: self.target.metadata.region_id, file_id: info.file_id, time_range: info.time_range, - level: 1, + // Region-local L0: window merges and semantic folding stay with + // ordinary region compaction. + level: 0, file_size: info.file_size, max_row_group_uncompressed_size: info.max_row_group_uncompressed_size, available_indexes: info.index_metadata.build_available_indexes(), diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 8ff2b0f6ce0..de9e796f8d1 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -87,6 +87,8 @@ mod skip_wal_test; mod staging_test; #[cfg(test)] mod sync_test; +#[cfg(feature = "enterprise")] +pub mod table_compaction; #[cfg(test)] mod truncate_test; diff --git a/src/mito2/src/engine/region_hook.rs b/src/mito2/src/engine/region_hook.rs index b3ecb4a1cdc..9f138405842 100644 --- a/src/mito2/src/engine/region_hook.rs +++ b/src/mito2/src/engine/region_hook.rs @@ -157,6 +157,7 @@ use std::fmt::Debug; use std::sync::Arc; use async_trait::async_trait; +use parquet::file::metadata::ParquetMetaData; use store_api::ManifestVersion; use store_api::metadata::RegionMetadataRef; use store_api::storage::RegionId; @@ -269,6 +270,13 @@ pub struct SstFileInfo<'a> { pub file_meta: &'a FileMeta, } +/// Externally produced SST with its verified footer. Index-builder statistics +/// are deliberately absent: they cannot be reconstructed from FileMeta. +pub struct VerifiedSstFileInfo<'a> { + pub file_meta: &'a FileMeta, + pub footer: &'a Arc, +} + /// Hook for observing region mutations in mito2. /// /// Implementations can be registered via the `Plugins` system: @@ -315,6 +323,21 @@ pub trait RegionHook: Send + Sync + Debug { Ok(HashSet::new()) } + /// Called for verified table-compaction outputs before manifest publication. + /// Unlike `on_sst_files_written`, this carries actual remote footers without + /// fabricating unavailable index-builder statistics. Retries may repeat it; + /// no manifest lock is held and implementations must be idempotent. Publication + /// may still fail after this callback; it is not a publication acknowledgement. + /// Use `on_manifest_updated` to observe a successful manifest commit. + async fn on_sst_files_verified( + &self, + region_id: RegionId, + region_metadata: &RegionMetadataRef, + files: &[VerifiedSstFileInfo<'_>], + ) { + let _ = (region_id, region_metadata, files); + } + /// Called after the region manifest is successfully committed to the **live** /// (normal) manifest directory. /// diff --git a/src/mito2/src/engine/table_compaction.rs b/src/mito2/src/engine/table_compaction.rs new file mode 100644 index 00000000000..d50cbb0944e --- /dev/null +++ b/src/mito2/src/engine/table_compaction.rs @@ -0,0 +1,131 @@ +// Copyright 2023-2026 GrepTime Inc. +// +// This file is part of the GreptimeDB Enterprise Edition and is licensed under +// the GreptimeDB Enterprise License. You may not use this file except in +// compliance with that license. A copy of the license is available at the root +// of this repository in the file LICENSE-ENTERPRISE. +// +// Unless required by applicable law or agreed to in writing, this software is +// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// either express or implied. + +//! One-shot publication of already-admitted shared inputs. Task tracking is external. + +pub(crate) mod output; +#[cfg(test)] +mod tests; + +use serde::{Deserialize, Serialize}; +use snafu::{OptionExt, ResultExt, ensure}; +use store_api::metadata::RegionMetadataRef; +use store_api::storage::RegionId; +use tokio::sync::oneshot; + +use crate::engine::MitoEngine; +use crate::error::{ + Error, InvalidRequestSnafu, RecvSnafu, RegionBusySnafu, RegionNotFoundSnafu, Result, + SerdeJsonSnafu, +}; +use crate::manifest::action::RegionEdit; +use crate::region::options::RegionOptions; +use crate::region::{RegionLeaderState, RegionRoleState}; +use crate::request::{RegionEditKind, RegionEditRequest, WorkerRequest}; +use crate::sst::file::{FileMeta, SHARED_LEVEL_SLOT}; + +/// A query-visible input snapshot. Callers may select a subset of `inputs` for a job. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TableCompactionSnapshot { + pub metadata: RegionMetadataRef, + pub options: serde_json::Value, + pub inputs: Vec, +} + +/// Transient publication preconditions, never stored in a manifest. +#[derive(Debug)] +pub(crate) struct PublicationContext { + pub metadata: RegionMetadataRef, + pub options: RegionOptions, +} + +/// A result for this publication attempt, not a durable task receipt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PublicationOutcome { + Applied, + /// The captured inputs/schema/options no longer match. Re-snapshot and replan. + StaleInputs, +} + +impl MitoEngine { + pub fn table_compaction_snapshot( + &self, + region_id: RegionId, + ) -> Result { + let region = self + .find_region(region_id) + .context(RegionNotFoundSnafu { region_id })?; + ensure!( + region.state() == RegionRoleState::Leader(RegionLeaderState::Writable), + RegionBusySnafu { region_id } + ); + let current = region.version_control.current(); + Ok(TableCompactionSnapshot { + metadata: current.version.metadata.clone(), + options: serde_json::to_value(¤t.version.options).context(SerdeJsonSnafu)?, + inputs: current.version.ssts.levels()[SHARED_LEVEL_SLOT] + .files() + .map(|file| file.meta_ref().clone()) + .collect(), + }) + } + + /// Publishes one region independently, using compaction rather than import sequences. + /// + /// Duplicate submissions are allowed. A stale outcome does NOT prove these + /// outputs were never published (an earlier ACK may have been lost). Never + /// blindly delete outputs on stale/error: keep their protection until recovery + /// or manifest-aware GC determines liveness. No input registration is performed. + /// Input admission must be complete/quiescent; a compaction retry must not replay + /// imports. The caller must produce a logically equivalent replacement under this snapshot. + pub async fn publish_table_compaction( + &self, + region_id: RegionId, + snapshot: TableCompactionSnapshot, + outputs: Vec, + ) -> Result { + ensure!( + snapshot.metadata.region_id == region_id && !snapshot.inputs.is_empty(), + InvalidRequestSnafu { + region_id, + reason: "Publication requires this region's nonempty input snapshot" + } + ); + // The public snapshot keeps JSON options; parse them once here so the + // worker compares typed options and reads typed flags without reparsing. + let options = serde_json::from_value(snapshot.options).context(SerdeJsonSnafu)?; + let edit = RegionEdit { + files_to_remove: snapshot.inputs, + files_to_add: outputs, + timestamp_ms: Some(chrono::Utc::now().timestamp_millis()), + ..Default::default() + }; + let (tx, rx) = oneshot::channel(); + let mut request = RegionEditRequest::new(region_id, edit, false, tx); + request.kind = RegionEditKind::Compaction(Box::new(PublicationContext { + metadata: snapshot.metadata, + options, + })); + self.inner + .workers + .submit_to_worker(region_id, WorkerRequest::EditRegion(request)) + .await?; + match rx.await.context(RecvSnafu)? { + Ok(()) => Ok(PublicationOutcome::Applied), + Err(Error::EditRegion { source, .. }) + if matches!(source.as_ref(), Error::StaleCompactionExecution { .. }) => + { + Ok(PublicationOutcome::StaleInputs) + } + Err(error) => Err(error), + } + } +} diff --git a/src/mito2/src/engine/table_compaction/output.rs b/src/mito2/src/engine/table_compaction/output.rs new file mode 100644 index 00000000000..8f85123439b --- /dev/null +++ b/src/mito2/src/engine/table_compaction/output.rs @@ -0,0 +1,207 @@ +// Copyright 2023-2026 GrepTime Inc. +// +// This file is part of the GreptimeDB Enterprise Edition and is licensed under +// the GreptimeDB Enterprise License. You may not use this file except in +// compliance with that license. A copy of the license is available at the root +// of this repository in the file LICENSE-ENTERPRISE. +// +// Unless required by applicable law or agreed to in writing, this software is +// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// either express or implied. + +use std::sync::Arc; + +use parquet::file::metadata::ParquetMetaData; +use parquet::file::statistics::Statistics; +use snafu::{OptionExt, ResultExt, ensure}; +use store_api::metadata::RegionMetadataRef; + +use crate::access_layer::AccessLayer; +use crate::cache::CachedSstMeta; +use crate::engine::region_hook::VerifiedSstFileInfo; +use crate::error::{InvalidRequestSnafu, OpenDalSnafu, Result}; +use crate::region::MitoRegionRef; +use crate::sst::file::FileMeta; +use crate::sst::location; +use crate::sst::parquet::metadata::{MetadataLoader, extract_primary_key_range}; + +/// Verifies every output, then notifies the region hook once if one is registered. +/// +/// Without a hook no footer is needed after its own verification, so each one is +/// dropped before the next output is read. With a hook every footer is kept until +/// all outputs verify, because the hook observes them in one call; footers are then +/// released when this returns, before the caller takes the manifest lock. A failed +/// verification notifies nothing. +pub(crate) async fn verify_and_notify( + region: &MitoRegionRef, + metadata: &RegionMetadataRef, + outputs: &[FileMeta], +) -> Result<()> { + let Some(hook) = region.manifest_ctx.hook() else { + for file in outputs { + verify_file(®ion.access_layer, metadata, file).await?; + } + return Ok(()); + }; + + let mut footers = Vec::with_capacity(outputs.len()); + for file in outputs { + footers.push(verify_file(®ion.access_layer, metadata, file).await?); + } + let verified = outputs + .iter() + .zip(&footers) + .map(|(file_meta, footer)| VerifiedSstFileInfo { file_meta, footer }) + .collect::>(); + hook.on_sst_files_verified(region.region_id, metadata, &verified) + .await; + Ok(()) +} + +async fn verify_file( + access: &AccessLayer, + metadata: &RegionMetadataRef, + file: &FileMeta, +) -> Result> { + let region_id = metadata.region_id; + let path = location::sst_file_path(access.table_dir(), file.file_id(), access.path_type()); + let size = access + .object_store() + .stat(&path) + .await + .context(OpenDalSnafu)? + .content_length(); + ensure!( + size == file.file_size, + InvalidRequestSnafu { + region_id, + reason: "Output SST size mismatch" + } + ); + let footer = MetadataLoader::new(access.object_store().clone(), &path, size) + .load(&mut Default::default()) + .await?; + let cached = CachedSstMeta::try_new_with_region_metadata(&path, footer, None)?; + ensure!( + cached.region_metadata() == *metadata, + InvalidRequestSnafu { + region_id, + reason: "Output footer schema or partition mismatch" + } + ); + let footer = cached.parquet_metadata(); + verify_statistics(&footer, metadata, file)?; + if file.index_file_size > 0 { + let path = + location::index_file_path(access.table_dir(), file.index_id(), access.path_type()); + let index_size = access + .object_store() + .stat(&path) + .await + .context(OpenDalSnafu)? + .content_length(); + ensure!( + index_size == file.index_file_size, + InvalidRequestSnafu { + region_id, + reason: "Output index size mismatch" + } + ); + } else { + ensure!( + file.available_indexes.is_empty() && file.indexes.is_empty(), + InvalidRequestSnafu { + region_id, + reason: "Output advertises indexes without an index object", + } + ); + } + Ok(footer) +} + +fn verify_statistics( + footer: &ParquetMetaData, + metadata: &RegionMetadataRef, + file: &FileMeta, +) -> Result<()> { + let max_uncompressed = footer + .row_groups() + .iter() + .map(|group| { + group + .columns() + .iter() + .map(|column| column.uncompressed_size() as u64) + .sum::() + }) + .max() + .unwrap_or(0); + let pk_range = extract_primary_key_range(footer, metadata); + ensure!( + footer.file_metadata().num_rows() > 0 + && footer.file_metadata().num_rows() as u64 == file.num_rows + && footer.num_row_groups() as u64 == file.num_row_groups + && max_uncompressed == file.max_row_group_uncompressed_size + && pk_range.as_ref().map(|range| &range.0) == file.primary_key_min.as_ref() + && pk_range.as_ref().map(|range| &range.1) == file.primary_key_max.as_ref() + // `num_series` is the writer's caller-reported estimate derived from + // timestamp boundaries, not a footer statistic, so it only bounds the + // count against rows instead of being verified against the footer. + && file.num_series <= file.num_rows, + InvalidRequestSnafu { + region_id: metadata.region_id, + reason: "Output statistics differ from its footer" + } + ); + verify_time_range(footer, metadata, file) +} + +fn verify_time_range( + footer: &ParquetMetaData, + metadata: &RegionMetadataRef, + file: &FileMeta, +) -> Result<()> { + let region_id = metadata.region_id; + let column_name = &metadata.time_index_column().column_schema.name; + let index = footer + .file_metadata() + .schema_descr() + .columns() + .iter() + .position(|column| column.path().parts().len() == 1 && column.name() == column_name) + .context(InvalidRequestSnafu { + region_id, + reason: "Output has no timestamp column", + })?; + let mut minimum = i64::MAX; + let mut maximum = i64::MIN; + for group in footer.row_groups() { + let Some(Statistics::Int64(stats)) = group.column(index).statistics() else { + return InvalidRequestSnafu { + region_id, + reason: "Output timestamp statistics missing", + } + .fail(); + }; + minimum = minimum.min(*stats.min_opt().context(InvalidRequestSnafu { + region_id, + reason: "Output timestamp minimum missing", + })?); + maximum = maximum.max(*stats.max_opt().context(InvalidRequestSnafu { + region_id, + reason: "Output timestamp maximum missing", + })?); + } + let unit = metadata.time_index_type().unit(); + ensure!( + file.time_range.0.value() == minimum + && file.time_range.1.value() == maximum + && file.time_range.0.unit() == unit + && file.time_range.1.unit() == unit, + InvalidRequestSnafu { + region_id, + reason: "Output timestamp range mismatch" + } + ); + Ok(()) +} diff --git a/src/mito2/src/engine/table_compaction/tests.rs b/src/mito2/src/engine/table_compaction/tests.rs new file mode 100644 index 00000000000..144c586a33e --- /dev/null +++ b/src/mito2/src/engine/table_compaction/tests.rs @@ -0,0 +1,1086 @@ +// Copyright 2023-2026 GrepTime Inc. +// +// This file is part of the GreptimeDB Enterprise Edition and is licensed under +// the GreptimeDB Enterprise License. You may not use this file except in +// compliance with that license. A copy of the license is available at the root +// of this repository in the file LICENSE-ENTERPRISE. +// +// Unless required by applicable law or agreed to in writing, this software is +// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// either express or implied. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Weak}; + +use api::v1::Rows; +use bytes::Bytes; +use common_base::Plugins; +use common_recordbatch::RecordBatches; +use common_time::Timestamp; +use common_time::timestamp::TimeUnit; +use parquet::file::metadata::ParquetMetaData; +use store_api::region_engine::RegionEngine; +use store_api::region_request::{RegionRequest, RegionTruncateRequest}; +use store_api::storage::{FileId, RegionId}; + +use super::{PublicationOutcome, TableCompactionSnapshot}; +use crate::config::MitoConfig; +use crate::engine::MitoEngine; +use crate::engine::region_hook::{RegionHook, RegionHookRef, VerifiedSstFileInfo}; +use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList}; +use crate::region::MitoRegionRef; +use crate::sst::file::{ColumnIndexMetadata, FileMeta, IndexType, LEVEL_SHARED, SHARED_LEVEL_SLOT}; +use crate::sst::location; +use crate::test_util::{ + CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows, reopen_region, rows_schema, +}; + +fn config() -> MitoConfig { + MitoConfig { + schedule_compaction_after_edit: false, + manifest_checkpoint_distance: 0, + ..Default::default() + } +} + +async fn copy_sst(region: &MitoRegionRef, source: &FileMeta, level: u8) -> FileMeta { + let mut output = source.clone(); + output.file_id = FileId::random(); + output.level = level; + let access = ®ion.access_layer; + let path = |file: &FileMeta| { + location::sst_file_path(access.table_dir(), file.file_id(), access.path_type()) + }; + access + .object_store() + .copy(&path(source), &path(&output)) + .await + .unwrap(); + if source.index_file_size > 0 { + let path = |file: &FileMeta| { + location::index_file_path(access.table_dir(), file.index_id(), access.path_type()) + }; + access + .object_store() + .copy(&path(source), &path(&output)) + .await + .unwrap(); + } + output +} + +/// Input admission is deliberately separate from the compaction API. +async fn seed(engine: &MitoEngine, region_id: RegionId) -> (TableCompactionSnapshot, FileMeta) { + let (snapshot, outputs) = seed_shared_inputs(engine, region_id, &[(0, 3)]).await; + let output = outputs.into_iter().next().unwrap(); + (snapshot, output) +} + +/// Writes each row range as a flushed SST, promotes the flushed files to shared +/// level, and returns one region-local output per shared input under the snapshot. +async fn seed_shared_inputs( + engine: &MitoEngine, + region_id: RegionId, + row_ranges: &[(usize, usize)], +) -> (TableCompactionSnapshot, Vec) { + let create = CreateRequestBuilder::new().build(); + engine + .handle_request(region_id, RegionRequest::Create(create.clone())) + .await + .unwrap(); + for &(start, end) in row_ranges { + put_rows( + engine, + region_id, + Rows { + schema: rows_schema(&create), + rows: build_rows(start, end), + }, + ) + .await; + flush_region(engine, region_id, None).await; + } + let region = engine.get_region(region_id).unwrap(); + let originals = region.version().ssts.levels()[0] + .files() + .map(|file| file.meta_ref().clone()) + .collect::>(); + assert_eq!(row_ranges.len(), originals.len()); + let mut shared = Vec::with_capacity(originals.len()); + for original in &originals { + shared.push(copy_sst(®ion, original, LEVEL_SHARED).await); + } + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: shared, + files_to_remove: originals, + ..Default::default() + }, + ) + .await + .unwrap(); + let snapshot = engine.table_compaction_snapshot(region_id).unwrap(); + assert_eq!(row_ranges.len(), snapshot.inputs.len()); + let mut outputs = Vec::with_capacity(snapshot.inputs.len()); + for input in &snapshot.inputs { + outputs.push(copy_sst(®ion, input, 0).await); + } + (snapshot, outputs) +} + +async fn row_count(engine: &MitoEngine, region_id: RegionId) -> usize { + RecordBatches::try_collect( + engine + .scan_to_stream(region_id, Default::default()) + .await + .unwrap(), + ) + .await + .unwrap() + .iter() + .map(|batch| batch.num_rows()) + .sum() +} + +#[tokio::test] +async fn test_duplicate_publication_and_later_replacement_do_not_readmit_inputs() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let region_id = RegionId::new(1, 1); + let (snapshot, output) = seed(&engine, region_id).await; + let region = engine.get_region(region_id).unwrap(); + let sequence = region.version_control.committed_sequence(); + let (first, second) = tokio::join!( + engine.publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]), + engine.publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]) + ); + let outcomes = [first.unwrap(), second.unwrap()]; + assert_eq!( + 1, + outcomes + .iter() + .filter(|outcome| **outcome == PublicationOutcome::Applied) + .count() + ); + assert_eq!( + 1, + outcomes + .iter() + .filter(|outcome| **outcome == PublicationOutcome::StaleInputs) + .count() + ); + assert_eq!(sequence, region.version_control.committed_sequence()); + assert_eq!(sequence, region.version_control.current().last_sequence); + assert_eq!(3, row_count(&engine, region_id).await); + let manifest = region.manifest_ctx.manifest().await; + let encoded = serde_json::to_value(manifest.as_ref()).unwrap(); + assert!(encoded.get("table_compaction").is_none() && encoded.get("extensions").is_none()); + + // Publish a later ordinary compaction, then remove the old output object. + // A late retry must reject its obsolete inputs before trying to verify C. + let replacement = copy_sst(®ion, &output, 0).await; + let edit = RegionEdit { + files_to_remove: vec![output.clone()], + files_to_add: vec![replacement.clone()], + ..Default::default() + }; + region + .manifest_ctx + .update_manifest_for_compaction(RegionMetaActionList::with_action(RegionMetaAction::Edit( + edit.clone(), + ))) + .await + .unwrap(); + region + .version_control + .apply_edit(Some(edit), &[], region.file_purger.clone()); + let path = location::sst_file_path( + region.access_layer.table_dir(), + output.file_id(), + region.path_type(), + ); + region + .access_layer + .object_store() + .delete(&path) + .await + .unwrap(); + assert_eq!( + PublicationOutcome::StaleInputs, + engine + .publish_table_compaction(region_id, snapshot, vec![output.clone()]) + .await + .unwrap() + ); + let manifest = region.manifest_ctx.manifest().await; + assert_eq!(1, manifest.files.len()); + assert!(manifest.files.contains_key(&replacement.file_id)); + assert!(!manifest.files.contains_key(&output.file_id)); + reopen_region(&engine, region_id, "test".into(), true, Default::default()).await; + assert_eq!(3, row_count(&engine, region_id).await); +} + +#[tokio::test] +async fn test_partial_success_can_retry_both_regions_without_duplicate_files() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let a = RegionId::new(1, 1); + let b = RegionId::new(1, 2); + let (snapshot_a, output_a) = seed(&engine, a).await; + let (snapshot_b, output_b) = seed(&engine, b).await; + let invalid = FileMeta { + file_size: output_b.file_size + 1, + ..output_b.clone() + }; + let (first_a, first_b) = tokio::join!( + engine.publish_table_compaction(a, snapshot_a.clone(), vec![output_a.clone()]), + engine.publish_table_compaction(b, snapshot_b.clone(), vec![invalid]) + ); + assert_eq!(PublicationOutcome::Applied, first_a.unwrap()); + assert!(first_b.is_err()); + assert_eq!( + snapshot_b.inputs, + engine.table_compaction_snapshot(b).unwrap().inputs + ); + let (retry_a, retry_b) = tokio::join!( + engine.publish_table_compaction(a, snapshot_a, vec![output_a.clone()]), + engine.publish_table_compaction(b, snapshot_b, vec![output_b.clone()]) + ); + assert_eq!(PublicationOutcome::StaleInputs, retry_a.unwrap()); + assert_eq!(PublicationOutcome::Applied, retry_b.unwrap()); + for (id, output) in [(a, output_a), (b, output_b)] { + let region = engine.get_region(id).unwrap(); + let manifest = region.manifest_ctx.manifest().await; + assert_eq!(1, manifest.files.len()); + assert_eq!(&output, &manifest.files[&output.file_id]); + assert_eq!(3, row_count(&engine, id).await); + } +} + +#[tokio::test] +async fn test_invalid_results_preserve_inputs_and_reopen_can_replan() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let region_id = RegionId::new(1, 1); + let (snapshot, output) = seed(&engine, region_id).await; + let region = engine.get_region(region_id).unwrap(); + let version = region.manifest_ctx.manifest_version().await; + // Snapshot-level and footer-derived mutations must all fail output admission + // with the specific reason, leaving the manifest, inputs and rows untouched. + #[derive(Clone, Copy)] + enum ExpectedError { + InvalidRequest(&'static str), + OpenDal, + } + let statistics_mismatch = + ExpectedError::InvalidRequest("Output statistics differ from its footer"); + let invalid_output = ExpectedError::InvalidRequest("Invalid region-local compaction output"); + let timestamp_mismatch = ExpectedError::InvalidRequest("Output timestamp range mismatch"); + let cases = [ + ( + FileMeta { + file_size: output.file_size + 1, + ..output.clone() + }, + ExpectedError::InvalidRequest("Output SST size mismatch"), + ), + ( + FileMeta { + num_rows: output.num_rows + 1, + ..output.clone() + }, + statistics_mismatch, + ), + ( + FileMeta { + num_row_groups: output.num_row_groups + 1, + ..output.clone() + }, + statistics_mismatch, + ), + ( + FileMeta { + max_row_group_uncompressed_size: output.max_row_group_uncompressed_size + 1, + ..output.clone() + }, + statistics_mismatch, + ), + ( + FileMeta { + primary_key_min: Some(Bytes::from_static(b"not-the-footer-minimum")), + ..output.clone() + }, + statistics_mismatch, + ), + ( + FileMeta { + primary_key_max: Some(Bytes::from_static(b"not-the-footer-maximum")), + ..output.clone() + }, + statistics_mismatch, + ), + ( + FileMeta { + time_range: ( + Timestamp::new(output.time_range.0.value() + 1, output.time_range.0.unit()), + output.time_range.1, + ), + ..output.clone() + }, + timestamp_mismatch, + ), + ( + FileMeta { + time_range: ( + output.time_range.0, + Timestamp::new(output.time_range.1.value(), TimeUnit::Second), + ), + ..output.clone() + }, + timestamp_mismatch, + ), + ( + FileMeta { + file_id: FileId::random(), + ..output.clone() + }, + ExpectedError::OpenDal, + ), + ( + FileMeta { + sequence: None, + ..output.clone() + }, + invalid_output, + ), + ( + FileMeta { + available_indexes: smallvec::smallvec![IndexType::InvertedIndex], + ..output.clone() + }, + ExpectedError::InvalidRequest("Output advertises indexes without an index object"), + ), + ( + FileMeta { + indexes: vec![ColumnIndexMetadata { + column_id: 0, + created_indexes: smallvec::smallvec![IndexType::InvertedIndex], + ..Default::default() + }], + ..output.clone() + }, + ExpectedError::InvalidRequest("Output advertises indexes without an index object"), + ), + ( + FileMeta { + file_id: snapshot.inputs[0].file_id, + ..output.clone() + }, + invalid_output, + ), + ]; + for (invalid, expected) in cases { + let error = engine + .publish_table_compaction(region_id, snapshot.clone(), vec![invalid]) + .await + .unwrap_err(); + let source = match error { + crate::error::Error::EditRegion { source, .. } => source, + other => panic!("unexpected error: {other}"), + }; + match expected { + ExpectedError::InvalidRequest(reason) => assert!( + matches!(source.as_ref(), crate::error::Error::InvalidRequest { reason: actual, .. } if actual == reason), + "unexpected error: {source}" + ), + ExpectedError::OpenDal => assert!( + matches!(source.as_ref(), crate::error::Error::OpenDal { .. }), + "unexpected error: {source}" + ), + } + assert_eq!(version, region.manifest_ctx.manifest_version().await); + assert_eq!( + snapshot.inputs, + engine.table_compaction_snapshot(region_id).unwrap().inputs + ); + assert_eq!(3, row_count(&engine, region_id).await); + } + // A real footer written for another region's metadata must reach the footer + // check; the stale-input shortcut must not mask it. + let foreign_region_id = RegionId::new(1, 2); + let (_, foreign_output) = seed(&engine, foreign_region_id).await; + let foreign_region = engine.get_region(foreign_region_id).unwrap(); + let mut foreign = foreign_output; + assert_eq!(0, foreign.index_file_size); + let foreign_path = location::sst_file_path( + foreign_region.access_layer.table_dir(), + foreign.file_id(), + foreign_region.access_layer.path_type(), + ); + foreign.file_id = FileId::random(); + foreign.region_id = region_id; + foreign.sequence = output.sequence; + let target_path = location::sst_file_path( + region.access_layer.table_dir(), + foreign.file_id(), + region.access_layer.path_type(), + ); + foreign_region + .access_layer + .object_store() + .copy(&foreign_path, &target_path) + .await + .unwrap(); + let error = engine + .publish_table_compaction(region_id, snapshot.clone(), vec![foreign]) + .await + .unwrap_err(); + let source = match error { + crate::error::Error::EditRegion { source, .. } => source, + other => panic!("unexpected error: {other}"), + }; + assert!( + matches!(source.as_ref(), crate::error::Error::InvalidRequest { reason, .. } + if reason == "Output footer schema or partition mismatch"), + "unexpected error: {source}" + ); + assert_eq!(version, region.manifest_ctx.manifest_version().await); + assert_eq!( + snapshot.inputs, + engine.table_compaction_snapshot(region_id).unwrap().inputs + ); + assert_eq!(3, row_count(&engine, region_id).await); + let mut stale_input = snapshot.clone(); + stale_input.inputs[0].index_version += 1; + assert_eq!( + PublicationOutcome::StaleInputs, + engine + .publish_table_compaction(region_id, stale_input, vec![output.clone()]) + .await + .unwrap() + ); + let mut duplicate = snapshot.clone(); + duplicate.inputs.push(snapshot.inputs[0].clone()); + assert!( + engine + .publish_table_compaction(region_id, duplicate, vec![output.clone()]) + .await + .is_err() + ); + let mut malformed = snapshot.clone(); + malformed.options = serde_json::json!({ "append_mode": "not-a-bool" }); + let error = engine + .publish_table_compaction(region_id, malformed, vec![output.clone()]) + .await + .unwrap_err(); + assert!(matches!(error, crate::error::Error::SerdeJson { .. })); + assert_eq!(version, region.manifest_ctx.manifest_version().await); + assert_eq!( + snapshot.inputs, + engine.table_compaction_snapshot(region_id).unwrap().inputs + ); + let mut stale = snapshot; + stale.options["append_mode"] = serde_json::json!(true); + assert_eq!( + PublicationOutcome::StaleInputs, + engine + .publish_table_compaction(region_id, stale, vec![output.clone()]) + .await + .unwrap() + ); + assert_eq!(version, region.manifest_ctx.manifest_version().await); + reopen_region(&engine, region_id, "test".into(), true, Default::default()).await; + // V1 refreshes the snapshot after restart instead of resuming a Prepared task. + // The public snapshot contract is JSON, so a serde round trip must still publish. + let fresh = engine.table_compaction_snapshot(region_id).unwrap(); + let fresh: TableCompactionSnapshot = + serde_json::from_value(serde_json::to_value(&fresh).unwrap()).unwrap(); + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(region_id, fresh, vec![output]) + .await + .unwrap() + ); + assert_eq!(3, row_count(&engine, region_id).await); +} + +/// An output carrying a real index object written by flush is accepted. +#[tokio::test] +async fn test_indexed_output_with_real_index_object_publishes() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let region_id = RegionId::new(1, 1); + let create = CreateRequestBuilder::new().build_with_index(); + engine + .handle_request(region_id, RegionRequest::Create(create.clone())) + .await + .unwrap(); + put_rows( + &engine, + region_id, + Rows { + schema: rows_schema(&create), + rows: build_rows(0, 3), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + let region = engine.get_region(region_id).unwrap(); + let original = region.version().ssts.levels()[0] + .files() + .next() + .unwrap() + .meta_ref() + .clone(); + assert!(original.index_file_size > 0); + assert!(!original.available_indexes.is_empty()); + assert!(!original.indexes.is_empty()); + let shared = copy_sst(®ion, &original, LEVEL_SHARED).await; + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![shared], + files_to_remove: vec![original], + ..Default::default() + }, + ) + .await + .unwrap(); + let snapshot = engine.table_compaction_snapshot(region_id).unwrap(); + let output = copy_sst(®ion, &snapshot.inputs[0], 0).await; + assert!(output.index_file_size > 0); + assert!(!output.available_indexes.is_empty()); + assert!(!output.indexes.is_empty()); + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(region_id, snapshot, vec![output.clone()]) + .await + .unwrap() + ); + let manifest = region.manifest_ctx.manifest().await; + assert_eq!(Some(&output), manifest.files.get(&output.file_id)); + assert_eq!(3, row_count(&engine, region_id).await); +} + +/// A preserve-row-sequence region trusts output markers only when the typed +/// snapshot options and the admitted inputs both carry the marker. +#[tokio::test] +async fn test_preserve_row_sequence_option_drives_output_admission() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let region_id = RegionId::new(1, 1); + let create = CreateRequestBuilder::new() + .insert_option("append_mode", "true") + .insert_option("preserve_row_sequence", "true") + .build(); + engine + .handle_request(region_id, RegionRequest::Create(create.clone())) + .await + .unwrap(); + put_rows( + &engine, + region_id, + Rows { + schema: rows_schema(&create), + rows: build_rows(0, 3), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + let region = engine.get_region(region_id).unwrap(); + let original = region.version().ssts.levels()[0] + .files() + .next() + .unwrap() + .meta_ref() + .clone(); + assert!(original.preserve_row_sequence); + // A generic import clears the trust marker, so install the admitted shared + // input directly: this is the shape table compaction receives after admission. + let shared = copy_sst(®ion, &original, LEVEL_SHARED).await; + let edit = RegionEdit { + files_to_add: vec![shared], + files_to_remove: vec![original], + ..Default::default() + }; + region + .manifest_ctx + .update_manifest_for_compaction(RegionMetaActionList::with_action(RegionMetaAction::Edit( + edit.clone(), + ))) + .await + .unwrap(); + region + .version_control + .apply_edit(Some(edit), &[], region.file_purger.clone()); + let snapshot = engine.table_compaction_snapshot(region_id).unwrap(); + assert_eq!( + Some(true), + snapshot.options["preserve_row_sequence"].as_bool() + ); + let output = copy_sst(®ion, &snapshot.inputs[0], 0).await; + assert!(output.preserve_row_sequence); + let untrusted = FileMeta { + preserve_row_sequence: false, + ..output.clone() + }; + let version = region.manifest_ctx.manifest_version().await; + let error = engine + .publish_table_compaction(region_id, snapshot.clone(), vec![untrusted]) + .await + .unwrap_err(); + assert!(matches!( + error, + crate::error::Error::EditRegion { source, .. } + if matches!(source.as_ref(), crate::error::Error::InvalidRequest { reason, .. } + if reason == "Invalid region-local compaction output") + )); + assert_eq!(version, region.manifest_ctx.manifest_version().await); + assert_eq!( + snapshot.inputs, + engine.table_compaction_snapshot(region_id).unwrap().inputs + ); + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(region_id, snapshot, vec![output.clone()]) + .await + .unwrap() + ); + let manifest = region.manifest_ctx.manifest().await; + assert_eq!(Some(&output), manifest.files.get(&output.file_id)); + assert_eq!(3, row_count(&engine, region_id).await); +} + +#[tokio::test] +async fn test_empty_target_replacement_preserves_other_shared_reference() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let source = RegionId::new(1, 1); + let target = RegionId::new(1, 2); + let (source_snapshot, _) = seed(&engine, source).await; + let expr = + partition::expr::col("tag_0").eq(datatypes::value::Value::String("not-in-source".into())); + let create = CreateRequestBuilder::new() + .partition_expr_json(Some(expr.as_json_str().unwrap())) + .build(); + engine + .handle_request(target, RegionRequest::Create(create)) + .await + .unwrap(); + let copy = store_api::region_engine::MitoCopyRegionFromRequest { + source_region_id: source, + parallelism: 1, + }; + engine.copy_region_from(target, copy.clone()).await.unwrap(); + engine.copy_region_from(target, copy).await.unwrap(); + let snapshot = engine.table_compaction_snapshot(target).unwrap(); + assert_eq!(1, snapshot.inputs.len()); + assert_eq!( + source_snapshot.inputs[0].file_id(), + snapshot.inputs[0].file_id() + ); + let region = engine.get_region(target).unwrap(); + assert_eq!(1, region.version_control.current().last_sequence); + assert_eq!(0, row_count(&engine, target).await); + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(target, snapshot.clone(), vec![]) + .await + .unwrap() + ); + assert_eq!( + PublicationOutcome::StaleInputs, + engine + .publish_table_compaction(target, snapshot, vec![]) + .await + .unwrap() + ); + assert_eq!(1, region.version_control.current().last_sequence); + assert_eq!(0, row_count(&engine, target).await); + assert_eq!(3, row_count(&engine, source).await); +} + +#[tokio::test] +async fn test_staging_rejects_publication_without_changing_files() { + use store_api::region_request::{EnterStagingRequest, StagingPartitionDirective}; + let mut env = TestEnv::new().await; + let engine = env.create_engine(config()).await; + let region_id = RegionId::new(1, 1); + let (snapshot, output) = seed(&engine, region_id).await; + engine + .handle_request( + region_id, + RegionRequest::EnterStaging(EnterStagingRequest { + partition_directive: StagingPartitionDirective::RejectAllWrites, + }), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let version = region.manifest_ctx.manifest_version().await; + assert!( + engine + .publish_table_compaction(region_id, snapshot, vec![output]) + .await + .is_err() + ); + assert!(region.is_staging()); + assert_eq!(version, region.manifest_ctx.manifest_version().await); + assert_eq!( + 1, + region.version().ssts.levels()[SHARED_LEVEL_SLOT] + .files + .len() + ); +} + +#[rstest::rstest] +#[case::before_persist(false)] +#[case::lost_ack(true)] +#[tokio::test] +async fn test_uncertain_write_recovers_files_before_retry(#[case] persisted: bool) { + use object_store::layers::mock::{ + Buffer, Error, ErrorKind, Metadata, MockLayerBuilder, Result, oio, + }; + struct FailManifestWrite { + inner: oio::Writer, + pending: Vec, + armed: Arc, + persisted: bool, + } + impl oio::Write for FailManifestWrite { + async fn write(&mut self, bytes: Buffer) -> Result<()> { + // Buffer at the I/O boundary so the pre-persist case never depends + // on whether the backing filesystem supports aborting a writer. + self.pending.push(bytes); + Ok(()) + } + async fn close(&mut self) -> Result { + let fail = self.armed.swap(false, Ordering::SeqCst); + if fail && !self.persisted { + return Err(Error::new( + ErrorKind::Unexpected, + "injected failure before persistence", + )); + } + for bytes in self.pending.drain(..) { + self.inner.write(bytes).await?; + } + let metadata = self.inner.close().await?; + if fail { + Err(Error::new( + ErrorKind::Unexpected, + "lost manifest acknowledgement", + )) + } else { + Ok(metadata) + } + } + async fn abort(&mut self) -> Result<()> { + self.inner.abort().await + } + } + let armed = Arc::new(AtomicBool::new(false)); + let fault = armed.clone(); + let layer = MockLayerBuilder::default() + .writer_factory(Arc::new(move |path, _, inner| { + if path.contains("/manifest/") { + Box::new(FailManifestWrite { + inner, + pending: Vec::new(), + armed: fault.clone(), + persisted, + }) as oio::Writer + } else { + inner + } + })) + .build() + .unwrap(); + let mut env = TestEnv::new().await.with_mock_layer(layer); + let engine = env.create_engine(config()).await; + let region_id = RegionId::new(1, 1); + let (snapshot, output) = seed(&engine, region_id).await; + let access = engine.get_region(region_id).unwrap().access_layer.clone(); + armed.store(true, Ordering::SeqCst); + assert!( + engine + .publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]) + .await + .is_err() + ); + assert!(!armed.load(Ordering::SeqCst)); + assert!(engine.get_region(region_id).is_none()); + let path = location::sst_file_path(access.table_dir(), output.file_id(), access.path_type()); + assert!(access.object_store().exists(&path).await.unwrap()); + reopen_region(&engine, region_id, "test".into(), true, Default::default()).await; + let fresh = engine.table_compaction_snapshot(region_id).unwrap(); + assert_eq!(!persisted, !fresh.inputs.is_empty()); + if persisted { + assert_eq!( + PublicationOutcome::StaleInputs, + engine + .publish_table_compaction(region_id, snapshot, vec![output]) + .await + .unwrap() + ); + } else { + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(region_id, fresh, vec![output]) + .await + .unwrap() + ); + } + assert_eq!(3, row_count(&engine, region_id).await); +} + +#[derive(Debug)] +struct PublicationBarrier { + after_commit: bool, + armed: AtomicBool, + entered: tokio::sync::Notify, + resume: tokio::sync::Notify, +} + +impl PublicationBarrier { + async fn pause(&self) { + if self.armed.swap(false, Ordering::SeqCst) { + self.entered.notify_one(); + self.resume.notified().await; + } + } +} + +#[async_trait::async_trait] +impl RegionHook for PublicationBarrier { + async fn on_sst_files_verified( + &self, + _: RegionId, + _: &store_api::metadata::RegionMetadataRef, + _: &[VerifiedSstFileInfo<'_>], + ) { + if !self.after_commit { + self.pause().await; + } + } + async fn on_manifest_updated( + &self, + _: RegionId, + actions: &RegionMetaActionList, + _: store_api::ManifestVersion, + ) { + if self.after_commit && actions.actions.iter().any(|action| matches!(action, + RegionMetaAction::Edit(edit) if edit.files_to_remove.iter().any(|file| file.level == LEVEL_SHARED))) { + self.pause().await; + } + } +} + +#[rstest::rstest] +#[case::verification(false)] +#[case::completion(true)] +#[tokio::test] +async fn test_close_reopen_fences_old_publication(#[case] after_commit: bool) { + let hook = Arc::new(PublicationBarrier { + after_commit, + armed: AtomicBool::new(false), + entered: Default::default(), + resume: Default::default(), + }); + let plugins = Plugins::new(); + plugins.insert(hook.clone() as RegionHookRef); + let mut env = TestEnv::new().await; + let engine = env.create_engine_with_plugins(config(), plugins).await; + let region_id = RegionId::new(1, 1); + let (snapshot, output) = seed(&engine, region_id).await; + hook.armed.store(true, Ordering::SeqCst); + let (late, ()) = tokio::time::timeout(std::time::Duration::from_secs(10), async { + tokio::join!( + engine.publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]), + async { + hook.entered.notified().await; + reopen_region(&engine, region_id, "test".into(), true, Default::default()).await; + engine + .handle_request( + region_id, + RegionRequest::Truncate(RegionTruncateRequest::All), + ) + .await + .unwrap(); + hook.resume.notify_one(); + } + ) + }) + .await + .unwrap(); + assert!(late.is_err()); + let region = engine.get_region(region_id).unwrap(); + assert!(region.manifest_ctx.manifest().await.files.is_empty()); + assert!( + region + .version() + .ssts + .levels() + .iter() + .all(|level| level.files.is_empty()) + ); + assert_eq!( + PublicationOutcome::StaleInputs, + engine + .publish_table_compaction(region_id, snapshot, vec![output]) + .await + .unwrap() + ); + assert_eq!(0, row_count(&engine, region_id).await); +} + +/// Records one notification per verification, keeping verified footers only as +/// weak references, and checks those references again when the publication's +/// manifest update is announced. `on_manifest_updated` runs after the commit, so +/// this catches footers retained across it; it does not claim the hook fires +/// before the commit. Nothing else in the test keeps the footers alive. +#[derive(Debug, Default)] +struct VerificationRecorder { + verified_files: AtomicUsize, + notifications: AtomicUsize, + manifest_updates: AtomicUsize, + released_by_commit: AtomicBool, + footers: std::sync::Mutex>>, +} + +#[async_trait::async_trait] +impl RegionHook for VerificationRecorder { + async fn on_sst_files_verified( + &self, + _: RegionId, + _: &store_api::metadata::RegionMetadataRef, + files: &[VerifiedSstFileInfo<'_>], + ) { + let mut footers = self.footers.lock().unwrap(); + footers.extend(files.iter().map(|file| Arc::downgrade(file.footer))); + self.verified_files.fetch_add(files.len(), Ordering::SeqCst); + self.notifications.fetch_add(1, Ordering::SeqCst); + } + + async fn on_manifest_updated( + &self, + _: RegionId, + actions: &RegionMetaActionList, + _: store_api::ManifestVersion, + ) { + let is_compaction = actions.actions.iter().any(|action| matches!(action, + RegionMetaAction::Edit(edit) if edit.files_to_remove.iter().any(|file| file.level == LEVEL_SHARED))); + if !is_compaction { + return; + } + let footers = self.footers.lock().unwrap(); + self.released_by_commit.store( + !footers.is_empty() && footers.iter().all(|footer| footer.upgrade().is_none()), + Ordering::SeqCst, + ); + self.manifest_updates.fetch_add(1, Ordering::SeqCst); + } +} + +#[rstest::rstest] +#[case::without_hook(false)] +#[case::with_hook(true)] +#[tokio::test] +async fn test_multiple_outputs_verify_notify_once_and_release_footers(#[case] with_hook: bool) { + let recorder = Arc::new(VerificationRecorder::default()); + let mut env = TestEnv::new().await; + let engine = if with_hook { + let plugins = Plugins::new(); + plugins.insert(recorder.clone() as RegionHookRef); + env.create_engine_with_plugins(config(), plugins).await + } else { + env.create_engine(config()).await + }; + let region_id = RegionId::new(1, 1); + let (snapshot, outputs) = seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)]).await; + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(region_id, snapshot, outputs.clone()) + .await + .unwrap() + ); + let expected_notifications = usize::from(with_hook); + assert_eq!( + expected_notifications * outputs.len(), + recorder.verified_files.load(Ordering::SeqCst) + ); + assert_eq!( + expected_notifications, + recorder.notifications.load(Ordering::SeqCst) + ); + if with_hook { + assert_eq!(1, recorder.manifest_updates.load(Ordering::SeqCst)); + assert!(recorder.released_by_commit.load(Ordering::SeqCst)); + assert!( + recorder + .footers + .lock() + .unwrap() + .iter() + .all(|footer| footer.upgrade().is_none()) + ); + } else { + assert_eq!(0, recorder.manifest_updates.load(Ordering::SeqCst)); + } + let region = engine.get_region(region_id).unwrap(); + let manifest = region.manifest_ctx.manifest().await; + assert_eq!(outputs.len(), manifest.files.len()); + for output in &outputs { + assert_eq!(Some(output), manifest.files.get(&output.file_id)); + } + assert_eq!(6, row_count(&engine, region_id).await); +} + +#[tokio::test] +async fn test_failed_verification_does_not_notify_hook() { + let recorder = Arc::new(VerificationRecorder::default()); + let plugins = Plugins::new(); + plugins.insert(recorder.clone() as RegionHookRef); + let mut env = TestEnv::new().await; + let engine = env.create_engine_with_plugins(config(), plugins).await; + let region_id = RegionId::new(1, 1); + let (snapshot, outputs) = seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)]).await; + let region = engine.get_region(region_id).unwrap(); + let version = region.manifest_ctx.manifest_version().await; + let invalid = FileMeta { + file_size: outputs[1].file_size + 1, + ..outputs[1].clone() + }; + let error = engine + .publish_table_compaction( + region_id, + snapshot.clone(), + vec![outputs[0].clone(), invalid], + ) + .await + .unwrap_err(); + assert!(matches!( + error, + crate::error::Error::EditRegion { source, .. } + if matches!(source.as_ref(), crate::error::Error::InvalidRequest { reason, .. } + if reason == "Output SST size mismatch") + )); + assert_eq!(0, recorder.verified_files.load(Ordering::SeqCst)); + assert_eq!(0, recorder.notifications.load(Ordering::SeqCst)); + assert_eq!(version, region.manifest_ctx.manifest_version().await); + assert_eq!( + snapshot.inputs, + engine.table_compaction_snapshot(region_id).unwrap().inputs + ); + assert_eq!(6, row_count(&engine, region_id).await); +} diff --git a/src/mito2/src/request.rs b/src/mito2/src/request.rs index 123133d4be0..d6777131b4f 100644 --- a/src/mito2/src/request.rs +++ b/src/mito2/src/request.rs @@ -1373,10 +1373,19 @@ impl Waiters { } } +/// Transient execution semantics; this is never serialized into the manifest. +#[derive(Debug)] +pub(crate) enum RegionEditKind { + Import, + #[cfg(feature = "enterprise")] + Compaction(Box), +} + /// Request to edit a region directly. #[derive(Debug)] pub(crate) struct RegionEditRequest { pub(crate) region_id: RegionId, + pub(crate) kind: RegionEditKind, pub(crate) edit: RegionEdit, /// Whether to preload SST files into the write cache. pub(crate) preload_sst_cache: bool, @@ -1398,6 +1407,7 @@ impl RegionEditRequest { region_id, edit, preload_sst_cache, + kind: RegionEditKind::Import, waiters: Waiters::one(waiter), staging_partition_expr: None, } diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index 79398a6d219..d8f5b0b3620 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -29,6 +29,8 @@ mod handle_manifest; mod handle_open; mod handle_rebuild_index; mod handle_remap; +#[cfg(feature = "enterprise")] +mod handle_table_compaction; mod handle_truncate; mod handle_write; diff --git a/src/mito2/src/worker/handle_manifest.rs b/src/mito2/src/worker/handle_manifest.rs index f1a575d4433..2a37f898f3c 100644 --- a/src/mito2/src/worker/handle_manifest.rs +++ b/src/mito2/src/worker/handle_manifest.rs @@ -45,8 +45,8 @@ use crate::region::version::VersionControlRef; use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState}; use crate::request::{ BackgroundNotify, BuildIndexRequest, DiscardUnflushedResult, OptionOutputTx, - RegionChangeResult, RegionEditRequest, RegionEditResult, RegionSyncRequest, TruncateResult, - WorkerRequest, WorkerRequestWithTime, + RegionChangeResult, RegionEditKind, RegionEditRequest, RegionEditResult, RegionSyncRequest, + TruncateResult, WorkerRequest, WorkerRequestWithTime, }; use crate::sst::index::IndexBuildType; use crate::sst::{file, location}; @@ -99,7 +99,11 @@ impl RegionEditQueue { } fn dequeue(&mut self) -> Option { - fn can_merge(edit: &RegionEdit) -> bool { + fn can_merge(request: &RegionEditRequest) -> bool { + if !matches!(request.kind, RegionEditKind::Import) { + return false; + } + let edit = &request.edit; // Only the `RegionEdit`: // 1. contains the "raw" (file without a sequence) files to add, // 2. and no `committed_sequence`, @@ -120,14 +124,11 @@ impl RegionEditQueue { } let mut merged = self.requests.pop_front()?; - if !can_merge(&merged.edit) { + if !can_merge(&merged) { return Some(merged); } - while let Some(request) = self - .requests - .pop_front_if(|request| can_merge(&request.edit)) - { + while let Some(request) = self.requests.pop_front_if(|request| can_merge(request)) { merged.edit.files_to_add.extend(request.edit.files_to_add); merged.waiters.merge(request.waiters); } @@ -365,12 +366,20 @@ impl RegionWorkerLoop { let RegionEditRequest { region_id: _, + kind, mut edit, waiters, preload_sst_cache, staging_partition_expr: _, } = request; - if let Err(error) = prepare_region_edit(®ion, &mut edit) { + #[cfg(feature = "enterprise")] + if matches!(kind, RegionEditKind::Compaction(_)) && region.is_staging() { + waiters.reply_with(|| RegionBusySnafu { region_id }.fail()); + return RegionEditDispatch::Rejected; + } + if matches!(kind, RegionEditKind::Import) + && let Err(error) = prepare_region_edit(®ion, &mut edit) + { let error = Arc::new(error); waiters.reply_with(|| Err(error.clone()).context(EditRegionSnafu { region_id })); return RegionEditDispatch::Rejected; @@ -399,15 +408,24 @@ impl RegionWorkerLoop { // Now the region is in editing state. // Updates manifest in background. common_runtime::spawn_global(async move { - let result = edit_region( - ®ion, - edit.clone(), - cache_manager, - listener, - is_staging, - preload_sst_cache, - ) - .await + let result = match kind { + RegionEditKind::Import => { + edit_region( + ®ion, + edit.clone(), + cache_manager, + listener, + is_staging, + preload_sst_cache, + ) + .await + } + #[cfg(feature = "enterprise")] + RegionEditKind::Compaction(context) => { + crate::worker::handle_table_compaction::publish(®ion, &context, edit.clone()) + .await + } + } .map_err(Arc::new); let notify = WorkerRequest::Background { region_id, diff --git a/src/mito2/src/worker/handle_table_compaction.rs b/src/mito2/src/worker/handle_table_compaction.rs new file mode 100644 index 00000000000..eddc81636e4 --- /dev/null +++ b/src/mito2/src/worker/handle_table_compaction.rs @@ -0,0 +1,151 @@ +// Copyright 2023-2026 GrepTime Inc. +// +// This file is part of the GreptimeDB Enterprise Edition and is licensed under +// the GreptimeDB Enterprise License. You may not use this file except in +// compliance with that license. A copy of the license is available at the root +// of this repository in the file LICENSE-ENTERPRISE. +// +// Unless required by applicable law or agreed to in writing, this software is +// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// either express or implied. + +//! At-least-once requests, conditional file publication, no durable task state. + +use std::collections::HashSet; + +use snafu::ensure; + +use crate::engine::table_compaction::{PublicationContext, output}; +use crate::error::{InvalidRequestSnafu, RegionBusySnafu, Result, StaleCompactionExecutionSnafu}; +use crate::manifest::action::{RegionEdit, RegionManifest, RegionMetaAction, RegionMetaActionList}; +use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState}; +use crate::sst::file::LEVEL_SHARED; + +pub(crate) async fn publish( + region: &MitoRegionRef, + context: &PublicationContext, + edit: RegionEdit, +) -> Result<()> { + let snapshot = region.manifest_ctx.manifest().await; + // An old result can name outputs already compacted away. Reject stale inputs + // before inspecting those objects; absence of an output is not a task receipt. + ensure!( + is_current(region, context, &edit, &snapshot), + StaleCompactionExecutionSnafu { + region_id: region.region_id + } + ); + validate_files(region, context, &edit, &snapshot)?; + output::verify_and_notify(region, &context.metadata, &edit.files_to_add).await?; + + let mut manager = region.manifest_ctx.manifest_manager.write().await; + ensure!( + matches!( + region.state(), + RegionRoleState::Leader(RegionLeaderState::Editing | RegionLeaderState::Downgrading) + ) && !manager.is_stopped(), + RegionBusySnafu { + region_id: region.region_id + } + ); + let manifest = manager.manifest(); + ensure!( + is_current(region, context, &edit, &manifest), + StaleCompactionExecutionSnafu { + region_id: region.region_id + } + ); + validate_files(region, context, &edit, &manifest)?; + let pending = match region + .manifest_ctx + .update_locked( + &mut manager, + RegionMetaActionList::with_action(RegionMetaAction::Edit(edit)), + false, + ) + .await + { + Ok(pending) => pending, + Err(error) => { + if error.may_have_persisted_manifest_update() { + // Do not accept another publication against a potentially stale + // in-memory file set. Completion removes this incarnation. + manager.stop().await; + } + return Err(error); + } + }; + drop(manager); + pending.fire().await; + Ok(()) +} + +fn is_current( + region: &MitoRegionRef, + context: &PublicationContext, + edit: &RegionEdit, + manifest: &RegionManifest, +) -> bool { + let current = region.version_control.current(); + context.metadata == manifest.metadata + && context.options == current.version.options + && !edit.files_to_remove.is_empty() + && edit + .files_to_remove + .iter() + .all(|file| manifest.files.get(&file.file_id) == Some(file)) +} + +fn validate_files( + region: &MitoRegionRef, + context: &PublicationContext, + edit: &RegionEdit, + manifest: &RegionManifest, +) -> Result<()> { + let region_id = region.region_id; + let mut inputs = HashSet::new(); + ensure!( + edit.files_to_remove + .iter() + .all(|file| file.level == LEVEL_SHARED + && file.region_id.table_id() == region_id.table_id() + && inputs.insert(file.file_id())), + InvalidRequestSnafu { + region_id, + reason: "Expected distinct, already-admitted shared inputs" + } + ); + let trusted = context.options.preserve_row_sequence + && edit.files_to_remove.iter().all(|file| { + if file.region_id == region_id { + file.preserve_row_sequence + } else { + file.sequence.is_some() + } + }); + let partition = + crate::region::parse_partition_expr(context.metadata.partition_expr.as_deref())?; + let sequence = edit + .files_to_remove + .iter() + .map(|file| file.sequence) + .collect::>>() + .and_then(|sequences| sequences.into_iter().max()); + let mut outputs = HashSet::new(); + ensure!( + edit.files_to_add + .iter() + .all(|file| file.region_id == region_id + && file.level == 0 + && outputs.insert(file.file_id) + && !manifest.files.contains_key(&file.file_id) + && file.partition_expr == partition + && file.preserve_row_sequence == trusted + && file.sequence == sequence), + InvalidRequestSnafu { + region_id, + reason: "Invalid region-local compaction output" + } + ); + Ok(()) +} diff --git a/tests/compatibility/manifest/table_compaction/README.md b/tests/compatibility/manifest/table_compaction/README.md index 7244199462e..4eb09a451d3 100644 --- a/tests/compatibility/manifest/table_compaction/README.md +++ b/tests/compatibility/manifest/table_compaction/README.md @@ -7,6 +7,18 @@ released binary. They preserve L0/L1 metadata, sequences and flush boundaries. V1 publishes compaction results using ordinary file edits. It adds no task IDs, phases, receipts, request epochs or extension-state fields to the manifest. Task retries may be submitted more than once; publication checks current inputs. +The Enterprise `publish_table_compaction` API consumes a query-visible input +snapshot and returns `Applied` or `StaleInputs`. A stale attempt must re-snapshot +and replan, never re-import its old inputs. Even stale/error outcomes must not +trigger blind output deletion: an earlier attempt may already have published +those objects. Callers retain output protection until recovery or GC resolves +liveness. + +Publication tests (including partial success, lost ACKs and reopened regions): + +```sh +cargo nextest run -p mito2 --features enterprise -E 'test(engine::table_compaction)' +``` ```sh cargo nextest run -p mito2 -E 'test(manifest::tests::compatibility)' From d1e5a2df8f866d66ae50b80d0ae8c82433a0ee3e Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Wed, 11 Nov 2026 06:44:06 +0000 Subject: [PATCH 07/63] fix(mito2): check the lease before manifest commits and reload regions after conflicts (#10311) * fix(mito2): check the lease before manifest commits and reload regions after conflicts In conditional manifest mode, refuse a commit whose Leader deadline has passed before its PUT, and fence a region whose commit hits a manifest version conflict, then reload it in the background and swap the new instance in. Signed-off-by: jeremyhi * fix(mito2): release the flush status when the WAL release after a flush fails handle_flush_finished failed the flush's waiters and returned when the WAL release after a committed flush failed, but left the flush registered in the flush scheduler, so every later flush of the region, and the reload of a fenced region, waited behind it forever. Handle the failure as a failed flush, which removes the registration and answers the pending requests. Signed-off-by: jeremyhi * test(mito2): cover staging saves after the deadline and a fence during catchup Add a listener hook before a catchup reopens the region, and test that a fence landing there makes the catchup answer RegionBusy without replacing the instance. Also test that entering staging after the Leader deadline saves no staging manifest. Signed-off-by: jeremyhi * docs(mito2): note that set_region_role does not check the reload mark Signed-off-by: jeremyhi --------- Signed-off-by: jeremyhi --- src/mito2/AGENTS.md | 4 + src/mito2/src/engine.rs | 3 +- src/mito2/src/engine/listener.rs | 6 + src/mito2/src/engine/object_store_wal_test.rs | 819 +++++++++++++++++- src/mito2/src/engine/sequence_test.rs | 50 +- src/mito2/src/error.rs | 5 + src/mito2/src/manifest/manager.rs | 5 + src/mito2/src/region.rs | 128 ++- src/mito2/src/request.rs | 21 +- src/mito2/src/test_util.rs | 13 +- src/mito2/src/worker.rs | 34 + src/mito2/src/worker/handle_apply_staging.rs | 7 +- src/mito2/src/worker/handle_catchup.rs | 105 ++- src/mito2/src/worker/handle_flush.rs | 8 +- src/mito2/src/worker/handle_manifest.rs | 13 +- src/mito2/src/worker/handle_reload.rs | 138 +++ 16 files changed, 1269 insertions(+), 90 deletions(-) create mode 100644 src/mito2/src/worker/handle_reload.rs diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index 9dc57b3f1fc..2aac0c1f2f8 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -116,6 +116,10 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes each manifest version has one fixed object name, created conditionally. A late create can succeed again once checkpoint cleanup frees the name, so a commit checks its result (`ensure_version_not_checkpointed` in `manifest/storage.rs`). +- In those regions a commit after the region's Leader deadline sends nothing, and a version + conflict fences the region (`ManifestContext::fence_for_reload`): no lease or catchup promotes + it until the worker swaps in an instance reloaded from the new manifest + (`worker/handle_reload.rs`). Never await a worker sender while holding a manifest guard. - Pending tails (`RegionManifest::pending_tails`) are WAL ranges a region still has to recover; the flushed entry id never prunes them. Opening a region replays its WAL after `RegionManifest::wal_replay_start`. The WAL releases at open and after diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index de9e796f8d1..d22cd3f9af2 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -1307,7 +1307,8 @@ impl EngineInner { scan_region } - /// Converts the [`RegionRole`]. + /// Converts the [`RegionRole`]. Unlike lease and catchup promotions, a conversion to Leader + /// does not check whether the region waits for a reload. fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<()> { let region = self.find_region(region_id)?; region.set_role(role); diff --git a/src/mito2/src/engine/listener.rs b/src/mito2/src/engine/listener.rs index 1aa6dbb3053..3ca23151339 100644 --- a/src/mito2/src/engine/listener.rs +++ b/src/mito2/src/engine/listener.rs @@ -31,6 +31,12 @@ pub trait EventListener: Send + Sync { /// Notifies the background opener after the worker acknowledges region registration. async fn on_region_open_registered(&self, _region_id: RegionId) {} + /// Notifies the listener before the worker replaces a fenced region with its reload. + async fn on_region_reload_swap(&self, _region_id: RegionId) {} + + /// Notifies the listener before a catchup reopens the region. + async fn on_catchup_reopen_begin(&self, _region_id: RegionId) {} + /// Notifies the listener that a region is flushed successfully. fn on_flush_success(&self, region_id: RegionId) { let _ = region_id; diff --git a/src/mito2/src/engine/object_store_wal_test.rs b/src/mito2/src/engine/object_store_wal_test.rs index 6a600958bf9..26b219f277c 100644 --- a/src/mito2/src/engine/object_store_wal_test.rs +++ b/src/mito2/src/engine/object_store_wal_test.rs @@ -16,39 +16,61 @@ use std::collections::HashMap; use std::sync::Arc; -use std::sync::atomic::Ordering; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use api::v1::region::{StrictWindow, compact_request}; use api::v1::{ColumnSchema, Rows}; +use async_trait::async_trait; +use common_base::Plugins; +use common_base::readable_size::ReadableSize; use common_datasource::compression::CompressionType; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; use common_recordbatch::RecordBatches; -use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION}; +use common_time::util::current_time_millis; +use common_wal::config::object_store::{AckMode, ObjectStoreWalConfig, STANDALONE_GENERATION}; use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions}; +use datatypes::value::Value; use futures::TryStreamExt; use log_store::ObjectStoreLogStore; use object_store::ObjectStore; +use object_store::layers::mock::MockLayerBuilder; +use object_store::services::Memory; +use partition::expr::col; use rstest::rstest; +use store_api::ManifestVersion; use store_api::logstore::LogStore; use store_api::logstore::provider::Provider; -use store_api::region_engine::{RegionEngine, RegionRole}; -use store_api::region_request::{ - PathType, RegionCleanUpRequest, RegionCloseRequest, RegionCompactRequest, RegionDropRequest, - RegionFlushRequest, RegionOpenRequest, RegionRequest, RegionTruncateRequest, +use store_api::region_engine::{ + RegionEngine, RegionRole, SetRegionRoleStateResponse, SettableRegionRoleState, }; -use store_api::storage::{RegionId, ScanRequest}; +use store_api::region_request::{ + EnterStagingRequest, PathType, RegionCatchupRequest, RegionCleanUpRequest, RegionCloseRequest, + RegionCompactRequest, RegionDropRequest, RegionFlushRequest, RegionOpenRequest, RegionRequest, + RegionTruncateRequest, StagingPartitionDirective, +}; +use store_api::storage::{FileId, RegionId, ScanRequest}; +use tokio::sync::{Notify, oneshot}; use crate::config::MitoConfig; use crate::engine::MitoEngine; +use crate::engine::listener::{EventListener, FlushCancellationListener}; +use crate::engine::region_hook::{RegionHook, RegionHookRef}; +use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList}; use crate::manifest::storage::{delta_file, gen_path, manifest_dir}; +use crate::region::MitoRegionRef; +use crate::request::{BackgroundNotify, RegionEditRequest, WorkerRequest}; +use crate::sst::file::FileMeta; use crate::sst::location::region_dir_from_table_dir; use crate::test_util::{ CheckpointTaskBlocker, CreateRequestBuilder, TestEnv, build_rows, flush_region, nop_action, put_rows, reopen_region, rows_schema, }; +use crate::time_provider::StdTimeProvider; +use crate::time_provider::mock::MockTimeProvider; use crate::wal::EntryId; +use crate::worker::CHECK_REGION_INTERVAL; fn wal_config() -> ObjectStoreWalConfig { ObjectStoreWalConfig { @@ -409,14 +431,24 @@ async fn create_leased_region( let (engine, log_store) = env .create_engine_with_object_store_wal(checkpoint_every_commit_config(), &wal_config()) .await; + let (table_dir, schema, deadline) = create_leased_region_on(&engine, region_id).await; + (engine, log_store, table_dir, schema, deadline) +} + +/// Creates a region whose writes require a lease on `engine`. Returns its table dir, row schema +/// and lease deadline, which the frozen clock of the lease checks has not reached. +async fn create_leased_region_on( + engine: &MitoEngine, + region_id: RegionId, +) -> (String, Vec, Instant) { engine.require_write_lease(); engine.freeze_lease_clock(Instant::now()); - let (table_dir, schema) = create_region(&engine, region_id).await; + let (table_dir, schema) = create_region(engine, region_id).await; let deadline = Instant::now() + Duration::from_secs(10); engine .set_region_role_with_lease(region_id, RegionRole::Leader, Instant::now(), deadline) .unwrap(); - (engine, log_store, table_dir, schema, deadline) + (table_dir, schema, deadline) } async fn count_ssts(store: &ObjectStore, region_dir: &str) -> usize { @@ -510,6 +542,8 @@ async fn test_stale_commit_on_deleted_delta_name_conflicts( let error = commit.await.unwrap().unwrap_err(); assert!(error.retry_hint().is_retryable(), "{error:?}"); assert!(format!("{error:?}").contains("conflicts"), "{error:?}"); + // The conflict fenced the old leader, which reloads the region from the shared WAL. + wait_until(|| is_replaced(&old_leader, ®ion)).await; let manager = region.manifest_ctx.manifest_manager.read().await; assert_eq!(VERSION - 1, manager.last_version()); @@ -569,3 +603,770 @@ async fn test_commit_crossing_deadline_applies_without_checkpoint() { reopen_region(&engine, region_id, table_dir, false, wal_options()).await; assert_eq!(3, count_rows(&engine, region_id).await); } + +/// Returns a WAL config whose batches are sealed only by +/// [`ObjectStoreLogStore::seal_open_batch`] and whose writes are acknowledged once enqueued. +fn held_wal_config() -> ObjectStoreWalConfig { + ObjectStoreWalConfig { + flush_interval: Duration::from_secs(3600), + max_batch_bytes: ReadableSize(u64::MAX), + ack_mode: AckMode::Enqueued, + ..wal_config() + } +} + +async fn new_log_store() -> Arc { + ObjectStoreLogStore::try_new( + ObjectStore::new(Memory::default()).unwrap(), + &wal_config(), + 0, + STANDALONE_GENERATION, + ) + .await + .unwrap() +} + +/// Holds the swap of a reloaded region until released. +#[derive(Default)] +struct ReloadSwapBlocker { + entered: Notify, + release: Notify, +} + +#[async_trait] +impl EventListener for ReloadSwapBlocker { + async fn on_region_reload_swap(&self, _region_id: RegionId) { + self.entered.notify_one(); + self.release.notified().await; + } +} + +/// Holds a catchup before it reopens the region until released. +#[derive(Default)] +struct CatchupReopenBlocker { + entered: Notify, + release: Notify, +} + +#[async_trait] +impl EventListener for CatchupReopenBlocker { + async fn on_catchup_reopen_begin(&self, _region_id: RegionId) { + self.entered.notify_one(); + self.release.notified().await; + } +} + +async fn put_range( + engine: &MitoEngine, + region_id: RegionId, + schema: &[ColumnSchema], + start: usize, + end: usize, +) { + let rows = Rows { + schema: schema.to_vec(), + rows: build_rows(start, end), + }; + put_rows(engine, region_id, rows).await; +} + +async fn wait_until(condition: impl Fn() -> bool) { + tokio::time::timeout(Duration::from_secs(10), async { + while !condition() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); +} + +/// Returns whether the engine registers another instance of the region than `old`. +fn is_replaced(engine: &MitoEngine, old: &MitoRegionRef) -> bool { + engine + .get_region(old.region_id) + .is_some_and(|region| !Arc::ptr_eq(®ion, old)) +} + +async fn next_manifest_version(region: &MitoRegionRef) -> u64 { + region + .manifest_ctx + .manifest_manager + .read() + .await + .last_version() + + 1 +} + +/// Stores `bytes` as manifest version `version` of the region, as another writer would. +async fn publish_delta(store: &ObjectStore, region_dir: &str, version: u64, bytes: Vec) { + let path = gen_path( + &manifest_dir(region_dir), + &delta_file(version), + CompressionType::Gzip, + ); + store.write(&path, bytes).await.unwrap(); +} + +async fn encode_delta(action_list: RegionMetaActionList) -> Vec { + CompressionType::Gzip + .encode(&action_list.encode().unwrap()[..]) + .await + .unwrap() +} + +/// Enters staging with a new partition expression, which saves a staging manifest. +fn enter_staging_request() -> RegionRequest { + let partition_expr = col("field_0") + .gt_eq(Value::Float64(0.0.into())) + .and(col("field_0").lt(Value::Float64(100.0.into()))) + .as_json_str() + .unwrap(); + RegionRequest::EnterStaging(EnterStagingRequest { + partition_directive: StagingPartitionDirective::UpdatePartitionExpr(partition_expr), + }) +} + +/// Fences the region as a version conflict does, without notifying its worker. +async fn fence(region: &MitoRegionRef) { + let mut manager = region.manifest_ctx.manifest_manager.write().await; + region + .manifest_ctx + .fence_for_reload(&mut manager, region.region_id) + .await; +} + +/// Notifies the region's worker as a commit outside the worker that fenced it does. +async fn notify_fenced(engine: &MitoEngine, region_id: RegionId) { + let notify = BackgroundNotify::RegionFenced; + let request = WorkerRequest::Background { region_id, notify }; + engine + .inner + .workers + .submit_to_worker(region_id, request) + .await + .unwrap(); +} + +/// Publishes the next manifest version as another writer, so that the next flush of the region +/// conflicts. Returns the instance the flush fenced. +async fn flush_into_conflict( + engine: &MitoEngine, + env: &TestEnv, + table_dir: &str, + region_id: RegionId, +) -> MitoRegionRef { + let region = engine.get_region(region_id).unwrap(); + let region_dir = region_dir_from_table_dir(table_dir, region_id, PathType::Bare); + let version = next_manifest_version(®ion).await; + let store = env.get_object_store().unwrap(); + publish_delta( + &store, + ®ion_dir, + version, + encode_delta(nop_action()).await, + ) + .await; + let flush = RegionRequest::Flush(RegionFlushRequest::default()); + let error = engine.handle_request(region_id, flush).await.unwrap_err(); + assert!(format!("{error:?}").contains("conflicts"), "{error:?}"); + region +} + +#[rstest] +#[case::flush(RegionRequest::Flush(RegionFlushRequest::default()), 0)] +#[case::compaction( + RegionRequest::Compact(RegionCompactRequest { + options: compact_request::Options::StrictWindow(StrictWindow { window_seconds: 3600 }), + ..Default::default() + }), + 2 +)] +#[tokio::test] +async fn test_commit_after_deadline_sends_nothing( + #[case] commit: RegionRequest, + #[case] flushes: usize, +) { + let mut env = TestEnv::with_prefix("commit-after-deadline").await; + let region_id = RegionId::new(1, 1); + let (engine, _log_store, table_dir, schema, deadline) = + create_leased_region(&mut env, region_id).await; + for start in (0..flushes).map(|i| i * 3) { + put_range(&engine, region_id, &schema, start, start + 3).await; + flush_region(&engine, region_id, None).await; + } + put_range(&engine, region_id, &schema, 6, 9).await; + let region = engine.get_region(region_id).unwrap(); + let version = next_manifest_version(®ion).await - 1; + let store = env.get_object_store().unwrap(); + let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare); + let ssts = count_ssts(&store, ®ion_dir).await; + + engine.freeze_lease_clock(deadline); + let error = engine.handle_request(region_id, commit).await.unwrap_err(); + + assert!( + format!("{error:?}").contains("does not hold a valid leader lease"), + "{error:?}" + ); + assert_eq!(version + 1, next_manifest_version(®ion).await); + let delta = gen_path( + &manifest_dir(®ion_dir), + &delta_file(version + 1), + CompressionType::Gzip, + ); + assert!(!store.exists(&delta).await.unwrap()); + assert_eq!(ssts, count_ssts(&store, ®ion_dir).await); + assert!(!region.manifest_ctx.is_reload_pending()); + assert!(region.is_writable()); +} + +#[tokio::test] +async fn test_staging_save_after_deadline_sends_nothing() { + let mut env = TestEnv::with_prefix("staging-after-deadline").await; + let region_id = RegionId::new(1, 1); + let (engine, _log_store, _, _, deadline) = create_leased_region(&mut env, region_id).await; + let region = engine.get_region(region_id).unwrap(); + let version = next_manifest_version(®ion).await; + + // The memtable is empty, so entering staging saves its manifest without a flush. + engine.freeze_lease_clock(deadline); + let error = engine + .handle_request(region_id, enter_staging_request()) + .await + .unwrap_err(); + + assert!( + format!("{error:?}").contains("does not hold a valid leader lease"), + "{error:?}" + ); + assert_eq!(version, next_manifest_version(®ion).await); + let store = region.manifest_ctx.manifest_manager.read().await.store(); + assert!(store.fetch_staging_manifests().await.unwrap().is_empty()); + assert!(!region.manifest_ctx.is_reload_pending()); + assert!(region.is_writable()); +} + +#[tokio::test] +async fn test_default_mode_commit_ignores_leader_deadline() { + let mut env = TestEnv::with_prefix("default-mode-deadline").await; + let (engine, _log_store) = new_engine(&mut env).await; + let region_id = RegionId::new(1, 1); + let (_, schema) = create_region(&engine, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + + // The region has no Leader deadline, which counts as passed. + flush_region(&engine, region_id, None).await; + + let region = engine.get_region(region_id).unwrap(); + assert_eq!(1, region.version().ssts.levels()[0].files.len()); +} + +#[tokio::test] +async fn test_lease_on_fenced_region_only_extends_deadline() { + let mut env = TestEnv::with_prefix("lease-on-fenced-region").await; + let region_id = RegionId::new(1, 1); + let (engine, _log_store, _, _, deadline) = create_leased_region(&mut env, region_id).await; + let region = engine.get_region(region_id).unwrap(); + fence(®ion).await; + let fenced_deadline = region.manifest_ctx.leader_deadline.get(); + + let later = deadline + Duration::from_secs(10); + let promoted = engine + .set_region_role_with_lease(region_id, RegionRole::Leader, Instant::now(), later) + .unwrap(); + + assert!(!promoted); + assert!(region.manifest_ctx.leader_deadline.get() > fenced_deadline); + assert!(region.is_follower()); +} + +#[rstest] +#[case::downgrading_leader(SettableRegionRoleState::DowngradingLeader)] +#[case::follower(SettableRegionRoleState::Follower)] +#[tokio::test] +async fn test_fenced_region_refuses_downgrade(#[case] state: SettableRegionRoleState) { + let mut env = TestEnv::with_prefix("downgrade-fenced-region").await; + let region_id = RegionId::new(1, 1); + let (engine, _log_store, _, _, _) = create_leased_region(&mut env, region_id).await; + fence(&engine.get_region(region_id).unwrap()).await; + + let response = engine + .set_region_role_state_gracefully(region_id, state) + .await + .unwrap(); + + let SetRegionRoleStateResponse::InvalidTransition(error) = response else { + panic!("a fenced region reported a downgrade: {response:?}"); + }; + assert!(error.retry_hint().is_retryable(), "{error:?}"); +} + +#[tokio::test] +async fn test_fenced_region_refuses_upgrade() { + let mut env = TestEnv::with_prefix("upgrade-fenced-region").await; + let region_id = RegionId::new(1, 1); + let (engine, _log_store, _, _, _) = create_leased_region(&mut env, region_id).await; + let region = engine.get_region(region_id).unwrap(); + fence(®ion).await; + + let catchup = RegionRequest::Catchup(RegionCatchupRequest { + set_writable: true, + ..Default::default() + }); + let error = engine.handle_request(region_id, catchup).await.unwrap_err(); + + assert!(error.retry_hint().is_retryable(), "{error:?}"); + assert!(Arc::ptr_eq(®ion, &engine.get_region(region_id).unwrap())); + assert!(region.is_follower()); +} + +#[tokio::test] +async fn test_fence_during_catchup_refuses_reopen() { + let mut env = TestEnv::with_prefix("fence-during-catchup").await; + let listener = Arc::new(CatchupReopenBlocker::default()); + let engine = env + .create_engine_with_log_store_and_time( + MitoConfig::default(), + new_log_store().await, + Arc::new(StdTimeProvider), + Some(listener.clone()), + ) + .await; + let region_id = RegionId::new(1, 1); + let (_, schema, _) = create_leased_region_on(&engine, region_id).await; + // Rows left in the memtable make the catchup reopen the region. + put_range(&engine, region_id, &schema, 0, 3).await; + engine + .set_region_role(region_id, RegionRole::Follower) + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let catchup = { + let engine = engine.clone(); + let request = RegionRequest::Catchup(RegionCatchupRequest { + set_writable: true, + ..Default::default() + }); + tokio::spawn(async move { engine.handle_request(region_id, request).await }) + }; + + // The catchup passed its entry check; a commit fences the region before the reopen. + listener.entered.notified().await; + fence(®ion).await; + listener.release.notify_one(); + + let error = catchup.await.unwrap().unwrap_err(); + assert!(error.retry_hint().is_retryable(), "{error:?}"); + assert!(Arc::ptr_eq(®ion, &engine.get_region(region_id).unwrap())); +} + +#[tokio::test] +async fn test_conflict_reloads_region() { + let mut env = TestEnv::with_prefix("conflict-reloads-region").await; + let region_id = RegionId::new(1, 1); + let (engine, _log_store, table_dir, schema, _) = + create_leased_region(&mut env, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + flush_region(&engine, region_id, None).await; + put_range(&engine, region_id, &schema, 3, 6).await; + + let old = flush_into_conflict(&engine, &env, &table_dir, region_id).await; + + assert!(old.manifest_ctx.manifest_manager.read().await.is_stopped()); + assert!(old.manifest_ctx.is_reload_pending()); + assert!(old.is_follower()); + wait_until(|| is_replaced(&engine, &old)).await; + let region = engine.get_region(region_id).unwrap(); + assert!(region.is_follower()); + assert!(!region.manifest_ctx.is_reload_pending()); + assert_eq!( + old.version_control.current().last_sequence, + region.version_control.current().last_sequence + ); + assert_eq!(6, count_rows(&engine, region_id).await); + assert!(!engine.is_region_catching_up(region_id)); +} + +#[tokio::test] +async fn test_reload_waits_for_held_upload() { + let mut env = TestEnv::with_prefix("reload-waits-for-upload").await; + let (engine, log_store) = env + .create_engine_with_object_store_wal(MitoConfig::default(), &held_wal_config()) + .await; + let region_id = RegionId::new(1, 1); + let (_, schema, _) = create_leased_region_on(&engine, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + let old = engine.get_region(region_id).unwrap(); + fence(&old).await; + + notify_fenced(&engine, region_id).await; + let waits = log_store.wait_for_durability_waits(1); + tokio::time::timeout(Duration::from_secs(10), waits) + .await + .unwrap() + .unwrap(); + assert!(!is_replaced(&engine, &old)); + log_store.seal_open_batch().await.unwrap(); + + wait_until(|| is_replaced(&engine, &old)).await; + assert_eq!(3, count_rows(&engine, region_id).await); +} + +#[tokio::test] +async fn test_reload_waits_for_running_flush() { + let mut env = TestEnv::with_prefix("reload-waits-for-flush").await; + let listener = Arc::new(FlushCancellationListener::default()); + let engine = env + .create_engine_with_log_store_and_time( + MitoConfig::default(), + new_log_store().await, + Arc::new(StdTimeProvider), + Some(listener.clone()), + ) + .await; + let region_id = RegionId::new(1, 1); + let (_, schema, _) = create_leased_region_on(&engine, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + let flush = tokio::spawn({ + let engine = engine.clone(); + let request = RegionRequest::Flush(RegionFlushRequest::default()); + async move { engine.handle_request(region_id, request).await } + }); + listener.wait_flush_started().await; + let old = engine.get_region(region_id).unwrap(); + fence(&old).await; + + notify_fenced(&engine, region_id).await; + // The worker handles a background notification before the requests it receives with it. + let catchup = RegionRequest::Catchup(RegionCatchupRequest::default()); + engine.handle_request(region_id, catchup).await.unwrap_err(); + assert!(!engine.is_region_catching_up(region_id)); + assert!(!is_replaced(&engine, &old)); + + listener.resume_flush(); + flush.await.unwrap().unwrap_err(); + wait_until(|| is_replaced(&engine, &old)).await; + assert_eq!(3, count_rows(&engine, region_id).await); +} + +/// Holds the next manifest hook call after it is armed until released. +#[derive(Debug, Default)] +struct BlockingManifestHook { + armed: AtomicBool, + entered: Notify, + release: Notify, +} + +#[async_trait] +impl RegionHook for BlockingManifestHook { + async fn on_manifest_updated( + &self, + _region_id: RegionId, + _action_list: &RegionMetaActionList, + _manifest_version: ManifestVersion, + ) { + if self.armed.swap(false, Ordering::Relaxed) { + self.entered.notify_one(); + self.release.notified().await; + } + } +} + +fn edit_files(files_to_add: Vec, files_to_remove: Vec) -> RegionEdit { + RegionEdit { + files_to_add, + files_to_remove, + ..Default::default() + } +} + +#[tokio::test] +async fn test_edit_conflict_reloads_region() { + let mut env = TestEnv::with_prefix("edit-conflict").await; + let region_id = RegionId::new(1, 1); + let (engine, _log_store, table_dir, schema, _) = + create_leased_region(&mut env, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + flush_region(&engine, region_id, None).await; + put_range(&engine, region_id, &schema, 3, 6).await; + let old = engine.get_region(region_id).unwrap(); + let flushed = old + .manifest_ctx + .manifest() + .await + .files + .values() + .next() + .unwrap() + .clone(); + let added = FileMeta { + file_id: FileId::random(), + ..flushed + }; + let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare); + let version = next_manifest_version(&old).await; + let store = env.get_object_store().unwrap(); + publish_delta( + &store, + ®ion_dir, + version, + encode_delta(nop_action()).await, + ) + .await; + + let edit = edit_files(vec![added], vec![]); + engine.edit_region(region_id, edit).await.unwrap_err(); + + wait_until(|| is_replaced(&engine, &old)).await; + assert_eq!(6, count_rows(&engine, region_id).await); +} + +#[tokio::test] +async fn test_reload_ignores_edit_of_replaced_instance() { + let mut env = TestEnv::with_prefix("reload-stale-edit").await; + let hook = Arc::new(BlockingManifestHook::default()); + let plugins = Plugins::new(); + plugins.insert::(hook.clone()); + let engine = env + .create_engine_with_log_store_and_plugins( + MitoConfig::default(), + new_log_store().await, + plugins, + ) + .await; + let region_id = RegionId::new(1, 1); + let (table_dir, schema, _) = create_leased_region_on(&engine, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + flush_region(&engine, region_id, None).await; + let old = engine.get_region(region_id).unwrap(); + let flushed = old + .manifest_ctx + .manifest() + .await + .files + .values() + .next() + .unwrap() + .clone(); + let file = |file_id| FileMeta { + file_id, + ..flushed.clone() + }; + let added = file(FileId::random()); + + hook.armed.store(true, Ordering::Relaxed); + let committed = { + let engine = engine.clone(); + let edit = edit_files(vec![added.clone()], vec![]); + tokio::spawn(async move { engine.edit_region(region_id, edit).await }) + }; + hook.entered.notified().await; + let (sender, queued) = oneshot::channel(); + let edit = edit_files(vec![file(FileId::random())], vec![]); + let request = WorkerRequest::EditRegion(RegionEditRequest::new(region_id, edit, true, sender)); + engine + .inner + .workers + .submit_to_worker(region_id, request) + .await + .unwrap(); + // The worker queues the edit before it handles the flush request sent after it. + let flush = RegionRequest::Flush(RegionFlushRequest::default()); + engine.handle_request(region_id, flush).await.unwrap_err(); + let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare); + let version = next_manifest_version(&old).await; + let removal = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit_files( + vec![], + vec![added.clone()], + ))); + let store = env.get_object_store().unwrap(); + publish_delta(&store, ®ion_dir, version, encode_delta(removal).await).await; + fence(&old).await; + notify_fenced(&engine, region_id).await; + wait_until(|| is_replaced(&engine, &old)).await; + // The swap rejects it as a close does, not as an edit sent to a Follower. + let error = queued.await.unwrap().unwrap_err(); + assert_eq!(StatusCode::RegionNotFound, error.status_code()); + + hook.release.notify_one(); + committed.await.unwrap().unwrap_err(); + let region = engine.get_region(region_id).unwrap(); + let ssts = region.version().ssts.clone(); + assert!( + !ssts + .levels() + .iter() + .any(|level| level.files.contains_key(&added.file_id)) + ); +} + +#[tokio::test] +async fn test_reload_ignores_leases_sent_before_swap() { + let mut env = TestEnv::with_prefix("reload-lease-fence").await; + let listener = Arc::new(ReloadSwapBlocker::default()); + let engine = env + .create_engine_with_log_store_and_time( + MitoConfig::default(), + new_log_store().await, + Arc::new(StdTimeProvider), + Some(listener.clone()), + ) + .await; + let region_id = RegionId::new(1, 1); + let (_, schema, deadline) = create_leased_region_on(&engine, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + let old = engine.get_region(region_id).unwrap(); + fence(&old).await; + notify_fenced(&engine, region_id).await; + + // The reloaded instance exists and waits for the swap. + listener.entered.notified().await; + let sent_before_swap = Instant::now(); + listener.release.notify_one(); + wait_until(|| is_replaced(&engine, &old)).await; + + let lease = |sent_at| { + engine.set_region_role_with_lease(region_id, RegionRole::Leader, sent_at, deadline) + }; + assert!(!lease(sent_before_swap).unwrap()); + assert!(engine.get_region(region_id).unwrap().is_follower()); + assert!(lease(Instant::now()).unwrap()); + assert!(engine.get_region(region_id).unwrap().is_writable()); +} + +#[rstest] +#[case::close(false)] +#[case::reopen(true)] +#[tokio::test] +async fn test_region_change_during_reload_drops_reloaded_instance(#[case] reopen: bool) { + let mut env = TestEnv::with_prefix("region-change-during-reload").await; + let (engine, log_store) = env + .create_engine_with_object_store_wal(MitoConfig::default(), &held_wal_config()) + .await; + let region_id = RegionId::new(1, 1); + let (table_dir, schema, _) = create_leased_region_on(&engine, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + fence(&engine.get_region(region_id).unwrap()).await; + notify_fenced(&engine, region_id).await; + wait_until(|| engine.is_region_catching_up(region_id)).await; + + close_region(&engine, region_id).await; + let reopened = if reopen { + let open = RegionRequest::Open(open_request(table_dir)); + engine.handle_request(region_id, open).await.unwrap(); + engine.get_region(region_id) + } else { + None + }; + log_store.seal_open_batch().await.unwrap(); + wait_until(|| !engine.is_region_catching_up(region_id)).await; + + let registered = engine.get_region(region_id); + match (reopened, registered) { + (None, None) => {} + (Some(reopened), Some(registered)) => assert!(Arc::ptr_eq(&reopened, ®istered)), + (reopened, registered) => panic!("reopened {reopened:?}, registered {registered:?}"), + } +} + +#[tokio::test] +async fn test_failed_reload_waits_for_backstop() { + let region_id = RegionId::new(1, 1); + // The region is created at version 0, so the conflicting flush commits version 1. + let delta_name = format!("{}.gz", delta_file(1)); + let delta_reads = Arc::new(AtomicUsize::new(0)); + let layer = MockLayerBuilder::default() + .reader_factory(Arc::new({ + let delta_reads = delta_reads.clone(); + move |path, _args, inner| { + if path.ends_with(&delta_name) { + delta_reads.fetch_add(1, Ordering::Relaxed); + } + inner + } + })) + .build() + .unwrap(); + let mut env = TestEnv::with_prefix("failed-reload") + .await + .with_mock_layer(layer); + let time_provider = Arc::new(MockTimeProvider::new(current_time_millis())); + let engine = env + .create_engine_with_log_store_and_time( + MitoConfig::default(), + new_log_store().await, + time_provider.clone(), + None, + ) + .await; + let (table_dir, schema, _) = create_leased_region_on(&engine, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + let old = engine.get_region(region_id).unwrap(); + let store = env.get_object_store().unwrap(); + let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare); + publish_delta(&store, ®ion_dir, 1, b"not a delta".to_vec()).await; + let flush = RegionRequest::Flush(RegionFlushRequest::default()); + engine.handle_request(region_id, flush).await.unwrap_err(); + + // The commit read the delta back, and the reload failed to decode it. + wait_until(|| { + delta_reads.load(Ordering::Relaxed) >= 2 && !engine.is_region_catching_up(region_id) + }) + .await; + let reads = delta_reads.load(Ordering::Relaxed); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(reads, delta_reads.load(Ordering::Relaxed)); + assert!(!is_replaced(&engine, &old)); + assert!(old.manifest_ctx.is_reload_pending()); + + publish_delta(&store, ®ion_dir, 1, encode_delta(nop_action()).await).await; + let interval = CHECK_REGION_INTERVAL.as_millis() as i64; + time_provider.set_elapsed(interval); + wait_until(|| is_replaced(&engine, &old)).await; + assert_eq!(3, count_rows(&engine, region_id).await); +} + +#[tokio::test] +async fn test_end_of_staging_conflict_reloads_region() { + let mut env = TestEnv::with_prefix("staging-conflict").await; + let region_id = RegionId::new(1, 1); + let (engine, _log_store, table_dir, schema, _) = + create_leased_region(&mut env, region_id).await; + put_range(&engine, region_id, &schema, 0, 3).await; + flush_region(&engine, region_id, None).await; + let old = engine.get_region(region_id).unwrap(); + let file = old + .manifest_ctx + .manifest() + .await + .files + .values() + .next() + .unwrap() + .clone(); + engine + .handle_request(region_id, enter_staging_request()) + .await + .unwrap(); + engine + .edit_region(region_id, edit_files(vec![file], vec![])) + .await + .unwrap(); + let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare); + let version = next_manifest_version(&old).await; + let store = env.get_object_store().unwrap(); + publish_delta( + &store, + ®ion_dir, + version, + encode_delta(nop_action()).await, + ) + .await; + + let response = engine + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Leader) + .await + .unwrap(); + + assert!(response.is_invalid_transition(), "{response:?}"); + wait_until(|| is_replaced(&engine, &old)).await; +} diff --git a/src/mito2/src/engine/sequence_test.rs b/src/mito2/src/engine/sequence_test.rs index f6c99ebb61b..ca2f0ae716e 100644 --- a/src/mito2/src/engine/sequence_test.rs +++ b/src/mito2/src/engine/sequence_test.rs @@ -17,6 +17,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; +use std::time::Duration; use api::v1::Rows; use common_recordbatch::RecordBatches; @@ -27,7 +28,9 @@ use store_api::logstore::entry::{Entry, NaiveEntry}; use store_api::logstore::provider::Provider; use store_api::logstore::{AppendBatchResponse, EntryId, LogStore, SendableEntryStream}; use store_api::region_engine::{RegionEngine, RegionRole}; -use store_api::region_request::{PathType, RegionOpenRequest, RegionPutRequest, RegionRequest}; +use store_api::region_request::{ + PathType, RegionFlushRequest, RegionOpenRequest, RegionPutRequest, RegionRequest, +}; use store_api::storage::{RegionId, ScanRequest}; use tokio::sync::oneshot; @@ -52,6 +55,7 @@ struct LogState { entries: HashMap>, fault: Option, append_calls: usize, + fail_obsolete: bool, } impl LogState { @@ -79,6 +83,10 @@ impl MemoryLogStore { let mut state = self.state.lock().unwrap(); assert!(state.fault.replace(fault).is_none()); } + + fn fail_next_obsolete(&self) { + self.state.lock().unwrap().fail_obsolete = true; + } } #[async_trait::async_trait] @@ -153,6 +161,9 @@ impl LogStore for MemoryLogStore { _region_id: RegionId, _id: EntryId, ) -> Result<()> { + if std::mem::take(&mut self.state.lock().unwrap().fail_obsolete) { + return IllegalStateSnafu {}.fail(); + } Ok(()) } async fn obsolete_all(&self, _provider: &Provider, _region_id: RegionId) -> Result<()> { @@ -408,3 +419,40 @@ async fn test_partial_region_append_preserves_all_allocations() { } engine.stop().await.unwrap(); } + +#[tokio::test] +async fn test_flush_after_failed_wal_obsolete() { + let mut env = TestEnv::new().await; + let store = Arc::new(MemoryLogStore::default()); + let engine = env + .create_engine_with_log_store(MitoConfig::default(), store.clone()) + .await; + let region_id = RegionId::new(1, 1); + let (_, schema) = create_region(&engine, region_id).await; + let flush = RegionRequest::Flush(RegionFlushRequest::default()); + let put = RegionRequest::Put(put_request(&schema, &[("a", 1)])); + engine.handle_request(region_id, put).await.unwrap(); + store.fail_next_obsolete(); + engine.handle_request(region_id, flush).await.unwrap_err(); + + // The failed WAL release must not leave the flush registered, or every later flush waits + // behind it. + let put = RegionRequest::Put(put_request(&schema, &[("b", 2)])); + engine.handle_request(region_id, put).await.unwrap(); + let flush = RegionRequest::Flush(RegionFlushRequest::default()); + tokio::time::timeout( + Duration::from_secs(10), + engine.handle_request(region_id, flush), + ) + .await + .unwrap() + .unwrap(); + let rows = scan_rows(&engine, region_id).await; + assert!( + rows.contains("| a | 1.0") && rows.contains("| b | 2.0"), + "{rows}" + ); + let version = engine.get_region(region_id).unwrap().version(); + assert!(version.memtables.is_empty()); + engine.stop().await.unwrap(); +} diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index 18cc8fcf814..bba682f555a 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -1557,6 +1557,7 @@ impl Error { | Error::RegionState { .. } | Error::RegionTruncated { .. } | Error::RegionStopped { .. } + | Error::RegionLeaseExpired { .. } | Error::SerdeJson { .. } | Error::CompressObject { .. } => false, Error::OpenDal { error, .. } => !matches!( @@ -2039,6 +2040,10 @@ mod tests { .build(); assert!(!error.may_have_persisted_manifest_update()); + // A commit refused before its PUT because the Leader deadline has passed. + let error = RegionLeaseExpiredSnafu { region_id }.build(); + assert!(!error.may_have_persisted_manifest_update()); + // This can be raised while applying an edit after its manifest file was saved. let error = RegionMetadataNotFoundSnafu {}.build(); assert!(error.may_have_persisted_manifest_update()); diff --git a/src/mito2/src/manifest/manager.rs b/src/mito2/src/manifest/manager.rs index 5cebfbc9b11..da8cac5125e 100644 --- a/src/mito2/src/manifest/manager.rs +++ b/src/mito2/src/manifest/manager.rs @@ -403,6 +403,11 @@ impl RegionManifestManager { self.stopped } + /// Returns whether deltas are published by conditional create. + pub(crate) fn is_conditional_publication(&self) -> bool { + self.store.is_conditional_publication() + } + /// Installs the manifest changes from the current version to the target version (inclusive). /// /// Returns installed version. diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index 2282eba0036..ad53b7a9424 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -57,8 +57,9 @@ use crate::access_layer::AccessLayerRef; use crate::compaction::CompactionStateRef; use crate::engine::region_hook::{PendingManifestHook, RegionHookRef}; use crate::error::{ - FlushableRegionStateSnafu, InvalidPartitionExprSnafu, InvalidRequestSnafu, RegionNotFoundSnafu, - RegionStateSnafu, RegionTruncatedSnafu, Result, UnexpectedSnafu, UpdateManifestSnafu, + Error, FlushableRegionStateSnafu, InvalidPartitionExprSnafu, InvalidRequestSnafu, + RegionBusySnafu, RegionLeaseExpiredSnafu, RegionNotFoundSnafu, RegionStateSnafu, + RegionTruncatedSnafu, Result, UnexpectedSnafu, UpdateManifestSnafu, }; use crate::lease::{Deadline, NodeLease}; use crate::manifest::action::{ @@ -568,6 +569,18 @@ impl MitoRegion { ) -> Result<()> { let mut manager: RwLockWriteGuard<'_, RegionManifestManager> = self.manifest_ctx.manifest_manager.write().await; + // Another writer advanced the manifest of a region waiting for a reload, so a migration + // from its last entry id could skip the rows still in its memtable. + if matches!( + state, + SettableRegionRoleState::Follower | SettableRegionRoleState::DowngradingLeader + ) && self.manifest_ctx.is_reload_pending() + { + return RegionBusySnafu { + region_id: self.region_id, + } + .fail(); + } let current_state = self.state(); let mut wait_for_checkpoint = false; @@ -1263,13 +1276,9 @@ pub(crate) struct ManifestContext { /// The state of the region. The region checks the state before updating /// manifest. state: AtomicCell, - /// When the region last began a downgrade. A promotion issued before it does not apply. The - /// lock covers comparing or raising it and the role change. - /// - /// It starts at creation time, so promotions issued before the region was opened or reopened - /// do not apply. A context that replaces this one is created after the worker loop closes or - /// reopens the region, so after its last downgrade began. - downgrade_started_at: Mutex, + /// Decides whether a promotion to Leader applies. The lock covers checking or changing it and + /// the role change. + promotion_fence: Mutex, /// Deadline of the region's latest Leader or StagingLeader lease from the metasrv, which is how /// long the Leader role stays valid. The engine extends it from those leases, and writes check /// it. @@ -1295,7 +1304,10 @@ impl ManifestContext { ManifestContext { manifest_manager: tokio::sync::RwLock::new(manager), state: AtomicCell::new(state), - downgrade_started_at: Mutex::new(Instant::now()), + promotion_fence: Mutex::new(PromotionFence { + downgrade_started_at: Instant::now(), + reload_pending: false, + }), leader_deadline: Deadline::default(), node_lease, staging_partition_info: Mutex::new(None), @@ -1543,12 +1555,26 @@ impl ManifestContext { // checkpoint barrier. let allow_checkpoint = !is_staging && self.state.load() != RegionRoleState::Leader(RegionLeaderState::Downgrading); - let version = manager - .update_with_verification(action_list, is_staging, allow_checkpoint, || { - self.is_leader_lease_expired() - }) - .await - .inspect_err(|e| error!(e; "Failed to update manifest, region_id: {}", region_id))?; + // A writer past its Leader deadline may no longer hold the region, so it sends nothing. + let result = if manager.is_conditional_publication() && self.is_leader_lease_expired() { + RegionLeaseExpiredSnafu { region_id }.fail() + } else { + manager + .update_with_verification(action_list, is_staging, allow_checkpoint, || { + self.is_leader_lease_expired() + }) + .await + }; + let version = match result { + Ok(version) => version, + Err(e) => { + error!(e; "Failed to update manifest, region_id: {}", region_id); + if matches!(e, Error::ManifestVersionConflict { .. }) { + self.fence_for_reload(manager, region_id).await; + } + return Err(e); + } + }; Ok(PendingManifestHook::new( region_id, @@ -1564,6 +1590,32 @@ impl ManifestContext { self.node_lease.now() >= self.leader_deadline.get() } + /// Fences a region whose manifest another writer has advanced, under the caller's manifest + /// lock: later commits fail, and the region stays a Follower that no promotion changes until + /// the worker replaces it with an instance reloaded from the new manifest. + pub(crate) async fn fence_for_reload( + &self, + manager: &mut RegionManifestManager, + region_id: RegionId, + ) { + manager.stop().await; + // Marked before the role change, so a promotion in between cannot make it writable again. + self.promotion_fence.lock().unwrap().reload_pending = true; + self.set_role(RegionRole::Follower, region_id); + warn!("Region {region_id} is fenced until it is reloaded"); + } + + /// Returns whether the region waits for a reload, see [Self::fence_for_reload]. + pub(crate) fn is_reload_pending(&self) -> bool { + self.promotion_fence.lock().unwrap().reload_pending + } + + /// Ignores the promotions issued before now. The worker calls it on a reloaded instance when + /// it replaces the old one, whose time a downgrade during the reload raised instead. + pub(crate) fn ignore_earlier_promotions(&self) { + self.promotion_fence.lock().unwrap().downgrade_started_at = Instant::now(); + } + /// Updates the manifest using a caller-held write lock, releases the lock, /// and then fires the manifest hook. /// @@ -1687,14 +1739,14 @@ impl ManifestContext { /// Raises the downgrade start time to now, then marks the region downgrading. pub(crate) fn begin_downgrade(&self, region_id: RegionId) { - let mut downgrade_started_at = self.downgrade_started_at.lock().unwrap(); - *downgrade_started_at = Instant::now(); + let mut fence = self.promotion_fence.lock().unwrap(); + fence.downgrade_started_at = Instant::now(); self.set_role(RegionRole::DowngradingLeader, region_id); } - /// Promotes the region to a writable leader unless a downgrade started after `issued_at`. - /// Returns false if the promotion is ignored for that reason; otherwise the role changes as - /// [`Self::set_role`] allows. + /// Promotes the region to a writable leader unless a downgrade started after `issued_at` or + /// the region waits for a reload. Returns false if the promotion is ignored for one of these + /// reasons; otherwise the role changes as [`Self::set_role`] allows. pub(crate) fn promote_unless_downgrade_started_after( &self, issued_at: Instant, @@ -1704,8 +1756,21 @@ impl ManifestContext { if self.state.load() == RegionRoleState::Leader(RegionLeaderState::Writable) { return true; } - let downgrade_started_at = self.downgrade_started_at.lock().unwrap(); - if issued_at < *downgrade_started_at { + let fence = self.promotion_fence.lock().unwrap(); + issued_at >= fence.downgrade_started_at + && self.promote_unless_reload_pending(&fence, region_id) + } + + /// Promotes a region that caught up to a writable leader. Returns false if the region waits + /// for a reload. + pub(crate) fn promote_after_catchup(&self, region_id: RegionId) -> bool { + let fence = self.promotion_fence.lock().unwrap(); + self.promote_unless_reload_pending(&fence, region_id) + } + + /// Promotes the region unless it waits for a reload. The caller holds the fence lock. + fn promote_unless_reload_pending(&self, fence: &PromotionFence, region_id: RegionId) -> bool { + if fence.reload_pending { return false; } self.set_role(RegionRole::Leader, region_id); @@ -1888,6 +1953,21 @@ impl ManifestContext { pub(crate) type ManifestContextRef = Arc; +/// The state that decides whether a promotion to Leader applies. +#[derive(Debug)] +struct PromotionFence { + /// When the region last began a downgrade. A promotion issued before it does not apply. + /// + /// It starts at creation time, so promotions issued before the region was opened or reopened + /// do not apply. A context that replaces this one after a close or reopen is created after + /// its last downgrade began. A reloaded one is created while this one is still registered, so + /// it raises the time when it replaces this one. + downgrade_started_at: Instant, + /// Whether another writer advanced the manifest, so this instance stays a Follower until a + /// reload replaces it. + reload_pending: bool, +} + /// Regions indexed by ids. #[derive(Debug, Default)] pub(crate) struct RegionMap { @@ -2535,7 +2615,7 @@ mod tests { async fn test_promoting_writable_leader_takes_no_lock() { let env = SchedulerEnv::new().await; let region = Arc::new(build_test_region(&env).await); - let _downgrade_started_at = region.manifest_ctx.downgrade_started_at.lock().unwrap(); + let _promotion_fence = region.manifest_ctx.promotion_fence.lock().unwrap(); let (tx, rx) = std::sync::mpsc::channel(); let promoted = region.clone(); std::thread::spawn(move || { diff --git a/src/mito2/src/request.rs b/src/mito2/src/request.rs index d6777131b4f..de9594229b3 100644 --- a/src/mito2/src/request.rs +++ b/src/mito2/src/request.rs @@ -1145,6 +1145,15 @@ pub(crate) enum BackgroundNotify { EnterStaging(EnterStagingResult), /// Copy region result. CopyRegionFromFinished(CopyRegionFromFinished), + /// A commit outside the worker fenced the region until it is reloaded. + RegionFenced, + /// The reload of a fenced region has finished. + RegionReloaded { + /// The instance the reload replaces. + old: MitoRegionRef, + /// The reloaded instance. + result: Result, + }, } /// Notifies a flush job is finished. @@ -1173,11 +1182,9 @@ impl FlushFinished { sender.send(Ok(0)); } } -} -impl OnFailure for FlushFinished { - fn on_failure(&mut self, err: Error) { - let err = Arc::new(err); + /// Marks the flush job as failed with an error that other waiters share. + pub(crate) fn on_shared_failure(&mut self, err: Arc) { for sender in self.senders.drain(..) { sender.send(Err(err.clone()).context(FlushRegionSnafu { region_id: self.region_id, @@ -1186,6 +1193,12 @@ impl OnFailure for FlushFinished { } } +impl OnFailure for FlushFinished { + fn on_failure(&mut self, err: Error) { + self.on_shared_failure(Arc::new(err)); + } +} + /// Notifies a flush job is failed. #[derive(Debug)] pub(crate) struct FlushFailed { diff --git a/src/mito2/src/test_util.rs b/src/mito2/src/test_util.rs index 75d6d575f6e..2c06c2b4978 100644 --- a/src/mito2/src/test_util.rs +++ b/src/mito2/src/test_util.rs @@ -539,6 +539,17 @@ impl TestEnv { &mut self, config: MitoConfig, log_store: Arc, + ) -> MitoEngine { + self.create_engine_with_log_store_and_plugins(config, log_store, Plugins::new()) + .await + } + + /// Creates a new engine with specific config and plugins on `log_store` under this env. + pub(crate) async fn create_engine_with_log_store_and_plugins( + &mut self, + config: MitoConfig, + log_store: Arc, + plugins: Plugins, ) -> MitoEngine { let object_store_manager = Arc::new(self.create_object_store_manager()); self.object_store_manager = Some(object_store_manager.clone()); @@ -552,7 +563,7 @@ impl TestEnv { self.schema_metadata_manager.clone(), self.file_ref_manager.clone(), self.partition_expr_fetcher.clone(), - Plugins::new(), + plugins, ) .await .unwrap() diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index d8f5b0b3620..7f5fe9aff63 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -28,6 +28,7 @@ mod handle_flush; mod handle_manifest; mod handle_open; mod handle_rebuild_index; +mod handle_reload; mod handle_remap; #[cfg(feature = "enterprise")] mod handle_table_compaction; @@ -1534,10 +1535,16 @@ impl RegionWorkerLoop { if let Err(e) = self.flush_periodically() { error!(e; "Failed to flush regions periodically"); } + // Retries the reloads that failed, and starts those no notification started. + for region in self.regions.list_regions() { + self.maybe_reload_region(region.region_id); + } } /// Handles region background request async fn handle_background_notify(&mut self, region_id: RegionId, notify: BackgroundNotify) { + // A reload that fails for good would otherwise restart itself forever. + let is_reload_result = matches!(notify, BackgroundNotify::RegionReloaded { .. }); match notify { BackgroundNotify::RegionOpened { region, registered } => { self.register_region(region); @@ -1597,6 +1604,14 @@ impl RegionWorkerLoop { BackgroundNotify::CopyRegionFromFinished(req) => { self.handle_copy_region_from_finished(req) } + BackgroundNotify::RegionFenced => {} + BackgroundNotify::RegionReloaded { old, result } => { + self.handle_region_reloaded(region_id, old, result).await + } + } + // A commit that found a newer manifest fenced the region before its job reported here. + if !is_reload_result { + self.maybe_reload_region(region_id); } } @@ -1622,6 +1637,7 @@ impl RegionWorkerLoop { let sweep_older_than = self.config.gc.unknown_file_lingering_time; #[cfg(feature = "hdfs-object-store")] let sweep_limiter = self.sweep_limiter.clone(); + let request_sender = self.sender.clone(); // We need to do this in background as we need the manifest lock. common_runtime::spawn_global(async move { match region.set_role_state_gracefully(region_role_state).await { @@ -1649,6 +1665,8 @@ impl RegionWorkerLoop { )); } } + // The call commits outside the worker when it ends staging or backfills metadata. + handle_reload::notify_if_fenced(&request_sender, ®ion).await; }); } else { let _ = sender.send(SetRegionRoleStateResponse::NotFound); @@ -1702,6 +1720,22 @@ impl WorkerListener { } } + /// The worker is about to replace a fenced region with its reload. + pub(crate) async fn on_region_reload_swap(&self, _region_id: RegionId) { + #[cfg(any(test, feature = "test"))] + if let Some(listener) = &self.listener { + listener.on_region_reload_swap(_region_id).await; + } + } + + /// A catchup is about to reopen the region. + pub(crate) async fn on_catchup_reopen_begin(&self, _region_id: RegionId) { + #[cfg(any(test, feature = "test"))] + if let Some(listener) = &self.listener { + listener.on_catchup_reopen_begin(_region_id).await; + } + } + /// Flush is finished successfully. pub(crate) fn on_flush_success(&self, region_id: RegionId) { #[cfg(any(test, feature = "test"))] diff --git a/src/mito2/src/worker/handle_apply_staging.rs b/src/mito2/src/worker/handle_apply_staging.rs index 73b9decd128..31a4679c64d 100644 --- a/src/mito2/src/worker/handle_apply_staging.rs +++ b/src/mito2/src/worker/handle_apply_staging.rs @@ -27,6 +27,7 @@ use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState}; use crate::request::{OptionOutputTx, RegionEditRequest, WorkerRequest, WorkerRequestWithTime}; use crate::sst::location::region_dir_from_table_dir; use crate::worker::RegionWorkerLoop; +use crate::worker::handle_reload::notify_if_fenced; impl RegionWorkerLoop { pub(crate) async fn handle_apply_staging_manifest_request( @@ -151,14 +152,16 @@ impl RegionWorkerLoop { return; }; let mut manager = region.manifest_ctx.manifest_manager.write().await; - let hook_payload = match region.exit_staging_on_success(&mut manager).await { + let result = region.exit_staging_on_success(&mut manager).await; + drop(manager); + let hook_payload = match result { Ok(payload) => payload, Err(e) => { + notify_if_fenced(&worker_sender, ®ion).await; sender.send(Err(e)); return; } }; - drop(manager); if let Some(pending) = hook_payload { pending.fire().await; } diff --git a/src/mito2/src/worker/handle_catchup.rs b/src/mito2/src/worker/handle_catchup.rs index 26229b66e93..1db62929941 100644 --- a/src/mito2/src/worker/handle_catchup.rs +++ b/src/mito2/src/worker/handle_catchup.rs @@ -18,8 +18,9 @@ use std::sync::Arc; use common_telemetry::tracing::warn; use common_telemetry::{debug, error, info}; +use snafu::ensure; use store_api::logstore::LogStore; -use store_api::region_engine::{RegionRole, SettableRegionRoleState}; +use store_api::region_engine::SettableRegionRoleState; use store_api::region_request::RegionCatchupRequest; use store_api::storage::RegionId; @@ -52,8 +53,10 @@ impl RegionWorkerLoop { return; } - if self.catchup_regions.is_region_exists(region_id) { - warn!("Region {region_id} under catching up"); + if self.catchup_regions.is_region_exists(region_id) + || region.manifest_ctx.is_reload_pending() + { + warn!("Region {region_id} under catching up or waiting for a reload"); sender.send(Err(error::RegionBusySnafu { region_id }.build())); return; } @@ -88,28 +91,35 @@ impl RegionWorkerLoop { // The region takes writes under the node lease until its next Leader // grant. node_lease.seed(®ion.manifest_ctx.leader_deadline); - region.set_role(RegionRole::Leader); - // Finalize leadership: persist backfilled metadata. - match region - .set_role_state_gracefully(SettableRegionRoleState::Leader) - .await - { - Ok(()) => { - #[cfg(feature = "hdfs-object-store")] - temp_file_sweeper::spawn_region_sweep( - region.access_layer(), - region_id, - sweep_older_than, - sweep_limiter, - ); - } - Err(err) => { - error!(err; "Failed to set region {region_id} to leader"); + if region.manifest_ctx.promote_after_catchup(region_id) { + // Finalize leadership: persist backfilled metadata. + match region + .set_role_state_gracefully(SettableRegionRoleState::Leader) + .await + { + Ok(()) => { + #[cfg(feature = "hdfs-object-store")] + temp_file_sweeper::spawn_region_sweep( + region.access_layer(), + region_id, + sweep_older_than, + sweep_limiter, + ); + } + Err(err) => { + error!(err; "Failed to set region {region_id} to leader"); + } } } } catchup_regions.remove_region(region_id); - sender.send(Ok(0)); + // A commit during the catchup, including the backfill above, may have found + // a newer manifest. + if region.manifest_ctx.is_reload_pending() { + sender.send(Err(error::RegionBusySnafu { region_id }.build())); + } else { + sender.send(Ok(0)); + } } Err(err) => { error!(err; "Failed to catchup region {region_id}"); @@ -126,13 +136,41 @@ impl RegionWorkerLoop { region: &Arc, ) -> Result> { let region_id = region.region_id; - let manifest_version = region.manifest_ctx.manifest_version().await; + // Commits of the old instance wait until the reopened one is registered, so a conflict + // either fenced the old instance before the check below or happens after it is replaced. + let manager = region.manifest_ctx.manifest_manager.read().await; + ensure!( + !region.manifest_ctx.is_reload_pending(), + error::RegionBusySnafu { region_id } + ); + let manifest_version = manager.manifest().manifest_version; let flushed_entry_id = region.version_control.current().last_entry_id; info!( "Reopening the region: {region_id}, manifest version: {manifest_version}, flushed entry id: {flushed_entry_id}" ); - let reopened_region = RegionOpener::new( - region_id, + let reopened_region = self + .region_reopener(region)? + .skip_wal_replay(true) + .open(&self.config, &self.wal) + .await?; + debug_assert!(!reopened_region.is_writable()); + // Preserve allocated sequences without publishing the old memtables. + reopened_region + .version_control + .update_last_sequence(region.version_control.current().last_sequence); + self.register_region(reopened_region.clone()); + drop(manager); + if let Some(state) = &self.series_index_task_state { + state.wake(); + } + + Ok(reopened_region) + } + + /// Returns an opener of the region from its manifest, with its current options. + pub(crate) fn region_reopener(&self, region: &MitoRegion) -> Result { + RegionOpener::new( + region.region_id, region.table_dir(), region.access_layer.path_type(), self.node_lease.clone(), @@ -149,21 +187,7 @@ impl RegionWorkerLoop { .series_index_store(self.series_index_store.clone()) .series_index_purger(self.series_index_purger.clone()) .hook(self.plugins.get()) - .options(region.version().options.clone())? - .skip_wal_replay(true) - .open(&self.config, &self.wal) - .await?; - debug_assert!(!reopened_region.is_writable()); - // Preserve allocated sequences without publishing the old memtables. - reopened_region - .version_control - .update_last_sequence(region.version_control.current().last_sequence); - self.register_region(reopened_region.clone()); - if let Some(state) = &self.series_index_task_state { - state.wake(); - } - - Ok(reopened_region) + .options(region.version().options.clone()) } async fn reopen_region_if_needed( @@ -185,6 +209,9 @@ impl RegionWorkerLoop { region.version_control.current().last_entry_id ); } + self.listener + .on_catchup_reopen_begin(region.region_id) + .await; self.reopen_region(®ion).await? } else { region diff --git a/src/mito2/src/worker/handle_flush.rs b/src/mito2/src/worker/handle_flush.rs index f68b85bc190..bcc71520c2b 100644 --- a/src/mito2/src/worker/handle_flush.rs +++ b/src/mito2/src/worker/handle_flush.rs @@ -527,8 +527,12 @@ impl RegionWorkerLoop { .obsolete(region_id, obsolete_entry_id, ®ion.provider) .await { - error!(e; "Failed to write wal, region: {}", region_id); - request.on_failure(e); + let err = Arc::new(e); + error!(err; "Failed to write wal, region: {}", region_id); + request.on_shared_failure(err.clone()); + // The flush scheduler still tracks the flush, so release it as a failed flush does. + self.handle_flush_failed(region_id, FlushFailed { err }) + .await; return; } diff --git a/src/mito2/src/worker/handle_manifest.rs b/src/mito2/src/worker/handle_manifest.rs index 2a37f898f3c..8cd0d77c5d3 100644 --- a/src/mito2/src/worker/handle_manifest.rs +++ b/src/mito2/src/worker/handle_manifest.rs @@ -486,13 +486,12 @@ impl RegionWorkerLoop { }); return; } - let requires_reopen = edit_result.result.is_err() - && region - .manifest_ctx - .manifest_manager - .read() - .await - .is_stopped(); + // A region waiting for a reload recovers its files when the reload replaces it. A fence + // stops the manager and sets the mark under the manifest lock, so read both under it. + let requires_reopen = edit_result.result.is_err() && { + let manager = region.manifest_ctx.manifest_manager.read().await; + manager.is_stopped() && !region.manifest_ctx.is_reload_pending() + }; if let Err(error) = &edit_result.result && requires_reopen { diff --git a/src/mito2/src/worker/handle_reload.rs b/src/mito2/src/worker/handle_reload.rs new file mode 100644 index 00000000000..67f6514fc77 --- /dev/null +++ b/src/mito2/src/worker/handle_reload.rs @@ -0,0 +1,138 @@ +// 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. + +//! Reloading a region that a manifest version conflict fenced. + +use std::sync::Arc; + +use common_telemetry::{error, info, warn}; +use store_api::logstore::LogStore; +use store_api::storage::RegionId; +use tokio::sync::mpsc::Sender; + +use crate::error::Result; +use crate::region::{MitoRegion, MitoRegionRef}; +use crate::request::{BackgroundNotify, WorkerRequest, WorkerRequestWithTime}; +use crate::worker::RegionWorkerLoop; + +impl RegionWorkerLoop { + /// Starts reloading the region from its manifest and this node's WAL if a manifest version + /// conflict fenced it and no catchup or reload of it runs. + pub(crate) fn maybe_reload_region(&mut self, region_id: RegionId) { + let Some(region) = self.regions.get_region(region_id) else { + return; + }; + // A flush of the old instance would report to the replacement, so the reload waits until + // the flush reports here, which checks again. + if !region.manifest_ctx.is_reload_pending() + || self.catchup_regions.is_region_exists(region_id) + || self.flush_scheduler.is_flush_requested(region_id) + { + return; + } + // The worker writes a region inline and a Follower takes no writes, so every + // acknowledged write has an entry id at or below the one read below. + if !region.is_follower() { + warn!( + "Region {region_id} waits for a reload but is {:?}, not reloading it", + region.state() + ); + return; + } + let opener = match self.region_reopener(®ion) { + Ok(opener) => opener.skip_wal_replay(false), + Err(e) => { + error!(e; "Failed to build the reload of region {region_id}"); + return; + } + }; + let last_entry_id = region.version_control.current().last_entry_id; + info!("Reloading region {region_id}, last entry id: {last_entry_id}"); + self.catchup_regions.insert_region(region_id); + let durability_barrier = self.wal.durability_barrier(region_id, ®ion.provider); + let wal = self.wal.clone(); + let config = self.config.clone(); + let sender = self.sender.clone(); + common_runtime::spawn_global(async move { + let result = async { + // The replay reads only what the log store has made durable. + durability_barrier.wait(last_entry_id).await?; + opener.open(&config, &wal).await + } + .await; + let notify = BackgroundNotify::RegionReloaded { + old: region, + result, + }; + let _ = sender + .send(WorkerRequestWithTime::new(WorkerRequest::Background { + region_id, + notify, + })) + .await; + }); + } + + /// Replaces the fenced instance with the reloaded one, unless the region was closed or + /// reopened during the reload. A failed reload leaves the fenced instance in place. + pub(crate) async fn handle_region_reloaded( + &mut self, + region_id: RegionId, + old: MitoRegionRef, + result: Result, + ) { + self.listener.on_region_reload_swap(region_id).await; + self.catchup_regions.remove_region(region_id); + let region = match result { + Ok(region) => region, + Err(e) => { + error!(e; "Failed to reload region {region_id}"); + return; + } + }; + let registered = self.regions.get_region(region_id); + if !registered.is_some_and(|registered| Arc::ptr_eq(®istered, &old)) { + info!("Region {region_id} changed during its reload, dropping the reloaded instance"); + return; + } + // Preserve allocated sequences without publishing the old memtables. + region + .version_control + .update_last_sequence(old.version_control.current().last_sequence); + // Leases apply through the shared region map, so only those from heartbeats sent after + // the replacement may promote the new instance. + region.manifest_ctx.ignore_earlier_promotions(); + // Requests waiting for the old instance are rejected as a close rejects them. + self.fail_region_stalled_requests_as_not_found(®ion_id); + self.reject_region_edit_queue_as_not_found(region_id); + self.register_region(region); + if let Some(state) = &self.series_index_task_state { + state.wake(); + } + info!("Region {region_id} is reloaded"); + } +} + +/// Asks the worker to reload the region if a commit outside the worker fenced it. The caller +/// must not hold the region's manifest lock, which the worker may wait for. +pub(crate) async fn notify_if_fenced(sender: &Sender, region: &MitoRegion) { + if region.manifest_ctx.is_reload_pending() { + let _ = sender + .send(WorkerRequestWithTime::new(WorkerRequest::Background { + region_id: region.region_id, + notify: BackgroundNotify::RegionFenced, + })) + .await; + } +} From 90d0c00a82ac491dd217698b19bd55c00449b27a Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 11 Nov 2026 10:06:12 +0000 Subject: [PATCH 08/63] fix(promql): resolve the OR right operand's time-index column from its schema (#10335) `or` inferred the qualifier of an operand plan from its first field (`schema.qualified_field(0)`). A binary operation with an explicit matching modifier derives its result labels from the left operand when the match reduces the label set, so its projected plan carries two qualifiers: the labels are `lhs.