The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(marker): zombie-aware stale-marker self-heal parity across all readers
Brooklyn Nicholson0590ab25fe6b
diff --git a/apps/bootstrap-installer/src-tauri/src/update.rs b/apps/bootstrap-installer/src-tauri/src/update.rsindex d028ea755c9..fc620db7afd 100644--- a/apps/bootstrap-installer/src-tauri/src/update.rs+++ b/apps/bootstrap-installer/src-tauri/src/update.rs@@ -250,6 +250,26 @@ fn pid_is_alive(pid: u32) -> bool {}}}+ // macOS has no /proc; `ps -o stat=` reports the same state field ('Z' for+ // a zombie). Only consulted after the marker's pid answered signal 0, so+ // the spawn cost is paid exactly when a stale-marker zombie is the+ // question. A failed or empty probe falls through to the signal-0+ // verdict (fail-open, matching the EPERM rule below).+ #[cfg(target_os = "macos")]+ {+ if let Ok(output) = std::process::Command::new("ps")+ .arg("-o")+ .arg("stat=")+ .arg("-p")+ .arg(pid.to_string())+ .output()+ {+ let state = String::from_utf8_lossy(&output.stdout);+ if state.trim_start().starts_with('Z') {+ return false;+ }+ }+ }let rc = unsafe { libc::kill(pid as libc::pid_t, 0) };if rc == 0 {return true;@@ -1757,8 +1777,9 @@ mod tests {#[test]fn live_marker_owner_keeps_own_live_marker() {// #74761: the desktop pre-writes the marker with OUR pid. That claim- // must be adoptable, never deleted as stale — deleting it would break- // the desktop handoff that pre-claims the lock for us.+ // must be reported (so `acquire` can adopt it without refreshing its+ // age), never deleted as stale — deleting it would break the desktop+ // handoff that pre-claims the lock for us.let dir = unique_tmp_dir("marker-read-own-live");let marker = dir.join(".hermes-update-in-progress");let started_at = std::time::SystemTime::now()@@ -1767,7 +1788,9 @@ mod tests {.unwrap_or(0);std::fs::write(&marker, format!("{}\n{started_at}", std::process::id())).unwrap();- assert!(live_marker_owner(&marker).is_none());+ let owner = live_marker_owner(&marker)+ .expect("our own live pid must be reported for acquire to adopt");+ assert_eq!(owner.pid, std::process::id());assert!(marker.exists(),"our own live marker must be kept for adoption"@@ -1838,6 +1861,47 @@ mod tests {}}+ #[cfg(target_os = "macos")]+ #[test]+ fn pid_is_alive_false_for_zombie() {+ // Same false positive as the Linux branch, probed the macOS way: the+ // child exits, the parent does not reap it, and `ps -o stat=` must+ // report state 'Z' (or 'Z+'), which counts as dead.+ unsafe {+ let pid = libc::fork();+ assert!(pid >= 0, "fork failed");+ if pid == 0 {+ libc::_exit(0);+ }+ let mut became_zombie = false;+ for _ in 0..20 {+ if let Ok(output) = std::process::Command::new("ps")+ .arg("-o")+ .arg("stat=")+ .arg("-p")+ .arg(pid.to_string())+ .output()+ {+ let state = String::from_utf8_lossy(&output.stdout);+ if state.trim_start().starts_with('Z') {+ became_zombie = true;+ break;+ }+ }+ std::thread::sleep(std::time::Duration::from_millis(25));+ }+ assert!(became_zombie, "child never reached zombie state");++ assert!(+ !pid_is_alive(pid as u32),+ "a zombie must not count as a live marker owner"+ );+ // Reap the zombie so the test process doesn't leak children.+ let mut status: libc::c_int = 0;+ libc::waitpid(pid, &mut status, 0);+ }+ }+#[test]fn completed_update_releases_marker_before_guard_drop() {let dir = unique_tmp_dir("marker-complete");diff --git a/apps/desktop/electron/update-marker.test.ts b/apps/desktop/electron/update-marker.test.tsindex 8607515aaa6..ed5537dcffc 100644--- a/apps/desktop/electron/update-marker.test.ts+++ b/apps/desktop/electron/update-marker.test.ts@@ -22,6 +22,7 @@ import { test } from 'vitest'import {isPidAlive,markerPath,+ posixProcessState,readLiveUpdateMarker,UPDATE_MARKER_MAX_AGE_MS,updateHandoffConflict,@@ -70,6 +71,37 @@ test('dead pid => no live update and marker is pruned', () => {assert.ok(!fs.existsSync(markerPath(home)), 'a dead-pid marker self-heals (deleted)')})+test('zombie pid => no live update and marker is pruned', () => {+ // The kill(pid, 0) false positive: a process that exited but is still in the+ // table (parent has not reaped it) answers signal 0 like a live one. The+ // state probe must turn that into "dead" so the boot gate self-heals in+ // seconds instead of parking for the whole 20-minute ceiling.+ const home = tmpHome('zombie')+ const now = 1_000_000_000_000+ writeMarker(home, 4242, Math.floor(now / 1000) - 5)+ const res = readLiveUpdateMarker(home, { kill: ALIVE, now: () => now, processState: () => 'Z' })+ assert.equal(res, null, 'a zombie owner is not a live update')+ assert.ok(!fs.existsSync(markerPath(home)), 'a zombie-owned marker self-heals (deleted)')+})++test('a live state keeps the marker (probe answers non-Z)', () => {+ const home = tmpHome('state-live')+ const now = 1_000_000_000_000+ writeMarker(home, 4242, Math.floor(now / 1000) - 5)+ const res = readLiveUpdateMarker(home, { kill: ALIVE, now: () => now, processState: () => 'S' })+ assert.ok(res, 'an alive, non-zombie owner keeps the gate closed')+ assert.ok(fs.existsSync(markerPath(home)), 'a live marker is NOT deleted')+})++test('an unknown process state fails open to alive (keeps the marker)', () => {+ const home = tmpHome('state-unknown')+ const now = 1_000_000_000_000+ writeMarker(home, 4242, Math.floor(now / 1000) - 5)+ const res = readLiveUpdateMarker(home, { kill: ALIVE, now: () => now, processState: () => null })+ assert.ok(res, 'probe failure must keep the conservative signal-0 verdict')+ assert.ok(fs.existsSync(markerPath(home)))+})+test('expired marker (past age ceiling) => no live update and pruned', () => {const home = tmpHome('expired')const now = 1_000_000_000_000@@ -104,6 +136,22 @@ test('isPidAlive: EPERM counts as alive (process owned by another user)', () =>assert.equal(isPidAlive(4242, eperm), true)})+test('posixProcessState: own pid is probeable and not a zombie; dead pid is unknown', () => {+ if (process.platform === 'win32') {+ // Windows has no zombie state and no ps stat lane; the probe is a no-op.+ assert.equal(posixProcessState(process.pid), null)+ return+ }++ const own = posixProcessState(process.pid)+ assert.ok(own, 'a live pid must be probeable on linux/darwin')+ assert.ok(!own.toUpperCase().startsWith('Z'), 'this process is not a zombie')++ // A pid nothing owns (and that kill(0) would reject) is simply unknowable —+ // callers keep their signal-0 verdict in that case.+ assert.equal(posixProcessState(2147483647), null)+})+test('writeUpdateMarker writes a marker that readLiveUpdateMarker accepts', () => {const home = tmpHome('write')const now = 1_000_000_000_000diff --git a/apps/desktop/electron/update-marker.ts b/apps/desktop/electron/update-marker.tsindex 4bc59665bde..11ab809c656 100644--- a/apps/desktop/electron/update-marker.ts+++ b/apps/desktop/electron/update-marker.ts@@ -21,6 +21,7 @@*/import fs from 'fs'+import { execFileSync } from 'node:child_process'import path from 'path'// Even with a live-looking PID, never treat a marker older than this as a live@@ -37,6 +38,11 @@ export function markerPath(hermesHome) {// not deliver a signal — it just probes existence/permission. ESRCH => dead;// EPERM => alive but owned by another user (still "alive" for our purposes).// Injectable `kill` keeps it unit-testable.+//+// NOT zombie-aware on its own: signal 0 also succeeds for a process that+// exited but whose parent has not reaped it. Callers deciding whether an+// update marker's owner is still running must layer `posixProcessState` on+// top (see `readLiveUpdateMarker`).export function isPidAlive(pid, kill: typeof process.kill = process.kill.bind(process)) {if (!Number.isInteger(pid) || pid <= 0) {return false@@ -51,6 +57,53 @@ export function isPidAlive(pid, kill: typeof process.kill = process.kill.bind(pr}}+/**+ * Single-letter process state (`ps` style) for a kill(0)-alive pid, or null+ * when it cannot be determined.+ *+ * A ZOMBIE — exited, still in the table because its parent has not reaped+ * it — answers signal 0 like a live process. A crashed updater lingering+ * that way would keep its update marker "live" and park the desktop boot+ * gate for the whole 20-minute ceiling (#77259, #120635, #125932). Linux+ * exposes the state via /proc; on macOS `ps -o stat=` does. Failures return+ * null so callers keep their signal-0 verdict (fail-open to alive, matching+ * the EPERM behavior above).+ */+export function posixProcessState(pid: number): string | null {+ if (process.platform === 'linux') {+ try {+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')+ const commEnd = stat.lastIndexOf(')')+ const state = commEnd >= 0 ? stat.slice(commEnd + 2, commEnd + 3) : ''++ return state || null+ } catch {+ return null+ }+ }++ if (process.platform === 'darwin') {+ try {+ const out = execFileSync('ps', ['-o', 'stat=', '-p', String(pid)], {+ encoding: 'utf8',+ timeout: 5000+ })++ return out.trim().charAt(0) || null+ } catch {+ return null+ }+ }++ return null+}++// A state of 'Z'/'Z+' (and friends) means the process exited and only its+// unreaped table entry remains — dead for every liveness decision here.+function isZombieState(state: string | null | undefined): boolean {+ return Boolean(state && state.toUpperCase().startsWith('Z'))+}+/*** Read + interpret the marker.*@@ -68,11 +121,14 @@ export function readLiveUpdateMarker({kill,now = Date.now,- maxAgeMs = UPDATE_MARKER_MAX_AGE_MS+ maxAgeMs = UPDATE_MARKER_MAX_AGE_MS,+ processState = posixProcessState}: {now?: () => numbermaxAgeMs?: numberkill?: typeof process.kill+ /** Injectable override of the zombie/state probe (see posixProcessState). */+ processState?: (pid: number) => string | null} = {}) {const file = markerPath(hermesHome)@@ -90,7 +146,7 @@ export function readLiveUpdateMarker(const ageMs = Number.isFinite(startedAt) ? now() - startedAt * 1000 : Infinityconst alive = Number.isInteger(pid) && isPidAlive(pid, kill)- if (!alive || ageMs > maxAgeMs) {+ if (!alive || isZombieState(processState(pid)) || ageMs > maxAgeMs) {try {fs.unlinkSync(file)} catch {diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex e8804e10e81..61b0aa0331a 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -107,12 +107,48 @@ def _read_marker_attempts(marker_path: Path) -> int:return 0+def _process_state(pid: int) -> str | None:+ """Single-letter process state (``ps`` style), or ``None`` when unknowable.++ ``os.kill(pid, 0)`` also succeeds for a ZOMBIE — a process that exited but+ whose parent has not reaped it yet. Reading the state lets callers treat a+ zombie as dead, so a crashed update stage lingering under an un-reaping+ parent cannot keep a stale update marker "live" for the whole age ceiling+ (#77259, #120635, #125932). Best-effort and stdlib-only: on any failure the+ answer is ``None`` and callers keep their signal-0 verdict.+ """+ if sys.platform == "linux":+ try:+ with open(f"/proc/{pid}/stat", "rb") as fh:+ stat = fh.read()+ except OSError:+ return None+ # Field 3 is the state, but comm may contain spaces/parens: anchor on+ # the closing paren of comm instead of splitting on whitespace.+ comm_end = stat.rfind(b")")+ if comm_end < 0:+ return None+ return stat[comm_end + 2 : comm_end + 3].decode("ascii", "replace") or None+ if sys.platform == "darwin":+ try:+ out = subprocess.run(+ ["ps", "-o", "stat=", "-p", str(pid)],+ capture_output=True, text=True, encoding="utf-8", errors="replace",+ timeout=5, check=False,+ ).stdout+ except (OSError, subprocess.SubprocessError):+ return None+ return out.strip()[:1] or None+ return None++def _pid_is_running(pid: int) -> bool:"""Best-effort stdlib-only process liveness probe.``os.kill(pid, 0)`` is not a no-op on Windows, so use the Win32 process handle API there. Anaccess-denied result counts as live: racing an elevated updater is worse than postponing- recovery for one launch.+ recovery for one launch. A zombie (exited, un-reaped) counts as dead — see+ :func:`_process_state`."""if pid <= 0:return False@@ -145,6 +181,9 @@ def _pid_is_running(pid: int) -> bool:return Trueexcept OSError:return False+ state = _process_state(pid)+ if state is not None and state.upper().startswith("Z"):+ return False # exited, unreaped — not a live ownerreturn Truediff --git a/tests/hermes_cli/test_early_recovery.py b/tests/hermes_cli/test_early_recovery.pyindex af3afc18b8a..b7943cf03de 100644--- a/tests/hermes_cli/test_early_recovery.py+++ b/tests/hermes_cli/test_early_recovery.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport osimport subprocessimport sys+import timefrom pathlib import Pathimport pytest@@ -120,6 +121,49 @@ def test_pid_liveness_recognizes_current_process():assert er._pid_is_running(os.getpid()) is Trueassert er._pid_is_running(0) is False+[email protected]("posix")+def test_pid_liveness_counts_a_zombie_as_dead():+ """A crashed stage lingering unreaped must not read as a live owner.++ ``os.kill(pid, 0)`` succeeds for a zombie, so before the state probe a+ crashed updater under an un-reaping parent pinned every lock keyed on its+ pid (update marker, recovery marker) for the full age ceiling.+ """+ pid = os.fork()+ assert pid >= 0+ if pid == 0:+ os._exit(0) # noqa: P111 — child exits without running pytest teardown++ # Do NOT wait() yet: the child must linger unreaped (a zombie). Poll until+ # the state probe actually reports 'Z' so the assertion can't race the exit.+ became_zombie = False+ for _ in range(40):+ state = er._process_state(pid)+ if state is not None and state.upper().startswith("Z"):+ became_zombie = True+ break+ time.sleep(0.05)+ assert became_zombie, "child never reached zombie state on this platform"++ assert er._pid_is_running(pid) is False, "a zombie is not a live owner"++ os.waitpid(pid, 0) # reap so the test leaks no children++[email protected]("linux", "macos")+def test_process_state_reports_a_letter_for_a_live_pid():+ state = er._process_state(os.getpid())+ assert state is not None and len(state) == 1, "a live pid must expose a state"+ assert not state.upper().startswith("Z"), "this process is not a zombie"++[email protected]("posix")+def test_process_state_is_none_for_a_dead_pid():+ state = er._process_state(4294967294)+ assert state is None, "an unprobeable pid must degrade to None (unknown)"++def test_marker_owner_liveness_uses_recorded_pid(tmp_path, monkeypatch):marker = tmp_path / ".update-incomplete"marker.write_text("started=1\npid=4321\n", encoding="utf-8")diff --git a/tests/hermes_cli/test_update_lock.py b/tests/hermes_cli/test_update_lock.pyindex d06454cd3a8..a770d69f3a2 100644--- a/tests/hermes_cli/test_update_lock.py+++ b/tests/hermes_cli/test_update_lock.py@@ -104,6 +104,40 @@ def test_refused_lock_does_not_delete_the_live_owners_marker(marker, other_pid):assert marker.exists(), "a refused claimant must never clear the live owner's lock"[email protected]("posix")+def test_marker_owned_by_a_zombie_self_heals(marker):+ """A crashed updater lingering unreaped must not pin the lock for 20 minutes.++ ``os.kill(pid, 0)`` still succeeds for a zombie, so a marker owned by a+ dead-but-unreaped stage used to read as a live update until the age ceiling+ expired (#77259, #120635, #125932).+ """+ pid = os.fork()+ assert pid >= 0+ if pid == 0:+ os._exit(0) # noqa: P111 — child exits without running pytest teardown++ # Keep the child unreaped (a zombie) and wait until the state probe+ # actually reports 'Z' so the assertion can't race the exit.+ from hermes_cli._early_recovery import _process_state++ became_zombie = False+ for _ in range(40):+ state = _process_state(pid)+ if state is not None and state.upper().startswith("Z"):+ became_zombie = True+ break+ time.sleep(0.05)+ assert became_zombie, "child never reached zombie state on this platform"++ try:+ _claim(marker, pid)+ assert read_live_update(path=marker) is None, "a zombie is not a live update"+ assert not marker.exists(), "the stale marker must self-heal (unlink)"+ finally:+ os.waitpid(pid, 0) # reap so the test leaks no children++def test_marker_naming_our_own_pid_is_adopted(marker, monkeypatch):"""A killed update's marker names the pid its retry gets (containers restart pid numbering).