Skip to content

The agent that grows with you

fix: an old Desktop never reads a dead owner while the POSIX hand-off dies

Teknium4a7c363c0b9f
diff --git a/scripts/desktop-update/marker.sh b/scripts/desktop-update/marker.sh
index 2157f52ae89..a61f18928f2 100644
--- a/scripts/desktop-update/marker.sh
+++ b/scripts/desktop-update/marker.sh
@@ -444,31 +444,31 @@ 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_custody_take_locked() { # pid ct -> 0 iff our claim now names that custodian on line 1
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
+ [ "$J_DELEGATE_STATE" -eq 2 ] || M_DPID="" M_DCT=""
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"
+marker_custody() { # posix.sh's refresher (CUSTODIAN_PID/CT), once the hand-off is gone; never returns
+ # An old packaged Desktop judges line 1 alone, and a SIGKILLed hand-off runs
+ # no trap. So line 1 names this custodian, not the hand-off, from before the
+ # update work starts (posix.sh hands it over): when the hand-off dies, the
+ # `hermes update` it started (line 4) or a completion survivor may still
+ # mutate the checkout, and the marker already names a live owner. Keep line
+ # 2 young until both are gone (bounded like the R6 wait), then release. Had
+ # the handover failed, take the claim over now. Only the hand-off ever wrote
+ # a delegate, so an unlocked look is enough to decide.
+ local dpid dct tick=0
+ marker_read && marker_parse "$SEEN" || exit 0
+ if [ "$M_PID" != "$CUSTODIAN_PID" ]; then
+ { [ -n "$M_DPID" ] || checkout_lock_held; } && [ -n "$CUSTODIAN_CT" ] \
+ && marker_locked marker_custody_take_locked "$CUSTODIAN_PID" "$CUSTODIAN_CT" || exit 0
+ fi
+ dpid="$M_DPID" dct="$M_DCT" MY_PID="$CUSTODIAN_PID" MY_CT="$CUSTODIAN_CT"
+ log "update hand-off is gone; pid $MY_PID keeps the update marker while its update holds the checkout"
while { [ -n "$dpid" ] && ident_alive "$dpid" "$dct"; } || checkout_lock_held; do
[ "$tick" -lt "${RELEASE_WAIT_S:-7200}" ] || exit 0
sleep 1; tick=$((tick + 1))
diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.sh
index 4d142f692ab..574fda23a08 100755
--- a/scripts/desktop-update/posix.sh
+++ b/scripts/desktop-update/posix.sh
@@ -131,9 +131,9 @@ marker_release() { # A7 rule 5, under the lock. Never while a survivor of the
# that completion still mutates the checkout. Wait it out; past the bound,
# leave the marker in place -- dead to every reader, and the Desktop's
# reclaim helper refuses to delete it while the checkout lock is held.
- # The line-2 refresher keeps running through that wait (an old Desktop
- # would otherwise age-delete the marker 20 minutes into it) and stops only
- # once the release is decided.
+ # The custodian (line 1, the line-2 refresher) keeps running through that
+ # wait (an old Desktop would otherwise age-delete the marker 20 minutes
+ # into it) and stops only once the marker is released.
local waited=0
[ "$MARKER_CLAIMED" -eq 1 ] && [ "$NO_MARKER_CLEANUP" -eq 0 ] || { marker_refresher_stop; return 0; }
while checkout_lock_held; do
@@ -146,31 +146,45 @@ marker_release() { # A7 rule 5, under the lock. Never while a survivor of the
fi
sleep 1; waited=$((waited + 1))
done
- marker_refresher_stop
marker_locked marker_release_locked
+ marker_refresher_stop
MARKER_CLAIMED=0
}
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 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).
+# or a line 2 20 minutes old, and it deletes the marker and boots its backend
+# -- it never looks at the delegate line or the A7 lock. We can be SIGKILLed
+# (no trap runs) while our update still runs or holds the checkout lock, and
+# a takeover after that death would leave an instant in which line 1 names a
+# dead pid. So before any update work starts, line 1 names a custodian that
+# outlives us: this refresher. From then on the marker's identity (MY_PID /
+# MY_CT) is the custodian's; it keeps line 2 young (marker_refresh_locked)
+# until the release is decided and, if we die first, keeps the marker until
+# our update and its survivors are gone (marker_custody). `exec sh` reports
+# its pid: bash 3.2 has no BASHPID.
MARKER_REFRESHER=""
marker_refresher_start() {
+ local ct
[ "$MARKER_CLAIMED" -eq 1 ] && [ -z "$MARKER_REFRESHER" ] || return 0
( trap '' HUP INT QUIT TERM
+ CUSTODIAN_PID="$(exec sh -c 'echo "$PPID"')"; CUSTODIAN_CT="$(proc_ct "$CUSTODIAN_PID")"
while :; do
for ((_tick = 0; _tick < MARKER_REFRESH_EVERY_S; _tick++)); do
- sleep 1; kill -0 "$MY_PID" 2>/dev/null || marker_custody
+ sleep 1; kill -0 $$ 2>/dev/null || marker_custody
done
- marker_locked marker_refresh_locked
+ MY_PID="$CUSTODIAN_PID" MY_CT="$CUSTODIAN_CT" marker_locked marker_refresh_locked
+ marker_locked marker_refresh_locked # line 1 is still ours: the handover below failed
done ) </dev/null >/dev/null 2>&1 &
MARKER_REFRESHER=$!
+ ct="$(proc_ct "$MARKER_REFRESHER")"
+ if [ -n "$ct" ] && marker_locked marker_custody_take_locked "$MARKER_REFRESHER" "$ct"; then
+ MY_PID="$MARKER_REFRESHER" MY_CT="$ct"
+ log "update marker names its custodian pid $MY_PID (hand-off pid $$)"
+ else
+ log "WARNING: could not name the update marker's custodian; it takes over only if this hand-off dies"
+ fi
}
marker_refresher_stop() {
[ -n "$MARKER_REFRESHER" ] || return 0
@@ -1152,7 +1166,7 @@ run_update() { # streams straight into the log (a killed run keeps its output);
for sig in HUP INT QUIT; do trap "PENDING_SIGNAL=\${PENDING_SIGNAL:-$sig}" "$sig"; done
rm -f "$go" 2>/dev/null
( trap - TERM
- while [ ! -e "$go" ]; do kill -0 "$MY_PID" 2>/dev/null || exit 70; sleep 0.05; done
+ while [ ! -e "$go" ]; do kill -0 $$ 2>/dev/null || exit 70; sleep 0.05; done
exec "${UPDATE_INVOKE[@]}" update --yes $GATEWAY_FLAG $KEEP_STASH "${TARGET_ARGS[@]}" ) >> "$LOG" 2>&1 <&0 &
pid=$!
if marker_add_delegate "$pid"; then
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 1f181d85081..d5d76fe6238 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
@@ -33,7 +33,7 @@ fcntl = pytest.importorskip("fcntl") # windows-footgun: ok
from tests.scripts.desktop_update.legacy_desktop_reader import legacy_read
from tests.scripts.desktop_update.lineage_rule_cases import ENV_CASES, RULE_CASES
from tests.scripts.desktop_update.lineage_rule_cases import FACTS as LINEAGE_FACTS
-from tests.scripts.desktop_update.test_desktop_update_posix_marker import POSIX, _calls, _ct, _install
+from tests.scripts.desktop_update.test_desktop_update_posix_marker import POSIX, _calls, _ct, _custodian, _install
pytestmark = pytest.mark.platforms("linux") # /proc ancestry and creation times
@@ -307,8 +307,9 @@ def test_marker_outlives_a_survivor_that_still_holds_the_checkout_lock(tmp_path)
assert time.monotonic() < deadline and script.poll() is None, log.read_text(encoding="utf-8-sig")
time.sleep(0.05)
time.sleep(1.5)
- assert script.poll() is None and marker.read_text(encoding="utf-8-sig").splitlines()[0] == str(script.pid)
- assert _helper(tmp_path, home, install, "reclaim") == f"live {script.pid}"
+ custodian = _custodian(home)
+ assert script.poll() is None and marker.read_text(encoding="utf-8-sig").splitlines()[0] == custodian
+ assert _helper(tmp_path, home, install, "reclaim") == f"live {custodian}"
os.killpg(script.pid, signal.SIGKILL); script.wait() # windows-footgun: ok — linux-only test # the script dies too: dead marker, lock still held
assert _helper(tmp_path, home, install, "reclaim") == "held"
assert marker.exists()
@@ -426,7 +427,7 @@ def test_line_two_stays_young_through_the_r6_release_wait(tmp_path):
for _ in range(4): # several refresh intervals, all inside the wait
time.sleep(1.5)
pid, started = marker.read_text(encoding="utf-8-sig").splitlines()[:2]
- assert script.poll() is None and pid == str(script.pid)
+ assert script.poll() is None and pid == _custodian(home)
assert time.time() - int(started) <= 3.5, started
finally:
completion.touch()
@@ -475,7 +476,7 @@ def test_script_killed_before_the_delegate_line_appears_runs_no_update(tmp_path)
lock_fd = None
try:
deadline = time.monotonic() + 30
- while not (marker.exists() and marker.read_text(encoding="utf-8-sig").split("\n")[0] == str(script.pid)):
+ while not (marker.exists() and _custodian(home) and marker.read_text(encoding="utf-8-sig").split("\n")[0] == _custodian(home)):
assert time.monotonic() < deadline and script.poll() is None
time.sleep(0.005)
lock_fd = os.open(str(marker) + ".lock", os.O_RDWR | os.O_CREAT, 0o644)
@@ -486,8 +487,10 @@ def test_script_killed_before_the_delegate_line_appears_runs_no_update(tmp_path)
time.sleep(0.01)
time.sleep(0.5) # the update child is spawned and parked behind the go-file
children = [int(p) for p in Path(f"/proc/{script.pid}/task/{script.pid}/children").read_text(encoding="utf-8").split()]
- # The (sub)shell that will exec `hermes update`; the other child is flock(1) waiting on us.
- gate = [p for p in children if Path(f"/proc/{p}/comm").read_text(encoding="utf-8").strip() == "bash"]
+ # The (sub)shell that will exec `hermes update`; the others are flock(1) waiting on us and
+ # the custodian (it outlives the script by design).
+ gate = [p for p in children if Path(f"/proc/{p}/comm").read_text(encoding="utf-8").strip() == "bash"
+ and str(p) != _custodian(home)]
assert gate, "the update child should exist before the delegate line is published"
script.kill(); script.wait()
time.sleep(1.0)
@@ -500,7 +503,11 @@ def test_script_killed_before_the_delegate_line_appears_runs_no_update(tmp_path)
os.close(lock_fd)
if script.poll() is None:
script.kill(); script.wait()
- assert _helper(tmp_path, home, install, "reclaim") == "reclaimed"
+ deadline = time.monotonic() + 30 # the custodian releases the marker: nothing holds the checkout
+ while (verdict := _helper(tmp_path, home, install, "reclaim")).startswith("live "):
+ assert time.monotonic() < deadline
+ time.sleep(0.1)
+ assert verdict in ("absent", "reclaimed")
# ── bounded probes and the old-reader line-2 refresh ────────────────────────
@@ -564,9 +571,11 @@ def test_line_two_is_refreshed_only_while_the_claim_is_still_ours(tmp_path, proc
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."""
+ the checkout lock. The old reader judges line 1 alone, so line 1 must name a live custodian at
+ EVERY instant -- including the first read after the kill, made while this test holds the A7
+ lock so nothing can take the marker over yet (review 5423056011: a takeover after the death
+ left a gap in which the old reader deleted the marker) -- keep line 2 young through the
+ delegate and the survivor, and release the marker only then."""
home, install = _install(tmp_path, legacy=True)
marker = home / ".hermes-update-in-progress"
hold, completion = tmp_path / "update-hold", tmp_path / "release-completion"
@@ -582,7 +591,14 @@ def test_old_desktop_stays_parked_after_the_orchestrator_is_killed_while_the_upd
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()
+ a7 = os.open(str(marker) + ".lock", os.O_RDWR | os.O_CREAT, 0o644)
+ try:
+ fcntl.flock(a7, fcntl.LOCK_EX) # no marker mutation (a takeover included) until we let go
+ script.kill(); script.wait()
+ seen = legacy_read(home)
+ assert seen["live"] is not None and seen["kept"], ("hand-off just died", seen)
+ finally:
+ os.close(a7)
for phase in ("delegate", "survivor"):
for _ in range(3):
time.sleep(1.5)
diff --git a/tests/scripts/desktop_update/test_desktop_update_posix_marker.py b/tests/scripts/desktop_update/test_desktop_update_posix_marker.py
index c84516a9cad..8f9287f6e9e 100644
--- a/tests/scripts/desktop_update/test_desktop_update_posix_marker.py
+++ b/tests/scripts/desktop_update/test_desktop_update_posix_marker.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import json
import os
from pathlib import Path
+import re
import shlex
import subprocess
import sys
@@ -316,6 +317,14 @@ def test_interrupted_app_swap_is_rolled_back_at_the_next_run(tmp_path):
assert not previous.exists() and not app.with_name("Hermes.app.new").exists()
+def _custodian(home: Path) -> str:
+ """The pid posix.sh names on line 1 before any update work starts: its custodian, which
+ outlives the hand-off so an old Desktop never reads a dead owner."""
+ log = home / "logs" / "desktop-update-handoff.log"
+ found = re.search(r"names its custodian pid (\d+)", log.read_text(encoding="utf-8-sig") if log.exists() else "")
+ return found.group(1) if found else ""
+
+
def _ancestry(pid: int) -> list[int]:
chain = []
while pid > 1:
@@ -355,7 +364,7 @@ def test_script_killed_right_after_spawning_the_update_leaves_a_live_marker(tmp_
script.wait(timeout=10)
child = int(child_pid_file.read_text(encoding="utf-8-sig"))
lines = marker.read_text(encoding="utf-8-sig").splitlines()
- assert lines[0] == str(script.pid)
+ assert lines[0] == _custodian(home) # never the killed hand-off
assert lines[3].startswith("delegate:"), lines
delegate = int(lines[3].split()[0].split(":")[1])
assert delegate in _ancestry(child) # the update process (or its exec-ing launcher)
@@ -367,8 +376,8 @@ def test_script_killed_right_after_spawning_the_update_leaves_a_live_marker(tmp_
hold.touch()
deadline = time.monotonic() + 30
- while Path(f"/proc/{delegate}").exists() and time.monotonic() < deadline:
- time.sleep(0.05)
+ while (Path(f"/proc/{delegate}").exists() or marker.exists()) and time.monotonic() < deadline:
+ time.sleep(0.05) # the custodian releases the marker once the delegate is gone
reclaimed = _run(tmp_path, home, install, "--self-test-marker", "--no-marker-cleanup")
assert reclaimed.returncode == 0, reclaimed.stdout + reclaimed.stderr
finally:
diff --git a/tests/scripts/desktop_update/test_handoff_delegate_publication.py b/tests/scripts/desktop_update/test_handoff_delegate_publication.py
index 5fb582bb30d..ed0a4088f42 100644
--- a/tests/scripts/desktop_update/test_handoff_delegate_publication.py
+++ b/tests/scripts/desktop_update/test_handoff_delegate_publication.py
@@ -14,7 +14,7 @@ fcntl = pytest.importorskip("fcntl")
pytestmark = pytest.mark.platforms("linux")
from tests.scripts.desktop_update.test_desktop_update_posix_handoff_protocol import _env
-from tests.scripts.desktop_update.test_desktop_update_posix_marker import POSIX, _calls, _install
+from tests.scripts.desktop_update.test_desktop_update_posix_marker import POSIX, _calls, _custodian, _install
@pytest.mark.parametrize("claim", ["missing", "foreign"])
@@ -50,7 +50,7 @@ def test_sidecar_timeout_never_releases_the_parked_update(tmp_path):
lock_fd = None
try:
deadline = time.monotonic() + 30
- while not (marker.exists() and marker.read_text().splitlines()[0] == str(script.pid)):
+ while not (marker.exists() and _custodian(home) and marker.read_text().splitlines()[0] == _custodian(home)):
assert script.poll() is None and time.monotonic() < deadline
time.sleep(0.005)
lock_fd = os.open(str(marker) + ".lock", os.O_CREAT | os.O_RDWR, 0o600)