Skip to content

The agent that grows with you

test(desktop-update): kill the macOS app swap at every step and prove recovery

Teknium808520532cf7
diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.sh
index f325793db3d..7a54fe71994 100755
--- a/scripts/desktop-update/posix.sh
+++ b/scripts/desktop-update/posix.sh
@@ -25,6 +25,9 @@
# [--no-ui] [--no-marker-cleanup] [--self-test-ui] [--self-test-gate]
# [--self-test-marker] [--self-test-refresh-every <seconds>] (tests only:
# line-2 refresh cadence, default 300)
+# [--self-test-swap-interrupt] (tests only: kill the macOS bundle swap at
+# every step, prove mac_bundle_recover; see
+# swap-selftest.sh)
# [-- <args...>] linux: filtered launch args to replay
#
# The shim (ui.html in a chromeless browser app window) is decoration: it
@@ -50,7 +53,7 @@ BRANCH_EXPLICIT=0
RELAUNCH_CWD="" SANDBOX_FALLBACK=0 RELAUNCH_ARGS=()
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
+SELF_TEST_TCC_HEAL=0 SELF_TEST_SWAP=0
HANDOFF_DAEMONIZED=0 HANDOFF_RUN="" MARKER_OP=""
MARKER_REFRESH_EVERY_S=300
while [ $# -gt 0 ]; do
@@ -75,6 +78,7 @@ while [ $# -gt 0 ]; do
--self-test-ui) SELF_TEST_UI=1; shift ;;
--self-test-gate) SELF_TEST_GATE=1; shift ;;
--self-test-tcc-heal) SELF_TEST_TCC_HEAL=1; shift ;;
+ --self-test-swap-interrupt) SELF_TEST_SWAP=1; NO_UI=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 ;;
@@ -82,7 +86,7 @@ while [ $# -gt 0 ]; do
*) 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; }
+[ "$SELF_TEST_UI" -eq 1 ] || [ "$SELF_TEST_SWAP" -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; }
@@ -593,6 +597,16 @@ mac_bundle_recover() { # bundle path -- finish or roll back an interrupted swap
done
}
+# Test seams of mac_swap, inert in a real run: --self-test-swap-interrupt
+# points the copy at `cp -R` where ditto is absent (Linux) and names the step
+# boundary at which the swapper SIGSTOPs itself so the self-test can SIGKILL it
+# there (or resume it and kill it mid-copy / mid-cleanup).
+MAC_DITTO=/usr/bin/ditto SWAP_PAUSE_AT=""
+swap_checkpoint() { # step
+ [ "$SWAP_PAUSE_AT" = "$1" ] || return 0
+ kill -STOP "$(exec sh -c 'echo "$PPID"')" # this (sub)shell: bash 3.2 has no BASHPID
+}
+
mac_swap() {
local rebuilt="" c
for c in "$INSTALL_ROOT/apps/desktop/release/mac-arm64/Hermes.app" \
@@ -609,7 +623,8 @@ mac_swap() {
&& [ -d "$RELAUNCH_TARGET" ] && [ "$rebuilt" != "$RELAUNCH_TARGET" ]; then
publish_stage "Installing the new app"
mac_bundle_recover "$RELAUNCH_TARGET"
- if ! /usr/bin/ditto "$rebuilt" "$RELAUNCH_TARGET.new"; then
+ swap_checkpoint start
+ if ! "$MAC_DITTO" "$rebuilt" "$RELAUNCH_TARGET.new"; then
rm -rf "$RELAUNCH_TARGET.new" 2>/dev/null || true
DONE_NOTE="Hermes was updated, but the new app could not be staged; the previous app was kept. Run the update again."
add_warning "app-swap" "bundle copy failed; previous app kept"
@@ -619,11 +634,12 @@ mac_swap() {
# leave no app at the user's path. Defer HUP/INT/QUIT/TERM across it;
# SIGKILL there is finished by mac_bundle_recover on the next run.
trap '' HUP INT QUIT TERM
+ swap_checkpoint staged
if ! mv "$RELAUNCH_TARGET" "$RELAUNCH_TARGET.old"; then
rm -rf "$RELAUNCH_TARGET.new" 2>/dev/null || true
DONE_NOTE="Hermes was updated, but the new app could not replace the old one; the previous app was kept. Run the update again."
add_warning "app-swap" "could not move the old bundle aside; previous app kept"
- elif ! mv "$RELAUNCH_TARGET.new" "$RELAUNCH_TARGET"; then
+ elif swap_checkpoint aside; ! mv "$RELAUNCH_TARGET.new" "$RELAUNCH_TARGET"; then
if mv "$RELAUNCH_TARGET.old" "$RELAUNCH_TARGET"; then
rm -rf "$RELAUNCH_TARGET.new" 2>/dev/null || true
DONE_NOTE="Hermes was updated, but the new app could not be installed; the previous app was restored. Run the update again."
@@ -633,6 +649,7 @@ mac_swap() {
add_warning "app-swap" "bundle install failed AND rollback failed"
fi
else
+ swap_checkpoint installed
rm -rf "$RELAUNCH_TARGET.old" 2>/dev/null || true
log "swapped app bundle"
fi
@@ -910,6 +927,18 @@ if [ "$SELF_TEST_TCC_HEAL" -eq 1 ]; then
exit 0
fi
+if [ "$SELF_TEST_SWAP" -eq 1 ]; then
+ # Kills the REAL mac_swap at every step against a fixture bundle tree and
+ # checks the REAL mac_bundle_recover; never touches an installed app.
+ # tests/scripts/desktop_update/test_desktop_update_mac_swap_interrupt.py runs
+ # it on Linux and on the macOS lane of tests-os.yml.
+ trap - EXIT
+ # shellcheck source=swap-selftest.sh
+ . "$SCRIPT_DIR/swap-selftest.sh"
+ swap_selftest
+ exit $?
+fi
+
if [ "$SELF_TEST_GATE" -eq 1 ]; then
# Prints the gate decision for the given --install-root/--relaunch-target
# and exits; scripts/desktop-update/repro.sh gate asserts the matrix.
diff --git a/scripts/desktop-update/swap-selftest.sh b/scripts/desktop-update/swap-selftest.sh
new file mode 100644
index 00000000000..37a6cefe951
--- /dev/null
+++ b/scripts/desktop-update/swap-selftest.sh
@@ -0,0 +1,206 @@
+# swap-selftest.sh -- posix.sh --self-test-swap-interrupt (tests only). Bash
+# 3.2 (macOS /bin/bash) compatible.
+# shellcheck shell=bash disable=SC2034 # sets posix.sh globals its mac_swap reads
+#
+# Sourced by posix.sh; uses its REAL mac_swap and mac_bundle_recover. For each
+# interruption point of the swap, against a fixture bundle tree in a fresh
+# temp dir (never an installed app):
+# 1. run mac_swap in its own process group; it SIGSTOPs itself at the named
+# step boundary (posix.sh swap_checkpoint);
+# 2. SIGKILL the whole group there -- or resume it and SIGKILL it while the
+# next step (the ditto copy, the cleanup rm) is half done;
+# 3. run mac_bundle_recover, as the next hand-off does at start of run.
+# Invariant: the target is the COMPLETE old or the COMPLETE new bundle (the
+# whole tree is compared, version marker included), no aside/staged copy is
+# left, and a second recovery changes nothing and logs nothing.
+# Prints one "ok [cell]" / "FAIL [cell] why" line per cell; exits 1 naming
+# the failed cells.
+#
+# The swap's interruption points (mac_swap order):
+# before-stage stopped before the copy -> old, nothing staged
+# mid-stage killed during ditto -> old, partial .new
+# staged copied, before the first mv -> old, complete .new
+# aside between the two renames -> NO app, .old + .new
+# installed after the second mv, before rm -> new, complete .old
+# mid-cleanup killed during `rm -rf .old` -> new, partial .old
+# complete control: never interrupted -> new, nothing left
+# A kill between a failed second mv and its rollback mv leaves the `aside`
+# state. Each rename is one rename(2) on one volume, so there is no mid-rename
+# state to kill into.
+
+SWAP_ST_FILES="${HERMES_SELFTEST_SWAP_FILES:-1500}"
+SWAP_ST_FAILED="" SWAP_ST_CELL=""
+
+swap_st_fail() { echo "FAIL [$SWAP_ST_CELL] $*"; SWAP_ST_FAILED="$SWAP_ST_FAILED $SWAP_ST_CELL"; }
+
+swap_st_bundle() { # dir version -- a fixture Hermes.app; every file carries the version
+ local d="$1" v="$2" i=0
+ mkdir -p "$d/Contents/MacOS" "$d/Contents/Resources/payload" || return 1
+ printf '%s\n' "$v" > "$d/Contents/Resources/hermes-version"
+ printf '#!/bin/sh\necho %s\n' "$v" > "$d/Contents/MacOS/Hermes" && chmod +x "$d/Contents/MacOS/Hermes"
+ # Enough files that a kill lands inside the copy / the cleanup.
+ while [ "$i" -lt "$SWAP_ST_FILES" ]; do
+ printf '%s %s\n' "$v" "$i" > "$d/Contents/Resources/payload/f$i"; i=$((i + 1))
+ done
+}
+
+swap_st_digest() { # dir -> one checksum of the tree: every path and every file's bytes
+ [ -d "$1" ] || { echo absent; return; }
+ ( cd "$1" && { find . -print | LC_ALL=C sort; find . -type f -exec cksum {} + | LC_ALL=C sort; } ) | cksum
+}
+
+swap_st_listing() { # dir -> every path below it (the residue / no-op check)
+ ( cd "$1" && find . -print | LC_ALL=C sort )
+}
+
+swap_st_stopped() { # pid -> 0 iff the process is stopped (job-control stop)
+ case "$(ps -o stat= -p "$1" 2>/dev/null)" in *T*) return 0 ;; esac
+ return 1
+}
+
+# One interruption: run the real swap on a fresh fixture, kill it, leave the
+# wreck. 0 = the kill landed where the cell says; 1 = it did not (retryable);
+# 2 = the swap never reached the step (a hard failure).
+swap_st_interrupt() { # root pause-at mode
+ local root="$1" pause="$2" mode="$3" t pid i deadline s sentinels
+ rm -rf "$root"
+ mkdir -p "$root/Applications" "$root/hermes-agent/apps/desktop/release/mac-arm64" || return 2
+ cp -R "$SWAP_ST_ROOT/old.app" "$root/Applications/Hermes.app" || return 2
+ cp -R "$SWAP_ST_ROOT/new.app" "$root/hermes-agent/apps/desktop/release/mac-arm64/Hermes.app" || return 2
+ INSTALL_ROOT="$root/hermes-agent" RELAUNCH_TARGET="$root/Applications/Hermes.app"
+ t="$RELAUNCH_TARGET"
+ if [ "$mode" = none ]; then
+ ( FINAL_CODE=0 APP_REBUILD_FAILED=0; mac_swap ) </dev/null >/dev/null 2>&1
+ return 0
+ fi
+ # Own process group (set -m): the kill takes the swapper AND its ditto/rm
+ # child, like a crash of the whole hand-off.
+ set -m
+ ( SWAP_PAUSE_AT="$pause" FINAL_CODE=0 APP_REBUILD_FAILED=0; mac_swap ) </dev/null >/dev/null 2>&1 &
+ pid=$!
+ set +m
+ for ((i = 0; i < 600; i++)); do
+ swap_st_stopped "$pid" && break
+ kill -0 "$pid" 2>/dev/null || break
+ sleep 0.05
+ done
+ if ! swap_st_stopped "$pid"; then
+ kill -KILL -- "-$pid" 2>/dev/null; wait "$pid" 2>/dev/null
+ return 2
+ fi
+ deadline=$((SECONDS + 30))
+ case "$mode" in
+ mid-stage) # resume into the copy; kill as soon as the staged dir exists
+ kill -CONT -- "-$pid"
+ while [ ! -e "$t.new" ] && [ ! -e "$t.old" ] && [ "$SECONDS" -lt "$deadline" ]; do :; done ;;
+ mid-cleanup) # resume into `rm -rf .old`; kill once it has deleted anything
+ # Builtin tests only (no fork per poll): a dozen files spread over the
+ # tree, whichever the rm reaches first.
+ sentinels=("$t.old/Contents/Resources/hermes-version" "$t.old/Contents/MacOS/Hermes")
+ for ((i = 0; i < SWAP_ST_FILES; i += SWAP_ST_FILES / 10 + 1)); do
+ sentinels+=("$t.old/Contents/Resources/payload/f$i")
+ done
+ kill -CONT -- "-$pid"
+ while [ "$SECONDS" -lt "$deadline" ]; do
+ for s in "${sentinels[@]}"; do [ -e "$s" ] || break 2; done
+ done ;;
+ esac
+ kill -KILL -- "-$pid" 2>/dev/null; wait "$pid" 2>/dev/null
+ case "$mode" in
+ mid-stage) # the staged copy must be there and incomplete
+ [ -d "$t.new" ] && [ "$(swap_st_digest "$t.new")" != "$SWAP_ST_NEW" ] || return 1 ;;
+ mid-cleanup) # the aside copy must be there and partly deleted
+ [ -d "$t.old" ] && [ "$(swap_st_digest "$t.old")" != "$SWAP_ST_OLD" ] || return 1 ;;
+ esac
+ return 0
+}
+
+swap_st_shape() { # dir complete-digest complete-word -> complete-word | old | new | absent | partial
+ # (no case inside $(...): bash 3.2 mis-parses its pattern parens there)
+ local d
+ d="$(swap_st_digest "$1")"
+ if [ "$d" = "$2" ]; then echo "$3"
+ elif [ "$d" = "$SWAP_ST_OLD" ]; then echo old
+ elif [ "$d" = "$SWAP_ST_NEW" ]; then echo new
+ elif [ "$d" = absent ]; then echo absent
+ else echo partial; fi
+}
+
+swap_st_state() { # target -> the wreck's shape before recovery, for the cell's precondition
+ echo "target=$(swap_st_shape "$1" "$SWAP_ST_OLD" old) old=$(swap_st_shape "$1.old" "$SWAP_ST_OLD" complete) new=$(swap_st_shape "$1.new" "$SWAP_ST_NEW" complete)"
+}
+
+swap_st_cell() { # cell pause-at mode expected-wreck expected-bundle
+ local cell="$1" pause="$2" mode="$3" want_state="$4" want="$5"
+ local root="$SWAP_ST_ROOT/$1" t attempt rc state got leftover r before log_lines
+ SWAP_ST_CELL="$cell"
+ t="$root/Applications/Hermes.app"
+ for attempt in 1 2 3 4 5; do
+ swap_st_interrupt "$root" "$pause" "$mode"; rc=$?
+ [ "$rc" -eq 1 ] || break
+ done
+ case "$rc" in
+ 1) swap_st_fail "could not land the kill inside the step in 5 tries"; return ;;
+ 2) swap_st_fail "the swap never stopped at its '$pause' step"; return ;;
+ esac
+ state="$(swap_st_state "$t")"
+ [ "$state" = "$want_state" ] || { swap_st_fail "wreck before recovery is '$state', expected '$want_state'"; return; }
+
+ mac_bundle_recover "$t" >/dev/null 2>&1
+
+ case "$(swap_st_digest "$t")" in
+ "$SWAP_ST_OLD") got=old ;;
+ "$SWAP_ST_NEW") got=new ;;
+ absent) swap_st_fail "no app at the target after recovery ($state)"; return ;;
+ *) swap_st_fail "the target is neither the complete old nor the complete new bundle after recovery ($state)"; return ;;
+ esac
+ [ "$got" = "$want" ] || { swap_st_fail "recovered to the $got bundle, expected $want ($state)"; return; }
+ leftover=""
+ for r in .old .new .hermes-update-old .hermes-update-new; do
+ [ ! -e "$t$r" ] || leftover="$leftover $t$r"
+ done
+ [ -z "$leftover" ] || { swap_st_fail "left after recovery:$leftover"; return; }
+
+ before="$(swap_st_listing "$root/Applications")"
+ log_lines="$(wc -l < "$LOG")"
+ mac_bundle_recover "$t" >/dev/null 2>&1
+ [ "$(swap_st_listing "$root/Applications")" = "$before" ] \
+ || { swap_st_fail "a second recovery changed the tree"; return; }
+ [ "$(wc -l < "$LOG")" -eq "$log_lines" ] \
+ || { swap_st_fail "a second recovery was not a no-op: $(tail -n 1 "$LOG")"; return; }
+ echo "ok [$cell] $state -> $got bundle (attempt $attempt)"
+ rm -rf "$root"
+}
+
+swap_selftest() {
+ SWAP_ST_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/hermes-swap-selftest.XXXXXX")" || return 1
+ LOG="$SWAP_ST_ROOT/handoff.log" STATUS="$SWAP_ST_ROOT/status"
+ : > "$LOG"
+ if [ ! -x "$MAC_DITTO" ]; then
+ # Linux: the same staged copy, by cp (ditto exists only on macOS).
+ # shellcheck disable=SC2016 # the shim's own "$1" "$2"
+ printf '#!/bin/sh\nexec cp -R "$1" "$2"\n' > "$SWAP_ST_ROOT/ditto" && chmod +x "$SWAP_ST_ROOT/ditto"
+ MAC_DITTO="$SWAP_ST_ROOT/ditto"
+ fi
+ echo "swap self-test: $(uname -s), copy=$MAC_DITTO, root=$SWAP_ST_ROOT"
+ if ! swap_st_bundle "$SWAP_ST_ROOT/old.app" old-1.0 || ! swap_st_bundle "$SWAP_ST_ROOT/new.app" new-2.0; then
+ echo "FAIL [fixture] could not build the fixture bundles"; return 1
+ fi
+ SWAP_ST_OLD="$(swap_st_digest "$SWAP_ST_ROOT/old.app")" SWAP_ST_NEW="$(swap_st_digest "$SWAP_ST_ROOT/new.app")"
+
+ # cell pause-at mode wreck before recovery after
+ swap_st_cell before-stage start kill "target=old old=absent new=absent" old
+ swap_st_cell mid-stage start mid-stage "target=old old=absent new=partial" old
+ swap_st_cell staged staged kill "target=old old=absent new=complete" old
+ swap_st_cell aside aside kill "target=absent old=complete new=complete" old
+ swap_st_cell installed installed kill "target=new old=complete new=absent" new
+ swap_st_cell mid-cleanup installed mid-cleanup "target=new old=partial new=absent" new
+ swap_st_cell complete "" none "target=new old=absent new=absent" new
+
+ if [ -n "$SWAP_ST_FAILED" ]; then
+ echo "swap self-test FAILED:$SWAP_ST_FAILED (fixture kept at $SWAP_ST_ROOT)"
+ return 1
+ fi
+ rm -rf "$SWAP_ST_ROOT"
+ echo "swap self-test passed: every interruption recovers to a complete bundle"
+}
diff --git a/tests/scripts/desktop_update/test_desktop_update_mac_swap_interrupt.py b/tests/scripts/desktop_update/test_desktop_update_mac_swap_interrupt.py
new file mode 100644
index 00000000000..a4159db3e8c
--- /dev/null
+++ b/tests/scripts/desktop_update/test_desktop_update_mac_swap_interrupt.py
@@ -0,0 +1,59 @@
+"""An interrupted macOS app swap always comes back as one complete bundle.
+
+The Desktop hand-off (``scripts/desktop-update/posix.sh::mac_swap``) replaces
+the installed ``Hermes.app`` by staging a ditto copy, renaming the old bundle
+aside and renaming the copy in. A hand-off killed anywhere in that sequence is
+finished or rolled back by ``mac_bundle_recover`` on the next run.
+
+``posix.sh --self-test-swap-interrupt`` runs the REAL ``mac_swap`` on a fixture
+bundle tree, SIGKILLs its process group at every step boundary and mid-copy /
+mid-cleanup, then runs the REAL ``mac_bundle_recover`` and checks the
+invariant: the target is the complete old or the complete new bundle, no
+aside/staged copy is left, and a second recovery is a no-op. ``posix`` because
+the swap and recovery are mv/rm/ditto; on Linux the self-test stages with
+``cp -R`` (ditto is macOS-only), and the macOS lane of tests-os.yml runs the
+same arm with the real ``/usr/bin/ditto``.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+POSIX_SH = REPO_ROOT / "scripts" / "desktop-update" / "posix.sh"
+
+# Every interruption point, in swap order (swap-selftest.sh header).
+CELLS = (
+ "before-stage",
+ "mid-stage",
+ "staged",
+ "aside",
+ "installed",
+ "mid-cleanup",
+ "complete",
+)
+
+
+def test_killed_app_swap_recovers_to_a_complete_bundle(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ home.mkdir()
+ proc = subprocess.run(
+ ["/bin/bash", str(POSIX_SH), "--self-test-swap-interrupt"],
+ env={
+ "PATH": "/usr/bin:/bin:/usr/sbin:/sbin",
+ "HOME": str(home),
+ "HERMES_HOME": str(home),
+ "TMPDIR": str(tmp_path),
+ },
+ capture_output=True,
+ text=True,
+ timeout=240,
+ )
+ report = proc.stdout + proc.stderr
+ assert proc.returncode == 0, report
+ for cell in CELLS:
+ assert f"ok [{cell}]" in proc.stdout, f"cell {cell} did not pass:\n{report}"