Cotton code
240 lines · 9.2 KB · RustRaw
//! **THE HELPER WATCHES ITS OWN EXECUTABLE**, and restarts onto a new one.//!//! The 2026-09-22 failure this module exists for, measured on one Mac: the app//! updated to 0.9.3 at 04:43 under Sparkle, and `cotton-session-host serve`//! (started 19 September) went on running the binary the update had already//! replaced. `KeepAlive` is what makes the helper outlive the app — and on its//! own it is also what makes a stale helper permanent, because nothing ever//! ends the process launchd would relaunch. The helper reported//! `hostVersion: "0.1.0"` and `agents: {}` for three days on a Mac whose//! bundle had carried the login-shell fix since the morning.//!//! The design says the helper "survives app restarts and Sparkle updates"//! (Cotton note "The Code tool — why a Mac holds the sessions"). It survives them by RESTARTING onto the//! new binary, not by staying on the old one.//!//! **IDENTITY IS THE FILE, NOT THE VERSION.** At `serve` start the helper//! records the size and modification time of its own executable — the path//! `std::env::current_exe()` resolves, which is absolute even though launchd's//! `ProgramArguments[0]` is bundle-relative. A Sparkle update replaces the//! whole bundle, so the file at that same path is a different file, and the//! difference is visible without reading a byte of it. A version string would//! miss a rebuild at the same version; a content hash would read megabytes off//! the disk every minute for an answer `stat(2)` already gives.//!//! **A LIVE SESSION OUTRANKS AN UPDATE.** Exiting while a person's `claude` is//! mid-turn would end that turn — a restart of this daemon ends its children//! (`PROTOCOL.md`). So a helper whose binary changed while sessions are alive//! DEFERS: it says `update_pending` in every sample, keeps checking, and exits//! the moment the last host-owned session ends.use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};/// How often `serve` re-reads its own executable.////// A minute. The cost is one `stat(2)`; the thing being waited for is a person/// noticing their Mac is running last week's helper, which on one Mac took/// three days.pub const CHECK_EVERY_SECONDS: u64 = 60;/// What a file looks like without opening it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct Fingerprint {    /// Bytes.    pub size: u64,    /// Modification time, whole seconds since the epoch.    pub modified_secs: i64,}impl Fingerprint {    /// The short string a sample carries and a log line prints.    ///    /// Hex, and two numbers rather than a digest: the only question anybody    /// asks of it is "is this the same one", and a reader comparing a helper's    /// answer with the bundle's wants to see two strings, not to trust a hash    /// nothing here computes.    pub fn short(self) -> String {        format!("{:x}-{:x}", self.size, self.modified_secs)    }}/// Read a file's fingerprint. `None` when it cannot be stat'ed at all —/// which, for this module's own executable, means a Sparkle update has the/// path open mid-swap or the bundle is gone.pub fn read(path: &Path) -> Option<Fingerprint> {    let meta = std::fs::metadata(path).ok()?;    let modified = meta        .modified()        .ok()        .and_then(|at| at.duration_since(std::time::UNIX_EPOCH).ok())        .map(|since| since.as_secs() as i64)        .unwrap_or(0);    Some(Fingerprint {        size: meta.len(),        modified_secs: modified,    })}/// What one check decided.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Verdict {    /// The executable is the one this process started from. Carry on.    Keep,    /// It is not, and no host-owned session would be ended by going. Exit 0    /// and let `KeepAlive` start the new one.    Exit,    /// It is not, but sessions are alive. Say so, and check again.    Defer,}/// **THE DECISION.** Pure, so every arm is a test rather than a Sparkle run.////// `at_start` is `None` on a helper that could not fingerprint itself when it/// started — a path it cannot stat, a filesystem that answers nothing. That/// helper never exits on a guess: there is nothing to compare, so the verdict/// is `Keep` whatever the file says now.pub fn verdict(    at_start: Option<Fingerprint>,    now: Option<Fingerprint>,    sessions_alive: u32,) -> Verdict {    let Some(at_start) = at_start else {        return Verdict::Keep;    };    // `now` absent is a CHANGE, deliberately: the executable this process was    // started from is not at its path any more, and the only way back to a    // helper anybody can reason about is a fresh one.    if now == Some(at_start) {        return Verdict::Keep;    }    if sessions_alive == 0 {        Verdict::Exit    } else {        Verdict::Defer    }}/// The two fields a [`crate::protocol::MachineSample`] carries about this/// helper's own binary.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct SelfReport {    /// The fingerprint recorded at `serve` start, empty when there is none.    pub fingerprint: String,    /// Whether this helper is waiting for its sessions to end so it can    /// restart onto a new binary.    pub update_pending: bool,}/// The helper's own executable, and what it has decided about it.////// Held by the daemon and read by every sample, which is why the pending flag/// is an atomic rather than a field behind the state lock: a sample must never/// queue behind a terminal's bytes to answer a boolean.#[derive(Debug)]pub struct Watch {    path: PathBuf,    at_start: Option<Fingerprint>,    pending: AtomicBool,}impl Watch {    /// Record what this executable is, now.    pub fn of(path: impl Into<PathBuf>) -> Watch {        let path = path.into();        let at_start = read(&path);        Watch {            path,            at_start,            pending: AtomicBool::new(false),        }    }    /// A watch over a path that is never read — what a test that is about    /// something else gets, and what a host built with no executable behind it    /// gets. Its verdict is always [`Verdict::Keep`].    pub fn unwatched() -> Watch {        Watch {            path: PathBuf::new(),            at_start: None,            pending: AtomicBool::new(false),        }    }    /// Where the executable is.    pub fn path(&self) -> &Path {        &self.path    }    /// The fingerprint this helper started from, as the sample spells it.    pub fn fingerprint(&self) -> String {        self.at_start.map(Fingerprint::short).unwrap_or_default()    }    /// Whether a restart is waiting on the sessions.    pub fn update_pending(&self) -> bool {        self.pending.load(Ordering::SeqCst)    }    /// What the sample carries.    pub fn report(&self) -> SelfReport {        SelfReport {            fingerprint: self.fingerprint(),            update_pending: self.update_pending(),        }    }    /// Read the file again and decide, remembering a deferral.    pub fn check(&self, sessions_alive: u32) -> Verdict {        let verdict = verdict(self.at_start, read(&self.path), sessions_alive);        self.pending            .store(matches!(verdict, Verdict::Defer), Ordering::SeqCst);        verdict    }    /// Remember that a restart is waiting on the sessions.    ///    /// What a `restart` REQUEST sets when it is deferred: the asker decided    /// this helper is stale, and every sample says so until the last session    /// ends — the minute timer would only say it once the file itself differs,    /// which is the same fact arriving by the other road.    pub fn defer(&self) {        self.pending.store(true, Ordering::SeqCst);    }    /// The line a verdict writes down.    ///    /// Pure, so the sentence is a test. Written when the verdict CHANGES —    /// this runs every minute for weeks, and `the executable is unchanged`    /// sixty times an hour would be the only thing in the log.    pub fn line(&self, verdict: Verdict, sessions_alive: u32) -> String {        match verdict {            // TWO READINGS OF ONE VERDICT, and the log says which. `Keep` is            // "the same file" when there is a fingerprint to compare and "no            // comparison is possible" when there is not — and the second is a            // helper that will never restart itself, which an operator must            // be able to read off the log rather than infer from silence.            Verdict::Keep if self.at_start.is_none() => format!(                "binary — this host cannot read its own executable at {}; it will not restart itself onto an update",                self.path.display()            ),            Verdict::Keep => format!(                "binary — {} ({}), unchanged since this host started",                self.path.display(),                self.fingerprint()            ),            Verdict::Exit => format!(                "binary — {} was replaced and no session is running; exiting so launchd starts the new one",                self.path.display()            ),            Verdict::Defer => format!(                "binary — {} was replaced, but {sessions_alive} session(s) are running; restarting when the last one ends",                self.path.display()            ),        }    }}#[cfg(test)]#[path = "binary_tests.rs"]mod binary_tests;