feat(mito2): take a region over from a source that reported no entry (#10761)

* feat(mito2): take a region over from a source that reported no entry

On a region whose manifest is published conditionally, a catchup that
makes the region writable and names its source but no reported entry (a
takeover) hands the region over without replaying, as a handover does.

The engine prepares the takeovers of a batch: it reads the latest
manifest version of each, asks for one heartbeat, and lists the WAL of
each source once for a bound. The log store hands the region over while
the catchup waits for a lease of the migration's candidate from a
heartbeat sent after the version read. Under the manifest lock the lease
and the version are checked again, and the commit records this node's
handoff floor and, if the bound is above where the manifest recovers the
source's WAL from, a listed tail up to the bound. The region worker
applies the edit and promotes the region. A region that skips the WAL
commits an empty edit after the same wait.

A takeover of a region that awaits its Leader lease is caught up again as
on main, and commits only after the prepared version while the latest
lease is the candidate's. RegionCatchupRequest gains candidate_lease_id,
passed from the upgrade instruction to the data region. The datanode
sends a requested heartbeat a millisecond after the request; one already
due sooner is kept and another follows it, and the scheduled time is kept
during its reconnect backoff.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* fix(mito2): keep the status of a failed source WAL listing

A takeover whose listing of the source's WAL fails now reports that
listing's status and retry hint: the error is shared across the takeovers
of a batch as an Arc<BoxedError> instead of a message and a status, so a
transient failure stays retryable and an empty WAL is not.

Document what the candidate-lease wait returns, how the worker answers a
takeover it was or was not prepared for, and what an abandoned hand-off
leaves. Cover a manifest that moves during the candidate-lease wait and
a takeover whose reopen fails.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* docs(mito2): clarify takeover preparation error doc

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
This commit is contained in:
jeremyhi
2026-12-01 08:31:24 +00:00
committed by GitHub
parent 768834c465
commit 7f367720f6
21 changed files with 1995 additions and 108 deletions
+58 -4
View File
@@ -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<u64>) -> KvBackendRef {
@@ -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()
}],
@@ -1414,6 +1414,12 @@ impl LogStore for ObjectStoreLogStore {
Ok(bound)
}
async fn list_upper_bound(&self, node_id: u64, region_id: RegionId) -> Result<Option<EntryId>> {
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,
+18 -5
View File
@@ -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)
);
}
}
+4
View File
@@ -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
+123 -8
View File
@@ -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<Notify> {
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<RegionHookRef>,
/// Asks the heartbeat task of the node to send a heartbeat now, see
/// [MitoEngine::heartbeat_request].
heartbeat_request: Arc<Notify>,
#[cfg(feature = "enterprise")]
extension_range_provider_factory: Option<BoxedExtensionRangeProviderFactory>,
}
@@ -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<Option<Result<TakeoverPrepared>>> {
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, &region) 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<u64, std::result::Result<Option<EntryId>, Arc<BoxedError>>> =
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<Vec<(RegionId, Result<AffectedRows>)>> {
// 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<Arc<KafkaProvider>, 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,
}),
@@ -186,6 +186,7 @@ async fn test_batch_catchup_with_format(factory: Option<LogStoreFactory>, 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<LogStoreFactory>, fl
metadata_entry_id: None,
checkpoint: None,
source_node_id: None,
candidate_lease_id: None,
},
)
})
@@ -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);
@@ -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
File diff suppressed because it is too large Load Diff
+26
View File
@@ -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<BoxedError>,
},
#[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, .. }
+244 -8
View File
@@ -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<Instant> = 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<Result<(), String>> {
(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<HashMap<RegionId, GrantedLease>>);
pub(crate) struct GrantedLeases(Mutex<GrantedLeasesInner>);
#[derive(Debug, Default)]
struct GrantedLeasesInner {
leases: HashMap<RegionId, GrantedLease>,
/// 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<RegionId, Arc<Notify>>,
}
impl GrantedLeasesInner {
fn wake(&self, region_id: RegionId) {
if let Some(waiter) = self.waiters.get(&region_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<Notify>,
}
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(&region_id);
let mut inner = self.0.lock().unwrap();
inner.leases.remove(&region_id);
inner.wake(region_id);
}
#[cfg(any(test, feature = "test"))]
pub(crate) fn get(&self, region_id: RegionId) -> Option<GrantedLease> {
self.0.lock().unwrap().get(&region_id).copied()
self.0.lock().unwrap().leases.get(&region_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(&region_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}");
}
}
+47 -15
View File
@@ -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<bool> {
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<ManifestVersion> {
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<impl TryStream<Ok = Option<ManifestVersion>, 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");
+10
View File
@@ -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<ManifestVersion> {
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.
///
+195 -35
View File
@@ -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<EntryId>,
/// 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<u64> {
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<S: LogStore>(
wal: &Wal<S>,
node_id: Option<u64>,
source_node_id: Option<u64>,
reported_entry_id: EntryId,
upto: EntryId,
candidate: Option<CandidateLease<'_>>,
) -> Result<(PendingManifestHook, Option<RegionEdit>)> {
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<S: LogStore>(
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<S: LogStore>(
entry_id: bound,
},
source_node_id,
reported_entry_id,
upto,
upto_kind,
)?;
bound
};
let floor = wal.handoff(region_id, &region.provider, bound).await?;
let handoff = wal.handoff(region_id, &region.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<S: LogStore>(
entry_id: floor,
},
source_node_id,
reported_entry_id,
upto,
upto_kind,
)?;
let pending = region
.manifest_ctx
@@ -322,27 +438,30 @@ impl<S: LogStore> RegionCatchupTask<S> {
}
}
/// 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<u64>,
reported_entry_id: EntryId,
upto: EntryId,
upto_kind: UptoKind,
) -> Result<RegionEdit> {
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:?}");
}
}
+14 -3
View File
@@ -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<WalEntryReceiver>,
takeover: Option<Result<TakeoverPrepared>>,
) -> (WorkerRequest, Receiver<Result<AffectedRows>>) {
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<WalEntryReceiver>)),
Catchup(
(
RegionCatchupRequest,
Option<WalEntryReceiver>,
Option<Result<TakeoverPrepared>>,
),
),
EnterStaging(EnterStagingRequest),
ApplyStagingManifest(ApplyStagingManifestRequest),
}
@@ -1648,6 +1656,9 @@ pub(crate) struct CaughtUpAgain {
pub(crate) result: Result<MitoRegionRef>,
/// 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<TakeoverPrepared>,
/// Receives the result of the catchup.
pub(crate) sender: OptionOutputTx,
}
+27 -1
View File
@@ -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<Entry>>;
/// [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<EntryStream<'static>>;
/// 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<Option<EntryId>, BoxedError>> {
Box::pin(async { Ok(None) })
}
}
/// Implement the [RawEntryReader] for the [LogStore].
@@ -47,6 +60,19 @@ impl<S> LogStoreRawEntryReader<S> {
}
impl<S: LogStore> RawEntryReader for LogStoreRawEntryReader<S> {
fn list_upper_bound(
&self,
node_id: u64,
region_id: RegionId,
) -> BoxFuture<'_, std::result::Result<Option<EntryId>, 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<EntryStream<'static>> {
let store = self.store.clone();
let provider = provider.clone();
+9 -3
View File
@@ -1721,9 +1721,15 @@ impl<S: LogStore> RegionWorkerLoop<S> {
.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) => {
+159 -24
View File
@@ -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<S: LogStore> RegionWorkerLoop<S> {
/// 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<WalEntryReceiver>,
takeover: Option<Result<TakeoverPrepared>>,
sender: OptionOutputTx,
) {
let Some(region) = self.regions.get_region(region_id) else {
@@ -89,10 +103,21 @@ impl<S: LogStore> RegionWorkerLoop<S> {
sender.send(Ok(0));
return;
};
let takeover = match takeover_source(&request, &region)
.map(|_| check_takeover(&region, 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<S: LogStore> RegionWorkerLoop<S> {
// 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<S: LogStore> RegionWorkerLoop<S> {
// 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<S: LogStore> RegionWorkerLoop<S> {
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(&region, &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(
&region,
&wal,
node_id,
request.source_node_id,
upto,
candidate,
)
.await
{
Ok((hook, edit)) => {
hook.fire().await;
@@ -223,12 +274,15 @@ impl<S: LogStore> RegionWorkerLoop<S> {
/// 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<WalEntryReceiver>,
takeover: Option<TakeoverPrepared>,
sender: OptionOutputTx,
) {
let region_id = region.region_id;
@@ -252,18 +306,29 @@ impl<S: LogStore> RegionWorkerLoop<S> {
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(&region))?;
}
None => task.run().await?,
}
Ok(replacement)
}
.await;
@@ -273,6 +338,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
last_sequence,
result,
set_writable: request.set_writable,
takeover,
sender,
});
notify_worker(&worker_sender, region_id, notify).await;
@@ -282,7 +348,9 @@ impl<S: LogStore> RegionWorkerLoop<S> {
/// 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<S: LogStore> RegionWorkerLoop<S> {
last_sequence,
result,
set_writable,
takeover,
sender,
} = caught_up;
let registered = self
@@ -322,7 +391,28 @@ impl<S: LogStore> RegionWorkerLoop<S> {
// 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<S: LogStore> RegionWorkerLoop<S> {
.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<MitoRegion>,
version: ManifestVersion,
) -> Result<Arc<MitoRegion>> {
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(&region).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<MitoRegion>,
@@ -663,6 +777,27 @@ impl<S> RegionWorkerLoop<S> {
}
}
/// 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<TakeoverPrepared>>,
) -> Result<TakeoverPrepared> {
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 {
+14
View File
@@ -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<Option<EntryId>, 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.
///
+6 -1
View File
@@ -2049,8 +2049,13 @@ pub struct RegionCatchupRequest {
pub metadata_entry_id: Option<entry::Id>,
/// Replay checkpoint.
pub checkpoint: Option<ReplayCheckpoint>,
/// 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<u64>,
/// 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<u64>,
}
#[derive(Debug, Clone)]