From 085170091169acd91a78cd36b50fc1443129b60f Mon Sep 17 00:00:00 2001 From: Chenglong Zheng Date: Wed, 25 Nov 2026 06:46:52 +0000 Subject: [PATCH] feat(meta): add object-store authority state machine and single writer (#10588) * feat: add object-store authority state machine and single writer Signed-off-by: hahaha * fix: validate conditional resignations and retry renewal reads Signed-off-by: hahaha * refactor: clarify object-store authority naming Signed-off-by: hahaha --------- Signed-off-by: hahaha --- src/common/meta/Cargo.toml | 1 + src/common/meta/src/election/object_store.rs | 7 +- .../src/election/object_store/authority.rs | 489 +++++++ .../election/object_store/authority/tests.rs | 1283 +++++++++++++++++ .../election/object_store/authority/writer.rs | 596 ++++++++ .../meta/src/election/object_store/tests.rs | 200 ++- src/common/meta/src/error.rs | 54 +- 7 files changed, 2610 insertions(+), 20 deletions(-) create mode 100644 src/common/meta/src/election/object_store/authority.rs create mode 100644 src/common/meta/src/election/object_store/authority/tests.rs create mode 100644 src/common/meta/src/election/object_store/authority/writer.rs diff --git a/src/common/meta/Cargo.toml b/src/common/meta/Cargo.toml index 09b7dd09d16..f2b566a59eb 100644 --- a/src/common/meta/Cargo.toml +++ b/src/common/meta/Cargo.toml @@ -106,3 +106,4 @@ common-test-util.workspace = true common-wal = { workspace = true, features = ["testing"] } datatypes.workspace = true object-store = { workspace = true, features = ["testing"] } +tokio = { workspace = true, features = ["test-util"] } diff --git a/src/common/meta/src/election/object_store.rs b/src/common/meta/src/election/object_store.rs index 9c5b22dc591..6f8d87c991b 100644 --- a/src/common/meta/src/election/object_store.rs +++ b/src/common/meta/src/election/object_store.rs @@ -12,13 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Authority Head v1 codec and non-retrying conditional object storage. +//! Object-store Authority election, Head v1 codec and conditional storage. +mod authority; mod head; mod probe; mod store; #[cfg(test)] mod tests; +pub use authority::{ + Authority, AuthorityMutation, AuthorityPrecondition, AuthorityStatus, FencingToken, + TakeoverOutcome, +}; pub use head::{AuthorityHead, HEAD_FORMAT_VERSION, NodeIdentity}; pub use store::{AuthorityState, HeadStore}; diff --git a/src/common/meta/src/election/object_store/authority.rs b/src/common/meta/src/election/object_store/authority.rs new file mode 100644 index 00000000000..450be6c41ae --- /dev/null +++ b/src/common/meta/src/election/object_store/authority.rs @@ -0,0 +1,489 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Object-store Authority with one writer per node and monotonic local leases. + +#[cfg(test)] +mod tests; +mod writer; + +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use chrono::Utc; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::task::JoinHandle; +use tokio::time::{Instant, sleep_until}; + +use crate::election::object_store::authority::writer::{Request, Resignation, Writer}; +use crate::election::object_store::{AuthorityHead, AuthorityState, HeadStore, NodeIdentity}; +use crate::error::{self, Error, Result}; + +const LEASE: Duration = Duration::from_secs(10); +const RENEW_INTERVAL: Duration = Duration::from_secs(5); +const CLOCK_GUARD: Duration = Duration::from_secs(2); +const GET_TIMEOUT: Duration = Duration::from_millis(500); +const QUEUE_CAPACITY: usize = 32; + +/// A token authorizes mutations only in its original local term. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FencingToken { + epoch: u64, +} + +impl FencingToken { + /// The logical epoch won by the takeover. + pub fn epoch(&self) -> u64 { + self.epoch + } +} + +/// Result of one takeover attempt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TakeoverOutcome { + /// The Head PUT applied and the node can lead in this term. + Acquired(FencingToken), + /// The Head PUT applied after local eligibility was lost. + AppliedButInactive, + /// The observed Head still has a live owner. + NotEligible, +} + +/// The local lifecycle of the Authority writer. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum AuthorityStatus { + /// Has no active local term and can attempt takeover. + #[default] + Follower, + /// Holds a local term that can admit writes before its deadline. + Leader { epoch: u64, deadline: Instant }, + /// Stops admitting new writes for the term while resignation is resolved. + Resigning { epoch: u64, deadline: Instant }, + /// The official Head is missing and requires operator recovery. + RecoveryRequired, + /// Rejects new operations after shutdown begins. + Closed, +} + +impl AuthorityStatus { + fn term(self) -> Option<(u64, Instant)> { + match self { + Self::Leader { epoch, deadline } | Self::Resigning { epoch, deadline } => { + Some((epoch, deadline)) + } + _ => None, + } + } +} + +/// Additional condition on the Head for a fenced mutation. +#[derive(Debug, Default, Clone, Copy)] +pub enum AuthorityPrecondition { + /// Accepts any current Head write sequence. + #[default] + Any, + /// Requires an exact match with the current Head write sequence. + WriteSeq(u64), +} + +impl AuthorityPrecondition { + fn check(self, head: &AuthorityHead) -> Result<()> { + let actual = head.write_seq(); + if let Self::WriteSeq(expected) = self + && actual != expected + { + return error::AuthorityWriteSeqMismatchSnafu { expected, actual }.fail(); + } + Ok(()) + } +} + +/// Fenced Head updates supported by Head v1. +#[derive(Debug, Clone, Copy)] +pub enum AuthorityMutation { + /// Renews the current lease while preserving the owner and epoch. + Renew, + /// Clears the current owner while preserving the epoch. + Resign, +} + +/// Node-local Authority. Share one instance and its writer across callers. +pub struct Authority { + inner: Arc, + request_tx: mpsc::Sender, + writer_task: tokio::sync::Mutex>>, +} + +impl Authority { + /// Starts the writer with the process identity generated once at startup. + pub fn new(store: Arc, identity: NodeIdentity) -> Self { + Self::start( + store, + identity, + || { + let now = Utc::now(); + i128::from(now.timestamp()) * 1_000_000_000 + + i128::from(now.timestamp_subsec_nanos()) + }, + QUEUE_CAPACITY, + common_runtime::spawn_global, + ) + } + + fn start( + store: Arc, + identity: NodeIdentity, + wall_now_ns: impl Fn() -> i128 + Send + Sync + 'static, + capacity: usize, + spawn: impl FnOnce(Pin + Send>>) -> JoinHandle<()>, + ) -> Self { + let (status_tx, _) = watch::channel(AuthorityStatus::Follower); + let inner = Arc::new(Inner { + store, + identity, + wall_now_ns: Box::new(wall_now_ns), + control: Mutex::default(), + status_tx, + }); + let (request_tx, request_rx) = mpsc::channel(capacity); + let writer_task = spawn(Box::pin(Writer::new(inner.clone(), request_rx).run())); + Self { + inner, + request_tx, + writer_task: tokio::sync::Mutex::new(Some(writer_task)), + } + } + + /// Reads a coherent Head and its complete metadata in a single storage operation. + pub async fn head(&self) -> Result { + self.inner.read(Admission::Read, None).await + } + + /// Returns the local state, accounting for any elapsed monotonic deadline. + pub fn status(&self) -> AuthorityStatus { + self.inner.update(|control, _| control.status) + } + + /// Attempts a single conditional takeover. + pub async fn takeover(&self) -> Result { + let (response, result) = oneshot::channel(); + self.submit(Admission::Takeover, Request::Takeover(response)) + .await?; + result.await.unwrap_or_else(|_| Err(closed())) + } + + /// Requests a fenced Head update. Success confirms its PUT. + pub async fn mutate( + &self, + token: &FencingToken, + precondition: AuthorityPrecondition, + mutation: AuthorityMutation, + ) -> Result<()> { + let epoch = token.epoch; + let (response, result) = oneshot::channel(); + match (mutation, precondition) { + (AuthorityMutation::Resign, AuthorityPrecondition::Any) => { + self.inner.update(|control, _| { + Admission::Renew(epoch).check(control.status)?; + let AuthorityStatus::Leader { deadline, .. } = control.status else { + return Err(rejected("term is inactive")); + }; + control.status = AuthorityStatus::Resigning { epoch, deadline }; + control.resignation = Some(Resignation { epoch, response }); + Ok(()) + })?; + } + (mutation, precondition) => { + let admission = match mutation { + AuthorityMutation::Renew => Admission::Renew(epoch), + AuthorityMutation::Resign => Admission::ConditionalResign(epoch), + }; + self.submit( + admission, + Request::Mutate { + epoch, + mutation, + precondition, + response, + }, + ) + .await?; + } + } + result.await.unwrap_or_else(|_| Err(closed())) + } + + /// Stops term admission and attempts to clear the owner before the frozen deadline. + pub async fn resign(&self, token: &FencingToken) -> Result<()> { + self.mutate(token, AuthorityPrecondition::Any, AuthorityMutation::Resign) + .await + } + + /// Stops the local term, cancels I/O waits and joins the writer. + pub async fn shutdown(&self) { + self.inner.close(); + let mut writer_task = self.writer_task.lock().await; + if let Some(task) = writer_task.as_mut() + && let Err(error) = task.await + { + common_telemetry::warn!("Authority writer exited with error: {error}"); + } + writer_task.take(); + } + + async fn submit(&self, admission: Admission, request: Request) -> Result<()> { + admission.check(self.status())?; + tokio::select! { + permit = self.request_tx.reserve() => { + let permit = permit.map_err(|_| closed())?; + self.inner.update(|control, _| { + admission.check(control.status)?; + permit.send(request); + Ok(()) + }) + } + _ = self.inner.wait_until(|status| admission.check(status).is_err()) => { + admission.check(self.status()).and_then(|()| Err(rejected("admission changed"))) + } + } + } +} + +impl Drop for Authority { + fn drop(&mut self) { + self.inner.close(); + } +} + +#[derive(Clone, Copy)] +enum Admission { + Read, + Takeover, + Renew(u64), + ConditionalResign(u64), + Resign(u64), +} + +impl Admission { + fn check(self, status: AuthorityStatus) -> Result<()> { + match (self, status) { + (_, AuthorityStatus::Closed) => Err(closed()), + (_, AuthorityStatus::RecoveryRequired) => error::AuthorityRecoveryRequiredSnafu.fail(), + (Self::Read, _) | (Self::Takeover, AuthorityStatus::Follower) => Ok(()), + ( + Self::Renew(expected) | Self::ConditionalResign(expected), + AuthorityStatus::Leader { epoch, .. }, + ) + | (Self::Resign(expected), AuthorityStatus::Resigning { epoch, .. }) + if expected == epoch => + { + Ok(()) + } + _ => Err(rejected( + "local state or fencing token does not authorize the operation", + )), + } + } +} + +#[derive(Default)] +struct Control { + status: AuthorityStatus, + resignation: Option, + snapshot: Option, +} + +impl Control { + fn expire(&mut self, now: Instant) { + if self + .status + .term() + .is_some_and(|(_, deadline)| now >= deadline) + { + self.status = AuthorityStatus::Follower; + } + } + + fn retire(&mut self, epoch: u64) { + if self + .status + .term() + .is_some_and(|(current, _)| current == epoch) + { + self.status = AuthorityStatus::Follower; + } + } +} + +/// A confirmed PUT no longer has usable Metadata. Its base is retained solely +/// to rule out a stale conditional version when the next snapshot arrives. +enum SnapshotFloor { + Observed(AuthorityState), + Applied { + head: AuthorityHead, + base: AuthorityState, + }, +} + +impl SnapshotFloor { + fn head(&self) -> &AuthorityHead { + match self { + Self::Observed(state) => state.head(), + Self::Applied { head, .. } => head, + } + } + + fn validate(&self, store: &HeadStore, state: &AuthorityState) -> Result<()> { + let head = state.head(); + let floor = self.head(); + if head.epoch() < floor.epoch() + || head.write_seq() < floor.write_seq() + || (head.write_seq() == floor.write_seq() && head != floor) + { + return Err(invalid_snapshot( + "Head moved behind an observed or applied write", + )); + } + let (metadata, expect_same_version) = match self { + Self::Observed(previous) => { + (previous.metadata(), head.write_seq() == floor.write_seq()) + } + Self::Applied { base, .. } => (base.metadata(), false), + }; + if store.same_version(metadata, state.metadata())? != expect_same_version { + return Err(invalid_snapshot( + "conditional version disagrees with Head write sequence", + )); + } + Ok(()) + } +} + +struct Inner { + store: Arc, + identity: NodeIdentity, + wall_now_ns: Box i128 + Send + Sync>, + control: Mutex, + status_tx: watch::Sender, +} + +impl Inner { + /// Runs the short state transitions and PUT authorization under the same lock. + fn update(&self, f: impl FnOnce(&mut Control, Instant) -> T) -> T { + let mut control = self.control.lock().unwrap_or_else(PoisonError::into_inner); + let before = control.status; + let now = Instant::now(); + control.expire(now); + let result = f(&mut control, now); + if control.status != before { + self.status_tx.send_replace(control.status); + } + result + } + + async fn wait_until(&self, predicate: impl Fn(AuthorityStatus) -> bool) { + let mut status = self.status_tx.subscribe(); + let _ = status.wait_for(|status| predicate(*status)).await; + } + + fn close(&self) { + self.update(|control, _| control.status = AuthorityStatus::Closed); + } + + async fn read( + &self, + admission: Admission, + deadline: Option, + ) -> Result { + self.update(|control, _| admission.check(control.status))?; + let now = Instant::now(); + let stop = deadline.map_or(now + GET_TIMEOUT, |end| end.min(now + GET_TIMEOUT)); + if now >= stop { + return Err(timeout("read")); + } + let result = tokio::select! { + biased; + _ = self.wait_until(|status| admission.check(status).is_err()) => { + return self.update(|control, _| { + admission.check(control.status)?; + Err(rejected("read admission changed")) + }); + } + result = self.store.read_head() => result, + _ = sleep_until(stop) => return Err(timeout("read")), + }; + if matches!(result, Err(Error::AuthorityMissing { .. })) { + self.update(|control, _| { + if control.status != AuthorityStatus::Closed { + control.status = AuthorityStatus::RecoveryRequired; + } + }); + } + let state = result?; + if Instant::now() >= stop { + return Err(timeout("read")); + } + self.observe(admission, &state)?; + Ok(state) + } + + fn observe(&self, admission: Admission, state: &AuthorityState) -> Result<()> { + self.update(|control, _| { + let head = state.head(); + if let Some(floor) = &control.snapshot { + // A concurrent reader can observe a newer Head while this response + // is in flight. Historical evidence is usable for readback, but + // it cannot replace the floor or supply a new CAS condition. + if matches!(admission, Admission::Read) + && head.write_seq() < floor.head().write_seq() + && head.epoch() <= floor.head().epoch() + { + return Ok(()); + } + floor.validate(&self.store, state)?; + } + if let Some((epoch, _)) = control.status.term() + && head.epoch() >= epoch + && (head.epoch() != epoch || head.owner.as_ref() != Some(&self.identity)) + { + control.retire(epoch); + } + control.snapshot = Some(SnapshotFloor::Observed(state.clone())); + Ok(()) + }) + } + + fn diagnostic_deadline(&self) -> u64 { + let ns = (self.wall_now_ns)().saturating_add(LEASE.as_nanos() as i128); + u64::try_from(ns / 1_000_000).unwrap_or(if ns < 0 { 0 } else { u64::MAX }) + } +} + +fn closed() -> Error { + error::AuthorityClosedSnafu.build() +} + +fn rejected(reason: &'static str) -> Error { + error::AuthorityRejectedSnafu { reason }.build() +} + +fn invalid_snapshot(reason: &'static str) -> Error { + error::AuthorityMetadataSnafu { reason }.build() +} + +fn timeout(operation: &'static str) -> Error { + error::AuthorityTimeoutSnafu { operation }.build() +} diff --git a/src/common/meta/src/election/object_store/authority/tests.rs b/src/common/meta/src/election/object_store/authority/tests.rs new file mode 100644 index 00000000000..90aa9ac15a2 --- /dev/null +++ b/src/common/meta/src/election/object_store/authority/tests.rs @@ -0,0 +1,1283 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::future::Future; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::task::Poll; + +use common_error::ext::{ErrorExt, RetryHint}; +use common_error::status_code::StatusCode; +use object_store::{Error as StorageError, ErrorKind}; +use tokio::time::advance; + +use super::*; +use crate::election::object_store::tests::{Backend, Call, store}; + +const CAPACITY: usize = 2; + +struct Fixture { + backend: Backend, + store: Arc, + wall_ns: Arc, +} + +impl Fixture { + async fn new() -> Self { + let backend = Backend::default(); + let store = Arc::new(store(&backend)); + store.create_initial_head().await.unwrap(); + let fixture = Self { + backend, + store, + wall_ns: Arc::new(AtomicI64::new(0)), + }; + fixture.clear_calls(); + fixture + } + + fn node(&self, addr: &str) -> Arc { + let wall = self.wall_ns.clone(); + Arc::new(Authority::start( + Arc::new(store(&self.backend)), + NodeIdentity::new(addr.into()), + move || i128::from(wall.load(Ordering::Relaxed)), + CAPACITY, + tokio::spawn, + )) + } + + fn clear_calls(&self) { + self.backend.data.lock().unwrap().calls.clear(); + } + + fn puts(&self) -> Vec { + self.backend + .data + .lock() + .unwrap() + .calls + .iter() + .filter_map(|call| match call { + Call::Get(_) => None, + Call::Put(head) => Some(head.clone()), + }) + .collect() + } + + fn order(&self) -> Vec<&'static str> { + self.backend + .data + .lock() + .unwrap() + .calls + .iter() + .map(|call| match call { + Call::Get(_) => "GET", + Call::Put(_) => "PUT", + }) + .collect() + } + + async fn expire_stored_lease(&self, extra_ns: i64) { + let head = self.store.read_head().await.unwrap(); + let modified = head + .metadata() + .last_modified() + .unwrap() + .into_inner() + .as_nanosecond(); + let at = modified + (LEASE + CLOCK_GUARD).as_nanos() as i128; + self.wall_ns + .store(i64::try_from(at).unwrap() + extra_ns, Ordering::Relaxed); + } + + async fn replace_remotely(&self, update: impl FnOnce(AuthorityHead) -> AuthorityHead) { + let base = self.store.read_head().await.unwrap(); + let head = update(base.head().clone()); + self.store.replace_head(&base, &head).await.unwrap(); + } +} + +async fn acquire(node: &Authority) -> FencingToken { + let TakeoverOutcome::Acquired(token) = node.takeover().await.unwrap() else { + panic!("Head must be acquirable"); + }; + token +} + +async fn renew( + node: &Authority, + token: FencingToken, + precondition: AuthorityPrecondition, +) -> Result<()> { + node.mutate(&token, precondition, AuthorityMutation::Renew) + .await +} + +fn takeover_task(node: &Arc) -> JoinHandle> { + let node = node.clone(); + tokio::spawn(async move { node.takeover().await }) +} + +fn renew_task(node: &Arc, token: FencingToken) -> JoinHandle> { + let node = node.clone(); + tokio::spawn(async move { renew(&node, token, AuthorityPrecondition::Any).await }) +} + +fn resign_task(node: &Arc, token: FencingToken) -> JoinHandle> { + let node = node.clone(); + tokio::spawn(async move { node.resign(&token).await }) +} + +fn assert_rejected(result: Result) { + assert!( + matches!(result, Err(Error::AuthorityRejected { .. })), + "{result:?}" + ); +} + +fn assert_write_seq_mismatch(result: Result<()>, expected: u64, actual: u64) { + let error = result.unwrap_err(); + assert!( + matches!( + error, + Error::AuthorityWriteSeqMismatch { + expected: error_expected, + actual: error_actual, + .. + } if error_expected == expected && error_actual == actual + ), + "{error:?}" + ); + assert_eq!(error.status_code(), StatusCode::RequestOutdated); + assert_eq!(error.retry_hint(), RetryHint::NonRetryable); +} + +fn assert_unknown(result: Result) { + assert!( + matches!(result, Err(Error::AuthorityUnknown { .. })), + "{result:?}" + ); +} + +fn assert_closed(result: Result) { + assert!( + matches!(result, Err(Error::AuthorityClosed { .. })), + "{result:?}" + ); +} + +async fn fill_queue( + node: &Authority, + token: FencingToken, + precondition: AuthorityPrecondition, +) -> Vec> + '_>>> { + let mut pending = Vec::new(); + for _ in 0..CAPACITY { + let mut request = Box::pin(renew(node, token, precondition)); + assert!(matches!(futures::poll!(&mut request), Poll::Pending)); + pending.push(request); + } + assert_eq!(node.request_tx.capacity(), 0); + pending +} + +#[tokio::test(start_paused = true)] +async fn empty_head_can_be_acquired_and_resigned() { + let fixture = Fixture::new().await; + let leader = fixture.node("a"); + let candidate = fixture.node("b"); + let token = acquire(&leader).await; + assert_eq!(token.epoch(), 1); + let head = leader.head().await.unwrap(); + assert_eq!(head.head().owner.as_ref(), Some(&leader.inner.identity)); + assert!(head.metadata().etag().is_some()); + assert!(head.metadata().last_modified().is_some()); + leader.resign(&token).await.unwrap(); + let head = leader.head().await.unwrap(); + assert!(head.head().owner.is_none()); + assert_eq!((head.head().epoch(), head.head().write_seq()), (1, 2)); + assert_eq!(leader.status(), AuthorityStatus::Follower); + assert_eq!(acquire(&candidate).await.epoch(), 2); + leader.shutdown().await; + candidate.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn takeover_requires_strictly_more_than_twelve_seconds() { + let fixture = Fixture::new().await; + let original = fixture.node("same-address"); + let replacement = fixture.node("same-address"); + let token = acquire(&original).await; + original.shutdown().await; + fixture.expire_stored_lease(0).await; + fixture.clear_calls(); + assert_eq!( + replacement.takeover().await.unwrap(), + TakeoverOutcome::NotEligible + ); + assert_eq!(fixture.order(), ["GET"]); + assert_rejected(renew(&replacement, token, AuthorityPrecondition::Any).await); + fixture.expire_stored_lease(1).await; + let new_token = acquire(&replacement).await; + assert_eq!(new_token.epoch(), token.epoch() + 1); + let head = replacement.head().await.unwrap(); + let owner = head.head().owner.as_ref().unwrap(); + assert_eq!(owner.addr, original.inner.identity.addr); + assert_ne!(owner.incarnation_id, original.inner.identity.incarnation_id); + fixture.clear_calls(); + assert_rejected(renew(&replacement, token, AuthorityPrecondition::Any).await); + assert!(fixture.puts().is_empty()); + replacement.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn candidates_racing_the_same_version_have_one_winner() { + let fixture = Fixture::new().await; + let first = fixture.node("first"); + let second = fixture.node("second"); + let mut first_put = fixture.backend.defer_next_write(); + let first_result = takeover_task(&first); + first_put.arrived.notified().await; + let mut second_put = fixture.backend.defer_next_write(); + let second_result = takeover_task(&second); + second_put.arrived.notified().await; + assert_eq!(fixture.order(), ["GET", "PUT", "GET", "PUT"]); + assert!(first_put.commit(true).await); + assert!(!second_put.commit(true).await); + assert!(first_put.respond()); + assert!(second_put.respond()); + assert!(matches!( + first_result.await.unwrap().unwrap(), + TakeoverOutcome::Acquired(_) + )); + let error = second_result.await.unwrap().unwrap_err(); + assert_eq!( + error.authority_storage_error().unwrap().kind(), + ErrorKind::ConditionNotMatch + ); + assert_eq!(fixture.order(), ["GET", "PUT", "GET", "PUT", "GET"]); + assert_eq!(second.status(), AuthorityStatus::Follower); + first.shutdown().await; + second.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn temporary_conflict_returns_before_deadline_without_replaying_put() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let (_, deadline) = node.status().term().unwrap(); + let base = fixture.store.read_head().await.unwrap(); + fixture.clear_calls(); + fixture.backend.fail_next_write( + StorageError::new(ErrorKind::Conflict, "injected conditional conflict").set_temporary(), + ); + + let error = renew(&node, token, AuthorityPrecondition::Any) + .await + .unwrap_err(); + assert!(matches!(error, Error::AuthorityStorage { .. }), "{error:?}"); + let source = error.authority_storage_error().unwrap(); + assert_eq!(source.kind(), ErrorKind::Conflict); + assert!(source.is_temporary()); + assert!(Instant::now() < deadline); + assert_eq!(fixture.order(), ["GET", "PUT", "GET"]); + let observed = fixture.store.read_head().await.unwrap(); + assert_eq!(observed.head(), base.head()); + assert!( + fixture + .store + .same_version(base.metadata(), observed.metadata()) + .unwrap() + ); + assert_eq!(node.status(), AuthorityStatus::Follower); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn same_address_with_another_uuid_cannot_write_an_existing_term() { + let fixture = Fixture::new().await; + let leader = fixture.node("same-address"); + let token = acquire(&leader).await; + fixture + .replace_remotely(|head| { + let mut next = head.with_next_write_seq().unwrap(); + next.owner = Some(NodeIdentity::new("same-address".into())); + next + }) + .await; + fixture.clear_calls(); + assert_rejected(renew(&leader, token, AuthorityPrecondition::Any).await); + assert_eq!(fixture.order(), ["GET"]); + assert_eq!(leader.status(), AuthorityStatus::Follower); + leader.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn overflow_is_rejected_before_put() { + for field in ["epoch", "write_seq"] { + let fixture = Fixture::new().await; + fixture + .replace_remotely(|head| { + let mut json = serde_json::to_value(head).unwrap(); + json[field] = u64::MAX.into(); + AuthorityHead::decode(&serde_json::to_vec(&json).unwrap()).unwrap() + }) + .await; + let node = fixture.node("a"); + fixture.clear_calls(); + let error = node.takeover().await.unwrap_err(); + assert!(matches!(error, Error::AuthorityOverflow { counter, .. } if counter == field)); + assert_eq!(fixture.order(), ["GET"]); + node.shutdown().await; + } +} + +#[tokio::test(start_paused = true)] +async fn write_seq_mismatch_rejects_put_without_retiring_term() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let active = node.status(); + fixture.clear_calls(); + + assert_write_seq_mismatch( + renew(&node, token, AuthorityPrecondition::WriteSeq(0)).await, + 0, + 1, + ); + assert_eq!(fixture.order(), ["GET"]); + assert_eq!(node.status(), active); + + renew(&node, token, AuthorityPrecondition::WriteSeq(1)) + .await + .unwrap(); + assert_eq!(fixture.order(), ["GET", "GET", "PUT"]); + assert_eq!(fixture.puts()[0].write_seq(), 2); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn due_renewal_overtakes_a_prepared_request_and_a_full_queue() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + advance(RENEW_INTERVAL - Duration::from_millis(200)).await; + let read = fixture.backend.pause_next_read(); + let condition = AuthorityPrecondition::WriteSeq(1); + let mut prepared = Box::pin(renew(&node, token, condition)); + assert!(futures::poll!(&mut prepared).is_pending()); + read.arrived.notified().await; + let waiting = fill_queue(&node, token, condition).await; + let mut scheduled = fixture.backend.defer_next_write(); + + advance(Duration::from_millis(200)).await; + read.release.notify_one(); + scheduled.arrived.notified().await; + assert_eq!(fixture.order(), ["GET", "GET", "PUT"]); + assert!(scheduled.commit(true).await); + assert!(scheduled.respond()); + assert_write_seq_mismatch(prepared.await, 1, 2); + for request in waiting { + assert_write_seq_mismatch(request.await, 1, 2); + } + assert_eq!(fixture.order(), ["GET", "GET", "PUT", "GET", "GET", "GET"]); + let puts = fixture.puts(); + assert_eq!((puts[0].epoch(), puts[0].write_seq()), (1, 2)); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn a_preparation_timeout_crossing_renewal_retries_against_the_renewed_head() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + advance(RENEW_INTERVAL - Duration::from_millis(200)).await; + let read = fixture.backend.pause_next_read(); + let mut scheduled = fixture.backend.defer_next_write(); + let mut queued = Box::pin(renew(&node, token, AuthorityPrecondition::WriteSeq(1))); + assert!(futures::poll!(&mut queued).is_pending()); + read.arrived.notified().await; + + advance(GET_TIMEOUT).await; + scheduled.arrived.notified().await; + assert_eq!(fixture.order(), ["GET", "GET", "PUT"]); + assert!(scheduled.commit(true).await); + assert!(scheduled.respond()); + assert_write_seq_mismatch(queued.await, 1, 2); + assert_eq!(fixture.order(), ["GET", "GET", "PUT", "GET"]); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn renewal_does_not_overlap_an_authorized_put() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + advance(Duration::from_secs(4)).await; + let mut ordinary = fixture.backend.defer_next_write(); + let pending = renew_task(&node, token); + ordinary.arrived.notified().await; + let sent = Instant::now(); + let scheduled = fixture.backend.defer_next_write(); + advance(Duration::from_secs(1)).await; + assert_eq!(fixture.order(), ["GET", "PUT"]); + assert!(ordinary.commit(true).await); + assert!(ordinary.respond()); + pending.await.unwrap().unwrap(); + assert_eq!( + node.status(), + AuthorityStatus::Leader { + epoch: 1, + deadline: sent + LEASE + } + ); + + advance(Duration::from_secs(4)).await; + scheduled.arrived.notified().await; + assert_eq!(fixture.order(), ["GET", "PUT", "GET", "PUT"]); + assert_eq!(fixture.puts()[1].write_seq(), 3); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn first_takeover_get_times_out_without_put() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let read = fixture.backend.pause_next_read(); + let attempt = takeover_task(&node); + read.arrived.notified().await; + advance(GET_TIMEOUT - Duration::from_millis(1)).await; + assert!(!attempt.is_finished()); + advance(Duration::from_millis(1)).await; + assert!(matches!( + attempt.await.unwrap(), + Err(Error::AuthorityTimeout { + operation: "read", + .. + }) + )); + assert_eq!(fixture.order(), ["GET"]); + assert_eq!(node.status(), AuthorityStatus::Follower); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn shutdown_interrupts_the_first_takeover_get_without_put() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let read = fixture.backend.pause_next_read(); + let attempt = takeover_task(&node); + read.arrived.notified().await; + node.shutdown().await; + assert_closed(attempt.await.unwrap()); + assert_eq!(fixture.order(), ["GET"]); + assert!(node.writer_task.lock().await.is_none()); +} + +#[tokio::test(start_paused = true)] +async fn takeover_success_at_deadline_does_not_issue_a_token() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let mut put = fixture.backend.defer_next_write(); + let attempt = takeover_task(&node); + put.arrived.notified().await; + assert!(put.commit(true).await); + + assert!(put.respond()); + advance(LEASE).await; + assert_eq!( + attempt.await.unwrap().unwrap(), + TakeoverOutcome::AppliedButInactive + ); + assert_eq!(node.status(), AuthorityStatus::Follower); + assert_eq!(fixture.order(), ["GET", "PUT"]); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn renewal_success_at_deadline_stays_applied_but_retires_once() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let mut status = node.inner.status_tx.subscribe(); + fixture.clear_calls(); + let mut put = fixture.backend.defer_next_write(); + let attempt = renew_task(&node, token); + put.arrived.notified().await; + let waiting = fill_queue(&node, token, AuthorityPrecondition::Any).await; + assert!(put.commit(true).await); + + assert!(put.respond()); + advance(LEASE).await; + attempt.await.unwrap().unwrap(); + status.changed().await.unwrap(); + assert_eq!(*status.borrow_and_update(), AuthorityStatus::Follower); + for request in waiting { + assert_rejected(request.await); + } + advance(LEASE).await; + assert!(!status.has_changed().unwrap()); + assert_eq!(fixture.order(), ["GET", "PUT"]); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn same_base_takeover_cannot_claim_an_earlier_late_put() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let mut first = fixture.backend.defer_next_write(); + let a = takeover_task(&node); + first.arrived.notified().await; + advance(LEASE).await; + assert_unknown(a.await.unwrap()); + assert_eq!(node.status(), AuthorityStatus::Follower); + + let mut second = fixture.backend.defer_next_write(); + let b = takeover_task(&node); + second.arrived.notified().await; + assert_eq!(fixture.puts()[0], fixture.puts()[1]); + assert!(first.commit(true).await); + assert!(!first.respond(), "the first client has stopped waiting"); + advance(Duration::from_secs(2)).await; + assert_unknown(b.await.unwrap()); + assert!( + !second.commit(true).await, + "the late first PUT won the same CAS" + ); + assert!(!second.respond()); + assert_eq!(node.status(), AuthorityStatus::Follower); + + // The ambiguity belongs to the old base version. A new version can be attributed. + fixture.expire_stored_lease(1).await; + let mut later = fixture.backend.defer_next_write(); + let c = takeover_task(&node); + later.arrived.notified().await; + assert!(later.commit(true).await); + drop(later); + assert!( + matches!(c.await.unwrap().unwrap(), TakeoverOutcome::Acquired(token) if token.epoch() == 2) + ); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn unchanged_version_stays_unknown_through_readback_backoff() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let put = fixture.backend.defer_next_write(); + let attempt = takeover_task(&node); + put.arrived.notified().await; + let start = Instant::now(); + assert_unknown(attempt.await.unwrap()); + let reads: Vec<_> = fixture + .backend + .data + .lock() + .unwrap() + .calls + .iter() + .filter_map(|call| match call { + Call::Get(at) => Some(*at), + Call::Put(_) => None, + }) + .collect(); + assert_eq!(&fixture.order()[..3], ["GET", "PUT", "GET"]); + let mut previous = start; + for (&at, delay) in reads[1..].iter().zip([2_000, 50, 100, 200, 400, 400]) { + let actual = at - previous; + // Tokio's timer wheel can round a deadline up to the next millisecond. + assert!( + (Duration::from_millis(delay)..=Duration::from_millis(delay + 1)).contains(&actual) + ); + previous = at; + } + assert!(reads.len() > 7); + assert!(reads.last().unwrap() < &(start + LEASE)); + assert!(start.elapsed() >= LEASE); + assert_eq!(fixture.puts().len(), 1); + assert_eq!(node.status(), AuthorityStatus::Follower); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn a_higher_epoch_cannot_confirm_a_superseded_put() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let mut put = fixture.backend.defer_next_write(); + let attempt = takeover_task(&node); + put.arrived.notified().await; + assert!(put.commit(true).await); + fixture + .replace_remotely(|head| { + let mut next = head + .with_next_epoch() + .unwrap() + .with_next_write_seq() + .unwrap(); + next.owner = Some(NodeIdentity::new("b".into())); + next + }) + .await; + drop(put); + let error = attempt.await.unwrap().unwrap_err(); + assert!(matches!(error, Error::AuthorityUnknown { .. })); + assert_eq!( + error.authority_storage_error().unwrap().kind(), + ErrorKind::Unexpected + ); + assert_eq!(node.status(), AuthorityStatus::Follower); + assert_eq!(node.head().await.unwrap().head().epoch(), 2); + assert_eq!(fixture.puts().len(), 2); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn missing_head_during_readback_requires_recovery_and_keeps_unknown() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let _put = fixture.backend.defer_next_write(); + let attempt = takeover_task(&node); + _put.arrived.notified().await; + fixture.backend.data.lock().unwrap().objects.clear(); + advance(Duration::from_secs(2)).await; + assert_unknown(attempt.await.unwrap()); + assert_eq!(node.status(), AuthorityStatus::RecoveryRequired); + assert_eq!(fixture.order(), ["GET", "PUT", "GET"]); + assert!(matches!( + node.takeover().await, + Err(Error::AuthorityRecoveryRequired { .. }) + )); + assert!(matches!( + node.head().await, + Err(Error::AuthorityRecoveryRequired { .. }) + )); + assert_eq!(fixture.order(), ["GET", "PUT", "GET"]); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn a_coherent_resign_readback_can_confirm_after_a_successor_is_observed() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let candidate = fixture.node("b"); + let token = acquire(&node).await; + let mut resign = fixture.backend.defer_next_write(); + let pending = resign_task(&node, token); + resign.arrived.notified().await; + assert!(resign.commit(true).await); + + let readback = fixture.backend.pause_next_read_response(); + drop(resign); + readback.arrived.notified().await; + assert_eq!(acquire(&candidate).await.epoch(), 2); + assert_eq!(node.head().await.unwrap().head().epoch(), 2); + readback.release.notify_one(); + pending.await.unwrap().unwrap(); + assert_eq!(node.status(), AuthorityStatus::Follower); + assert_eq!(node.head().await.unwrap().head().epoch(), 2); + assert_eq!(fixture.puts().len(), 3); + node.shutdown().await; + candidate.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn confirmed_write_survives_a_missing_head_on_the_next_read() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let mut put = fixture.backend.defer_next_write(); + let mutation = renew_task(&node, token); + put.arrived.notified().await; + assert!(put.commit(true).await); + fixture.backend.data.lock().unwrap().objects.clear(); + assert!(matches!( + node.head().await, + Err(Error::AuthorityMissing { .. }) + )); + assert_eq!(node.status(), AuthorityStatus::RecoveryRequired); + assert!(put.respond()); + mutation.await.unwrap().unwrap(); + assert_eq!(node.status(), AuthorityStatus::RecoveryRequired); + assert_eq!(fixture.puts().len(), 2); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn late_confirmation_of_unknown_renewal_does_not_restore_term() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let mut status = node.inner.status_tx.subscribe(); + fixture.clear_calls(); + let mut put = fixture.backend.defer_next_write(); + let attempt = renew_task(&node, token); + put.arrived.notified().await; + let waiting = fill_queue(&node, token, AuthorityPrecondition::Any).await; + + advance(Duration::from_secs(2)).await; + status.changed().await.unwrap(); + assert_eq!(*status.borrow_and_update(), AuthorityStatus::Follower); + assert_eq!(fixture.order(), ["GET", "PUT", "GET"]); + assert!(put.commit(true).await); + assert!(!put.respond()); + advance(Duration::from_millis(50)).await; + attempt.await.unwrap().unwrap(); + for request in waiting { + assert_rejected(request.await); + } + assert!(!status.has_changed().unwrap()); + assert_eq!(fixture.order(), ["GET", "PUT", "GET", "GET"]); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn confirmed_write_invalidates_its_base_even_when_refresh_fails() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + let mut put = fixture.backend.defer_next_write(); + let first = renew_task(&node, token); + put.arrived.notified().await; + assert!(put.commit(true).await); + fixture.backend.fail_next_read(); + assert!(put.respond()); + first.await.unwrap().unwrap(); + assert_eq!(fixture.order(), ["GET", "PUT"]); + + let error = renew(&node, token, AuthorityPrecondition::Any) + .await + .unwrap_err(); + assert_eq!( + error.authority_storage_error().unwrap().kind(), + ErrorKind::PermissionDenied + ); + assert_eq!(fixture.order(), ["GET", "PUT", "GET"]); + assert_eq!(node.status(), AuthorityStatus::Follower); + assert_eq!( + fixture.store.read_head().await.unwrap().head().write_seq(), + 2 + ); + assert_rejected(renew(&node, token, AuthorityPrecondition::WriteSeq(2)).await); + assert_eq!(fixture.order(), ["GET", "PUT", "GET", "GET"]); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn confirmed_write_rejects_a_rolled_back_snapshot() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let stale = fixture.backend.data.lock().unwrap().objects.clone(); + renew(&node, token, AuthorityPrecondition::Any) + .await + .unwrap(); + fixture.clear_calls(); + fixture.backend.data.lock().unwrap().objects = stale; + + let error = renew(&node, token, AuthorityPrecondition::Any) + .await + .unwrap_err(); + assert!(matches!(error, Error::AuthorityMetadata { .. })); + assert_eq!(fixture.order(), ["GET"]); + assert_eq!(node.status(), AuthorityStatus::Follower); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn failed_prepare_get_retires_both_renewal_paths_once() { + for scheduled in [false, true] { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let (_, deadline) = node.status().term().unwrap(); + let mut status = node.inner.status_tx.subscribe(); + fixture.clear_calls(); + fixture.backend.fail_next_read(); + + if scheduled { + advance(RENEW_INTERVAL).await; + } else { + let error = renew(&node, token, AuthorityPrecondition::Any) + .await + .unwrap_err(); + assert_eq!( + error.authority_storage_error().unwrap().kind(), + ErrorKind::PermissionDenied + ); + assert_eq!(node.status(), AuthorityStatus::Follower); + } + + status.changed().await.unwrap(); + assert_eq!(*status.borrow_and_update(), AuthorityStatus::Follower); + assert!(Instant::now() < deadline); + assert_rejected(renew(&node, token, AuthorityPrecondition::Any).await); + advance(LEASE).await; + assert!(!status.has_changed().unwrap()); + assert_eq!(fixture.order(), ["GET"]); + node.shutdown().await; + } +} + +#[tokio::test(start_paused = true)] +async fn renewal_retries_a_timed_out_prepare_get_with_the_original_deadline() { + for scheduled in [false, true] { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let active = node.status(); + let (epoch, original_deadline) = active.term().unwrap(); + let mut status = node.inner.status_tx.subscribe(); + fixture.clear_calls(); + let read = fixture.backend.pause_next_read(); + let mut put = fixture.backend.defer_next_write(); + let attempt = if scheduled { + advance(RENEW_INTERVAL).await; + None + } else { + Some(renew_task(&node, token)) + }; + read.arrived.notified().await; + let started_at = Instant::now(); + + // A regression that retires on the first timeout must fail in virtual time. + tokio::time::timeout(Duration::from_secs(2), put.arrived.notified()) + .await + .unwrap(); + assert!(started_at.elapsed() > GET_TIMEOUT); + assert_eq!(fixture.order(), ["GET", "GET", "PUT"]); + assert_eq!(node.status(), active); + assert_eq!( + (fixture.puts()[0].epoch(), fixture.puts()[0].write_seq()), + (epoch, 2) + ); + assert!(put.commit(true).await); + assert!(put.respond()); + + status.changed().await.unwrap(); + assert!(matches!( + *status.borrow_and_update(), + AuthorityStatus::Leader { epoch: renewed, deadline } + if renewed == epoch && deadline > original_deadline + )); + if let Some(attempt) = attempt { + attempt.await.unwrap().unwrap(); + } + node.shutdown().await; + } +} + +#[tokio::test(start_paused = true)] +async fn renewal_retries_a_temporary_prepare_get_error() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + fixture.backend.fail_next_read_with( + StorageError::new(ErrorKind::Unexpected, "injected temporary read error").set_temporary(), + ); + + renew(&node, token, AuthorityPrecondition::Any) + .await + .unwrap(); + assert_eq!(fixture.order(), ["GET", "GET", "PUT"]); + let head = &fixture.puts()[0]; + assert_eq!((head.epoch(), head.write_seq()), (token.epoch(), 2)); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn renewal_prepare_timeouts_exhaust_the_budget_without_a_put() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let (_, deadline) = node.status().term().unwrap(); + let budget_end = deadline - Duration::from_secs(1); + let mut status = node.inner.status_tx.subscribe(); + fixture.clear_calls(); + let first = fixture.backend.pause_next_read(); + for _ in 0..10 { + fixture.backend.pause_next_read(); + } + advance(RENEW_INTERVAL).await; + first.arrived.notified().await; + status.changed().await.unwrap(); + + assert_eq!(*status.borrow_and_update(), AuthorityStatus::Follower); + assert!(Instant::now() >= budget_end && Instant::now() < deadline); + assert_rejected(renew(&node, token, AuthorityPrecondition::Any).await); + let order = fixture.order(); + assert!(order.len() > 1); + assert!(order.iter().all(|request| *request == "GET")); + assert!( + fixture + .backend + .data + .lock() + .unwrap() + .calls + .iter() + .all(|call| matches!(call, Call::Get(started_at) if *started_at < budget_end)) + ); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn conditional_resign_rejects_mismatched_sequence_without_retiring_term() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let active = node.status(); + let before = node.head().await.unwrap(); + fixture.clear_calls(); + + for expected in [0, 2] { + let result = node + .mutate( + &token, + AuthorityPrecondition::WriteSeq(expected), + AuthorityMutation::Resign, + ) + .await; + assert_write_seq_mismatch(result, expected, 1); + assert_eq!(node.status(), active); + } + assert_eq!(fixture.order(), ["GET", "GET"]); + let after = node.head().await.unwrap(); + assert_eq!(before.head(), after.head()); + assert!( + fixture + .store + .same_version(before.metadata(), after.metadata()) + .unwrap() + ); + renew(&node, token, AuthorityPrecondition::WriteSeq(1)) + .await + .unwrap(); + assert_eq!(fixture.puts().len(), 1); + assert_eq!(fixture.puts()[0].epoch(), token.epoch()); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn conditional_resign_stops_admission_at_put_authorization() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let active = node.status(); + let (epoch, deadline) = active.term().unwrap(); + fixture.clear_calls(); + let read = fixture.backend.pause_next_read(); + let mut put = fixture.backend.defer_next_write(); + let mut resign = Box::pin(node.mutate( + &token, + AuthorityPrecondition::WriteSeq(1), + AuthorityMutation::Resign, + )); + assert!(futures::poll!(&mut resign).is_pending()); + read.arrived.notified().await; + assert_eq!(node.status(), active); + let waiting = fill_queue(&node, token, AuthorityPrecondition::Any).await; + + read.release.notify_one(); + put.arrived.notified().await; + assert_eq!( + node.status(), + AuthorityStatus::Resigning { epoch, deadline } + ); + assert_rejected(renew(&node, token, AuthorityPrecondition::Any).await); + for request in waiting { + assert_rejected(request.await); + } + assert_eq!(fixture.order(), ["GET", "PUT"]); + assert!(put.commit(true).await); + assert!(put.respond()); + resign.await.unwrap(); + assert_eq!(node.status(), AuthorityStatus::Follower); + let head = node.head().await.unwrap(); + assert!(head.head().owner.is_none()); + assert_eq!((head.head().epoch(), head.head().write_seq()), (epoch, 2)); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn conditional_resign_rechecks_sequence_after_a_due_renewal() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + advance(RENEW_INTERVAL - Duration::from_millis(200)).await; + let read = fixture.backend.pause_next_read(); + let mut resign = Box::pin(node.mutate( + &token, + AuthorityPrecondition::WriteSeq(1), + AuthorityMutation::Resign, + )); + assert!(futures::poll!(&mut resign).is_pending()); + read.arrived.notified().await; + + advance(Duration::from_millis(200)).await; + read.release.notify_one(); + assert_write_seq_mismatch(resign.await, 1, 2); + assert_eq!(fixture.order(), ["GET", "GET", "PUT", "GET"]); + assert!(fixture.puts()[0].owner.is_some()); + assert!( + matches!(node.status(), AuthorityStatus::Leader { epoch, .. } if epoch == token.epoch()) + ); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn resign_cancels_a_preparing_get_before_authorization() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + let read = fixture.backend.pause_next_read(); + let prepared = renew_task(&node, token); + read.arrived.notified().await; + node.resign(&token).await.unwrap(); + assert_rejected(prepared.await.unwrap()); + assert_eq!(fixture.order(), ["GET", "GET", "PUT"]); + let writes = fixture.puts(); + assert!(writes[0].owner.is_none()); + assert_eq!(node.status(), AuthorityStatus::Follower); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn resign_wins_before_a_full_queue_can_authorize_a_put() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + let waiting = fill_queue(&node, token, AuthorityPrecondition::Any).await; + let mut resign = Box::pin(node.resign(&token)); + assert!(futures::poll!(&mut resign).is_pending()); + assert!(matches!(node.status(), AuthorityStatus::Resigning { .. })); + resign.await.unwrap(); + for request in waiting { + assert_rejected(request.await); + } + assert_eq!(fixture.order(), ["GET", "PUT"]); + assert!(fixture.puts()[0].owner.is_none()); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn resign_stops_full_queue_but_preserves_authorized_put_results() { + for outcome in ["applied", "failed", "unknown"] { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let mut put = fixture.backend.defer_next_write(); + let sent = renew_task(&node, token); + put.arrived.notified().await; + let waiting = fill_queue(&node, token, AuthorityPrecondition::Any).await; + let mut resign = Box::pin(node.resign(&token)); + assert!(futures::poll!(&mut resign).is_pending()); + assert!(matches!( + node.status(), + AuthorityStatus::Resigning { epoch: 1, .. } + )); + + match outcome { + "applied" => { + assert!(put.commit(true).await); + assert!(put.respond()); + sent.await.unwrap().unwrap(); + resign.await.unwrap(); + let writes = fixture.puts(); + assert_eq!(writes.len(), 3); + assert!(writes[2].owner.is_none()); + assert_eq!((writes[2].epoch(), writes[2].write_seq()), (1, 3)); + } + "failed" => { + assert!(!put.commit(false).await); + assert!(put.respond()); + let error = sent.await.unwrap().unwrap_err(); + assert_eq!( + error.authority_storage_error().unwrap().kind(), + ErrorKind::PermissionDenied + ); + assert_rejected(resign.await); + assert_eq!(fixture.puts().len(), 2); + } + _ => { + advance(LEASE).await; + assert_unknown(sent.await.unwrap()); + assert_rejected(resign.await); + assert_eq!(fixture.puts().len(), 2); + } + } + for request in waiting { + assert_rejected(request.await); + } + assert_eq!(node.status(), AuthorityStatus::Follower); + node.shutdown().await; + } +} + +#[tokio::test(start_paused = true)] +async fn resignation_does_not_discard_a_takeover_queued_after_retirement() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let mut put = fixture.backend.defer_next_write(); + let sent = renew_task(&node, token); + put.arrived.notified().await; + let mut resign = Box::pin(node.resign(&token)); + assert!(futures::poll!(&mut resign).is_pending()); + + advance(Duration::from_secs(2)).await; + node.inner + .wait_until(|status| status == AuthorityStatus::Follower) + .await; + fixture.expire_stored_lease(1).await; + let mut takeover = Box::pin(node.takeover()); + assert!(futures::poll!(&mut takeover).is_pending()); + assert_eq!(node.request_tx.capacity(), CAPACITY - 1); + + advance(Duration::from_secs(8)).await; + assert_unknown(sent.await.unwrap()); + assert_rejected(resign.await); + assert!( + matches!(takeover.await.unwrap(), TakeoverOutcome::Acquired(token) if token.epoch() == 2) + ); + assert!(!put.commit(true).await); + assert!(!put.respond()); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn resign_freezes_old_deadline_while_scheduled_renewal_is_in_flight() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let AuthorityStatus::Leader { deadline, .. } = node.status() else { + panic!("acquisition must activate the term"); + }; + let mut renewing = fixture.backend.defer_next_write(); + advance(RENEW_INTERVAL).await; + renewing.arrived.notified().await; + assert!(renewing.commit(true).await); + let reading_to_resign = fixture.backend.pause_next_read(); + let mut resign = Box::pin(node.resign(&token)); + assert!(futures::poll!(&mut resign).is_pending()); + + assert!(renewing.respond()); + // A paused process can observe success after the PUT timer, before the old deadline. + advance(deadline - Instant::now() - Duration::from_secs(1)).await; + reading_to_resign.arrived.notified().await; + assert_eq!( + node.status(), + AuthorityStatus::Resigning { epoch: 1, deadline } + ); + reading_to_resign.release.notify_one(); + assert!(matches!( + resign.await, + Err(Error::AuthorityTimeout { + operation: "write budget", + .. + }) + )); + assert_eq!(fixture.puts().len(), 2); + assert_eq!(node.status(), AuthorityStatus::Follower); + node.shutdown().await; +} + +#[tokio::test(start_paused = true)] +async fn shutdown_closes_a_full_queue_and_preserves_unknown_in_flight_put() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + let mut put = fixture.backend.defer_next_write(); + let sent = renew_task(&node, token); + put.arrived.notified().await; + let waiting = fill_queue(&node, token, AuthorityPrecondition::Any).await; + let mut blocked_send = Box::pin(renew(&node, token, AuthorityPrecondition::Any)); + assert!(futures::poll!(&mut blocked_send).is_pending()); + + tokio::join!(node.shutdown(), node.shutdown()); + assert_unknown(sent.await.unwrap()); + assert_closed(blocked_send.await); + for request in waiting { + assert_closed(request.await); + } + assert!(node.writer_task.lock().await.is_none()); + assert_eq!(node.status(), AuthorityStatus::Closed); + assert_eq!(fixture.order(), ["GET", "PUT"]); + assert!( + put.commit(true).await, + "the simulated server can finish after shutdown" + ); + assert!(!put.respond()); + let head = fixture.store.read_head().await.unwrap(); + assert_eq!(head.head().owner.as_ref(), Some(&node.inner.identity)); + assert_eq!(head.head().write_seq(), 2); +} + +#[tokio::test(start_paused = true)] +async fn shutdown_preserves_a_put_response_ready_at_cancellation() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let mut put = fixture.backend.defer_next_write(); + let sent = renew_task(&node, token); + put.arrived.notified().await; + assert!(put.commit(true).await); + assert!(put.respond()); + node.shutdown().await; + sent.await.unwrap().unwrap(); + assert_eq!(node.status(), AuthorityStatus::Closed); + assert!(node.writer_task.lock().await.is_none()); + assert_eq!(fixture.puts().len(), 2); +} + +#[tokio::test(start_paused = true)] +async fn shutdown_cancels_renewal_preparation() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + fixture.clear_calls(); + let read = fixture.backend.pause_next_read(); + let renewal = renew_task(&node, token); + read.arrived.notified().await; + node.shutdown().await; + assert_closed(renewal.await.unwrap()); + assert_eq!(node.status(), AuthorityStatus::Closed); + assert_eq!(fixture.order(), ["GET"]); +} + +#[tokio::test(start_paused = true)] +async fn shutdown_cancels_resign_preparation_and_keeps_the_stored_owner() { + let fixture = Fixture::new().await; + let node = fixture.node("a"); + let token = acquire(&node).await; + let read = fixture.backend.pause_next_read(); + let resign = resign_task(&node, token); + read.arrived.notified().await; + node.shutdown().await; + assert_closed(resign.await.unwrap()); + assert!(node.writer_task.lock().await.is_none()); + assert_eq!(fixture.puts().len(), 1); + let head = fixture.store.read_head().await.unwrap(); + assert_eq!(head.head().owner.as_ref(), Some(&node.inner.identity)); +} diff --git a/src/common/meta/src/election/object_store/authority/writer.rs b/src/common/meta/src/election/object_store/authority/writer.rs new file mode 100644 index 00000000000..e99dd128f72 --- /dev/null +++ b/src/common/meta/src/election/object_store/authority/writer.rs @@ -0,0 +1,596 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; +use std::time::Duration; + +use object_store::ErrorKind; +use snafu::{IntoError, OptionExt}; +use tokio::sync::{mpsc, oneshot}; +use tokio::time::{Instant, sleep_until}; + +use crate::election::object_store::authority::{ + Admission, AuthorityMutation, AuthorityPrecondition, AuthorityStatus, CLOCK_GUARD, + FencingToken, Inner, LEASE, RENEW_INTERVAL, SnapshotFloor, TakeoverOutcome, closed, rejected, + timeout, +}; +use crate::election::object_store::{AuthorityHead, AuthorityState}; +use crate::error::{self, Error, Result}; + +const PUT_TIMEOUT: Duration = Duration::from_secs(2); +const READBACK_RESERVE: Duration = Duration::from_secs(1); +const INITIAL_BACKOFF: Duration = Duration::from_millis(50); +const MAX_BACKOFF: Duration = Duration::from_millis(400); + +pub(crate) enum Request { + Takeover(oneshot::Sender>), + Mutate { + epoch: u64, + mutation: AuthorityMutation, + precondition: AuthorityPrecondition, + response: oneshot::Sender>, + }, +} + +impl Request { + fn reject(self, error: Error) { + match self { + Self::Takeover(response) => { + let _ = response.send(Err(error)); + } + Self::Mutate { response, .. } => { + let _ = response.send(Err(error)); + } + } + } +} + +pub(crate) struct Resignation { + pub(crate) epoch: u64, + pub(crate) response: oneshot::Sender>, +} + +pub(crate) struct Writer { + inner: Arc, + request_rx: mpsc::Receiver, + ambiguous_takeover: Option, +} + +impl Writer { + pub(crate) fn new(inner: Arc, request_rx: mpsc::Receiver) -> Self { + Self { + inner, + request_rx, + ambiguous_takeover: None, + } + } + + pub(crate) async fn run(mut self) { + let mut changes = self.inner.status_tx.subscribe(); + loop { + let (status, resignation) = self + .inner + .update(|control, _| (control.status, control.resignation.take())); + if status == AuthorityStatus::Closed { + if let Some(request) = resignation { + let _ = request.response.send(Err(closed())); + } + break; + } + if let Some(request) = resignation { + self.drain_resigning(request.epoch); + let result = self.resign(request.epoch).await; + let _ = request.response.send(result); + continue; + } + let term = match status { + AuthorityStatus::Leader { epoch, deadline } => Some((epoch, deadline)), + _ => None, + }; + let deadline = term.map_or_else(Instant::now, |(_, deadline)| deadline); + tokio::select! { + biased; + _ = changes.changed() => {} + _ = sleep_until(deadline), if term.is_some() => {} + _ = sleep_until(renew_at(deadline)), if term.is_some() => { + if let Some((epoch, _)) = term { + self.renew(epoch).await; + } + } + request = self.request_rx.recv() => match request { + Some(request) => self.process(request).await, + None => break, + } + } + } + self.request_rx.close(); + self.drain(closed); + } + + fn drain_resigning(&mut self, epoch: u64) { + // Once the term retires, the FIFO can also contain a new takeover. + while let Some(request) = self.inner.update(|control, _| { + Admission::Resign(epoch).check(control.status).ok()?; + self.request_rx.try_recv().ok() + }) { + request.reject(rejected("resignation stopped admission before PUT")); + } + } + + fn drain(&mut self, error: impl Fn() -> Error) { + while let Ok(request) = self.request_rx.try_recv() { + request.reject(error()); + } + } + + async fn process(&mut self, request: Request) { + match request { + Request::Takeover(response) => { + let _ = response.send(self.takeover().await); + } + Request::Mutate { + epoch, + mutation, + precondition, + response, + } => { + let result = loop { + let put = match mutation { + AuthorityMutation::Renew => { + self.prepare_renewal(epoch, precondition, false).await + } + AuthorityMutation::Resign => { + self.prepare_term( + Admission::ConditionalResign(epoch), + precondition, + true, + ) + .await + } + }; + match put { + Ok(Some(put)) => { + if matches!(mutation, AuthorityMutation::Resign) { + self.drain_resigning(epoch); + } + break self.write(&put).await.map(|_| ()); + } + Ok(None) => self.renew(epoch).await, + Err(error) => break Err(error), + } + }; + let _ = response.send(result); + } + } + } + + async fn takeover(&mut self) -> Result { + let base = self.inner.read(Admission::Takeover, None).await?; + let ambiguous = if let Some(previous) = &self.ambiguous_takeover { + self.inner + .store + .same_version(previous.metadata(), base.metadata())? + } else { + false + }; + if !ambiguous { + self.ambiguous_takeover = None; + } + + if base.head().owner.is_some() { + let modified = base + .metadata() + .last_modified() + .context(error::AuthorityMetadataSnafu { + reason: "read returned no last_modified", + })? + .into_inner() + .as_nanosecond(); + if (self.inner.wall_now_ns)() <= modified + (LEASE + CLOCK_GUARD).as_nanos() as i128 { + return Ok(TakeoverOutcome::NotEligible); + } + } + let mut next = base + .head() + .clone() + .with_next_epoch()? + .with_next_write_seq()?; + next.owner = Some(self.inner.identity.clone()); + next.lease_deadline_ms = self.inner.diagnostic_deadline(); + let put = self.inner.update(|control, now| { + Admission::Takeover.check(control.status)?; + if let Some(floor) = &control.snapshot { + floor.validate(&self.inner.store, &base)?; + } + Ok(Put { + admission: Admission::Takeover, + base, + next, + sent_at: now, + deadline: now + LEASE, + ambiguous, + }) + })?; + + match self.write(&put).await { + Ok(true) => Ok(TakeoverOutcome::Acquired(FencingToken { + epoch: put.next.epoch(), + })), + Ok(false) => Ok(TakeoverOutcome::AppliedButInactive), + Err(error) => { + if matches!(error, Error::AuthorityUnknown { .. }) { + let base_unresolved = self.inner.update(|control, _| { + control.snapshot.as_ref().is_none_or(|observed| { + observed.head().write_seq() <= put.base.head().write_seq() + }) + }); + self.ambiguous_takeover = base_unresolved.then_some(put.base); + } + Err(error) + } + } + } + + async fn renew(&self, epoch: u64) { + if let Ok(Some(put)) = self + .prepare_renewal(epoch, AuthorityPrecondition::Any, true) + .await + && let Err(error) = self.write(&put).await + { + common_telemetry::warn!(error; "Authority renewal of epoch {epoch} failed"); + } + } + + async fn prepare_renewal( + &self, + epoch: u64, + precondition: AuthorityPrecondition, + scheduled: bool, + ) -> Result> { + let admission = Admission::Renew(epoch); + let result = self.prepare_term(admission, precondition, !scheduled).await; + if let Err(error) = &result + && !matches!(error, Error::AuthorityWriteSeqMismatch { .. }) + { + // Resignation or shutdown can take over while the preparation GET is in flight. + let retired = self.inner.update(|control, _| { + if admission.check(control.status).is_ok() { + control.retire(epoch); + true + } else { + false + } + }); + if scheduled && retired { + common_telemetry::warn!(error; "Authority renewal of epoch {epoch} failed"); + } + } + result + } + + async fn resign(&self, epoch: u64) -> Result<()> { + let result = match self + .prepare_term(Admission::Resign(epoch), AuthorityPrecondition::Any, false) + .await + { + Ok(Some(put)) => self.write(&put).await.map(|_| ()), + Ok(None) => Err(rejected("resignation could not be authorized")), + Err(error) => Err(error), + }; + self.inner.update(|control, _| control.retire(epoch)); + result + } + + /// An empty result keeps the FIFO request in hand while we perform a due renewal. + async fn prepare_term( + &self, + admission: Admission, + precondition: AuthorityPrecondition, + defer_for_renewal: bool, + ) -> Result> { + let (epoch, deadline) = self.inner.update(|control, _| { + admission.check(control.status)?; + control + .status + .term() + .ok_or_else(|| rejected("term is inactive")) + })?; + let read = match admission { + Admission::Renew(_) => { + self.read_renewal_head(admission, deadline, defer_for_renewal) + .await + } + _ => self.inner.read(admission, Some(deadline)).await, + }; + let base = match read { + Ok(base) => base, + Err(error) => { + let renew_due = defer_for_renewal + && self.inner.update(|control, now| { + admission.check(control.status).is_ok() && now >= renew_at(deadline) + }); + return if renew_due { Ok(None) } else { Err(error) }; + } + }; + let next = base.head().clone().with_next_write_seq().map(|mut next| { + if matches!( + admission, + Admission::Resign(_) | Admission::ConditionalResign(_) + ) { + next.owner = None; + next.lease_deadline_ms = 0; + } else { + next.lease_deadline_ms = self.inner.diagnostic_deadline(); + } + next + }); + self.inner.update(|control, now| { + admission.check(control.status)?; + if defer_for_renewal && now >= renew_at(deadline) { + return Ok(None); + } + if now + READBACK_RESERVE >= deadline { + control.retire(epoch); + return Err(timeout("write budget")); + } + if base.head().epoch() != epoch + || base.head().owner.as_ref() != Some(&self.inner.identity) + { + return Err(rejected("Head is not owned by this term")); + } + if let Some(floor) = &control.snapshot { + floor.validate(&self.inner.store, &base)?; + } + precondition.check(base.head())?; + let next = next?; + let admission = if matches!(admission, Admission::ConditionalResign(_)) { + // Close admission and authorize the CAS against this read under one lock. + control.status = AuthorityStatus::Resigning { epoch, deadline }; + Admission::Resign(epoch) + } else { + admission + }; + Ok(Some(Put { + admission, + base, + next, + sent_at: now, + deadline, + ambiguous: false, + })) + }) + } + + async fn read_renewal_head( + &self, + admission: Admission, + deadline: Instant, + defer_for_renewal: bool, + ) -> Result { + let prepare_deadline = deadline - READBACK_RESERVE; + // A queued renewal yields to the scheduled renewal during read backoff. + let retry_until = if defer_for_renewal { + prepare_deadline.min(renew_at(deadline)) + } else { + prepare_deadline + }; + let mut backoff = INITIAL_BACKOFF; + loop { + let error = match self.inner.read(admission, Some(prepare_deadline)).await { + Ok(head) => return Ok(head), + Err(error) => error, + }; + let retryable = matches!( + error, + Error::AuthorityTimeout { + operation: "read", + .. + } + ) || error.authority_storage_error().is_some_and(|source| { + source.is_temporary() + && !matches!( + source.kind(), + ErrorKind::PermissionDenied | ErrorKind::NotFound + ) + }); + let now = Instant::now(); + if !retryable || now >= retry_until { + return Err(error); + } + tokio::select! { + biased; + _ = self.inner.wait_until(|status| admission.check(status).is_err()) => {} + _ = sleep_until((now + backoff).min(retry_until)) => {} + } + self.inner + .update(|control, _| admission.check(control.status))?; + if Instant::now() >= retry_until { + return Err(error); + } + backoff = (backoff * 2).min(MAX_BACKOFF); + } + } + + async fn write(&self, put: &Put) -> Result { + let response = self.send(put).await; + match response { + PutResponse::Applied => Ok(self.confirm(put, true)), + PutResponse::Unsent(error) | PutResponse::Failed(error) => { + self.retire(put); + Err(error) + } + PutResponse::Conflict(error) => { + self.retire(put); + // Re-evaluate the observed version and term without replaying the CAS. + let _ = self.inner.read(Admission::Read, Some(put.deadline)).await; + Err(error) + } + PutResponse::Unknown(error) => { + self.retire(put); + if self.resolve(put).await { + Ok(self.confirm(put, false)) + } else { + Err(error::AuthorityUnknownSnafu.into_error(Box::new(error))) + } + } + } + } + + async fn send(&self, put: &Put) -> PutResponse { + let stop = (put.sent_at + PUT_TIMEOUT).min(put.deadline - READBACK_RESERVE); + let request = async { + if let Err(error) = + Admission::Read.check(self.inner.update(|control, _| control.status)) + { + return PutResponse::Unsent(error); + } + if Instant::now() >= stop { + return PutResponse::Unsent(timeout("write budget")); + } + match self.inner.store.replace_head(&put.base, &put.next).await { + Ok(()) => PutResponse::Applied, + Err(error) => match error.authority_storage_error() { + Some(storage) + if matches!( + storage.kind(), + ErrorKind::ConditionNotMatch + | ErrorKind::AlreadyExists + | ErrorKind::Conflict + | ErrorKind::NotFound + ) => + { + PutResponse::Conflict(error) + } + Some(storage) + if storage.is_temporary() || storage.kind() == ErrorKind::Unexpected => + { + PutResponse::Unknown(error) + } + _ => PutResponse::Failed(error), + }, + } + }; + // A response already available when the task wakes still determines the PUT + // result. The state transition separately checks the clock under the lock. + tokio::select! { + biased; + result = request => result, + _ = self.inner.wait_until(|status| status == AuthorityStatus::Closed) => PutResponse::Unknown(closed()), + _ = sleep_until(stop) => PutResponse::Unknown(timeout("write")), + } + } + + async fn resolve(&self, put: &Put) -> bool { + let mut backoff = INITIAL_BACKOFF; + while Instant::now() < put.deadline { + match self.inner.read(Admission::Read, Some(put.deadline)).await { + Ok(state) => { + let advanced = self + .inner + .store + .same_version(put.base.metadata(), state.metadata()); + if matches!(advanced, Ok(false)) + && state.head().write_seq() >= put.next.write_seq() + { + // A later or competing write may have overwritten our evidence. + // With an older ambiguous takeover, even an exact match is inconclusive. + return !put.ambiguous && state.head() == &put.next; + } + } + Err( + Error::AuthorityClosed { .. } + | Error::AuthorityMissing { .. } + | Error::AuthorityRecoveryRequired { .. }, + ) => return false, + Err(_) => {} + } + let retry_at = (Instant::now() + backoff).min(put.deadline); + tokio::select! { + _ = self.inner.wait_until(|status| Admission::Read.check(status).is_err()) => return false, + _ = sleep_until(retry_at) => {} + } + backoff = (backoff * 2).min(MAX_BACKOFF); + } + false + } + + fn confirm(&self, put: &Put, direct: bool) -> bool { + self.inner.update(|control, now| { + let current = control.snapshot.as_ref().map(SnapshotFloor::head); + let still_current = current + .is_none_or(|head| head.write_seq() < put.next.write_seq() || head == &put.next); + if current.is_none_or(|head| head.write_seq() < put.next.write_seq()) { + control.snapshot = Some(SnapshotFloor::Applied { + head: put.next.clone(), + base: put.base.clone(), + }); + } + let epoch = put.next.epoch(); + if matches!(put.admission, Admission::Resign(_)) { + control.retire(epoch); + return false; + } + if still_current && now < put.deadline { + match put.admission { + Admission::Takeover if control.status == AuthorityStatus::Follower => { + control.status = AuthorityStatus::Leader { + epoch, + deadline: put.deadline, + }; + return true; + } + Admission::Renew(_) + if direct && Admission::Renew(epoch).check(control.status).is_ok() => + { + control.status = AuthorityStatus::Leader { + epoch, + deadline: put.sent_at + LEASE, + }; + } + _ => {} + } + } + false + }) + } + + fn retire(&self, put: &Put) { + if let Admission::Renew(epoch) | Admission::Resign(epoch) = put.admission { + self.inner.update(|control, _| control.retire(epoch)); + } + } +} + +fn renew_at(deadline: Instant) -> Instant { + deadline - (LEASE - RENEW_INTERVAL) +} + +/// The writer obtains this single-use authorization under the state lock and +/// owns it until the PUT outcome is classified. No other code sends a Head PUT. +struct Put { + admission: Admission, + base: AuthorityState, + next: AuthorityHead, + sent_at: Instant, + deadline: Instant, + ambiguous: bool, +} + +enum PutResponse { + Applied, + Unsent(Error), + Conflict(Error), + Failed(Error), + Unknown(Error), +} diff --git a/src/common/meta/src/election/object_store/tests.rs b/src/common/meta/src/election/object_store/tests.rs index 9e857766078..e8fb6607224 100644 --- a/src/common/meta/src/election/object_store/tests.rs +++ b/src/common/meta/src/election/object_store/tests.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex}; use common_error::ext::{ErrorExt, RetryHint}; @@ -24,14 +24,20 @@ use object_store::layers::mock::{ Result, RpCreateDir, RpPresign, RpRead, RpRename, RpStat, Service, Timestamp, oio, }; use object_store::{ObjectStore, ServiceInfo}; +use tokio::sync::{Notify, oneshot}; +use tokio::time::Instant; use super::*; // Explicitly supplies coherent response metadata. This is a protocol simulator, // not a claim about memory-service or real-backend semantics. #[derive(Debug, Default)] -struct Data { - objects: HashMap, Metadata)>, +pub(crate) struct Data { + pub(crate) calls: Vec, + read_actions: VecDeque, + write_actions: VecDeque, + next_write_error: Option, + pub(crate) objects: HashMap, Metadata)>, seq: u64, writes: usize, ignore_conditions: bool, @@ -58,8 +64,8 @@ enum ConflictMutation { } #[derive(Debug, Clone)] -struct Backend { - data: Arc>, +pub(crate) struct Backend { + pub(crate) data: Arc>, scheme: &'static str, capability: Capability, } @@ -82,6 +88,116 @@ impl Default for Backend { } } +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Call { + Get(Instant), + Put(AuthorityHead), +} + +#[derive(Debug)] +enum ReadAction { + Pause(DeferredRead), + PauseResponse(DeferredRead), + Fail(Error), +} + +#[derive(Debug, Clone)] +pub(crate) struct DeferredRead { + pub(crate) arrived: Arc, + pub(crate) release: Arc, +} + +type WriteReceipt = (Result, oneshot::Sender>); + +#[derive(Debug)] +struct WriteAction { + arrived: Arc, + commit: oneshot::Receiver, + committed: oneshot::Sender, +} + +pub(crate) struct DeferredWrite { + pub(crate) arrived: Arc, + commit: Option>, + committed: oneshot::Receiver, + receipt: Option, +} + +impl DeferredWrite { + pub(crate) async fn commit(&mut self, apply: bool) -> bool { + self.commit.take().unwrap().send(apply).unwrap(); + let receipt = (&mut self.committed).await.unwrap(); + let applied = receipt.0.is_ok(); + self.receipt = Some(receipt); + applied + } + + pub(crate) fn respond(mut self) -> bool { + let (result, response) = self.receipt.take().unwrap(); + response.send(result).is_ok() + } +} + +impl Backend { + pub(crate) fn pause_next_read(&self) -> DeferredRead { + self.pause_read(ReadAction::Pause) + } + + pub(crate) fn pause_next_read_response(&self) -> DeferredRead { + self.pause_read(ReadAction::PauseResponse) + } + + fn pause_read(&self, action: impl FnOnce(DeferredRead) -> ReadAction) -> DeferredRead { + let gate = DeferredRead { + arrived: Arc::new(Notify::new()), + release: Arc::new(Notify::new()), + }; + self.data + .lock() + .unwrap() + .read_actions + .push_back(action(gate.clone())); + gate + } + + pub(crate) fn fail_next_read(&self) { + self.fail_next_read_with(denied()); + } + + pub(crate) fn fail_next_read_with(&self, error: Error) { + self.data + .lock() + .unwrap() + .read_actions + .push_back(ReadAction::Fail(error)); + } + + pub(crate) fn fail_next_write(&self, error: Error) { + self.data.lock().unwrap().next_write_error = Some(error); + } + + pub(crate) fn defer_next_write(&self) -> DeferredWrite { + let arrived = Arc::new(Notify::new()); + let (commit_tx, commit) = oneshot::channel(); + let (committed, committed_rx) = oneshot::channel(); + self.data + .lock() + .unwrap() + .write_actions + .push_back(WriteAction { + arrived: arrived.clone(), + commit, + committed, + }); + DeferredWrite { + arrived, + commit: Some(commit_tx), + committed: committed_rx, + receipt: None, + } + } +} + impl Service for Backend { async fn create_dir( &self, @@ -157,7 +273,7 @@ impl Service for Backend { } } -struct TestLister; +pub(crate) struct TestLister; impl oio::List for TestLister { async fn next(&mut self) -> Result> { @@ -169,13 +285,28 @@ fn denied() -> Error { Error::new(ErrorKind::PermissionDenied, "injected permission failure") } -struct TestReader { +pub(crate) struct TestReader { data: Arc>, path: String, } impl oio::Read for TestReader { async fn open(&self, _: BytesRange) -> Result<(RpRead, Box)> { + let action = { + let mut data = self.data.lock().unwrap(); + data.calls.push(Call::Get(Instant::now())); + data.read_actions.pop_front() + }; + let pause_response = match action { + Some(ReadAction::Pause(gate)) => { + gate.arrived.notify_one(); + gate.release.notified().await; + None + } + Some(ReadAction::PauseResponse(gate)) => Some((gate.arrived, gate.release)), + Some(ReadAction::Fail(error)) => return Err(error), + None => None, + }; let data = self.data.lock().unwrap(); let (body, meta) = data .objects @@ -190,7 +321,7 @@ impl oio::Read for TestReader { rp, Box::new(TestStream { body: Buffer::from(body.clone()), - pause: data.pause.clone(), + pause: pause_response.or_else(|| data.pause.clone()), }), )) } @@ -215,7 +346,8 @@ impl oio::ReadStream for TestStream { } } -struct TestWriter { +#[derive(Clone)] +pub(crate) struct TestWriter { data: Arc>, path: String, args: OpWrite, @@ -242,11 +374,47 @@ impl oio::Write for TestWriter { if let Some(barrier) = barrier { barrier.wait().await; } + let action = { + let mut data = self.data.lock().unwrap(); + if data.write_barrier.is_some() { + data.writes_in_flight -= 1; + } + data.writes += 1; + data.calls + .push(Call::Put(AuthorityHead::decode(&self.body).unwrap())); + data.write_actions.pop_front() + }; + if let Some(action) = action { + let writer = self.clone(); + let (response, result) = oneshot::channel(); + // The server owns the conditional update even after the client stops waiting. + tokio::spawn(async move { + action.arrived.notify_one(); + let outcome = match action.commit.await { + Ok(true) => writer.commit(), + Ok(false) => Err(denied()), + Err(_) => return, + }; + let _ = action.committed.send((outcome, response)); + }); + return result.await.unwrap_or_else(|_| { + Err(Error::new(ErrorKind::Unexpected, "lost response").set_temporary()) + }); + } + self.commit() + } + + async fn abort(&mut self) -> Result<()> { + Ok(()) + } +} + +impl TestWriter { + fn commit(&self) -> Result { let mut data = self.data.lock().unwrap(); - if data.write_barrier.is_some() { - data.writes_in_flight -= 1; + if let Some(error) = data.next_write_error.take() { + return Err(error); } - data.writes += 1; if data.fail == Some("write") { return Err(Error::new(ErrorKind::Unexpected, "lost response").set_temporary()); } @@ -300,10 +468,6 @@ impl oio::Write for TestWriter { .insert(self.path.clone(), (self.body.clone(), meta.clone())); Ok(meta) } - - async fn abort(&mut self) -> Result<()> { - Ok(()) - } } fn corrupt_conflict(data: &mut Data, path: &str, mutation: Option) { @@ -326,7 +490,7 @@ fn corrupt_conflict(data: &mut Data, path: &str, mutation: Option>); +pub(crate) struct TestDeleter(Arc>); impl oio::Delete for TestDeleter { async fn delete(&mut self, path: &str, _: OpDelete) -> Result<()> { @@ -344,7 +508,7 @@ impl oio::Delete for TestDeleter { } } -fn store(backend: &Backend) -> HeadStore { +pub(crate) fn store(backend: &Backend) -> HeadStore { HeadStore::new_for_test( ObjectStore::from_parts(OperationContext::default(), Arc::new(backend.clone())), "cluster", diff --git a/src/common/meta/src/error.rs b/src/common/meta/src/error.rs index 2befbc3520c..2052c27bb06 100644 --- a/src/common/meta/src/error.rs +++ b/src/common/meta/src/error.rs @@ -1141,6 +1141,51 @@ pub enum Error { location: Location, }, + #[snafu(display("Authority is closed"))] + AuthorityClosed { + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Authority Head requires operator recovery"))] + AuthorityRecoveryRequired { + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Authority operation was not executed: {}", reason))] + AuthorityRejected { + reason: &'static str, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display( + "Authority Head write sequence mismatch: expected {}, actual {}", + expected, + actual + ))] + AuthorityWriteSeqMismatch { + expected: u64, + actual: u64, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Authority {} timed out", operation))] + AuthorityTimeout { + operation: &'static str, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Authority PUT outcome is unknown"))] + AuthorityUnknown { + source: Box, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Failed to open Authority storage"))] AuthorityOpen { #[snafu(source)] @@ -1334,7 +1379,13 @@ impl ErrorExt for Error { AuthorityMissing { .. } | AuthorityMetadata { .. } | AuthorityStorage { .. } - | AuthorityOpen { .. } => StatusCode::StorageUnavailable, + | AuthorityOpen { .. } + | AuthorityClosed { .. } + | AuthorityRecoveryRequired { .. } + | AuthorityTimeout { .. } + | AuthorityUnknown { .. } => StatusCode::StorageUnavailable, + AuthorityRejected { .. } => StatusCode::IllegalState, + AuthorityWriteSeqMismatch { .. } => StatusCode::RequestOutdated, NoLeader { .. } => StatusCode::TableUnavailable, ValueNotExist { .. } | ProcedurePoisonConflict { .. } @@ -1557,6 +1608,7 @@ impl Error { Self::AuthorityStorage { error, .. } | Self::AuthorityMissing { error, .. } => { Some(error) } + Self::AuthorityUnknown { source, .. } => source.authority_storage_error(), _ => None, } }