From 045211e212f507c19f357b4b447b3a7d9f7c3b58 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 22 Nov 2026 17:20:56 -0700 Subject: [PATCH] fix(host): a start that loses to a live app server says so; the window's close keeps one 90 s deadline Two copies of the app started at once left the loser showing 'starting' for ever: its server waited on the other's lock. The wait now gives up when another app's live server has held the books for two seconds, stops its own child, and says another program has them. A server that is closing is still waited for, and a missing info file never counts, so the app's own server cannot be taken for another. The window's close passes what remains of its 90 seconds to each step (it could reach about 185), and a close that panics leaves a notice. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/app_server.rs | 94 +++++++++++++++++++++++++++ crates/ledger-host/src/app_server.rs | 87 +++++++++++++++++++++---- docs/delegation-log.md | 1 + 3 files changed, 169 insertions(+), 13 deletions(-) diff --git a/crates/ledger-cli/tests/app_server.rs b/crates/ledger-cli/tests/app_server.rs index bed9e0dd..3ff3d70e 100644 --- a/crates/ledger-cli/tests/app_server.rs +++ b/crates/ledger-cli/tests/app_server.rs @@ -761,6 +761,100 @@ fn a_server_that_never_gets_ready_is_stopped_with_the_window_and_not_left_behind until("the server's process is gone", || !alive(pid)); } +/// A start that loses the race (a second window, two starts at once) +/// does not wait on the other's lock for ever: it stops its own child and +/// says, in words, that another program has the books. +#[cfg(unix)] +#[test] +fn a_start_that_loses_the_race_says_another_has_the_books() { + let home = Home::new("host-lost-race"); + // A child that never takes the lock, as one waiting behind another's + // would not have: alive until its input closes. + let waiting = script( + home.dir.path(), + "waiting", + "#!/bin/sh\ncat >/dev/null\nexit 0\n", + ); + let loser = AppServer::start_in(&waiting, Some(&home.root()), &[], |_| {}).unwrap(); + let pid = loser.pid(); + // Another books server takes the books after the loser's look. + let other = Server::start_with(&home, &["--started-by", "app", "--open", "none"]); + let (said, heard) = mpsc::channel(); + let waiter = std::thread::spawn(move || { + said.send(loser.wait_started(Duration::from_millis(100))) + .ok(); + loser + }); + let answer = heard + .recv_timeout(Duration::from_secs(30)) + .expect("the loser stopped waiting"); + assert_eq!(answer, Err(ANOTHER_HAS_THEM.to_string())); + let loser = waiter.join().unwrap(); + until("the loser's child is gone", || !alive(pid)); + assert!(loser.exited().is_some()); + // The other one is untouched. + assert!(server_lock_held(&home.run())); + other.close(); +} + +/// A start while the books of the window just closed are still being +/// backed up is waited for, not told "another has them": the old server +/// says it is closing, and the new start goes on once it is gone. +#[cfg(unix)] +#[test] +fn a_start_behind_a_closing_server_waits_for_it() { + let home = Home::new("host-behind-closing"); + let run = home.run(); + let waiting = script( + home.dir.path(), + "waiting", + "#!/bin/sh\ncat >/dev/null\nexit 0\n", + ); + let later = AppServer::start_in(&waiting, Some(&home.root()), &[], |_| {}).unwrap(); + // The old server: the lock held, under another pid, saying it closes. + let lock = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(run.join("server.lock")) + .unwrap(); + lock.lock().unwrap(); + std::fs::write( + run.join("server.info"), + format!( + r#"{{"by":"app","pid":{},"closing":true}}"#, + std::process::id() + 1 + ), + ) + .unwrap(); + let later = std::sync::Arc::new(later); + let (said, heard) = mpsc::channel(); + let waiter = std::thread::spawn({ + let later = later.clone(); + move || { + said.send(later.wait_started(Duration::from_millis(100))) + .ok() + } + }); + // Well past the time a live holder would have beaten it. + assert!( + heard.recv_timeout(Duration::from_millis(3500)).is_err(), + "a closing server is waited for" + ); + // The window ends the wait by stopping its own server: the start then + // ends because its server is gone, not because another had the books. + later.stop(Duration::from_secs(30)); + let answer = heard + .recv_timeout(Duration::from_secs(30)) + .expect("the wait ended"); + assert!( + answer.as_ref().is_err_and(|why| why != ANOTHER_HAS_THEM), + "{answer:?}" + ); + waiter.join().unwrap(); + drop(lock); +} + /// The window closes after the child was spawned and before the start /// stored it (finding: the window closed before the start thread stored /// the child): the start stops it itself. diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs index f63e9997..433c0823 100644 --- a/crates/ledger-host/src/app_server.rs +++ b/crates/ledger-host/src/app_server.rs @@ -123,6 +123,15 @@ pub const STOP_WAIT: Duration = Duration::from_secs(90); /// taken them, is seen before this one is taken to have lost the race. const BEATEN_AFTER: Duration = Duration::from_millis(300); +/// How long the same live program must hold the books, against a start +/// being waited for, before that start is taken to have lost: well past +/// the moment between a server taking the lock and saying what it is, or +/// a stale word of a server that crashed being replaced. +const LOST_AFTER: Duration = Duration::from_secs(2); + +/// How often a start that is waited for is checked for having lost. +const BEATEN_LOOK: Duration = Duration::from_millis(50); + /// What [`AppServer::wait_ready_unless_beaten`] came to. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Waited { @@ -511,18 +520,65 @@ impl AppServer { matches!(&*self.shared.phase(), Phase::Ready) } + /// Whether the books are held by a program that is up and serving and + /// is not this server: a host (`wanderbooks serve`), or another app's + /// server that says so and is not closing. What is only finishing (a + /// server that has begun to close, a host's orphan, one a command is + /// running for the length of its work) is not that: it ends by itself, + /// and this server waits for it. Nor is a lock held with no word + /// readable, or with the word of one that is gone: that is the moment + /// before this server says what it is, or an earlier build's. Each is + /// waited for; none counts as another's. + fn another_serves(&self) -> Option { + if host_lock_held(&self.run) { + // A host's own pid is not known here: a changing holder is + // not told apart, and a host lock held does not come from + // this child, which takes only the server's. + return Some(0); + } + if !server_lock_held(&self.run) { + return None; + } + let info = ledger_mcp::local::read_server_info(&self.run)?; + (info.by == StartedBy::App && !info.closing && info.pid != self.pid).then_some(info.pid) + } + /// Wait for the server to be ready for as long as it lives: a server /// still opening companies, or waiting for another server to finish /// (local.rs INVARIANT 1), is waited for and not given up on; `Err` - /// only when it has exited (INVARIANT 8). `slice` is how long each - /// wait runs before the server is looked at again. + /// only when it has exited (INVARIANT 8), or when a host or another + /// live app server has held the books for [`LOST_AFTER`], the same + /// one all that time (the start lost the race: a second window, two + /// starts at once): this server is then stopped and the words are + /// [`ANOTHER_HAS_THEM`]. A server that is only finishing, a closing + /// backup of the window just closed included, is waited for. `slice` + /// is how long each wait runs before the server is looked at again. pub fn wait_started(&self, slice: Duration) -> Result<(), String> { + let mut beaten: Option<(u32, Instant)> = None; loop { - match self.wait_ready(slice) { + // Looked at often, whatever `slice` is: whether another + // program holds the books is read between the waits. + match self.wait_ready(slice.min(BEATEN_LOOK)) { Ok(()) => return Ok(()), Err(_) if self.exited().is_none() => {} Err(why) => return Err(why), } + match self.another_serves() { + Some(pid) => { + let (held, since) = beaten.get_or_insert((pid, Instant::now())); + if *held != pid { + (*held, *since) = (pid, Instant::now()); + } + if since.elapsed() >= LOST_AFTER { + // This child only waits on the other's lock. Its + // input is closed, which ends it without touching + // anything. + self.stop(FAILED_START_STOP_WAIT); + return Err(ANOTHER_HAS_THEM.into()); + } + } + None => beaten = None, + } } } @@ -998,7 +1054,7 @@ impl AppHost { /// Close the window's books (INVARIANT 9): each open company is closed /// first, so its closing backup is reported if it was not whole; then /// the server's input is closed and its exit waited for, the whole - /// taking about `within`. `Ok(None)` when all went whole; else the + /// taking at most `within` in all. `Ok(None)` when all went whole; else the /// words, a line each (the companies whose backup was incomplete, a /// server that exited badly or is still closing). Never kills. pub fn stop(&self, within: Duration) -> Result, String> { @@ -1007,10 +1063,13 @@ impl AppHost { let Some(server) = self.slot().take() else { return Ok(None); }; - let begun = Instant::now(); + // One deadline for the whole close (WB-app-4): every step gets + // what is left of it. + let deadline = Instant::now() + within; + let remaining = || deadline.saturating_duration_since(Instant::now()); let mut said: Vec = Vec::new(); if server.is_ready() && server.exited().is_none() { - match server.books(Some(within)) { + match server.books(Some(remaining())) { Ok(books) => { let open: Vec = books.into_iter().filter(|b| b.open).map(|b| b.id).collect(); @@ -1020,9 +1079,9 @@ impl AppHost { let handles: Vec<_> = open .iter() .map(|id| { - let server = &server; + let (server, remaining) = (&server, &remaining); scope.spawn(move || { - match server.close_book_within(id, Some(within)) { + match server.close_book_within(id, Some(remaining())) { Ok(notice) => notice, Err(why) => { Some(format!("{id} could not be closed cleanly: {why}")) @@ -1033,7 +1092,12 @@ impl AppHost { .collect(); handles .into_iter() - .map(|h| h.join().unwrap_or(None)) + .zip(open.iter()) + .map(|(h, id)| { + h.join().unwrap_or_else(|_| { + Some(format!("{id} could not be closed cleanly: the close stopped unexpectedly")) + }) + }) .collect() }); said.extend(notices.into_iter().flatten()); @@ -1043,10 +1107,7 @@ impl AppHost { )), } } - let left = within - .saturating_sub(begun.elapsed()) - .max(Duration::from_secs(5)); - match server.stop(left) { + match server.stop(remaining()) { Stopped::Closed => {} Stopped::Failed(how) => said.push(format!( "The books server ended badly ({how}). Its log is {SERVER_LOG} in the books' run folder; `wanderbooks doctor` says whether the books are whole." diff --git a/docs/delegation-log.md b/docs/delegation-log.md index be1a5107..a756359e 100644 --- a/docs/delegation-log.md +++ b/docs/delegation-log.md @@ -96,3 +96,4 @@ Columns: date | type (scout, run/verify, implement, refactor, debug, review) | p - 2026-11-21 | debug 2 | sonnet (high) | a phone number refused as a tax id; the burst-close test | accepted: phones and ZIP+4 kept, the test's assumption fixed; rerun after merge - 2026-11-21 | debug 3 | sonnet (high) | two Windows-only failures (authority list change detection; the assistant pictures) | accepted: rerun after merge; the Windows hash was reproduced on Linux with the dock held back - 2026-11-22 | impl-multi 2 | sonnet | the relay's setup kit for a Vultr machine; CAA at the relay's own name so its certificate renews | accepted: hunk read, relay tests rerun +- 2026-11-22 | read 2 + impl 2 | sonnet | a late review of the app's server rechecked on main; the lost-race start, the 90 s close deadline, a panicked close's notice | accepted after one send-back: a closing holder is waited for, missing info never counts