From 17624bfd40761cf01749d8957eccf69184ea2939 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 12:44:36 -0700 Subject: [PATCH] fix(store): a git's output is taken when git has ended and the pipes hold nothing, not after a fixed wait on a pipe that has no end run_with waited up to 10 s for each of stdout and stderr to reach end-of-file after git exited. On Windows a pipe has no end while any process holds a copy of its write end: std makes the child's end of each pipe inheritable when it makes the pipe and starts every child with all inheritable handles, so a process started at the same moment (a `taskkill` that stops another git while a close's own last backup begins) keeps the pipe open until it ends. Each command then cost up to 20 s, and the close's last backup passed its 60 s bound (the open/close hammer on Windows: 106 s). The reader now takes what git wrote as soon as git has ended and the pipe holds nothing (PeekNamedPipe on Windows, poll(2) on Unix, the reader seen blocked in its read for 100 ms), and never loses a byte already in the pipe; the 10 s wait stays only as the last resort. `taskkill` goes through lock::spawn, and on Windows spawns are exclusive, so no child takes a copy of another's pipe ends. WANDERBOOKS_GIT_TIMINGS= appends one line per git command (ran, spawn, pipes, how each pipe ended) for runs nobody can watch. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-store/src/backup.rs | 182 +++++++++++---- crates/ledger-store/src/drain.rs | 370 ++++++++++++++++++++++++++++++ crates/ledger-store/src/lib.rs | 1 + crates/ledger-store/src/lock.rs | 15 +- 4 files changed, 524 insertions(+), 44 deletions(-) create mode 100644 crates/ledger-store/src/drain.rs diff --git a/crates/ledger-store/src/backup.rs b/crates/ledger-store/src/backup.rs index c09765c5..4dbf74a1 100644 --- a/crates/ledger-store/src/backup.rs +++ b/crates/ledger-store/src/backup.rs @@ -116,8 +116,16 @@ //! running is killed. A stopped drill or proof removes its scratch //! clone (the one removal that is not itself stopped: it is as long //! as the clone is big). The longest between two looks is one git -//! command's stop (SIGTERM and up to TERM_GRACE, then a kill, GROUP_GONE_WAIT, -//! and up to 10 s for its pipes), one journal line, one file, or one 64 KiB chunk. +//! command's stop (SIGTERM and up to TERM_GRACE, then a kill, GROUP_GONE_WAIT), +//! one journal line, one file, or one 64 KiB chunk. +//! 7. What a git said is in hand as soon as it has ended and everything +//! it wrote has been read (drain.rs): to the end of its pipes, or, when +//! another process still holds a pipe open (Windows: a copy taken by a +//! process started at the same moment), to the point where the pipe +//! holds nothing; never for a fixed wait on a pipe that has no end +//! (10 s at most, as the last resort). With `WANDERBOOKS_GIT_TIMINGS` +//! set to a file, each command appends a line to it: how long it ran, +//! how long its pipes took to close, and how each ended. //! ``` use std::path::{Path, PathBuf}; @@ -510,45 +518,22 @@ impl Git { use std::os::unix::process::CommandExt; c.process_group(0); } + let asked = Instant::now(); + let running = Running::begin(); let mut child = crate::lock::spawn(&mut c).map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => BackupError::NoGit, kind => BackupError::Io(kind), })?; let started = Instant::now(); + let spawn_took = started.duration_since(asked); // Milliseconds since `started` when git last said anything. let heard = std::sync::Arc::new(AtomicU64::new(0)); - let drain = |pipe: Option>, cap: usize| { - let (tx, rx) = std::sync::mpsc::channel(); - let heard = heard.clone(); - std::thread::spawn(move || { - let mut bytes = Vec::new(); - if let Some(mut p) = pipe { - let mut buf = [0u8; 8192]; - while let Ok(n) = p.read(&mut buf) { - if n == 0 { - break; - } - heard.store(started.elapsed().as_millis() as u64, Ordering::Relaxed); - // Bounded: a git that says this much is kept only - // in part, its last part (where its errors are). - bytes.extend_from_slice(&buf[..n]); - if bytes.len() > cap.saturating_mul(2) { - bytes.drain(..bytes.len() - cap); - } - } - } - if bytes.len() > cap { - bytes.drain(..bytes.len() - cap); - } - let _ = tx.send(bytes); - }); - rx - }; - use std::io::Read; // What it answers is kept whole (a listing of every file); what it // says of itself, in part. - let stdout = drain(child.stdout.take().map(|p| Box::new(p) as _), usize::MAX); - let stderr = drain(child.stderr.take().map(|p| Box::new(p) as _), OUTPUT_MAX); + let stdout = + crate::drain::Drain::start(child.stdout.take(), usize::MAX, started, heard.clone()); + let stderr = + crate::drain::Drain::start(child.stderr.take(), OUTPUT_MAX, started, heard.clone()); // Once git has ended normally, what it started is stopped (Unix: // its group; Windows has no group to signal, and nothing is looked // for: a process spawned per git call would cost more than the @@ -572,19 +557,40 @@ impl Git { .saturating_sub(Duration::from_millis(heard.load(Ordering::Relaxed))); if self.cancelled() { killed.set(self.stop(&mut child)); + git_stopped(what, "cancelled", running.0, started.elapsed()); return Err(BackupError::Cancelled(what.to_string())); } if quiet_for > self.quiet { killed.set(self.stop(&mut child)); + git_stopped(what, "quiet", running.0, started.elapsed()); return Err(BackupError::TimedOut(what.to_string())); } std::thread::sleep(Duration::from_millis(20)); }; - // What it started may still hold its pipes: not waited for long. + let ran = started.elapsed(); + // What it started may still hold its pipes: not waited for. Once + // git has ended, what it wrote is in its pipes already; it is read + // to the pipes' end, or, when something else still holds them open + // (a copy a process started at the same moment took, on Windows), + // until nothing is left in them (drain.rs), never for the 10 s + // limit that stays only as the last resort. kill_leftovers(child.id()); - let wait = Duration::from_secs(10); - let stdout = stdout.recv_timeout(wait).unwrap_or_default(); - let stderr = stderr.recv_timeout(wait).unwrap_or_default(); + let ended = Instant::now(); + let [(stdout, out_how), (stderr, err_how)] = + crate::drain::finish([&stdout, &stderr], ended, Duration::from_secs(10)); + git_timing(&GitTiming { + what, + first: args.first().map(|a| a.to_string_lossy().into_owned()), + exit: status + .code() + .map_or_else(|| "signal".to_string(), |c| c.to_string()), + running: running.0, + spawn_took, + ran, + pipes_took: ended.elapsed(), + out: (out_how, stdout.len()), + err: (err_how, stderr.len()), + }); if status.success() { Ok(String::from_utf8_lossy(&stdout).trim().to_string()) } else { @@ -636,12 +642,14 @@ impl Git { } #[cfg(windows)] { - let _ = std::process::Command::new("taskkill") - .args(["/T", "/F", "/PID", &child.id().to_string()]) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status(); + let _ = crate::lock::spawn( + std::process::Command::new("taskkill") + .args(["/T", "/F", "/PID", &child.id().to_string()]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()), + ) + .and_then(|mut k| k.wait()); let _ = child.kill(); let _ = child.wait(); Killed::Gone @@ -649,6 +657,96 @@ impl Git { } } +/// Git commands of this process running now, for [`git_timing`]. +static RUNNING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// One running git command, counted from the moment it is asked for; `.0` +/// is how many (itself included) there were then. +struct Running(usize); + +impl Running { + fn begin() -> Running { + Running(RUNNING.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1) + } +} + +impl Drop for Running { + fn drop(&mut self) { + RUNNING.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + } +} + +/// What one git command did (see [`git_timing`]). +struct GitTiming<'a> { + what: &'a str, + first: Option, + exit: String, + running: usize, + spawn_took: Duration, + ran: Duration, + pipes_took: Duration, + out: (crate::drain::Closed, usize), + err: (crate::drain::Closed, usize), +} + +/// The file `WANDERBOOKS_GIT_TIMINGS` names, if it is set: every git +/// command of this process appends a line to it as it ends (a diagnostic +/// for the tests that run the server on a machine nobody can look at: how +/// long each command ran, and how long its pipes took to close after it +/// ended). Never set by the program itself. +fn timings_file() -> Option<&'static Path> { + static FILE: std::sync::OnceLock> = std::sync::OnceLock::new(); + FILE.get_or_init(|| { + std::env::var_os("WANDERBOOKS_GIT_TIMINGS") + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + }) + .as_deref() +} + +fn timings_line(line: &str) { + use std::io::Write; + static BEGAN: std::sync::OnceLock = std::sync::OnceLock::new(); + let Some(file) = timings_file() else { + return; + }; + let at = BEGAN.get_or_init(Instant::now).elapsed().as_millis(); + if let Ok(mut f) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(file) + { + let _ = writeln!(f, "+{at}ms {line}"); + } +} + +fn git_timing(t: &GitTiming<'_>) { + if timings_file().is_none() { + return; + } + timings_line(&format!( + "git {} {} exit={} running={} spawn={}ms ran={}ms pipes={}ms stdout={}:{}B stderr={}:{}B", + t.what, + t.first.as_deref().unwrap_or(""), + t.exit, + t.running, + t.spawn_took.as_millis(), + t.ran.as_millis(), + t.pipes_took.as_millis(), + t.out.0.word(), + t.out.1, + t.err.0.word(), + t.err.1, + )); +} + +fn git_stopped(what: &str, why: &str, running: usize, ran: Duration) { + timings_line(&format!( + "git {what} stopped={why} running={running} ran={}ms", + ran.as_millis() + )); +} + /// The most kept of what a git says of itself. const OUTPUT_MAX: usize = 1 << 20; diff --git a/crates/ledger-store/src/drain.rs b/crates/ledger-store/src/drain.rs new file mode 100644 index 00000000..eda2bc92 --- /dev/null +++ b/crates/ledger-store/src/drain.rs @@ -0,0 +1,370 @@ +//! Reading what a child process says, without waiting on a pipe it doesn't +//! hold (P11c, found on Windows in the open/close hammer). +//! +//! ```text +//! GOAL: the output of a child that has ended is in hand once everything +//! it wrote has been read, however long some other process keeps the +//! other end of its pipe open. +//! SOURCE: the standard library's `Command` (Windows: `CreateProcessW` with +//! `bInheritHandles`, the child's end of each pipe inheritable from +//! the moment it is made until the parent closes it, so a process +//! started by another thread in that moment holds a copy and the +//! pipe has no end-of-file until that process ends too); found by +//! the open/close hammer on Windows (plan/p15-app-and-relay.md +//! 3.1, D-77). +//! INVARIANTS: +//! 1. Nothing a child wrote is lost: bytes already in the pipe when the +//! child ended are read before the reader is let go (the pipe is asked +//! what it holds; the reader is let go only when it is blocked in its +//! read with nothing in the pipe, for QUIET together). +//! 2. The reader is let go when the pipe reaches its end (every writer +//! gone), or when it is idle as in 1, or after `limit`, whichever is +//! first; which one is reported ([`Closed`]). +//! 3. A reader let go while still blocked ends by itself when the last +//! holder of the pipe's other end lets go; it holds nothing else. +//! ``` + +use std::io::Read; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// How long a reader must be seen blocked in its read, with nothing in the +/// pipe, before it is let go (INVARIANT 1): longer than any thread waits to +/// run after it has been handed a byte. +pub(crate) const QUIET: Duration = Duration::from_millis(100); + +/// How long a reader in its read, with no read returning, is waited for when +/// the pipe can't say whether it holds anything. +const BLIND: Duration = Duration::from_millis(1500); + +/// How the wait for a pipe ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Closed { + /// The pipe reached its end: every writer was gone. + Eof, + /// Something else still held the pipe's other end, and nothing was left + /// in it to read. + Idle, + /// The limit passed first; what had been read is what is returned. + Limit, +} + +impl Closed { + pub(crate) fn word(self) -> &'static str { + match self { + Closed::Eof => "eof", + Closed::Idle => "held-open", + Closed::Limit => "limit", + } + } +} + +/// A pipe being read on its own thread. +pub(crate) struct Drain { + bytes: Arc>>, + /// True while the pipe is open (its reader hasn't ended): guards the + /// raw descriptor or handle asked about below. + open: Arc>, + /// True from just before the reader calls `read` until it returns. + reading: Arc, + /// How many reads have returned. + reads: Arc, + raw: usize, + cap: usize, +} + +/// The raw descriptor (Unix) or handle (Windows) of a pipe, as a number. +pub(crate) trait Raw { + fn raw(&self) -> usize; +} + +#[cfg(unix)] +impl Raw for T { + fn raw(&self) -> usize { + self.as_raw_fd() as usize + } +} + +#[cfg(windows)] +impl Raw for T { + fn raw(&self) -> usize { + self.as_raw_handle() as usize + } +} + +/// How many bytes `pipe` holds now, if that can be asked: `None` when it +/// can't (the pipe is at its end, or the question failed), which is never +/// taken as "nothing". +fn pending(raw: usize) -> Option { + #[cfg(unix)] + { + let mut fd = libc::pollfd { + fd: raw as libc::c_int, + events: libc::POLLIN, + revents: 0, + }; + // SAFETY: one valid pollfd, and no wait. + let ready = unsafe { libc::poll(&mut fd, 1, 0) }; + // Anything else is readable, or hung up (end of file), or failed: + // never "nothing". + if ready == 0 { Some(0) } else { None } + } + #[cfg(windows)] + { + use windows_sys::Win32::System::Pipes::PeekNamedPipe; + let mut available: u32 = 0; + // SAFETY: `raw` is a pipe handle that stays open while `open` is + // held (the reader closes it only under that lock); no buffer is + // asked for, only the count. + let ok = unsafe { + PeekNamedPipe( + raw as *mut core::ffi::c_void, + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + &mut available, + std::ptr::null_mut(), + ) + }; + if ok == 0 { + None + } else { + Some(available as usize) + } + } +} + +impl Drain { + /// Start reading `pipe` (if any) on a thread of its own, keeping the + /// last `cap` bytes; `heard` is set to the milliseconds since `started` + /// whenever a byte arrives. + pub(crate) fn start

( + pipe: Option

, + cap: usize, + started: Instant, + heard: Arc, + ) -> Drain + where + P: Read + Raw + Send + 'static, + { + let bytes = Arc::new(Mutex::new(Vec::new())); + let open = Arc::new(Mutex::new(pipe.is_some())); + let reading = Arc::new(AtomicBool::new(false)); + let reads = Arc::new(AtomicU64::new(0)); + let raw = pipe.as_ref().map_or(0, Raw::raw); + let (b, o, r, n_reads) = (bytes.clone(), open.clone(), reading.clone(), reads.clone()); + if let Some(mut p) = pipe { + std::thread::spawn(move || { + let mut buf = [0u8; 8192]; + loop { + r.store(true, Ordering::SeqCst); + let got = p.read(&mut buf); + r.store(false, Ordering::SeqCst); + n_reads.fetch_add(1, Ordering::SeqCst); + match got { + Ok(0) => break, + Ok(n) => { + heard.store(started.elapsed().as_millis() as u64, Ordering::Relaxed); + // Bounded: a git that says this much is kept + // only in part, its last part (where its + // errors are). + let mut bytes = b.lock().unwrap_or_else(|e| e.into_inner()); + bytes.extend_from_slice(&buf[..n]); + if bytes.len() > cap.saturating_mul(2) { + let cut = bytes.len() - cap; + bytes.drain(..cut); + } + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(_) => break, + } + } + // Closed under the lock the question above is asked under, + // so a descriptor that is gone is never asked about. + let mut open = o.lock().unwrap_or_else(|e| e.into_inner()); + *open = false; + drop(p); + }); + } + Drain { + bytes, + open, + reading, + reads, + raw, + cap, + } + } + + /// Whether the pipe has reached its end. + fn ended(&self) -> bool { + !*self.open.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Whether the reader is blocked in its read with nothing in the pipe; + /// when the pipe can't say what it holds, whether the reader is in its + /// read (`None` is returned for the caller to weigh against time). + fn idle(&self) -> Option { + let open = self.open.lock().unwrap_or_else(|e| e.into_inner()); + if !*open || !self.reading.load(Ordering::SeqCst) { + return Some(false); + } + pending(self.raw).map(|n| n == 0) + } + + /// What has been read, in whole (the last `cap` bytes of it). + fn taken(&self) -> Vec { + let mut bytes = self.bytes.lock().unwrap_or_else(|e| e.into_inner()); + if bytes.len() > self.cap { + let cut = bytes.len() - self.cap; + bytes.drain(..cut); + } + std::mem::take(&mut *bytes) + } +} + +/// Wait, until `limit` after `since`, for every one of `drains` to reach +/// its end or to be idle (INVARIANT 1 and 2), then take what each read: the +/// bytes, and how its wait ended. +pub(crate) fn finish( + drains: [&Drain; N], + since: Instant, + limit: Duration, +) -> [(Vec, Closed); N] { + // When each reader was first seen blocked in its read (with nothing in + // the pipe, or the pipe unable to say), and the reads it had made then. + let mut idle_since: [Option; N] = [None; N]; + let mut blind_since: [Option<(Instant, u64)>; N] = [None; N]; + let mut how: [Option; N] = [None; N]; + loop { + let now = Instant::now(); + for (i, d) in drains.iter().enumerate() { + if how[i].is_some() { + continue; + } + if d.ended() { + how[i] = Some(Closed::Eof); + } else { + match d.idle() { + Some(true) => { + let since = *idle_since[i].get_or_insert(now); + if now.duration_since(since) >= QUIET { + how[i] = Some(Closed::Idle); + } + } + Some(false) => { + idle_since[i] = None; + blind_since[i] = None; + } + // The pipe can't say what it holds: the reader in its + // read, with no read returning for BLIND, is idle (a + // reader is never kept from a byte for that long). + None => { + let reads = d.reads.load(Ordering::SeqCst); + let (since, was) = *blind_since[i].get_or_insert((now, reads)); + if was != reads { + blind_since[i] = Some((now, reads)); + } else if now.duration_since(since) >= BLIND { + how[i] = Some(Closed::Idle); + } + } + } + } + } + if how.iter().all(Option::is_some) { + break; + } + if now.duration_since(since) >= limit { + break; + } + std::thread::sleep(Duration::from_millis(2)); + } + // An end reached in the instant before this is read: its last bytes + // are in, the reader having stored them before it ended. + std::array::from_fn(|i| (drains[i].taken(), how[i].unwrap_or(Closed::Limit))) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::process::{Command, Stdio}; + + fn drained(child: &mut std::process::Child) -> (Drain, Drain) { + let heard = Arc::new(AtomicU64::new(0)); + let now = Instant::now(); + ( + Drain::start(child.stdout.take(), usize::MAX, now, heard.clone()), + Drain::start(child.stderr.take(), 1 << 20, now, heard), + ) + } + + /// INVARIANT 1 and 2. A child that ends, leaving a grandchild that + /// still holds its pipes (the Windows leak, made by hand), has its + /// whole output read, and the wait ends in far less than the limit. + #[test] + fn a_pipe_another_process_still_holds_is_read_in_whole_without_waiting_for_it() { + let mut child = Command::new("sh") + .arg("-c") + .arg("echo out-one; echo err-one >&2; (sleep 5 = RwLock::new(()); /// Start `command`: returns once the child has exec'd (or failed to), so /// from then on it holds no copy of any descriptor of this process. +/// +/// On Windows one spawn runs at a time (INVARIANT 5): the standard library +/// makes the child's end of each pipe inheritable when it makes the pipe, +/// and starts the child with every inheritable handle of the process, so a +/// process started by another thread in that moment holds a copy of it too. +/// A pipe whose other end is so held has no end-of-file when its own child +/// ends, until the process that took the copy ends. pub fn spawn(command: &mut Command) -> std::io::Result { + #[cfg(windows)] + let _spawning = SPAWNING.write().unwrap_or_else(|e| e.into_inner()); + #[cfg(not(windows))] let _spawning = SPAWNING.read().unwrap_or_else(|e| e.into_inner()); command.spawn() }