From 5952a49e2fb20859804fbe4108a3fc0023fc1039 Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Fri, 20 Nov 2026 13:05:34 +0000 Subject: [PATCH] fix(mito2): wait for a Leader lease before committing after a catchup (#10544) * fix(mito2): wait for a Leader lease before committing after a catchup On a datanode whose writes need a lease, a catchup makes a migration target writable before the route points to it. Until a Leader or StagingLeader lease of a heartbeat sent after the catchup applies, such a region commits to its manifest only replayed WAL tails and what it commits while downgrading; any other commit fails with the retryable RegionLeaseNotReceived in ManifestContext::update_locked. No flush or compaction trigger starts work for it, a write over its own write buffer is rejected as for a staging region, and a close that must flush downgrades it first. The lease that ends the wait tells the region's worker once. The worker schedules the engine-full and region-full flushes and, if the region is then a writable leader, starts a compaction, builds missing indexes in async index mode and persists the metadata the opener backfilled. Signed-off-by: jeremyhi * test(mito2): refuse a discard of pending tails while awaiting the Leader lease Signed-off-by: jeremyhi * fix(mito2): keep extension indexes in the lease-end index pass The index pass at the end of a wait for the Leader lease is a flush build of every file, which builds no extension index, so it replaced the index of a compacted file whose sketch the compaction built. It now skips files that have an extension index, as the background build after a compaction does, through the same check. Signed-off-by: jeremyhi * fix(mito2): drop the FileMeta import the moved check left unused Signed-off-by: jeremyhi * test(mito2): share the sketch region setup of the index build tests Signed-off-by: jeremyhi * test(mito2): check the lease-end index candidates where they are chosen Signed-off-by: jeremyhi * test(mito2): select and test the whole-region index builds in one function Signed-off-by: jeremyhi * fix(mito2): start no checkpoint while awaiting the Leader lease in every publication mode Signed-off-by: jeremyhi * fix(mito2): pin no memtable while persisting backfilled metadata The backfilled metadata save keeps only the region metadata and SST format across its manifest write instead of the whole version, so a flush applied meanwhile frees its memtable. Test that a save the end of a lease wait spawns asks the worker to reload the region it fences, and describe update_locked as the lease check around the shared write that a tail replay makes directly. Signed-off-by: jeremyhi * test(mito2): test the backfill save's reload request on the task itself Signed-off-by: jeremyhi * refactor(mito2): address the review of the lease wait carve Name the spawned backfill task for both of its steps, select the whole-region index builds from file handles, reuse promote_with_lease in the new tail replay tests, and make the docs, AGENTS.md and comments say what the code does: the hook entry points, the discard that the lease check refuses, the background flush triggers and the region write buffer threshold of a waiting region. Signed-off-by: jeremyhi * docs(mito2): describe the hook entry point as the write behind update_locked Signed-off-by: jeremyhi * test(mito2): check the deferred compaction as it is scheduled The replay's commit clears the pending tails before the worker decides on its compaction, so a count read after the replay could miss a compaction scheduled during the wait. The listener now checks the wait whenever a compaction is scheduled. Signed-off-by: jeremyhi * fix(mito2): build index retries refused while awaiting the Leader lease after it A retry of an index build whose publication found the schema changed has no caller to try again. When the region awaits its Leader lease the worker refused it, and the lease-end pass does not cover files with an extension index or build types other than flush. The worker now keeps such retries per region and re-issues them through the normal handler when the lease ends the wait with the region a writable leader. Closing or dropping the region clears them. Signed-off-by: jeremyhi * test(mito2): gate the deferred compaction check on the end of the replay The worker reports the replay's end after it handled the replay's commit and its compaction decision, so the check no longer needs to watch the region. The retry test needs no WAL listener. Signed-off-by: jeremyhi * test(mito2): publish the end of a tail replay with release ordering A test that observes the end of a replay then reads counts the worker's earlier callbacks set, so the end is stored with release and read with acquire. Signed-off-by: jeremyhi * fix(mito2): forget kept index build retries when the worker cleans up Signed-off-by: jeremyhi --------- Signed-off-by: jeremyhi --- src/mito2/AGENTS.md | 21 +- src/mito2/src/compaction/scheduler.rs | 22 +- src/mito2/src/compaction/scheduler_test.rs | 23 +- src/mito2/src/engine.rs | 32 +- src/mito2/src/engine/lease_test.rs | 674 +++++++++++++++++- src/mito2/src/engine/listener.rs | 8 + .../engine/object_store_wal_recovery_test.rs | 36 +- src/mito2/src/engine/object_store_wal_test.rs | 111 ++- src/mito2/src/engine/open_test.rs | 44 +- src/mito2/src/engine/region_hook.rs | 14 +- src/mito2/src/engine/staging_test.rs | 43 +- .../src/engine/table_compaction/tests.rs | 46 +- src/mito2/src/engine/tail_replay_test.rs | 188 ++++- src/mito2/src/error.rs | 22 +- src/mito2/src/region.rs | 461 ++++++++++-- src/mito2/src/request.rs | 4 + src/mito2/src/tail_replay.rs | 9 +- src/mito2/src/test_util.rs | 6 + src/mito2/src/worker.rs | 42 +- src/mito2/src/worker/handle_alter.rs | 8 + src/mito2/src/worker/handle_catchup.rs | 98 ++- src/mito2/src/worker/handle_close.rs | 8 + src/mito2/src/worker/handle_compaction.rs | 16 +- src/mito2/src/worker/handle_drop.rs | 1 + src/mito2/src/worker/handle_enter_staging.rs | 10 + src/mito2/src/worker/handle_flush.rs | 32 +- src/mito2/src/worker/handle_rebuild_index.rs | 125 +++- 27 files changed, 1895 insertions(+), 209 deletions(-) diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index 90b1d86918a..6a8df94559b 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -89,7 +89,8 @@ pending. DDL cancellation retains its existing scheduling fence and priority. - **SST/Parquet layout** (`sst/`): readers must stay compatible with existing files. - **Index extensions**: shared contracts and provider validation live in `sst/index/registry.rs`; typed sketch options are enterprise-gated. Lifecycle and failure tests live in - `engine/index_build_test.rs` and `compaction/`. + `engine/index_build_test.rs` and `compaction/`. A background rebuild must not replace a file + that carries extension indexes (`worker/handle_rebuild_index.rs::needs_background_indexes`). - **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 range entries and expires series indexes to reclaim published usage. Concurrent builds may @@ -202,17 +203,27 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes - Staging regions, ending staging included, never flush: a flush would stage its SST and release the rows' WAL, losing them if staging does not end successfully. Every flush trigger in `worker/handle_flush.rs` must skip them: background triggers test `is_writable()` - and `is_staging()`, a flush request `is_flushable()` and `is_staging()` (`is_writable()` and + and `defers_background_flush()`, a flush request `is_flushable()` and `is_staging()` (`is_writable()` and `is_flushable()` are false while ending staging). `handle_close` leaves staging first. Tail replays never run for them: entering staging fails while tails are pending. - Direct SST imports without a staging binding cannot publish into staging. `worker/handle_manifest.rs` seals edit admission while EnterStaging drains accepted edits. Scheduler-owned DDLs resume through execution, bypassing initial admission. +- On a node whose writes need a lease, a region that a catchup made writable waits for a + Leader or StagingLeader lease sent after the catchup (`awaits_leader_lease`). Until then + `ManifestContext::update_locked` refuses its commits unless they are staged or the region is + downgrading (a close that must flush downgrades first); only a replay of tails + (`TailsEditor::Replay`) skips the check, a discard does not, and ending staging checks it + before `commit_staged_locked`. No flush or compaction trigger starts work for a waiting region except + a downgrade's flush. The lease that ends the wait wakes the worker + (`handle_leader_lease_wait_ended`) to schedule the flushes the wait deferred and, only if the + region is then a writable leader, start a compaction, build missing indexes, re-issue the + index build retries the wait refused and persist backfilled metadata. - The latest lease each region received (`GrantedLeases` in `lease.rs`) lives outside the region instance, so a reopen during catchup keeps it. Every path that removes a region from - a worker's region map must also remove its record: `RegionWorkerLoop::remove_region` - (`worker/handle_close.rs`, also used after a close-time flush), `drop_region` - (`worker/handle_drop.rs`) and `RegionWorkerLoop::clean` (`worker.rs`). + a worker's region map must also remove its record and its kept index build retries: + `RegionWorkerLoop::remove_region` (`worker/handle_close.rs`, also used after a close-time + flush), `drop_region` (`worker/handle_drop.rs`) and `RegionWorkerLoop::clean` (`worker.rs`). ## Maintenance contract diff --git a/src/mito2/src/compaction/scheduler.rs b/src/mito2/src/compaction/scheduler.rs index 028c7615d07..21a692cd0dd 100644 --- a/src/mito2/src/compaction/scheduler.rs +++ b/src/mito2/src/compaction/scheduler.rs @@ -594,6 +594,14 @@ impl CompactionScheduler { waiter.send(Ok(0)); return Ok(false); } + if manifest_ctx.awaits_leader_lease() { + info!( + "Skipping compaction for region {} that awaits its Leader lease, options: {:?}", + region_id, compact_options + ); + waiter.send(Ok(0)); + return Ok(false); + } if status.has_pending_tails() { info!( "Skipping compaction for region {} with pending WAL tails, options: {:?}", @@ -669,7 +677,13 @@ impl CompactionScheduler { let Some(pending_request) = std::mem::take(&mut status.pending_request) else { return false; }; - if status.has_pending_tails() { + let awaits_leader_lease = manifest_ctx.awaits_leader_lease(); + if awaits_leader_lease { + info!( + "Region {region_id} awaits its Leader lease, answering its queued compaction without compacting" + ); + } + if status.has_pending_tails() || awaits_leader_lease { status.pending_task_state = None; status.publish_state(); pending_request.waiter.send(Ok(0)); @@ -768,7 +782,11 @@ impl CompactionScheduler { let Some(status) = self.region_status.get_mut(®ion_id) else { return false; }; - if status.has_pending_tails() { + let awaits_leader_lease = manifest_ctx.awaits_leader_lease(); + if awaits_leader_lease { + info!("Region {region_id} awaits its Leader lease, starting no follow-up compaction"); + } + if status.has_pending_tails() || awaits_leader_lease { return false; } // An external automatic trigger requires one unrestricted follow-up pick. diff --git a/src/mito2/src/compaction/scheduler_test.rs b/src/mito2/src/compaction/scheduler_test.rs index 102ee31e47b..e2b3246ed1e 100644 --- a/src/mito2/src/compaction/scheduler_test.rs +++ b/src/mito2/src/compaction/scheduler_test.rs @@ -3671,8 +3671,15 @@ async fn test_compaction_tasks_linear_local_publication(#[case] reject_after_fir assert!(!scheduler.is_compacting(region_id)); } +/// A queued manual compaction or an automatic follow-up starts nothing while the region has +/// pending tails or awaits its Leader lease. +#[rstest::rstest] +#[case::pending_tails(false)] +#[case::awaiting_leader_lease(true)] #[tokio::test] -async fn test_finishing_compaction_with_pending_tails_starts_nothing() { +async fn test_finishing_compaction_of_blocked_region_starts_nothing( + #[case] awaiting_leader_lease: bool, +) { let env = SchedulerEnv::new().await; let (tx, _rx) = mpsc::channel(4); let mut scheduler = env.mock_compaction_scheduler(tx); @@ -3697,11 +3704,15 @@ async fn test_finishing_compaction_with_pending_tails_starts_nothing() { 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(), - ); + if awaiting_leader_lease { + manifest_ctx.start_leader_lease_wait_for_test(region_id); + } else { + 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) diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 8454ba8adb8..494e74c4644 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -108,7 +108,7 @@ mod puffin_index; use std::any::Any; use std::collections::{HashMap, HashSet}; use std::sync::{Arc, RwLock}; -use std::time::Instant; +use std::time::{Duration, Instant}; use api::region::RegionResponse; use async_trait::async_trait; @@ -1408,6 +1408,23 @@ impl EngineInner { } } + /// Logs the end of the wait of `region` for its Leader lease, which lasted `waited`, and + /// tells its worker to start what the wait deferred. Does nothing if the lease ended no wait + /// or the region waits again, so a wait ends with one notification. + fn notify_if_leader_lease_wait_ended(&self, region: &MitoRegionRef, waited: Option) { + let Some(waited) = waited else { + return; + }; + if region.manifest_ctx.awaits_leader_lease() { + return; + } + info!( + "Region {} received its Leader lease {:?} after a catchup made it writable", + region.region_id, waited + ); + self.workers.notify_leader_lease_wait_ended(region); + } + /// Asks the worker to replay the pending tails of `region` if a role change made it /// writable. The worker may already have started an ALTER or an edit of the region. fn notify_if_became_writable(&self, region: &MitoRegionRef, was_writable: bool) { @@ -1765,11 +1782,20 @@ impl RegionEngine for MitoEngine { } if role == RegionRole::Leader { let was_writable = region.is_writable(); - let promoted = region + let promotion = region .manifest_ctx .promote_unless_downgrade_started_after(sent_at, region_id); self.inner.notify_if_became_writable(®ion, was_writable); - return Ok(promoted); + self.inner + .notify_if_leader_lease_wait_ended(®ion, promotion.ended_wait); + return Ok(promotion.promoted); + } + // The metasrv grants it to the leader of a region whose route is in staging, and it ends + // the wait for a Leader lease too. + if role == RegionRole::StagingLeader && region.manifest_ctx.awaits_leader_lease() { + let ended_wait = region.manifest_ctx.record_leader_lease(sent_at); + self.inner + .notify_if_leader_lease_wait_ended(®ion, ended_wait); } let previous = region.set_role(role); self.inner.notify_if_can_no_longer_replay(®ion, previous); diff --git a/src/mito2/src/engine/lease_test.rs b/src/mito2/src/engine/lease_test.rs index dcce6b57e1a..a0c280c104a 100644 --- a/src/mito2/src/engine/lease_test.rs +++ b/src/mito2/src/engine/lease_test.rs @@ -13,23 +13,30 @@ // limitations under the License. //! Tests that a region acknowledges only writes whose WAL append completed within its leader -//! lease, and that Leader grants for heartbeats sent before a downgrade do not make it writable -//! again. +//! lease, that Leader grants for heartbeats sent before a downgrade do not make it writable +//! again, and what a region a catchup made writable may commit before a later lease confirms it. use std::collections::HashMap; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use api::region::RegionResponse; +use api::v1::region::{StrictWindow, compact_request}; use api::v1::{ColumnSchema, Rows}; +use common_base::readable_size::ReadableSize; use common_error::ext::{BoxedError, ErrorExt}; +use common_error::status_code::StatusCode; use common_recordbatch::RecordBatches; use rstest::rstest; use rstest_reuse::apply; -use store_api::region_engine::{RegionEngine, RegionRole, SettableRegionRoleState}; +use store_api::region_engine::{ + RegionEngine, RegionRole, SetRegionRoleStateResponse, SettableRegionRoleState, +}; use store_api::region_request::{ - EnterStagingRequest, RegionCatchupRequest, RegionCloseRequest, RegionDropRequest, - RegionPutRequest, RegionRequest, StagingPartitionDirective, + EnterStagingRequest, RegionAlterRequest, RegionBuildIndexRequest, RegionCatchupRequest, + RegionCloseRequest, RegionCompactRequest, RegionDropRequest, RegionFlushRequest, + RegionPutRequest, RegionRequest, RegionTruncateRequest, StagingPartitionDirective, }; use store_api::storage::{RegionId, ScanRequest}; use tokio::task::JoinHandle; @@ -37,14 +44,29 @@ use tokio::task::JoinHandle; use crate::config::MitoConfig; use crate::engine::MitoEngine; use crate::engine::basic_test::build_bulk_insert_request; -use crate::engine::listener::WriteWalListener; +use crate::engine::index_build_test::async_build_mode_config; +use crate::engine::listener::{ + CountingStallListener, EventListener, EventListenerRef, WriteWalListener, +}; +use crate::engine::object_store_wal_test::wait_until; +use crate::engine::open_test::open_region_with_backfilled_partition_expr; +use crate::engine::pending_tail_test::add_field; +use crate::engine::staging_test::{ + enter_staging, first_file, float_range_expr, submit_staging_edit, +}; use crate::error::Error; +use crate::flush::FlushReason; use crate::lease::GrantedLease; +use crate::manifest::action::RegionEdit; +use crate::metrics::{FLUSH_FAILURE_TOTAL, FLUSH_REQUESTS_TOTAL}; use crate::region::{RegionLeaderState, RegionRoleState}; +use crate::request::{BackgroundNotify, BuildIndexRequest, WorkerRequest}; +use crate::sst::file::IndexType; +use crate::sst::index::IndexBuildType; use crate::test_util::{ - CreateRequestBuilder, LogStoreFactory, TestEnv, build_rows, kafka_log_store_factory, - multiple_log_store_factories, prepare_test_for_kafka_log_store, raft_engine_log_store_factory, - reopen_region, rows_schema, + CreateRequestBuilder, LogStoreFactory, TestEnv, build_rows, flush_region, + kafka_log_store_factory, multiple_log_store_factories, prepare_test_for_kafka_log_store, + put_rows, raft_engine_log_store_factory, reopen_region, rows_schema, }; const LEASE: Duration = Duration::from_secs(10); @@ -57,8 +79,20 @@ async fn create_region( topic: Option, ) -> (Arc, MitoEngine, Vec) { let listener = Arc::new(WriteWalListener::default()); + let (engine, schema) = + create_region_with_config(env, topic, MitoConfig::default(), listener.clone()).await; + (listener, engine, schema) +} + +/// As [create_region], on an engine of `config` with `listener`. +async fn create_region_with_config( + env: &mut TestEnv, + topic: Option, + config: MitoConfig, + listener: EventListenerRef, +) -> (MitoEngine, Vec) { let engine = env - .create_engine_with(MitoConfig::default(), None, Some(listener.clone()), None) + .create_engine_with(config, None, Some(listener), None) .await; engine.require_write_lease(); engine.freeze_lease_clock(Instant::now()); @@ -68,7 +102,7 @@ async fn create_region( .handle_request(REGION_ID, RegionRequest::Create(request)) .await .unwrap(); - (listener, engine, schema) + (engine, schema) } fn grant(engine: &MitoEngine, role: RegionRole, deadline: Instant) { @@ -496,3 +530,621 @@ async fn test_granted_lease_removed_on_engine_stop() { assert_eq!(granted_lease(&engine), None); } + +/// Demotes `region_id` on an engine whose writes need a lease and makes it writable again by a +/// catchup, after which it awaits its Leader lease. +pub(crate) async fn promote_to_await_leader_lease(engine: &MitoEngine, region_id: RegionId) { + engine + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower) + .await + .unwrap(); + // The lease the catchup seeds never runs out. + engine.freeze_lease_clock(Instant::now()); + engine.renew_node_lease(Instant::now() + LEASE); + catchup_region(engine, region_id).await.unwrap(); + let region = engine.get_region(region_id).unwrap(); + assert!(region.is_writable()); + assert!(region.manifest_ctx.awaits_leader_lease()); +} + +async fn catchup(engine: &MitoEngine) -> Result { + catchup_region(engine, REGION_ID).await +} + +async fn catchup_region( + engine: &MitoEngine, + region_id: RegionId, +) -> Result { + let request = RegionCatchupRequest { + set_writable: true, + ..Default::default() + }; + engine + .handle_request(region_id, RegionRequest::Catchup(request)) + .await +} + +fn add_field_request() -> RegionRequest { + RegionRequest::Alter(RegionAlterRequest { + kind: add_field(None), + }) +} + +async fn flush(engine: &MitoEngine) -> Result { + engine + .handle_request( + REGION_ID, + RegionRequest::Flush(RegionFlushRequest::default()), + ) + .await +} + +async fn manifest_files(engine: &MitoEngine) -> Vec { + let manifest = engine + .get_region(REGION_ID) + .unwrap() + .manifest_ctx + .manifest() + .await; + manifest.files.values().map(|file| file.num_rows).collect() +} + +fn lease_not_received(err: &Error) -> bool { + matches!(err, Error::RegionLeaseNotReceived { .. }) +} + +#[tokio::test] +async fn test_catchup_without_write_lease_does_not_await_leader_lease() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("catchup-without-write-lease").await; + let engine = env.create_engine(MitoConfig::default()).await; + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + engine + .handle_request(REGION_ID, RegionRequest::Create(request)) + .await + .unwrap(); + engine + .set_region_role_state_gracefully(REGION_ID, SettableRegionRoleState::Follower) + .await + .unwrap(); + catchup(&engine).await.unwrap(); + + let region = engine.get_region(REGION_ID).unwrap(); + assert!(region.is_writable()); + assert!(!region.manifest_ctx.awaits_leader_lease()); + put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); + flush(&engine).await.unwrap(); + assert_eq!(manifest_files(&engine).await, vec![3]); +} + +#[tokio::test] +async fn test_region_awaiting_leader_lease_flushes_after_it() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("catchup-flush-after-lease").await; + let (_listener, engine, schema) = create_region(&mut env, None).await; + let sent_before_catchup = Instant::now(); + promote_to_await_leader_lease(&engine, REGION_ID).await; + put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); + + let err = flush(&engine).await.unwrap_err(); + assert_eq!(err.status_code(), StatusCode::RegionBusy, "{err:?}"); + assert!(manifest_files(&engine).await.is_empty()); + + // A lease of a heartbeat sent before the catchup does not end the wait. + grant_at(&engine, RegionRole::Leader, sent_before_catchup, None); + assert!(flush(&engine).await.is_err()); + assert!(manifest_files(&engine).await.is_empty()); + + grant_at(&engine, RegionRole::Leader, Instant::now(), None); + flush(&engine).await.unwrap(); + assert_eq!(manifest_files(&engine).await, vec![3]); +} + +/// A change the region commits through its manifest is refused while it awaits its Leader +/// lease, and the region stays writable. +#[rstest] +#[case::alter(true)] +#[case::truncate(false)] +#[tokio::test] +async fn test_region_awaiting_leader_lease_commits_no_change(#[case] alter: bool) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("catchup-change-before-lease").await; + let (_listener, engine, _schema) = create_region(&mut env, None).await; + promote_to_await_leader_lease(&engine, REGION_ID).await; + let region = engine.get_region(REGION_ID).unwrap(); + let version = region.manifest_ctx.manifest_version().await; + let change = || match alter { + true => add_field_request(), + false => RegionRequest::Truncate(RegionTruncateRequest::All), + }; + + assert_retryable( + engine.handle_request(REGION_ID, change()).await, + lease_not_received, + ); + assert_eq!(region.manifest_ctx.manifest_version().await, version); + assert_eq!( + region.state(), + RegionRoleState::Leader(RegionLeaderState::Writable) + ); + + grant_at(&engine, RegionRole::Leader, Instant::now(), None); + engine.handle_request(REGION_ID, change()).await.unwrap(); + assert_eq!(region.manifest_ctx.manifest_version().await, version + 1); +} + +#[tokio::test] +async fn test_staging_leader_lease_ends_wait_for_leader_lease() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("staging-lease-ends-wait").await; + let (_listener, engine, schema) = create_region(&mut env, None).await; + promote_to_await_leader_lease(&engine, REGION_ID).await; + put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); + + grant_at(&engine, RegionRole::StagingLeader, Instant::now(), None); + + let region = engine.get_region(REGION_ID).unwrap(); + assert!(!region.manifest_ctx.awaits_leader_lease()); + // The lease does not change the role of a writable leader. + assert_eq!( + region.state(), + RegionRoleState::Leader(RegionLeaderState::Writable) + ); + flush(&engine).await.unwrap(); + assert_eq!(manifest_files(&engine).await, vec![3]); +} + +/// ALTER and EnterStaging flush the rows first, which a region that awaits its Leader lease +/// cannot commit, so they start no flush. +#[rstest] +#[case::alter(FlushReason::Alter)] +#[case::enter_staging(FlushReason::EnterStaging)] +#[tokio::test] +async fn test_ddl_flush_refused_awaiting_leader_lease(#[case] reason: FlushReason) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("ddl-flush-awaiting-lease").await; + let (_listener, engine, schema) = create_region(&mut env, None).await; + promote_to_await_leader_lease(&engine, REGION_ID).await; + put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); + let request = || match reason { + FlushReason::Alter => add_field_request(), + _ => RegionRequest::EnterStaging(EnterStagingRequest { + partition_directive: StagingPartitionDirective::RejectAllWrites, + }), + }; + let reason_label: &'static str = (&reason).into(); + let flushes = || { + FLUSH_REQUESTS_TOTAL + .with_label_values(&[reason_label]) + .get() + }; + let before = flushes(); + + assert_retryable( + engine.handle_request(REGION_ID, request()).await, + lease_not_received, + ); + assert_eq!(flushes(), before); + assert!(manifest_files(&engine).await.is_empty()); + + grant_at(&engine, RegionRole::Leader, Instant::now(), None); + engine.handle_request(REGION_ID, request()).await.unwrap(); + assert_eq!(flushes(), before + 1); + assert_eq!(manifest_files(&engine).await, vec![3]); +} + +/// A close of a region that awaits its Leader lease, such as the close of a shutdown, keeps rows +/// that are not in the WAL: it flushes them as a downgrade does. Rows in the WAL need no flush. +#[rstest] +#[case::wal_rows(false, false)] +#[case::flush_on_close(false, true)] +#[case::skip_wal_rows(true, false)] +#[tokio::test] +async fn test_close_of_region_awaiting_leader_lease_keeps_rows( + #[case] skip_wal: bool, + #[case] flush_on_close: bool, +) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("close-awaiting-lease").await; + let (_listener, engine, schema) = create_region(&mut env, None).await; + promote_to_await_leader_lease(&engine, REGION_ID).await; + let mut request = put_request(&schema, 0); + if let RegionRequest::Put(put) = &mut request { + put.skip_wal = skip_wal; + } + engine.handle_request(REGION_ID, request).await.unwrap(); + + let close = RegionRequest::Close(RegionCloseRequest { flush_on_close }); + engine.handle_request(REGION_ID, close).await.unwrap(); + assert!(engine.get_region(REGION_ID).is_none()); + + let engine = env.reopen_engine(engine, MitoConfig::default()).await; + let table_dir = CreateRequestBuilder::new().build().table_dir; + reopen_region(&engine, REGION_ID, table_dir, false, HashMap::new()).await; + let flushed = skip_wal || flush_on_close; + assert_eq!(manifest_files(&engine).await.len(), usize::from(flushed)); + assert_eq!(count_rows(&engine).await, 3); +} + +#[tokio::test] +async fn test_staging_of_region_awaiting_leader_lease_ends_after_lease() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("end-staging-awaiting-lease").await; + let (_listener, engine, schema) = create_region(&mut env, None).await; + grant(&engine, RegionRole::Leader, Instant::now() + LEASE); + put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); + flush(&engine).await.unwrap(); + promote_to_await_leader_lease(&engine, REGION_ID).await; + // Staged changes stay in memory, which a region that awaits its Leader lease may do. + enter_staging(&engine, REGION_ID).await; + let region = engine.get_region(REGION_ID).unwrap(); + submit_staging_edit( + &engine, + REGION_ID, + first_file(®ion).await, + float_range_expr("field_0", 0., 100.).as_json_str().unwrap(), + ) + .await + .unwrap(); + let version = region.manifest_ctx.manifest_version().await; + let end_staging = + || engine.set_region_role_state_gracefully(REGION_ID, SettableRegionRoleState::Leader); + + let SetRegionRoleStateResponse::InvalidTransition(err) = end_staging().await.unwrap() else { + panic!("the end of staging must fail before the Leader lease"); + }; + let err = err.into_inner(); + assert!( + lease_not_received(err.as_any().downcast_ref::().unwrap()), + "{err:?}" + ); + assert!(region.is_staging()); + assert_eq!(region.manifest_ctx.manifest_version().await, version); + + grant_at(&engine, RegionRole::StagingLeader, Instant::now(), None); + assert!(matches!( + end_staging().await.unwrap(), + SetRegionRoleStateResponse::Success(_) + )); + assert!(!region.is_staging()); + assert!(region.manifest_ctx.manifest_version().await > version); +} + +#[tokio::test] +async fn test_downgrade_flushes_region_awaiting_leader_lease() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("downgrade-awaiting-lease").await; + let (_listener, engine, schema) = create_region(&mut env, None).await; + promote_to_await_leader_lease(&engine, REGION_ID).await; + // Rows that are not in the WAL survive the migration only through the downgrade's flush. + let mut request = put_request(&schema, 0); + if let RegionRequest::Put(put) = &mut request { + put.skip_wal = true; + } + engine.handle_request(REGION_ID, request).await.unwrap(); + + engine + .set_region_role_state_gracefully(REGION_ID, SettableRegionRoleState::DowngradingLeader) + .await + .unwrap(); + assert!( + engine + .get_region(REGION_ID) + .unwrap() + .manifest_ctx + .awaits_leader_lease() + ); + flush(&engine).await.unwrap(); + + assert_eq!(manifest_files(&engine).await, vec![3]); +} + +/// Opens a region whose opener filled in the partition expression its manifest lacks and makes +/// it writable by a catchup, after which it awaits its Leader lease. Returns the engine and the +/// expression. +async fn catchup_region_with_backfill( + env: &mut TestEnv, + listener: Option, +) -> (MitoEngine, String) { + let (engine, expr_json, _) = + open_region_with_backfilled_partition_expr(env, REGION_ID, listener).await; + engine.require_write_lease(); + engine.freeze_lease_clock(Instant::now()); + engine.renew_node_lease(Instant::now() + LEASE); + catchup(&engine).await.unwrap(); + // The catchup cannot commit it before the Leader lease. + assert_eq!(persisted_partition_expr(&engine).await, None); + (engine, expr_json) +} + +async fn persisted_partition_expr(engine: &MitoEngine) -> Option { + let region = engine.get_region(REGION_ID).unwrap(); + region + .manifest_ctx + .manifest() + .await + .metadata + .partition_expr + .clone() +} + +async fn wait_persisted_partition_expr(engine: &MitoEngine) -> String { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(expr) = persisted_partition_expr(engine).await { + return expr; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap() +} + +#[rstest] +#[case::leader(RegionRole::Leader)] +#[case::staging_leader(RegionRole::StagingLeader)] +#[tokio::test] +async fn test_leader_lease_after_catchup_persists_backfilled_partition_expr( + #[case] role: RegionRole, +) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("lease-persists-backfill").await; + let (engine, expr_json) = catchup_region_with_backfill(&mut env, None).await; + + grant_at(&engine, role, Instant::now(), None); + + assert_eq!(wait_persisted_partition_expr(&engine).await, expr_json); +} + +/// Counts the ends of a region's wait for its Leader lease, once the worker handled them, and +/// the persisting of backfilled metadata the worker spawned. +#[derive(Default)] +struct LeaseWaitEndedListener { + wait_ends: AtomicUsize, + backfill_persists: AtomicUsize, +} + +#[async_trait::async_trait] +impl EventListener for LeaseWaitEndedListener { + fn on_leader_lease_wait_ended(&self, _region_id: RegionId) { + // Releases the persist count recorded before it, which the test acquires with `wait_ends`. + self.wait_ends.fetch_add(1, Ordering::Release); + } + + fn on_persist_backfilled_metadata_begin(&self, _region_id: RegionId) { + self.backfill_persists.fetch_add(1, Ordering::Relaxed); + } +} + +impl LeaseWaitEndedListener { + async fn wait_for_end(&self) { + wait_until(|| self.wait_ends.load(Ordering::Acquire) != 0).await; + } +} + +/// A Follower or DowngradingLeader lease during the wait leaves the region waiting. The next +/// Leader lease promotes it and ends the wait, after which the worker persists the backfilled +/// metadata once. +#[rstest] +#[case::follower(RegionRole::Follower)] +#[case::downgrading_leader(RegionRole::DowngradingLeader)] +#[tokio::test] +async fn test_leader_lease_after_demotion_ends_wait(#[case] role: RegionRole) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("lease-after-demotion").await; + let listener = Arc::new(LeaseWaitEndedListener::default()); + let (engine, expr_json) = catchup_region_with_backfill(&mut env, Some(listener.clone())).await; + let region = engine.get_region(REGION_ID).unwrap(); + + grant_at(&engine, role, Instant::now(), None); + assert!(!region.is_writable()); + assert!(region.manifest_ctx.awaits_leader_lease()); + + grant_at(&engine, RegionRole::Leader, Instant::now(), None); + assert!(region.is_writable()); + listener.wait_for_end().await; + assert_eq!(listener.backfill_persists.load(Ordering::Relaxed), 1); + assert_eq!(wait_persisted_partition_expr(&engine).await, expr_json); +} + +/// A lease that finds the region in the middle of a change persists no backfilled metadata. +#[tokio::test] +async fn test_leader_lease_during_change_persists_no_backfill() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("lease-during-change-backfill").await; + let listener = Arc::new(LeaseWaitEndedListener::default()); + let (engine, _) = catchup_region_with_backfill(&mut env, Some(listener.clone())).await; + let region = engine.get_region(REGION_ID).unwrap(); + region.set_editing(RegionLeaderState::Writable).unwrap(); + + grant_at(&engine, RegionRole::Leader, Instant::now(), None); + listener.wait_for_end().await; + + // The worker reports the persisting as it spawns it, and the end of the wait after. + assert_eq!(listener.backfill_persists.load(Ordering::Relaxed), 0); + region.switch_state_to_writable(RegionLeaderState::Editing); + assert_eq!(persisted_partition_expr(&engine).await, None); +} + +/// The replayed and new rows of a region that awaits its Leader lease stay in its memtable until +/// the lease ends the wait. A write the engine's full buffer stalls completes after the lease +/// with no other write; a write the region's own buffer would stall is rejected, since only the +/// lease could release it. +#[rstest] +#[case::engine_full(FlushReason::EngineFull)] +#[case::region_full(FlushReason::RegionFull)] +#[tokio::test] +async fn test_full_write_buffer_waits_for_leader_lease_to_flush(#[case] reason: FlushReason) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("full-buffer-awaiting-lease").await; + let engine_full = reason == FlushReason::EngineFull; + let config = if engine_full { + // Any row fills it. + MitoConfig { + global_write_buffer_size: ReadableSize(1), + global_write_buffer_reject_size: ReadableSize::mb(64), + ..Default::default() + } + } else { + // One put of three rows (167 bytes) fills it. + MitoConfig { + default_region_write_buffer_size: ReadableSize(100), + ..Default::default() + } + }; + let listener = Arc::new(CountingStallListener::default()); + let (engine, schema) = + create_region_with_config(&mut env, None, config, listener.clone()).await; + promote_to_await_leader_lease(&engine, REGION_ID).await; + put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); + let flush_failures = FLUSH_FAILURE_TOTAL.get(); + let reason_label: &'static str = (&reason).into(); + let reason_flushes = || { + FLUSH_REQUESTS_TOTAL + .with_label_values(&[reason_label]) + .get() + }; + let flushes = reason_flushes(); + + // The buffer is full and the region starts no flush to free it. + let second = put(&engine, REGION_ID, &schema, 3); + let stalled = if engine_full { + tokio::time::timeout(Duration::from_secs(10), listener.wait_for_count(1)) + .await + .unwrap(); + assert!(!second.is_finished()); + Some(second) + } else { + let err = tokio::time::timeout(Duration::from_secs(10), second) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(err.status_code(), StatusCode::StorageUnavailable, "{err:?}"); + None + }; + assert_eq!(reason_flushes(), flushes); + assert!(manifest_files(&engine).await.is_empty()); + + // The lease starts the flush. Its completion releases a stalled write, and frees the + // region's buffer for the write it rejected. + grant_at(&engine, RegionRole::Leader, Instant::now(), None); + if let Some(stalled) = stalled { + tokio::time::timeout(Duration::from_secs(10), stalled) + .await + .unwrap() + .unwrap() + .unwrap(); + } else { + tokio::time::timeout(Duration::from_secs(10), async { + while manifest_files(&engine).await.is_empty() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + put(&engine, REGION_ID, &schema, 3).await.unwrap().unwrap(); + } + // The released write may fill the buffer and start another flush. + assert!(reason_flushes() > flushes); + assert!(!manifest_files(&engine).await.is_empty()); + assert_eq!(FLUSH_FAILURE_TOTAL.get(), flush_failures); +} + +#[tokio::test] +async fn test_compaction_skipped_awaiting_leader_lease() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("compaction-awaiting-lease").await; + let (_listener, engine, schema) = create_region(&mut env, None).await; + grant(&engine, RegionRole::Leader, Instant::now() + LEASE); + for start in [0, 3] { + put(&engine, REGION_ID, &schema, start) + .await + .unwrap() + .unwrap(); + flush(&engine).await.unwrap(); + } + promote_to_await_leader_lease(&engine, REGION_ID).await; + let compact = || { + RegionRequest::Compact(RegionCompactRequest { + options: compact_request::Options::StrictWindow(StrictWindow { window_seconds: 0 }), + ..Default::default() + }) + }; + + engine.handle_request(REGION_ID, compact()).await.unwrap(); + assert_eq!(manifest_files(&engine).await.len(), 2); + + grant_at(&engine, RegionRole::Leader, Instant::now(), None); + engine.handle_request(REGION_ID, compact()).await.unwrap(); + assert_eq!(manifest_files(&engine).await, vec![6]); +} + +/// An index build retry that the wait refuses is built when the lease ends the wait, also for a +/// file that the lease-end pass leaves since its writer built an extension index. +#[tokio::test] +async fn test_index_build_retry_refused_awaiting_leader_lease_runs_after_it() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("index-retry-awaiting-lease").await; + let engine = env + .create_engine_with(async_build_mode_config(false), None, None, None) + .await; + engine.require_write_lease(); + engine.freeze_lease_clock(Instant::now()); + let request = CreateRequestBuilder::new().build_with_index(); + let schema = rows_schema(&request); + engine + .handle_request(REGION_ID, RegionRequest::Create(request)) + .await + .unwrap(); + grant(&engine, RegionRole::Leader, Instant::now() + LEASE); + let rows = Rows { + schema, + rows: build_rows(0, 3), + }; + put_rows(&engine, REGION_ID, rows).await; + flush_region(&engine, REGION_ID, None).await; + let region = engine.get_region(REGION_ID).unwrap(); + let mut files = region.all_manifest_files().await.0; + files[0].available_indexes.push(IndexType::HllIndex); + let edit = RegionEdit { + files_to_add: files.clone(), + ..Default::default() + }; + engine.edit_region(REGION_ID, edit).await.unwrap(); + promote_to_await_leader_lease(&engine, REGION_ID).await; + + // What a publication that found the schema changed sends. + let notify = BackgroundNotify::IndexBuildRetry(BuildIndexRequest { + region_id: REGION_ID, + build_type: IndexBuildType::Manual, + file_metas: files, + result_senders: Vec::new(), + }); + let request = WorkerRequest::Background { + region_id: REGION_ID, + notify, + }; + let workers = &engine.inner.workers; + workers.submit_to_worker(REGION_ID, request).await.unwrap(); + // The worker handled the retry before this request. + let build = RegionRequest::BuildIndex(RegionBuildIndexRequest::default()); + assert_retryable( + engine.handle_request(REGION_ID, build).await, + lease_not_received, + ); + let has_inverted_index = || { + let version = engine.get_region(REGION_ID).unwrap().version(); + version.ssts.levels()[0].files.values().any(|file| { + file.meta_ref() + .available_indexes + .contains(&IndexType::InvertedIndex) + }) + }; + assert!(!has_inverted_index()); + + grant_at(&engine, RegionRole::Leader, Instant::now(), None); + wait_until(has_inverted_index).await; +} diff --git a/src/mito2/src/engine/listener.rs b/src/mito2/src/engine/listener.rs index c89bdeb5c5f..b615e315ec1 100644 --- a/src/mito2/src/engine/listener.rs +++ b/src/mito2/src/engine/listener.rs @@ -38,6 +38,14 @@ pub trait EventListener: Send + Sync { /// Notifies the listener before a catchup reopens the region. async fn on_catchup_reopen_begin(&self, _region_id: RegionId) {} + /// Notifies the listener after the worker handled the end of the region's wait for its + /// Leader lease. + fn on_leader_lease_wait_ended(&self, _region_id: RegionId) {} + + /// Notifies the listener when the worker spawns the persisting of the region's backfilled + /// metadata. + fn on_persist_backfilled_metadata_begin(&self, _region_id: RegionId) {} + /// Notifies the listener before a tail replay commits its result. async fn on_tail_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 8aaf938e296..72cb8d07812 100644 --- a/src/mito2/src/engine/object_store_wal_recovery_test.rs +++ b/src/mito2/src/engine/object_store_wal_recovery_test.rs @@ -2306,12 +2306,17 @@ async fn wait_for_pressure_admission( /// Exercises the production threshold, worker timers, flush and WAL release. /// Both regions pin the oldest object and belong to different workers. +/// With `awaiting_leader_lease`, region A is a writable leader that awaits its Leader lease. #[rstest] -#[case::writable(RegionRoleState::Leader(RegionLeaderState::Writable))] -#[case::follower(RegionRoleState::Follower)] -#[case::staging(RegionRoleState::Leader(RegionLeaderState::Staging))] +#[case::writable(RegionRoleState::Leader(RegionLeaderState::Writable), false)] +#[case::follower(RegionRoleState::Follower, false)] +#[case::staging(RegionRoleState::Leader(RegionLeaderState::Staging), false)] +#[case::awaiting_leader_lease(RegionRoleState::Leader(RegionLeaderState::Writable), true)] #[tokio::test] -async fn test_wal_pressure_flushes_blockers_across_workers(#[case] state: RegionRoleState) { +async fn test_wal_pressure_flushes_blockers_across_workers( + #[case] state: RegionRoleState, + #[case] awaiting_leader_lease: bool, +) { use crate::time_provider::mock::MockTimeProvider; let mut env = TestEnv::new().await; @@ -2423,8 +2428,18 @@ async fn test_wal_pressure_flushes_blockers_across_workers(#[case] state: Region RegionRoleState::Leader(RegionLeaderState::Writable) => {} _ => unreachable!(), } + let lease_deadline = std::time::Instant::now() + Duration::from_secs(600); + if awaiting_leader_lease { + region(&engine, REGION_B) + .manifest_ctx + .leader_deadline + .extend(lease_deadline); + region_a + .manifest_ctx + .start_leader_lease_wait_for_test(REGION_A); + } clock.set_now(now + 240_000); - if state != RegionRoleState::Leader(RegionLeaderState::Writable) { + if state != RegionRoleState::Leader(RegionLeaderState::Writable) || awaiting_leader_lease { // 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); @@ -2445,6 +2460,17 @@ async fn test_wal_pressure_flushes_blockers_across_workers(#[case] state: Region assert_eq!(vec![REGION_A], store.flush_candidates()); if region_a.is_staging() { region_a.exit_staging().unwrap(); + } else if awaiting_leader_lease { + let sent_at = std::time::Instant::now(); + engine + .set_region_role_with_lease( + REGION_A, + RegionRole::Leader, + sent_at, + lease_deadline, + None, + ) + .unwrap(); } else { engine .set_region_role(REGION_A, RegionRole::Leader) diff --git a/src/mito2/src/engine/object_store_wal_test.rs b/src/mito2/src/engine/object_store_wal_test.rs index 2b64acaa389..bfea7a07290 100644 --- a/src/mito2/src/engine/object_store_wal_test.rs +++ b/src/mito2/src/engine/object_store_wal_test.rs @@ -55,7 +55,9 @@ use tokio::sync::{Notify, oneshot}; use crate::config::MitoConfig; use crate::engine::MitoEngine; +use crate::engine::lease_test::promote_to_await_leader_lease; use crate::engine::listener::{EventListener, FlushCancellationListener}; +use crate::engine::open_test::new_dummy_fetcher; use crate::engine::region_hook::{RegionHook, RegionHookRef}; use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList}; use crate::manifest::storage::{delta_file, gen_path, manifest_dir}; @@ -536,20 +538,36 @@ pub(crate) async fn count_ssts(store: &ObjectStore, region_dir: &str) -> usize { .count() } +/// A commit is stale because the Leader deadline of its writer passes while it is written, or, +/// with `awaiting_leader_lease`, because a catchup made its writer writable and no Leader lease +/// confirmed it; the cases cover the commits such a writer still makes: the flushes of its +/// downgrade and of its close. #[rstest] -#[case::flush(RegionRequest::Flush(RegionFlushRequest::default()), 1)] +#[case::flush(RegionRequest::Flush(RegionFlushRequest::default()), 1, false)] #[case::compaction( RegionRequest::Compact(RegionCompactRequest { options: compact_request::Options::StrictWindow(StrictWindow { window_seconds: 3600 }), ..Default::default() }), - 1 + 1, + false +)] +#[case::truncate(RegionRequest::Truncate(RegionTruncateRequest::All), 0, false)] +#[case::downgrade_flush_awaiting_leader_lease( + RegionRequest::Flush(RegionFlushRequest::default()), + 1, + true +)] +#[case::close_flush_awaiting_leader_lease( + RegionRequest::Close(RegionCloseRequest { flush_on_close: true }), + 1, + true )] -#[case::truncate(RegionRequest::Truncate(RegionTruncateRequest::All), 0)] #[tokio::test] async fn test_stale_commit_on_deleted_delta_name_conflicts( #[case] commit: RegionRequest, #[case] new_ssts: usize, + #[case] awaiting_leader_lease: bool, ) { common_telemetry::init_default_ut_logging(); // The creation is version 0 and the flushes below are versions 1 and 2. @@ -569,7 +587,17 @@ async fn test_stale_commit_on_deleted_delta_name_conflicts( put_rows(&old_leader, region_id, rows(start)).await; flush_region(&old_leader, region_id, None).await; } + if awaiting_leader_lease { + promote_to_await_leader_lease(&old_leader, region_id).await; + } put_rows(&old_leader, region_id, rows(6)).await; + // A close turns the region downgrading itself. + if awaiting_leader_lease && !matches!(commit, RegionRequest::Close(_)) { + old_leader + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::DowngradingLeader) + .await + .unwrap(); + } let region = old_leader.get_region(region_id).unwrap(); let (manifest, checkpoint) = { @@ -614,7 +642,22 @@ async fn test_stale_commit_on_deleted_delta_name_conflicts( } } - old_leader.freeze_lease_clock(deadline); + if awaiting_leader_lease { + assert!(region.manifest_ctx.awaits_leader_lease()); + // A lease that ends the wait during the write does not lift the check. + old_leader + .set_region_role_with_lease( + region_id, + RegionRole::StagingLeader, + Instant::now(), + deadline, + None, + ) + .unwrap(); + assert!(!region.manifest_ctx.awaits_leader_lease()); + } else { + old_leader.freeze_lease_clock(deadline); + } blocker.release(); let error = commit.await.unwrap().unwrap_err(); assert!(error.retry_hint().is_retryable(), "{error:?}"); @@ -1177,6 +1220,66 @@ async fn test_conflict_reloads_region() { assert!(!engine.is_region_catching_up(region_id)); } +/// The persisting of backfilled metadata that the end of a wait for the Leader lease spawns +/// outside the worker asks the worker to reload the region it fenced on a newer manifest. +#[tokio::test] +async fn test_conflicting_backfill_asks_for_reload() { + let region_id = RegionId::new(1, 1); + let expr = r#"{"Expr":{"lhs":{"Column":"a"},"op":"GtEq","rhs":{"Value":{"UInt32":10}}}}"#; + let mut env = TestEnv::with_prefix("backfill-conflict-reload") + .await + .with_partition_expr_fetcher(new_dummy_fetcher(region_id, expr.to_string())); + let (engine, _log_store) = new_engine(&mut env).await; + engine.require_write_lease(); + engine.freeze_lease_clock(Instant::now()); + let request = CreateRequestBuilder::new() + .insert_option(WAL_OPTIONS_KEY, &wal_options()[WAL_OPTIONS_KEY]) + .partition_expr_json(None) + .build(); + let table_dir = request.table_dir.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + close_region(&engine, region_id).await; + let open = RegionRequest::Open(open_request(table_dir.clone())); + engine.handle_request(region_id, open).await.unwrap(); + let now = Instant::now(); + engine + .set_region_role_with_lease( + region_id, + RegionRole::Leader, + now, + now + Duration::from_secs(10), + None, + ) + .unwrap(); + 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 (sender, mut receiver) = tokio::sync::mpsc::channel(1); + + crate::worker::persist_backfilled_metadata_and_notify_if_fenced(&sender, ®ion).await; + + assert!(region.manifest_ctx.is_reload_pending()); + let request = receiver.try_recv().unwrap().request; + assert!(matches!( + request, + WorkerRequest::Background { + region_id: notified, + notify: BackgroundNotify::RegionFenced, + } if notified == region_id + )); +} + #[tokio::test] async fn test_reload_waits_for_held_upload() { let mut env = TestEnv::with_prefix("reload-waits-for-upload").await; diff --git a/src/mito2/src/engine/open_test.rs b/src/mito2/src/engine/open_test.rs index 32bd9dea335..b14f29c7bf2 100644 --- a/src/mito2/src/engine/open_test.rs +++ b/src/mito2/src/engine/open_test.rs @@ -35,8 +35,9 @@ use tokio::sync::{Notify, oneshot}; use crate::compaction::compactor::{CompactionRegionOpener, OpenCompactionRegionRequest}; use crate::config::MitoConfig; +use crate::engine::MitoEngine; use crate::engine::flush_test::MockRegionHook; -use crate::engine::listener::EventListener; +use crate::engine::listener::{EventListener, EventListenerRef}; use crate::engine::region_hook::RegionHookRef; use crate::error; use crate::region::opener::{PartitionExprFetcher, PartitionExprFetcherRef}; @@ -1173,7 +1174,7 @@ async fn test_compaction_region_opens_preserve_live_index_files() { } /// Returns a dummy fetcher that returns the expr_json only once. -fn new_dummy_fetcher(region_id: RegionId, expr_json: String) -> PartitionExprFetcherRef { +pub(crate) fn new_dummy_fetcher(region_id: RegionId, expr_json: String) -> PartitionExprFetcherRef { struct DummyFetcher { region_id: RegionId, expr_json: String, @@ -1198,22 +1199,19 @@ fn new_dummy_fetcher(region_id: RegionId, expr_json: String) -> PartitionExprFet }) } -#[rstest::rstest] -#[case::from_writable(false)] -#[case::after_empty_staging(true)] -#[tokio::test] -async fn test_open_backfills_partition_expr_with_fetcher(#[case] staging: bool) { - let mut env = TestEnv::with_prefix("open-backfill-fetcher").await; - - // prepare plugins with dummy fetcher - let region_id = RegionId::new(100, 1); +/// Creates `region_id` without a partition expression, as a table created before the manifest +/// stored it, and reopens it on an engine whose fetcher fills the expression in and that reports +/// to `listener`. Returns the engine, the expression and the table directory. +pub(crate) async fn open_region_with_backfilled_partition_expr( + env: &mut TestEnv, + region_id: RegionId, + listener: Option, +) -> (MitoEngine, String, String) { let expr_json = r#"{\"Expr\":{\"lhs\":{\"Column\":\"a\"},\"op\":\"GtEq\",\"rhs\":{\"Value\":{\"UInt32\":10}}}}"#.to_string(); let fetcher = new_dummy_fetcher(region_id, expr_json.clone()); let engine = env - .create_engine_with(MitoConfig::default(), None, None, Some(fetcher)) + .create_engine_with(MitoConfig::default(), None, listener, Some(fetcher)) .await; - - // create region with partition_expr=None (legacy style) let request = CreateRequestBuilder::new() .table_dir("t") .partition_expr_json(None) @@ -1222,11 +1220,9 @@ async fn test_open_backfills_partition_expr_with_fetcher(#[case] staging: bool) .handle_request(region_id, RegionRequest::Create(request.clone())) .await .unwrap(); - let meta = engine.get_region(region_id).unwrap().metadata(); assert!(meta.partition_expr.is_none()); - // close and reopen to trigger backfill in opener engine .handle_request( region_id, @@ -1249,10 +1245,20 @@ async fn test_open_backfills_partition_expr_with_fetcher(#[case] staging: bool) ) .await .unwrap(); - - // verify partition_expr is backfilled and persisted let meta = engine.get_region(region_id).unwrap().metadata(); assert_eq!(meta.partition_expr.as_deref(), Some(expr_json.as_str())); + (engine, expr_json, request.table_dir) +} + +#[rstest::rstest] +#[case::from_writable(false)] +#[case::after_empty_staging(true)] +#[tokio::test] +async fn test_open_backfills_partition_expr_with_fetcher(#[case] staging: bool) { + let mut env = TestEnv::with_prefix("open-backfill-fetcher").await; + let region_id = RegionId::new(100, 1); + let (engine, expr_json, table_dir) = + open_region_with_backfilled_partition_expr(&mut env, region_id, None).await; // Set leader and trigger backfill engine @@ -1294,7 +1300,7 @@ async fn test_open_backfills_partition_expr_with_fetcher(#[case] staging: bool) region_id, RegionRequest::Open(RegionOpenRequest { engine: String::new(), - table_dir: request.table_dir.clone(), + table_dir, path_type: PathType::Bare, options: HashMap::default(), skip_wal_replay: false, diff --git a/src/mito2/src/engine/region_hook.rs b/src/mito2/src/engine/region_hook.rs index ff52553b18f..dfacfaa03ca 100644 --- a/src/mito2/src/engine/region_hook.rs +++ b/src/mito2/src/engine/region_hook.rs @@ -121,14 +121,17 @@ //! tail replay task), immediately after SST files are written but **before** the manifest //! is committed. //! -//! `on_manifest_updated` is funneled through [`ManifestContext::update_locked`], -//! which calls the low-level [`RegionManifestManager::update_with_verification`] +//! `on_manifest_updated` is funneled through the shared write that +//! [`ManifestContext::update_locked`] makes after it checks the Leader lease; the +//! write calls the low-level [`RegionManifestManager::update_with_verification`] //! and packages each successful write into a [`PendingManifestHook`]. The caller //! owns the write lock, drops it, and *then* fires the receipt — the hook must //! never run under the lock. [`ManifestContext::update_manifest`] is the common //! case: it acquires the lock, delegates to `update_locked`, and fires the -//! receipt in one go. Multi-step sequences (staging-exit, role-state backfill) -//! call `update_locked` directly under their own held guard. +//! receipt in one go. The role-state backfill and the table-compaction publication +//! call `update_locked` directly under their own held guard; a replay of pending +//! tails makes the same write without the Leader lease check, and the end of +//! staging builds its receipt in `commit_staged_locked`. //! //! Non-logical writes (GC, staging bookkeeping) call the manager's own methods //! directly and intentionally do not fire the hook. @@ -171,7 +174,8 @@ use crate::sst::file::{FileMeta, RegionFileId}; use crate::sst::parquet::SstInfo; /// A deferred [`RegionHook::on_manifest_updated`] notification produced by a -/// logical manifest write via [`ManifestContext::update_locked`](crate::region::ManifestContext::update_locked). +/// logical manifest write via [`ManifestContext::update_locked`](crate::region::ManifestContext::update_locked), +/// a replay of pending tails or the end of staging. /// /// Must be [`fire`](Self::fire)d **after** the manifest write lock is released /// (the hook may read the manifest). `#[must_use]` so a forgotten receipt warns. diff --git a/src/mito2/src/engine/staging_test.rs b/src/mito2/src/engine/staging_test.rs index 1cce6d85ee9..5248ee5f44f 100644 --- a/src/mito2/src/engine/staging_test.rs +++ b/src/mito2/src/engine/staging_test.rs @@ -52,6 +52,7 @@ use store_api::storage::{FileId, RegionId, ScanRequest}; use crate::config::MitoConfig; use crate::engine::MitoEngine; use crate::engine::basic_test::build_bulk_insert_request; +use crate::engine::lease_test::promote_to_await_leader_lease; use crate::engine::listener::{ CountingStallListener, EventListener, FlushListener, NotifyEnterStagingResultListener, }; @@ -78,7 +79,7 @@ fn range_expr(col_name: &str, start: i64, end: i64) -> PartitionExpr { .and(col(col_name).lt(Value::Int64(end))) } -fn float_range_expr(col_name: &str, start: f64, end: f64) -> PartitionExpr { +pub(crate) fn float_range_expr(col_name: &str, start: f64, end: f64) -> PartitionExpr { col(col_name) .gt_eq(Value::Float64(start.into())) .and(col(col_name).lt(Value::Float64(end.into()))) @@ -1437,7 +1438,7 @@ async fn test_enter_staging_clean_staging_manifest_error_with_format(flat_format test_enter_staging_error(&mut env, flat_format).await; } -async fn enter_staging(engine: &MitoEngine, region_id: RegionId) { +pub(crate) async fn enter_staging(engine: &MitoEngine, region_id: RegionId) { engine .handle_request( region_id, @@ -1534,7 +1535,7 @@ async fn put_range_skip_wal( } /// Returns one of the files in the region's manifest. -async fn first_file(region: &MitoRegionRef) -> FileMeta { +pub(crate) async fn first_file(region: &MitoRegionRef) -> FileMeta { let manifest = region.manifest_ctx.manifest().await; manifest.files.values().next().unwrap().as_ref().clone() } @@ -1661,8 +1662,13 @@ async fn test_memory_pressure_keeps_staging_rows_after_rollback() { assert_eq!(5, count_rows(&engine, staging_region_id).await); } +/// The periodic flush skips a staging region and, with `awaiting_leader_lease`, a region that +/// awaits its Leader lease instead: either defers its flush. +#[rstest::rstest] +#[case::staging(false)] +#[case::awaiting_leader_lease(true)] #[tokio::test] -async fn test_periodic_flush_skips_staging_region() { +async fn test_periodic_flush_skips_region_deferring_flush(#[case] awaiting_leader_lease: bool) { let listener = Arc::new(FlushListener::default()); let now = current_time_millis(); let time_provider = Arc::new(MockTimeProvider::new(now)); @@ -1679,11 +1685,30 @@ async fn test_periodic_flush_skips_staging_region() { time_provider.clone(), ) .await; - let staging_region_id = RegionId::new(1024, 0); + let deferring_region_id = RegionId::new(1024, 0); let writable_region_id = RegionId::new(1024, 1); - let (schema, _) = create_staging_region(&engine, staging_region_id).await; + let schema = if awaiting_leader_lease { + create_writable_region(&engine, deferring_region_id).await; + engine.require_write_lease(); + promote_to_await_leader_lease(&engine, deferring_region_id).await; + rows_schema(&CreateRequestBuilder::new().build()) + } else { + create_staging_region(&engine, deferring_region_id).await.0 + }; create_writable_region(&engine, writable_region_id).await; - put_range(&engine, staging_region_id, &schema, (0, 3)).await; + if awaiting_leader_lease { + let deadline = std::time::Instant::now() + Duration::from_secs(60); + engine + .set_region_role_with_lease( + writable_region_id, + RegionRole::Leader, + std::time::Instant::now(), + deadline, + None, + ) + .unwrap(); + } + put_range(&engine, deferring_region_id, &schema, (0, 3)).await; put_range(&engine, writable_region_id, &schema, (0, 3)).await; time_provider.set_now(now + 600_000); @@ -1693,7 +1718,7 @@ async fn test_periodic_flush_skips_staging_region() { .unwrap(); assert_eq!((1, 0), scan_inputs(&engine, writable_region_id).await); - assert_unflushed(&engine, staging_region_id).await; + assert_unflushed(&engine, deferring_region_id).await; } #[tokio::test] @@ -2234,7 +2259,7 @@ async fn test_stale_staging_edit_rejected_after_close_time_flush_fails() { ); } -async fn submit_staging_edit( +pub(crate) async fn submit_staging_edit( engine: &MitoEngine, region_id: RegionId, file: FileMeta, diff --git a/src/mito2/src/engine/table_compaction/tests.rs b/src/mito2/src/engine/table_compaction/tests.rs index cb98f54ef40..290f62b47d7 100644 --- a/src/mito2/src/engine/table_compaction/tests.rs +++ b/src/mito2/src/engine/table_compaction/tests.rs @@ -11,6 +11,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Weak}; +use std::time::{Duration, Instant}; use api::v1::Rows; use bytes::Bytes; @@ -19,14 +20,16 @@ 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_engine::{RegionEngine, RegionRole}; 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::lease_test::promote_to_await_leader_lease; use crate::engine::region_hook::{RegionHook, RegionHookRef, VerifiedSstFileInfo}; +use crate::error::Error; use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList}; use crate::region::MitoRegionRef; use crate::sst::file::{ColumnIndexMetadata, FileMeta, IndexType, LEVEL_SHARED, SHARED_LEVEL_SLOT}; @@ -144,6 +147,47 @@ async fn row_count(engine: &MitoEngine, region_id: RegionId) -> usize { .sum() } +#[tokio::test] +async fn test_publication_refused_awaiting_leader_lease() { + 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.require_write_lease(); + engine.freeze_lease_clock(Instant::now()); + promote_to_await_leader_lease(&engine, region_id).await; + let region = engine.get_region(region_id).unwrap(); + let version = region.manifest_ctx.manifest_version().await; + + let err = engine + .publish_table_compaction(region_id, snapshot.clone(), vec![output.clone()]) + .await + .unwrap_err(); + assert!( + matches!(&err, Error::EditRegion { source, .. } + if matches!(source.as_ref(), Error::RegionLeaseNotReceived { .. })), + "{err:?}" + ); + assert_eq!(region.manifest_ctx.manifest_version().await, version); + + engine + .set_region_role_with_lease( + region_id, + RegionRole::Leader, + Instant::now(), + Instant::now() + Duration::from_secs(10), + None, + ) + .unwrap(); + assert_eq!( + PublicationOutcome::Applied, + engine + .publish_table_compaction(region_id, snapshot, vec![output]) + .await + .unwrap() + ); +} + #[tokio::test] async fn test_duplicate_publication_and_later_replacement_do_not_readmit_inputs() { let mut env = TestEnv::new().await; diff --git a/src/mito2/src/engine/tail_replay_test.rs b/src/mito2/src/engine/tail_replay_test.rs index 976d1b8c9d7..a88b2a2496a 100644 --- a/src/mito2/src/engine/tail_replay_test.rs +++ b/src/mito2/src/engine/tail_replay_test.rs @@ -44,9 +44,9 @@ use store_api::region_engine::{ RegionEngine, RegionManifestInfo, RegionRole, SettableRegionRoleState, }; use store_api::region_request::{ - PathType, RegionAlterRequest, RegionCatchupRequest, RegionCloseRequest, - RegionDiscardPendingTailsRequest, RegionDropRequest, RegionFlushRequest, RegionOpenRequest, - RegionRequest, RegionTruncateRequest, + PathType, RegionAlterRequest, RegionBuildIndexRequest, RegionCatchupRequest, + RegionCloseRequest, RegionDiscardPendingTailsRequest, RegionDropRequest, RegionFlushRequest, + RegionOpenRequest, RegionRequest, RegionTruncateRequest, }; use store_api::storage::{RegionId, ScanRequest}; @@ -102,6 +102,7 @@ struct TailReplayListener { fence_begins: AtomicUsize, /// Index builds the worker learned stopped. index_builds_stopped: AtomicUsize, + compactions_scheduled: AtomicUsize, } #[async_trait] @@ -138,12 +139,17 @@ impl EventListener for TailReplayListener { } fn on_tail_replay_ended(&self, _region_id: RegionId) { - self.ended.fetch_add(1, Ordering::Relaxed); + // A test that sees the end also sees the counts of the callbacks before it. + self.ended.fetch_add(1, Ordering::Release); } async fn on_index_build_stopped(&self, _region_file_id: RegionFileId) { self.index_builds_stopped.fetch_add(1, Ordering::Relaxed); } + + fn on_compaction_scheduled(&self, _region_id: RegionId) { + self.compactions_scheduled.fetch_add(1, Ordering::Relaxed); + } } impl TailReplayListener { @@ -168,7 +174,7 @@ impl TailReplayListener { } fn ended(&self) -> usize { - self.ended.load(Ordering::Relaxed) + self.ended.load(Ordering::Acquire) } fn failed(&self) -> bool { @@ -197,6 +203,10 @@ impl TailReplayListener { fn fence_begins(&self) -> usize { self.fence_begins.load(Ordering::Relaxed) } + + fn compactions_scheduled(&self) -> usize { + self.compactions_scheduled.load(Ordering::Relaxed) + } } struct TestRegion { @@ -756,19 +766,74 @@ async fn test_tail_read_stops_at_its_upto(#[case] upto_kind: UptoKind) { assert_eq!(region.entries[0], region.version().flushed_entry_id); } +/// With write leases the replayed tail is published while the region awaits its Leader lease, +/// and the compaction its commit could not start starts when the lease ends the wait. +#[rstest] +#[case::without_write_lease(false)] +#[case::awaiting_leader_lease(true)] #[tokio::test] -async fn test_catchup_replays_remote_reported_tail() { - let region = TestRegion::new("tail-replay-remote-reported", false, None).await; +async fn test_catchup_replays_remote_reported_tail(#[case] leased: bool) { + let region = TestRegion::new("tail-replay-remote-reported", leased, None).await; let last = region.write_remote_rows(region.region_id, 6, 9).await; region .reopen_with_tails(vec![remote_tail(0, last, UptoKind::Reported)]) .await; + // The catchup lets the region write until the node's deadline. + if leased { + region + .engine + .renew_node_lease(Instant::now() + Duration::from_secs(10)); + } region.catchup().await; region.wait_until_replayed().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + assert_eq!(leased, mito_region.manifest_ctx.awaits_leader_lease()); assert_eq!(last, region.version().flushed_entry_id); assert_eq!(9, count_rows(®ion.engine, region.region_id).await); + if leased { + // The worker reports the replay's end after it handled the commit and its compaction. + wait_until(|| region.listener.ended() == 1).await; + assert_eq!(0, region.listener.compactions_scheduled()); + region.promote_with_lease(); + } + wait_until(|| region.listener.compactions_scheduled() == 1).await; +} + +/// A tail replay that commits while the region awaits its Leader lease starts no checkpoint, +/// which could clean up versions the previous leader may still need. +#[tokio::test] +async fn test_tail_commit_awaiting_leader_lease_starts_no_checkpoint() { + let config = MitoConfig { + manifest_checkpoint_distance: 1, + ..Default::default() + }; + let region = TestRegion::build("tail-replay-no-checkpoint", true, None, None, config).await; + let last = region.write_remote_rows(region.region_id, 6, 9).await; + region + .reopen_with_tails(vec![remote_tail(0, last, UptoKind::Reported)]) + .await; + region + .engine + .renew_node_lease(Instant::now() + Duration::from_secs(10)); + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let manager = mito_region.manifest_ctx.manifest_manager.read().await; + let (version, checkpoint) = ( + manager.last_version(), + manager.checkpointer().last_checkpoint_version(), + ); + drop(manager); + + region.catchup().await; + region.wait_until_replayed().await; + + let mito_region = region.engine.get_region(region.region_id).unwrap(); + assert!(mito_region.manifest_ctx.awaits_leader_lease()); + let manager = mito_region.manifest_ctx.manifest_manager.read().await; + assert!(manager.last_version() > version); + assert_eq!(checkpoint, manager.checkpointer().last_checkpoint_version()); + assert!(!manager.checkpointer().is_doing_checkpoint()); } #[tokio::test] @@ -875,6 +940,22 @@ async fn test_unread_remote_listed_tail_waits_for_leader_lease() { assert_eq!(version, next_manifest_version(&mito_region).await); // The replay waits for the lease instead of ending and starting again. assert_eq!(0, region.listener.ended()); + // Without write leases a StagingLeader lease is not the Leader lease the replay waits for. + let now = Instant::now(); + region + .engine + .set_region_role_with_lease( + region.region_id, + RegionRole::StagingLeader, + now, + now + Duration::from_secs(10), + None, + ) + .unwrap(); + let checks = region.listener.lease_checks(); + wait_until(|| region.listener.lease_checks() >= checks + 2).await; + assert!(region.has_pending_tails()); + assert_eq!(version, next_manifest_version(&mito_region).await); region.promote_with_lease(); region.wait_until_replayed().await; @@ -1728,17 +1809,30 @@ async fn test_failed_replay_reloads_region_from_newer_manifest() { assert_eq!(6, count_rows(®ion.engine, region.region_id).await); } +/// With write leases the replay commits while the region awaits its Leader lease, and the lease +/// that ends the wait builds the index the replay could not publish. #[rstest] -#[case::create_on_flush(true)] -#[case::no_create_on_flush(false)] +#[case::create_on_flush(true, false)] +#[case::no_create_on_flush(false, false)] +#[case::awaiting_leader_lease(true, true)] #[tokio::test] -async fn test_replayed_ssts_build_index_as_flushed(#[case] create_on_flush: bool) { - let region = TestRegion::with_config( +async fn test_replayed_ssts_build_index_as_flushed( + #[case] create_on_flush: bool, + #[case] leased: bool, +) { + let region = TestRegion::build( "tail-replay-index", + leased, + None, None, async_build_mode_config(create_on_flush), ) .await; + if leased { + region + .engine + .renew_node_lease(Instant::now() + Duration::from_secs(10)); + } let region_id = RegionId::new(1, 2); let request = CreateRequestBuilder::new() .insert_option(WAL_OPTIONS_KEY, &wal_options()[WAL_OPTIONS_KEY]) @@ -1765,6 +1859,37 @@ async fn test_replayed_ssts_build_index_as_flushed(#[case] create_on_flush: bool .unwrap(); let replayed = region.engine.get_region(region_id).unwrap(); wait_until(|| !replayed.version().has_pending_tails()).await; + if leased { + assert!(replayed.manifest_ctx.awaits_leader_lease()); + // The worker handled the replay's commit before this request, and refused its build. + let err = region + .engine + .handle_request( + region_id, + RegionRequest::BuildIndex(RegionBuildIndexRequest::default()), + ) + .await + .unwrap_err(); + assert!( + matches!( + err.as_any().downcast_ref::(), + Some(Error::RegionLeaseNotReceived { .. }) + ), + "{err:?}" + ); + assert_eq!(region.listener.index_builds_stopped(), 0); + let now = Instant::now(); + region + .engine + .set_region_role_with_lease( + region_id, + RegionRole::Leader, + now, + now + Duration::from_secs(10), + None, + ) + .unwrap(); + } wait_until(|| region.listener.index_builds_stopped() == 1).await; let version = replayed.version(); @@ -2178,6 +2303,47 @@ async fn test_discard_own_tails_releases_their_wal() { assert_eq!(3, count_rows(®ion.engine, region.region_id).await); } +/// A discard of pending tails is refused while the region awaits its Leader lease, and the same +/// discard succeeds after the lease. +#[tokio::test] +async fn test_discard_awaiting_leader_lease_succeeds_after_it() { + let region = TestRegion::new("tail-discard-awaiting-lease", true, None).await; + let tails = vec![ + own_tail(0, region.entries[0], UptoKind::Reported), + own_tail(region.entries[0], region.entries[1], UptoKind::Reported), + ]; + region.reopen_with_tails(tails.clone()).await; + region + .engine + .renew_node_lease(Instant::now() + Duration::from_secs(10)); + region.listener.hold_from(1); + region.catchup().await; + wait_until(|| region.listener.commits() == 1).await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + assert!(mito_region.manifest_ctx.awaits_leader_lease()); + let flushed_entry_id = region.version().flushed_entry_id; + + let error = region.discard_pending_tails(NODE_ID).await.unwrap_err(); + + assert!( + matches!( + error.as_any().downcast_ref::(), + Some(Error::RegionLeaseNotReceived { .. }) + ), + "{error:?}" + ); + assert_eq!(StatusCode::RegionNotReady, error.status_code()); + assert_eq!(tails, region.version().pending_tails); + assert_eq!(flushed_entry_id, region.version().flushed_entry_id); + + region.promote_with_lease(); + assert_eq!(2, region.discard_pending_tails(NODE_ID).await.unwrap()); + let version = region.version(); + assert!(version.pending_tails.is_empty()); + assert_eq!(region.entries[1], version.flushed_entry_id); + region.listener.hold_from(0); +} + #[tokio::test] async fn test_discard_listed_tail_raises_flushed_entry_id_to_its_bound() { let region = TestRegion::new("tail-discard-listed", false, None).await; diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index 79db4ad2a4e..fcd60f8b145 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -801,6 +801,16 @@ pub enum Error { location: Location, }, + #[snafu(display( + "Region {} has not received a leader lease since a catchup made it writable", + region_id + ))] + RegionLeaseNotReceived { + region_id: RegionId, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display( "Region {} lost its leader lease while writing to the WAL, the write may have been applied", region_id @@ -1636,6 +1646,7 @@ impl Error { | Error::RegionTruncated { .. } | Error::RegionStopped { .. } | Error::RegionLeaseExpired { .. } + | Error::RegionLeaseNotReceived { .. } | Error::EndStagingPending { .. } | Error::SerdeJson { .. } | Error::CompressObject { .. } => false, @@ -1782,7 +1793,9 @@ impl ErrorExt for Error { CompatReader { .. } => StatusCode::Unexpected, InvalidRegionRequest { source, .. } => source.status_code(), RegionState { .. } | UpdateManifest { .. } => StatusCode::RegionNotReady, - RegionLeaseExpired { .. } | UnacknowledgedWrite { .. } => StatusCode::RegionNotReady, + RegionLeaseExpired { .. } + | RegionLeaseNotReceived { .. } + | UnacknowledgedWrite { .. } => StatusCode::RegionNotReady, RegionPendingTails { .. } => StatusCode::RegionNotReady, RemoteWalUnsupported { .. } => StatusCode::Unsupported, TailEntryMissing { .. } => StatusCode::StorageUnavailable, @@ -1887,6 +1900,7 @@ impl ErrorExt for Error { | RegionClosed { .. } | RejectWriteInStaging { .. } | RegionLeaseExpired { .. } + | RegionLeaseNotReceived { .. } | UnacknowledgedWrite { .. } | RegionState { state: RegionRoleState::Follower, @@ -2143,6 +2157,12 @@ mod tests { let error = RegionLeaseExpiredSnafu { region_id }.build(); assert!(!error.may_have_persisted_manifest_update()); + // A commit refused before its PUT because no Leader lease has confirmed the catchup. + let error = RegionLeaseNotReceivedSnafu { region_id }.build(); + assert!(!error.may_have_persisted_manifest_update()); + assert_eq!(error.status_code(), StatusCode::RegionNotReady); + assert!(error.retry_hint().is_retryable()); + // 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/region.rs b/src/mito2/src/region.rs index bf16ebf85f9..9f572e50322 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -25,7 +25,7 @@ use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, RwLock}; -use std::time::Instant; +use std::time::{Duration, Instant}; use common_base::hash::partition_expr_version; use common_recordbatch::adapter::RegionQueryStatCounters; @@ -58,8 +58,9 @@ use crate::compaction::CompactionStateRef; use crate::engine::region_hook::{PendingManifestHook, RegionHookRef}; use crate::error::{ EndStagingSnafu, Error, FlushableRegionStateSnafu, InvalidPartitionExprSnafu, - InvalidRequestSnafu, RegionBusySnafu, RegionLeaseExpiredSnafu, RegionNotFoundSnafu, - RegionStateSnafu, RegionTruncatedSnafu, Result, UnexpectedSnafu, UpdateManifestSnafu, + InvalidRequestSnafu, RegionBusySnafu, RegionLeaseExpiredSnafu, RegionLeaseNotReceivedSnafu, + RegionNotFoundSnafu, RegionStateSnafu, RegionTruncatedSnafu, Result, UnexpectedSnafu, + UpdateManifestSnafu, }; use crate::lease::{Deadline, NodeLease, lease_nanos}; use crate::manifest::action::{ @@ -437,6 +438,13 @@ impl MitoRegion { self.manifest_ctx.state.load() == RegionRoleState::Leader(RegionLeaderState::Staging) } + /// Returns whether background flush triggers must skip the region: a staging region keeps + /// its rows in the WAL until staging ends, and a region that awaits its Leader lease cannot + /// commit a flush yet. + pub(crate) fn defers_background_flush(&self) -> bool { + self.is_staging() || self.manifest_ctx.awaits_leader_lease() + } + /// Returns whether the region is in a staging session: staging, ending staging, or in a /// staged edit. pub(crate) fn in_staging_session(&self) -> bool { @@ -764,38 +772,7 @@ impl MitoRegion { } // Hack(zhongzc): If we have just become leader (writable), persist any backfilled metadata. - let mut backfill_hook_payload: Option = None; - if self.state() == RegionRoleState::Leader(RegionLeaderState::Writable) { - // Persist backfilled metadata if manifest is missing fields (e.g., partition_expr) - let manifest_meta = &manager.manifest().metadata; - let current_version = self.version(); - let current_meta = ¤t_version.metadata; - if manifest_meta.partition_expr.is_none() && current_meta.partition_expr.is_some() { - let action = RegionMetaAction::Change(RegionChange { - metadata: current_meta.clone(), - sst_format: current_version.options.sst_format.unwrap_or_default(), - append_mode: None, - }); - let action_list = RegionMetaActionList::with_action(action); - match self - .manifest_ctx - .update_locked(&mut manager, action_list, false) - .await - { - Ok(pending) => { - info!( - "Successfully persisted backfilled metadata for region {}, version: {}", - self.region_id, - pending.version() - ); - backfill_hook_payload = Some(pending); - } - Err(e) => { - warn!(e; "Failed to persist backfilled metadata for region {}", self.region_id); - } - } - } - } + let backfill_hook_payload = self.persist_backfilled_metadata_locked(&mut manager).await; drop(manager); @@ -815,6 +792,71 @@ impl MitoRegion { Ok(()) } + /// Persists the metadata backfilled when the region was opened if the manifest lacks it. + /// A catchup cannot do it for a region that [awaits its Leader + /// lease](ManifestContext::awaits_leader_lease), so the lease that ends the wait does. + pub(crate) async fn persist_backfilled_metadata(&self) { + let mut manager = self.manifest_ctx.manifest_manager.write().await; + let pending = self.persist_backfilled_metadata_locked(&mut manager).await; + // The hook may read the manifest. + drop(manager); + if let Some(pending) = pending { + pending.fire().await; + } + } + + /// Persists the backfilled metadata of a writable leader that may commit, under the + /// caller's manifest lock. Returns the hook to fire after the lock is dropped. + async fn persist_backfilled_metadata_locked( + &self, + manager: &mut RwLockWriteGuard<'_, RegionManifestManager>, + ) -> Option { + if self.state() != RegionRoleState::Leader(RegionLeaderState::Writable) + || self.manifest_ctx.awaits_leader_lease() + { + return None; + } + // Persist backfilled metadata if manifest is missing fields (e.g., partition_expr). + // Only the metadata and the format are kept, so the memtables of the version are not + // pinned across the write below. + let (current_meta, sst_format) = { + let current_version = self.version(); + ( + current_version.metadata.clone(), + current_version.options.sst_format.unwrap_or_default(), + ) + }; + if manager.manifest().metadata.partition_expr.is_some() + || current_meta.partition_expr.is_none() + { + return None; + } + let action = RegionMetaAction::Change(RegionChange { + metadata: current_meta, + sst_format, + append_mode: None, + }); + let action_list = RegionMetaActionList::with_action(action); + match self + .manifest_ctx + .update_locked(manager, action_list, false) + .await + { + Ok(pending) => { + info!( + "Successfully persisted backfilled metadata for region {}, version: {}", + self.region_id, + pending.version() + ); + Some(pending) + } + Err(e) => { + warn!(e; "Failed to persist backfilled metadata for region {}", self.region_id); + None + } + } + } + /// Switches the region state to `RegionRoleState::Leader(RegionLeaderState::Writable)` if the current state is `expect`. /// Otherwise, logs an error. pub(crate) fn switch_state_to_writable(&self, expect: RegionLeaderState) { @@ -1246,6 +1288,8 @@ impl MitoRegion { ); } + self.manifest_ctx + .ensure_leader_lease_or_downgrading(self.region_id)?; let ending_started_at = self.manifest_ctx.begin_ending_staging(self.region_id)?; let mut result = self.manifest_ctx.commit_staged_locked(manager).await; if let Ok((pending, committed)) = &mut result { @@ -1389,12 +1433,23 @@ impl IndexBuildSource { } } +/// What [ManifestContext::promote_unless_downgrade_started_after] did with a Leader lease. +pub(crate) struct LeaderLeasePromotion { + /// Whether the promotion applied; see the function. + pub(crate) promoted: bool, + /// How long the region awaited its Leader lease, if this lease ended the wait, as + /// [ManifestContext::record_leader_lease] returns it. + pub(crate) ended_wait: Option, +} + /// Context to update the region manifest. #[derive(Debug)] pub(crate) struct ManifestContext { /// Manager to maintain manifest for this region. Logical writes go through /// [`update_locked`](Self::update_locked) (or an [`update_manifest`](Self::update_manifest) - /// variant) so they produce a [`PendingManifestHook`]. + /// variant; a replay of pending tails makes the same write unchecked, and the end of staging + /// commits through [`commit_staged_locked`](Self::commit_staged_locked)) so they produce a + /// [`PendingManifestHook`]. pub(crate) manifest_manager: tokio::sync::RwLock, /// The state of the region. The region checks the state before updating /// manifest. @@ -1403,7 +1458,8 @@ pub(crate) struct ManifestContext { /// the role change. promotion_fence: Mutex, /// When a catchup last made the region writable, in the unit of [Deadline], until a Leader - /// lease of a heartbeat sent after it applies; 0 otherwise. While it is set, the region keeps + /// lease of a heartbeat sent after it applies (or a StagingLeader lease, on a node whose + /// writes need a lease); 0 otherwise. While it is set, the region keeps /// the unread part of another node's listed tails. catchup_promoted_at: AtomicU64, /// Whether a tail replay's manifest update has an uncertain result: it may be saved in @@ -1802,7 +1858,7 @@ impl ManifestContext { action_list: RegionMetaActionList, editor: TailsEditor, ) -> Result { - let manager = self.manifest_manager.write().await; + let mut manager = self.manifest_manager.write().await; match self.state.load() { RegionRoleState::Leader(RegionLeaderState::Writable) => {} RegionRoleState::Leader(RegionLeaderState::Altering | RegionLeaderState::Editing) => { @@ -1828,7 +1884,16 @@ impl ManifestContext { } _ => false, }; - let result = self.update_and_fire(manager, action_list, false).await; + // A region that awaits its Leader lease commits a replay of its tails, not a discard. + let result = match editor { + TailsEditor::Replay => { + match self.write_locked(&mut manager, action_list, false).await { + Ok(pending) => Ok(self.unlock_and_fire(manager, pending).await), + Err(e) => Err(e), + } + } + TailsEditor::Discard => self.update_and_fire(manager, action_list, false).await, + }; if editor == TailsEditor::Replay && tracks_uncertainty { match &result { Ok(_) => self @@ -1846,32 +1911,51 @@ impl ManifestContext { /// Performs a manifest write under a caller-held write lock and returns a /// [`PendingManifestHook`] to [`fire`](PendingManifestHook::fire) after - /// dropping the lock. It calls - /// [`RegionManifestManager::update_with_verification`] and is the funnel - /// through which all logical manifest writes notify the hook. + /// dropping the lock. It is the checked entry of the shared write + /// `write_locked`, which a replay of pending tails calls without the check; + /// the end of staging commits through [`Self::commit_staged_locked`] instead. /// - /// Does not validate state or edit applicability — the caller must do so - /// while still holding the lock (see `update_manifest_with_state_check` - /// and `MitoRegion::end_staging_locked`). + /// Fails an update that is not staged while the region [awaits its Leader + /// lease](Self::awaits_leader_lease) and is not downgrading. Does not + /// validate state or edit applicability — the caller must do so while still + /// holding the lock (see `update_manifest_with_state_check` and + /// `MitoRegion::persist_backfilled_metadata_locked`). pub(crate) async fn update_locked( &self, manager: &mut RegionManifestManager, action_list: RegionMetaActionList, is_staging: bool, + ) -> Result { + if !is_staging { + self.ensure_leader_lease_or_downgrading(manager.manifest().metadata.region_id)?; + } + self.write_locked(manager, action_list, is_staging).await + } + + /// Performs the manifest write of [Self::update_locked] without its Leader lease check. + async fn write_locked( + &self, + manager: &mut RegionManifestManager, + action_list: RegionMetaActionList, + is_staging: bool, ) -> Result { let region_id = manager.manifest().metadata.region_id; // Clone before `action_list` is moved into `update_with_verification` // so the hook still sees what was written. let action_list_for_hook = self.hook.as_ref().map(|_| action_list.clone()); + // A lease that ends the wait during the write does not lift the checks below. + let awaited_leader_lease = self.awaits_leader_lease(); // The final flush of a downgrading leader must not start cleanup after the downgrade - // checkpoint barrier. + // checkpoint barrier, nor may a region that awaits its Leader lease and may not own the + // region yet. let allow_checkpoint = !is_staging - && self.state.load() != RegionRoleState::Leader(RegionLeaderState::Downgrading); + && self.state.load() != RegionRoleState::Leader(RegionLeaderState::Downgrading) + && !awaited_leader_lease; let version = self .commit_locked(manager, async |manager| { manager .update_with_verification(action_list, is_staging, allow_checkpoint, || { - self.is_leader_lease_expired() + awaited_leader_lease || self.must_verify_commit() }) .await }) @@ -1896,9 +1980,7 @@ impl ManifestContext { let region_id = manager.manifest().metadata.region_id; let (version, committed) = self .commit_locked(manager, async |manager| { - manager - .commit_staged(|| self.is_leader_lease_expired()) - .await + manager.commit_staged(|| self.must_verify_commit()).await }) .await?; let actions_for_hook = self.hook.as_ref().map(|_| committed.clone()); @@ -1937,6 +2019,14 @@ impl ManifestContext { result } + /// Returns whether a commit, once written, checks that no checkpoint covers its version: a + /// region past its Leader deadline may no longer hold the region, and one that [awaits its + /// Leader lease](Self::awaits_leader_lease) may not hold it yet, so either may have written a + /// version name that checkpoint cleanup freed. + fn must_verify_commit(&self) -> bool { + self.is_leader_lease_expired() || self.awaits_leader_lease() + } + /// Returns whether the region's Leader deadline has passed. No deadline counts as passed. fn is_leader_lease_expired(&self) -> bool { self.node_lease.now() >= self.leader_deadline.get() @@ -1979,10 +2069,19 @@ impl ManifestContext { action_list: RegionMetaActionList, is_staging: bool, ) -> Result { - let region_id = manager.manifest().metadata.region_id; let pending = self .update_locked(&mut manager, action_list, is_staging) .await?; + Ok(self.unlock_and_fire(manager, pending).await) + } + + /// Releases the lock of the write that returned `pending`, then fires its hook. + async fn unlock_and_fire( + &self, + manager: RwLockWriteGuard<'_, RegionManifestManager>, + pending: PendingManifestHook, + ) -> ManifestVersion { + let region_id = manager.manifest().metadata.region_id; let version = pending.version(); // Hook implementations may read the manifest or send region requests @@ -1997,7 +2096,7 @@ impl ManifestContext { } pending.fire().await; - Ok(version) + version } async fn update_manifest_with_state_check( @@ -2097,24 +2196,34 @@ impl ManifestContext { } /// 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. + /// the region waits for a reload. `promoted` is false if the promotion is ignored for one of + /// these reasons; otherwise the role changes as [`Self::set_role`] allows. `ended_wait` tells + /// whether this lease ended the region's wait for its Leader lease, whether or not it promoted + /// the region. pub(crate) fn promote_unless_downgrade_started_after( &self, issued_at: Instant, region_id: RegionId, - ) -> bool { + ) -> LeaderLeasePromotion { // A writable leader needs no change; a staging leader is promoted below. if self.state.load() == RegionRoleState::Leader(RegionLeaderState::Writable) { - self.record_leader_lease(issued_at); - return true; + return LeaderLeasePromotion { + promoted: true, + ended_wait: self.record_leader_lease(issued_at), + }; } let fence = self.promotion_fence.lock().unwrap(); if issued_at < fence.downgrade_started_at { - return false; + return LeaderLeasePromotion { + promoted: false, + ended_wait: None, + }; + } + let ended_wait = self.record_leader_lease(issued_at); + LeaderLeasePromotion { + promoted: self.promote_unless_reload_pending(&fence, region_id, false), + ended_wait, } - self.record_leader_lease(issued_at); - self.promote_unless_reload_pending(&fence, region_id, false) } /// Promotes a region that caught up to a writable leader. Returns false if the region waits @@ -2124,6 +2233,18 @@ impl ManifestContext { self.promote_unless_reload_pending(&fence, region_id, true) } + /// Makes the region wait for its Leader lease as a catchup on a node whose writes need a lease + /// does, without a catchup: it keeps the memtable and enables the node lease the engine + /// shares. + #[cfg(test)] + pub(crate) fn start_leader_lease_wait_for_test(&self, region_id: RegionId) { + self.node_lease.enable(); + self.leader_deadline + .extend(Instant::now() + Duration::from_secs(60)); + assert!(self.promote_after_catchup(region_id)); + assert!(self.awaits_leader_lease()); + } + /// Promotes the region unless it waits for a reload. The caller holds the fence lock. fn promote_unless_reload_pending( &self, @@ -2143,30 +2264,69 @@ impl ManifestContext { true } - /// Counts an applied Leader lease of a heartbeat sent at `issued_at` as received since the + /// Counts an applied Leader lease (or StagingLeader lease, on a node whose writes need a lease) + /// of a heartbeat sent at `issued_at` as received since the /// last catchup promotion. A heartbeat sent before the promotion does not count: its lease /// may have been granted before an earlier downgrade of this node, which the fast path of /// [Self::promote_unless_downgrade_started_after] does not check, and the lease of the next /// heartbeat counts instead. It reads one atomic, since every lease of a writable leader - /// comes here. - pub(crate) fn record_leader_lease(&self, issued_at: Instant) { + /// comes here. On a node whose writes need a lease, returns how long the region + /// [awaited](Self::awaits_leader_lease) its Leader lease if this lease ended the wait: of the + /// leases that apply together, only the one that ends it returns it. + pub(crate) fn record_leader_lease(&self, issued_at: Instant) -> Option { let promoted_at = self.catchup_promoted_at.load(Ordering::Relaxed); - if promoted_at != 0 && lease_nanos(issued_at) >= promoted_at { - let _ = self.catchup_promoted_at.compare_exchange( - promoted_at, - 0, - Ordering::Relaxed, - Ordering::Relaxed, - ); + if promoted_at == 0 || lease_nanos(issued_at) < promoted_at { + return None; } + self.end_leader_lease_wait(promoted_at) } - /// Returns whether a Leader lease of a heartbeat sent after the last catchup promotion applied, - /// or no catchup promoted the region. + /// Ends the wait of the catchup promotion at `promoted_at` if no other lease ended it since + /// it was read, and returns what [Self::record_leader_lease] returns for the lease that ends it. + fn end_leader_lease_wait(&self, promoted_at: u64) -> Option { + self.catchup_promoted_at + .compare_exchange(promoted_at, 0, Ordering::Relaxed, Ordering::Relaxed) + .ok()?; + self.node_lease + .is_enabled() + .then(|| Duration::from_nanos(lease_nanos(Instant::now()).saturating_sub(promoted_at))) + } + + /// Returns whether a Leader lease (or a StagingLeader lease, on a node whose writes need a + /// lease) of a heartbeat sent after the last catchup promotion applied, or no catchup promoted + /// the region. pub(crate) fn leader_lease_received(&self) -> bool { self.catchup_promoted_at.load(Ordering::Relaxed) == 0 } + /// Returns whether the region, on a node whose writes need a lease, still waits for the + /// Leader or StagingLeader lease that follows its catchup promotion, whatever its role is + /// now. Until that lease nothing confirms that it owns the region, even if the route already + /// points to it, so it commits nothing but replayed tails and what it commits while + /// downgrading, and starts no work that only such a commit could finish. + pub(crate) fn awaits_leader_lease(&self) -> bool { + self.node_lease.is_enabled() && !self.leader_lease_received() + } + + /// Fails a manifest commit of a region that [awaits its Leader lease](Self::awaits_leader_lease), + /// unless the region is downgrading: a downgrade is asked only of the leader in the route. + /// A commit calls it under the manifest lock before it sends anything; a request that would + /// flush first calls it before it schedules the flush, and an index build before it starts. + /// It reads atomics only. + pub(crate) fn ensure_leader_lease_or_downgrading(&self, region_id: RegionId) -> Result<()> { + ensure!( + !self.refuses_commits_awaiting_leader_lease(), + RegionLeaseNotReceivedSnafu { region_id } + ); + Ok(()) + } + + /// Returns whether [Self::ensure_leader_lease_or_downgrading] fails. + pub(crate) fn refuses_commits_awaiting_leader_lease(&self) -> bool { + self.awaits_leader_lease() + && self.state.load() != RegionRoleState::Leader(RegionLeaderState::Downgrading) + } + /// Sets the [`RegionRole`]. /// /// ```text @@ -2758,6 +2918,7 @@ fn manifest_file_matches(meta: &FileMeta, filters: &MetadataFilter) -> bool { #[cfg(test)] mod tests { use std::sync::Arc; + use std::sync::atomic::Ordering; use common_datasource::compression::CompressionType; use common_test_util::temp_dir::create_temp_dir; @@ -2780,6 +2941,7 @@ mod tests { use crate::region::{ IndexBuildSource, IndexPublication, IndexPublicationStale, ManifestContext, ManifestStats, MitoRegion, RegionLeaderState, RegionRoleState, RegionStats, StagingPartitionInfo, + TailPublication, TailsEditor, }; use crate::sst::FormatType; use crate::sst::index::intermediate::IntermediateManager; @@ -2871,6 +3033,13 @@ mod tests { } async fn build_test_region(env: &SchedulerEnv) -> MitoRegion { + build_test_region_with_checkpoint_distance(env, 10).await + } + + async fn build_test_region_with_checkpoint_distance( + env: &SchedulerEnv, + checkpoint_distance: u64, + ) -> MitoRegion { let builder = VersionControlBuilder::new(); let version_control = Arc::new(builder.build()); let metadata = version_control.current().version.metadata.clone(); @@ -2883,7 +3052,7 @@ mod tests { manifest_dir: "".to_string(), object_store: env.access_layer.object_store().clone(), compress_type: CompressionType::Uncompressed, - checkpoint_distance: 10, + checkpoint_distance, remove_file_options: Default::default(), manifest_cache: None, conditional_publication: false, @@ -3043,13 +3212,35 @@ mod tests { let manifest_ctx = &promoted.manifest_ctx; let issued_at = std::time::Instant::now(); tx.send( - manifest_ctx.promote_unless_downgrade_started_after(issued_at, promoted.region_id), + manifest_ctx + .promote_unless_downgrade_started_after(issued_at, promoted.region_id) + .promoted, ) .unwrap(); }); assert!(rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap()); } + #[tokio::test] + async fn test_awaiting_leader_lease_requires_verification() { + let env = SchedulerEnv::new().await; + let region = build_test_region(&env).await; + let manifest_ctx = ®ion.manifest_ctx; + manifest_ctx.node_lease.enable(); + manifest_ctx + .leader_deadline + .extend(std::time::Instant::now() + std::time::Duration::from_secs(60)); + assert!(!manifest_ctx.must_verify_commit()); + + region.set_role(RegionRole::Follower); + assert!(manifest_ctx.promote_after_catchup(region.region_id)); + assert!(manifest_ctx.must_verify_commit()); + + std::thread::sleep(std::time::Duration::from_millis(1)); + manifest_ctx.record_leader_lease(std::time::Instant::now()); + assert!(!manifest_ctx.must_verify_commit()); + } + #[tokio::test] async fn test_lease_sent_before_catchup_promotion_does_not_count() { let env = SchedulerEnv::new().await; @@ -3060,13 +3251,66 @@ mod tests { std::thread::sleep(std::time::Duration::from_millis(1)); assert!(manifest_ctx.promote_after_catchup(region.region_id)); - assert!(manifest_ctx.promote_unless_downgrade_started_after(sent_before, region.region_id)); + assert!( + manifest_ctx + .promote_unless_downgrade_started_after(sent_before, region.region_id) + .promoted + ); assert!(!manifest_ctx.leader_lease_received()); let sent_after = std::time::Instant::now(); - assert!(manifest_ctx.promote_unless_downgrade_started_after(sent_after, region.region_id)); + assert!( + manifest_ctx + .promote_unless_downgrade_started_after(sent_after, region.region_id) + .promoted + ); assert!(manifest_ctx.leader_lease_received()); } + /// A replay of pending tails that commits while the region awaits its Leader lease starts no + /// checkpoint without conditional publication too, where no verification of the commit + /// turns it off. + #[tokio::test] + async fn test_tail_commit_awaiting_leader_lease_starts_no_checkpoint_without_conditional_publication() + { + let env = SchedulerEnv::new().await; + let region = build_test_region_with_checkpoint_distance(&env, 1).await; + let manifest_ctx = ®ion.manifest_ctx; + manifest_ctx.start_leader_lease_wait_for_test(region.region_id); + let action_list = + RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit::default())); + + let publication = manifest_ctx + .update_manifest_for_tails(&[], action_list, TailsEditor::Replay) + .await + .unwrap(); + + assert!(matches!(publication, TailPublication::Committed(_))); + let manager = manifest_ctx.manifest_manager.read().await; + assert_eq!(0, manager.checkpointer().last_checkpoint_version()); + assert!(!manager.checkpointer().is_doing_checkpoint()); + } + + /// Of the leases that apply together, only the one that ends the wait reports it. + #[tokio::test] + async fn test_only_the_lease_that_ends_the_wait_reports_it() { + let env = SchedulerEnv::new().await; + let region = build_test_region(&env).await; + let manifest_ctx = ®ion.manifest_ctx; + manifest_ctx.start_leader_lease_wait_for_test(region.region_id); + // Two leases that read the same wait before either ends it. + let promoted_at = manifest_ctx.catchup_promoted_at.load(Ordering::Relaxed); + + assert!(manifest_ctx.end_leader_lease_wait(promoted_at).is_some()); + assert!(manifest_ctx.end_leader_lease_wait(promoted_at).is_none()); + assert!(!manifest_ctx.awaits_leader_lease()); + // A lease that reads the wait after it ended. + assert!( + manifest_ctx + .record_leader_lease(std::time::Instant::now()) + .is_none() + ); + } + #[tokio::test] async fn test_compaction_update_manifest_allows_editing_state() { let env = SchedulerEnv::new().await; @@ -3106,6 +3350,69 @@ mod tests { ); } + #[rstest::rstest] + #[case::writable(false)] + #[case::downgrading(true)] + #[tokio::test] + async fn test_index_publication_refused_awaiting_leader_lease_unless_downgrading( + #[case] downgrading: bool, + ) { + let env = SchedulerEnv::new().await; + let region = build_test_region(&env).await; + let source = crate::sst::file::FileMeta { + region_id: region.region_id, + file_id: FileId::random(), + level: 1, + file_size: 1024, + ..Default::default() + }; + region + .manifest_ctx + .update_manifest( + RegionLeaderState::Writable, + RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit { + files_to_add: vec![source.clone()], + ..empty_edit() + })), + false, + ) + .await + .unwrap(); + let manifest_ctx = ®ion.manifest_ctx; + manifest_ctx.start_leader_lease_wait_for_test(region.region_id); + let index_source = + IndexBuildSource::new(source.clone(), region.version().metadata.schema_version); + let mut updated = source.clone(); + updated.index_version = 1; + updated.index_file_size = 128; + let publish = || manifest_ctx.update_manifest_for_index(&index_source, updated.clone()); + + if downgrading { + // A downgrade is asked only of the leader in the route. + manifest_ctx.begin_downgrade(region.region_id); + } else { + let err = publish().await.unwrap_err(); + assert!( + matches!(err, Error::RegionLeaseNotReceived { .. }), + "{err:?}" + ); + assert_eq!( + manifest_ctx + .manifest() + .await + .files + .get(&source.file_id) + .map(AsRef::as_ref), + Some(&source) + ); + manifest_ctx.record_leader_lease(std::time::Instant::now()); + } + assert!(matches!( + publish().await.unwrap(), + IndexPublication::Committed { .. } + )); + } + #[tokio::test] async fn test_index_publication_rejects_older_source_generation() { let env = SchedulerEnv::new().await; diff --git a/src/mito2/src/request.rs b/src/mito2/src/request.rs index c17881a5a46..c7a6cb77425 100644 --- a/src/mito2/src/request.rs +++ b/src/mito2/src/request.rs @@ -1171,6 +1171,9 @@ pub(crate) enum BackgroundNotify { }, /// The region became writable and may have pending tails to replay. RegionBecameWritable, + /// A lease ended the region's wait for its Leader lease, so the work the wait deferred may + /// start. + LeaderLeaseWaitEnded, /// A role change left the region unable to replay its tails (see /// [MitoRegion::can_replay_tails](crate::region::MitoRegion::can_replay_tails)); a running /// replay is cancelled. @@ -1236,6 +1239,7 @@ impl BackgroundNotify { | Self::RegionFenced | Self::RegionReloaded { .. } | Self::RegionBecameWritable + | Self::LeaderLeaseWaitEnded | Self::RegionCannotReplay { .. } | Self::TailReplayCommitted { .. } | Self::TailReplayEnded diff --git a/src/mito2/src/tail_replay.rs b/src/mito2/src/tail_replay.rs index f34ca87453f..7889e7dd38c 100644 --- a/src/mito2/src/tail_replay.rs +++ b/src/mito2/src/tail_replay.rs @@ -355,11 +355,14 @@ impl TailReplayTask { .await } - /// Waits until the region receives a Leader lease. Returns false if the region stops being - /// a writable, altering or editing leader, or the task is cancelled, first. + /// Waits until the region receives a Leader lease, or a StagingLeader lease on a node whose + /// writes need a lease. Returns false if the region stops being a writable, altering or + /// editing leader, or the task is cancelled, first. async fn wait_for_leader_lease(&self) -> bool { let region_id = self.region.region_id; - info!("Region {region_id} waits for a Leader lease to clear its unread listed tails"); + info!( + "Region {region_id} waits for a lease that confirms it as the leader to clear its unread listed tails" + ); while self.region.can_replay_tails() { self.listener.on_tail_lease_check(region_id); if self.region.manifest_ctx.leader_lease_received() { diff --git a/src/mito2/src/test_util.rs b/src/mito2/src/test_util.rs index f5631e7e9e4..d354da66347 100644 --- a/src/mito2/src/test_util.rs +++ b/src/mito2/src/test_util.rs @@ -530,6 +530,12 @@ impl TestEnv { self } + /// Uses `fetcher` for the partition expressions of regions whose manifest lacks one. + pub(crate) fn with_partition_expr_fetcher(mut self, fetcher: PartitionExprFetcherRef) -> Self { + self.partition_expr_fetcher = fetcher; + self + } + /// Sets the original `object_store_mock_layer`. pub fn with_mock_layer(mut self, mock_layer: MockLayer) -> TestEnv { self.object_store_mock_layer = Some(mock_layer); diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index da605572c4f..6b86b51126b 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -36,6 +36,9 @@ mod handle_tail_replay; mod handle_truncate; mod handle_write; +#[cfg(test)] +pub(crate) use handle_catchup::persist_backfilled_metadata_and_notify_if_fenced; + use std::collections::{HashMap, HashSet, VecDeque}; use std::path::Path; use std::sync::Arc; @@ -81,8 +84,8 @@ use crate::region::{ RegionMapRef, }; use crate::request::{ - BackgroundNotify, BulkInsertRequest, DdlRequest, OptionOutputTx, SenderBulkRequest, - SenderDdlRequest, SenderWriteRequest, WorkerRequest, WorkerRequestWithTime, + BackgroundNotify, BuildIndexRequest, BulkInsertRequest, DdlRequest, OptionOutputTx, + SenderBulkRequest, SenderDdlRequest, SenderWriteRequest, WorkerRequest, WorkerRequestWithTime, }; use crate::schedule::CancellableTaskState; use crate::schedule::scheduler::{LocalScheduler, SchedulerRef}; @@ -440,6 +443,15 @@ impl WorkerGroup { &self.granted_leases } + /// Tells the worker of `region` that a lease ended its wait for its Leader lease, without + /// waiting. + pub(crate) fn notify_leader_lease_wait_ended(&self, region: &MitoRegionRef) { + handle_catchup::notify_leader_lease_wait_ended( + &self.worker(region.region_id).sender, + region, + ); + } + /// Asks the worker of `region` to replay its pending tails, if it has any, without waiting. pub(crate) fn notify_writable(&self, region: &MitoRegionRef) { handle_tail_replay::notify_writable(&self.worker(region.region_id).sender, region); @@ -895,6 +907,7 @@ impl WorkerStarter { granted_leases: self.granted_leases, staging_regions: self.staging_regions, tail_replays: HashMap::new(), + lease_deferred_index_retries: HashMap::new(), }; let handle = common_runtime::spawn_global(async move { worker_thread.run().await; @@ -1361,6 +1374,9 @@ struct RegionWorkerLoop { staging_regions: StagingRegionsRef, /// Running tail replays, which stay here until they report their end. tail_replays: HashMap, + /// Index build retries refused while their region awaited its Leader lease, which the end of + /// the wait re-issues. + lease_deferred_index_retries: HashMap>, } impl RegionWorkerLoop { @@ -1856,6 +1872,9 @@ impl RegionWorkerLoop { self.handle_region_reloaded(region_id, old, result).await } BackgroundNotify::RegionBecameWritable => self.maybe_replay_tails(region_id), + BackgroundNotify::LeaderLeaseWaitEnded => { + self.handle_leader_lease_wait_ended(region_id).await + } BackgroundNotify::RegionCannotReplay { region } => { self.handle_region_cannot_replay(region_id, region) } @@ -1959,7 +1978,7 @@ impl RegionWorkerLoop { impl RegionWorkerLoop { /// Cleans up the worker. - async fn clean(&self) { + async fn clean(&mut self) { for state in self.tail_replays.values() { let _ = state.request_cancel(); } @@ -1982,6 +2001,7 @@ impl RegionWorkerLoop { self.regions.clear(); for region in regions { self.granted_leases.remove(region.region_id); + self.lease_deferred_index_retries.remove(®ion.region_id); } } @@ -2058,6 +2078,22 @@ impl WorkerListener { } } + /// The worker handled the end of the region's wait for its Leader lease. + pub(crate) fn on_leader_lease_wait_ended(&self, _region_id: RegionId) { + #[cfg(any(test, feature = "test"))] + if let Some(listener) = &self.listener { + listener.on_leader_lease_wait_ended(_region_id); + } + } + + /// The worker spawns the persisting of the region's backfilled metadata. + pub(crate) fn on_persist_backfilled_metadata_begin(&self, _region_id: RegionId) { + #[cfg(any(test, feature = "test"))] + if let Some(listener) = &self.listener { + listener.on_persist_backfilled_metadata_begin(_region_id); + } + } + /// A tail replay checks for a Leader lease while it waits. pub(crate) fn on_tail_lease_check(&self, _region_id: RegionId) { #[cfg(any(test, feature = "test"))] diff --git a/src/mito2/src/worker/handle_alter.rs b/src/mito2/src/worker/handle_alter.rs index eb5c33aca09..2760ae71bc2 100644 --- a/src/mito2/src/worker/handle_alter.rs +++ b/src/mito2/src/worker/handle_alter.rs @@ -151,6 +151,14 @@ impl RegionWorkerLoop { // Checks whether we can alter the region directly. if !version.memtables.is_empty() { + // A region that awaits its Leader lease cannot commit the flush. + if let Err(e) = region + .manifest_ctx + .ensure_leader_lease_or_downgrading(region_id) + { + sender.send(Err(e)); + return; + } // If memtable is not empty, we can't alter it directly and need to flush // all memtables first. info!("Flush region: {} before alteration", region_id); diff --git a/src/mito2/src/worker/handle_catchup.rs b/src/mito2/src/worker/handle_catchup.rs index 47ad46447bb..e8a4e7062c3 100644 --- a/src/mito2/src/worker/handle_catchup.rs +++ b/src/mito2/src/worker/handle_catchup.rs @@ -12,8 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Handling catchup request. +//! Handling catchup request and the end of a region's wait for its Leader lease. +use std::collections::HashSet; use std::sync::Arc; use common_telemetry::tracing::warn; @@ -23,16 +24,22 @@ use store_api::logstore::LogStore; use store_api::region_engine::SettableRegionRoleState; use store_api::region_request::RegionCatchupRequest; use store_api::storage::RegionId; +use tokio::sync::mpsc::Sender; +use crate::config::IndexBuildMode; use crate::error::{self, Result}; -use crate::region::MitoRegion; use crate::region::catchup::RegionCatchupTask; use crate::region::opener::RegionOpener; -use crate::request::OptionOutputTx; +use crate::region::{MitoRegion, MitoRegionRef, RegionLeaderState, RegionRoleState}; +use crate::request::{BackgroundNotify, BuildIndexRequest, OptionOutputTx, WorkerRequestWithTime}; +use crate::sst::index::IndexBuildType; +use crate::tail_replay::notify_worker; #[cfg(feature = "hdfs-object-store")] use crate::temp_file_sweeper; use crate::wal::entry_distributor::WalEntryReceiver; -use crate::worker::{RegionWorkerLoop, drain_ended_staging, handle_tail_replay}; +use crate::worker::{ + RegionWorkerLoop, WorkerListener, drain_ended_staging, handle_reload, handle_tail_replay, +}; impl RegionWorkerLoop { pub(crate) async fn handle_catchup_request( @@ -222,4 +229,87 @@ impl RegionWorkerLoop { Ok(region) } + + /// Starts the work that a region deferred while it awaited its Leader lease. + pub(crate) async fn handle_leader_lease_wait_ended(&mut self, region_id: RegionId) { + let retries = self + .lease_deferred_index_retries + .remove(®ion_id) + .unwrap_or_default(); + let Some(region) = self.regions.get_region(region_id) else { + return; + }; + // As for any flush, the completion of these handles the stalled writes. + self.maybe_flush_worker(); + self.maybe_flush_write_regions(HashSet::from([region_id])); + let state = region.state(); + if state == RegionRoleState::Leader(RegionLeaderState::Writable) { + self.schedule_compaction(®ion).await; + self.build_missing_indexes(®ion).await; + for request in retries { + self.handle_rebuild_index_inner(request, OptionOutputTx::new(None), true) + .await; + } + spawn_persist_backfilled_metadata(&self.listener, &self.sender, region); + } else { + info!( + "Region {region_id} is {state:?} when its Leader lease wait ends, starting no compaction, building no missing index, re-issuing no index build retry and persisting no backfilled metadata" + ); + } + self.listener.on_leader_lease_wait_ended(region_id); + } + + /// Builds the indexes of the region's files that lack them, which a region that waits does + /// not build. + async fn build_missing_indexes(&mut self, region: &MitoRegionRef) { + if self.config.index.build_mode != IndexBuildMode::Async { + return; + } + let request = BuildIndexRequest { + region_id: region.region_id, + build_type: IndexBuildType::Flush, + file_metas: Vec::new(), + result_senders: Vec::new(), + }; + self.handle_rebuild_index(request, OptionOutputTx::new(None)) + .await; + } +} + +/// Persists the metadata the opener filled in, which the catchup of a region that waits does +/// not, without blocking the worker. The commit runs outside the worker, so it asks for the +/// reload of a region it fences. +fn spawn_persist_backfilled_metadata( + listener: &WorkerListener, + sender: &Sender, + region: MitoRegionRef, +) { + listener.on_persist_backfilled_metadata_begin(region.region_id); + let sender = sender.clone(); + common_runtime::spawn_global(async move { + persist_backfilled_metadata_and_notify_if_fenced(&sender, ®ion).await; + }); +} + +/// Persists the metadata the opener filled in for `region` and, if the commit fenced the region, +/// asks its worker through `sender` for the reload. +pub(crate) async fn persist_backfilled_metadata_and_notify_if_fenced( + sender: &Sender, + region: &MitoRegionRef, +) { + region.persist_backfilled_metadata().await; + handle_reload::notify_if_fenced(sender, region).await; +} + +/// Tells the worker that a lease ended the wait of `region` for its Leader lease, without +/// waiting. +pub(crate) fn notify_leader_lease_wait_ended( + sender: &Sender, + region: &MitoRegionRef, +) { + let sender = sender.clone(); + let region_id = region.region_id; + common_runtime::spawn_global(async move { + notify_worker(&sender, region_id, BackgroundNotify::LeaderLeaseWaitEnded).await; + }); } diff --git a/src/mito2/src/worker/handle_close.rs b/src/mito2/src/worker/handle_close.rs index 03da3578a58..7ca8bbe1664 100644 --- a/src/mito2/src/worker/handle_close.rs +++ b/src/mito2/src/worker/handle_close.rs @@ -60,6 +60,13 @@ impl RegionWorkerLoop { // Followers cannot flush; explicit flush-on-close and region WAL options // retain their existing behavior. if close_needs_flush(®ion, &request) && region.is_flushable() { + // A region that awaits its Leader lease holds rows that exist nowhere else only if + // it was written to, which happens only after it was routed to; a close, such as the + // one of a shutdown, must not drop them. It gives up the role as a downgrade does, so + // its flush commits under the downgrade's checks. + if region.is_writable() && region.manifest_ctx.awaits_leader_lease() { + region.manifest_ctx.begin_downgrade(region_id); + } info!("Region {} has pending data, waiting for flush", region_id); if self.flush_scheduler.is_flush_requested(region_id) { self.flush_scheduler @@ -127,6 +134,7 @@ impl RegionWorkerLoop { return; }; self.granted_leases.remove(region_id); + self.lease_deferred_index_retries.remove(®ion_id); region.deactivate_region_manifest_size_metric(); self.cancel_tail_replay(region_id); region.stop().await; diff --git a/src/mito2/src/worker/handle_compaction.rs b/src/mito2/src/worker/handle_compaction.rs index 6bc8d13a5da..dbf5219599f 100644 --- a/src/mito2/src/worker/handle_compaction.rs +++ b/src/mito2/src/worker/handle_compaction.rs @@ -27,23 +27,9 @@ use crate::request::{ BuildIndexRequest, CompactionFailed, CompactionFinished, CompactionUnitNotification, OnFailure, OptionOutputTx, }; -use crate::sst::file::FileMeta; use crate::sst::index::IndexBuildType; -use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; use crate::worker::RegionWorkerLoop; - -/// Completed extensions prove the writer built this output's indexes together. -/// A background replacement would otherwise erase those extension blobs. -fn needs_background_indexes(file: &FileMeta) -> bool { - !ExtensionIndexKind::ALL.iter().any(|kind| { - let index_type = IndexKind::Extension(*kind).index_type(); - file.available_indexes.contains(&index_type) - || file - .indexes - .iter() - .any(|column| column.created_indexes.contains(&index_type)) - }) -} +use crate::worker::handle_rebuild_index::needs_background_indexes; fn made_progress(files_to_add: usize, files_to_remove: usize) -> bool { files_to_add > 0 || files_to_remove > files_to_add diff --git a/src/mito2/src/worker/handle_drop.rs b/src/mito2/src/worker/handle_drop.rs index 0f3ef43f87b..677f8287910 100644 --- a/src/mito2/src/worker/handle_drop.rs +++ b/src/mito2/src/worker/handle_drop.rs @@ -115,6 +115,7 @@ where // Removes this region from region map to prevent other requests from accessing this region self.regions.remove_region(region_id); self.granted_leases.remove(region_id); + self.lease_deferred_index_retries.remove(®ion_id); region.deactivate_region_manifest_size_metric(); self.cancel_tail_replay(region_id); self.dropping_regions.insert_region(region.clone()); diff --git a/src/mito2/src/worker/handle_enter_staging.rs b/src/mito2/src/worker/handle_enter_staging.rs index 119f07241f6..6b0cba75840 100644 --- a/src/mito2/src/worker/handle_enter_staging.rs +++ b/src/mito2/src/worker/handle_enter_staging.rs @@ -67,6 +67,16 @@ impl RegionWorkerLoop { sender.send(Err(e)); return; } + // Rows in the memtable need a flush first, which a region that awaits its Leader lease + // cannot commit. + if !region.version().memtables.is_empty() + && let Err(e) = region + .manifest_ctx + .ensure_leader_lease_or_downgrading(region_id) + { + 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 e51845c71ce..ffa9f84398e 100644 --- a/src/mito2/src/worker/handle_flush.rs +++ b/src/mito2/src/worker/handle_flush.rs @@ -135,9 +135,10 @@ impl RegionWorkerLoop { for region in ®ions { if self.flush_scheduler.is_flush_requested(region.region_id) || !region.is_writable() - || region.is_staging() + || region.defers_background_flush() { - // Already flushing, not writable, or in staging, whose rows must stay in the WAL. + // Already flushing, not writable, staging, whose rows must stay in the WAL, or + // awaiting its Leader lease, which it needs to commit a flush. continue; } @@ -242,6 +243,15 @@ impl RegionWorkerLoop { continue; } + // A region that awaits its Leader lease cannot commit a flush yet, so it rejects the + // writes it would stall, from its write buffer on: only the lease would release them. + if region.manifest_ctx.awaits_leader_lease() { + if status.should_stall || status.should_reject { + pressure.rejected_region_ids.insert(region_id); + } + continue; + } + if status.should_flush && !self.flush_scheduler.is_flush_requested(region.region_id) { let task = self.new_flush_task( ®ion, @@ -381,8 +391,11 @@ impl RegionWorkerLoop { // when handling flush request instead of in `schedule_flush` or `flush_finished`. self.update_topic_latest_entry_id(®ion); - // A staging region must keep its WAL until staging ends, so it flushes nothing. - if region.is_staging() && !region.version().memtables.is_empty() { + // A staging region must keep its WAL until staging ends, and a region that awaits its + // Leader lease cannot commit a flush before it is downgraded, so they flush nothing. + if (region.is_staging() || region.manifest_ctx.refuses_commits_awaiting_leader_lease()) + && !region.version().memtables.is_empty() + { sender.send(match request.reason { // These only ask to advance the flushed position, which can wait. Some(RegionFlushReason::RegionMigration | RegionFlushReason::RemoteWalPrune) => { @@ -418,7 +431,7 @@ impl RegionWorkerLoop { Some(tail.node_id) == node_id && tail.after <= version.flushed_entry_id }); if !region.is_writable() - || region.is_staging() + || region.defers_background_flush() || self.flush_scheduler.is_flush_requested(region_id) || region_memtable_usage(&version) == 0 || release_capped @@ -444,10 +457,11 @@ impl RegionWorkerLoop { continue; } self.update_topic_latest_entry_id(region); - // The rows of a staging region must stay in the WAL until staging ends, so a staging - // region with rows pins its topic's prune point: the update above only keeps the id - // fresh while the memtable is empty. - if region.is_staging() { + // A staging region, whose rows must stay in the WAL until staging ends, or a region + // that awaits its Leader lease, which it needs to commit a flush, pins its topic's + // prune point while it has rows: the update above only keeps the id fresh while the + // memtable is empty. + if region.defers_background_flush() { continue; } diff --git a/src/mito2/src/worker/handle_rebuild_index.rs b/src/mito2/src/worker/handle_rebuild_index.rs index f7e73894183..ed4e123e637 100644 --- a/src/mito2/src/worker/handle_rebuild_index.rs +++ b/src/mito2/src/worker/handle_rebuild_index.rs @@ -18,7 +18,7 @@ use std::collections::HashMap; use std::sync::Arc; use api::v1::region::build_index_request; -use common_telemetry::{debug, warn}; +use common_telemetry::{debug, info, warn}; use snafu::{IntoError, ResultExt}; use store_api::metadata::RegionMetadataRef; use store_api::region_request::RegionBuildIndexRequest; @@ -35,8 +35,9 @@ use crate::metrics::INDEX_PUBLICATION_STALE_TOTAL; use crate::region::options::IndexOptions; use crate::region::{IndexBuildSource, MitoRegionRef, RegionLeaderState, RegionRoleState}; use crate::request::{BuildIndexRequest, IndexBuildFinished, IndexBuildStopped, OptionOutputTx}; -use crate::sst::file::{self, FileHandle, FileMeta, RegionFileId, RegionIndexId}; +use crate::sst::file::{self, FileHandle, FileMeta, FileMetaRef, RegionFileId, RegionIndexId}; use crate::sst::index::handler::{IndexKindProviderRef, PlanContext}; +use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; use crate::sst::index::registry::{IndexRegistry, IndexRegistryRef}; use crate::sst::index::{ IndexBuildOutcome, IndexBuildTask, IndexBuildType, IndexerBuilderImpl, ResultMpscSender, @@ -53,6 +54,43 @@ pub(crate) struct IndexBuildSnapshot { index_options: IndexOptions, } +/// Returns whether a background build may replace the index of `file`: a file that already has +/// an extension index was indexed whole by its writer, and a replacement would erase those blobs. +pub(crate) fn needs_background_indexes(file: &FileMeta) -> bool { + !ExtensionIndexKind::ALL.iter().any(|kind| { + let index_type = IndexKind::Extension(*kind).index_type(); + file.available_indexes.contains(&index_type) + || file + .indexes + .iter() + .any(|column| column.created_indexes.contains(&index_type)) + }) +} + +/// Selects the files that a build of `build_type` for every file of a region builds, from the +/// region's files that its manifest records (`candidates`, each with the manifest's file meta). +/// A flush build, which the end of a wait for the Leader lease asks for, builds no extension +/// index, so it leaves the files that have one. Of the others it builds those whose index in the +/// version is not current for the plan of `build_type`: a publication committed to the manifest +/// but not yet applied is still invisible to queries, and its build still holds the file, so a +/// manual build waits for it. +fn select_whole_region_builds( + candidates: Vec<(FileHandle, FileMetaRef)>, + registry: &IndexRegistry, + snapshot: &IndexBuildSnapshot, + build_type: &IndexBuildType, +) -> Vec<(FileHandle, FileMetaRef)> { + candidates + .into_iter() + .filter(|(_, file_meta)| { + *build_type != IndexBuildType::Flush || needs_background_indexes(file_meta) + }) + .filter(|(file, _)| { + index_needs_rebuild(registry, snapshot, file.meta_ref(), build_type.clone()) + }) + .collect() +} + impl RegionWorkerLoop { pub(crate) fn new_index_build_task( &self, @@ -215,6 +253,26 @@ impl RegionWorkerLoop { ); return; } + // A region that awaits its Leader lease could not publish the index. In async build + // mode the end of the wait builds the missing indexes if the region is then a writable + // leader. + if let Err(e) = region + .manifest_ctx + .ensure_leader_lease_or_downgrading(region_id) + { + // A retry has no caller to try again, so the end of the wait re-issues it. + if is_retry { + info!("Region {region_id} awaits its Leader lease, keeping an index build retry"); + self.lease_deferred_index_retries + .entry(region_id) + .or_default() + .push(request); + return; + } + info!("Region {region_id} awaits its Leader lease, building no index"); + sender.send(Err(e)); + return; + } // Only keep the parts of the version that index builds need, so the // memtables and SST version are not pinned across the awaits below. @@ -294,20 +352,7 @@ impl RegionWorkerLoop { } }; let build_tasks = if request.file_metas.is_empty() { - // Check the version rather than the manifest: a publication committed - // to the manifest but not yet applied is still invisible to queries. - // Its build still holds the file, so the manual task waits for it. - candidates - .into_iter() - .filter(|(file, _)| { - index_needs_rebuild( - ®istry, - &snapshot, - file.meta_ref(), - request.build_type.clone(), - ) - }) - .collect::>() + select_whole_region_builds(candidates, ®istry, &snapshot, &request.build_type) } else { candidates }; @@ -575,12 +620,60 @@ mod tests { use super::*; use crate::sst::file::ColumnIndexMetadata; + use crate::sst::file_purger::NoopFilePurger; use crate::sst::index::handler::{ BuildContext, IndexCreator, IndexKindHandler, PlanEntry, PlannedIndex, }; use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; use crate::test_util::CreateRequestBuilder; + #[test] + fn test_whole_region_flush_build_leaves_files_with_extension_indexes() { + let request = CreateRequestBuilder::new().build_with_index(); + let mut metadata = RegionMetadataBuilder::new(RegionId::new(1, 1)); + metadata.primary_key(request.primary_key); + for column in request.column_metadatas { + metadata.push_column_metadata(column); + } + let snapshot = IndexBuildSnapshot { + metadata: Arc::new(metadata.build().unwrap()), + index_options: IndexOptions::default(), + }; + let registry = + IndexRegistry::new(Default::default(), Default::default(), Default::default()); + let sketched = FileMeta { + file_id: FileId::random(), + indexes: vec![ColumnIndexMetadata { + column_id: 0, + created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex], + ..Default::default() + }], + ..Default::default() + }; + let plain = FileMeta { + file_id: FileId::random(), + ..Default::default() + }; + let select = |build_type| { + let candidates = [&sketched, &plain] + .map(|file| { + let handle = FileHandle::new(file.clone(), Arc::new(NoopFilePurger)); + (handle, FileMetaRef::from(file.clone())) + }) + .to_vec(); + select_whole_region_builds(candidates, ®istry, &snapshot, &build_type) + .into_iter() + .map(|(_, file)| file.file_id) + .collect::>() + }; + + assert_eq!(vec![plain.file_id], select(IndexBuildType::Flush)); + assert_eq!( + vec![sketched.file_id, plain.file_id], + select(IndexBuildType::Manual) + ); + } + #[derive(Debug)] struct MaintenanceHandler;