The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: posix hand-off names its hermes update child as the marker delegate at spawn
Teknium2245190411d8
diff --git a/scripts/desktop-update/marker.ps1 b/scripts/desktop-update/marker.ps1index eacd8ab6d77..b9fe21990fe 100644--- a/scripts/desktop-update/marker.ps1+++ b/scripts/desktop-update/marker.ps1@@ -264,7 +264,8 @@ function Remove-MarkerIfOwned {}function Add-MarkerDelegate([int[]]$Candidates) {- # The tree could not be quiesced: name a still-running member as the+ # Name a running updater process (the `hermes update` child as soon as it+ # starts, or a member of a tree that could not be quiesced) as the# marker's delegate so every reader keeps it LIVE exactly as long as that# process lives, instead of judging it dead with this script. A2 readers# ignore a delegate line without a creation time, so a member whose time@@ -279,7 +280,7 @@ function Add-MarkerDelegate([int[]]$Candidates) {if (-not $probe.Alive -or $null -eq $probe.Ct) { continue }$line = "delegate:$candidate ct:$(Format-Ct $probe.Ct)"if (Set-MarkerIfUnchanged $seen ((Get-MarkerHead $script:MarkerBody) + "`n" + $line + "`n")) {- Write-HandoffLog "update marker now names surviving updater pid $candidate as its delegate"+ Write-HandoffLog "update marker now names updater pid $candidate as its delegate"}return}diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.shindex ae4b763cfe1..45dc6770268 100755--- a/scripts/desktop-update/posix.sh+++ b/scripts/desktop-update/posix.sh@@ -265,6 +265,28 @@ marker_release() { # compare-and-delete; never drops a marker whose delegate isMARKER_CLAIMED=0}+marker_add_delegate() { # pid -> line 4 `delegate:<pid> ct:<ct>` under our claim (C1 rule 6)+ # Written the moment the update child exists: killed in the second before+ # that child takes the update lock, this script would otherwise leave a+ # marker that reads DEAD while the update goes on. Compare-and-swap on our+ # own lines 1-3; a marker with no ct line (v1) gets no delegate.+ local pid="$1" ct seen tmp="$MARKER.$$.tmp"+ [ "$MARKER_CLAIMED" -eq 1 ] || return 0+ case "$MARKER_BODY" in *$'\n'ct:*) ;; *) return 0 ;; esac+ ct="$(proc_ct "$pid")"+ [ -n "$ct" ] || { log "WARNING: no creation time for update pid $pid; marker names no delegate"; return 0; }+ seen="$(cat "$MARKER" 2>/dev/null)" || return 0+ case "$seen"$'\n' in "$MARKER_BODY"*) ;; *) log "update marker is no longer ours; no delegate written"; return 0 ;; esac+ marker_parse "$seen"+ if [ -n "$M_DPID" ] && [ "$M_DPID" != "$pid" ] && marker_ident_live "$M_DPID" "$M_DCT"; then return 0; fi+ printf '%sdelegate:%s ct:%s\n' "$MARKER_BODY" "$pid" "$ct" > "$tmp" 2>/dev/null || { rm -f "$tmp" 2>/dev/null; return 0; }+ if [ "$(cat "$MARKER" 2>/dev/null)" = "$seen" ] && mv -f "$tmp" "$MARKER" 2>/dev/null; then+ log "update marker names update pid $pid (ct $ct) as its delegate"+ else+ rm -f "$tmp" 2>/dev/null+ fi+}+run_bounded() { # seconds cmd... -> cmd's stdout; 124 when it had to be killedlocal secs="$1" out pid i rcshift@@ -1151,11 +1173,24 @@ firun_update() { # streams straight into the log (a killed run keeps its output);# OUT = this run's slice of the log. TERM goes back to default for the child# so neither it nor anything it starts (gateways) inherits our SIG_IGN.- local offset+ # The child runs asynchronously only so its pid can go into the marker+ # (marker_add_delegate) before it does anything; a HUP/INT/QUIT that lands+ # meanwhile is handled once it exits, exactly like a foreground child.+ local offset pid sigoffset="$(wc -c < "$LOG" 2>/dev/null | tr -d '[:space:]')"- ( trap - TERM; exec "${UPDATE_INVOKE[@]}" update --yes $GATEWAY_FLAG $KEEP_STASH "${TARGET_ARGS[@]}" ) >> "$LOG" 2>&1- CODE=$?+ PENDING_SIGNAL=""+ for sig in HUP INT QUIT; do trap "PENDING_SIGNAL=\${PENDING_SIGNAL:-$sig}" "$sig"; done+ ( trap - TERM; exec "${UPDATE_INVOKE[@]}" update --yes $GATEWAY_FLAG $KEEP_STASH "${TARGET_ARGS[@]}" ) >> "$LOG" 2>&1 <&0 &+ pid=$!+ marker_add_delegate "$pid"+ while :; do+ wait "$pid"; CODE=$?+ [ "$CODE" -ne 127 ] || break # not our child any more+ kill -0 "$pid" 2>/dev/null || break # reaped: CODE is its exit status+ done+ for sig in HUP INT QUIT; do trap "on_signal $sig" "$sig"; doneOUT="$(tail -c +"$(( ${offset:-0} + 1 ))" "$LOG" 2>/dev/null)"+ [ -z "$PENDING_SIGNAL" ] || on_signal "$PENDING_SIGNAL"}log "running: ${UPDATE_INVOKE[*]} update --yes $GATEWAY_FLAG $KEEP_STASH ${TARGET_ARGS[*]}"diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1index ea91d28454b..c666e2a37aa 100644--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@ -1232,6 +1232,11 @@ function Invoke-HermesStep([string]$Exe, [string[]]$HermesArgs, [string]$Tag) {if ($null -eq $savedPythonUnbuffered) { Remove-Item Env:PYTHONUNBUFFERED -ErrorAction SilentlyContinue } else { $env:PYTHONUNBUFFERED = $savedPythonUnbuffered }}$proc = $started.Process+ # C1 rule 6: the update child is the marker's delegate from its first+ # instant. Killed before that child takes the update lock (about a second+ # of Python start-up), this script would otherwise leave a marker that+ # reads DEAD while the update goes on.+ if ($Tag -eq 'update') { Add-MarkerDelegate @($proc.Id) }$stdoutReader = $started.StandardOutput$stderrReader = $started.StandardError$job = $started.Jobdiff --git a/tests/scripts/desktop_update/test_desktop_update_posix_marker.py b/tests/scripts/desktop_update/test_desktop_update_posix_marker.pyindex 946be73988b..750ace47adc 100644--- a/tests/scripts/desktop_update/test_desktop_update_posix_marker.py+++ b/tests/scripts/desktop_update/test_desktop_update_posix_marker.py@@ -28,6 +28,11 @@ with open(os.environ['HANDOFF_CAPTURE'], 'a', encoding='utf-8') as f:f.write(' '.join(sys.argv[1:]) + '\\n')if sys.argv[1:2] == ['desktop']:sys.exit(1)+hold = os.environ.get('HANDOFF_HOLD')+if hold: # an update still running: report the pid, then wait to be released+ Path(hold + '.pid').write_text(str(os.getpid()), encoding='utf-8')+ while not Path(hold).exists():+ __import__('time').sleep(0.05)print(os.environ.get('HANDOFF_OUTPUT', ''))sys.exit(int(os.environ.get('HANDOFF_EXIT', '0')))"""@@ -226,3 +231,63 @@ def test_interrupted_app_swap_is_rolled_back_at_the_next_run(tmp_path):assert result.returncode == 0, result.stdout + result.stderrassert (app / "Contents" / "Info.plist").read_text(encoding="utf-8-sig") == "previous"assert not previous.exists() and not app.with_name("Hermes.app.new").exists()+++def _ancestry(pid: int) -> list[int]:+ chain = []+ while pid > 1:+ chain.append(pid)+ pid = int(Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(") ", 1)[1].split()[1])+ return chain+++def test_script_killed_right_after_spawning_the_update_leaves_a_live_marker(tmp_path):+ """C1 rule 6, written by the script itself: posix.sh dies (SIGKILL) while its `hermes update`+ child is only starting up and has not taken the update lock. The marker must still read LIVE+ through the child named on line 4, and turn dead once that child is gone."""+ home, install = _install(tmp_path)+ hold = tmp_path / "release-update"+ marker = home / ".hermes-update-in-progress"+ env = {**os.environ, "HOME": str(tmp_path), "TMPDIR": str(tmp_path), "HERMES_HOME": str(home),+ "HANDOFF_CAPTURE": str(tmp_path / "calls.txt"), "HERMES_RUNTIME_DIR": str(tmp_path / "store"),+ "HERMES_UPDATE_SHIM_GRACE_SECONDS": "0", "HANDOFF_HOLD": str(hold)}+ for key in ("PYTHONPATH", "PYTHONHOME", "HERMES_UPDATE_STARTED_AT"):+ env.pop(key, None)+ script = subprocess.Popen(["bash", str(POSIX), "--daemonized", "--no-ui", "--install-root", str(install)],+ env=env, cwd=tmp_path, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ start_new_session=True)+ child_pid_file = Path(str(hold) + ".pid")+ try:+ deadline = time.monotonic() + 60+ while not child_pid_file.exists():+ assert time.monotonic() < deadline and script.poll() is None, "update child never started"+ time.sleep(0.01)+ # Kill the script the moment the delegate line is there (at most 3 s after the spawn).+ settle = time.monotonic() + 3+ while time.monotonic() < settle and len(marker.read_text(encoding="utf-8-sig").splitlines()) < 4:+ time.sleep(0.005)+ script.kill()+ 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 len(lines) == 4 and 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)+ assert lines[3] == f"delegate:{delegate} ct:{_ct(delegate)}"++ # A real reader (the script itself) sees an update in progress and refuses.+ refused = _run(tmp_path, home, install, "--self-test-marker", "--no-marker-cleanup")+ assert refused.returncode == 2, refused.stdout + refused.stderr++ hold.touch()+ deadline = time.monotonic() + 30+ while Path(f"/proc/{delegate}").exists() and time.monotonic() < deadline:+ time.sleep(0.05)+ reclaimed = _run(tmp_path, home, install, "--self-test-marker", "--no-marker-cleanup")+ assert reclaimed.returncode == 0, reclaimed.stdout + reclaimed.stderr+ finally:+ hold.touch()+ if script.poll() is None:+ script.kill()+ script.wait()