diff --git a/src/datanode/src/heartbeat.rs b/src/datanode/src/heartbeat.rs index 7127dbbd6a1..357fed74324 100644 --- a/src/datanode/src/heartbeat.rs +++ b/src/datanode/src/heartbeat.rs @@ -307,13 +307,14 @@ impl HeartbeatTask { let total_memory_bytes = self.resource_stat.get_total_memory_bytes(); let resource_stat = self.resource_stat.clone(); let region_alive_keeper = self.region_alive_keeper.clone(); - let gc_limiter = self + let mito_engine = self .region_server .mito_engine() - .context(RegionEngineNotFoundSnafu { name: "mito" })? - .gc_limiter(); + .context(RegionEngineNotFoundSnafu { name: "mito" })?; + let gc_limiter = mito_engine.gc_limiter(); let mut env_var_extensions = HashMap::new(); self.env_vars.into_extensions(&mut env_var_extensions); + let requested_heartbeat = mito_engine.heartbeat_request(); common_runtime::spawn_hb(async move { let sleep = tokio::time::sleep(Duration::from_millis(0)); @@ -346,12 +347,24 @@ impl HeartbeatTask { ..Default::default() }; + // Whether the task waits to reconnect, which a requested heartbeat must not shorten. + let mut in_backoff = false; + // Whether a requested heartbeat must follow the next one, see requested_heartbeat_at. + let mut pending_followup = false; loop { if !running.load(Ordering::Relaxed) { info!("shutdown heartbeat task"); break; } let req = tokio::select! { + // The engine needs the leases of a heartbeat sent from now on. + _ = requested_heartbeat.notified() => { + let (at, followup) = + requested_heartbeat_at(Instant::now(), sleep.deadline(), in_backoff); + sleep.as_mut().reset(at); + pending_followup |= followup; + None + } message = outgoing_rx.recv() => { if let Some(message) = message { match outgoing_message_to_mailbox_message(message) { @@ -417,7 +430,12 @@ impl HeartbeatTask { info.memory_usage_bytes = resource_stat.get_memory_usage_bytes(); } - sleep.as_mut().reset(now + Duration::from_millis(interval)); + let next = if std::mem::take(&mut pending_followup) { + now + Duration::from_millis(1) + } else { + now + Duration::from_millis(interval) + }; + sleep.as_mut().reset(next); Some(req) } // If the heartbeat stream is broken, send a dummy heartbeat request to re-create the heartbeat stream. @@ -457,12 +475,14 @@ impl HeartbeatTask { ); // Triggers to send heartbeat immediately. sleep.as_mut().reset(Instant::now()); + in_backoff = false; } Err(e) => { // Before the META_LEASE_SECS expires, // any retries are meaningless, it always reads the old meta leader address. // Triggers to retry after retry_interval from Metasrv config. sleep.as_mut().reset(Instant::now() + retry_interval); + in_backoff = true; error!(e; "Failed to reconnect to metasrv!"); } } @@ -520,6 +540,23 @@ impl HeartbeatTask { } } +/// Returns when to send the next heartbeat once one is requested at `now`, given the one +/// `scheduled`, and whether another must follow it. A heartbeat due later is brought forward to a +/// millisecond after the request, so its send time, kept in whole milliseconds, is after the +/// request. One due sooner is kept, so requests never postpone a heartbeat; as its send time may +/// not be after the request, another follows it a millisecond after it is sent. While the task +/// waits to reconnect, the scheduled time is kept. +fn requested_heartbeat_at(now: Instant, scheduled: Instant, in_backoff: bool) -> (Instant, bool) { + let soon = now + Duration::from_millis(1); + if in_backoff { + (scheduled, false) + } else if scheduled > soon { + (soon, false) + } else { + (scheduled, true) + } +} + #[cfg(test)] mod tests { use common_meta::cache_invalidator::DummyCacheInvalidator; @@ -531,6 +568,23 @@ mod tests { use super::*; use crate::tests::mock_region_server; + #[test] + fn test_requested_heartbeat_is_sent_after_the_request_and_not_during_backoff() { + let now = Instant::now(); + let soon = now + Duration::from_millis(1); + let scheduled = now + Duration::from_secs(3); + assert_eq!((soon, false), requested_heartbeat_at(now, scheduled, false)); + assert_eq!( + (scheduled, false), + requested_heartbeat_at(now, scheduled, true) + ); + // A heartbeat due sooner, as one an earlier request brought forward, is not postponed; + // another follows it. + assert_eq!((now, true), requested_heartbeat_at(now, now, false)); + let later = now + Duration::from_micros(500); + assert_eq!((soon, true), requested_heartbeat_at(later, soon, false)); + } + const NODE_ID: u64 = 7; async fn kv_backend_with_record(node_epoch: Option) -> KvBackendRef { diff --git a/src/datanode/src/heartbeat/handler/upgrade_region.rs b/src/datanode/src/heartbeat/handler/upgrade_region.rs index 90cc14d7b1d..875e410d6b4 100644 --- a/src/datanode/src/heartbeat/handler/upgrade_region.rs +++ b/src/datanode/src/heartbeat/handler/upgrade_region.rs @@ -138,6 +138,7 @@ impl UpgradeRegionsHandler { metadata_replay_entry_id, replay_timeout, location_id, + candidate_lease_id, .. } = upgrade_region; match timeout { @@ -167,6 +168,7 @@ impl UpgradeRegionsHandler { metadata_entry_id: metadata_last_entry_id, checkpoint, source_node_id: location_id, + candidate_lease_id, }, )); } @@ -342,6 +344,7 @@ mod tests { assert_eq!(request.entry_id, Some(10)); assert_eq!(request.metadata_entry_id, Some(5)); assert_eq!(request.source_node_id, location_id); + assert_eq!(request.candidate_lease_id, Some(9)); Ok(0) })); }); @@ -356,6 +359,7 @@ mod tests { last_entry_id: Some(10), metadata_last_entry_id: Some(5), location_id, + candidate_lease_id: Some(9), replay_timeout: Duration::from_secs(1), ..Default::default() }], diff --git a/src/log-store/src/object_store_wal/store.rs b/src/log-store/src/object_store_wal/store.rs index e7fe49a994b..096331d7093 100644 --- a/src/log-store/src/object_store_wal/store.rs +++ b/src/log-store/src/object_store_wal/store.rs @@ -1414,6 +1414,12 @@ impl LogStore for ObjectStoreLogStore { Ok(bound) } + async fn list_upper_bound(&self, node_id: u64, region_id: RegionId) -> Result> { + let prefix = NodeWalPrefix::try_new(&self.config.node_prefix(node_id, self.generation))?; + let reader = self.node_readers.reader(&prefix)?; + Ok(Some(reader.list_upper_bound(region_id).await?)) + } + async fn read_node( &self, node_id: u64, diff --git a/src/metric-engine/src/engine/catchup.rs b/src/metric-engine/src/engine/catchup.rs index 117796da97a..94ab78475c4 100644 --- a/src/metric-engine/src/engine/catchup.rs +++ b/src/metric-engine/src/engine/catchup.rs @@ -106,9 +106,13 @@ fn mito_catchup_requests( metadata_entry_id: None, }), // The engine loads the logical tables from the metadata region once the catchup - // ends, so the source's unflushed metadata is not left to a background replay: a - // catchup that would need it fails. + // ends, so the source's unflushed metadata is not left to a background replay: as + // the request names no source, a handover fails if the source has entries the + // manifest does not cover. In a takeover, this catchup does not recover the + // source's unflushed metadata yet: it replays only this node's WAL and commits + // with no candidate-lease check. source_node_id: None, + candidate_lease_id: None, }, ), ( @@ -122,6 +126,7 @@ fn mito_catchup_requests( metadata_entry_id: None, }), source_node_id: req.source_node_id, + candidate_lease_id: req.candidate_lease_id, }, ), ] @@ -141,15 +146,23 @@ mod tests { entry_id: Some(10), metadata_entry_id: Some(5), source_node_id: Some(42), + candidate_lease_id: Some(9), ..Default::default() }, ); assert_eq!(utils::to_metadata_region_id(region_id), metadata_region_id); assert_eq!( - (Some(5), None), - (metadata.entry_id, metadata.source_node_id) + (Some(5), None, None), + ( + metadata.entry_id, + metadata.source_node_id, + metadata.candidate_lease_id + ) ); assert_eq!(utils::to_data_region_id(region_id), data_region_id); - assert_eq!((Some(10), Some(42)), (data.entry_id, data.source_node_id)); + assert_eq!( + (Some(10), Some(42), Some(9)), + (data.entry_id, data.source_node_id, data.candidate_lease_id) + ); } } diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index 8f4609def34..a58a3b4c763 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -192,6 +192,10 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes follower's skip-WAL change are refused while the instance is in a catchup, or is fenced while the worker holds a catchup or reload registration for the region (`is_catching_up_or_reloading`); a follower opened after a close is not refused for its predecessor's catchup. + A takeover (no reported entry) is prepared by `prepare_takeovers` in `engine.rs` (manifest + version, one heartbeat request, one WAL listing per source of a region that writes the WAL) + and waits for its candidate lease (`GrantedLeases::wait_for_candidate_lease`) before it + commits after that version. - A leader that is writable, altering or editing replays its pending tails in one background task (`tail_replay.rs`), started by the worker when a lease, catchup or role change makes the region writable, or when it registers a region created or opened diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 3cfecca9008..528450e012a 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -152,7 +152,7 @@ use store_api::region_request::{ }; use store_api::sst_entry::{self, ManifestSstEntry, PuffinIndexMetaEntry, StorageSstEntry}; use store_api::storage::{FileId, FileRefsManifest, RegionId, ScanRequest, SequenceNumber}; -use tokio::sync::{Semaphore, oneshot}; +use tokio::sync::{Notify, Semaphore, oneshot}; use crate::access_layer::RegionFilePathFactory; use crate::cache::{CacheManagerRef, CacheStrategy}; @@ -161,8 +161,9 @@ use crate::config::{MitoConfig, ScanMemoryMode}; use crate::engine::puffin_index::{IndexEntryContext, collect_index_entries_from_puffin}; use crate::error::{ EngineStoppedSnafu, IncrementalQueryStaleSnafu, InvalidRequestSnafu, JoinSnafu, - MitoManifestInfoSnafu, RecvSnafu, RegionNotFoundSnafu, Result, SequenceRangeUnsupportedSnafu, - SerdeJsonSnafu, SerializeColumnMetadataSnafu, SnapshotFenceStaleSnafu, + ListNodeWalSnafu, MitoManifestInfoSnafu, RecvSnafu, RegionNotFoundSnafu, + RemoteWalUnsupportedSnafu, Result, SequenceRangeUnsupportedSnafu, SerdeJsonSnafu, + SerializeColumnMetadataSnafu, SnapshotFenceStaleSnafu, }; #[cfg(feature = "enterprise")] use crate::extension::BoxedExtensionRangeProviderFactory; @@ -175,6 +176,7 @@ use crate::metrics::{ }; use crate::read::scan_region::{ScanRegion, Scanner, exact_sequence_range}; use crate::read::stream::ScanBatchStream; +use crate::region::catchup::{TakeoverPrepared, takeover_source}; use crate::region::opener::{PartitionExprFetcherRef, sanitize_open_request_options}; use crate::region::options::{RegionOptions, parse_wal_options}; use crate::region::{MitoRegionRef, RegionMetadataLoader, RegionRoleState}; @@ -282,6 +284,7 @@ impl<'a, S: LogStore> MitoEngineBuilder<'a, S> { wal_raw_entry_reader: RwLock::new(Some(wal_raw_entry_reader)), scan_memory_tracker, region_hook, + heartbeat_request: Arc::new(Notify::new()), #[cfg(feature = "enterprise")] extension_range_provider_factory: None, }; @@ -354,6 +357,12 @@ impl MitoEngine { self.inner.workers.node_lease_permit() } + /// Returns what the engine notifies when it needs the leases of a heartbeat sent from now on, + /// so the heartbeat task of the node sends a heartbeat soon. + pub fn heartbeat_request(&self) -> Arc { + self.inner.heartbeat_request.clone() + } + /// Renews the lease of this node from a heartbeat response that carries region leases. pub fn renew_node_lease(&self, deadline: Instant) { self.inner.workers.node_lease().renew(deadline); @@ -989,6 +998,9 @@ struct EngineInner { /// The region hook (if any) registered via plugins; exposed for the GC worker /// to fire [`RegionHook::on_region_gc`]. region_hook: Option, + /// Asks the heartbeat task of the node to send a heartbeat now, see + /// [MitoEngine::heartbeat_request]. + heartbeat_request: Arc, #[cfg(feature = "enterprise")] extension_range_provider_factory: Option, } @@ -1163,6 +1175,94 @@ impl EngineInner { Ok(responses) } + /// Prepares the takeovers among `requests`: catchups that make a region whose manifest is + /// published conditionally writable and name a source but no entry it reported. It reads + /// the latest manifest version in storage of each, noting when each read returned, then asks + /// for one heartbeat for them all, then lists the WAL of each source once, so every listing + /// follows every version read. Requests that are not takeovers are left to the worker, which + /// also answers a region that is writable or busy. A failure is only that request's result. + /// Returns what was prepared for each request, at the request's position. + async fn prepare_takeovers( + &self, + parallelism: usize, + requests: &[(RegionId, RegionCatchupRequest)], + ) -> Vec>> { + let mut prepared = Vec::new(); + prepared.resize_with(requests.len(), || None); + let mut takeovers = Vec::new(); + for (position, (region_id, request)) in requests.iter().enumerate() { + let region_id = *region_id; + let Some(region) = self.workers.get_region(region_id) else { + continue; + }; + let Some(source_node_id) = takeover_source(request, ®ion) else { + continue; + }; + let Some(candidate_lease_id) = request.candidate_lease_id else { + let error = InvalidRequestSnafu { + region_id, + reason: "a takeover must name its candidate lease", + }; + prepared[position] = Some(error.fail()); + continue; + }; + takeovers.push((position, region, source_node_id, candidate_lease_id)); + } + if takeovers.is_empty() { + return prepared; + } + + let semaphore = Semaphore::new(parallelism); + let versions = join_all(takeovers.iter().map(|(_, region, _, _)| async { + // Safety: the semaphore is never closed. + let _permit = semaphore.acquire().await.unwrap(); + let version = region.manifest_ctx.latest_stored_version().await; + (version, Instant::now()) + })) + .await; + // A heartbeat sent from now on is after every version read. + self.heartbeat_request.notify_one(); + + // The bound of each source's WAL, or the error of its listing. + let mut bounds: HashMap, Arc>> = + HashMap::new(); + for ((position, region, node_id, candidate_lease_id), (version, read_at)) in + takeovers.into_iter().zip(versions) + { + let region_id = region.region_id; + let result = async { + let version = version?; + let bound = if region.version().options.skip_wal { + None + } else { + let bound = match bounds.get(&node_id) { + Some(bound) => bound.clone(), + None => { + let bound = self + .wal_raw_entry_reader()? + .list_upper_bound(node_id, region_id) + .await + .map_err(Arc::new); + bounds.insert(node_id, bound.clone()); + bound + } + }; + let bound = bound.context(ListNodeWalSnafu { region_id, node_id })?; + Some(bound.context(RemoteWalUnsupportedSnafu { region_id, node_id })?) + }; + Ok(TakeoverPrepared { + version, + read_at, + bound, + candidate_lease_id, + }) + } + .await; + prepared[position] = Some(result); + } + prepared + } + async fn catchup_topic_regions( &self, provider: Provider, @@ -1184,8 +1284,12 @@ impl EngineInner { for ((region_id, request), entry_receiver) in region_requests.into_iter().zip(entry_receivers) { - let (request, receiver) = - WorkerRequest::new_catchup_region_request(region_id, request, Some(entry_receiver)); + let (request, receiver) = WorkerRequest::new_catchup_region_request( + region_id, + request, + Some(entry_receiver), + None, + ); self.workers.submit_to_worker(region_id, request).await?; responses.push(async move { receiver.await.context(RecvSnafu)? }); } @@ -1215,6 +1319,8 @@ impl EngineInner { parallelism: usize, requests: Vec<(RegionId, RegionCatchupRequest)>, ) -> Result)>> { + // A zero parallelism would hold every request on its permit. + let parallelism = parallelism.max(1); let mut responses = Vec::with_capacity(requests.len()); let mut topic_regions: HashMap, Vec<_>> = HashMap::new(); let mut remaining_region_requests = vec![]; @@ -1255,16 +1361,24 @@ impl EngineInner { } if !remaining_region_requests.is_empty() { + let takeovers = self + .prepare_takeovers(parallelism, &remaining_region_requests) + .await; let mut tasks = Vec::with_capacity(remaining_region_requests.len()); let mut region_ids = Vec::with_capacity(remaining_region_requests.len()); - for (region_id, request) in remaining_region_requests { + for ((region_id, request), takeover) in + remaining_region_requests.into_iter().zip(takeovers) + { + // A failed preparation is answered by the worker, which first skips the catchup + // of a region that is writable and awaits no Leader lease. let semaphore_moved = semaphore.clone(); region_ids.push(region_id); tasks.push(async move { // Safety: semaphore must exist let _permit = semaphore_moved.acquire().await.unwrap(); - let (request, receiver) = - WorkerRequest::new_catchup_region_request(region_id, request, None); + let (request, receiver) = WorkerRequest::new_catchup_region_request( + region_id, request, None, takeover, + ); self.workers.submit_to_worker(region_id, request).await?; @@ -2045,6 +2159,7 @@ impl MitoEngine { wal_raw_entry_reader: RwLock::new(Some(wal_raw_entry_reader)), scan_memory_tracker, region_hook: None, + heartbeat_request: Arc::new(Notify::new()), #[cfg(feature = "enterprise")] extension_range_provider_factory: None, }), diff --git a/src/mito2/src/engine/batch_catchup_test.rs b/src/mito2/src/engine/batch_catchup_test.rs index 62dd55fb5ae..e79d4a98d18 100644 --- a/src/mito2/src/engine/batch_catchup_test.rs +++ b/src/mito2/src/engine/batch_catchup_test.rs @@ -186,6 +186,7 @@ async fn test_batch_catchup_with_format(factory: Option, flat_f metadata_entry_id: None, checkpoint: None, source_node_id: None, + candidate_lease_id: None, }, ) }) @@ -233,6 +234,7 @@ async fn test_batch_catchup_err_with_format(factory: Option, fl metadata_entry_id: None, checkpoint: None, source_node_id: None, + candidate_lease_id: None, }, ) }) 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 d928e65ad36..d57ef16f706 100644 --- a/src/mito2/src/engine/object_store_wal_recovery_test.rs +++ b/src/mito2/src/engine/object_store_wal_recovery_test.rs @@ -2082,6 +2082,7 @@ async fn test_catchup_again_failed_replay_keeps_rows(#[case] empty_replay: bool) ..Default::default() }, Some(WalEntryReceiver::new(entry_receiver, start_sender)), + None, ); // The replay reads no entry. drop(entry_sender); diff --git a/src/mito2/src/engine/set_role_state_test.rs b/src/mito2/src/engine/set_role_state_test.rs index 431b2a1ef5f..f9af900e72f 100644 --- a/src/mito2/src/engine/set_role_state_test.rs +++ b/src/mito2/src/engine/set_role_state_test.rs @@ -1568,6 +1568,7 @@ async fn test_downgrade_during_alter_keeps_acknowledged_writes_with_local_wal() metadata_entry_id: None, checkpoint: None, source_node_id: None, + candidate_lease_id: None, }), ) .await diff --git a/src/mito2/src/engine/tail_replay_test.rs b/src/mito2/src/engine/tail_replay_test.rs index b784aa85779..9796431c1f4 100644 --- a/src/mito2/src/engine/tail_replay_test.rs +++ b/src/mito2/src/engine/tail_replay_test.rs @@ -14,6 +14,7 @@ //! Tests for the background replay of pending WAL tails. +use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -30,11 +31,12 @@ use common_recordbatch::RecordBatches; use common_wal::config::object_store::FIXED_DIRECTORY_GENERATION; use common_wal::options::WAL_OPTIONS_KEY; use datatypes::arrow::array::Array; +use futures::FutureExt; use log_store::ObjectStoreLogStore; use log_store::object_store_wal::{NodeWalPrefix, ObjectStoreWalReaders}; use object_store::ObjectStore; use object_store::layers::mock::{ - Buffer, Entry as ListEntry, Error as MockError, ErrorKind, List, Metadata, MockLayer, + Buffer, Entry as ListEntry, Error as MockError, ErrorKind, List, Lister, Metadata, MockLayer, MockLayerBuilder, Result as MockResult, Write, Writer, }; use object_store::services::Memory; @@ -51,6 +53,7 @@ use store_api::region_request::{ RegionRequest, RegionTruncateRequest, StagingPartitionDirective, }; use store_api::storage::{RegionId, ScanRequest}; +use tokio::sync::Semaphore; use tokio::task::JoinHandle; use crate::config::MitoConfig; @@ -70,6 +73,7 @@ use crate::manifest::action::{ WalRecoveryEdit, }; use crate::manifest::storage::delta_file; +use crate::region::catchup::TakeoverPrepared; use crate::region::version::VersionRef; use crate::region::{MitoRegion, RegionLeaderState, RegionRoleState}; use crate::request::{BackgroundNotify, WorkerRequest}; @@ -1628,6 +1632,59 @@ impl List for StalledLister { } } +/// Counts the listings of the paths its layer targets and, while `held` is set, holds each until +/// `release` has a permit. +struct ListingGate { + listed: AtomicUsize, + held: AtomicBool, + release: Semaphore, +} + +impl ListingGate { + fn new() -> Arc { + Arc::new(Self { + listed: AtomicUsize::new(0), + held: AtomicBool::new(false), + release: Semaphore::new(0), + }) + } + + fn layer(self: &Arc, is_target: fn(&str) -> bool) -> MockLayer { + let gate = self.clone(); + MockLayerBuilder::default() + .lister_factory(Arc::new(move |path, _args, inner| { + if !is_target(path) { + return inner; + } + gate.listed.fetch_add(1, Ordering::Relaxed); + if gate.held.load(Ordering::Relaxed) { + let gate = gate.clone(); + Box::new(HeldLister { gate, inner }) + } else { + inner + } + })) + .build() + .unwrap() + } + + fn listed(&self) -> usize { + self.listed.load(Ordering::Relaxed) + } +} + +struct HeldLister { + gate: Arc, + inner: Lister, +} + +impl List for HeldLister { + async fn next(&mut self) -> MockResult> { + drop(self.gate.release.acquire().await); + self.inner.next().await + } +} + #[rstest] #[case::close(false)] #[case::engine_stop(true)] @@ -3756,3 +3813,972 @@ async fn test_handover_commit_conflict_can_be_retried() { region.wait_until_replayed().await; assert_eq!(9, count_rows(®ion.engine, region.region_id).await); } + +const CANDIDATE_LEASE_ID: u64 = 7; +const TAKEOVER_TIMEOUT: Duration = Duration::from_secs(10); + +/// Returns a takeover from [REMOTE_NODE_ID]: a catchup that makes the region writable and names +/// its source but no entry the source reported. +fn takeover_request(candidate_lease_id: Option) -> RegionCatchupRequest { + RegionCatchupRequest { + set_writable: true, + source_node_id: Some(REMOTE_NODE_ID), + candidate_lease_id, + ..Default::default() + } +} + +/// Sends `requests` through the engine's batch entry, which prepares the takeovers among them, +/// after letting the regions write until the node's deadline once they are writable. +fn spawn_batch_catchup( + engine: &MitoEngine, + requests: Vec<(RegionId, RegionCatchupRequest)>, +) -> tokio::task::JoinHandle)>> { + engine.renew_node_lease(Instant::now() + Duration::from_secs(60)); + let engine = engine.clone(); + // Every region waits for its lease while it holds a permit. + let parallelism = requests.len(); + tokio::spawn(async move { + engine + .handle_batch_catchup_requests(parallelism, requests) + .await + .unwrap() + }) +} + +impl TestRegion { + fn spawn_take_over( + &self, + request: RegionCatchupRequest, + ) -> tokio::task::JoinHandle> { + let catchup = spawn_batch_catchup(&self.engine, vec![(self.region_id, request)]); + tokio::spawn(async move { + let mut responses = catchup.await.unwrap(); + assert_eq!(1, responses.len()); + responses.pop().unwrap().1 + }) + } + + /// Sends `request` through the engine's batch entry and returns the region's result. + async fn take_over(&self, request: RegionCatchupRequest) -> Result { + let catchup = self.spawn_take_over(request); + tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap() + } + + /// Sends a takeover of candidate [CANDIDATE_LEASE_ID], waits until it waits for its lease, + /// then records a lease of candidate `granted` for a heartbeat sent now. Returns the result. + async fn take_over_granting(&self, granted: u64) -> Result { + let catchup = self.spawn_take_over(takeover_request(Some(CANDIDATE_LEASE_ID))); + self.wait_until_lease_waited().await; + assert!(!catchup.is_finished()); + self.record_lease(Some(granted)); + tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap() + } + + fn is_waiting_for_lease(&self) -> bool { + let workers = &self.engine.inner.workers; + workers.granted_leases().is_waiting(self.region_id) + } + + async fn wait_until_lease_waited(&self) { + wait_until(|| self.is_waiting_for_lease()).await; + } + + /// Records a lease of candidate `candidate_lease_id` for a heartbeat sent now, which is after + /// every takeover that already waits for its lease began. + fn record_lease(&self, candidate_lease_id: Option) { + self.engine + .record_granted_lease(self.region_id, Instant::now(), candidate_lease_id); + } + + /// Submits a takeover with `prepared` to the worker directly and returns its result. + async fn take_over_prepared(&self, prepared: TakeoverPrepared) -> crate::error::Result { + let (request, response) = WorkerRequest::new_catchup_region_request( + self.region_id, + takeover_request(Some(CANDIDATE_LEASE_ID)), + None, + Some(Ok(prepared)), + ); + let workers = &self.engine.inner.workers; + workers + .submit_to_worker(self.region_id, request) + .await + .unwrap(); + tokio::time::timeout(TAKEOVER_TIMEOUT, response) + .await + .unwrap() + .unwrap() + } + + async fn set_skip_wal(&self) { + self.engine + .handle_request(self.region_id, set_skip_wal_request(true)) + .await + .unwrap(); + } +} + +fn takeover_prepared(version: u64, bound: Option) -> TakeoverPrepared { + TakeoverPrepared { + version, + read_at: Instant::now(), + bound, + candidate_lease_id: CANDIDATE_LEASE_ID, + } +} + +fn assert_candidate_lease_not_received(error: &BoxedError) { + assert!( + matches!( + error.as_any().downcast_ref::(), + Some(Error::CandidateLeaseNotReceived { .. }) + ), + "{error:?}" + ); + assert!(error.retry_hint().is_retryable()); +} + +/// A takeover lists the source's WAL for a bound, waits for the lease of its candidate, then +/// records a listed tail of the source up to that bound and this node's handoff floor, without +/// replaying any WAL. The tail is replayed in the background, and its unread part stays until a +/// Leader lease arrives. +#[tokio::test] +async fn test_takeover_records_listed_tail_and_replays_it() { + let region = TestRegion::new("takeover-records-tail", true, None).await; + region.flush_and_demote().await; + let flushed = region.version().flushed_entry_id; + region.write_handed_over_remote_rows().await; + let bound = region.remote_listed_bound().await; + region.listener.hold_from(1); + + region.take_over_granting(CANDIDATE_LEASE_ID).await.unwrap(); + + let mito_region = region.engine.get_region(region.region_id).unwrap(); + assert!(mito_region.is_writable()); + let tails = vec![remote_tail(flushed, bound, UptoKind::Listed)]; + assert_eq!(tails, region.version().pending_tails); + let manifest = region.manifest().await; + assert_eq!(tails, manifest.pending_tails); + assert!(manifest.handoff_floors[&NODE_ID] >= bound); + + region.listener.hold_from(0); + region.promote_with_lease(); + region.wait_until_replayed().await; + assert_eq!(9, count_rows(®ion.engine, region.region_id).await); +} + +/// The batch entry prepares each takeover on its own: one heartbeat request for the batch, one +/// listing per source, and a failure only for the region whose source cannot be listed. Neither +/// the heartbeat request nor a listing comes before every manifest version read returned. Other +/// catchups are left as they are. +#[tokio::test] +async fn test_batch_prepares_each_takeover_on_its_own() { + let (manifests, wal) = (ListingGate::new(), ListingGate::new()); + let layers = (manifests.layer(is_manifest), wal.layer(is_remote_wal)); + let region = + TestRegion::with_wal_layer("takeover-batch", true, Some(layers.0), Some(layers.1)).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + // B is taken over from the same source as A, C from a node whose WAL is empty, and D is + // caught up as before. + let [b, c, d] = [2, 3, 4].map(|number| RegionId::new(1, number)); + for region_id in [b, c, d] { + create_leased_region_on(®ion.engine, region_id).await; + region + .engine + .set_region_role(region_id, RegionRole::Follower) + .unwrap(); + } + let requested = region.engine.heartbeat_request(); + let requests = Arc::new(AtomicUsize::new(0)); + let counter = { + let requests = requests.clone(); + tokio::spawn(async move { + loop { + requested.notified().await; + requests.fetch_add(1, Ordering::Relaxed); + } + }) + }; + let (manifests_before, listed_before) = (manifests.listed(), wal.listed()); + manifests.held.store(true, Ordering::Relaxed); + let takeover = takeover_request(Some(CANDIDATE_LEASE_ID)); + let catchup = spawn_batch_catchup( + ®ion.engine, + vec![ + (region.region_id, takeover), + (b, takeover), + ( + c, + RegionCatchupRequest { + source_node_id: Some(REMOTE_NODE_ID + 8), + ..takeover + }, + ), + ( + d, + RegionCatchupRequest { + set_writable: true, + ..Default::default() + }, + ), + ], + ); + // The version reads of the three takeovers are held. + wait_until(|| manifests.listed() >= manifests_before + 3).await; + assert_eq!(0, requests.load(Ordering::Relaxed)); + assert_eq!(listed_before, wal.listed()); + manifests.held.store(false, Ordering::Relaxed); + manifests.release.add_permits(1); + let leases = region.engine.inner.workers.granted_leases(); + wait_until(|| leases.is_waiting(region.region_id) && leases.is_waiting(b)).await; + assert_eq!(listed_before + 1, wal.listed()); + for region_id in [region.region_id, b] { + region + .engine + .record_granted_lease(region_id, Instant::now(), Some(CANDIDATE_LEASE_ID)); + } + + let results = tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap() + .into_iter() + .collect::>(); + + for region_id in [region.region_id, b, d] { + results[®ion_id].as_ref().unwrap(); + assert!(region.engine.get_region(region_id).unwrap().is_writable()); + } + let error = results[&c].as_ref().unwrap_err(); + assert!( + matches!( + error.as_any().downcast_ref::(), + Some(Error::ListNodeWal { .. }) + ), + "{error:?}" + ); + assert!(region.engine.get_region(c).unwrap().is_follower()); + assert_eq!(1, requests.load(Ordering::Relaxed)); + counter.abort(); +} + +/// A takeover that names no candidate lease fails before it reads the manifest, asks for a +/// heartbeat or lists any WAL, and changes nothing. +#[tokio::test] +async fn test_takeover_without_candidate_lease_fails_before_it_starts() { + let (manifests, wal) = (ListingGate::new(), ListingGate::new()); + let layers = (manifests.layer(is_manifest), wal.layer(is_remote_wal)); + let region = TestRegion::with_wal_layer( + "takeover-no-candidate", + true, + Some(layers.0), + Some(layers.1), + ) + .await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let version = next_manifest_version(&mito_region).await; + let listed = (manifests.listed(), wal.listed()); + + let error = region.take_over(takeover_request(None)).await.unwrap_err(); + + assert_eq!( + StatusCode::InvalidArguments, + error.status_code(), + "{error:?}" + ); + assert_eq!(listed, (manifests.listed(), wal.listed())); + let requested = region.engine.heartbeat_request(); + assert!(requested.notified().now_or_never().is_none()); + assert!(mito_region.is_follower()); + assert_eq!(version, next_manifest_version(&mito_region).await); +} + +/// Two takeovers of one region in a batch each take their own preparation: the one whose source +/// can be listed takes the region over from it, and the other fails, with its listing error or as +/// the region is busy. +#[tokio::test] +async fn test_batch_takeovers_of_one_region_keep_their_own_preparation() { + let region = TestRegion::new("takeover-same-region", true, None).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + let takeover = takeover_request(Some(CANDIDATE_LEASE_ID)); + let empty_source = RegionCatchupRequest { + source_node_id: Some(REMOTE_NODE_ID + 8), + candidate_lease_id: Some(CANDIDATE_LEASE_ID + 1), + ..takeover + }; + let requests = vec![ + (region.region_id, takeover), + (region.region_id, empty_source), + ]; + let catchup = spawn_batch_catchup(®ion.engine, requests); + region.wait_until_lease_waited().await; + region.record_lease(Some(CANDIDATE_LEASE_ID)); + + let results = tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap(); + + let errors = results + .iter() + .filter_map(|(_, result)| result.as_ref().err()) + .collect::>(); + assert_eq!(1, errors.len(), "{results:?}"); + assert!( + matches!( + errors[0].as_any().downcast_ref::(), + Some(Error::ListNodeWal { .. } | Error::RegionBusy { .. }) + ), + "{:?}", + errors[0] + ); + assert!( + region + .engine + .get_region(region.region_id) + .unwrap() + .is_writable() + ); +} + +/// A takeover that reaches the worker without what the engine prepares, as through the engine's +/// single-request entry, fails instead of replaying this node's WAL, and ends its catchup, so a +/// Leader lease promotes the region again. So does one that reaches a region awaiting its Leader +/// lease. +#[rstest] +#[case::follower(false)] +#[case::awaiting_leader_lease(true)] +#[tokio::test] +async fn test_takeover_sent_to_the_worker_directly_fails(#[case] awaiting: bool) { + let region = TestRegion::new("takeover-not-prepared", true, None).await; + region.flush_and_demote().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + if awaiting { + let manifest_ctx = &mito_region.manifest_ctx; + manifest_ctx.start_leader_lease_wait_for_test(region.region_id); + } + let catchup = RegionRequest::Catchup(takeover_request(Some(CANDIDATE_LEASE_ID))); + + let error = region + .engine + .handle_request(region.region_id, catchup) + .await + .unwrap_err(); + + assert_eq!( + StatusCode::InvalidArguments, + error.status_code(), + "{error:?}" + ); + assert!(!is_replaced(®ion.engine, &mito_region)); + assert!(mito_region.is_follower()); + assert!(!region.has_pending_tails()); + region.promote_with_lease(); + assert!(mito_region.is_writable()); +} + +/// A takeover fails retryably when its region's manifest is not the version it began from: when +/// the region already holds a newer one, or when it is behind and its reopen finds yet another. +#[rstest] +#[case::past_version(false)] +#[case::reopened_past_version(true)] +#[tokio::test] +async fn test_takeover_of_region_not_at_its_version_is_busy(#[case] behind: bool) { + let region = TestRegion::new("takeover-not-at-version", true, None).await; + region.flush_and_demote().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let installed = mito_region.manifest_ctx.manifest_version().await; + let version = if behind { + // Two writers committed since the takeover read its version. + let store = region.env.get_object_store().unwrap(); + for version in [installed + 1, installed + 2] { + let delta = encode_delta(nop_action()).await; + publish_delta(&store, ®ion.region_dir(), version, delta).await; + } + installed + 1 + } else { + installed - 1 + }; + + let error = region + .take_over_prepared(takeover_prepared(version, Some(region.entries[1]))) + .await + .unwrap_err(); + + assert!(matches!(error, Error::RegionBusy { .. }), "{error:?}"); + assert_eq!(behind, is_replaced(®ion.engine, &mito_region)); + let current = region.engine.get_region(region.region_id).unwrap(); + assert!(current.is_follower()); + // The catchup ended, also on a reopened instance, so a Leader lease promotes it. + region.promote_with_lease(); + assert!(current.is_writable()); +} + +/// A takeover fails retryably when the region's choice to skip the WAL changed since the takeover +/// was prepared, in either direction. +#[rstest] +#[case::listed_but_skips_wal(true)] +#[case::not_listed_but_writes_wal(false)] +#[tokio::test] +async fn test_takeover_after_skip_wal_changed_is_busy(#[case] skips_wal: bool) { + let region = TestRegion::new("takeover-skip-wal-changed", true, None).await; + region.flush_and_demote().await; + if skips_wal { + region.set_skip_wal().await; + } + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let installed = mito_region.manifest_ctx.manifest_version().await; + // The takeover was prepared for the other choice. + let bound = if skips_wal { + Some(region.entries[1]) + } else { + None + }; + + let error = region + .take_over_prepared(takeover_prepared(installed, bound)) + .await + .unwrap_err(); + + assert!(matches!(error, Error::RegionBusy { .. }), "{error:?}"); + assert!(mito_region.is_follower()); + assert_eq!(installed, mito_region.manifest_ctx.manifest_version().await); +} + +/// A takeover reopens a region whose manifest is behind the version the takeover began from, and +/// commits the version after it. +#[tokio::test] +async fn test_takeover_reopens_region_behind_its_version() { + let region = TestRegion::new("takeover-behind-version", true, None).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let version = next_manifest_version(&mito_region).await; + let store = region.env.get_object_store().unwrap(); + publish_delta( + &store, + ®ion.region_dir(), + version, + encode_delta(nop_action()).await, + ) + .await; + + region.take_over_granting(CANDIDATE_LEASE_ID).await.unwrap(); + + assert!(is_replaced(®ion.engine, &mito_region)); + assert_eq!(version + 1, region.manifest().await.manifest_version); +} + +/// A takeover fails retryably, committing nothing, when the lease that arrives after it began is +/// not its candidate's, also when that lease arrives after the wait ended but before the commit. +#[rstest] +#[case::during_wait(false)] +#[case::before_commit(true)] +#[tokio::test] +async fn test_takeover_fails_on_lease_of_another_candidate(#[case] before_commit: bool) { + let region = TestRegion::new("takeover-other-candidate", true, None).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let version = next_manifest_version(&mito_region).await; + + let error = if before_commit { + // The hand-off waits for the object that carries its record while the candidate's lease + // ends the wait; a later lease then replaces it. + region.log_store.hold_creates(); + let catchup = region.spawn_take_over(takeover_request(Some(CANDIDATE_LEASE_ID))); + tokio::time::timeout( + TAKEOVER_TIMEOUT, + region.log_store.wait_for_parked_creates(1), + ) + .await + .unwrap() + .unwrap(); + region.wait_until_lease_waited().await; + region.record_lease(Some(CANDIDATE_LEASE_ID)); + wait_until(|| !region.is_waiting_for_lease()).await; + region.engine.record_granted_lease( + region.region_id, + Instant::now() + Duration::from_millis(2), + None, + ); + region.log_store.release_creates(); + tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap() + .unwrap_err() + } else { + region + .take_over_granting(CANDIDATE_LEASE_ID + 1) + .await + .unwrap_err() + }; + + assert_candidate_lease_not_received(&error); + assert!(mito_region.is_follower()); + assert_eq!(version, next_manifest_version(&mito_region).await); +} + +/// A lease of the candidate sent before the takeover began does not complete it: the takeover +/// keeps waiting, here until the lease of this node expires. +#[tokio::test] +async fn test_takeover_ignores_candidate_lease_sent_before_it_began() { + let region = TestRegion::new("takeover-early-lease", true, None).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let version = next_manifest_version(&mito_region).await; + let sent_before = Instant::now(); + region + .engine + .record_granted_lease(region.region_id, sent_before, Some(CANDIDATE_LEASE_ID)); + region.log_store.hold_creates(); + let catchup = region.spawn_take_over(takeover_request(Some(CANDIDATE_LEASE_ID))); + tokio::time::timeout( + TAKEOVER_TIMEOUT, + region.log_store.wait_for_parked_creates(1), + ) + .await + .unwrap() + .unwrap(); + region.wait_until_lease_waited().await; + + // The lease of this node expires, and an older lease wakes the wait. + region + .engine + .freeze_lease_clock(Instant::now() + Duration::from_secs(61)); + region.engine.record_granted_lease( + region.region_id, + sent_before - Duration::from_millis(1), + Some(CANDIDATE_LEASE_ID), + ); + let error = tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap() + .unwrap_err(); + + region.log_store.release_creates(); + assert_candidate_lease_not_received(&error); + assert!(format!("{error:?}").contains("expired"), "{error:?}"); + assert!(mito_region.is_follower()); + assert_eq!(version, next_manifest_version(&mito_region).await); +} + +/// A close while a takeover waits for its candidate lease ends the takeover, committing nothing. +#[tokio::test] +async fn test_close_ends_takeover_waiting_for_lease() { + let region = TestRegion::new("takeover-closed", true, None).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + let store = region.env.get_object_store().unwrap(); + let manifest_dir = format!("{}/manifest/", region.region_dir()); + let manifests = store.list(&manifest_dir).await.unwrap().len(); + let catchup = region.spawn_take_over(takeover_request(Some(CANDIDATE_LEASE_ID))); + region.wait_until_lease_waited().await; + + let close = RegionRequest::Close(RegionCloseRequest::default()); + region + .engine + .handle_request(region.region_id, close) + .await + .unwrap(); + let error = tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap() + .unwrap_err(); + + assert_eq!(StatusCode::RegionNotFound, error.status_code(), "{error:?}"); + assert_eq!(manifests, store.list(&manifest_dir).await.unwrap().len()); +} + +/// A takeover whose hand-off fails ends without waiting for its candidate lease. +#[tokio::test] +async fn test_takeover_whose_handoff_fails_ends_the_wait() { + let region = TestRegion::new("takeover-handoff-fails", true, None).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + region.log_store.fail_creates(); + + let error = region + .take_over(takeover_request(Some(CANDIDATE_LEASE_ID))) + .await + .unwrap_err(); + + assert!( + matches!( + error.as_any().downcast_ref::(), + Some(Error::HandoffWal { .. }) + ), + "{error:?}" + ); + assert!(error.retry_hint().is_retryable()); + let mito_region = region.engine.get_region(region.region_id).unwrap(); + assert!(mito_region.is_follower()); +} + +/// A takeover of a region that skips the WAL lists nothing and hands nothing over to the log +/// store; it waits for its candidate lease and commits an empty edit, or nothing if the lease is +/// another candidate's or a later lease of no candidate arrives before the commit. +#[rstest] +#[case::candidate(CANDIDATE_LEASE_ID, false)] +#[case::another_candidate(CANDIDATE_LEASE_ID + 1, false)] +#[case::another_lease_before_commit(CANDIDATE_LEASE_ID, true)] +#[tokio::test] +async fn test_takeover_of_region_that_skips_wal(#[case] granted: u64, #[case] before_commit: bool) { + let region = TestRegion::new("takeover-skip-wal", true, None).await; + region.flush_and_demote().await; + region.set_skip_wal().await; + let manifest = region.manifest().await; + // A hand-off would fail, and so would a listing: the source wrote no WAL. + region.log_store.fail_creates(); + + let result = if before_commit { + // The candidate's lease ends the wait while the manifest lock is held; a later lease + // then replaces it. + let catchup = region.spawn_take_over(takeover_request(Some(CANDIDATE_LEASE_ID))); + region.wait_until_lease_waited().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let manager = mito_region.manifest_ctx.manifest_manager.write().await; + region.record_lease(Some(CANDIDATE_LEASE_ID)); + wait_until(|| !region.is_waiting_for_lease()).await; + region.engine.record_granted_lease( + region.region_id, + Instant::now() + Duration::from_millis(2), + None, + ); + drop(manager); + tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap() + } else { + region.take_over_granting(granted).await + }; + + let caught_up = region.manifest().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + if granted == CANDIDATE_LEASE_ID && !before_commit { + result.unwrap(); + assert_eq!(manifest.manifest_version + 1, caught_up.manifest_version); + assert!(caught_up.handoff_floors.is_empty()); + assert!(caught_up.pending_tails.is_empty()); + assert!(mito_region.is_writable()); + } else { + assert_candidate_lease_not_received(&result.unwrap_err()); + assert_eq!(manifest.manifest_version, caught_up.manifest_version); + assert!(mito_region.is_follower()); + } +} + +/// A takeover repeated before the Leader lease, as a retry of the same migration sends it, catches +/// the region up again into a replacement and promotes it. The listed tail of the first takeover +/// stays recorded and is replayed once the Leader lease arrives. +#[tokio::test] +async fn test_repeated_takeover_before_leader_lease_succeeds() { + let region = TestRegion::new("takeover-repeated", true, None).await; + region.flush_and_demote().await; + let flushed = region.version().flushed_entry_id; + region.write_handed_over_remote_rows().await; + let bound = region.remote_listed_bound().await; + region.listener.hold_from(1); + region.take_over_granting(CANDIDATE_LEASE_ID).await.unwrap(); + let mito_region = region.engine.get_region(region.region_id).unwrap(); + + region.take_over_granting(CANDIDATE_LEASE_ID).await.unwrap(); + + assert!(is_replaced(®ion.engine, &mito_region)); + let replacement = region.engine.get_region(region.region_id).unwrap(); + assert!(replacement.is_writable()); + let tails = vec![remote_tail(flushed, bound, UptoKind::Listed)]; + assert_eq!(tails, region.manifest().await.pending_tails); + region.listener.hold_from(0); + region.promote_with_lease(); + region.wait_until_replayed().await; + assert_eq!(9, count_rows(®ion.engine, region.region_id).await); +} + +/// A takeover of a region that awaits its Leader lease commits nothing and keeps the region a +/// Follower when the lease after it began is another candidate's, or when a later lease of no +/// candidate arrives after the wait ended but before the commit. +#[rstest] +#[case::another_candidate(false)] +#[case::another_lease_before_commit(true)] +#[tokio::test] +async fn test_takeover_of_region_awaiting_leader_lease_fails_on_lease(#[case] before_commit: bool) { + let region = TestRegion::new("takeover-awaiting-leader-lease", true, None).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + mito_region + .manifest_ctx + .start_leader_lease_wait_for_test(region.region_id); + let version = mito_region + .manifest_ctx + .latest_stored_version() + .await + .unwrap(); + + let catchup = region.spawn_take_over(takeover_request(Some(CANDIDATE_LEASE_ID))); + region.wait_until_lease_waited().await; + // The worker checks the lease again under the manifest lock of the region it replaces. + let manager = mito_region.manifest_ctx.manifest_manager.write().await; + if before_commit { + region.record_lease(Some(CANDIDATE_LEASE_ID)); + wait_until(|| !region.is_waiting_for_lease()).await; + region.engine.record_granted_lease( + region.region_id, + Instant::now() + Duration::from_millis(2), + None, + ); + } else { + region.record_lease(Some(CANDIDATE_LEASE_ID + 1)); + } + drop(manager); + let result = tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap(); + + assert_candidate_lease_not_received(&result.unwrap_err()); + assert!(!is_replaced(®ion.engine, &mito_region)); + assert!(mito_region.is_follower()); + let stored = mito_region.manifest_ctx.latest_stored_version().await; + assert_eq!(version, stored.unwrap()); +} + +/// A takeover of a region that awaits its Leader lease fails retryably, committing nothing, when +/// its replacement opens a manifest past the version the takeover began from. +#[tokio::test] +async fn test_takeover_caught_up_again_past_its_version_is_busy() { + let region = TestRegion::new("takeover-again-past-version", true, None).await; + region.flush_and_demote().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let manifest_ctx = &mito_region.manifest_ctx; + manifest_ctx.start_leader_lease_wait_for_test(region.region_id); + let installed = manifest_ctx.manifest_version().await; + // Another writer committed after the takeover read its version. + let store = region.env.get_object_store().unwrap(); + let delta = encode_delta(nop_action()).await; + publish_delta(&store, ®ion.region_dir(), installed + 1, delta).await; + + let prepared = takeover_prepared(installed, Some(region.entries[1])); + let deadline = Instant::now() + Duration::from_secs(60); + region.engine.renew_node_lease(deadline); + let (result, ()) = tokio::join!(region.take_over_prepared(prepared), async { + region.wait_until_lease_waited().await; + region.record_lease(Some(CANDIDATE_LEASE_ID)); + }); + + let error = result.unwrap_err(); + assert!(matches!(error, Error::RegionBusy { .. }), "{error:?}"); + assert!(!is_replaced(®ion.engine, &mito_region)); + assert!(mito_region.is_follower()); + let stored = manifest_ctx.latest_stored_version().await; + assert_eq!(installed + 1, stored.unwrap()); +} + +/// A catchup that names a source but no entry, on a region whose manifest is not published +/// conditionally, is not a takeover: it replays this node's WAL. +#[tokio::test] +async fn test_catchup_naming_source_of_region_not_published_conditionally() { + let region = TestRegion::new("takeover-not-conditional", false, None).await; + let region_id = region.region_id; + region + .engine + .set_region_role(region_id, RegionRole::Follower) + .unwrap(); + + region + .take_over(takeover_request(Some(CANDIDATE_LEASE_ID))) + .await + .unwrap(); + + assert!(region.engine.get_region(region_id).unwrap().is_writable()); + assert_eq!(6, count_rows(®ion.engine, region_id).await); +} + +/// A takeover whose candidate lease arrived commits nothing if the lease of this node expired +/// before the commit, also on a region that skips the WAL, which hands nothing over to the log +/// store. +#[tokio::test] +async fn test_takeover_after_node_lease_expired_commits_nothing() { + let region = TestRegion::new("takeover-node-lease-expired", true, None).await; + region.flush_and_demote().await; + region.set_skip_wal().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let version = next_manifest_version(&mito_region).await; + let catchup = region.spawn_take_over(takeover_request(Some(CANDIDATE_LEASE_ID))); + region.wait_until_lease_waited().await; + + let manager = mito_region.manifest_ctx.manifest_manager.write().await; + region.record_lease(Some(CANDIDATE_LEASE_ID)); + wait_until(|| !region.is_waiting_for_lease()).await; + // The batch entry renewed the lease of this node for 60 seconds. + region + .engine + .freeze_lease_clock(Instant::now() + Duration::from_secs(61)); + drop(manager); + let error = tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap() + .unwrap_err(); + + assert_candidate_lease_not_received(&error); + assert!(format!("{error:?}").contains("expired"), "{error:?}"); + assert!(mito_region.is_follower()); + assert_eq!(version, next_manifest_version(&mito_region).await); +} + +/// A takeover whose preparation failed, here as the source's WAL holds no object, still gets the +/// answer every catchup of a writable region that awaits no Leader lease gets: it is skipped. +#[tokio::test] +async fn test_takeover_of_writable_leader_skips_failed_preparation() { + let region = TestRegion::new("takeover-writable-leader", true, None).await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + assert!(mito_region.is_writable()); + assert!(!mito_region.manifest_ctx.awaits_leader_lease()); + + region + .take_over(takeover_request(Some(CANDIDATE_LEASE_ID))) + .await + .unwrap(); + + assert!(!is_replaced(®ion.engine, &mito_region)); + assert!(mito_region.is_writable()); +} + +/// A takeover whose source's WAL holds no object fails with the listing's status, as that region's +/// own result, before it hands anything over. +#[tokio::test] +async fn test_takeover_of_empty_source_wal_fails() { + let region = TestRegion::new("takeover-empty-source", true, None).await; + region.flush_and_demote().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let version = next_manifest_version(&mito_region).await; + + let error = region + .take_over(takeover_request(Some(CANDIDATE_LEASE_ID))) + .await + .unwrap_err(); + + assert!( + matches!( + error.as_any().downcast_ref::(), + Some(Error::ListNodeWal { .. }) + ), + "{error:?}" + ); + assert_eq!(StatusCode::InvalidArguments, error.status_code()); + assert!(!error.retry_hint().is_retryable()); + assert!(mito_region.is_follower()); + assert_eq!(version, next_manifest_version(&mito_region).await); +} + +/// A takeover whose listing of the source's WAL fails transiently fails with that listing's +/// status and retry hint. +#[tokio::test] +async fn test_takeover_whose_source_listing_fails_transiently_is_retryable() { + let fail = Arc::new(AtomicBool::new(false)); + let failing = fail.clone(); + let layer = MockLayerBuilder::default() + .lister_factory(Arc::new(move |path, _args, inner| { + if is_remote_wal(path) && failing.load(Ordering::Relaxed) { + Box::new(FailingLister) + } else { + inner + } + })) + .build() + .unwrap(); + let region = + TestRegion::with_wal_layer("takeover-listing-fails", true, None, Some(layer)).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + fail.store(true, Ordering::Relaxed); + + let error = region + .take_over(takeover_request(Some(CANDIDATE_LEASE_ID))) + .await + .unwrap_err(); + + assert!( + matches!( + error.as_any().downcast_ref::(), + Some(Error::ListNodeWal { .. }) + ), + "{error:?}" + ); + assert_eq!(StatusCode::StorageUnavailable, error.status_code()); + assert!(error.retry_hint().is_retryable()); +} + +struct FailingLister; + +impl List for FailingLister { + async fn next(&mut self) -> MockResult> { + Err(MockError::new(ErrorKind::Unexpected, "listing failed").set_temporary()) + } +} + +/// A takeover fails retryably, committing nothing, when the region's manifest moves past the +/// version it began from while it waits for its candidate lease. +#[tokio::test] +async fn test_takeover_whose_manifest_moves_during_the_wait_is_busy() { + let region = TestRegion::new("takeover-moved-during-wait", true, None).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let catchup = region.spawn_take_over(takeover_request(Some(CANDIDATE_LEASE_ID))); + region.wait_until_lease_waited().await; + + let mut manager = mito_region.manifest_ctx.manifest_manager.write().await; + let version = manager.update(nop_action(), false).await.unwrap(); + drop(manager); + region.record_lease(Some(CANDIDATE_LEASE_ID)); + let error = tokio::time::timeout(TAKEOVER_TIMEOUT, catchup) + .await + .unwrap() + .unwrap() + .unwrap_err(); + + assert_eq!(StatusCode::RegionBusy, error.status_code(), "{error:?}"); + assert!(mito_region.is_follower()); + let stored = mito_region.manifest_ctx.latest_stored_version().await; + assert_eq!(version, stored.unwrap()); +} + +/// A takeover whose reopen fails, here as the newer manifest it reopens cannot be read, ends its +/// catchup, so a Leader lease still makes the region writable. +#[tokio::test] +async fn test_takeover_whose_reopen_fails_leaves_region_promotable() { + let region = TestRegion::new("takeover-reopen-fails", true, None).await; + region.flush_and_demote().await; + region.write_handed_over_remote_rows().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let version = next_manifest_version(&mito_region).await; + let store = region.env.get_object_store().unwrap(); + publish_delta(&store, ®ion.region_dir(), version, b"corrupt".to_vec()).await; + + region + .take_over(takeover_request(Some(CANDIDATE_LEASE_ID))) + .await + .unwrap_err(); + + assert!(!is_replaced(®ion.engine, &mito_region)); + region.promote_with_lease(); + assert!(mito_region.is_writable()); +} diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index 8add00eb96b..fae51159f12 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -556,6 +556,16 @@ pub enum Error { source: BoxedError, }, + #[snafu(display("Failed to list the WAL of node {} for region {}", node_id, region_id))] + ListNodeWal { + region_id: RegionId, + node_id: u64, + #[snafu(implicit)] + location: Location, + /// Shared by the takeovers of a batch whose source's WAL failed to list. + source: Arc, + }, + #[snafu(display("Failed to decode WAL entry, region_id: {}", region_id))] DecodeWal { region_id: RegionId, @@ -842,6 +852,18 @@ pub enum Error { location: Location, }, + #[snafu(display( + "Region {} did not receive the lease of its migration candidate: {}", + region_id, + reason + ))] + CandidateLeaseNotReceived { + region_id: RegionId, + reason: String, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display( "Region {} lost its leader lease while writing to the WAL, the write may have been applied", region_id @@ -1829,7 +1851,9 @@ impl ErrorExt for Error { RegionState { .. } | UpdateManifest { .. } => StatusCode::RegionNotReady, RegionLeaseExpired { .. } | RegionLeaseNotReceived { .. } + | CandidateLeaseNotReceived { .. } | UnacknowledgedWrite { .. } => StatusCode::RegionNotReady, + ListNodeWal { source, .. } => source.status_code(), RegionPendingTails { .. } => StatusCode::RegionNotReady, RemoteWalUnsupported { .. } => StatusCode::Unsupported, TailEntryMissing { .. } => StatusCode::StorageUnavailable, @@ -1935,6 +1959,7 @@ impl ErrorExt for Error { | RejectWriteInStaging { .. } | RegionLeaseExpired { .. } | RegionLeaseNotReceived { .. } + | CandidateLeaseNotReceived { .. } | UnacknowledgedWrite { .. } | RegionState { state: RegionRoleState::Follower, @@ -1975,6 +2000,7 @@ impl ErrorExt for Error { | HandoffWal { source, .. } | FetchManifests { source, .. } | External { source, .. } => source.retry_hint(), + ListNodeWal { source, .. } => source.retry_hint(), OpenRegion { source, .. } | LoadSstMeta { source, .. } diff --git a/src/mito2/src/lease.rs b/src/mito2/src/lease.rs index b6b7caaada9..ab78acc1a51 100644 --- a/src/mito2/src/lease.rs +++ b/src/mito2/src/lease.rs @@ -14,11 +14,12 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{LazyLock, Mutex}; -use std::time::Instant; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::{Duration, Instant}; use store_api::logstore::ObjectStoreWalIoPermit; use store_api::storage::RegionId; +use tokio::sync::Notify; /// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64]. static LEASE_EPOCH: LazyLock = LazyLock::new(Instant::now); @@ -66,6 +67,11 @@ impl NodeLease { self.deadline.extend(deadline); } + /// Returns whether the deadline of this node has passed. + pub(crate) fn is_expired(&self) -> bool { + self.now() >= self.deadline.get() + } + /// Returns the current time in the unit of [Deadline]. pub(crate) fn now(&self) -> u64 { #[cfg(any(test, feature = "test"))] @@ -102,10 +108,67 @@ pub(crate) struct GrantedLease { pub(crate) sent_at: Instant, } +impl GrantedLease { + /// Returns, for a lease of a heartbeat sent after `after`, whether it is the lease of + /// candidate `candidate_lease_id`, with the reason if not; None for an earlier lease. + pub(crate) fn of_candidate_after( + &self, + candidate_lease_id: u64, + after: Instant, + ) -> Option> { + (self.sent_at > after).then(|| { + if self.candidate_lease_id == Some(candidate_lease_id) { + Ok(()) + } else { + Err(format!( + "a lease sent after the catchup began carries candidate lease id {:?}", + self.candidate_lease_id + )) + } + }) + } +} + /// The lease of the latest heartbeat each region received, whether or not the region applied it. /// It is kept apart from the region instance, so a reopen during catchup keeps it. #[derive(Debug, Default)] -pub(crate) struct GrantedLeases(Mutex>); +pub(crate) struct GrantedLeases(Mutex); + +#[derive(Debug, Default)] +struct GrantedLeasesInner { + leases: HashMap, + /// Wakes the waiter of a region's candidate lease when its lease is recorded or removed. It + /// is empty unless a catchup waits; a lookup in an empty map returns before hashing, so a + /// record then costs one more length check. A region has one waiter, as the worker runs one + /// catchup of a region at a time. + waiters: HashMap>, +} + +impl GrantedLeasesInner { + fn wake(&self, region_id: RegionId) { + if let Some(waiter) = self.waiters.get(®ion_id) { + waiter.notify_one(); + } + } +} + +/// Removes the waiter of a region from [GrantedLeases] when dropped. +struct LeaseWaiter<'a> { + leases: &'a GrantedLeases, + region_id: RegionId, + notify: Arc, +} + +impl Drop for LeaseWaiter<'_> { + fn drop(&mut self) { + self.leases + .0 + .lock() + .unwrap() + .waiters + .remove(&self.region_id); + } +} impl GrantedLeases { /// Records the lease if `region_is_open` holds. The check runs under the same lock as @@ -122,11 +185,12 @@ impl GrantedLeases { candidate_lease_id, sent_at, }; - let mut leases = self.0.lock().unwrap(); + let mut inner = self.0.lock().unwrap(); if !region_is_open() { return; } - leases + inner + .leases .entry(region_id) .and_modify(|latest| { if sent_at > latest.sent_at { @@ -134,15 +198,77 @@ impl GrantedLeases { } }) .or_insert(lease); + inner.wake(region_id); } pub(crate) fn remove(&self, region_id: RegionId) { - self.0.lock().unwrap().remove(®ion_id); + let mut inner = self.0.lock().unwrap(); + inner.leases.remove(®ion_id); + inner.wake(region_id); } - #[cfg(any(test, feature = "test"))] pub(crate) fn get(&self, region_id: RegionId) -> Option { - self.0.lock().unwrap().get(®ion_id).copied() + self.0.lock().unwrap().leases.get(®ion_id).copied() + } + + /// Returns whether a catchup waits for the candidate lease of the region. + #[cfg(test)] + pub(crate) fn is_waiting(&self, region_id: RegionId) -> bool { + self.0.lock().unwrap().waiters.contains_key(®ion_id) + } + + fn register(&self, region_id: RegionId) -> LeaseWaiter<'_> { + let notify = Arc::new(Notify::new()); + self.0 + .lock() + .unwrap() + .waiters + .insert(region_id, notify.clone()); + LeaseWaiter { + leases: self, + region_id, + notify, + } + } + + /// Waits until region `region_id` records the lease of a heartbeat sent after `after`; send + /// times have millisecond precision. Returns `Ok(())` only if that lease carries + /// `candidate_lease_id`, and fails with the reason as soon as a lease sent after `after` + /// carries another candidate lease id or none. Also fails with the reason if `is_stopped` + /// holds, or if the lease of this node, `node_lease`, expires before such a lease is recorded. + /// + /// The wait has no bound of its own: every reply to a heartbeat sent after `after` records a + /// lease of the region, or, once the migration ends, the metasrv closes the region, and a node + /// cut off from the metasrv loses its lease. + pub(crate) async fn wait_for_candidate_lease( + &self, + node_lease: &NodeLease, + region_id: RegionId, + candidate_lease_id: u64, + after: Instant, + is_stopped: impl Fn() -> bool, + ) -> Result<(), String> { + // Registered before the lease is read, so a lease recorded meanwhile wakes the wait. + let waiter = self.register(region_id); + loop { + if is_stopped() { + return Err("the region was closed".to_string()); + } + if let Some(result) = self + .get(region_id) + .and_then(|lease| lease.of_candidate_after(candidate_lease_id, after)) + { + return result; + } + let (now, deadline) = (node_lease.now(), node_lease.deadline.get()); + if now >= deadline { + return Err("the lease of this node expired".to_string()); + } + tokio::select! { + _ = waiter.notify.notified() => {} + _ = tokio::time::sleep(Duration::from_nanos(deadline - now)) => {} + } + } } } @@ -158,6 +284,18 @@ mod tests { use super::*; + /// Waits until a wait for a candidate lease of `region_id` registered its waiter, so a + /// lease recorded or removed afterwards must wake it. + async fn wait_until_waiting(leases: &GrantedLeases, region_id: RegionId) { + tokio::time::timeout(Duration::from_secs(10), async { + while !leases.is_waiting(region_id) { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + } + #[test] fn test_object_store_permission_follows_node_lease() { let lease = NodeLease::default(); @@ -191,4 +329,102 @@ mod tests { leases.record(region_id, Instant::now(), Some(2), || false); assert_eq!(leases.get(region_id), None); } + + /// A node lease that lasts, on a frozen clock, and the instant the wait counts from. + fn lasting_node_lease() -> (NodeLease, Instant) { + let lease = NodeLease::default(); + lease.enable(); + let now = Instant::now(); + lease.renew(now + Duration::from_secs(60)); + lease.freeze_clock(now); + (lease, now) + } + + #[tokio::test] + async fn test_candidate_lease_wait_takes_only_a_later_lease() { + let (node_lease, after) = lasting_node_lease(); + let leases = Arc::new(GrantedLeases::default()); + let region_id = RegionId::new(1, 1); + // A lease of a heartbeat sent before the wait began does not count. + leases.record(region_id, after, Some(7), || true); + let wait = { + let leases = leases.clone(); + tokio::spawn(async move { + leases + .wait_for_candidate_lease(&node_lease, region_id, 7, after, || false) + .await + }) + }; + wait_until_waiting(&leases, region_id).await; + assert!(!wait.is_finished()); + + leases.record(region_id, after + Duration::from_millis(1), Some(7), || { + true + }); + tokio::time::timeout(Duration::from_secs(10), wait) + .await + .unwrap() + .unwrap() + .unwrap(); + // The waiter is gone once the wait ends. + assert!(leases.0.lock().unwrap().waiters.is_empty()); + } + + #[tokio::test] + async fn test_candidate_lease_wait_fails_on_another_candidate() { + let (node_lease, after) = lasting_node_lease(); + let leases = GrantedLeases::default(); + let region_id = RegionId::new(1, 1); + let later = after + Duration::from_millis(1); + for candidate_lease_id in [None, Some(8)] { + leases.record(region_id, later, candidate_lease_id, || true); + let reason = leases + .wait_for_candidate_lease(&node_lease, region_id, 7, after, || false) + .await + .unwrap_err(); + assert!(reason.contains("candidate lease id"), "{reason}"); + leases.remove(region_id); + } + } + + #[tokio::test] + async fn test_candidate_lease_wait_ends_when_region_is_removed() { + let (node_lease, after) = lasting_node_lease(); + let leases = Arc::new(GrantedLeases::default()); + let region_id = RegionId::new(1, 1); + let stopped = Arc::new(AtomicBool::new(false)); + let wait = { + let (leases, stopped) = (leases.clone(), stopped.clone()); + tokio::spawn(async move { + leases + .wait_for_candidate_lease(&node_lease, region_id, 7, after, || { + stopped.load(Ordering::Relaxed) + }) + .await + }) + }; + wait_until_waiting(&leases, region_id).await; + assert!(!wait.is_finished()); + + // A close stops the region, then removes it. + stopped.store(true, Ordering::Relaxed); + leases.remove(region_id); + let reason = tokio::time::timeout(Duration::from_secs(10), wait) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert!(reason.contains("closed"), "{reason}"); + } + + #[tokio::test] + async fn test_candidate_lease_wait_fails_without_node_lease() { + let (node_lease, after) = lasting_node_lease(); + node_lease.freeze_clock(after + Duration::from_secs(60)); + let reason = GrantedLeases::default() + .wait_for_candidate_lease(&node_lease, RegionId::new(1, 1), 7, after, || false) + .await + .unwrap_err(); + assert!(reason.contains("expired"), "{reason}"); + } } diff --git a/src/mito2/src/manifest/storage.rs b/src/mito2/src/manifest/storage.rs index af7e4a02e3a..7e3e2f1e712 100644 --- a/src/mito2/src/manifest/storage.rs +++ b/src/mito2/src/manifest/storage.rs @@ -27,7 +27,7 @@ use common_datasource::compression::CompressionType; use common_error::ext::ErrorExt; use common_telemetry::{debug, warn}; use crc32fast::Hasher; -use futures::TryStreamExt; +use futures::{TryStream, TryStreamExt}; use lazy_static::lazy_static; use object_store::util::join_dir; use object_store::{Entry, ErrorKind, Lister, ObjectStore, util}; @@ -265,6 +265,34 @@ impl ManifestObjectStore { /// Returns whether the directory holds a delta or checkpoint of a version after /// `last_version`. It reads the directory without locking it. pub(crate) async fn has_version_after(&self, last_version: ManifestVersion) -> Result { + self.versions_after(last_version) + .await? + .try_any(|version| async move { version.is_some() }) + .await + .context(OpenDalSnafu) + } + + /// Returns the largest version of a delta or checkpoint in the directory, or `last_version` + /// if none is after it. It reads the directory without locking it. + pub(crate) async fn latest_version( + &self, + last_version: ManifestVersion, + ) -> Result { + self.versions_after(last_version) + .await? + .try_fold(last_version, |latest, version| async move { + Ok(version.map_or(latest, |version| latest.max(version))) + }) + .await + .context(OpenDalSnafu) + } + + /// Lists the directory after `last_version`, yielding for each entry the version of a delta + /// or checkpoint after it, and None for other entries. + async fn versions_after( + &self, + last_version: ManifestVersion, + ) -> Result, Error = object_store::Error>> { // Skip older files at the object-store layer. Files for `v == last_version` // may still appear (`{path}{v:020}` sorts before `{path}{v:020}.json`) but // they are filtered out below by the `version > last_version` check. @@ -275,20 +303,12 @@ impl ManifestObjectStore { .context(EmptyManifestDirSnafu { manifest_dir: self.manifest_dir(), })?; - - streamer - .try_any(|entry| async move { - let file_name = entry.name(); - if is_delta_file(file_name) || is_checkpoint_file(file_name) { - let version = file_version(file_name); - if version > last_version { - return true; - } - } - false - }) - .await - .context(OpenDalSnafu) + Ok(streamer.map_ok(move |entry| { + let file_name = entry.name(); + (is_delta_file(file_name) || is_checkpoint_file(file_name)) + .then(|| file_version(file_name)) + .filter(|version| *version > last_version) + })) } /// Returns an iterator of manifests. @@ -833,6 +853,18 @@ mod tests { assert!(it.next().is_none()); } + #[tokio::test] + async fn test_latest_version_counts_deltas_and_checkpoints() { + let mut store = new_test_manifest_store(); + for v in 0..3 { + store.save(v, b"delta").await.unwrap(); + } + assert_eq!(2, store.latest_version(0).await.unwrap()); + assert_eq!(5, store.latest_version(5).await.unwrap()); + store.save_checkpoint(7, b"checkpoint").await.unwrap(); + assert_eq!(7, store.latest_version(2).await.unwrap()); + } + #[tokio::test] async fn test_file_version() { let version = file_version("00000000000000000007.checkpoint"); diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index 154432f72c5..7e4b8e90e4a 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -1718,6 +1718,16 @@ impl ManifestContext { self.manifest_manager.read().await.has_update().await } + /// Returns the latest manifest version in storage, at least the installed one. The listing + /// runs without the manifest lock, so it does not hold up commits or a stop. + pub(crate) async fn latest_stored_version(&self) -> Result { + let (store, installed) = { + let manager = self.manifest_manager.read().await; + (manager.store(), manager.last_version()) + }; + store.latest_version(installed).await + } + /// Waits for the in-flight checkpoint of a stopped manager. A stopped manager starts no /// checkpoint, so this instance no longer writes the manifest directory afterwards. /// diff --git a/src/mito2/src/region/catchup.rs b/src/mito2/src/region/catchup.rs index 42906774330..b1ac644924f 100644 --- a/src/mito2/src/region/catchup.rs +++ b/src/mito2/src/region/catchup.rs @@ -16,16 +16,21 @@ use std::sync::Arc; use std::time::Instant; use common_telemetry::{info, warn}; +use futures::try_join; use snafu::{OptionExt, ensure}; +use store_api::ManifestVersion; use store_api::logstore::LogStore; -use store_api::storage::SequenceNumber; +use store_api::region_request::RegionCatchupRequest; +use store_api::storage::{RegionId, SequenceNumber}; use crate::engine::region_hook::PendingManifestHook; use crate::error::{self, Result}; +use crate::lease::{GrantedLeases, NodeLease}; use crate::manifest::action::{ HandoffFloor, PendingTail, RegionEdit, RegionManifest, UptoKind, WalRecoveryEdit, cap_wal_release, }; +use crate::manifest::manager::RegionManifestManager; use crate::region::MitoRegion; use crate::region::opener::{check_wal_history, replay_memtable}; use crate::wal::entry_distributor::WalEntryReceiver; @@ -42,15 +47,104 @@ const HANDOVER_SEQUENCE_GAP: SequenceNumber = 1 << 40; /// it to the region's writes, which allocate them without checking for overflow. const MAX_HANDOVER_SEQUENCE: SequenceNumber = 1 << 62; +/// What a takeover, a catchup that carries no entry its source reported, prepares before the +/// worker checks the region. +#[derive(Debug, Clone, Copy)] +pub(crate) struct TakeoverPrepared { + /// The latest manifest version in storage when the takeover began. The takeover commits + /// the version after it. + pub(crate) version: ManifestVersion, + /// When reading that version returned. Only a lease of a heartbeat sent later counts. + pub(crate) read_at: Instant, + /// The bound the listing of the source's WAL returned, at or above every entry in the listed + /// objects; None for a region that skips the WAL, which is not listed. + pub(crate) bound: Option, + /// The candidate lease id of the migration's registration of the region. + pub(crate) candidate_lease_id: u64, +} + +/// The candidate lease a takeover waits for before it commits. +pub(crate) struct CandidateLease<'a> { + pub(crate) prepared: TakeoverPrepared, + pub(crate) leases: &'a GrantedLeases, + pub(crate) node_lease: &'a NodeLease, +} + +impl CandidateLease<'_> { + /// Waits for a lease of the region's candidate, see [GrantedLeases::wait_for_candidate_lease]. + pub(crate) async fn wait(&self, region: &MitoRegion) -> Result<()> { + let region_id = region.region_id; + self.leases + .wait_for_candidate_lease( + self.node_lease, + region_id, + self.prepared.candidate_lease_id, + self.prepared.read_at, + || region.manifest_ctx.is_stopped(), + ) + .await + .map_err(|reason| error::CandidateLeaseNotReceivedSnafu { region_id, reason }.build()) + } + + /// Checks again that the lease of this node has not expired, that the latest lease of the + /// region is the candidate's, and that the manifest `manager` holds is the version the + /// takeover began from. + pub(crate) fn check(&self, region_id: RegionId, manager: &RegionManifestManager) -> Result<()> { + let TakeoverPrepared { + candidate_lease_id, + read_at, + .. + } = self.prepared; + ensure!( + !(self.node_lease.is_enabled() && self.node_lease.is_expired()), + error::CandidateLeaseNotReceivedSnafu { + region_id, + reason: "the lease of this node expired", + } + ); + self.leases + .get(region_id) + .and_then(|lease| lease.of_candidate_after(candidate_lease_id, read_at)) + .unwrap_or_else(|| Err("no lease sent after the catchup began".to_string())) + .map_err(|reason| { + error::CandidateLeaseNotReceivedSnafu { region_id, reason }.build() + })?; + ensure!( + manager.manifest().manifest_version == self.prepared.version, + error::RegionBusySnafu { region_id } + ); + Ok(()) + } +} + +/// Returns the source of a takeover: a catchup that makes `region`, whose manifest is published +/// conditionally, writable and names a source but no entry the source reported. +pub(crate) fn takeover_source(request: &RegionCatchupRequest, region: &MitoRegion) -> Option { + match ( + request.set_writable, + request.entry_id, + request.source_node_id, + ) { + (true, None, Some(source)) if region.manifest_ctx.is_conditional_publication() => { + Some(source) + } + _ => None, + } +} + /// Hands a region whose manifest is published conditionally over to this node `node_id`, which -/// becomes its writer, from the source node `source_node_id` that reported `reported_entry_id` -/// as its last entry. Replays nothing. +/// becomes its writer, from the source node `source_node_id` that reported `upto` as its last +/// entry or, in a takeover (`candidate` is set), whose WAL listing returned `upto`, a bound at or +/// above every entry in the listed objects; entries of the source above `upto` are not recovered. +/// Replays nothing. /// -/// The log store first hands the region over (see [Wal::handoff]). Then the catchup commits, after -/// the manifest the region holds, this node's handoff floor, the bound that hand-off returned, -/// and, if the source has entries after where the manifest recovers its WAL from, a reported tail -/// of the source over them, raising the committed sequence by [HANDOVER_SEQUENCE_GAP]. The tail is -/// replayed in the background once the region is writable. +/// The log store first hands the region over (see [Wal::handoff]); a takeover also waits for the +/// lease of its candidate meanwhile. Then the catchup commits, after the manifest the region +/// holds (in a takeover, the version it began from), this node's handoff floor, the bound that +/// hand-off returned, and, if `upto` is above where the manifest recovers the source's WAL from, +/// a tail of the source up to `upto` (of kind Reported, or Listed in a takeover), raising the +/// committed sequence by [HANDOVER_SEQUENCE_GAP]. The tail is replayed in the background once the +/// region is writable. /// /// Returns the receipt of the manifest hook and the committed edit, which the region's worker /// applies to the region's version, in order with the edits of flushes and compactions. @@ -63,11 +157,18 @@ pub(crate) async fn hand_over( wal: &Wal, node_id: Option, source_node_id: Option, - reported_entry_id: EntryId, + upto: EntryId, + candidate: Option>, ) -> Result<(PendingManifestHook, Option)> { let region_id = region.region_id; if region.version().options.skip_wal { + if let Some(candidate) = &candidate { + candidate.wait(region).await?; + } let mut manager = region.manifest_ctx.manifest_manager.write().await; + if let Some(candidate) = &candidate { + candidate.check(region_id, &manager)?; + } let pending = region .manifest_ctx .commit_catchup_locked(&mut manager, RegionEdit::default()) @@ -77,13 +178,14 @@ pub(crate) async fn hand_over( let node_id = node_id.with_context(|| error::UnexpectedSnafu { reason: format!("No node id to hand region {region_id} over to"), })?; + let upto_kind = if candidate.is_some() { + UptoKind::Listed + } else { + UptoKind::Reported + }; let bound = { let manifest = region.manifest_ctx.manifest().await; - let bound = handoff_entry_id( - reported_entry_id, - manifest.flushed_entry_id, - &manifest.pending_tails, - ); + let bound = handoff_entry_id(upto, manifest.flushed_entry_id, &manifest.pending_tails); // A handover that cannot commit after this manifest fails before the log store hands the // region over. The commit builds the edit again for the manifest it commits after. handover_edit( @@ -94,12 +196,25 @@ pub(crate) async fn hand_over( entry_id: bound, }, source_node_id, - reported_entry_id, + upto, + upto_kind, )?; bound }; - let floor = wal.handoff(region_id, ®ion.provider, bound).await?; + let handoff = wal.handoff(region_id, ®ion.provider, bound); + let floor = match &candidate { + // An abandoned hand-off leaves a raised sequence floor and a release record of the + // unchanged watermark, which only keep this node's later ids higher. If the candidate wait + // fails, the log store may still persist them while the region's local history + // (`start_region_history`) is not registered; this attempt commits no handover, and a later + // successful hand-off registers the history. + Some(candidate) => try_join!(handoff, candidate.wait(region))?.0, + None => handoff.await?, + }; let mut manager = region.manifest_ctx.manifest_manager.write().await; + if let Some(candidate) = &candidate { + candidate.check(region_id, &manager)?; + } let edit = handover_edit( &manager.manifest(), region.version_control.current().last_sequence, @@ -108,7 +223,8 @@ pub(crate) async fn hand_over( entry_id: floor, }, source_node_id, - reported_entry_id, + upto, + upto_kind, )?; let pending = region .manifest_ctx @@ -322,27 +438,30 @@ impl RegionCatchupTask { } } -/// Returns the entry id a hand-off of the region has to cover: the largest of the one its source -/// reported, its flushed entry id and the bounds of its pending tails. +/// Returns the entry id a hand-off of the region has to cover: the largest of `upto` (the source's +/// reported entry, or the listed bound in a takeover), its flushed entry id and the bounds of its +/// pending tails. fn handoff_entry_id( - reported_entry_id: EntryId, + upto: EntryId, flushed_entry_id: EntryId, pending_tails: &[PendingTail], ) -> EntryId { pending_tails .iter() .map(|tail| tail.upto) - .fold(reported_entry_id.max(flushed_entry_id), EntryId::max) + .fold(upto.max(flushed_entry_id), EntryId::max) } /// Returns the edit of a handover to `floor.node_id` (see [hand_over]) that commits after -/// `manifest`. `last_sequence` is the largest sequence the region used on this node. +/// `manifest`, recording a tail whose bound is of kind `upto_kind`. `last_sequence` is the largest +/// sequence the region used on this node. fn handover_edit( manifest: &RegionManifest, last_sequence: SequenceNumber, floor: HandoffFloor, source_node_id: Option, - reported_entry_id: EntryId, + upto: EntryId, + upto_kind: UptoKind, ) -> Result { let region_id = manifest.metadata.region_id; let mut edit = RegionEdit { @@ -354,13 +473,13 @@ fn handover_edit( }; // Entries of the source up to here are flushed, in its tails or below its handoff floor. let after = manifest.wal_replay_start(source_node_id); - if after >= reported_entry_id { + if after >= upto { return Ok(edit); } let node_id = source_node_id.with_context(|| error::InvalidRequestSnafu { region_id, reason: format!( - "the request names no source of the entries in ({after}, {reported_entry_id}] to recover" + "the request names no source of the entries in ({after}, {upto}] to recover" ), })?; let committed_sequence = manifest @@ -377,8 +496,8 @@ fn handover_edit( tails.push(PendingTail { node_id, after, - upto: reported_entry_id, - upto_kind: UptoKind::Reported, + upto, + upto_kind, }); edit.committed_sequence = Some(committed_sequence); edit.wal_recovery.pending_tails = Some(tails); @@ -445,7 +564,15 @@ mod tests { (vec![tail(SOURCE, 10, 20)], Some(25), 25), ] { let manifest = manifest(tails.clone(), source_floor); - let edit = handover_edit(&manifest, 12, floor(50), Some(SOURCE), 40).unwrap(); + let edit = handover_edit( + &manifest, + 12, + floor(50), + Some(SOURCE), + 40, + UptoKind::Reported, + ) + .unwrap(); let mut expected = tails; expected.push(tail(SOURCE, after, 40)); @@ -455,11 +582,20 @@ mod tests { assert_eq!(edit.committed_sequence, Some(12 + HANDOVER_SEQUENCE_GAP)); assert_eq!(edit.flushed_entry_id, None); } - let edit = handover_edit(&manifest(vec![], None), 0, floor(50), Some(SOURCE), 40).unwrap(); + let edit = handover_edit( + &manifest(vec![], None), + 0, + floor(50), + Some(SOURCE), + 40, + UptoKind::Reported, + ) + .unwrap(); assert_eq!(edit.committed_sequence, Some(9 + HANDOVER_SEQUENCE_GAP)); let mut raised = manifest(vec![], None); raised.committed_sequence = Some(20); - let edit = handover_edit(&raised, 12, floor(50), Some(SOURCE), 40).unwrap(); + let edit = + handover_edit(&raised, 12, floor(50), Some(SOURCE), 40, UptoKind::Reported).unwrap(); assert_eq!(edit.committed_sequence, Some(20 + HANDOVER_SEQUENCE_GAP)); } @@ -473,7 +609,15 @@ mod tests { (vec![], None, None, 8), ] { let manifest = manifest(tails, source_floor); - let edit = handover_edit(&manifest, 12, floor(50), source, reported).unwrap(); + let edit = handover_edit( + &manifest, + 12, + floor(50), + source, + reported, + UptoKind::Reported, + ) + .unwrap(); assert_eq!( edit, RegionEdit { @@ -492,7 +636,8 @@ mod tests { // Another node's tail and floor do not count for an unknown source. let mut manifest = manifest(vec![tail(3, 10, 40)], None); manifest.handoff_floors = BTreeMap::from([(3, 45)]); - let error = handover_edit(&manifest, 12, floor(50), None, 40).unwrap_err(); + let error = + handover_edit(&manifest, 12, floor(50), None, 40, UptoKind::Reported).unwrap_err(); assert!(matches!(error, Error::InvalidRequest { .. }), "{error:?}"); } @@ -500,10 +645,25 @@ mod tests { fn test_handover_fails_without_sequences_left() { let manifest = manifest(vec![], None); let last_sequence = MAX_HANDOVER_SEQUENCE - HANDOVER_SEQUENCE_GAP; - let edit = handover_edit(&manifest, last_sequence, floor(50), Some(SOURCE), 40).unwrap(); + let edit = handover_edit( + &manifest, + last_sequence, + floor(50), + Some(SOURCE), + 40, + UptoKind::Reported, + ) + .unwrap(); assert_eq!(edit.committed_sequence, Some(MAX_HANDOVER_SEQUENCE)); - let error = - handover_edit(&manifest, last_sequence + 1, floor(50), Some(SOURCE), 40).unwrap_err(); + let error = handover_edit( + &manifest, + last_sequence + 1, + floor(50), + Some(SOURCE), + 40, + UptoKind::Reported, + ) + .unwrap_err(); assert!(matches!(error, Error::Unexpected { .. }), "{error:?}"); } } diff --git a/src/mito2/src/request.rs b/src/mito2/src/request.rs index 066d86ce3db..b03e6153733 100644 --- a/src/mito2/src/request.rs +++ b/src/mito2/src/request.rs @@ -63,6 +63,7 @@ use crate::memtable::MemtableId; use crate::memtable::bulk::part::BulkPart; use crate::metrics::COMPACTION_ELAPSED_TOTAL; use crate::region::MitoRegionRef; +use crate::region::catchup::TakeoverPrepared; use crate::region::options::RegionOptions; use crate::sst::file::FileMeta; use crate::sst::index::{IndexBuildType, ResultMpscSender}; @@ -894,12 +895,13 @@ impl WorkerRequest { region_id: RegionId, request: RegionCatchupRequest, entry_receiver: Option, + takeover: Option>, ) -> (WorkerRequest, Receiver>) { let (sender, receiver) = oneshot::channel(); let worker_request = WorkerRequest::Ddl(SenderDdlRequest { region_id, sender: sender.into(), - request: DdlRequest::Catchup((request, entry_receiver)), + request: DdlRequest::Catchup((request, entry_receiver, takeover)), }); (worker_request, receiver) } @@ -1006,7 +1008,7 @@ impl WorkerRequest { RegionRequest::Catchup(v) => WorkerRequest::Ddl(SenderDdlRequest { region_id, sender: sender.into(), - request: DdlRequest::Catchup((v, None)), + request: DdlRequest::Catchup((v, None, None)), }), RegionRequest::EnterStaging(v) => WorkerRequest::Ddl(SenderDdlRequest { region_id, @@ -1145,7 +1147,13 @@ pub(crate) enum DdlRequest { Compact(RegionCompactRequest), BuildIndex(RegionBuildIndexRequest), Truncate(RegionTruncateRequest), - Catchup((RegionCatchupRequest, Option)), + Catchup( + ( + RegionCatchupRequest, + Option, + Option>, + ), + ), EnterStaging(EnterStagingRequest), ApplyStagingManifest(ApplyStagingManifestRequest), } @@ -1648,6 +1656,9 @@ pub(crate) struct CaughtUpAgain { pub(crate) result: Result, /// Whether the catchup promotes the region. pub(crate) set_writable: bool, + /// What the engine prepared for a takeover, which commits only after its version and while + /// the latest lease is its candidate's. + pub(crate) takeover: Option, /// Receives the result of the catchup. pub(crate) sender: OptionOutputTx, } diff --git a/src/mito2/src/wal/raw_entry_reader.rs b/src/mito2/src/wal/raw_entry_reader.rs index 0841d21f669..a7823b95f77 100644 --- a/src/mito2/src/wal/raw_entry_reader.rs +++ b/src/mito2/src/wal/raw_entry_reader.rs @@ -16,6 +16,7 @@ use std::sync::Arc; use async_stream::try_stream; use common_error::ext::BoxedError; +use futures::future::BoxFuture; use futures::stream::BoxStream; use snafu::ResultExt; use store_api::logstore::LogStore; @@ -30,9 +31,21 @@ use crate::wal::EntryId; /// A stream that yields [Entry]. pub type EntryStream<'a> = BoxStream<'a, Result>; -/// [RawEntryReader] provides the ability to read [Entry] from the underlying [LogStore]. +/// [RawEntryReader] reads [Entry] from the underlying [LogStore] and lists the WAL of another +/// node for a bound. pub(crate) trait RawEntryReader: Send + Sync { fn read(&self, provider: &Provider, start_id: EntryId) -> Result>; + + /// Returns a bound at or above every entry, of any region, in the listed objects of the WAL + /// of node `node_id`, see [LogStore::list_upper_bound], or None if the log store cannot list + /// that WAL. `region_id` only names the request in errors. + fn list_upper_bound( + &self, + _node_id: u64, + _region_id: RegionId, + ) -> BoxFuture<'_, std::result::Result, BoxedError>> { + Box::pin(async { Ok(None) }) + } } /// Implement the [RawEntryReader] for the [LogStore]. @@ -47,6 +60,19 @@ impl LogStoreRawEntryReader { } impl RawEntryReader for LogStoreRawEntryReader { + fn list_upper_bound( + &self, + node_id: u64, + region_id: RegionId, + ) -> BoxFuture<'_, std::result::Result, BoxedError>> { + Box::pin(async move { + self.store + .list_upper_bound(node_id, region_id) + .await + .map_err(BoxedError::new) + }) + } + fn read(&self, provider: &Provider, start_id: EntryId) -> Result> { let store = self.store.clone(); let provider = provider.clone(); diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index ce7e7aaf1cc..4cfffa108a8 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -1721,9 +1721,15 @@ impl RegionWorkerLoop { .await; return; } - DdlRequest::Catchup((req, wal_entry_receiver)) => { - self.handle_catchup_request(ddl.region_id, req, wal_entry_receiver, ddl.sender) - .await; + DdlRequest::Catchup((req, wal_entry_receiver, takeover)) => { + self.handle_catchup_request( + ddl.region_id, + req, + wal_entry_receiver, + takeover, + ddl.sender, + ) + .await; return; } DdlRequest::EnterStaging(req) => { diff --git a/src/mito2/src/worker/handle_catchup.rs b/src/mito2/src/worker/handle_catchup.rs index 575783065a9..2c7c5329136 100644 --- a/src/mito2/src/worker/handle_catchup.rs +++ b/src/mito2/src/worker/handle_catchup.rs @@ -18,7 +18,9 @@ use std::collections::HashSet; use std::sync::Arc; use common_telemetry::{debug, error, info, warn}; -use snafu::ensure; +use futures::try_join; +use snafu::{OptionExt, ensure}; +use store_api::ManifestVersion; use store_api::logstore::LogStore; use store_api::region_engine::SettableRegionRoleState; use store_api::region_request::RegionCatchupRequest; @@ -27,7 +29,10 @@ use tokio::sync::mpsc::Sender; use crate::config::IndexBuildMode; use crate::error::{self, Result}; -use crate::region::catchup::{RegionCatchupTask, hand_over}; +use crate::manifest::action::RegionEdit; +use crate::region::catchup::{ + CandidateLease, RegionCatchupTask, TakeoverPrepared, hand_over, takeover_source, +}; use crate::region::opener::RegionOpener; use crate::region::{ CatchupRegionsRef, MitoRegion, MitoRegionRef, RegionLeaderState, RegionRoleState, @@ -56,11 +61,20 @@ impl RegionWorkerLoop { /// under a local WAL, are dropped, while flushed rows stay in its SSTs. Only a catchup with /// `set_writable` promotes the region again. The replay of a remote WAL first waits until the /// entries the region acknowledged are durable. + /// + /// A catchup that makes such a region writable and names its source but no reported entry is a + /// takeover. `takeover` carries what the engine prepared for it (see [TakeoverPrepared]): the + /// manifest version it began from, when that read returned, the listed bound of the source's + /// WAL and the candidate lease id; or the error of the preparation, which the worker answers + /// unless it skips the catchup of a region that is writable and awaits no Leader lease. The + /// takeover waits for a lease of its candidate before it hands the region over up to that + /// bound. For any other catchup `takeover` is None, and a takeover without it fails. pub(crate) async fn handle_catchup_request( &mut self, region_id: RegionId, request: RegionCatchupRequest, entry_receiver: Option, + takeover: Option>, sender: OptionOutputTx, ) { let Some(region) = self.regions.get_region(region_id) else { @@ -89,10 +103,21 @@ impl RegionWorkerLoop { sender.send(Ok(0)); return; }; + let takeover = match takeover_source(&request, ®ion) + .map(|_| check_takeover(®ion, takeover)) + .transpose() + { + Ok(takeover) => takeover, + Err(e) => { + region.manifest_ctx.end_catchup(); + sender.send(Err(e)); + return; + } + }; // A catchup promoted the region and no Leader lease followed, so the region may lack // what the leader has written since, also when a failed catchup again demoted it. if awaits_leader_lease { - self.catch_up_again(region, request, entry_receiver, sender) + self.catch_up_again(region, request, entry_receiver, takeover, sender) .await; return; } @@ -103,11 +128,14 @@ impl RegionWorkerLoop { // of the rows it holds, and a reopen would drop them, which for rows written without the // WAL is their only copy. The refused region keeps its rows as a Follower; a retry succeeds // once a Leader lease has made it writable again (the catchup is then skipped) or it was - // reopened without those rows. - let handover = if request.set_writable && region.manifest_ctx.is_conditional_publication() { - request.entry_id - } else { - None + // reopened without those rows. A takeover is a handover whose source reported no entry: + // the engine prepared it, and it commits after the manifest version it began from once + // its candidate lease arrives. + let conditional = request.set_writable && region.manifest_ctx.is_conditional_publication(); + let handover = match (request.entry_id, takeover) { + (_, Some(prepared)) => Some((prepared.bound.unwrap_or_default(), Some(prepared))), + (Some(entry_id), None) if conditional => Some((entry_id, None)), + _ => None, }; // A tail replay of this instance that has not reported its end may still have a // committed edit for the worker to apply. A handover's edit applied first changes the @@ -132,8 +160,17 @@ impl RegionWorkerLoop { // The worker writes a region inline, so every write acknowledged so far has an entry id // at or below this one. let last_entry_id = region.version_control.current().last_entry_id; - // If the memtable is not empty or the manifest has been updated, we need to reopen the region. - let region = match self.reopen_region_if_needed(region.clone()).await { + // A takeover reopens the region only if its manifest is behind the version the engine read + // (see reopen_region_for_takeover); other catchups reopen it if the memtable is not empty + // or the manifest has an update. + let reopened = match handover { + Some((_, Some(prepared))) => { + self.reopen_region_for_takeover(region.clone(), prepared.version) + .await + } + _ => self.reopen_region_if_needed(region.clone()).await, + }; + let region = match reopened { Ok(region) => region, Err(e) => { region.manifest_ctx.end_catchup(); @@ -147,13 +184,27 @@ impl RegionWorkerLoop { let wal = self.wal.clone(); let allow_stale_entries = self.config.allow_stale_entries; let node_lease = self.node_lease.clone(); + let granted_leases = self.granted_leases.clone(); let node_id = self.file_ref_manager.node_id(); common_runtime::spawn_global(async move { // Under conditional manifest publication, the region becomes writable only once its // catchup committed the next manifest version. let result = match handover { - Some(entry_id) => { - match hand_over(®ion, &wal, node_id, request.source_node_id, entry_id).await + Some((upto, takeover)) => { + let candidate = takeover.map(|prepared| CandidateLease { + prepared, + leases: &granted_leases, + node_lease: &node_lease, + }); + match hand_over( + ®ion, + &wal, + node_id, + request.source_node_id, + upto, + candidate, + ) + .await { Ok((hook, edit)) => { hook.fire().await; @@ -223,12 +274,15 @@ impl RegionWorkerLoop { /// write and made no commit meanwhile and, for a catchup that makes the region writable, the /// replacement's catchup commit succeeded (under conditional manifest publication it commits /// an empty edit). Otherwise the region keeps its memtable, so a later Leader lease can promote - /// it; one that waits for a reload is reloaded instead. + /// it; one that waits for a reload is reloaded instead. A takeover, which the engine prepared, + /// also waits for its candidate lease during the replay, and commits only after the version + /// it began from and while the latest lease is still the candidate's. async fn catch_up_again( &mut self, region: MitoRegionRef, request: RegionCatchupRequest, entry_receiver: Option, + takeover: Option, sender: OptionOutputTx, ) { let region_id = region.region_id; @@ -252,18 +306,29 @@ impl RegionWorkerLoop { let node_id = self.file_ref_manager.node_id(); let config = self.config.clone(); let worker_sender = self.sender.clone(); + let (node_lease, granted_leases) = (self.node_lease.clone(), self.granted_leases.clone()); common_runtime::spawn_global(async move { + let candidate = takeover.map(|prepared| CandidateLease { + prepared, + leases: &granted_leases, + node_lease: &node_lease, + }); let result = async { let replacement = opener.open(&config, &wal).await?; - RegionCatchupTask::new(replacement.clone(), wal, config.allow_stale_entries) - .with_entry_receiver(entry_receiver) - .with_node_id(node_id) - .with_expected_last_entry_id(request.entry_id) - .with_set_writable(request.set_writable) - .with_replay_checkpoint_entry_id(request.checkpoint.map(|c| c.entry_id)) - .with_acknowledged_entry_id(acknowledged_entry_id) - .run() - .await?; + let mut task = + RegionCatchupTask::new(replacement.clone(), wal, config.allow_stale_entries) + .with_entry_receiver(entry_receiver) + .with_node_id(node_id) + .with_expected_last_entry_id(request.entry_id) + .with_set_writable(request.set_writable) + .with_replay_checkpoint_entry_id(request.checkpoint.map(|c| c.entry_id)) + .with_acknowledged_entry_id(acknowledged_entry_id); + match &candidate { + Some(candidate) => { + try_join!(task.run(), candidate.wait(®ion))?; + } + None => task.run().await?, + } Ok(replacement) } .await; @@ -273,6 +338,7 @@ impl RegionWorkerLoop { last_sequence, result, set_writable: request.set_writable, + takeover, sender, }); notify_worker(&worker_sender, region_id, notify).await; @@ -282,7 +348,9 @@ impl RegionWorkerLoop { /// Replaces the region with the instance its catchup again replayed into, or keeps the region /// if the replay failed, the region was closed or reopened, waits for a reload or a flush, /// committed or took a write since the catchup began, or the catchup commit of the - /// replacement failed. A kept region ends its catchup, so a later Leader lease can promote it + /// replacement failed. A takeover also keeps the region if its candidate lease did not arrive + /// or is no longer the latest, or the replacement is not at the version the takeover began + /// from. A kept region ends its catchup, so a later Leader lease can promote it /// with its memtable; one that waits for a reload is reloaded instead. pub(crate) async fn handle_caught_up_again( &mut self, @@ -295,6 +363,7 @@ impl RegionWorkerLoop { last_sequence, result, set_writable, + takeover, sender, } = caught_up; let registered = self @@ -322,7 +391,28 @@ impl RegionWorkerLoop { // commit cannot move into a spawned task, since the old instance could then commit or // be fenced between it and the checks. A catchup again is rare. Ok(replacement) if set_writable => { - replacement.manifest_ctx.commit_catchup().await.map(|hook| { + let committed = match takeover { + // The replacement opened the latest manifest after the takeover read its + // version, so the check refuses it if a commit came in between. + Some(prepared) => { + async { + let candidate = CandidateLease { + prepared, + leases: &self.granted_leases, + node_lease: &self.node_lease, + }; + let ctx = &replacement.manifest_ctx; + let mut manager = ctx.manifest_manager.write().await; + candidate.check(region_id, &manager)?; + ctx.commit_catchup_locked(&mut manager, RegionEdit::default()) + .await + .map(Some) + } + .await + } + None => replacement.manifest_ctx.commit_catchup().await, + }; + committed.map(|hook| { catchup_hook = hook; replacement }) @@ -514,6 +604,30 @@ impl RegionWorkerLoop { .options(region.version().options.clone()) } + /// Reopens the region for its takeover if its installed manifest is behind `version`, the + /// version the takeover began from; fails if it is past it, or if the reopened region does not + /// hold that version either. + async fn reopen_region_for_takeover( + &mut self, + region: Arc, + version: ManifestVersion, + ) -> Result> { + let region_id = region.region_id; + let installed = region.manifest_ctx.manifest_version().await; + ensure!(installed <= version, error::RegionBusySnafu { region_id }); + if installed == version { + return Ok(region); + } + self.listener.on_catchup_reopen_begin(region_id).await; + let reopened = self.reopen_region(®ion).await?; + if reopened.manifest_ctx.manifest_version().await != version { + // The reopened instance began its own catchup. + reopened.manifest_ctx.end_catchup(); + return error::RegionBusySnafu { region_id }.fail(); + } + Ok(reopened) + } + async fn reopen_region_if_needed( &mut self, region: Arc, @@ -663,6 +777,27 @@ impl RegionWorkerLoop { } } +/// Returns what the engine prepared for the takeover of `region`. `None` means the engine prepared +/// nothing, as for a catchup sent to the worker directly, and fails with `InvalidRequest`; +/// `Some(Err(e))` fails with the error of the preparation. Fails retryably with `RegionBusy` if the +/// region's choice to skip the WAL changed since the preparation, as the takeover then listed the +/// source's WAL or not by mistake. +fn check_takeover( + region: &MitoRegion, + takeover: Option>, +) -> Result { + let region_id = region.region_id; + let prepared = takeover.with_context(|| error::InvalidRequestSnafu { + region_id, + reason: "a takeover must be prepared by the engine", + })??; + ensure!( + prepared.bound.is_none() == region.version().options.skip_wal, + error::RegionBusySnafu { region_id } + ); + Ok(prepared) +} + /// What ends a successful catchup: it finalizes the leadership of a promoted region, ends the /// catchup and replies. struct CatchupFinish { diff --git a/src/store-api/src/logstore.rs b/src/store-api/src/logstore.rs index 6f18413efaa..d529ab29d08 100644 --- a/src/store-api/src/logstore.rs +++ b/src/store-api/src/logstore.rs @@ -218,6 +218,20 @@ pub trait LogStore: Send + Sync + 'static + std::fmt::Debug { Ok(entry_id) } + /// Lists the WAL of node `node_id`, which shares this log store's storage, without reading + /// any object, and returns a bound at or above every entry, of any region, in the listed + /// objects; entries in objects written later may not be covered. A WAL that holds no object + /// is an error. `region_id` only names the request in errors. + /// + /// The default returns `None`: the log store cannot list the WAL of another node. + async fn list_upper_bound( + &self, + _node_id: u64, + _region_id: RegionId, + ) -> Result, Self::Error> { + Ok(None) + } + /// Streams the entries of `region_id` in `(after, upper]` from the WAL of node `node_id`, /// which shares this log store's storage, without writing to that WAL. /// diff --git a/src/store-api/src/region_request.rs b/src/store-api/src/region_request.rs index c2a92fd9361..e007a07861c 100644 --- a/src/store-api/src/region_request.rs +++ b/src/store-api/src/region_request.rs @@ -2049,8 +2049,13 @@ pub struct RegionCatchupRequest { pub metadata_entry_id: Option, /// Replay checkpoint. pub checkpoint: Option, - /// Id of the datanode that led the region before and reported `entry_id`. + /// Id of the datanode that led the region before: the one that reported `entry_id`, or, + /// without `entry_id`, the one a takeover takes the region over from. pub source_node_id: Option, + /// The candidate lease id of the migration's registration of this region, which a takeover + /// waits for before it commits: a catchup with `set_writable`, `source_node_id` and no + /// `entry_id`, of a region whose manifest is published conditionally. + pub candidate_lease_id: Option, } #[derive(Debug, Clone)]