Skip to content

The agent that grows with you

fix: hand-off probes the checkout lock for two syscalls and refreshes line 2 through the R6 wait

Tekniumb493b91a3358
diff --git a/scripts/desktop-update/marker-claim.ps1 b/scripts/desktop-update/marker-claim.ps1
index ca55d2f0367..1821ddb61f8 100644
--- a/scripts/desktop-update/marker-claim.ps1
+++ b/scripts/desktop-update/marker-claim.ps1
@@ -190,6 +190,8 @@ function Invoke-MarkerRelease {
if ($NoMarkerCleanup -or $script:MarkerClaim -notin @('claimed', 'adopted')) { return }
# R6: never while a survivor of the update still holds the checkout lock --
# the marker would read free while that process still mutates the checkout.
+ # Line 2 keeps its heartbeat through that wait: an old packaged Desktop would
+ # otherwise age-delete the marker 20 minutes into it.
$waited = 0
while (Test-CheckoutLockHeld) {
if ($waited -eq 0) { Write-HandoffLog "a process still holds the checkout update lock; keeping the update marker until it exits" }
@@ -197,6 +199,7 @@ function Invoke-MarkerRelease {
Write-HandoffLog "checkout update lock still held after $($waited)s; leaving the update marker"
return
}
+ Update-MarkerHeartbeat
Start-Sleep -Seconds 1
$waited++
}
diff --git a/scripts/desktop-update/marker.sh b/scripts/desktop-update/marker.sh
index ab712808cfc..4bd4efca42c 100644
--- a/scripts/desktop-update/marker.sh
+++ b/scripts/desktop-update/marker.sh
@@ -31,6 +31,7 @@ MARKER_CT_RE='^ct:([0-9]+(\.[0-9]+)?)$'
MARKER_DELEGATE_RE='^delegate:([0-9]+) ct:([0-9]+(\.[0-9]+)?)$'
MARKER_RUN_RE='^run:([A-Za-z0-9._-]{1,128})$'
MARKER_LOCK_TOOL="${MARKER_LOCK_TOOL:-}"
+MARKER_LOCK_TOOL_FORCED="$MARKER_LOCK_TOOL" # tests pin a tool; the checkout probe honours it
MY_PID="${MY_PID:-$$}"
MY_CT="${MY_CT:-}"
@@ -450,12 +451,47 @@ checkout_lock_path() {
}
checkout_lock_held() { # 0 iff some process holds the checkout kernel lock right now
- local path rc
+ # The probe takes the REAL lock, so it must never make a concurrent `hermes
+ # update` see it busy: one non-blocking try, given straight back. With perl
+ # (macOS, nearly every Linux) or python3 (the daemon already needs it) the
+ # take and the drop are two consecutive syscalls in one process that opened
+ # the file itself -- no process exit, wait or shell work in between. flock(1)
+ # can only take it on a shell fd, so there the hold spans flock(1)'s exit and
+ # our close. No tool: held (fail closed, the release waits).
+ local path rc tool="$MARKER_LOCK_TOOL_FORCED"
path="$(checkout_lock_path)"
[ -f "$path" ] || return 1
- { exec 8<"$path"; } 2>/dev/null || return 1
- fd_flock 8 0; rc=$?
- exec 8<&- # closing our probe releases it when we did get it
+ if [ -z "$tool" ]; then
+ if command -v perl >/dev/null 2>&1; then tool=perl
+ elif command -v python3 >/dev/null 2>&1; then tool=python3
+ elif command -v flock >/dev/null 2>&1; then tool=flock
+ else tool=none
+ fi
+ fi
+ case "$tool" in
+ perl)
+ perl -MFcntl=:flock -e '
+ open(my $f, "<", $ARGV[0]) or exit 2;
+ flock($f, LOCK_EX | LOCK_NB) or exit 1;
+ flock($f, LOCK_UN); exit 0' "$path"; rc=$? ;;
+ python3)
+ python3 -c '
+import fcntl, os, sys
+try:
+ fd = os.open(sys.argv[1], os.O_RDONLY)
+except OSError:
+ sys.exit(2)
+try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+except OSError:
+ sys.exit(1)
+fcntl.flock(fd, fcntl.LOCK_UN)' "$path"; rc=$? ;;
+ flock)
+ { exec 8<"$path"; } 2>/dev/null || return 1
+ flock -x -n 8; rc=$?
+ exec 8<&- ;; # closing our probe fd releases it when we did get it
+ *) rc=1 ;;
+ esac
[ "$rc" -eq 1 ]
}
diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.sh
index 6e521a46b1d..b0459e472c4 100755
--- a/scripts/desktop-update/posix.sh
+++ b/scripts/desktop-update/posix.sh
@@ -23,7 +23,8 @@
# [--sandbox-fallback] linux: the caller vouches for a sandbox opt-out
# (ELECTRON_DISABLE_SANDBOX / --no-sandbox launch)
# [--no-ui] [--no-marker-cleanup] [--self-test-ui] [--self-test-gate]
-# [--self-test-marker]
+# [--self-test-marker] [--self-test-refresh-every <seconds>] (tests only:
+# line-2 refresh cadence, default 300)
# [-- <args...>] linux: filtered launch args to replay
#
# The shim (ui.html in a chromeless browser app window) is decoration: it
@@ -51,6 +52,7 @@ NO_GATEWAY=0
NO_UI=0 NO_MARKER_CLEANUP=0 SELF_TEST_UI=0 SELF_TEST_GATE=0 SELF_TEST_MARKER=0
SELF_TEST_TCC_HEAL=0
HANDOFF_DAEMONIZED=0 HANDOFF_RUN="" MARKER_OP=""
+MARKER_REFRESH_EVERY_S=300
while [ $# -gt 0 ]; do
case "$1" in
--install-root) INSTALL_ROOT="$2"; shift 2 ;;
@@ -75,12 +77,14 @@ while [ $# -gt 0 ]; do
--self-test-tcc-heal) SELF_TEST_TCC_HEAL=1; shift ;;
--daemonized) HANDOFF_DAEMONIZED=1; shift ;;
--self-test-marker) SELF_TEST_MARKER=1; NO_UI=1; NO_MARKER_CLEANUP=1; shift ;;
+ --self-test-refresh-every) MARKER_REFRESH_EVERY_S="$2"; shift 2 ;;
--) shift; RELAUNCH_ARGS=("$@"); shift $# ;;
*) echo "unknown arg: $1" >&2; exit 64 ;;
esac
done
[ "$SELF_TEST_UI" -eq 1 ] || [ -n "$INSTALL_ROOT" ] || { echo "--install-root is required" >&2; exit 64; }
case "$DESKTOP_PID" in ''|*[!0-9]*) echo "--desktop-pid must be a pid" >&2; exit 64 ;; esac
+case "$MARKER_REFRESH_EVERY_S" in ''|0|*[!0-9]*) echo "--self-test-refresh-every must be a positive number of seconds" >&2; exit 64 ;; esac
[ -z "$HANDOFF_RUN" ] || [[ "$HANDOFF_RUN" =~ ^[A-Za-z0-9._-]{1,128}$ ]] || { echo "--handoff-run must match [A-Za-z0-9._-]{1,128}" >&2; exit 64; }
[ "$BRANCH_EXPLICIT" -eq 0 ] || [ -z "$CHANNEL" ] || { echo "--branch and --channel are mutually exclusive" >&2; exit 64; }
TARGET_ARGS=(--branch "$BRANCH")
@@ -124,21 +128,49 @@ 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.
local waited=0
- [ "$MARKER_CLAIMED" -eq 1 ] && [ "$NO_MARKER_CLEANUP" -eq 0 ] || return 0
+ [ "$MARKER_CLAIMED" -eq 1 ] && [ "$NO_MARKER_CLEANUP" -eq 0 ] || { marker_refresher_stop; return 0; }
while checkout_lock_held; do
[ "$waited" -gt 0 ] || log "a process still holds the checkout update lock; keeping the update marker until it exits"
if [ "$waited" -ge "$RELEASE_WAIT_S" ]; then
log "WARNING: checkout update lock still held after ${waited}s; leaving the update marker"
+ marker_refresher_stop
return 0
fi
sleep 1; waited=$((waited + 1))
done
+ marker_refresher_stop
marker_locked marker_release_locked
MARKER_CLAIMED=0
}
RELEASE_WAIT_S=7200
+# 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.
+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
+ done
+ marker_locked marker_refresh_locked
+ done ) </dev/null >/dev/null 2>&1 &
+ MARKER_REFRESHER=$!
+}
+marker_refresher_stop() {
+ [ -n "$MARKER_REFRESHER" ] || return 0
+ kill -KILL "$MARKER_REFRESHER" 2>/dev/null; wait "$MARKER_REFRESHER" 2>/dev/null
+ MARKER_REFRESHER=""
+}
+
run_bounded() { # seconds cmd... -> cmd's stdout; 124 when it had to be killed
local secs="$1" out pid i rc
shift
@@ -915,6 +947,7 @@ if [ "$SELF_TEST_MARKER" -eq 1 ]; then
trap - EXIT
exit 0
fi
+marker_refresher_start
# Start-of-run recovery of litter only a dead hand-off can leave (we hold the
# marker, so no other hand-off is running): an interrupted app swap, a TCC heal
@@ -1047,7 +1080,7 @@ run_update() { # streams straight into the log (a killed run keeps its output);
# but the marker names neither a live owner nor a live delegate. A
# HUP/INT/QUIT that lands meanwhile is handled once it exits, exactly like a
# foreground child.
- local offset pid sig go="${TMPDIR:-/tmp}/hermes-update-go.$$" refresher
+ local offset pid sig go="${TMPDIR:-/tmp}/hermes-update-go.$$"
offset="$(wc -c < "$LOG" 2>/dev/null | tr -d '[:space:]')"
PENDING_SIGNAL=""
for sig in HUP INT QUIT; do trap "PENDING_SIGNAL=\${PENDING_SIGNAL:-$sig}" "$sig"; done
@@ -1058,19 +1091,11 @@ run_update() { # streams straight into the log (a killed run keeps its output);
pid=$!
marker_add_delegate "$pid"
: > "$go"
- # An older packaged Desktop judges a marker by line 2 alone and deletes it
- # 20 minutes in, live owner or not: keep line 2 young while we own it.
- ( for _ in $(seq 1 100000); do
- for _ in $(seq 1 60); do sleep 5; kill -0 "$MY_PID" 2>/dev/null || exit 0; done
- marker_locked marker_refresh_locked
- done ) >/dev/null 2>&1 &
- refresher=$!
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
- kill -KILL "$refresher" 2>/dev/null; wait "$refresher" 2>/dev/null
rm -f "$go" 2>/dev/null
for sig in HUP INT QUIT; do trap "on_signal $sig" "$sig"; done
OUT="$(tail -c +"$(( ${offset:-0} + 1 ))" "$LOG" 2>/dev/null)"
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 ba9f15da0f1..fe642fed4aa 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
@@ -235,6 +235,61 @@ def test_release_waits_for_the_survivor_then_removes_the_marker(tmp_path):
assert not (home / ".hermes-update-in-progress").exists()
+def test_line_two_stays_young_through_the_r6_release_wait(tmp_path):
+ """An old packaged Desktop deletes a marker whose line 2 is 20 minutes old, live owner or
+ not. The release wait can last hours, so the refresher must outlive `hermes update`."""
+ home, install = _install(tmp_path, legacy=True)
+ marker = home / ".hermes-update-in-progress"
+ completion = tmp_path / "release-completion"
+ env = _env(tmp_path, home, HANDOFF_COMPLETION=str(completion), HANDOFF_CHECKOUT_LOCK=str(install / ".hermes-update.lock"),
+ HERMES_UPDATE_STARTED_AT=str(int(time.time()) - 600))
+ script = subprocess.Popen(["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)
+ log = home / "logs" / "desktop-update-handoff.log"
+ try:
+ deadline = time.monotonic() + 60
+ while "keeping the update marker" not in (log.read_text(encoding="utf-8-sig") if log.exists() else ""):
+ assert time.monotonic() < deadline and script.poll() is None, log.read_text(encoding="utf-8-sig")
+ time.sleep(0.05)
+ 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 time.time() - int(started) <= 3.5, started
+ finally:
+ completion.touch()
+ if script.poll() is None:
+ assert script.wait(timeout=30) == 0
+ assert not marker.exists()
+
+
+def test_checkout_lock_probe_never_makes_a_concurrent_acquire_fail(tmp_path):
+ """checkout_lock_held takes the REAL lock; a `hermes update` acquiring it non-blocking in a
+ tight loop meanwhile must (practically) never see it busy. A probe that holds it across a
+ process exit and a shell close refused ~7% of such attempts."""
+ lock = tmp_path / ".hermes-update.lock"
+ lock.touch()
+ loop = (f"log() {{ :; }}; MARKER=/dev/null INSTALL_ROOT={shlex.quote(str(tmp_path))}; . {shlex.quote(str(MARKER_SH))}; "
+ "end=$((SECONDS + 4)); n=0; while [ $SECONDS -lt $end ]; do checkout_lock_held && echo held; n=$((n + 1)); done; echo \"probes=$n\"")
+ env = {k: v for k, v in os.environ.items() if k != "MARKER_LOCK_TOOL"}
+ prober = subprocess.Popen(["bash", "-c", loop], env=env, stdout=subprocess.PIPE, text=True, encoding="utf-8")
+ attempts = refused = 0
+ while prober.poll() is None:
+ fd = os.open(lock, os.O_RDWR)
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ refused += 1
+ finally:
+ os.close(fd)
+ attempts += 1
+ time.sleep(0.002)
+ out = prober.communicate(timeout=10)[0]
+ assert attempts > 300 and "probes=" in out, (attempts, out)
+ assert refused * 100 <= attempts, f"{refused} of {attempts} acquires refused by the probe alone"
+
+
# ── pre-publication kill cell ───────────────────────────────────────────────
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_marker_ops.py b/tests/scripts/desktop_update/test_desktop_update_windows_marker_ops.py
index af885575ddd..fc7fe4f6ce8 100644
--- a/tests/scripts/desktop_update/test_desktop_update_windows_marker_ops.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_marker_ops.py
@@ -90,11 +90,12 @@ def test_marker_op_withdraw(tmp_path: Path, sleeper: subprocess.Popen) -> None:
# -- release / heartbeat (production functions in a real PowerShell process) ---
HARNESS = r"""
-param([string]$MarkerPs1, [string]$Marker, [string]$Body, [string]$Action)
+param([string]$MarkerPs1, [string]$Marker, [string]$Body, [string]$Action, [string]$InstallRoot = '', [int]$Heartbeat = 300)
$MarkerPath = $Marker
$NoMarkerCleanup = $false
function Write-HandoffLog([string]$Message) { [Console]::Error.WriteLine($Message) }
. $MarkerPs1
+$script:MarkerHeartbeatSeconds = $Heartbeat
$own = Format-Ct (Get-LiveProcessCt $PID).Ct
[System.IO.File]::WriteAllText($MarkerPath, $Body.Replace('{self}', "$PID").Replace('{selfct}', $own))
$script:MarkerClaim = 'claimed'
@@ -181,3 +182,45 @@ def test_marker_op_reclaim_reports_held_while_a_survivor_holds_the_checkout_lock
holder.wait(timeout=30)
assert _op(tmp_path, '-MarkerOp', 'reclaim')[:2] == (0, 'reclaimed\n')
assert not (tmp_path / MARKER).exists()
+
+
+def test_release_wait_keeps_line_2_young_while_the_checkout_lock_is_held(tmp_path: Path) -> None:
+ """R6 wait + old packaged Desktops: while the release waits on a survivor's checkout lock
+ (up to hours), the heartbeat keeps line 2 young, or an old Desktop age-deletes the marker."""
+ install = tmp_path / 'hermes-agent'
+ install.mkdir()
+ marker = tmp_path / MARKER
+ release = tmp_path / 'release-holder'
+ holder = subprocess.Popen([sys.executable, '-c', _CHECKOUT_HOLDER, str(install / '.hermes-update.lock'), str(release)])
+ harness = tmp_path / 'harness.ps1'
+ harness.write_text(HARNESS, encoding='utf-8')
+ started = int(time.time()) - 900
+ proc = None
+ try:
+ deadline = time.monotonic() + 30
+ while not Path(str(release) + '.ready').exists():
+ assert time.monotonic() < deadline and holder.poll() is None
+ time.sleep(0.05)
+ proc = subprocess.Popen([POWERSHELL, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(harness),
+ '-MarkerPs1', str(MARKER_PS1), '-Marker', str(marker), '-Body', f'{{self}}\n{started}\nct:{{selfct}}\n',
+ '-Action', 'release', '-InstallRoot', str(install), '-Heartbeat', '1'],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ deadline = time.monotonic() + 60
+ while not marker.exists():
+ assert time.monotonic() < deadline and proc.poll() is None, proc.communicate()
+ time.sleep(0.05)
+ seen = []
+ for _ in range(2):
+ time.sleep(4)
+ assert proc.poll() is None, proc.communicate()
+ lines = marker.read_bytes().decode().split('\n')
+ assert time.time() - int(lines[1]) <= 3, lines
+ seen.append(int(lines[1]))
+ assert seen[1] > seen[0]
+ finally:
+ release.touch()
+ holder.wait(timeout=30)
+ out, err = proc.communicate(timeout=60)
+ assert proc.returncode == 0, out + err
+ assert not marker.exists()