feat: hand a region over to the object store WAL during catchup (#10589)

* feat(log-store): hand a region over to the object store WAL

Add LogStore::handoff, called before a region becomes writable on a log
store. Once it returns, every id the log store assigns the region is
above the given entry id and every id it assigned the region before,
also after a restart; no entry became obsolete, and check_region_history
accepts the region. The default does nothing.

The object store WAL raises its next object sequence above the object
holding that id, sealing the open batch first if it holds ids under the
current sequence, and keeps a release record of the region's current
watermark for the next sealed batch. It answers once that object is
durable and indexed, in both acknowledgement modes, and then records
that the region's history starts in the store. Hand-offs within one
flush interval share the object.

A store that is failing or lacks I/O permission keeps the floor and the
record and fails the call with a retryable error. If the open batch
cannot be sealed, a durable store has rolled it back and applies both at
once; an enqueued store keeps the batch and applies the largest deferred
floor of each region once it is sealed, unless the store stops first. A
hand-off handled after stop began fails as stopped and keeps nothing.

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

* feat(mito2): hand a region over and claim the next manifest version in catchup

A catchup that makes a region writable and carries the entry id its
source reported hands the region over to the log store before the WAL
history check. The hand-off covers the reported id, the flushed entry id
and every pending tail's upto. A catchup that still has to replay entries
above where its replay starts hands nothing over, so if it cannot reach
them it leaves nothing behind; on the object store WAL it cannot read
them from this node's prefix.

Before the region is promoted, the catchup commits an empty edit as the
version after the manifest the region holds. It runs only under
conditional manifest publication and requires a Follower with no pending
reload and not stopped. It skips the Leader deadline check, starts no
checkpoint and applies only if no checkpoint covers its version. A
writer that committed other content at that version conflicts with it;
the conflict fails the catchup with a retryable error and leaves the
region a Follower that is not fenced. Two catchups that start from the
same manifest version are not told apart.

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

* fix(log-store): prune cancelled hand-off waiters and correct the hand-off docs

A hand-off whose caller stopped waiting left its closed response in the
actor until the record's object was sealed, so repeated cancelled
hand-offs during a long outage accumulated one dead waiter each. Prune
closed responses on admission, as the durability waiters do.

Document that errors other than a failing store or a missing I/O permit
keep the retry hint the object store reports, and that a hand-off pending
when stop begins fails as stopped in the durable mode when its object's
create had not started. Add a test for an issued id in the open batch.

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

* test(log-store): describe what a hand-off after stop keeps

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

* fix(mito2): hand over and commit a region caught up again before its swap

A catchup again replays into an unregistered replacement. It now hands the
region over in that replay and makes the catchup commit of the replacement in
handle_caught_up_again, after the checks of the old instance and under its
manifest lock, so no refusal follows the commit.

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

* fix(mito2): fire the catchup commit's manifest hook without manifest locks

commit_catchup returns the receipt of its manifest hook. A catchup again fires
it once it no longer holds the old instance's manifest lock, so a hook that
reads the manifest cannot queue behind a writer waiting for that lock.

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

* docs(log-store): say which object answers a hand-off pending at stop

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

* docs(mito2): note when the catchup commit's manifest hook fires

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

* test(log-store): cover a hand-off in the open batch when stop begins

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

* refactor(log-store): return the hand-off bound and tidy its docs and tests

LogStore::handoff returns the bound it raised the region above; the default
returns the entry id. The object store WAL defers a hand-off only when the
open batch it cannot seal is not empty. The two open-batch seal tests are one
test now, which also checks the returned bound.

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

* docs(mito2): describe the catchup commit's cost and hook, and guard the hand-off gate

Documents the worker stall of a catchup again's commit, the writable catchup
in the region hook coverage, and the replacement's commit in catch_up_again.
Logs a failed catchup commit. Adds cases for a catchup that does not make the
region writable and for a region that skips the WAL.

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

* fix(mito2): keep Leader leases off a caught-up replacement while its hook runs

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

* docs(mito2): tie the replacement's fence to set_writable and tidy the catchup docs and tests

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

* docs(store-api): say which assigned ids the hand-off bound covers

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

* docs: describe the replacement's lease fence and the hand-off bound precisely

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

* fix(mito2): skip the hand-off for a region without a WAL provider

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

* docs(mito2): name the catchup commit as the exception to the manifest fencing rule

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

* test(mito2): cover the hand-off of a region without a WAL provider

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

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
This commit is contained in:
jeremyhi
2026-11-24 16:22:18 +00:00
committed by GitHub
parent 9ecd84f622
commit 0dfd6e70cf
12 changed files with 1684 additions and 79 deletions
+711 -16
View File
@@ -474,6 +474,8 @@ impl ObjectStoreLogStore {
durable_reclaim_boundary: reclaim_boundary,
unindexed: unindexed.into_iter().chain(moved_past).collect(),
pending_releases: BTreeMap::new(),
handoff_waiters: Vec::new(),
deferred_handoffs: HashMap::new(),
release_retry: RetryBackoff::default(),
release_retry_logged_at: None,
creating: HashSet::new(),
@@ -1326,6 +1328,58 @@ impl LogStore for ObjectStoreLogStore {
Ok(())
}
/// Raises the sequence of the next object above the object that holds
/// the bound, the larger of `entry_id` and the largest id of the region in
/// the objects the store opened with or issued since it opened, sealing
/// the open batch first if it holds ids under the current sequence.
/// Returns the bound once a release record of the region's current
/// watermark is durable and indexed in an object at or above that
/// sequence. A store opened later takes its next sequence from that
/// object, and the watermark does not move. The record joins the next
/// sealed batch, so hand-offs within one flush interval share an object.
///
/// In the `enqueued` mode a bound at or below an id the store already
/// assigned the region needs no raised sequence, as that mode never
/// assigns an id twice: the record may then share the object of that id,
/// and every later id of the region is above it.
///
/// A store that is failing or lacks I/O permission keeps the raised
/// sequence and the record and fails the call with a retryable error; the
/// record is written with a later batch. Other errors are as the object
/// store reports them. If the open batch holds ids under the floor and
/// cannot be sealed, the floor and the record wait for that seal instead,
/// unless the store stops first.
///
/// The wait usually ends with the next periodic seal. It is longer while
/// the object store returns errors: in the `enqueued` mode the create is
/// repeated until it succeeds, and in the `durable` mode a seal that only
/// carries records waits for the backoff of earlier rollbacks. A hand-off
/// pending when stop begins gets the outcome of the object that carries
/// its record, which is stop's last object if its record was not yet
/// sealed into a batch. In the `durable` mode, one whose record was in a
/// sealed batch whose create had not started fails as stopped, and stop
/// writes the record into its last object.
async fn handoff(&self, provider: &Provider, entry_id: EntryId) -> Result<EntryId> {
let region_id = self.region_of(provider)?;
let (response_tx, response_rx) = oneshot::channel();
self.command_tx
.send(Command::Handoff {
region_id,
entry_id,
response: response_tx,
})
.await
.ok()
.context(ObjectStoreWalStoppedSnafu)?;
let (bound, persisted) = response_rx
.await
.ok()
.context(ObjectStoreWalStoppedSnafu)??;
persisted.await.ok().context(ObjectStoreWalStoppedSnafu)??;
self.start_region_history(provider)?;
Ok(bound)
}
async fn read_node(
&self,
node_id: u64,
@@ -1372,6 +1426,13 @@ enum Command {
full: bool,
response: oneshot::Sender<Result<()>>,
},
/// Answered with the bound and a receiver of the outcome of the object
/// that carries the release record, see [`Actor::handle_handoff`].
Handoff {
region_id: RegionId,
entry_id: EntryId,
response: oneshot::Sender<Result<(EntryId, oneshot::Receiver<Result<()>>)>>,
},
/// Answered once the actor has accepted the bounded release for its next
/// batch. Unlike `Release`, this does not wait for persistence.
ReleaseEntries {
@@ -1560,9 +1621,9 @@ impl Failing {
/// | --- | --- | --- | --- |
/// | created, or identical retry | advances | acknowledged in order | healthy |
/// | transient error, `durable` mode | never reused: a create that reported an error may have written its object | every batch that is not indexed fails, created ones included; retries are assigned new ids | healthy: the next batch links to the last indexed object, so no chain reaches a failed batch; retained releases back off before a release-only retry |
/// | transient error, `enqueued` mode | unchanged | already acknowledged, except a permanent release, which waits for the repeat | healthy: the create is repeated with the same bytes after [`CREATE_RETRY_DELAY`], which an identical retry accepts |
/// | error that requires intervention, `enqueued` mode | unchanged | already acknowledged, except a permanent release, which fails while its record stays in the backlog; later appends and permanent releases are rejected with a retryable error | failing, see [`Failing`]: the lowest pending create is repeated alone with backoff, and the first create that succeeds ends it |
/// | object store error, `enqueued` mode after `stop` began | never reused | already acknowledged, except a permanent release, which fails with the stopped error | the backlog is dropped and `stop` reports the error |
/// | transient error, `enqueued` mode | unchanged | already acknowledged, except a permanent release or a hand-off, which waits for the repeat | healthy: the create is repeated with the same bytes after [`CREATE_RETRY_DELAY`], which an identical retry accepts |
/// | error that requires intervention, `enqueued` mode | unchanged | already acknowledged, except a permanent release or a hand-off, which fails while its record stays in the backlog; later appends, permanent releases and hand-offs are rejected with a retryable error | failing, see [`Failing`]: the lowest pending create is repeated alone with backoff, and the first create that succeeds ends it |
/// | object store error, `enqueued` mode after `stop` began | never reused | already acknowledged, except a permanent release or a hand-off, which fails with the stopped error | the backlog is dropped and `stop` reports the error |
/// | an object of an earlier epoch holds the sequence, `durable` mode | never reused | as for a transient error | healthy: that object can never be on the chain |
/// | an object of the same or a later epoch holds the sequence, any conflicting object in the `enqueued` mode, encoding or catalog error | unchanged | every batch that is not indexed fails | poisoned |
/// | created at the last representable sequence | cannot advance | acknowledged | poisoned: no later batch can be allocated a sequence |
@@ -1656,6 +1717,15 @@ struct Actor {
/// region for the next sealed batch. Timer ticks seal them when no entries
/// arrive, after any durable rollback backoff; shutdown drains them in both modes.
pending_releases: BTreeMap<RegionId, EntryId>,
/// Callers of a hand-off whose record is in `pending_releases`; the next
/// sealed batch carries them.
handoff_waiters: Vec<oneshot::Sender<Result<()>>>,
/// Regions and bounds of hand-offs that found the open batch holding ids
/// under a sequence their floor must pass and could not seal it, keeping
/// the largest bound of each region. Once it is sealed, the floors move
/// and the next batch carries their records, unless the store stops
/// first: a stopped store assigns no ids, and their hand-offs failed.
deferred_handoffs: HashMap<RegionId, EntryId>,
/// Backoff for release-only sealing after a durable rollback retains records.
release_retry: RetryBackoff,
/// Last warning about retained release records after a durable rollback.
@@ -1730,6 +1800,10 @@ impl Actor {
Some(Command::Release { region_id, full, response }) => {
self.handle_release(region_id, full, response);
}
Some(Command::Handoff { region_id, entry_id, response }) => {
let result = self.handle_handoff(region_id, entry_id);
let _ = response.send(result);
}
Some(Command::ReleaseEntries { region_id, entry_id, response }) => {
let result = self.handle_release_entries(region_id, entry_id);
let _ = response.send(result);
@@ -2023,11 +2097,19 @@ impl Actor {
sealed_at: Instant::now(),
attempts: 0,
waiters: std::mem::take(&mut self.pending),
release_waiters: Vec::new(),
// Their records were pending, so the batch carries them.
release_waiters: std::mem::take(&mut self.handoff_waiters),
#[cfg(any(test, feature = "testing"))]
seal_waiters: Vec::new(),
state: CreateState::Pending,
});
// The open batch is sealed, so the deferred floors can move, and a
// later batch carries their records.
for (region_id, bound) in std::mem::take(&mut self.deferred_handoffs) {
if matches!(self.raise_sequence_floor(region_id, bound), Ok(true)) {
self.keep_watermark_record(region_id);
}
}
self.start_creates();
true
}
@@ -2271,10 +2353,13 @@ impl Actor {
}
// So would a release. Its record stays in the backlog and becomes
// durable with it.
for batch in &mut self.sealed {
for waiter in batch.release_waiters.drain(..) {
let _ = waiter.send(Err(failing.reject()));
}
for waiter in self
.sealed
.iter_mut()
.flat_map(|batch| batch.release_waiters.drain(..))
.chain(self.handoff_waiters.drain(..))
{
let _ = waiter.send(Err(failing.reject()));
}
}
@@ -2520,7 +2605,8 @@ impl Actor {
self.fail_waiters(error);
}
/// Fails the waiters of the open batch and the durability waiters.
/// Fails the waiters of the open batch, the durability waiters and the
/// hand-offs whose records are pending; the records stay pending.
fn fail_waiters(&mut self, error: impl Fn() -> Error) {
for pending in self.pending.drain(..) {
let _ = pending.response.send(Err(error()));
@@ -2528,6 +2614,9 @@ impl Actor {
for waiter in self.durable_waiters.drain(..) {
let _ = waiter.response.send(Err(error()));
}
for waiter in self.handoff_waiters.drain(..) {
let _ = waiter.send(Err(error()));
}
}
fn handle_wait_durable(
@@ -2704,6 +2793,63 @@ impl Actor {
Ok(())
}
/// Handles [`ObjectStoreLogStore::handoff`], see there: returns the bound
/// and a receiver answered with the outcome of the batch that carries the
/// release record.
fn handle_handoff(
&mut self,
region_id: RegionId,
entry_id: EntryId,
) -> Result<(EntryId, oneshot::Receiver<Result<()>>)> {
let bound = entry_id.max(self.issued_entry_ids.get(&region_id).copied().unwrap_or(0));
// Stop, then a terminal error, are checked only by the raise, so a
// hand-off handled after stop began fails as stopped.
match self.raise_sequence_floor(region_id, bound) {
Ok(raised) => ensure!(raised, ObjectStoreWalStoppedSnafu),
Err(Error::WalObjectSequenceUnsettled { .. }) => {
// A `durable` store without I/O permission rolls the open
// batch back, so the floor can move now; the `enqueued` mode
// keeps the batch, and the floor waits for its seal.
if !self.flush_open_batch() && !self.open_batch.is_empty() {
let deferred = self.deferred_handoffs.entry(region_id).or_default();
*deferred = (*deferred).max(bound);
return ObjectStoreWalLeaseExpiredSnafu.fail();
}
ensure!(
self.raise_sequence_floor(region_id, bound)?,
ObjectStoreWalStoppedSnafu
);
}
Err(error) => return Err(error),
}
self.keep_watermark_record(region_id);
if let Some(failing) = &mut self.failing {
return Err(failing.reject());
}
ensure!(self.io_allowed(), ObjectStoreWalLeaseExpiredSnafu);
let (response, receiver) = oneshot::channel();
// A caller that stopped waiting leaves a closed response behind.
self.handoff_waiters.retain(|waiter| !waiter.is_closed());
self.handoff_waiters.push(response);
Ok((bound, receiver))
}
/// Keeps a release record of the region's current watermark, or of 0
/// without one, for the next sealed batch.
fn keep_watermark_record(&mut self, region_id: RegionId) {
let watermark = self
.obsolete_entry_ids
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(&region_id)
.copied()
.unwrap_or(0);
self.keep_release(Release {
region_id,
entry_id: watermark,
});
}
/// Moves the watermark of the region up to the release and seals the
/// open batch with a release record of the region; `response` is
/// answered once that object is durable and indexed. The batch carries
@@ -2898,10 +3044,11 @@ impl Actor {
/// `entry_id` unless it is there already. The move fails while the open
/// batch has handed out ids under the next sequence. A floor that does
/// not fit an entry id poisons the store like an exhausted sequence.
fn raise_sequence_floor(&mut self, region_id: RegionId, entry_id: EntryId) -> Result<()> {
// Nothing is assigned an id after stop began.
/// Returns false if stop began, which leaves the floor where it is, as
/// nothing is assigned an id any more.
fn raise_sequence_floor(&mut self, region_id: RegionId, entry_id: EntryId) -> Result<bool> {
if self.is_stopped() {
return Ok(());
return Ok(false);
}
if let Some(error) = terminal(&self.terminal_error) {
return Err(shared(&error));
@@ -2914,14 +3061,14 @@ impl Actor {
if self.ack_mode == AckMode::Enqueued
&& entry_id <= self.issued_entry_ids.get(&region_id).copied().unwrap_or(0)
{
return Ok(());
return Ok(true);
}
let sequence_floor = sequence_floor(entry_id);
let Some(next_object_seq) = self.next_object_seq else {
return Ok(());
return Ok(true);
};
if next_object_seq >= sequence_floor {
return Ok(());
return Ok(true);
}
ensure!(
self.open_batch.is_empty(),
@@ -2931,7 +3078,7 @@ impl Actor {
);
if sequence_floor < OBJECT_SEQ_LIMIT {
self.next_object_seq = Some(sequence_floor);
Ok(())
Ok(true)
} else {
self.next_object_seq = None;
let error = self.poison(
@@ -4127,6 +4274,18 @@ mod tests {
tokio::spawn(async move { store.append_batch(entries).await })
}
/// Waits until `count` hand-offs wait for the object that carries their
/// records.
async fn wait_for_handoff_waiters(store: &ObjectStoreLogStore, count: usize) {
timeout(WAIT, async {
while inspect_actor(store, |actor| actor.handoff_waiters.len()).await < count {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}
/// Appends `count` single-entry batches, waiting for each to be admitted
/// before the next is sent, so they are admitted in order.
async fn spawn_appends(
@@ -10585,6 +10744,542 @@ mod tests {
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_handoff_raises_ids_above_the_bound_and_keeps_the_watermark() {
let _serialized = SERIALIZED.lock().await;
let object_store = memory_store();
let config = config(MIN_FLUSH_INTERVAL, u64::MAX);
let store = open(object_store.clone(), &config).await;
let one = region(1);
let first = append(&store, one, "a1").await.unwrap().last_entry_ids[&one];
assert_eq!(id(1, 1), first);
// A bound below the ids issued for the region hands it over too.
store.handoff(&provider(one), 0).await.unwrap();
// A larger bound moves the next sequence past its object, and the
// object carrying the record is the first at that sequence. The record
// keeps the region's watermark, which it has none of.
let bound = id(5, 3);
store.handoff(&provider(one), bound).await.unwrap();
assert_eq!(
vec![release(one, 0)],
releases_of(store.io.as_ref(), 6).await
);
assert_eq!(None, watermark(&store, one));
assert_eq!(
expected_entries(one, &[(first, "a1")]),
read_entries(&store, one, 0).await
);
store.stop().await.unwrap();
assert!(matches!(
store.handoff(&provider(one), bound).await,
Err(Error::ObjectStoreWalStopped { .. })
));
// A store opened later, whose newest object is the record's, holds
// the history through the bound, assigns ids above it and still reads
// the region's entries.
let store = open(object_store, &config).await;
assert_eq!(None, missing_history(&store, one, bound).await);
let next = append(&store, one, "a3").await.unwrap().last_entry_ids[&one];
assert!(next > bound, "{next} is not above {bound}");
assert_eq!(first, read_entries(&store, one, 0).await[0].entry_id());
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_handoff_records_the_current_watermark_of_the_region() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &config(MIN_FLUSH_INTERVAL, u64::MAX)).await;
let one = region(1);
let first = append(&store, one, "a1").await.unwrap().last_entry_ids[&one];
let second = append(&store, one, "a2").await.unwrap().last_entry_ids[&one];
store.obsolete(&provider(one), one, first).await.unwrap();
assert_eq!(Some(first), watermark(&store, one));
// Each hand-off records the watermark, not its bound, and the entry
// above the watermark stays readable.
let bound = id(5, 3);
store.handoff(&provider(one), bound).await.unwrap();
assert_eq!(
vec![release(one, first)],
releases_of(store.io.as_ref(), 6).await
);
let bound = id(7, 1);
store.handoff(&provider(one), bound).await.unwrap();
assert_eq!(
vec![release(one, first)],
releases_of(store.io.as_ref(), 8).await
);
assert_eq!(Some(first), watermark(&store, one));
assert_eq!(
expected_entries(one, &[(second, "a2")]),
read_entries(&store, one, 0).await
);
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_handoff_admitted_after_stop_began_keeps_nothing() {
let _serialized = SERIALIZED.lock().await;
for poisoned in [false, true] {
let store = open(memory_store(), &manual()).await;
let one = region(1);
// Stop sets its flag before the actor handles a command, so a
// hand-off the actor handles after that fails as stopped, also on a
// poisoned store, and keeps no floor, record or waiter.
let (stopped, next_object_seq, records, waiters) =
inspect_actor(&store, move |actor| {
if poisoned {
set_terminal(
&actor.terminal_error,
WalObjectSequenceExhaustedSnafu {
last_object_seq: 1_u64,
}
.build(),
);
}
let next_object_seq = actor.next_object_seq;
actor.stopped.store(true, Ordering::Release);
let result = actor.handle_handoff(one, id(9, 1));
actor.stopped.store(false, Ordering::Release);
(
matches!(result, Err(Error::ObjectStoreWalStopped { .. })),
actor.next_object_seq == next_object_seq,
actor.pending_releases.len(),
actor.handoff_waiters.len(),
)
})
.await;
assert!(stopped, "poisoned: {poisoned}");
assert!(next_object_seq);
assert_eq!(0, records);
assert_eq!(0, waiters);
let _ = store.stop().await;
}
}
#[tokio::test]
async fn test_store_handoff_starts_the_region_history_on_a_prefix_found_empty() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &config(MIN_FLUSH_INTERVAL, u64::MAX)).await;
let (one, two) = (region(1), region(2));
let bound = id(9, 1);
store.handoff(&provider(one), bound).await.unwrap();
// The store accepts the history of the region handed over to it,
// though it found its prefix empty, and only that one. The record
// object reclaims the start object, and the store goes on taking
// appends.
assert_eq!(None, missing_history(&store, one, bound).await);
assert!(missing_history(&store, two, 0).await.is_some());
assert_eq!(vec![10], collected_object_seqs(&store).await);
append(&store, two, "b1").await.unwrap();
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_handoffs_in_one_interval_share_an_object() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &manual()).await;
let (one, two) = (region(1), region(2));
let handoffs = [one, two].map(|region_id| {
let store = store.clone();
tokio::spawn(async move { store.handoff(&provider(region_id), 0).await })
});
wait_for_handoff_waiters(&store, 2).await;
assert!(handoffs.iter().all(|handoff| !handoff.is_finished()));
store.seal_open_batch().await.unwrap();
for handoff in handoffs {
handoff.await.unwrap().unwrap();
}
assert_eq!(vec![1], collected_object_seqs(&store).await);
assert_eq!(
vec![release(one, 0), release(two, 0)],
releases_of(store.io.as_ref(), 1).await
);
store.stop().await.unwrap();
}
/// A hand-off whose floor must pass ids in the open batch seals that batch
/// first: an id of another region under the given bound, or an id issued
/// to the region itself, whose largest issued id then is the bound. The
/// record goes into the first object above the bound.
#[tokio::test]
async fn test_store_handoff_seals_the_open_batch_below_the_floor() {
let _serialized = SERIALIZED.lock().await;
let (one, two) = (region(1), region(2));
// The appended region, the hand-off's entry id, the bound it returns
// and the object of its record.
for (appended_region, entry_id, bound, record_seq) in
[(two, id(5, 1), id(5, 1), 6), (one, 0, id(1, 1), 2)]
{
let store = open(memory_store(), &manual()).await;
// The append waits in the open batch under sequence 1.
let [appended] = spawn_appends(&store, appended_region, 1)
.await
.try_into()
.unwrap();
let handoff = {
let store = store.clone();
tokio::spawn(async move { store.handoff(&provider(one), entry_id).await })
};
wait_for_handoff_waiters(&store, 1).await;
// The hand-off's own seal created the object of the append.
let appended = timeout(WAIT, appended).await.unwrap().unwrap().unwrap();
assert_eq!(id(1, 1), appended.last_entry_ids[&appended_region]);
store.seal_open_batch().await.unwrap();
assert_eq!(
bound,
timeout(WAIT, handoff).await.unwrap().unwrap().unwrap()
);
assert_eq!(vec![1, record_seq], collected_object_seqs(&store).await);
assert_eq!(
vec![release(one, 0)],
releases_of(store.io.as_ref(), record_seq).await
);
store.stop().await.unwrap();
}
}
#[tokio::test]
async fn test_store_handoff_without_io_permission_keeps_the_floor_and_the_record() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &manual()).await;
let permit = Arc::new(TestIoPermit::default());
store.set_io_permit(permit.clone()).unwrap();
let one = region(1);
let bound = id(5, 1);
let error = store.handoff(&provider(one), bound).await.unwrap_err();
assert!(
matches!(error, Error::ObjectStoreWalLeaseExpired { .. }),
"unexpected error: {error:?}"
);
assert!(error.retry_hint().is_retryable());
// Once permission returns, the record goes into an object above the
// bound, and later ids of the region are above it too.
permit.0.store(true, Ordering::Release);
store.seal_open_batch().await.unwrap();
assert_eq!(
vec![release(one, 0)],
releases_of(store.io.as_ref(), 6).await
);
let [append_one] = spawn_appends(&store, one, 1).await.try_into().unwrap();
store.seal_open_batch().await.unwrap();
let next = timeout(WAIT, append_one)
.await
.unwrap()
.unwrap()
.unwrap()
.last_entry_ids[&one];
assert!(next > bound, "{next} is not above {bound}");
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_enqueued_handoff_behind_an_open_batch_without_io_permission_keeps_the_floor()
{
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &enqueued(manual())).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
let (one, two) = (region(1), region(2));
// Acknowledged on admission, the entry stays in the open batch under
// sequence 1.
let appended = append(&store, two, "b1").await.unwrap().last_entry_ids[&two];
assert_eq!(id(1, 1), appended);
permit.0.store(false, Ordering::Release);
let bound = id(5, 1);
let error = store.handoff(&provider(one), bound).await.unwrap_err();
assert!(
matches!(error, Error::ObjectStoreWalLeaseExpired { .. }),
"unexpected error: {error:?}"
);
assert!(error.retry_hint().is_retryable());
// Retries keep one deferred bound per region, the largest.
let largest = id(9, 1);
for retry in [bound, largest, bound] {
assert!(store.handoff(&provider(one), retry).await.is_err());
}
assert_eq!(
vec![(one, largest)],
inspect_actor(&store, |actor| actor
.deferred_handoffs
.iter()
.map(|(region_id, bound)| (*region_id, *bound))
.collect::<Vec<_>>())
.await
);
let bound = largest;
// Once permission returns, the open batch is sealed under its own
// sequence and the record goes into the first object above the
// bound, without another hand-off.
permit.0.store(true, Ordering::Release);
store.seal_open_batch().await.unwrap();
store.seal_open_batch().await.unwrap();
assert_eq!(
vec![release(one, 0)],
releases_of(store.io.as_ref(), 10).await
);
assert_eq!(
expected_entries(two, &[(appended, "b1")]),
read_entries(&store, two, 0).await
);
let next = append(&store, one, "a1").await.unwrap().last_entry_ids[&one];
assert!(next > bound, "{next} is not above {bound}");
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_cancelled_handoffs_leave_at_most_one_closed_waiter() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &manual()).await;
let one = region(1);
// Each caller stops waiting before the record's object is sealed; each
// admission drops the closed waiters before it, so only the last one
// is left.
let (waiters, records) = inspect_actor(&store, move |actor| {
for _ in 0..3 {
drop(actor.handle_handoff(one, id(5, 1)).unwrap());
}
(actor.handoff_waiters.len(), actor.pending_releases.len())
})
.await;
assert_eq!((1, 1), (waiters, records));
store.stop().await.unwrap();
}
/// A durable hand-off whose record was not yet sealed into a batch when
/// stop begins is sealed into stop's last object and gets that object's
/// outcome: success with its record, or stopped if the create fails.
#[tokio::test]
async fn test_store_pending_handoff_at_stop_gets_the_last_object() {
let _serialized = SERIALIZED.lock().await;
for fail in [false, true] {
let store = open(memory_store(), &manual()).await;
let one = region(1);
let handoff = {
let store = store.clone();
tokio::spawn(async move { store.handoff(&provider(one), 0).await })
};
wait_for_handoff_waiters(&store, 1).await;
store.hold_creates();
let stop = {
let store = store.clone();
tokio::spawn(async move { store.stop().await })
};
store.wait_for_parked_creates(1).await.unwrap();
assert!(!handoff.is_finished());
if fail {
store.fail_creates();
}
store.release_creates();
let handoff = timeout(WAIT, handoff).await.unwrap().unwrap();
let stopped = timeout(WAIT, stop).await.unwrap().unwrap();
if fail {
assert!(
matches!(handoff, Err(Error::ObjectStoreWalStopped { .. })),
"{handoff:?}"
);
// Stop reports the record it lost.
assert!(stopped.is_err());
} else {
handoff.unwrap();
stopped.unwrap();
assert_eq!(
vec![release(one, 0)],
releases_of(store.io.as_ref(), 1).await
);
}
}
}
#[tokio::test]
async fn test_store_deferred_handoff_sealed_after_stop_began_keeps_no_record() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &enqueued(manual())).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
let (one, two) = (region(1), region(2));
append(&store, two, "b1").await.unwrap();
permit.0.store(false, Ordering::Release);
assert!(store.handoff(&provider(one), id(5, 1)).await.is_err());
permit.0.store(true, Ordering::Release);
// A seal after stop began moves no deferred floor, so it keeps no record.
let records = inspect_actor(&store, |actor| {
actor.stopped.store(true, Ordering::Release);
actor.flush_open_batch();
actor.stopped.store(false, Ordering::Release);
actor.pending_releases.len()
})
.await;
assert_eq!(0, records);
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_durable_handoff_behind_an_open_batch_without_io_permission_keeps_the_floor()
{
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &manual()).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
let (one, two) = (region(1), region(2));
// The append waits in the open batch under sequence 1.
let appended = spawn_appends(&store, two, 1).await.pop().unwrap();
permit.0.store(false, Ordering::Release);
let bound = id(5, 1);
let error = store.handoff(&provider(one), bound).await.unwrap_err();
assert!(
matches!(error, Error::ObjectStoreWalLeaseExpired { .. }),
"unexpected error: {error:?}"
);
assert!(error.retry_hint().is_retryable());
// Losing permission rolled the open batch back.
assert!(timeout(WAIT, appended).await.unwrap().unwrap().is_err());
// Once permission returns, the record goes into the first object
// above the bound without another hand-off or append.
permit.0.store(true, Ordering::Release);
store.seal_open_batch().await.unwrap();
assert_eq!(
vec![release(one, 0)],
releases_of(store.io.as_ref(), 6).await
);
let next = spawn_appends(&store, one, 1).await.pop().unwrap();
store.seal_open_batch().await.unwrap();
let next = timeout(WAIT, next)
.await
.unwrap()
.unwrap()
.unwrap()
.last_entry_ids[&one];
assert!(next > bound, "{next} is not above {bound}");
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_handoff_fails_while_the_store_is_failing_and_keeps_the_floor() {
let _serialized = SERIALIZED.lock().await;
let (store, io, mut parked) =
open_parking_creates(memory_store(), &enqueued(manual())).await;
let (one, two, three) = (region(1), region(2), region(3));
let appended = append(&store, two, "b1").await.unwrap().last_entry_ids[&two];
let sealed = {
let store = store.clone();
tokio::spawn(async move { store.seal_open_batch().await })
};
let (object_seq, create) = next_parked_operation(&mut parked).await;
assert_eq!(1, object_seq);
let (one_bound, three_bound) = (id(5, 1), id(7, 1));
let waiting = {
let store = store.clone();
tokio::spawn(async move { store.handoff(&provider(one), one_bound).await })
};
wait_for_handoff_waiters(&store, 1).await;
// The refused create makes the store fail: the waiting hand-off and
// one admitted afterwards fail at once.
io.creates_refused.store(true, Ordering::SeqCst);
create.send(false).unwrap();
let error = timeout(WAIT, waiting).await.unwrap().unwrap().unwrap_err();
assert_rejected(&error, ErrorKind::PermissionDenied);
let error = store
.handoff(&provider(three), three_bound)
.await
.unwrap_err();
assert_rejected(&error, ErrorKind::PermissionDenied);
// Once a create succeeds, both records go into the first object above
// both bounds without another hand-off, and later ids are above them.
io.creates_refused.store(false, Ordering::SeqCst);
let (object_seq, create) = next_parked_operation(&mut parked).await;
assert_eq!(1, object_seq);
create.send(true).unwrap();
timeout(WAIT, sealed).await.unwrap().unwrap().unwrap();
assert_eq!(0, failing_stores());
assert_eq!(
expected_entries(two, &[(appended, "b1")]),
read_entries(&store, two, 0).await
);
let sealed = {
let store = store.clone();
tokio::spawn(async move { store.seal_open_batch().await })
};
let (object_seq, create) = next_parked_operation(&mut parked).await;
assert_eq!(8, object_seq);
create.send(true).unwrap();
timeout(WAIT, sealed).await.unwrap().unwrap().unwrap();
assert_eq!(
vec![release(one, 0), release(three, 0)],
releases_of(io.as_ref(), 8).await
);
io.creates_parked.store(false, Ordering::SeqCst);
let next = append(&store, one, "a1").await.unwrap().last_entry_ids[&one];
assert!(next > three_bound, "{next} is not above {three_bound}");
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_handoff_waiting_for_its_object_fails_when_io_permission_is_lost() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &manual()).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
let one = region(1);
let bound = id(5, 1);
let handoff = {
let store = store.clone();
tokio::spawn(async move { store.handoff(&provider(one), bound).await })
};
wait_for_handoff_waiters(&store, 1).await;
// The hand-off fails as soon as the store loses permission, and its
// record goes above the bound once permission returns.
permit.0.store(false, Ordering::Release);
assert!(store.seal_open_batch().await.is_err());
let error = timeout(WAIT, handoff).await.unwrap().unwrap().unwrap_err();
assert!(error.retry_hint().is_retryable(), "{error:?}");
assert!(
format!("{error:?}").contains("node lease is unavailable or expired"),
"unexpected error: {error:?}"
);
permit.0.store(true, Ordering::Release);
store.seal_open_batch().await.unwrap();
assert_eq!(
vec![release(one, 0)],
releases_of(store.io.as_ref(), 6).await
);
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_enqueued_handoff_answers_once_its_object_is_durable() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &enqueued(manual())).await;
let one = region(1);
store.hold_creates();
let handoff = {
let store = store.clone();
tokio::spawn(async move { store.handoff(&provider(one), 0).await })
};
wait_for_handoff_waiters(&store, 1).await;
let seal = {
let store = store.clone();
tokio::spawn(async move { store.seal_open_batch().await })
};
store.wait_for_parked_creates(1).await.unwrap();
assert!(!handoff.is_finished());
store.release_creates();
timeout(WAIT, seal).await.unwrap().unwrap().unwrap();
timeout(WAIT, handoff).await.unwrap().unwrap().unwrap();
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_store_recovery_seeds_watermarks_from_release_records() {
let _serialized = SERIALIZED.lock().await;
+11 -6
View File
@@ -155,7 +155,9 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
it until the worker swaps in an instance reloaded from the new manifest
(`worker/handle_reload.rs`). A tail replay round that fails while the storage holds a newer
manifest fences a writable leader the same way. Never await a worker sender while holding a
manifest guard.
manifest guard. The catchup commit (`ManifestContext::commit_catchup`) is the exception: it
commits as a Follower without the deadline check, and a conflict fails the catchup retryably
without fencing the region; a retry reopens it from the newer manifest.
- Pending tails (`RegionManifest::pending_tails`) are WAL ranges a region still has
to recover; the flushed entry id never prunes them. Opening a region replays its
WAL after `RegionManifest::wal_replay_start`. The WAL releases at open, after
@@ -234,15 +236,18 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
`ManifestContext::update_locked` refuses its commits unless they are staged or the region is
downgrading (a close that must flush downgrades first); only a replay of tails
(`TailsEditor::Replay`) skips the check, a discard does not, and ending staging checks it
before `commit_staged_locked`. No flush or compaction trigger starts work for a waiting region except
a downgrade's flush. The lease that ends the wait wakes the worker
before `commit_staged_locked`. `ManifestContext::commit_catchup` commits an empty edit as a
Follower; fire its hook only after every manifest guard is dropped, including the old instance's
read guard held by `handle_caught_up_again`. No flush or compaction trigger starts work for a
waiting region except a downgrade's flush. The lease that ends the wait wakes the worker
(`handle_leader_lease_wait_ended`) to schedule the flushes the wait deferred and, only if the
region is then a writable leader, start a compaction, build missing indexes, re-issue the
index build retries the wait refused and persist backfilled metadata. A catchup of a waiting
region catches it up again into an unregistered replacement while the region stays registered,
demoted unless it is in a transient leader state. The replacement replaces it only if the replay
succeeds and the region took no write and made no commit meanwhile; otherwise the region keeps
its memtable for the next Leader lease (`catch_up_again`, `handle_caught_up_again`); the datanode
demoted unless it is in a transient leader state. The replacement replaces it only if the
replay succeeds, the region took no write and made no commit meanwhile and, for a catchup that
makes it writable, the replacement's catchup commit succeeds; otherwise the region keeps its
memtable for the next Leader lease (`catch_up_again`, `handle_caught_up_again`); the datanode
upgrade handler sends that catchup unless `RegionEngine::is_confirmed_leader` is true, so an
engine wrapping mito must implement that method from mito's answers (the metric engine requires
both regions of the pair). A Follower lease that carries a `candidate_lease_id` leaves a waiting
@@ -51,7 +51,7 @@ use store_api::mito_engine_options::SKIP_WAL_KEY;
use store_api::region_engine::{RegionEngine, RegionManifestInfo, RegionRole};
use store_api::region_request::{
PathType, RegionCatchupRequest, RegionCloseRequest, RegionDropRequest, RegionFlushRequest,
RegionOpenRequest, RegionPutRequest, RegionRequest, RegionTruncateRequest,
RegionOpenRequest, RegionPutRequest, RegionRequest, RegionTruncateRequest, ReplayCheckpoint,
};
use store_api::storage::{RegionId, ScanRequest};
@@ -62,7 +62,9 @@ use crate::engine::object_store_wal_test::{
encode_delta, is_replaced, next_manifest_version, publish_delta, wait_until,
};
use crate::engine::pending_tail_test::{set_pending_tails, tail};
use crate::manifest::action::{PendingTail, UptoKind};
use crate::manifest::action::{
PendingTail, RegionEdit, RegionMetaAction, RegionMetaActionList, UptoKind,
};
use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState};
use crate::request::WorkerRequest;
use crate::sst::location::region_dir_from_table_dir;
@@ -994,6 +996,178 @@ async fn test_moving_the_wal_keeps_the_history_only_with_its_objects() {
assert_eq!(10, engine.get_region_statistic(REGION_A).unwrap().num_rows);
}
/// A catchup whose source reported entries above the flushed entry id cannot replay them from this
/// node's WAL, so it hands nothing over: it fails, and so do one without a reported entry id and
/// one that does not make the region writable, also after a restart. A writable catchup of a
/// region that skips the WAL hands nothing over either.
#[tokio::test]
async fn test_catchups_that_hand_nothing_over() {
let mut env = TestEnv::with_prefix("object-store-wal-no-handoff").await;
let config = ObjectStoreWalConfig {
flush_interval: Duration::from_millis(10),
..store_config(AckMode::Durable)
};
let open_store = |object_store: ObjectStore| {
let config = config.clone();
async move {
ObjectStoreLogStore::try_new(object_store, &config, 0, FIXED_DIRECTORY_GENERATION)
.await
.unwrap()
}
};
let engine = new_engine(&mut env, open_store(memory_store()).await).await;
let (table_dir, schema) = create_region(&engine, REGION_A, &[]).await;
let (table_dir_b, _) = create_region(&engine, REGION_B, &[(SKIP_WAL_KEY, "true")]).await;
put_rows(&engine, REGION_A, rows(&schema, 0, 3)).await;
flush_region(&engine, REGION_A, None).await;
let flushed_entry_id = region(&engine, REGION_A).version().flushed_entry_id;
put_rows(&engine, REGION_A, rows(&schema, 3, 5)).await;
let reported_entry_id = region(&engine, REGION_A)
.version_control
.current()
.last_entry_id;
engine.stop().await.unwrap();
drop(engine);
let location = memory_store();
let catchup = |set_writable, entry_id| {
RegionRequest::Catchup(RegionCatchupRequest {
set_writable,
entry_id,
..Default::default()
})
};
let skip_replay = || {
RegionRequest::Open(RegionOpenRequest {
skip_wal_replay: true,
..open_request(&table_dir)
})
};
for (set_writable, entry_id) in [
(true, Some(reported_entry_id)),
(true, None),
(false, Some(flushed_entry_id)),
] {
let store = open_store(location.clone()).await;
let engine = new_engine(&mut env, store.clone()).await;
engine
.handle_request(REGION_A, skip_replay())
.await
.unwrap();
let error = engine
.handle_request(REGION_A, catchup(set_writable, entry_id))
.await
.unwrap_err();
assert!(
matches!(
error.as_any().downcast_ref::<crate::error::Error>(),
Some(crate::error::Error::CheckWalHistory { .. })
),
"{set_writable} {entry_id:?}: {error:?}"
);
crash(engine, store).await;
}
let store = open_store(location.clone()).await;
let engine = new_engine(&mut env, store.clone()).await;
open_region(&engine, REGION_B, &table_dir_b, &[(SKIP_WAL_KEY, "true")])
.await
.unwrap();
engine
.set_region_role(REGION_B, RegionRole::Follower)
.unwrap();
let objects = wal_object_seqs(&location).await;
engine
.handle_request(REGION_B, catchup(true, Some(0)))
.await
.unwrap();
assert_eq!(objects, wal_object_seqs(&location).await);
}
/// A catchup that makes a region writable with the last entry id its source reported hands the
/// region over to this node's WAL, whose location held no object when the store opened: the
/// catchup passes the WAL history check, the region opens again after a crash right after it,
/// its new entries take ids above the entry id its source reported, and after another crash the
/// region opens with every row.
#[tokio::test]
async fn test_catchup_with_reported_entry_id_hands_the_region_over() {
let mut env = TestEnv::with_prefix("object-store-wal-handoff").await;
// Seals on its own, as a datanode's store does.
let config = ObjectStoreWalConfig {
flush_interval: Duration::from_millis(10),
..store_config(AckMode::Durable)
};
let open_store = |object_store: ObjectStore| {
let config = config.clone();
async move {
ObjectStoreLogStore::try_new(object_store, &config, 0, FIXED_DIRECTORY_GENERATION)
.await
.unwrap()
}
};
let source = open_store(memory_store()).await;
let engine = new_engine(&mut env, source).await;
let (table_dir, schema) = create_region(&engine, REGION_A, &[]).await;
// One durable append per row puts the flushed entry id in a later object of the source than
// a fresh destination reaches with its first writes without the hand-off.
for row in 0..5 {
put_rows(&engine, REGION_A, rows(&schema, row, row + 1)).await;
}
flush_region(&engine, REGION_A, None).await;
let reported_entry_id = region(&engine, REGION_A).version().flushed_entry_id;
engine.stop().await.unwrap();
drop(engine);
let location = memory_store();
let store = open_store(location.clone()).await;
let engine = new_engine(&mut env, store.clone()).await;
engine
.handle_request(
REGION_A,
RegionRequest::Open(RegionOpenRequest {
skip_wal_replay: true,
..open_request(&table_dir)
}),
)
.await
.unwrap();
engine
.handle_request(
REGION_A,
RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
entry_id: Some(reported_entry_id),
..Default::default()
}),
)
.await
.unwrap();
assert!(region(&engine, REGION_A).is_writable());
// The hand-off's object alone holds the region's history here after a crash.
crash(engine, store).await;
let store = open_store(location.clone()).await;
let engine = new_engine(&mut env, store.clone()).await;
open_region(&engine, REGION_A, &table_dir, &[])
.await
.unwrap();
put_rows(&engine, REGION_A, rows(&schema, 5, 8)).await;
let last_entry_id = region(&engine, REGION_A)
.version_control
.current()
.last_entry_id;
assert!(last_entry_id > reported_entry_id, "{last_entry_id}");
let rows_before = scan_rows(&engine, REGION_A).await;
crash(engine, store).await;
let store = open_store(location).await;
let engine = new_engine(&mut env, store).await;
open_region(&engine, REGION_A, &table_dir, &[])
.await
.unwrap();
assert_eq!(rows_before, scan_rows(&engine, REGION_A).await);
assert_eq!(8, engine.get_region_statistic(REGION_A).unwrap().num_rows);
}
#[tokio::test]
async fn test_open_region_fails_when_its_watermark_is_above_the_wal_objects() {
let mut env = TestEnv::with_prefix("object-store-wal-watermark-above").await;
@@ -1449,6 +1623,7 @@ async fn test_flush_waits_until_the_wal_is_durable() {
/// created while creates are held.
struct WaitingRegion {
env: TestEnv,
location: ObjectStore,
store: Arc<ObjectStoreLogStore>,
engine: MitoEngine,
schema: Vec<api::v1::ColumnSchema>,
@@ -1458,7 +1633,8 @@ struct WaitingRegion {
async fn waiting_region(prefix: &str, ack_mode: AckMode) -> WaitingRegion {
let mut env = TestEnv::with_prefix(prefix).await;
let store = open_store(&memory_store(), ack_mode).await;
let location = memory_store();
let store = open_store(&location, ack_mode).await;
let engine = new_engine(&mut env, store.clone()).await;
engine.require_write_lease();
let (table_dir, schema) = create_region(&engine, REGION_A, &[]).await;
@@ -1474,6 +1650,7 @@ async fn waiting_region(prefix: &str, ack_mode: AckMode) -> WaitingRegion {
let waiting = region(&engine, REGION_A);
WaitingRegion {
env,
location,
store,
engine,
schema,
@@ -1674,6 +1851,103 @@ async fn test_catchup_again_replaces_region_behind_published_manifest() {
assert!(caught_up.is_writable());
}
/// A catchup again with `set_writable` and the entry id its source reported hands the region over
/// and commits the next manifest version before it replaces the region: the replacement holds that
/// version, the replaced instance does not, and the hand-off's record lies above the reported
/// entry id.
#[tokio::test]
async fn test_catchup_again_hands_over_and_commits_before_the_swap() {
let w = waiting_region("object-store-wal-catchup-again-commit", AckMode::Durable).await;
let engine = &w.engine;
let version = next_manifest_version(&w.waiting).await;
// Above every entry of the region, so only the hand-off puts its new entries above it.
let reported_entry_id = entry_id(100, 1);
let request = RegionCatchupRequest {
set_writable: true,
entry_id: Some(reported_entry_id),
checkpoint: Some(ReplayCheckpoint {
entry_id: reported_entry_id,
metadata_entry_id: None,
}),
..Default::default()
};
let catchup = {
let engine = engine.clone();
tokio::spawn(async move {
engine
.handle_request(REGION_A, RegionRequest::Catchup(request))
.await
})
};
// The store seals no batch on its own, and the hand-off answers once its record is durable.
tokio::time::timeout(WAIT, async {
while !catchup.is_finished() {
w.store.seal_open_batch().await.unwrap();
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
catchup_result(catchup).await.unwrap();
let caught_up = region(engine, REGION_A);
assert!(!Arc::ptr_eq(&w.waiting, &caught_up));
assert!(caught_up.is_writable());
assert_eq!(version, caught_up.manifest_ctx.manifest_version().await);
assert_eq!(version, next_manifest_version(&w.waiting).await);
// The hand-off's record went into an object above the reported entry id; the end of the
// replay raises the next object sequence too, but writes no object.
let seqs = wal_object_seqs(&w.location).await;
assert!(seqs.iter().any(|seq| *seq > 100), "{seqs:?}");
}
/// A catchup again whose commit conflicts with a version another writer published while it
/// replayed keeps the region's instance with its rows and fails retryably; a retry opens the
/// replacement from that version and replaces the region.
#[tokio::test]
async fn test_catchup_again_commit_conflict_keeps_the_region() {
let w = waiting_region("object-store-wal-catchup-again-conflict", AckMode::Enqueued).await;
let (engine, waiting) = (&w.engine, &w.waiting);
let version = next_manifest_version(waiting).await;
let (catchup, seal) = spawn_catchup_waiting_for_durability(&w, true).await;
// Other content than the catchup's empty edit.
let other = RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit {
timestamp_ms: Some(1),
..Default::default()
}));
let region_dir = region_dir_from_table_dir(&w.table_dir, REGION_A, PathType::Bare);
publish_delta(
&w.env.get_object_store().unwrap(),
&region_dir,
version,
encode_delta(other).await,
)
.await;
release_held_batch(&w.store, seal).await;
let error = catchup_result(catchup).await.unwrap_err();
assert!(
matches!(
error.as_any().downcast_ref::<crate::error::Error>(),
Some(crate::error::Error::ManifestVersionConflict { .. })
),
"{error:?}"
);
assert!(error.retry_hint().is_retryable(), "{error:?}");
assert!(!engine.is_region_catching_up(REGION_A));
assert!(Arc::ptr_eq(waiting, &region(engine, REGION_A)));
assert!(waiting.is_follower());
assert_eq!(3, memtable_rows(engine).await);
catchup_result(spawn_catchup(engine, true, None))
.await
.unwrap();
let caught_up = region(engine, REGION_A);
assert!(!Arc::ptr_eq(waiting, &caught_up));
assert!(caught_up.is_writable());
assert_eq!(version + 1, caught_up.manifest_ctx.manifest_version().await);
}
/// What happens to the waiting region while its catchup again waits for durability.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Interference {
+444 -11
View File
@@ -15,8 +15,8 @@
//! Tests for regions whose WAL options select the object store WAL.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use api::v1::region::{StrictWindow, compact_request};
@@ -59,8 +59,9 @@ use crate::engine::lease_test::promote_to_await_leader_lease;
use crate::engine::listener::{EventListener, FlushCancellationListener};
use crate::engine::open_test::new_dummy_fetcher;
use crate::engine::region_hook::{RegionHook, RegionHookRef};
use crate::error::Error;
use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList};
use crate::manifest::storage::{delta_file, gen_path, manifest_dir};
use crate::manifest::storage::{checkpoint_file, delta_file, gen_path, manifest_dir};
use crate::region::MitoRegionRef;
use crate::request::{BackgroundNotify, RegionEditRequest, WorkerRequest};
use crate::sst::file::FileMeta;
@@ -570,9 +571,10 @@ async fn test_stale_commit_on_deleted_delta_name_conflicts(
#[case] awaiting_leader_lease: bool,
) {
common_telemetry::init_default_ut_logging();
// The creation is version 0 and the flushes below are versions 1 and 2.
const VERSION: u64 = 3;
let (blocker, layer) = CheckpointTaskBlocker::block_delta_write(VERSION);
// The creation is version 0, the flushes below are versions 1 and 2, and the catchup that
// makes the region await its Leader lease commits version 3.
let blocked_version = if awaiting_leader_lease { 4 } else { 3 };
let (blocker, layer) = CheckpointTaskBlocker::block_delta_write(blocked_version);
let mut env = TestEnv::with_prefix("stale-manifest-commit")
.await
.with_mock_layer(layer);
@@ -626,14 +628,14 @@ async fn test_stale_commit_on_deleted_delta_name_conflicts(
new_holder.handle_request(region_id, open).await.unwrap();
let delta = gen_path(
&manifest_dir(&region_dir),
&delta_file(VERSION),
&delta_file(blocked_version),
CompressionType::Gzip,
);
{
let held = new_holder.get_region(region_id).unwrap();
let mut manager = held.manifest_ctx.manifest_manager.write().await;
assert_eq!(VERSION - 1, manager.last_version());
while manager.last_version() < VERSION || store.exists(&delta).await.unwrap() {
assert_eq!(blocked_version - 1, manager.last_version());
while manager.last_version() < blocked_version || store.exists(&delta).await.unwrap() {
manager
.update_with_verification(nop_action(), false, true, || false)
.await
@@ -666,7 +668,7 @@ async fn test_stale_commit_on_deleted_delta_name_conflicts(
wait_until(|| is_replaced(&old_leader, &region)).await;
let manager = region.manifest_ctx.manifest_manager.read().await;
assert_eq!(VERSION - 1, manager.last_version());
assert_eq!(blocked_version - 1, manager.last_version());
assert!(Arc::ptr_eq(&manifest, &manager.manifest()));
assert_eq!(checkpoint, manager.checkpointer().last_checkpoint_version());
assert!(!manager.checkpointer().is_doing_checkpoint());
@@ -771,6 +773,20 @@ async fn test_node_lease_fences_wal_and_renews_without_region_grants() {
engine.stop().await.unwrap();
}
/// A region without a WAL provider hands nothing over: the object store WAL, which has no region
/// for it, is not called, and the given entry id is the bound.
#[tokio::test]
async fn test_handoff_of_a_region_without_a_wal_provider_does_nothing() {
let log_store = new_log_store().await;
let wal = crate::wal::Wal::new(log_store.clone());
let bound = wal
.handoff(RegionId::new(1, 1), &Provider::Noop, 42)
.await
.unwrap();
assert_eq!(42, bound);
log_store.stop().await.unwrap();
}
async fn new_log_store() -> Arc<ObjectStoreLogStore> {
ObjectStoreLogStore::try_new(
ObjectStore::new(Memory::default()).unwrap(),
@@ -1221,6 +1237,285 @@ async fn test_fence_or_lease_during_catchup_reopen(#[case] lease: bool) {
}
}
/// A Leader lease that arrives while a catchup waits for its hand-off to become durable does not
/// promote the region the catchup reopened; the catchup promotes it when it ends.
#[tokio::test]
async fn test_leader_lease_during_handoff_does_not_promote() {
let mut env = TestEnv::with_prefix("lease-during-handoff").await;
let region_id = RegionId::new(1, 1);
let (engine, log_store, _, schema, deadline) = create_leased_region(&mut env, region_id).await;
// Rows left in the memtable make the catchup reopen the region.
put_range(&engine, region_id, &schema, 0, 3).await;
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
let old = engine.get_region(region_id).unwrap();
let reported_entry_id = old.version().flushed_entry_id;
log_store.hold_creates();
let catchup = {
let engine = engine.clone();
let request = RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
entry_id: Some(reported_entry_id),
..Default::default()
});
tokio::spawn(async move { engine.handle_request(region_id, request).await })
};
// The hand-off of the reopened region waits for the object that carries its record.
log_store.wait_for_parked_creates(1).await.unwrap();
assert!(!catchup.is_finished());
assert!(is_replaced(&engine, &old));
let region = engine.get_region(region_id).unwrap();
let promoted = engine
.set_region_role_with_lease(
region_id,
RegionRole::Leader,
Instant::now(),
deadline,
None,
)
.unwrap();
assert!(!promoted);
assert!(region.is_follower());
log_store.release_creates();
catchup.await.unwrap().unwrap();
assert!(region.is_writable());
assert_eq!(3, count_rows(&engine, region_id).await);
}
/// A catchup that makes a region writable first commits an empty edit as the version after the
/// manifest it read, as a Follower whose Leader deadline has passed.
#[tokio::test]
async fn test_catchup_commits_the_next_version_before_it_promotes() {
let mut env = TestEnv::with_prefix("catchup-commits-next-version").await;
let region_id = RegionId::new(1, 1);
let (engine, _log_store, _, _, deadline) = create_leased_region(&mut env, region_id).await;
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
engine.freeze_lease_clock(deadline);
let region = engine.get_region(region_id).unwrap();
let version = next_manifest_version(&region).await;
let files = region.version().ssts.levels()[0].files.len();
let last_checkpoint_version = || async {
let mut manager = region.manifest_ctx.manifest_manager.write().await;
manager.wait_for_pending_checkpoint().await;
manager.checkpointer().last_checkpoint_version()
};
let checkpoint = last_checkpoint_version().await;
let catchup = RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
..Default::default()
});
engine.handle_request(region_id, catchup).await.unwrap();
assert!(region.is_writable());
assert_eq!(version, next_manifest_version(&region).await - 1);
assert_eq!(files, region.version().ssts.levels()[0].files.len());
// Every commit checkpoints under this configuration, except the catchup's.
assert_eq!(checkpoint, last_checkpoint_version().await);
}
/// When another writer committed other content as the version the catchup's empty edit takes,
/// the commit fails with a retryable error and leaves the region a Follower that is not fenced,
/// so the next catchup reopens it from the newer manifest and promotes it.
#[tokio::test]
async fn test_catchup_commit_conflict_keeps_the_region_a_follower() {
let mut env = TestEnv::with_prefix("catchup-commit-conflict").await;
let region_id = RegionId::new(1, 1);
let (engine, _log_store, table_dir, _, _) = create_leased_region(&mut env, region_id).await;
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = next_manifest_version(&region).await;
let other = RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit {
timestamp_ms: Some(1),
..Default::default()
}));
let store = env.get_object_store().unwrap();
let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare);
publish_delta(&store, &region_dir, version, encode_delta(other).await).await;
let error = region.manifest_ctx.commit_catchup().await.err().unwrap();
assert!(error.retry_hint().is_retryable(), "{error:?}");
assert!(region.is_follower());
assert!(!region.manifest_ctx.is_reload_pending());
assert!(
!region
.manifest_ctx
.manifest_manager
.read()
.await
.is_stopped()
);
let catchup = RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
..Default::default()
});
engine.handle_request(region_id, catchup).await.unwrap();
assert!(is_replaced(&engine, &region));
let region = engine.get_region(region_id).unwrap();
assert!(region.is_writable());
assert_eq!(version + 2, next_manifest_version(&region).await);
}
/// A checkpoint that covers the version the catchup's empty edit took means a writer that already
/// cleaned that version name up, so the commit fails as a conflict and applies nothing.
#[tokio::test]
async fn test_catchup_commit_covered_by_a_checkpoint_conflicts() {
let mut env = TestEnv::with_prefix("catchup-commit-checkpointed").await;
let region_id = RegionId::new(1, 1);
let (engine, _log_store, table_dir, _, _) = create_leased_region(&mut env, region_id).await;
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = next_manifest_version(&region).await;
let store = env.get_object_store().unwrap();
let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare);
let checkpoint = gen_path(
&manifest_dir(&region_dir),
&checkpoint_file(version),
CompressionType::Gzip,
);
store.write(&checkpoint, Vec::<u8>::new()).await.unwrap();
let error = region.manifest_ctx.commit_catchup().await.err().unwrap();
assert!(
matches!(error, Error::ManifestVersionConflict { .. }),
"{error:?}"
);
assert_eq!(version, next_manifest_version(&region).await);
assert!(region.is_follower());
}
/// A region that a stop already marked, while the stop still waits to stop its manifest manager,
/// commits nothing for its catchup.
#[tokio::test]
async fn test_catchup_commit_of_a_stopping_region_commits_nothing() {
let mut env = TestEnv::with_prefix("catchup-commit-stopping").await;
let region_id = RegionId::new(1, 1);
let (engine, _log_store, _, _, _) = create_leased_region(&mut env, region_id).await;
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = next_manifest_version(&region).await;
region.manifest_ctx.mark_stopped_for_test();
let error = region.manifest_ctx.commit_catchup().await.err().unwrap();
assert!(matches!(error, Error::RegionStopped { .. }), "{error:?}");
assert_eq!(version, next_manifest_version(&region).await);
}
/// A catchup whose hand-off fails returns a retryable error before it replays or commits, and
/// leaves the region a Follower; the next catchup makes the region writable.
#[tokio::test]
async fn test_catchup_whose_handoff_fails_can_be_retried() {
let mut env = TestEnv::with_prefix("catchup-handoff-fails").await;
let region_id = RegionId::new(1, 1);
let (engine, log_store, _, _, _) = create_leased_region(&mut env, region_id).await;
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = next_manifest_version(&region).await;
let catchup = || {
RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
entry_id: Some(region.version().flushed_entry_id),
..Default::default()
})
};
log_store.fail_creates();
let error = engine
.handle_request(region_id, catchup())
.await
.unwrap_err();
assert!(
matches!(
error.as_any().downcast_ref::<Error>(),
Some(Error::HandoffWal { .. })
),
"{error:?}"
);
assert!(error.retry_hint().is_retryable(), "{error:?}");
assert!(region.is_follower());
assert_eq!(version, next_manifest_version(&region).await);
log_store.allow_creates();
engine.handle_request(region_id, catchup()).await.unwrap();
assert!(region.is_writable());
}
/// A region promoted directly while its catchup waits for the hand-off is no longer the Follower
/// the catchup commits for, so the catchup fails without committing.
#[tokio::test]
async fn test_catchup_of_a_region_promoted_meanwhile_commits_nothing() {
let mut env = TestEnv::with_prefix("catchup-promoted-meanwhile").await;
let region_id = RegionId::new(1, 1);
let (engine, log_store, _, _, _) = create_leased_region(&mut env, region_id).await;
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = next_manifest_version(&region).await;
log_store.hold_creates();
let catchup = {
let engine = engine.clone();
let request = RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
entry_id: Some(region.version().flushed_entry_id),
..Default::default()
});
tokio::spawn(async move { engine.handle_request(region_id, request).await })
};
log_store.wait_for_parked_creates(1).await.unwrap();
engine
.set_region_role(region_id, RegionRole::Leader)
.unwrap();
log_store.release_creates();
let error = catchup.await.unwrap().unwrap_err();
assert!(
matches!(
error.as_any().downcast_ref::<Error>(),
Some(Error::RegionState { .. })
),
"{error:?}"
);
assert_eq!(version, next_manifest_version(&region).await);
}
/// Without conditional publication the catchup commits nothing.
#[tokio::test]
async fn test_catchup_without_conditional_publication_commits_nothing() {
let mut env = TestEnv::with_prefix("catchup-unconditional").await;
let (engine, _log_store) = new_engine(&mut env).await;
let region_id = RegionId::new(1, 1);
create_region(&engine, region_id).await;
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = next_manifest_version(&region).await;
let catchup = RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
..Default::default()
});
engine.handle_request(region_id, catchup).await.unwrap();
assert!(region.is_writable());
assert_eq!(version, next_manifest_version(&region).await);
}
/// Fails every read of a manifest file.
struct FailedManifestReader;
@@ -1522,6 +1817,8 @@ struct BlockingManifestHook {
armed: AtomicBool,
entered: Notify,
release: Notify,
/// The version and actions of the call it held last.
held: Mutex<Option<(ManifestVersion, RegionMetaActionList)>>,
}
#[async_trait]
@@ -1529,16 +1826,152 @@ impl RegionHook for BlockingManifestHook {
async fn on_manifest_updated(
&self,
_region_id: RegionId,
_action_list: &RegionMetaActionList,
_manifest_version: ManifestVersion,
action_list: &RegionMetaActionList,
manifest_version: ManifestVersion,
) {
if self.armed.swap(false, Ordering::Relaxed) {
*self.held.lock().unwrap() = Some((manifest_version, action_list.clone()));
self.entered.notify_one();
self.release.notified().await;
}
}
}
/// The catchup's empty edit fires the manifest hook after the manifest lock is released and
/// before the region is promoted; a close while the hook runs leaves the region unpromoted.
#[rstest]
#[case::promoted(false)]
#[case::closed(true)]
#[tokio::test]
async fn test_catchup_commit_fires_the_hook_after_unlocking(#[case] close: bool) {
let mut env = TestEnv::with_prefix("catchup-commit-hook").await;
let hook = Arc::new(BlockingManifestHook::default());
let plugins = Plugins::new();
plugins.insert::<RegionHookRef>(hook.clone());
let engine = env
.create_engine_with_log_store_and_plugins(
MitoConfig::default(),
new_log_store().await,
plugins,
)
.await;
let region_id = RegionId::new(1, 1);
create_leased_region_on(&engine, region_id).await;
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
let region = engine.get_region(region_id).unwrap();
let version = next_manifest_version(&region).await;
hook.armed.store(true, Ordering::Relaxed);
let catchup = {
let engine = engine.clone();
let request = RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
..Default::default()
});
tokio::spawn(async move { engine.handle_request(region_id, request).await })
};
tokio::time::timeout(Duration::from_secs(10), hook.entered.notified())
.await
.unwrap();
let (held_version, actions) = hook.held.lock().unwrap().take().unwrap();
assert_eq!(version, held_version);
assert_eq!(
RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit::default())),
actions
);
// The hook runs without the manifest lock, before the promotion.
let manager = tokio::time::timeout(
Duration::from_secs(10),
region.manifest_ctx.manifest_manager.read(),
)
.await
.unwrap();
assert_eq!(version, manager.manifest().manifest_version);
drop(manager);
assert!(region.is_follower());
if close {
close_region(&engine, region_id).await;
}
hook.release.notify_one();
let caught_up = catchup.await.unwrap();
if close {
let error = caught_up.unwrap_err();
assert_eq!(StatusCode::RegionNotFound, error.status_code());
assert!(region.is_follower());
} else {
caught_up.unwrap();
assert!(region.is_writable());
}
}
/// A catchup again fires the hook of its commit once it holds no manifest lock, so a hook that
/// reads the manifest is not queued behind a writer that waits for the old instance's lock, and
/// no Leader lease promotes the replacement while the hook runs.
#[tokio::test]
async fn test_catchup_again_fires_the_hook_without_manifest_locks() {
let mut env = TestEnv::with_prefix("catchup-again-commit-hook").await;
let hook = Arc::new(BlockingManifestHook::default());
let plugins = Plugins::new();
plugins.insert::<RegionHookRef>(hook.clone());
let engine = env
.create_engine_with_log_store_and_plugins(
MitoConfig::default(),
new_log_store().await,
plugins,
)
.await;
let region_id = RegionId::new(1, 1);
let (_, _, deadline) = create_leased_region_on(&engine, region_id).await;
promote_to_await_leader_lease(&engine, region_id).await;
let old = engine.get_region(region_id).unwrap();
hook.armed.store(true, Ordering::Relaxed);
let catchup = {
let engine = engine.clone();
let request = RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
..Default::default()
});
tokio::spawn(async move { engine.handle_request(region_id, request).await })
};
let wait = Duration::from_secs(10);
tokio::time::timeout(wait, hook.entered.notified())
.await
.unwrap();
// While the hook runs, a writer of the old instance and a reader of the registered one get
// their locks.
drop(
tokio::time::timeout(wait, old.manifest_ctx.manifest_manager.write())
.await
.unwrap(),
);
let registered = engine.get_region(region_id).unwrap();
drop(
tokio::time::timeout(wait, registered.manifest_ctx.manifest_manager.read())
.await
.unwrap(),
);
// Nor does a Leader lease promote the registered replacement before its catchup ends.
let promoted = engine
.set_region_role_with_lease(
region_id,
RegionRole::Leader,
Instant::now(),
deadline,
None,
)
.unwrap();
assert!(!promoted);
assert!(registered.is_follower());
hook.release.notify_one();
catchup.await.unwrap().unwrap();
assert!(!Arc::ptr_eq(&old, &registered));
assert!(registered.is_writable());
}
fn edit_files(files_to_add: Vec<FileMeta>, files_to_remove: Vec<FileMeta>) -> RegionEdit {
RegionEdit {
files_to_add,
+17 -6
View File
@@ -62,6 +62,7 @@
//! | Enter staging | ❌ (no SST files) | ❌ (in memory) |
//! | Operations during staging | N/A | ❌ (in memory) |
//! | Async index build | ❌ (index files only) | ✅ Yes |
//! | Writable catchup ³ | ❌ (no SST files) | ✅ Yes |
//!
//! ¹ Remote compaction runs on a dedicated compactor node via `CompactionRegionOpener::open()`;
//! pass plugins via `OpenCompactionRegionRequest` to enable hooks there. `sst_infos` is
@@ -71,9 +72,14 @@
//! all staged manifest actions (including the SST file additions) into the live manifest.
//! The intermediate staging `RegionEdit` is staged in memory and does not
//! fire the hook — its file list is included in the promote notification.
//! ³ Only under conditional manifest publication: the catchup commits an empty `RegionEdit`
//! while the region is still a Follower.
//!
//! The following paths do **not** trigger any hook:
//! - Follower region sync / catchup (manifest read-only; followers don't author changes)
//! - Follower region sync, and a catchup that does not make the region writable (manifest
//! read-only; followers don't author changes). A catchup that makes the region writable
//! under conditional manifest publication commits an empty edit and fires
//! `on_manifest_updated` for it.
//! - GC / checkpoint / remap (internal bookkeeping, not logical state changes)
//!
//! An explicit region **drop** does fire lifecycle hooks — see
@@ -130,8 +136,9 @@
//! case: it acquires the lock, delegates to `update_locked`, and fires the
//! receipt in one go. The role-state backfill and the table-compaction publication
//! call `update_locked` directly under their own held guard; a replay of pending
//! tails makes the same write without the Leader lease check, and the end of
//! staging builds its receipt in `commit_staged_locked`.
//! tails makes the same write without the Leader lease check, the end of
//! staging builds its receipt in `commit_staged_locked`, and the empty edit of a
//! catchup builds its receipt in [`ManifestContext::commit_catchup`].
//!
//! Non-logical writes (GC, staging bookkeeping) call the manager's own methods
//! directly and intentionally do not fire the hook.
@@ -156,6 +163,7 @@
//! [`RegionManifestManager::update_with_verification`]: crate::manifest::manager::RegionManifestManager::update_with_verification
//! [`ManifestContext::update_locked`]: crate::region::ManifestContext::update_locked
//! [`ManifestContext::update_manifest`]: crate::region::ManifestContext::update_manifest
//! [`ManifestContext::commit_catchup`]: crate::region::ManifestContext::commit_catchup
use std::collections::HashSet;
use std::fmt::Debug;
@@ -349,13 +357,16 @@ pub trait RegionHook: Send + Sync + Debug {
/// (normal) manifest directory.
///
/// Fires for: flush, compaction, region edit, copy region, alter, truncate,
/// async index build, and apply-staging promote. Does **not** fire for actions
/// staged in memory (enter staging, operations during staging,
/// async index build, apply-staging promote, and a catchup that makes the
/// region writable under conditional manifest publication (an empty
/// `RegionEdit`, committed while the region is still a Follower). Does **not**
/// fire for actions staged in memory (enter staging, operations during staging,
/// the intermediate apply-staging edit) — those are suppressed because their
/// effects are accumulated and delivered in a single promote notification.
///
/// Does **not** fire for:
/// - Manifest reads / follower sync (no write)
/// - Follower sync and a catchup that does not make the region writable
/// (no write)
/// - GC / checkpoint (internal bookkeeping)
/// - Failed manifest updates
async fn on_manifest_updated(
+34 -16
View File
@@ -395,8 +395,15 @@ impl TestRegion {
}
async fn catchup(&self) {
self.catchup_with_entry_id(None).await;
}
/// Makes the region writable through a catchup that carries `entry_id` as the last entry id
/// its source reported.
async fn catchup_with_entry_id(&self, entry_id: Option<EntryId>) {
let catchup = RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
entry_id,
..Default::default()
});
self.engine
@@ -496,9 +503,10 @@ impl TestRegion {
}
/// Flushes this node's rows, records a listed tail of [REMOTE_NODE_ID] whose bound lies
/// above every entry of both nodes, loses that node's WAL and makes the region writable, so
/// the replay keeps failing. Returns the bound.
async fn start_lost_listed_tail(&self) -> EntryId {
/// above every entry of both nodes, loses that node's WAL and makes the region writable
/// through a catchup that carries `reported_entry_id`, so the replay keeps failing. Returns
/// the bound.
async fn start_lost_listed_tail(&self, reported_entry_id: Option<EntryId>) -> EntryId {
// Rows of the region stay readable after a reopen from a flushed entry id at the bound.
flush_region(&self.engine, self.region_id, None).await;
self.write_remote_rows(self.region_id, 6, 9).await;
@@ -508,7 +516,7 @@ impl TestRegion {
self.reopen_with_tails(vec![remote_tail(0, upto, UptoKind::Listed)])
.await;
self.delete_remote_objects().await;
self.catchup().await;
self.catchup_with_entry_id(reported_entry_id).await;
wait_until(|| self.listener.failed()).await;
upto
}
@@ -2378,7 +2386,7 @@ async fn test_discard_awaiting_leader_lease_succeeds_after_it() {
#[tokio::test]
async fn test_discard_listed_tail_raises_flushed_entry_id_to_its_bound() {
let region = TestRegion::new("tail-discard-listed", false, None).await;
let upto = region.start_lost_listed_tail().await;
let upto = region.start_lost_listed_tail(None).await;
assert_eq!(
1,
@@ -2723,17 +2731,19 @@ async fn test_conditional_discard_over_uncertain_replay_reloads_region() {
/// A discard raises the flushed entry id to a listed tail's bound. After a crash, the
/// object-store WAL, which by default does not accept missing history, checks history, so the
/// region opens only if this node's WAL durably holds history through the bound, as whoever
/// records the tail ensures.
/// records the tail ensures: a later write past the bound, or a catchup that carries the last
/// entry id the source reported and so hands the region over to this node's WAL.
#[rstest]
#[case::history_past_bound(true)]
#[case::history_below_bound(false)]
#[case::history_past_bound(BoundHistory::Written)]
#[case::history_below_bound(BoundHistory::Below)]
#[case::history_handed_over_past_bound(BoundHistory::HandedOver)]
#[tokio::test]
async fn test_discard_reopens_after_crash_with_history_past_bound(
#[case] history_past_bound: bool,
) {
async fn test_discard_reopens_after_crash_with_history_past_bound(#[case] history: BoundHistory) {
let region = TestRegion::new("tail-discard-crash", false, None).await;
let upto = region.start_lost_listed_tail().await;
if history_past_bound {
let reported_entry_id =
(history == BoundHistory::HandedOver).then(|| region.version().flushed_entry_id);
let upto = region.start_lost_listed_tail(reported_entry_id).await;
if history == BoundHistory::Written {
// Moves this node's next entry id past the bound and makes an entry there durable.
let provider = region
.engine
@@ -2756,14 +2766,22 @@ async fn test_discard_reopens_after_crash_with_history_past_bound(
let opened = region.crash_and_open().await;
if history_past_bound {
opened.unwrap();
} else {
if history == BoundHistory::Below {
let error = format!("{:?}", opened.unwrap_err());
assert!(error.contains("does not hold the history"), "{error}");
} else {
opened.unwrap();
}
}
/// How this node's WAL comes to hold history past a tail's bound before the tail is discarded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BoundHistory {
Below,
Written,
HandedOver,
}
#[tokio::test]
async fn test_region_statistic_reports_pending_tails() {
let region = TestRegion::new("tail-replay-statistic", false, None).await;
+11 -1
View File
@@ -567,6 +567,14 @@ pub enum Error {
source: BoxedError,
},
#[snafu(display("Failed to hand the WAL of region {} over to this node", region_id))]
HandoffWal {
region_id: RegionId,
#[snafu(implicit)]
location: Location,
source: BoxedError,
},
#[snafu(display("Failed to resolve the WAL provider, region_id: {}", region_id))]
ResolveWalProvider {
region_id: RegionId,
@@ -1701,7 +1709,8 @@ impl ErrorExt for Error {
| DeleteWal { source, .. }
| WaitWalDurable { source, .. }
| ResolveWalProvider { source, .. }
| CheckWalHistory { source, .. } => source.status_code(),
| CheckWalHistory { source, .. }
| HandoffWal { source, .. } => source.status_code(),
CompressObject { .. }
| DecompressObject { .. }
| SerdeJson { .. }
@@ -1947,6 +1956,7 @@ impl ErrorExt for Error {
| WaitWalDurable { source, .. }
| ResolveWalProvider { source, .. }
| CheckWalHistory { source, .. }
| HandoffWal { source, .. }
| FetchManifests { source, .. }
| External { source, .. } => source.retry_hint(),
+58 -4
View File
@@ -59,12 +59,12 @@ use crate::engine::region_hook::{PendingManifestHook, RegionHookRef};
use crate::error::{
EndStagingSnafu, Error, FlushableRegionStateSnafu, InvalidPartitionExprSnafu,
InvalidRequestSnafu, RegionBusySnafu, RegionLeaseExpiredSnafu, RegionLeaseNotReceivedSnafu,
RegionNotFoundSnafu, RegionStateSnafu, RegionTruncatedSnafu, Result, UnexpectedSnafu,
UpdateManifestSnafu,
RegionNotFoundSnafu, RegionStateSnafu, RegionStoppedSnafu, RegionTruncatedSnafu, Result,
UnexpectedSnafu, UpdateManifestSnafu,
};
use crate::lease::{Deadline, NodeLease, lease_nanos};
use crate::manifest::action::{
PendingTail, RegionChange, RegionManifest, RegionMetaAction, RegionMetaActionList,
PendingTail, RegionChange, RegionEdit, RegionManifest, RegionMetaAction, RegionMetaActionList,
};
use crate::manifest::manager::RegionManifestManager;
use crate::metrics::manifest_size::RegionManifestSizeMetric;
@@ -768,7 +768,7 @@ impl MitoRegion {
};
// The checkpoint task is taken under the lock after the state change, so every commit
// that could start a checkpoint has registered it: a follower takes no commit, and a
// that could start a checkpoint has registered it: a follower's commit starts none, and a
// commit of a downgrading leader starts no checkpoint. The wait holds no lock, so the
// worker and other users of the manifest are not blocked while the checkpoint finishes.
if wait_for_checkpoint {
@@ -1928,6 +1928,54 @@ impl ManifestContext {
Ok(TailPublication::Committed(result?))
}
/// Commits the empty edit a catchup makes before the region becomes writable, as the version
/// after the manifest the region holds when it commits. A writer that committed other content
/// at that version conflicts with it. Two catchups that start from the same manifest version
/// commit the same content, so they are not told apart. Only a manifest published
/// conditionally detects a conflict, so without conditional publication it commits nothing.
///
/// The region commits as a Follower, which needs no valid Leader deadline, so the commit
/// skips the deadline check. Like a commit of a region that awaits its Leader lease, it
/// starts no checkpoint and applies only if no checkpoint covers its version. A conflict
/// leaves the region and its manifest manager as they are: the next catchup reopens the
/// region from the newer manifest. A stopped region commits nothing.
///
/// Returns the receipt of the manifest hook, which the caller fires once it holds no manifest
/// lock, or None if it committed nothing.
pub(crate) async fn commit_catchup(&self) -> Result<Option<PendingManifestHook>> {
let mut manager = self.manifest_manager.write().await;
if !manager.is_conditional_publication() {
return Ok(None);
}
let region_id = manager.manifest().metadata.region_id;
let state = self.state.load();
ensure!(
state == RegionRoleState::Follower,
RegionStateSnafu {
region_id,
state,
expect: RegionRoleState::Follower,
}
);
ensure!(!self.is_reload_pending(), RegionBusySnafu { region_id });
// A stop marks the region before it waits for this lock to stop the manager.
ensure!(!self.is_stopped(), RegionStoppedSnafu { region_id });
let action_list =
RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit::default()));
let action_list_for_hook = self.hook.as_ref().map(|_| action_list.clone());
let version = manager
.update_with_verification(action_list, false, false, || true)
.await?;
let pending = PendingManifestHook::new(
region_id,
action_list_for_hook,
version,
self.hook.clone(),
false,
);
Ok(Some(pending))
}
/// Performs a manifest write under a caller-held write lock and returns a
/// [`PendingManifestHook`] to [`fire`](PendingManifestHook::fire) after
/// dropping the lock. It is the checked entry of the shared write
@@ -2331,6 +2379,12 @@ impl ManifestContext {
assert!(self.awaits_leader_lease());
}
/// Marks the region stopped as [MitoRegion::stop] does before it stops the manifest manager.
#[cfg(test)]
pub(crate) fn mark_stopped_for_test(&self) {
self.promotion_fence.lock().unwrap().stopped = true;
}
/// Promotes the region unless it waits for a reload or was stopped. The caller holds the fence
/// lock.
fn promote_unless_reload_pending(
+31 -6
View File
@@ -32,6 +32,8 @@ pub struct RegionCatchupTask<S> {
expected_last_entry_id: Option<u64>,
/// The largest entry id the region acknowledged on this node.
acknowledged_entry_id: u64,
/// Whether the catchup makes the region writable on this node.
set_writable: bool,
allow_stale_entries: bool,
wal: Wal<S>,
}
@@ -44,11 +46,18 @@ impl<S: LogStore> RegionCatchupTask<S> {
replay_checkpoint_entry_id: None,
expected_last_entry_id: None,
acknowledged_entry_id: 0,
set_writable: false,
allow_stale_entries,
wal,
}
}
/// Sets whether the catchup makes the region writable on this node.
pub(crate) fn with_set_writable(mut self, set_writable: bool) -> Self {
self.set_writable = set_writable;
self
}
/// Sets the expected last entry id.
pub(crate) fn with_expected_last_entry_id(
mut self,
@@ -99,12 +108,28 @@ impl<S: LogStore> RegionCatchupTask<S> {
"Trying to replay memtable for region: {region_id}, provider: {:?}, replay from entry id: {replay_from_entry_id}, flushed entry id: {flushed_entry_id}",
self.region.provider
);
check_wal_history(
&self.wal,
&self.region.provider,
&self.region.version_control.current().version,
)
.await?;
let version = self.region.version_control.current().version;
// A catchup that makes the region writable and carries the entry id its source
// reported hands the region over to this node's log store: from now on the region takes
// ids above every id the source, the manifest or a pending tail used, so a later rise of
// its flushed entry id passes none of its new entries, and this node's log store holds
// its history from here on. A catchup that still has to replay entries above where its
// replay starts hands nothing over, so if it cannot reach them it leaves nothing behind.
if self.set_writable
&& let Some(reported_entry_id) = self.expected_last_entry_id
&& reported_entry_id <= replay_from_entry_id
&& !version.options.skip_wal
{
let entry_id = version
.pending_tails
.iter()
.map(|tail| tail.upto)
.fold(reported_entry_id.max(version.flushed_entry_id), u64::max);
self.wal
.handoff(region_id, &self.region.provider, entry_id)
.await?;
}
check_wal_history(&self.wal, &self.region.provider, &version).await?;
let timer = Instant::now();
// The replay reads only what the log store has made durable.
self.wal
+19 -1
View File
@@ -40,7 +40,7 @@ use store_api::storage::RegionId;
use tokio::sync::watch;
use crate::error::{
BuildEntrySnafu, CheckWalHistorySnafu, DeleteWalSnafu, ReadNodeWalSnafu,
BuildEntrySnafu, CheckWalHistorySnafu, DeleteWalSnafu, HandoffWalSnafu, ReadNodeWalSnafu,
RemoteWalUnsupportedSnafu, ResolveWalProviderSnafu, Result, WaitWalDurableSnafu, WriteWalSnafu,
};
use crate::wal::entry_reader::{LogStoreEntryReader, WalEntryReader, decode_raw_entry};
@@ -221,6 +221,24 @@ impl<S: LogStore> Wal<S> {
.context(CheckWalHistorySnafu { region_id })
}
/// Hands the region over to the log store before it becomes writable on
/// this node and returns the bound, see [LogStore::handoff].
pub(crate) async fn handoff(
&self,
region_id: RegionId,
provider: &Provider,
entry_id: EntryId,
) -> Result<EntryId> {
if let Provider::Noop = provider {
return Ok(entry_id);
}
self.store
.handoff(provider, entry_id)
.await
.map_err(BoxedError::new)
.context(HandoffWalSnafu { region_id })
}
/// Records that the WAL history of the region starts in the log store,
/// as it does for a region created on it.
pub(crate) fn start_region_history(
+46 -9
View File
@@ -114,11 +114,21 @@ impl<S: LogStore> RegionWorkerLoop<S> {
let mut task = RegionCatchupTask::new(region.clone(), wal, allow_stale_entries)
.with_entry_receiver(entry_receiver)
.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(last_entry_id);
match task.run().await {
Ok(_) => {
// Under conditional manifest publication, the region becomes writable only once its
// catchup committed the next manifest version.
let result = match task.run().await {
Ok(_) if request.set_writable => region.manifest_ctx.commit_catchup().await,
result => result.map(|()| None),
};
match result {
Ok(hook) => {
if let Some(hook) = hook {
hook.fire().await;
}
let promoted = if !request.set_writable {
region.manifest_ctx.end_catchup();
false
@@ -150,9 +160,11 @@ impl<S: LogStore> RegionWorkerLoop<S> {
/// region stays registered, demoted unless it is in a transient leader state, while a
/// replacement opened from its manifest replays the WAL outside the worker;
/// [Self::handle_caught_up_again] registers the replacement only if its replay succeeded (on
/// a remote WAL it must reach the entries the region acknowledged) and the region took no
/// write and made no commit meanwhile. Otherwise the region keeps its memtable, so a later
/// Leader lease can promote it; one that waits for a reload is reloaded instead.
/// a remote WAL it must reach the entries the region acknowledged), the region took no
/// 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.
async fn catch_up_again(
&mut self,
region: MitoRegionRef,
@@ -186,6 +198,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
RegionCatchupTask::new(replacement.clone(), wal, config.allow_stale_entries)
.with_entry_receiver(entry_receiver)
.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()
@@ -206,10 +219,10 @@ 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, or
/// committed or took a write since the catchup began. 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.
/// 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
/// with its memtable; one that waits for a reload is reloaded instead.
pub(crate) async fn handle_caught_up_again(
&mut self,
region_id: RegionId,
@@ -237,9 +250,22 @@ impl<S: LogStore> RegionWorkerLoop<S> {
// meanwhile makes it writable again, and the replay misses the writes it then
// acknowledges, with or without the WAL.
&& old.version_control.current().last_sequence == last_sequence;
let mut catchup_hook = None;
let replacement = match result {
_ if !registered => Err(error::RegionNotFoundSnafu { region_id }.build()),
Ok(_) if !unchanged => Err(error::RegionBusySnafu { region_id }.build()),
// The replacement's own commit guards pass, as it is unregistered; the checks of the
// old instance above do the guarding. The old instance's commits wait on the read
// guard held here, so once the commit succeeds nothing below can refuse the swap.
// This awaits one conditional PUT and one LIST on the worker, under that guard: the
// 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| {
catchup_hook = hook;
replacement
})
}
result => result,
};
let replacement = match replacement {
@@ -263,8 +289,19 @@ impl<S: LogStore> RegionWorkerLoop<S> {
// Requests waiting for the old instance are rejected as a close rejects them.
self.fail_region_stalled_requests_as_not_found(&region_id);
self.reject_region_requests_as_not_found(region_id);
// Leases apply through the shared region map, so a writable catchup keeps them from
// promoting the registered replacement before the promotion below (including while its
// hook runs); that promotion ends this catchup.
if set_writable {
let begun = replacement.manifest_ctx.begin_catchup(region_id);
debug_assert_eq!(begun, Some(false));
}
self.register_region(replacement.clone());
drop(manager);
// A hook may read the manifest of the region, so it fires once no manifest lock is held.
if let Some(hook) = catchup_hook {
hook.fire().await;
}
if let Some(state) = &self.series_index_task_state {
state.wake();
}
+25
View File
@@ -193,6 +193,31 @@ pub trait LogStore: Send + Sync + 'static + std::fmt::Debug {
Ok(())
}
/// Hands the provider's region over to this log store before the region
/// becomes writable on it, and returns the bound: an id at or above
/// `entry_id` and every id of the region the log store still holds or
/// assigned since it opened. Ids it assigned before and no longer holds
/// need not be covered; they stay below every id it assigns later.
///
/// Once it returns:
/// - every id the log store assigns to the region is above the bound,
/// also after a restart;
/// - no entry of the region is obsolete that was not before;
/// - [`check_region_history`](Self::check_region_history) accepts the
/// region, as [`start_region_history`](Self::start_region_history)
/// makes it.
///
/// The default does nothing and returns `entry_id`. It suits a log store
/// that never assigns a region an id at or below one already used for the
/// region, wherever it was used, and that accepts every history.
async fn handoff(
&self,
_provider: &Provider,
entry_id: EntryId,
) -> Result<EntryId, Self::Error> {
Ok(entry_id)
}
/// 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.
///