Skip to content

The agent that grows with you

fix(install-metrics): a Ctrl-C a stage handles no longer aborts the install; user aborts read interrupted

Teknium5f7f9e143d5f
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 06b3bd94d02..4a197c92358 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -344,7 +344,7 @@ function Initialize-ResolvedPaths {
$storeInside = $cmpStore -eq $cmpDir -or
$cmpStore.StartsWith($dirPrefix, [StringComparison]::OrdinalIgnoreCase)
if ($storeInside) {
- Fail "HermesHome ($resolvedHome) cannot be the install directory or live inside it ($resolvedDir): the tool store would land inside the checkout. Use a separate -HermesHome, or point HERMES_RUNTIME_DIR outside -InstallDir." other
+ Fail "HermesHome ($resolvedHome) cannot be the install directory or live inside it ($resolvedDir): the tool store would land inside the checkout. Use a separate -HermesHome, or point HERMES_RUNTIME_DIR outside -InstallDir."
}
# The param() variables live in the CALLER's scope, which is the script
# scope only under -File. Under the documented
@@ -744,6 +744,7 @@ function Fail([string]$msg, [string]$Class = "other") {
function Write-InstallReceipt([string]$Outcome, [string]$FailedStage, [string]$Class) {
if ($script:InstallReceiptWritten) { return }
$script:InstallReceiptWritten = $true
+ $tmp = $null # never a caller's $tmp (dynamic scope) in the catch below
try {
$dir = Join-Path $HermesHome "telemetry\shared_metrics\pending_installs"
New-Item -ItemType Directory -Force -Path $dir | Out-Null
@@ -753,7 +754,21 @@ function Write-InstallReceipt([string]$Outcome, [string]$FailedStage, [string]$C
$tmp = Join-Path $dir ".$id.tmp"
[IO.File]::WriteAllText($tmp, $json, (New-Object System.Text.UTF8Encoding $false))
Move-Item -LiteralPath $tmp -Destination (Join-Path $dir "$id.json") -Force
- } catch {}
+ } catch {
+ # A full disk leaves a partial temp file the reader never looks at (it skips dotfiles).
+ if ($tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue }
+ }
+}
+
+# The receipt class for a ladder stage that threw. A native child Ctrl-C ended
+# (130, or Windows STATUS_CONTROL_C_EXIT 0xC000013A) is a user abort even when
+# the host did not stop the pipeline first; it beats the stage's own class.
+# (A Ctrl-C the host saw stops the pipeline: catch is skipped and finally
+# records `interrupted`.)
+function Get-StageFailureClass {
+ if ($global:LASTEXITCODE -in @(130, -1073741510, 3221225786)) { return "interrupted" }
+ if ($script:FailureClass) { return $script:FailureClass }
+ return "other"
}
function Emit-Frame([bool]$ok, [string]$name, [bool]$skipped, [string]$reason = "") {
@@ -1398,7 +1413,7 @@ try {
Write-InstallReceipt "success" "none" "none"
Write-PathReloadHint
} catch {
- Write-InstallReceipt "failed" $script:InstallStage $(if ($script:FailureClass) { $script:FailureClass } else { "other" })
+ Write-InstallReceipt "failed" $script:InstallStage (Get-StageFailureClass)
Write-Err "$_"
if ($script:RunAsFile) { exit 1 }
# Under iex: report failure without closing the user's window.
diff --git a/scripts/install.sh b/scripts/install.sh
index 74455f3c587..3fa829d1ecc 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -37,6 +37,8 @@ INSTALL_LADDER=false
INSTALL_STARTED=0
INSTALL_RUN_ID=""
FAILURE_CLASS=""
+INSTALL_SIGNAL=""
+INSTALL_IN_STAGE=false
while [ $# -gt 0 ]; do
case "$1" in
@@ -109,15 +111,54 @@ fail() { STAGE_REASON="$1"; FAILURE_CLASS="${2:-other}"; log_error "$1"; exit 1;
# unreported when collection is off. Best effort: never fails the install.
write_install_receipt() {
# $1 outcome, $2 failed stage, $3 failure class. One file per run: the first writer wins.
+ # A failed write (full disk) removes its partial temp file: the reader never sees dotfiles.
{
local dir="$HERMES_HOME/telemetry/shared_metrics/pending_installs" id="$INSTALL_RUN_ID"
- [ -n "$id" ] && [ ! -e "$dir/$id.json" ] && mkdir -p "$dir" \
- && printf '{"id":"%s","installer":"install_sh","outcome":"%s","failed_stage":"%s","failure_class":"%s","started_at":%s,"finished_at":%s}\n' \
+ [ -n "$id" ] && [ ! -e "$dir/$id.json" ] && mkdir -p "$dir" && {
+ printf '{"id":"%s","installer":"install_sh","outcome":"%s","failed_stage":"%s","failure_class":"%s","started_at":%s,"finished_at":%s}\n' \
"$id" "$1" "$2" "$3" "$INSTALL_STARTED" "$(date +%s)" > "$dir/.$id.tmp" \
- && mv -f "$dir/.$id.tmp" "$dir/$id.json"
+ && mv -f "$dir/.$id.tmp" "$dir/$id.json" \
+ || rm -f "$dir/.$id.tmp"
+ }
} >/dev/null 2>&1 || :
}
+# Ladder signal handling. The traps only note the signal while a stage owns the
+# terminal: bash runs a trap once the foreground stage returns, and that stage's
+# result decides. A stage whose child caught Ctrl-C and succeeded (setup's
+# provider picker: "Provider setup skipped.") lets the ladder carry on, as bash's
+# own wait-and-cooperative-exit did before these traps existed. A stage that
+# failed after the signal is recorded as `interrupted`, then the signal is
+# re-raised so the exit status is the signal's. A TERM or HUP sent to the
+# installer alone (not its process group) takes effect when the running stage
+# returns, and the receipt names the stage the run stopped before. The stage
+# stays in the foreground because a background stage's children ignore Ctrl-C
+# under bash 3.2 (macOS /bin/bash), even after `trap -`.
+install_signal() {
+ # $1 signal name. Outside a stage (platform check, banner, between stages) stop now.
+ INSTALL_SIGNAL="$1"
+ [ "$INSTALL_IN_STAGE" = true ] || install_interrupted
+}
+
+install_interrupted() {
+ # Record the stage the signal cut off, then die by that signal (exit code if it is blocked).
+ local stage="${s:-prerequisites}" sig="${INSTALL_SIGNAL:-INT}" code=130
+ case "$sig" in HUP) code=129 ;; TERM) code=143 ;; esac
+ write_install_receipt failed "${stage//-/_}" interrupted
+ trap - INT TERM HUP EXIT
+ kill -s "$sig" "$$" 2>/dev/null
+ exit "$code"
+}
+
+# Inside a ladder stage: a child the signal killed ends the stage like bash's own
+# cooperative exit (its status is the signal's, 128+N); a child that caught the
+# signal keeps its own result, and the stage's receipt reads `interrupted`.
+stage_signal() {
+ # $1 status of the command the signal arrived during, $2 this signal's 128+N.
+ STAGE_INTERRUPTED=true
+ [ "$1" -ne "$2" ] || exit "$2"
+}
+
print_banner() {
printf '\n%s%s' "$C_MAGENTA" "$C_BOLD"
printf '%s\n' "┌─────────────────────────────────────────────────────────┐"
@@ -399,9 +440,13 @@ stage_result() {
if [ "$JSON" = true ]; then
json_frame "$ok" "$STAGE" "${STAGE_SKIPPED:-false}" "$reason"
fi
- # 130/143 (Ctrl-C, SIGTERM) are recorded by the ladder as `interrupted`.
- if [ "$ok" = false ] && [ "${INSTALL_LADDER:-false}" = true ] && [ "$code" -ne 130 ] && [ "$code" -ne 143 ]; then
- write_install_receipt failed "${STAGE//-/_}" "${FAILURE_CLASS:-other}"
+ if [ "$ok" = false ] && [ "${INSTALL_LADDER:-false}" = true ]; then
+ local class="${FAILURE_CLASS:-other}"
+ # A user abort beats the stage's own class: a child that caught Ctrl-C and exited 1
+ # (pm, source_completion, `hermes setup`) still reaches the stage's `|| fail ... <class>`.
+ case "$code" in 129|130|143) class=interrupted ;; esac
+ [ "${STAGE_INTERRUPTED:-false}" = false ] || class=interrupted
+ write_install_receipt failed "${STAGE//-/_}" "$class"
fi
}
@@ -888,8 +933,14 @@ run_stage() (
STAGE="$1"
STAGE_REASON=""
FAILURE_CLASS=""
+ STAGE_INTERRUPTED=false
STAGE_SKIPPED=false
trap 'stage_result "$?"' EXIT
+ if [ "$INSTALL_LADDER" = true ]; then
+ trap 'stage_signal "$?" 130' INT
+ trap 'stage_signal "$?" 143' TERM
+ trap 'stage_signal "$?" 129' HUP
+ fi
if [ "$NON_INTERACTIVE" = true ] && { [ "$STAGE" = setup ] || [ "$STAGE" = gateway ]; }; then
STAGE_SKIPPED=true
STAGE_REASON="needs user input"
@@ -924,10 +975,16 @@ if [ "${BASH_SOURCE[0]:-$0}" = "$0" ]; then
trap 'stage_result "$?"' EXIT
elif [ -z "$STAGE" ]; then
INSTALL_LADDER=true
- INSTALL_STARTED="$(date +%s)"
+ INSTALL_STARTED="$(date +%s 2>/dev/null)"
INSTALL_RUN_ID="$(od -An -N16 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n')" || INSTALL_RUN_ID=""
- [ "${#INSTALL_RUN_ID}" -eq 32 ] || INSTALL_RUN_ID="$(printf '%08x%08x%08x%08x' "$RANDOM$RANDOM" "$$" "$INSTALL_STARTED" "$RANDOM")"
+ [ "${#INSTALL_RUN_ID}" -eq 32 ] || INSTALL_RUN_ID="$(printf '%08x%08x%08x%08x' "$(( RANDOM * 32768 + RANDOM ))" "$$" "${INSTALL_STARTED:-0}" "$RANDOM")"
+ # No clock, no receipt: the reader drops a receipt without both timestamps anyway.
+ case "$INSTALL_STARTED" in ''|*[!0-9]*) INSTALL_RUN_ID="" ;; esac
trap '[ "$?" -eq 0 ] || write_install_receipt failed prerequisites "${FAILURE_CLASS:-other}"' EXIT
+ # Ctrl-C, SIGTERM or a closed terminal (SIGHUP) anywhere in the run: one `interrupted` receipt.
+ trap 'install_signal INT' INT
+ trap 'install_signal TERM' TERM
+ trap 'install_signal HUP' HUP
fi
check_platform
trap - EXIT
@@ -940,15 +997,31 @@ if [ "${BASH_SOURCE[0]:-$0}" = "$0" ]; then
# No --stage: run the whole ladder — the same authoritative list the
# manifest prints, so --include-desktop inserts desktop here too.
print_banner
- # Ctrl-C / SIGTERM (a closed terminal) end the install mid-stage: one `interrupted` receipt.
- trap 'write_install_receipt failed "${s//-/_}" interrupted; exit 130' INT
- trap 'write_install_receipt failed "${s//-/_}" interrupted; exit 143' TERM
for s in $(stage_names); do
+ # A TERM/HUP noted while the previous stage ran stops the run before this one.
+ [ -z "$INSTALL_SIGNAL" ] || install_interrupted
+ INSTALL_IN_STAGE=true
run_stage "$s"
rc=$?
- case "$rc" in 0) ;; 130|143) write_install_receipt failed "${s//-/_}" interrupted; exit "$rc" ;; *) exit "$rc" ;; esac
+ INSTALL_IN_STAGE=false
+ if [ "$rc" -eq 0 ]; then
+ # The stage succeeded, so a Ctrl-C it saw was handled there: carry on.
+ [ "$INSTALL_SIGNAL" != INT ] || INSTALL_SIGNAL=""
+ continue
+ fi
+ case "$rc" in
+ 129) INSTALL_SIGNAL="${INSTALL_SIGNAL:-HUP}" ;;
+ 130) INSTALL_SIGNAL="${INSTALL_SIGNAL:-INT}" ;;
+ 143) INSTALL_SIGNAL="${INSTALL_SIGNAL:-TERM}" ;;
+ esac
+ [ -z "$INSTALL_SIGNAL" ] || install_interrupted
+ # The stage normally wrote its receipt; one killed outright (SIGKILL, OOM) did not.
+ write_install_receipt failed "${s//-/_}" other
+ exit "$rc"
done
- trap - INT TERM
write_install_receipt success none none
+ # Every stage finished: the receipt says success, and a pending TERM/HUP still ends the run.
+ [ -z "$INSTALL_SIGNAL" ] || install_interrupted
+ trap - INT TERM HUP
print_path_reload_hint
fi
diff --git a/tests/hermes_cli/test_shared_metrics_install_run.py b/tests/hermes_cli/test_shared_metrics_install_run.py
index 156b2025bee..289af50e1f3 100644
--- a/tests/hermes_cli/test_shared_metrics_install_run.py
+++ b/tests/hermes_cli/test_shared_metrics_install_run.py
@@ -6,6 +6,7 @@ import json
import os
import re
import shutil
+import signal
import subprocess
import sys
import time
@@ -62,7 +63,7 @@ def _park(home: Path, receipt: dict, name: str | None = None) -> Path:
def test_schema_and_installers_match_the_contract_exactly():
- schema = json.loads(SCHEMA.read_text(encoding="utf-8"))
+ schema = json.loads(SCHEMA.read_text(encoding="utf-8-sig"))
by_name = {d["properties"]["name"]["const"]: d for d in schema["$defs"].values() if "properties" in d}
dims = by_name[contract.INSTALL_RUN_METRIC]["properties"]["dimensions"]
assert {field: set(spec["enum"]) for field, spec in dims["properties"].items()} == {
@@ -70,7 +71,12 @@ def test_schema_and_installers_match_the_contract_exactly():
assert set(dims["required"]) == set(dims["properties"])
assert {"$ref": "#/$defs/install_run_counter"} in schema["properties"]["metrics"]["items"]["oneOf"]
- sh, ps1 = INSTALL_SH.read_text(encoding="utf-8"), INSTALL_PS1.read_text(encoding="utf-8")
+ sh, ps1 = INSTALL_SH.read_text(encoding="utf-8-sig"), INSTALL_PS1.read_text(encoding="utf-8-sig")
+ # Initialize-ResolvedPaths runs before the ladder's try, so its Fail can never write a receipt and
+ # carries no class (a class there would be dead); every ladder call site must carry one.
+ pre_ladder = re.search(r"\nfunction Initialize-ResolvedPaths \{\r?\n.*?\r?\n\}\r?\n", ps1, re.S).group(0)
+ assert re.search(r'Fail "[^\n]*-InstallDir\."\r?\n', pre_ladder)
+ ps1 = ps1.replace(pre_ladder, "\n")
# Every fail()/Fail call site passes a class from the contract, and every class is used somewhere.
sh_sites = re.findall(r'(?<![-\w])fail "(?:[^"\\$]|\\.|\$\([^)]*\)|\$)*" ?([a-z_]*)', sh)
ps1_sites = re.findall(r'(?<![-\w])Fail "(?:[^"`$]|`.|\$\([^)]*\)|\$)*" ?([a-z_$(]*)', ps1)
@@ -146,10 +152,77 @@ def test_real_install_sh_ladder_leaves_only_closed_tokens(tmp_path):
assert "git is required" in result.stderr
receipts = list(install_run.pending_installs_dir(home).glob("*.json"))
assert len(receipts) == 1
- text = receipts[0].read_text(encoding="utf-8")
+ text = receipts[0].read_text(encoding="utf-8-sig")
assert "example.invalid" not in text and str(tmp_path) not in text and "required" not in text
receipt = json.loads(text)
assert install_run.install_run_fields(receipt) == {
"duration_bucket": "lt_30s", "failed_stage": "prerequisites", "failure_class": "git_missing",
"installer": "install_sh", "outcome": "failed",
}
+
+
+_MAIN_GUARD = 'if [ "${BASH_SOURCE[0]:-$0}" = "$0" ]; then\n'
+_CHILD = """
+import pathlib, sys, time
+pathlib.Path(sys.argv[1]).write_text("ready")
+try:
+ time.sleep(30)
+except KeyboardInterrupt:
+ print("child handled Ctrl-C")
+ sys.exit(int(sys.argv[2]))
+"""
+
+
+def _ctrl_c_ladder(tmp_path: Path, child_exit: int) -> tuple[int, str, list[dict]]:
+ """The real install.sh main block and traps, with every stage body a no-op except python-deps,
+ whose child catches Ctrl-C like pm.cli / `hermes setup` do. Ctrl-C reaches the whole process
+ group, as from a terminal."""
+ script = INSTALL_SH.read_text(encoding="utf-8-sig")
+ assert script.count(_MAIN_GUARD) == 1
+ stubs = "".join(f"stage_{name}() {{ echo 'stage {name} ok'; }}\n" for name in (
+ "prerequisites", "repository", "venv", "config", "products", "setup", "gateway", "desktop", "complete"))
+ stubs += ('stage_python_deps() { "$STUB_PY" -c "$STUB_CHILD" "$STUB_READY" "$STUB_EXIT" '
+ '|| fail "pm install failed" deps_install_failed; }\nprint_banner() { :; }\n')
+ harness = tmp_path / "install-harness.sh"
+ harness.write_text(script.replace(_MAIN_GUARD, stubs + _MAIN_GUARD), encoding="utf-8")
+ home, ready = tmp_path / "home", tmp_path / "ready"
+ proc = subprocess.Popen(
+ ["bash", str(harness), "--non-interactive", "--hermes-home", str(home), "--dir", str(tmp_path / "checkout")],
+ env={"HOME": str(tmp_path), "PATH": os.environ.get("PATH", ""), "STUB_PY": sys.executable,
+ "STUB_CHILD": _CHILD, "STUB_READY": str(ready), "STUB_EXIT": str(child_exit)},
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True,
+ )
+ try:
+ deadline = time.monotonic() + 30
+ while not ready.exists() and proc.poll() is None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert ready.exists(), "the stage child never started"
+ time.sleep(0.2) # the child is inside its sleep
+ os.killpg(proc.pid, signal.SIGINT) # windows-footgun: ok (POSIX-only test)
+ out, _ = proc.communicate(timeout=30)
+ finally:
+ if proc.poll() is None:
+ os.killpg(proc.pid, signal.SIGKILL) # windows-footgun: ok (POSIX-only test)
+ receipts = [json.loads(p.read_text(encoding="utf-8-sig")) for p in install_run.pending_installs_dir(home).glob("*.json")]
+ return proc.returncode, out.decode("utf-8", "replace"), receipts
+
+
[email protected](sys.platform == "win32", reason="runs the real install.sh")
+def test_a_ctrl_c_the_stage_handles_lets_the_install_finish(tmp_path):
+ """The receipt's signal traps must never change the installer's control flow: before them, bash's
+ cooperative exit let the ladder carry on when the child caught Ctrl-C and succeeded."""
+ rc, out, receipts = _ctrl_c_ladder(tmp_path, child_exit=0)
+ assert "child handled Ctrl-C" in out
+ assert rc == 0, out
+ assert "stage complete ok" in out
+ assert [(r["outcome"], r["failed_stage"], r["failure_class"]) for r in receipts] == [("success", "none", "none")]
+
+
[email protected](sys.platform == "win32", reason="runs the real install.sh")
+def test_a_user_abort_the_child_turns_into_exit_1_is_recorded_as_interrupted(tmp_path):
+ """pm.cli / source_completion / `hermes setup` catch KeyboardInterrupt and exit 1, which reaches the
+ stage's `|| fail ... deps_install_failed`; the receipt must still say the user stopped it."""
+ rc, out, receipts = _ctrl_c_ladder(tmp_path, child_exit=1)
+ assert rc != 0 and "stage complete ok" not in out
+ assert [(r["outcome"], r["failed_stage"], r["failure_class"]) for r in receipts] == [
+ ("failed", "python_deps", "interrupted")]