Skip to content

The agent that grows with you

fix: an old Desktop stays parked when the POSIX hand-off dies mid-update

Tekniume410ffc941d2
diff --git a/scripts/desktop-update/marker.sh b/scripts/desktop-update/marker.sh
index 10cc9f02b4f..52e3bc20110 100644
--- a/scripts/desktop-update/marker.sh
+++ b/scripts/desktop-update/marker.sh
@@ -444,6 +444,40 @@ marker_refresh_locked() { # old packaged Desktops age a marker on line 2 (20 min
marker_replace "$(marker_canonical "$M_PID" "$(marker_now)" "$M_CT" "$M_DPID" "$M_DCT")"$'\n'
}
+marker_custody_take_locked() { # pid ct -> 0 iff the dead hand-off's claim now names this custodian
+ marker_read || return 1
+ marker_judge "$SEEN"
+ [ "$M_PID" = "$MY_PID" ] && [ "$J_OWNER_STATE" -eq 0 ] || return 1
+ if [ "$J_DELEGATE_STATE" -ne 2 ]; then
+ checkout_lock_held || return 1
+ M_DPID="" M_DCT=""
+ fi
+ marker_replace "$(marker_canonical "$1" "$(marker_now)" "$2" "$M_DPID" "$M_DCT")"$'\n'
+}
+
+marker_custody() { # posix.sh's refresher, once the hand-off is gone; never returns
+ # The hand-off's claim would name a dead pid while the `hermes update` it
+ # started (line 4) or a completion survivor still mutates the checkout, and
+ # an old packaged Desktop judges line 1 alone. So name ourselves on line 1
+ # until both are gone (bounded like the R6 wait), keep line 2 young, then
+ # release. Only the dead hand-off ever wrote a delegate, so an unlocked look
+ # that finds neither one nor a held checkout lock is final -- no need to wait
+ # out a busy A7 lock. `exec sh` reports our pid: bash 3.2 has no BASHPID.
+ local me ct dpid dct tick=0
+ marker_read && marker_parse "$SEEN" && { [ -n "$M_DPID" ] || checkout_lock_held; } || exit 0
+ me="$(exec sh -c 'echo "$PPID"')"; ct="$(proc_ct "$me")"
+ [ -n "$ct" ] && marker_locked marker_custody_take_locked "$me" "$ct" || exit 0
+ dpid="$M_DPID" dct="$M_DCT" MY_PID="$me" MY_CT="$ct"
+ log "update hand-off died while its update still holds the checkout; pid $me keeps the update marker"
+ while { [ -n "$dpid" ] && ident_alive "$dpid" "$dct"; } || checkout_lock_held; do
+ [ "$tick" -lt "${RELEASE_WAIT_S:-7200}" ] || exit 0
+ sleep 1; tick=$((tick + 1))
+ [ $((tick % ${MARKER_REFRESH_EVERY_S:-300})) -ne 0 ] || marker_locked marker_refresh_locked
+ done
+ marker_locked marker_release_locked
+ exit 0
+}
+
marker_release_locked() { # A7 rule 5 / corpus "release"
marker_read || return 0
marker_judge "$SEEN"
diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.sh
index 8658996abda..4d142f692ab 100755
--- a/scripts/desktop-update/posix.sh
+++ b/scripts/desktop-update/posix.sh
@@ -153,18 +153,20 @@ marker_release() { # A7 rule 5, under the lock. Never while a survivor of the
RELEASE_WAIT_S=7200
RELEASE_WAITED=0 # the R6 wait ran: the result written before it carries a stale finished_at
-# An older packaged Desktop judges a marker by line 2 alone and deletes it 20
-# minutes in, live owner or not. From the claim until the release is decided
-# (the update, every follow-up step and the R6 wait above), keep line 2 young
-# -- under the A7 lock and only while line 1 is still our exact incarnation
-# (marker_refresh_locked). It dies with us: a dead script refreshes nothing.
+# An older packaged Desktop judges a marker by lines 1 and 2 alone: a dead pid,
+# or a line 2 20 minutes old, and it deletes the marker and boots its backend.
+# From the claim until the release is decided (the update, every follow-up
+# step and the R6 wait above), keep line 2 young -- under the A7 lock and only
+# while line 1 is still our exact incarnation (marker_refresh_locked). If we
+# die first (SIGKILL runs no trap) while our update still runs or holds the
+# checkout lock, the refresher outlives us as its custodian (marker_custody).
MARKER_REFRESHER=""
marker_refresher_start() {
[ "$MARKER_CLAIMED" -eq 1 ] && [ -z "$MARKER_REFRESHER" ] || return 0
( trap '' HUP INT QUIT TERM
while :; do
for ((_tick = 0; _tick < MARKER_REFRESH_EVERY_S; _tick++)); do
- sleep 1; kill -0 "$MY_PID" 2>/dev/null || exit 0
+ sleep 1; kill -0 "$MY_PID" 2>/dev/null || marker_custody
done
marker_locked marker_refresh_locked
done ) </dev/null >/dev/null 2>&1 &
diff --git a/tests/fixtures/legacy_desktop/update-marker-be3fd671.mts b/tests/fixtures/legacy_desktop/update-marker-be3fd671.mts
new file mode 100644
index 00000000000..c077a330f4e
--- /dev/null
+++ b/tests/fixtures/legacy_desktop/update-marker-be3fd671.mts
@@ -0,0 +1,162 @@
+// The update-marker reader a packaged Desktop shipped at be3fd671d70 (apps/desktop/electron/update-marker.ts
+// lines 1-160, verbatim): the old reader new hand-off scripts must keep parked. Never edit it.
+/**
+ * In-app update mutual-exclusion marker (#50238).
+ *
+ * The Tauri updater writes HERMES_HOME/.hermes-update-in-progress for the whole
+ * duration of an `--update` run (see apps/bootstrap-installer/src-tauri/src/
+ * update.rs `UpdateMarkerGuard`). The marker body is two lines: the updater's
+ * pid and the unix-seconds it started.
+ *
+ * Why: if the user relaunches the desktop mid-update — the window vanished with
+ * no progress and looks crashed — a fresh instance must NOT spawn its own local
+ * backend. That backend re-locks the venv shim, the updater's straggler cleanup
+ * (`force_kill_other_hermes`, taskkill /IM hermes.exe) kills it, the launch
+ * fails with the 45s "backend didn't come up" timeout, and the user relaunches
+ * into the same trap — an infinite respawn/kill loop. The desktop gates local
+ * backend startup on this marker and parks until the update finishes.
+ *
+ * This module holds the PURE, side-effect-light logic (path, pid liveness,
+ * parse + staleness) so it is unit-testable without booting Electron. The
+ * polling/boot-progress wrapper lives in main.ts where the boot-progress and
+ * log sinks are.
+ */
+
+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
+// update. A full update (git pull + pip + desktop rebuild) is minutes, not tens
+// of minutes; past this the marker is almost certainly stale (e.g. the OS
+// recycled the pid onto an unrelated process), so the gate self-heals.
+export const UPDATE_MARKER_MAX_AGE_MS = 20 * 60 * 1000
+
+export function markerPath(hermesHome) {
+ return path.join(hermesHome, '.hermes-update-in-progress')
+}
+
+// True only if a host process with this pid is currently alive. Signal 0 does
+// 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
+ }
+
+ try {
+ kill(pid, 0)
+
+ return true
+ } catch (err) {
+ return Boolean(err && err.code === 'EPERM')
+ }
+}
+
+/**
+ * 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.
+ *
+ * Returns `{ pid, ageMs }` only when an update is GENUINELY still running
+ * (parseable pid that is alive, within the age ceiling). Returns `null` for
+ * every "no live update" case — absent, unreadable, malformed, dead pid, or
+ * past the ceiling — and, when a stale marker file exists, deletes it so it
+ * cannot strand future launches.
+ *
+ * Pure-ish: file I/O against the given path, plus an injectable pid probe and
+ * clock for tests.
+ */
+export function readLiveUpdateMarker(
+ hermesHome,
+ {
+ kill,
+ now = Date.now,
+ maxAgeMs = UPDATE_MARKER_MAX_AGE_MS,
+ processState = posixProcessState
+ }: {
+ now?: () => number
+ maxAgeMs?: number
+ kill?: typeof process.kill
+ /** Injectable override of the zombie/state probe (see posixProcessState). */
+ processState?: (pid: number) => string | null
+ } = {}
+) {
+ const file = markerPath(hermesHome)
+ let raw
+
+ try {
+ raw = fs.readFileSync(file, 'utf8')
+ } catch {
+ return null // absent or unreadable => no live update
+ }
+
+ const [pidLine, startedLine] = String(raw).split('\n')
+ const pid = Number.parseInt((pidLine || '').trim(), 10)
+ const startedAt = Number.parseInt((startedLine || '').trim(), 10)
+ const ageMs = Number.isFinite(startedAt) ? now() - startedAt * 1000 : Infinity
+ const alive = Number.isInteger(pid) && isPidAlive(pid, kill)
+
+ if (!alive || isZombieState(processState(pid)) || ageMs > maxAgeMs) {
+ try {
+ fs.unlinkSync(file)
+ } catch {
+ void 0
+ }
+
+ return null
+ }
+
+ return { pid, ageMs }
+}
diff --git a/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py b/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py
index 616d940a0fc..de02720eba4 100644
--- a/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py
+++ b/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py
@@ -530,3 +530,67 @@ def test_line_two_is_refreshed_only_while_the_claim_is_still_ours(tmp_path, proc
marker.write_text(foreign, encoding="utf-8")
subprocess.run(["bash", "-c", run + "marker_locked marker_refresh_locked"], check=True, timeout=30)
assert marker.read_text(encoding="utf-8-sig") == foreign
+
+
+# ── old packaged Desktop after the orchestrator dies ────────────────────────
+
+LEGACY_READER = Path(__file__).resolve().parents[2] / "fixtures" / "legacy_desktop" / "update-marker-be3fd671.mts"
+
+
+def _legacy_read(home: Path) -> dict:
+ """The exact reader an old packaged Desktop runs at boot: line 1 dead or line 2 past 20
+ minutes => it unlinks the marker and starts its backend."""
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is needed to run the shipped Desktop reader")
+ code = (f"import fs from 'fs'; import {{ readLiveUpdateMarker }} from {json.dumps(LEGACY_READER.as_uri())}; "
+ f"const live = readLiveUpdateMarker(process.argv[1]); "
+ f"console.log(JSON.stringify({{ live, kept: fs.existsSync(process.argv[1] + '/.hermes-update-in-progress') }}))")
+ out = subprocess.run([node, "--input-type=module", "-e", code, str(home)], capture_output=True, text=True,
+ encoding="utf-8", timeout=60)
+ assert out.returncode == 0, out.stderr
+ return json.loads(out.stdout.strip().splitlines()[-1])
+
+
+def test_old_desktop_stays_parked_after_the_orchestrator_is_killed_while_the_update_holds_the_lock(tmp_path):
+ """SIGKILL the hand-off once its delegate (`hermes update`) runs and a completion survivor holds
+ the checkout lock. The old reader judges line 1 alone, so a live custodian must take line 1
+ and keep line 2 young until custody ends -- through the delegate and the survivor -- and only
+ then release the marker."""
+ home, install = _install(tmp_path, legacy=True)
+ marker = home / ".hermes-update-in-progress"
+ hold, completion = tmp_path / "update-hold", tmp_path / "release-completion"
+ lock = install / ".hermes-update.lock"
+ env = _env(tmp_path, home, HANDOFF_HOLD=str(hold), HANDOFF_COMPLETION=str(completion), HANDOFF_CHECKOUT_LOCK=str(lock))
+ script = subprocess.Popen([bash := shutil.which("bash"), str(POSIX), "--daemonized", "--no-ui", "--install-root", str(install),
+ "--self-test-refresh-every", "1"], env=env, cwd=tmp_path,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ try:
+ deadline = time.monotonic() + 60
+ while not Path(str(hold) + ".pid").exists():
+ assert time.monotonic() < deadline and script.poll() is None
+ time.sleep(0.05)
+ delegate = int(Path(str(hold) + ".pid").read_text(encoding="utf-8"))
+ assert f"delegate:{delegate} " in marker.read_text(encoding="utf-8-sig")
+ script.kill(); script.wait()
+ for phase in ("delegate", "survivor"):
+ for _ in range(3):
+ time.sleep(1.5)
+ seen = _legacy_read(home)
+ assert seen["live"] is not None and seen["kept"], (phase, seen)
+ if phase == "delegate":
+ hold.touch()
+ deadline = time.monotonic() + 30
+ while Path(f"/proc/{delegate}").exists() and "Z" not in Path(f"/proc/{delegate}/stat").read_text(encoding="utf-8").rsplit(") ", 1)[1][:1]:
+ assert time.monotonic() < deadline
+ time.sleep(0.05)
+ probe = subprocess.run([bash, "-c", f"log() {{ :; }}; MARKER=/dev/null INSTALL_ROOT={shlex.quote(str(install))}; "
+ f". {shlex.quote(str(MARKER_SH))}; checkout_lock_held"], timeout=30)
+ assert probe.returncode == 0, "the survivor should still hold the checkout lock"
+ finally:
+ hold.touch(); completion.touch()
+ deadline = time.monotonic() + 30
+ while marker.exists():
+ assert time.monotonic() < deadline, marker.read_text(encoding="utf-8-sig")
+ time.sleep(0.1)
+ assert _legacy_read(home)["live"] is None