//! NOTHING WAITS WHILE IT HOLDS A FILE. //! //! A person's file is one SQLite connection behind one mutex. Whoever holds it //! holds every route, every worker and every phone's sync against that file, //! so a hold is a few statements long and never longer: nothing waits on the //! network, a child process or another lock while it has the file in hand. //! The failure it prevents was measured on a serving Mac: the peer-sync pass //! sat in a TLS handshake to the relay inside the file, and the session host, //! every route and every sweep queued on the mutex behind it — the log went //! silent and the phones saw no server. //! //! This module is the guard. Every lock over a file marks the thread for the //! length of the hold ([`holding`]); every place that waits — an outbound //! call, a dial, a child process, a socket to another process, another //! lock — asks [`must_not_wait`] first. In a debug build (every test) a wait //! inside a hold PANICS with both names, so the test that reaches the path is //! the test that fails. A release build says so on stderr and carries on: //! a stall is bad, a crashed server is worse. //! //! It lives in the store because every crate that holds a file links it — the //! server's `OpenFile`, the client's replica, the Mac shell's served handle — //! and every crate that waits does too. use std::cell::RefCell; thread_local! { /// What this thread holds right now, innermost last. A stack, because a /// hold can nest (the write lock, then the file inside it). static HOLDING: RefCell> = const { RefCell::new(Vec::new()) }; } /// Marks the thread as holding `what` until the guard drops. A guard rather /// than a pair of calls, so a closure that panics still un-marks. #[must_use = "the thread is marked only while the guard lives"] pub struct Holding { what: &'static str, /// Not `Send`: the mark is this thread's, and a guard moved to another /// thread would un-mark the wrong one. _thread: std::marker::PhantomData<*const ()>, } /// Mark this thread as holding `what` — a name a panic can print, such as /// `"the served file"`. pub fn holding(what: &'static str) -> Holding { HOLDING.with(|held| held.borrow_mut().push(what)); Holding { what, _thread: std::marker::PhantomData, } } impl Drop for Holding { fn drop(&mut self) { HOLDING.with(|held| { let mut held = held.borrow_mut(); if let Some(at) = held.iter().rposition(|name| *name == self.what) { held.remove(at); } }); } } /// What this thread holds, if anything — the innermost hold. pub fn held() -> Option<&'static str> { HOLDING.with(|held| held.borrow().last().copied()) } /// The check every wait makes before it waits. `on` names the wait — /// `"an outbound HTTP call"`, `"the statements slot"` — for the message. /// /// # Panics /// /// In a debug build, when the thread holds a file: the caller is about to /// stall everything that needs that file for as long as the wait lasts. #[track_caller] pub fn must_not_wait(on: &str) { let Some(what) = held() else { return; }; let at = std::panic::Location::caller(); let message = format!( "waits on {on} while holding {what} (at {at}) — release the file first: \ nothing waits on the network, a child process or another lock inside a file" ); if cfg!(debug_assertions) { panic!("{message}"); } eprintln!("cotton: {message}"); } // ── what a hold did ───────────────────────────────────────────────────────── /// What one hold of a file did, for the line a slow one writes: who asked, /// and how much was folded. /// /// **A SLOW HOLD IS DIAGNOSED FROM THE LOG OR NOT AT ALL.** On 10 Oct 2026 /// one write held the owner's file for more than ten minutes and the only way /// to learn anything about it was a stack sample of the live process — which /// said what the thread was inside, and could not say which tool or which /// sync batch had asked. So the paths that do the work NAME themselves as /// they run ([`doing`], [`folded`]) and whoever holds the file reads the /// names back when the hold ends ([`tally`]). #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Work { /// What ran, in the order it first ran — `the MCP tool erase_photos`, /// `a write (bin by user:…)`, `a pushed batch` — each named once. pub doing: Vec, /// How many facts (ops) were folded. pub facts: usize, /// In how many folds. pub folds: usize, /// The acts that went past what an act may ask of a file ([`act_done`]), /// each as the line that says so. pub over: Vec, } /// More names than this say nothing a person will read; the count still does. const NAMES_KEPT: usize = 8; thread_local! { /// One [`Work`] per open [`tally`] on this thread, innermost last. static WORK: RefCell> = const { RefCell::new(Vec::new()) }; } /// Counts what this thread does from now until [`Tally::done`]. Notes made /// with no tally open are dropped, so a path outside a hold pays nothing. #[must_use = "the work is counted only until the tally is done"] pub struct Tally { open: bool, _thread: std::marker::PhantomData<*const ()>, } /// Start counting this thread's work. A tally inside another (a hold of one /// file inside a hold of a second) counts its own, and adds it to the outer /// one when it is done. pub fn tally() -> Tally { WORK.with(|work| work.borrow_mut().push(Work::default())); Tally { open: true, _thread: std::marker::PhantomData, } } impl Tally { /// What was done since [`tally`]. pub fn done(mut self) -> Work { self.open = false; close_tally() } } impl Drop for Tally { fn drop(&mut self) { if self.open { close_tally(); } } } fn close_tally() -> Work { WORK.with(|work| { let mut work = work.borrow_mut(); let mine = work.pop().unwrap_or_default(); if let Some(outer) = work.last_mut() { for name in &mine.doing { name_once(outer, name); } outer.facts += mine.facts; outer.folds += mine.folds; outer.over.extend(mine.over.iter().cloned()); } mine }) } fn name_once(work: &mut Work, what: &str) { if work.doing.len() < NAMES_KEPT && !work.doing.iter().any(|name| name == what) { work.doing.push(what.to_string()); } } /// Name what this thread is doing inside the hold — a tool, a write, a sync /// batch. Each name is kept once. pub fn doing(what: &str) { WORK.with(|work| { if let Some(work) = work.borrow_mut().last_mut() { name_once(work, what); } }); } /// Count one fold of `facts` ops. pub fn folded(facts: usize) { WORK.with(|work| { if let Some(work) = work.borrow_mut().last_mut() { work.facts += facts; work.folds += 1; } }); } // ── what an act may ask of a file ─────────────────────────────────────────── /// How much one act of a job, and one act that erases, may ask of a file: the /// statements' virtual-machine steps by SQLite's own count /// ([`crate::driver::Driver::steps`]). /// /// **AN ACT'S WORK GROWS WITH THE ACT, NEVER WITH THE ACT TIMES THE FILE.** /// Twice a write that nobody asked for — a worker's hourly pass — held the /// owner's file for more than ten minutes (10 and 11 Oct 2026): each asked a /// question that read a whole table, once per fact it folded and once per row /// it erased. Nothing was wrong in either result, so no test of a result /// could fail; what was wrong was how much was read. So every such act is /// measured where it is minted, and one that reads more than this is not /// allowed to pass a test: in a debug build it PANICS, naming the act, and in /// a release build the hold says so in the log. /// /// Sixty million steps is about a second of a serving Mac. Two thousand /// bundles erased in one act read under four million, and a thousand runs /// with their jobs fourteen (`repos::prune`'s tests); the act that read a /// table per row passed sixty at four hundred rows. pub const ACT_STEPS: u64 = 60_000_000; /// How long such an act may take before the hold says so in the log. Said and /// never panicked on: a machine's load is not the act's doing. pub const ACT_TIME: std::time::Duration = std::time::Duration::from_secs(2); /// The line for an act of `who` that went past [`ACT_STEPS`] or [`ACT_TIME`], /// or `None` for one within both. pub fn act_over_line(who: &str, facts: usize, steps: u64, took: std::time::Duration) -> Option { if steps <= ACT_STEPS && took <= ACT_TIME { return None; } Some(format!( "{who} asked too much of the file in one act: {facts} fact(s), {steps} steps read (an act's bound is {ACT_STEPS}), {:.1} s (bound {:.0} s) — an act's work grows with the act, never with the file", took.as_secs_f64(), ACT_TIME.as_secs_f64(), )) } /// What `mint` reports of every bounded act when it is done. /// /// # Panics /// /// In a debug build, when the act read more than [`ACT_STEPS`]. pub fn act_done(who: &str, facts: usize, steps: u64, took: std::time::Duration) { let Some(line) = act_over_line(who, facts, steps, took) else { return; }; if cfg!(debug_assertions) && steps > ACT_STEPS { panic!("{line}"); } WORK.with(|work| { if let Some(work) = work.borrow_mut().last_mut() { work.over.push(line); } }); } /// How long a hold of a file may last before it is said in the log. pub const SLOW_HOLD: std::time::Duration = std::time::Duration::from_secs(5); /// THE ONE LINE A SLOW HOLD WRITES, or `None` for a hold shorter than `slow`: /// whose file, how long, what ran, how many facts were folded, and where in /// the code the hold was asked for. pub fn slow_hold_line( whose: &str, took: std::time::Duration, slow: std::time::Duration, work: &Work, asked: &Asked, asked_at: &std::panic::Location<'_>, ) -> Option { if took < slow { return None; } let ran = if work.doing.is_empty() { "nothing that named itself".to_string() } else { work.doing.join(", ") }; let slowest = match &asked.slowest { Some((took, sql)) => format!(", its slowest statement {:.1} s: {sql}", took.as_secs_f64()), None => String::new(), }; // AND THE BAND THE HOLDING THREAD RAN IN: a thread the kernel holds below // the default band reads 10–23x slower while the Mac builds (`thread_band`). let thread = crate::thread_band::this_thread(); let band = if thread.below_default() { ", held below the default band" } else { "" }; Some(format!( "a hold of {whose}'s file took {:.1} s — {ran}; {} fact(s) folded in {} fold(s), {} steps read, {:.1} s inside SQLite{slowest} (asked at {asked_at}; on a {} thread{band})", took.as_secs_f64(), work.facts, work.folds, asked.steps, asked.inside.as_secs_f64(), thread.said(), )) } /// WHAT A HOLD ASKED OF SQLITE, so a slow one says where its time went: the /// steps it read, the wall time it spent inside its statements, and the /// slowest of them. Many steps is a scan. Few steps and a long time inside is /// a wait SQLite made — for another connection's lock, for the disk — and the /// slowest statement says which. Little time inside at all is the holder's own /// work, done while everybody else waited for the file. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Asked { pub steps: u64, pub inside: std::time::Duration, pub slowest: Option<(std::time::Duration, String)>, } impl Asked { /// What `db` has been asked since `before` was read from it /// ([`Asked::so_far`]) — the hold's own share. pub fn since(db: &crate::driver::Driver, before: &Asked) -> Asked { Asked { steps: db.steps() - before.steps, inside: db.time_inside().saturating_sub(before.inside), slowest: db.take_slowest(), } } /// The handle's counts as a hold begins; an earlier hold's slowest /// statement is forgotten here. pub fn so_far(db: &crate::driver::Driver) -> Asked { db.take_slowest(); Asked { steps: db.steps(), inside: db.time_inside(), slowest: None } } } #[cfg(test)] #[path = "held_tests.rs"] mod tests;