fix(host): what holds the books is known, not guessed; a command joins what starts beside it

Plan P15 unit A5, fix round. A server answering its admin socket with no host
over it was taken to be "the app". Three wrong outcomes followed: a `serve`
started while a killed host's server was still finishing its last backup was
told "the app has these books open" and exited, `close` and `doctor` said "the
app" during such a close, and a command attached to another command's short-lived
server as if it were the app (refused "not open" for another company, or its
server closed under the other).

A server now says what it is. `wanderbooks server --started-by app|host|command`
writes run/server.info beside its lock (who started it, its pid, whether it has
begun to close), moved into place whole as soon as the lock is its, rewritten
`closing` the moment it is told to close, removed just before the lock goes. It
is read only while the lock is held, which is when it is the lock holder's. A
file beside the lock, not a field in the admin hello: it also covers a server
that has no admin socket yet (opening) and costs the older admin protocol
nothing. A server that says nothing (an earlier build's) is taken for the app's,
as before. `opener::what_holds` reads it: only a server the app started, not
closing and answering, is the app. A command's server, or one that is closing
(the app's, or the orphan of a host that went), is waited for, said in words,
bounded by `open_wait` (a bridge waits as long as its session does), and the
holder or command goes on once it is gone. `close`, `doctor` and the bridge say
the true thing for each.

A command racing another program's start no longer fails with "close it" or waits
silently 300 s: if its own server loses the lock to a program that started after
its look, it lets its start go and joins what runs (`wait_ready_unless_beaten`,
`reach`), inside one `open_wait`.

A command's own server is started clean, as a host is: the host's environment
only, the root as an absolute path, `/` as its folder (Windows: `run/`), and
every server closes the descriptors above 2 at its start, so one that outlives
its command (still closing after 90 s) holds none of the invoker's pipes. The
app's own child keeps its environment: it is the window's child, closes with the
window and needs the user's session (ssh agent, git configuration) for backups;
it too loses stray descriptors, since the server does that for any starter.

Test knobs: `--start-delay` (a server's slow start) and `timer_hold=1` for a
command's own server, following `--timer-hold`.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 12:12:28 -07:00
1 parent 6b95ce59ad
commit 2ff2913274
9 files changed
+598 -80

No files matched your search

+118 -2
View File
@@ -80,6 +80,7 @@
use crate::host::{SERVER_LOG, children_executable, open_log};
use crate::opener::{host_lock_held, server_lock_held};
use ledger_mcp::admin::{self, CloseOutcome, OpenOutcome, Request, Response};
pub use ledger_mcp::local::StartedBy;
use ledger_store::root::Root;
use std::io::BufRead;
use std::path::{Path, PathBuf};
@@ -102,6 +103,19 @@ pub const READY_WAIT: Duration = Duration::from_secs(300);
/// and running calls finish first.
pub const STOP_WAIT: Duration = Duration::from_secs(90);
/// How long another program holding the books, while this server has not
/// taken them, is seen before this one is taken to have lost the race.
const BEATEN_AFTER: Duration = Duration::from_millis(300);
/// What [`AppServer::wait_ready_unless_beaten`] came to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Waited {
/// The server is ready.
Ready,
/// Another program took the books first.
Beaten,
}
/// What a refused start says (INVARIANT 1).
pub const ANOTHER_HAS_THEM: &str = "Another program has these books open: another Wanderbooks window, `wanderbooks serve`, or a books server that is still finishing its last backup. Close it (`wanderbooks close` closes the books) or wait a moment, then start Wanderbooks again.";
@@ -217,7 +231,7 @@ pub struct AppServer {
/// now: no host holds the root, a server does, and its admin socket
/// answers (INVARIANT 7).
pub fn the_apps_server_runs(run: &Path) -> bool {
!host_lock_held(run) && server_lock_held(run) && crate::opener::admin_answers(run) == Ok(true)
crate::opener::what_holds(run) == Ok(crate::opener::Holder::App)
}
impl AppServer {
@@ -229,6 +243,38 @@ impl AppServer {
Self::start_in(&children_executable(), root, open, |_| {})
}
/// The server of a command that does its own work with nothing else
/// running (commands.rs `reach`): the same server, started clean as a
/// host starts it (INVARIANT 13), saying it is a command's.
pub fn start_for_command(
root: Option<&Path>,
open: &[String],
knobs: &crate::knobs::Knobs,
) -> Result<Self, String> {
let d = crate::knobs::Knobs::default();
Self::start_as(
&children_executable(),
root,
open,
StartedBy::Command,
|command| {
// The timings a test shortened, as the host passes them on.
for (flag, now, default) in [
("--backup-quiet", knobs.backup_quiet, d.backup_quiet),
("--drill-first", knobs.drill_first, d.drill_first),
("--start-delay", knobs.server_delay, d.server_delay),
] {
if now != default {
command.arg(flag).arg(now.as_millis().to_string());
}
}
if knobs.timer_hold {
command.arg("--timer-hold");
}
},
)
}
/// [`AppServer::start`] from the program `exe`, `configure` having the
/// last word on its command (tests give it an environment of its own).
pub fn start_in(
@@ -236,6 +282,19 @@ impl AppServer {
root: Option<&Path>,
open: &[String],
configure: impl FnOnce(&mut Command),
) -> Result<Self, String> {
Self::start_as(exe, root, open, StartedBy::App, configure)
}
/// [`AppServer::start_in`] for a server started `by` the app or a
/// command, which it says of itself (`--started-by`, INVARIANT 13).
/// A command's is started clean (INVARIANT 13).
pub fn start_as(
exe: &Path,
root: Option<&Path>,
open: &[String],
by: StartedBy,
configure: impl FnOnce(&mut Command),
) -> Result<Self, String> {
let found = Root::find(root).map_err(|e| e.to_string())?;
let run = found.run_dir().map_err(|e| e.to_string())?;
@@ -259,7 +318,20 @@ impl AppServer {
command.process_group(0);
}
command.arg("server");
if let Some(root) = root {
command.arg("--started-by").arg(by.flag());
if by == StartedBy::Command {
// Nothing of the invoker's reaches a server that may outlive
// the command (INVARIANT 13): the host's environment, and a
// folder of its own to stand in (the root's absolute path
// goes on, as the host's does). Its descriptors are closed by
// the server itself at its start.
command.arg("--root").arg(found.path());
crate::start::clean_environment(&mut command)?;
#[cfg(unix)]
command.current_dir("/");
#[cfg(windows)]
command.current_dir(&run);
} else if let Some(root) = root {
command.arg("--root").arg(root);
}
command.arg("--open").arg(open_argument(open));
@@ -364,6 +436,50 @@ impl AppServer {
}
}
/// Wait for the server to be ready, up to `within`, but not for
/// another program that took the books first: if, while this server
/// is not ready, a host or another server holds them (a command racing
/// the app's start, or `serve`'s), this one has lost the race and the
/// caller is to join what runs (commands.rs `reach`). Seen for as long
/// as [`BEATEN_AFTER`], so the moment between this server taking the
/// lock and saying so is not taken for losing.
pub fn wait_ready_unless_beaten(&self, within: Duration) -> Result<Waited, String> {
let deadline = Instant::now() + within;
let mut beaten_since: Option<Instant> = None;
loop {
let slice = Duration::from_millis(50).min(
deadline
.checked_duration_since(Instant::now())
.unwrap_or_default(),
);
match self.wait_ready(slice) {
Ok(()) => return Ok(Waited::Ready),
Err(why) if self.exited().is_some() => return Err(why),
Err(why) => {
if Instant::now() >= deadline {
return Err(why);
}
}
}
if self.another_holds() {
let since = *beaten_since.get_or_insert_with(Instant::now);
if since.elapsed() >= BEATEN_AFTER {
return Ok(Waited::Beaten);
}
} else {
beaten_since = None;
}
}
}
/// Whether a host, or a server that is not this one, holds the books.
fn another_holds(&self) -> bool {
host_lock_held(&self.run)
|| (server_lock_held(&self.run)
&& ledger_mcp::local::read_server_info(&self.run)
.is_none_or(|info| info.pid != self.pid))
}
/// Whether the server has said it is ready (and is still there).
pub fn is_ready(&self) -> bool {
matches!(&*self.shared.phase(), Phase::Ready)