Skip to content

The agent that grows with you

fix(update): a refused Windows resume after the commit point never fails the update (M4)

Tekniumccfbb2e8613f
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index dd292ba496b..52c03ec25fe 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -721,6 +721,41 @@ def _source_completion_request(opts, plan, snapshot_id, windows_resume, desktop,
}
+def _settle_windows_resume(request: dict) -> None:
+ """This run's post-commit resume attempt is over (the completion child's, or the A6 branch's).
+
+ A failure is already the ``windows_resume`` follow-up, so neither the command's ``finally``
+ nor the atexit net may replay it: a replay waits again and its error would fail a committed
+ update (C3).
+ """
+ import atexit
+
+ from hermes_cli import update_cmd_windows
+
+ atexit.unregister(_m()._resume_windows_gateways_after_update)
+ atexit.unregister(update_cmd_windows._resume_windows_gateways_after_update)
+ request["windows_resume_settled"] = True
+
+
+def _resume_paused_gateways_at_exit(token: dict | None, request: dict | None) -> None:
+ """The command's last resume of gateways it paused; a failure is reported, never raised.
+
+ Raising here would replace the run's own exit (a committed update's 0, or the original
+ failure) with the restart's error. Skipped when the post-commit attempt already ran.
+ """
+ if not token or not token.get("resume_needed") or (request or {}).get("windows_resume_settled"):
+ return
+ try:
+ _m()._resume_windows_gateways_after_update(token)
+ except Exception as exc: # noqa: BLE001 — a restart failure is owed, not the update's status
+ from hermes_cli.update_receipt import _current, amend_terminal_followup, record_followup
+
+ reason = f"Windows gateway recovery failed: {exc}"
+ record_followup("windows_resume", reason)
+ if _current.get() is None and request: # the run already finalized its receipt
+ amend_terminal_followup(request["receipt"]["update_id"], "windows_resume", reason)
+
+
def _complete_source_update(request: dict | None) -> None:
# Never "Update complete!" while this run's local patches sit unrestored in the stash (#122557).
unrestored = _unrestored_autostash_notice()
@@ -751,6 +786,7 @@ def _complete_source_update(request: dict | None) -> None:
resumed = dict(result["windows_resume"])
token.clear()
token.update(resumed)
+ _settle_windows_resume(request)
elif token and token.get("resume_needed") and not result["exit_code"]:
# Dependencies owed (A6): the bootstrap child cannot resume paused gateways; this process can.
try:
@@ -761,6 +797,7 @@ def _complete_source_update(request: dict | None) -> None:
reason = f"Windows gateway recovery failed: {exc}"
record_followup("windows_resume", reason)
amend_terminal_followup(request["receipt"]["update_id"], "windows_resume", reason)
+ _settle_windows_resume(request)
if result.get("receipt") is not None:
current = _completion_receipt._current.get()
if current is not None:
@@ -1535,8 +1572,7 @@ def _cmd_update_impl(args, gateway_mode: bool):
target_sha=release_sha, completion_request=completion_request,
**({"target_repository": target_repository} if target_repository else {}))
finally:
- if _windows_gateway_resume and _windows_gateway_resume.get("resume_needed"):
- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)
+ _resume_paused_gateways_at_exit(_windows_gateway_resume, completion_request)
return
@@ -1630,5 +1666,4 @@ def _cmd_update_impl(args, gateway_mode: bool):
e, args, gateway_mode, had_desktop_app_before_update, target_sha=release_sha,
target_repository=target_repository, completion_request=completion_request)
finally:
- if _windows_gateway_resume and _windows_gateway_resume.get("resume_needed"):
- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)
+ _resume_paused_gateways_at_exit(_windows_gateway_resume, completion_request)
diff --git a/hermes_cli/update_finish.py b/hermes_cli/update_finish.py
index 96527643b76..6ccc5df1bb6 100644
--- a/hermes_cli/update_finish.py
+++ b/hermes_cli/update_finish.py
@@ -168,16 +168,21 @@ def main(context: Path, result: Path) -> int:
# receipt. Preserve the original handoff, just like preparation.
update_receipt.begin_update_receipt(previous=request.get("receipt"), correlation_id=request["update_id"])
begun = update_receipt._current.get() is not None
+ attempted = False
if resume is not None:
try:
resume(token)
- except Exception as exc:
- code = 1
- print(f"Gateway recovery failed: {exc}", file=sys.stderr, flush=True)
+ except Exception as exc: # noqa: BLE001 — a restart failure is owed, never the exit status (C3)
+ attempted = True
+ reason = f"Windows gateway recovery failed: {exc}"
+ update_receipt.record_followup("windows_resume", reason)
+ if update_receipt._current.get() is None: # the run already finalized its receipt
+ update_receipt.amend_terminal_followup(request["update_id"], "windows_resume", reason)
handled = cli_started or (begun and update_receipt._current.get() is None)
written = update_receipt.finalize_pending_update_receipt(code, "historical takeover completion")
result.write_text(json.dumps({
- "resume_handled": not token or not token.get("resume_needed"),
+ # An attempt that failed is reported here: the historical parent must not replay it.
+ "resume_handled": attempted or not token or not token.get("resume_needed"),
"receipt_handled": handled or written is not None,
}), encoding="utf-8")
return code
diff --git a/tests/hermes_cli/test_update_finish.py b/tests/hermes_cli/test_update_finish.py
index 781a71139c8..c244330e63e 100644
--- a/tests/hermes_cli/test_update_finish.py
+++ b/tests/hermes_cli/test_update_finish.py
@@ -219,6 +219,14 @@ def completion(tmp_path, monkeypatch):
(root / 'resumed-token.json').write_text(json.dumps(token))
return merge(outcome, token, gateway_mode)
update._resume_windows_gateways_and_merge_outcome = resume
+ if fault == 'scm':
+ # The Windows service manager refuses the paused gateway's restart.
+ from hermes_cli import update_cmd_windows
+ def scm(token):
+ if token and token.get('resume_needed'):
+ raise RuntimeError('Could not restart Windows gateway service(s): HermesGatewayProbe')
+ module._resume_windows_gateways_after_update = scm
+ update_cmd_windows._resume_windows_gateways_after_update = scm
spec.loader.exec_module = execute
return spec
sys.meta_path.insert(0, CompletionImports())
@@ -270,6 +278,30 @@ def test_failure_preserves_original_receipt_before_build(completion, fault):
assert not (source / "build-environment.json").exists()
+def test_refused_gateway_resume_after_commit_is_a_followup_not_exit_1(completion):
+ """C3 for the historical takeover child: the code is committed, so a Windows gateway resume
+ that the service manager refuses is an owed ``windows_resume`` follow-up, never exit 1."""
+ source, home, request, context, result, run = completion
+ request["gateway_mode"] = True
+ # A real start time names the run's archive file, so the running and terminal records share one
+ # file (the fixture's placeholder falls back to the clock and can split them across a second).
+ request["receipt"]["started_at"] = "2026-10-04T12:00:00+00:00"
+ request["windows_resume"] = {"resume_needed": True, "profiles": {}, "unmapped": [],
+ "services": ["HermesGatewayProbe"],
+ "service_profiles": {"HermesGatewayProbe": "default"}}
+ context.write_text(json.dumps(request), encoding="utf-8")
+ child = run("scm")
+ assert child.returncode == 0, child.stdout + child.stderr
+ receipt = json.loads((home / "logs/update_receipts/latest.json").read_text())
+ assert receipt["update_id"] == request["update_id"]
+ assert receipt["outcome"] == "success"
+ assert "windows_resume" in [row["step"] for row in receipt["followups"]], child.stdout + child.stderr
+ assert (home / ".update_exit_code").read_text().strip() == "0"
+ # The attempt is reported: the historical parent must not replay it at its own exit.
+ assert json.loads(result.read_text())["resume_handled"] is True
+
+
@pytest.mark.platforms("posix")
@pytest.mark.parametrize("captured, installed, expected", [
(None, None, False),
diff --git a/tests/hermes_cli/test_update_post_commit_safety.py b/tests/hermes_cli/test_update_post_commit_safety.py
index 66cd90d0ea5..7b7c4d92193 100644
--- a/tests/hermes_cli/test_update_post_commit_safety.py
+++ b/tests/hermes_cli/test_update_post_commit_safety.py
@@ -256,6 +256,97 @@ def test_restart_failure_is_owed_and_never_reported_as_a_failed_update(tmp_path,
assert summary["marker_final"] == "0"
+# The NEW tree's completion child after a committed update whose Windows resume the service
+# manager refused (what _finish answers): the run is a success with a windows_resume follow-up,
+# and the token it hands back still owes the restart.
+_REFUSED_RESUME_COMPLETION = textwrap.dedent('''
+ import json, os, sys
+ from pathlib import Path
+ request = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8-sig"))
+ receipts = Path(os.environ["PROBE_RECEIPTS"])
+ receipt = dict(request["receipt"], outcome="success", exit_code=0, finished_at="now", followups=[
+ {"step": "windows_resume", "reason": "Windows gateway recovery failed: refused"}])
+ payload = json.dumps(receipt)
+ (receipts / ("update_probe_" + receipt["update_id"] + ".json")).write_text(payload)
+ (receipts / "latest.json").write_text(payload)
+ (Path(request["home"]) / ".update_exit_code").write_text("0")
+ Path(sys.argv[2]).write_text(json.dumps({
+ "schema": 1, "update_id": receipt["update_id"], "exit_code": 0, "receipt": receipt,
+ "windows_resume": dict(request["windows_resume"], resume_needed=True)}))
+''')
+
+_ZIP_PARENT = textwrap.dedent('''
+ import json, os, sys
+ from pathlib import Path
+ from types import SimpleNamespace
+ root_checkout, cell = sys.argv[1:3]
+ sys.path.insert(0, root_checkout)
+ cell = Path(cell)
+ calls = cell / "parent-resume-calls.jsonl"
+ from hermes_cli import main as hermes_main, update_cmd, update_inventory, update_receipt
+ hermes_main.PROJECT_ROOT = cell / "source"
+ receipts = update_receipt._receipt_dir()
+ receipts.mkdir(parents=True, exist_ok=True)
+ os.environ["PROBE_RECEIPTS"] = str(receipts)
+ # Machine boundaries only: the host's process inventory, backups, terminal/hangup handling,
+ # the Windows service manager, and the ZIP download + swap (a no-.git install).
+ def no_inventory():
+ raise RuntimeError("the host's runtime inventory is not part of this probe")
+ update_inventory.collect_runtime_inventory = no_inventory
+ hermes_main._update_preflight_handled = lambda args: False
+ hermes_main._install_hangup_protection = lambda **kwargs: None
+ hermes_main._finalize_update_output = lambda state: None
+ hermes_main._run_pre_update_backup = lambda args: None
+ token = {"resume_needed": True, "profiles": {}, "unmapped": [], "services": ["HermesGatewayProbe"],
+ "service_profiles": {"HermesGatewayProbe": "probe"}}
+ hermes_main._pause_windows_gateways_for_update = lambda: token
+ def scm(resume_token):
+ with calls.open("a") as handle:
+ handle.write(json.dumps(bool(resume_token and resume_token.get("resume_needed"))) + "\\n")
+ if resume_token and resume_token.get("resume_needed"):
+ raise RuntimeError("Could not restart Windows gateway service(s): HermesGatewayProbe")
+ hermes_main._resume_windows_gateways_after_update = scm
+ update_cmd._prepare_git_command = lambda: (True, None, False)
+ def via_zip(args, *, had_desktop_app_before_update, target_sha=None, completion_request=None, **kwargs):
+ completion_request["expected_sha"] = target_sha
+ completion_request["apply_mode"] = "zip"
+ update_cmd._complete_source_update(completion_request)
+ update_cmd._update_via_zip = via_zip
+ class Args(SimpleNamespace):
+ def __getattr__(self, name):
+ return None
+ hermes_main.cmd_update(Args(gateway=True, branch="main", yes=True))
+''')
+
+
+def test_zip_update_never_replays_a_refused_resume_after_the_commit_point(tmp_path):
+ """The child already tried the resume and recorded the follow-up: the parent's finally and its
+ atexit net must not run it again, and a restart error must not become exit 1 / "/update failed"."""
+ cell = tmp_path / "cell"
+ home = cell / "home" / ".hermes"
+ (home / "logs/update_receipts").mkdir(parents=True)
+ completion = cell / "source" / "hermes_cli" / "update_completion.py"
+ completion.parent.mkdir(parents=True)
+ completion.write_text(_REFUSED_RESUME_COMPLETION, encoding="utf-8")
+ env = _child_env(HOME=str(cell / "home"), HERMES_HOME=str(home), HERMES_DISABLE_LAZY_INSTALLS="1",
+ HERMES_RUNTIME_DIR=str(tmp_path / "store"), PYTHONDONTWRITEBYTECODE="1",
+ XDG_CONFIG_HOME=str(cell / "home/.config"), XDG_CACHE_HOME=str(cell / "home/.cache"),
+ XDG_STATE_HOME=str(cell / "home/.local/state"))
+ driver = tmp_path / "zip_parent.py"
+ driver.write_text(_ZIP_PARENT, encoding="utf-8")
+ done = subprocess.run([sys.executable, "-B", str(driver), str(ROOT), str(cell)],
+ env=env, cwd=tmp_path, capture_output=True, text=True, timeout=240)
+ output = done.stdout + done.stderr
+ assert done.returncode == 0, output
+ assert (home / ".update_exit_code").read_text().strip() == "0", output
+ calls = cell / "parent-resume-calls.jsonl"
+ assert not calls.exists(), calls.read_text() + output
+ latest = json.loads((home / "logs/update_receipts/latest.json").read_text(encoding="utf-8-sig"))
+ assert latest["outcome"] == "success"
+ assert [row["step"] for row in latest["followups"]] == ["windows_resume"]
+
+
_RECEIPT_CHILD = textwrap.dedent('''
import json, sys
root_checkout, action = sys.argv[1:3]