//! THE SWAP OF THE DATABASE THIS PHONE STANDS ON, waited out by every read.//!//! Signing out (`personal.standLocal {signedOut}`), signing in over a copy//! that must go aside or come back (`personal.connect`), removing the copy//! (`personal.remove`) and forgetting a deleted account (`account.forget`)//! each let go of one database and open another. Between the two there is no//! connection record, or one naming a file being moved: Android asks the core//! on four threads, and a read that landed there (Words' list, launch walk,//! 22 Nov 2026) was answered "has not started or joined a database yet", a//! moment of nothing to read on every Sign out.//!//! The thread that swaps holds a [`SwapTurn`] from before it lets go until the//! new database stands. Every call from the app waits it out before it begins//! (`methods::dispatch_across_swaps`), holding no lock while it waits, and a//! read a swap overtook part way ([`SwapGate::epoch`] moved) is asked again//! once the swap is over: either way it is answered from the database that//! stands after the swap. The core's own threads never wait here (a wait//! inside an open, under a lock a swap needs, held the swap for the whole//! bound). The swapping thread itself passes, and a turn nests on its own//! thread. The wait is bounded ([`READ_WAIT`]): a swap that runs longer lets//! the call go on and answer what stands then, rather than hang a thread.use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, Condvar, Mutex};use std::thread::ThreadId;use std::time::{Duration, Instant};/// The longest a call waits for a swap on another thread to finish. A swap/// is moments on a phone; a debug build on a busy machine stands on a fresh/// database in tens of seconds, and the bound is there for a swap that never/// ends, not to cut a slow one short.pubconst READ_WAIT: Duration = Duration::from_secs(60);/// Who is swapping, and how deep its turns nest.#[derive(Debug, Default)]pubstructSwapGate { held: Mutex<Option<(ThreadId, usize)>>, ended: Condvar,/// Bumped as each swap begins. began: AtomicU64,}implSwapGate {/// Take the turn to swap: waits for a swap on another thread to end (two/// swaps never interleave), nests on this one. Released when dropped.pubfn enter(self: &Arc<Self>) -> SwapTurn {let me = std::thread::current().id();letmut held = self.held.lock().unwrap_or_else(|poisoned| poisoned.into_inner());loop {match held.as_mut() {None => { *held = Some((me, 1));self.began.fetch_add(1, Ordering::SeqCst);break; }Some((thread, depth)) if *thread == me => { *depth += 1;break; }Some(_) => held = self.ended.wait(held).unwrap_or_else(|poisoned| poisoned.into_inner()), } }SwapTurn { gate: Arc::clone(self) } }/// Wait until no other thread is swapping, at most [`READ_WAIT`]. At once/// when none is, or when this thread is the one swapping.pubfn wait_out(&self) {let me = std::thread::current().id();let deadline = Instant::now() + READ_WAIT;letmut held = self.held.lock().unwrap_or_else(|poisoned| poisoned.into_inner());whileletSome((thread, _)) = held.as_ref() {if *thread == me {return; }let left = deadline.saturating_duration_since(Instant::now());if left.is_zero() { eprintln!("[swap] a read waited {READ_WAIT:?} for the database to be swapped and goes on without it");return; } held = self.ended.wait_timeout(held, left).unwrap_or_else(|poisoned| poisoned.into_inner()).0; } }/// How many swaps have begun: a call that reads it before and after/// knows whether a swap overtook it.pubfn epoch(&self) -> u64 {self.began.load(Ordering::SeqCst) }/// Whether a swap is under way on any thread.pubfn swapping(&self) -> bool {self.held.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).is_some() }}/// One thread's turn to swap; the gate opens when the outermost is dropped.#[derive(Debug)]pubstructSwapTurn { gate: Arc<SwapGate>,}implDropforSwapTurn {fn drop(&mutself) {letmut held = self.gate.held.lock().unwrap_or_else(|poisoned| poisoned.into_inner());ifletSome((_, depth)) = held.as_mut() { *depth -= 1;if *depth == 0 { *held = None;self.gate.ended.notify_all(); } } }}#[cfg(test)]mod tests {usesuper::*; #[test]fn a_read_waits_for_the_swap_and_the_swapping_thread_passes() {let gate = Arc::new(SwapGate::default());let turn = gate.enter();let nested = gate.enter(); gate.wait_out(); // the swapping thread itself passeslet reader = {let gate = Arc::clone(&gate); std::thread::spawn(move || {let began = Instant::now(); gate.wait_out(); began.elapsed() }) }; std::thread::sleep(Duration::from_millis(100)); drop(nested); assert!(gate.swapping(), "the outer turn still holds"); std::thread::sleep(Duration::from_millis(100)); drop(turn);let waited = reader.join().expect("the reader ends"); assert!(waited >= Duration::from_millis(190), "the read waited for the whole swap: {waited:?}"); assert!(!gate.swapping()); }}