use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use pigeonhole_engine::Engine;
use crate::db::Db;
use crate::options::Recovery;
use crate::{Error, ErrorCode, Result};
const MAX_RECOVERIES: usize = 3;
const WINDOW: Duration = Duration::from_secs(10 * 60);
const BACKOFF: [Duration; MAX_RECOVERIES] = [
Duration::ZERO,
Duration::from_secs(1),
Duration::from_secs(4),
];
const POLL: Duration = Duration::from_millis(500);
const DEADLINE_STALLS: u32 = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum FailureCause {
Panic = 1,
DriverDropped = 2,
Io = 3,
Internal = 4,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Failure {
pub shard: u32,
pub cause: FailureCause,
}
impl Failure {
pub const MAIN_FILE: u32 = u32::MAX;
pub(crate) fn from_engine(f: pigeonhole_engine::Failure) -> Self {
use pigeonhole_engine::FailureCause as C;
let cause = match f.cause {
C::Panic => FailureCause::Panic,
C::DriverDropped => FailureCause::DriverDropped,
C::Io => FailureCause::Io,
_ => FailureCause::Internal,
};
Self {
shard: f.shard,
cause,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RecoveryStats {
pub generation: u64,
pub recoveries: u64,
pub gave_up: bool,
pub last_failure: Option<Failure>,
pub last_recovery: Duration,
}
#[derive(Debug)]
enum Phase {
Healthy,
Recovering {
deadline: Instant,
},
GaveUp,
Uncovered,
}
#[derive(Debug)]
struct State {
phase: Phase,
stats: RecoveryStats,
recent: Vec<Instant>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Settled {
Swapped,
Failed,
TimedOut,
}
pub(crate) struct Supervision {
mode: Recovery,
recovering: AtomicBool,
state: Mutex<State>,
changed: Condvar,
thread: Mutex<Option<JoinHandle<()>>>,
#[cfg(test)]
pub(crate) test_hold: TestHold,
started_in: u32,
}
#[cfg(test)]
#[derive(Debug, Default)]
pub(crate) struct TestHold {
pub(crate) armed: AtomicBool,
waited: AtomicBool,
}
#[cfg(test)]
impl TestHold {
pub(crate) fn release(&self) {
self.waited.store(true, Ordering::SeqCst);
}
fn hold(&self) {
if !self.armed.load(Ordering::SeqCst) {
return;
}
let deadline = Instant::now() + Duration::from_secs(10);
while !self.waited.load(Ordering::SeqCst) && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(1));
}
}
}
impl std::fmt::Debug for Supervision {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Supervision")
.field("mode", &self.mode)
.field("recovering", &self.recovering.load(Ordering::Relaxed))
.finish_non_exhaustive()
}
}
impl Supervision {
pub(crate) fn new(mode: Recovery) -> Self {
Self {
mode,
recovering: AtomicBool::new(false),
state: Mutex::new(State {
phase: Phase::Healthy,
stats: RecoveryStats::default(),
recent: Vec::new(),
}),
changed: Condvar::new(),
thread: Mutex::new(None),
#[cfg(test)]
test_hold: TestHold::default(),
started_in: pigeonhole_io::sys::process_id(),
}
}
fn forked(&self) -> bool {
pigeonhole_io::sys::process_id() != self.started_in
}
fn lock(&self) -> std::sync::MutexGuard<'_, State> {
let mut st = self.state.lock().unwrap_or_else(PoisonError::into_inner);
if let Phase::Recovering { deadline, .. } = st.phase
&& Instant::now() >= deadline
{
st.phase = Phase::GaveUp;
st.stats.gave_up = true;
self.recovering.store(false, Ordering::Release);
self.changed.notify_all();
}
st
}
#[inline]
pub(crate) fn recovering(&self) -> bool {
self.recovering.load(Ordering::Acquire)
}
pub(crate) fn gave_up(&self) -> bool {
if self.forked() {
return false;
}
matches!(self.lock().phase, Phase::GaveUp)
}
pub(crate) fn stood_down(&self) -> bool {
if self.forked() {
return false;
}
matches!(self.lock().phase, Phase::GaveUp | Phase::Uncovered)
}
pub(crate) fn covers_refusal(&self, failure: Option<Failure>) -> bool {
if self.forked() {
return false;
}
match self.lock().phase {
Phase::Uncovered => false,
Phase::Healthy => failure.is_none_or(|f| covers(self.mode, f.cause)),
Phase::Recovering { .. } | Phase::GaveUp => true,
}
}
pub(crate) fn stats(&self, generation: u64) -> RecoveryStats {
if self.forked() {
return RecoveryStats {
generation,
..RecoveryStats::default()
};
}
let mut s = self.lock().stats;
s.generation = generation;
s
}
pub(crate) fn last_failure(&self) -> Option<Failure> {
if self.forked() {
return None;
}
self.lock().stats.last_failure
}
pub(crate) fn wait_settled(
&self,
timeout: Duration,
still_failing: impl Fn() -> bool,
) -> Settled {
if self.forked() {
return Settled::Failed;
}
#[cfg(test)]
self.test_hold.waited.store(true, Ordering::SeqCst);
let deadline = Instant::now() + timeout;
let mut st = self.lock();
loop {
match st.phase {
Phase::Healthy if !still_failing() => return Settled::Swapped,
Phase::Healthy | Phase::Recovering { .. } => {}
Phase::GaveUp | Phase::Uncovered => return Settled::Failed,
}
let now = Instant::now();
if now >= deadline {
return Settled::TimedOut;
}
drop(st);
let wait = (deadline - now).min(POLL);
let guard = self.state.lock().unwrap_or_else(PoisonError::into_inner);
let _ = self
.changed
.wait_timeout(guard, wait)
.unwrap_or_else(PoisonError::into_inner);
st = self.lock();
}
}
pub(crate) fn start(db: &Arc<Db>) -> Result<()> {
let weak = Arc::downgrade(db);
let thread = std::thread::Builder::new()
.name("pigeonhole-recovery".to_owned())
.spawn(move || run(weak))
.map_err(|e| {
Error::new(ErrorCode::Io, format!("spawn the recovery supervisor: {e}"))
})?;
*db.supervision()
.expect("started only with the option on")
.thread
.lock()
.unwrap_or_else(PoisonError::into_inner) = Some(thread);
Ok(())
}
pub(crate) fn join(&self) {
let thread = self
.thread
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
if self.forked() {
std::mem::forget(thread);
return;
}
if let Some(t) = thread
&& t.thread().id() != std::thread::current().id()
{
let _ = t.join();
}
}
}
fn run(weak: Weak<Db>) {
loop {
let Some(db) = weak.upgrade() else { return };
if db.is_closed() {
return;
}
let engine = db.engine_arc();
let failed = engine.wait_failed(Instant::now() + POLL);
if db.is_closed() {
return;
}
if !failed {
drop(engine);
drop(db);
continue;
}
#[cfg(test)]
if let Some(sup) = db.supervision() {
sup.test_hold.hold();
}
if !recover(&db, engine) {
return;
}
}
}
fn covers(mode: Recovery, cause: FailureCause) -> bool {
match mode {
Recovery::Off => false,
Recovery::Io => cause == FailureCause::Io,
Recovery::Any => cause != FailureCause::DriverDropped,
}
}
fn fatal(e: &pigeonhole_engine::Error) -> bool {
use pigeonhole_engine::Error as E;
matches!(
e,
E::Corruption(_)
| E::UnsupportedFormat(_)
| E::NoSpace
| E::WriterLocked
| E::ShmVersionMismatch { .. }
)
}
fn recover(db: &Arc<Db>, failed: Arc<Engine>) -> bool {
let sup = db
.supervision()
.expect("the supervisor runs only with the option on");
let failure = failed.failure().map(Failure::from_engine);
if !failure.is_some_and(|f| covers(sup.mode, f.cause)) {
let mut st = sup.lock();
if matches!(st.phase, Phase::Healthy) {
st.phase = Phase::Uncovered;
st.stats.last_failure = failure;
sup.changed.notify_all();
}
return false;
}
let (since, deadline, attempt) = {
let mut st = sup.lock();
if !matches!(st.phase, Phase::Healthy) {
return false;
}
let now = Instant::now();
st.recent.retain(|t| now.duration_since(*t) < WINDOW);
st.stats.last_failure = failure;
if st.recent.len() >= MAX_RECOVERIES {
st.phase = Phase::GaveUp;
st.stats.gave_up = true;
sup.changed.notify_all();
return false;
}
let deadline = now + db.stall_timeout().saturating_mul(DEADLINE_STALLS);
st.phase = Phase::Recovering { deadline };
sup.recovering.store(true, Ordering::Release);
sup.changed.notify_all();
(now, deadline, st.recent.len())
};
let give_up = |sup: &Supervision| {
let mut st = sup.lock();
st.phase = Phase::GaveUp;
st.stats.gave_up = true;
sup.recovering.store(false, Ordering::Release);
sup.changed.notify_all();
false
};
let (_closed, handover) = failed.close_for_reopen();
drop(failed);
if sup.gave_up() || db.is_closed() {
drop(handover);
return give_up(sup);
}
let mut handover = handover;
let mut tries = attempt;
loop {
let backoff = BACKOFF[tries.min(MAX_RECOVERIES - 1)];
if !backoff.is_zero() {
let now = Instant::now();
if now + backoff >= deadline {
return give_up(sup);
}
std::thread::sleep(backoff);
}
let options = match db.reopen_options() {
Ok(o) => o,
Err(_) => return give_up(sup),
};
let path = db.path();
let result = match handover.take() {
Some(h) => Engine::open_with(path, options, h).map_err(|(e, h)| {
handover = Some(h);
e
}),
None => Engine::open(path, options),
};
match result {
Ok(engine) => {
let mut engine = Some(engine);
let old = {
let mut st = sup.lock();
if matches!(st.phase, Phase::Recovering { .. }) && !db.is_closed() {
let old = db.swap_engine(engine.take().expect("not swapped yet"));
let now = Instant::now();
st.recent.push(now);
st.stats.recoveries += 1;
st.stats.last_recovery = now.duration_since(since);
st.phase = Phase::Healthy;
sup.recovering.store(false, Ordering::Release);
sup.changed.notify_all();
Some(old)
} else {
None
}
};
match old {
Some(old) => {
old.release_memory();
drop(old);
return true;
}
None => {
let engine = engine.take().expect("not swapped");
let _ = engine.close();
drop(engine);
return give_up(sup);
}
}
}
Err(e) => {
tries += 1;
if fatal(&e) || tries >= MAX_RECOVERIES || Instant::now() >= deadline {
drop(handover);
return give_up(sup);
}
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use pigeonhole_io::sim::SimVfs;
use crate::{ErrorCode, Family, Options, Pigeonhole, Recovery, RetryPolicy};
#[test]
fn a_commit_refused_by_a_failed_shard_before_the_close_recovers() {
let vfs = SimVfs::new(9211);
let options = Options::default()
.shards(2)
.pin_threads(false)
.memtable_budget(4 << 20)
.write_stall_timeout(Duration::from_secs(10))
.vfs(Arc::clone(&vfs) as _)
.auto_recover(Recovery::Any);
let db = Pigeonhole::open("/db/r921.phdb", options).unwrap();
let t = db
.table("t")
.unwrap()
.family("f", Family::default())
.create_if_missing()
.unwrap();
t.mutate(b"n").put("f", b"q", b"0").commit().unwrap();
db.db
.supervision()
.unwrap()
.test_hold
.armed
.store(true, Ordering::SeqCst);
let mut attempts = 0;
let (value, _) = db
.transact(&RetryPolicy::default(), |txn| {
attempts += 1;
let n: u64 = txn.get(&t, b"n", "f", b"q")?.map_or(0, |c| {
std::str::from_utf8(c.value()).unwrap().parse().unwrap()
});
if attempts == 1 {
db.engine()
.to_arc()
.inject(pigeonhole_engine::Fault::NextApply, true);
let e = t.mutate(b"x").put("f", b"q", b"1").commit().unwrap_err();
assert_eq!(e.code(), ErrorCode::OutcomeUnknown);
}
txn.put(&t, b"n", "f", b"q", (n + 1).to_string().as_bytes());
Ok::<_, crate::Error>(n)
})
.unwrap();
assert_eq!(attempts, 2, "{:?}", db.recovery_stats());
assert_eq!(value, 0);
assert_eq!(t.get(b"n", "f", b"q").unwrap().unwrap().value(), b"1");
assert_eq!(db.recovery_stats().recoveries, 1);
drop(t);
db.close().unwrap();
}
#[test]
fn a_ticket_or_async_commit_refused_before_the_swap_is_busy_after_it() {
let vfs = SimVfs::new(9662);
let options = Options::default()
.shards(1)
.pin_threads(false)
.memtable_budget(4 << 20)
.write_stall_timeout(Duration::from_secs(10))
.vfs(Arc::clone(&vfs) as _)
.auto_recover(Recovery::Any);
let db = Pigeonhole::open("/db/r9662.phdb", options).unwrap();
let t = db
.table("t")
.unwrap()
.family("f", Family::default())
.family("c", Family::counter())
.create_if_missing()
.unwrap();
db.db
.supervision()
.unwrap()
.test_hold
.armed
.store(true, Ordering::SeqCst);
db.engine()
.to_arc()
.inject(pigeonhole_engine::Fault::NextApply, true);
let e = t.mutate(b"x").put("f", b"q", b"1").commit().unwrap_err();
assert_eq!(e.code(), ErrorCode::OutcomeUnknown);
let watch = db.db.watch();
let mut wb = db.write_batch();
wb.put(&t, b"w", "f", b"q", b"2");
let ticket = wb.commit_with_ticket(crate::Durability::Buffered).unwrap();
#[cfg(feature = "async")]
let fut = t.mutate(b"z").put("f", b"q", b"3").commit_async();
#[cfg(feature = "async")]
let returning = t.mutate(b"n").incr("c", b"q", 1).commit_returning_async();
db.db.supervision().unwrap().test_hold.release();
let deadline = std::time::Instant::now() + Duration::from_secs(30);
while db.recovery_stats().recoveries < 1 {
assert!(
std::time::Instant::now() < deadline,
"{:?}",
db.recovery_stats()
);
std::thread::sleep(Duration::from_millis(5));
}
let e = ticket.wait().unwrap_err();
assert_eq!(e.code(), ErrorCode::Busy, "ticket: {e}");
let closed: crate::Error = pigeonhole_engine::Error::Closed.into();
let e = watch.refused(closed);
assert_eq!(e.code(), ErrorCode::Busy, "a Closed refusal: {e}");
#[cfg(feature = "async")]
{
let e = crate::doc_support::block_on(fut).unwrap_err();
assert_eq!(e.code(), ErrorCode::Busy, "async: {e}");
let e = crate::doc_support::block_on(returning).unwrap_err();
assert_eq!(e.code(), ErrorCode::Busy, "async returning: {e}");
}
drop(t);
db.close().unwrap();
}
#[test]
fn a_commit_after_a_give_up_is_closed_even_when_the_failed_shard_refuses_it() {
let vfs = SimVfs::new(9661);
let options = Options::default()
.shards(1)
.pin_threads(false)
.memtable_budget(4 << 20)
.write_stall_timeout(Duration::from_secs(10))
.vfs(Arc::clone(&vfs) as _)
.auto_recover(Recovery::Any);
let db = Pigeonhole::open("/db/r966.phdb", options).unwrap();
let t = db
.table("t")
.unwrap()
.family("f", Family::default())
.create_if_missing()
.unwrap();
let fail = || {
db.engine()
.to_arc()
.inject(pigeonhole_engine::Fault::NextApply, true);
let e = t.mutate(b"x").put("f", b"q", b"1").commit().unwrap_err();
assert_eq!(e.code(), ErrorCode::OutcomeUnknown);
};
for n in 1..=3 {
fail();
let deadline = std::time::Instant::now() + Duration::from_secs(30);
while db.recovery_stats().recoveries < n {
assert!(
std::time::Instant::now() < deadline,
"{:?}",
db.recovery_stats()
);
std::thread::sleep(Duration::from_millis(5));
}
}
fail();
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !db.recovery_stats().gave_up {
assert!(
std::time::Instant::now() < deadline,
"{:?}",
db.recovery_stats()
);
std::thread::sleep(Duration::from_millis(5));
}
assert!(db.is_failed());
let e = t.mutate(b"y").put("f", b"q", b"2").commit().unwrap_err();
assert_eq!(e.code(), ErrorCode::Closed, "{e}");
let mut wb = db.write_batch();
wb.put(&t, b"w", "f", b"q", b"3");
let e = wb
.commit_with_ticket(crate::Durability::Buffered)
.and_then(crate::CommitTicket::wait)
.unwrap_err();
assert_eq!(e.code(), ErrorCode::Closed, "ticket: {e}");
assert!(e.to_string().contains("gave up"), "ticket: {e}");
#[cfg(feature = "async")]
{
let fut = t.mutate(b"z").put("f", b"q", b"4").commit_async();
let e = crate::doc_support::block_on(fut).unwrap_err();
assert_eq!(e.code(), ErrorCode::Closed, "async: {e}");
}
drop(t);
let _ = db.close();
}
#[test]
fn an_early_decided_commit_held_on_a_poisoned_coordinator_ends_with_the_swap() {
let vfs = SimVfs::new(2860);
let options = Options::default()
.shards(2)
.pin_threads(false)
.memtable_budget(4 << 20)
.write_stall_timeout(Duration::from_secs(10))
.vfs(Arc::clone(&vfs) as _)
.auto_recover(Recovery::Any);
let db = Pigeonhole::open("/db/r2860.phdb", options).unwrap();
let mut tables: Vec<crate::Table> = Vec::new();
for i in 0..64 {
let t = db
.table(&format!("t{i}"))
.unwrap()
.family("f", Family::default())
.create_if_missing()
.unwrap();
if tables.iter().all(|o| o.shard_of(b"r") != t.shard_of(b"r")) {
tables.push(t);
}
if tables.len() == 2 {
break;
}
}
let (a, b) = (tables[0].clone(), tables[1].clone());
let engine = db.engine().to_arc();
db.db
.supervision()
.unwrap()
.test_hold
.armed
.store(true, Ordering::SeqCst);
struct ReleaseOnPanic(Arc<pigeonhole_engine::Engine>);
impl Drop for ReleaseOnPanic {
fn drop(&mut self) {
if std::thread::panicking() {
self.0.release_held_decisions();
}
}
}
let _release = ReleaseOnPanic(Arc::clone(&engine));
engine.inject(pigeonhole_engine::Fault::HoldDecisionRecords, true);
let rounds = engine.metrics().cross_shard.rounds;
let cross = {
let (db, a, b) = (db.clone(), a.clone(), b.clone());
std::thread::spawn(move || {
let mut wb = db.write_batch();
wb.put(&a, b"x", "f", b"q", b"v");
wb.put(&b, b"x", "f", b"q", b"v");
wb.commit_with(crate::Durability::Buffered)
})
};
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while engine.metrics().cross_shard.rounds == rounds {
assert!(std::time::Instant::now() < deadline, "never decided");
std::thread::sleep(Duration::from_millis(1));
}
engine.inject(pigeonhole_engine::Fault::NextSingleApply, true);
let e = a.mutate(b"s").put("f", b"q", b"s").commit().unwrap_err();
assert_eq!(e.code(), ErrorCode::OutcomeUnknown);
engine.release_held_decisions();
let e = cross.join().unwrap().unwrap_err();
assert_eq!(e.code(), ErrorCode::OutcomeUnknown);
assert_eq!(engine.abort_decides_sent(a.shard_of(b"r").unwrap()), 0);
db.db.supervision().unwrap().test_hold.release();
let deadline = std::time::Instant::now() + Duration::from_secs(30);
while db.recovery_stats().recoveries < 1 || db.is_failed() {
assert!(
std::time::Instant::now() < deadline,
"{:?}",
db.recovery_stats()
);
std::thread::sleep(Duration::from_millis(5));
}
assert!(a.get(b"x", "f", b"q").unwrap().is_none());
assert!(b.get(b"x", "f", b"q").unwrap().is_none());
b.mutate(b"later").put("f", b"q", b"l").commit().unwrap();
assert!(b.get(b"later", "f", b"q").unwrap().is_some());
drop((a, b, tables));
db.close().unwrap();
}
}