Skip to content

The agent that grows with you

fix(update): a lost completion after the commit point is owed, not failed

Teknium1faf3b5e761a
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 965dec28612..d9d4697f17e 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -774,12 +774,21 @@ def _complete_source_update(request: dict | None) -> None:
# A head capture that came back empty must not arm an SHA-less record: it names no code the
# fleet can be proven current on, so the warning could never clear (#125952).
_write_fleet_restart_pending_marker(expected_sha=request.get("expected_sha") or _current_checkout_sha() or "")
+ # Pre-swap module (imported with run_completion above): never the replacement tree's.
+ from hermes_cli.update_completion import settle_lost_completion
try:
result = run_completion(request)
except KeyboardInterrupt as interrupt:
# Ctrl-C after the commit point: the tree is new, so the run is interrupted, never "failed".
_completion_receipt.finalize_interrupted_update_receipt("KeyboardInterrupt: interrupted after the code was updated")
raise SystemExit(130) from interrupt
+ except Exception as exc: # health: allow BLE001 -- after the commit point a lost completion is owed, never a failed update (C3)
+ result = settle_lost_completion(request, f"{type(exc).__name__}: {exc}")
+ if result.get("receipt") is None and result["exit_code"] == 130:
+ _completion_receipt.finalize_interrupted_update_receipt("the completion was interrupted after the code was updated")
+ elif result.get("receipt") is None:
+ # The child crashed (OOM, SIGKILL) or never answered: the same owed tail (review P2).
+ result = settle_lost_completion(request, result.get("error") or f"the completion process exited {result['exit_code']}")
_accept_completion_pm_receipt(result.get("pm_receipt"), request["receipt"]["update_id"])
token = request["windows_resume"]
if token is not None and result.get("windows_resume") is not None:
@@ -788,7 +797,7 @@ def _complete_source_update(request: dict | None) -> None:
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.
+ # Dependencies owed (A6) or a lost completion: no child resumed paused gateways; this process can.
try:
_m()._resume_windows_gateways_after_update(token)
except Exception as exc: # health: allow BLE001 -- the code is committed (C3)
diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.py
index 135caec8827..bcd6b3cd620 100644
--- a/hermes_cli/update_completion.py
+++ b/hermes_cli/update_completion.py
@@ -116,8 +116,9 @@ def run_completion(request: dict) -> dict:
if code == 0 and receipt is None:
raise ValueError("completion did not publish a terminal receipt")
except (OSError, ValueError, KeyError, TypeError) as exc:
- print(f"✗ Source update completion did not finish: {exc}")
- return {"exit_code": code or 1, "receipt": None, "windows_resume": None}
+ # No correlated terminal result: the caller settles it (settle_lost_completion).
+ return {"exit_code": code or 1, "receipt": None, "windows_resume": None,
+ "error": f"{exc} (the completion process exited {code})"}
return result
@@ -218,6 +219,41 @@ def _report_desktop_build_owed(request: dict, record: dict | None, reason: str)
print(f" {DESKTOP_BUILD_OWED} {reason}", flush=True)
+def settle_lost_completion(request: dict, reason: str) -> dict:
+ """The parent's side of C3: the code is committed, but the completion never answered (review P2).
+
+ Reached when spawning or reading the completion failed (an OSError from the temporary
+ directory, the request file or Popen) or the child died without a correlated terminal result
+ (OOM, SIGKILL). The tail is owed, never a failed update: it is armed for the next launch, the
+ run's receipt is a success that names the ``completion`` follow-up, and the exit is 0 -- unless
+ the user's local changes are still parked (#122557: ``partial``, exit 1). Runs in the parent
+ (pre-swap) interpreter: everything it uses is already imported there.
+ """
+ from hermes_cli import update_receipt
+
+ print(f" ⚠ Source update completion did not finish: {reason}", flush=True)
+ receipt = _read_terminal_receipt(request) # the child finalized the run, then died
+ if receipt is None:
+ try:
+ from hermes_cli.venv_sync import arm_completion
+
+ arm_completion(Path(request["source"]))
+ except Exception as exc: # health: allow BLE001 -- post-commit boundary: stale dependencies still make the next launch sync
+ print(f" ⚠ Could not record the owed source-update tail: {exc}")
+ _report_desktop_build_owed(request, _running_record(request), "the update completion did not finish")
+ update_receipt.record_followup("completion", reason, retry="the next launch or `hermes update` finishes it")
+ parked = not _record_owed_user_action(request)
+ if parked:
+ print(_owed_user_action(request)) # the completion child that prints it may never have run
+ update_receipt.finalize_pending_update_receipt(1 if parked else 0, "completion owed after the code was updated")
+ receipt = _read_terminal_receipt(request)
+ outcome = (receipt or {}).get("outcome")
+ code = 130 if outcome == "interrupted" else 1 if outcome == "partial" else 0
+ if code == 0:
+ _publish_gateway_success(request)
+ return {"exit_code": code, "receipt": receipt, "windows_resume": None, "pm_receipt": None}
+
+
def _settle_after_commit(request: dict, result_path: Path, step: str, reason: str) -> int:
"""The tree already moved, so a failure here is owed work, never a failed update (C3, A6).
diff --git a/tests/hermes_cli/test_update_completion_process.py b/tests/hermes_cli/test_update_completion_process.py
index 2dc5d811e29..032092faadc 100644
--- a/tests/hermes_cli/test_update_completion_process.py
+++ b/tests/hermes_cli/test_update_completion_process.py
@@ -248,13 +248,11 @@ def test_old_process_new_git_tree_completes_in_fresh_python(transition, tmp_path
assert [e["name"] for e in events].index("exit_marker") < [e["name"] for e in events].index("restart")
[email protected]("code", [0, 23])
-def test_missing_child_result_fails_boundary_receipt_and_releases_lock(transition, monkeypatch, code):
+def _run_cmd_update(monkeypatch, request, capsys):
+ """``hermes update --gateway`` whose impl hands this request to the real post-commit completion."""
from types import SimpleNamespace
- from hermes_cli import main, update_cmd, update_receipt, update_lock
+ from hermes_cli import main, update_cmd, update_receipt
- root, git, old, new, request = transition
- (root / "hermes_cli/update_completion.py").write_text(f"import os\nos._exit({code})\n")
monkeypatch.setenv("HERMES_HOME", request["home"])
monkeypatch.setattr(main, "_update_preflight_handled", lambda args: False)
monkeypatch.setattr(main, "_install_hangup_protection", lambda **kw: None)
@@ -266,20 +264,78 @@ def test_missing_child_result_fails_boundary_receipt_and_releases_lock(transitio
update_cmd._complete_source_update(request)
monkeypatch.setattr(update_cmd, "_cmd_update_impl", complete)
- with pytest.raises(SystemExit) as error:
+ try:
main.cmd_update(SimpleNamespace(gateway=True))
- assert error.value.code == (code or 1)
- receipt = update_receipt.read_latest_receipt()
- assert receipt["outcome"] == "failed"
- assert receipt["exit_code"] == (code or 1)
+ code = 0
+ except SystemExit as exc:
+ code = exc.code
+ return code, update_receipt.read_latest_receipt(), capsys.readouterr().out
+
+
[email protected]("code", [0, 23, -9])
+def test_missing_child_result_is_an_owed_completion_and_releases_lock(transition, monkeypatch, capsys, code):
+ """Review P2 (invariant 3): the tree already moved, so a completion that died without a result
+ (exit 0/23 with no answer, SIGKILL/OOM) is an owed ``completion`` follow-up, never "Update failed".
+
+ Was exit ``code or 1``, receipt ``failed``, ``.update_exit_code`` 1 and the paused gateways left
+ paused: that pinned the failure invariant 3 forbids.
+ """
+ from hermes_cli import update_lock
+
+ root, git, old, new, request = transition
+ die = f"os._exit({code})" if code >= 0 else "os.kill(os.getpid(), 9)"
+ (root / "hermes_cli/update_completion.py").write_text(f"import os\n{die}\n")
+ exit_code, receipt, out = _run_cmd_update(monkeypatch, request, capsys)
+ assert exit_code == 0, out
assert receipt["update_id"] == request["receipt"]["update_id"]
- assert request["windows_resume"]["resume_needed"] is True
- assert (Path(request["home"]) / ".update_exit_code").read_text().strip() == "1"
+ assert receipt["outcome"] == "success"
+ assert receipt["exit_code"] == 0
+ assert [row["step"] for row in receipt["followups"]] == ["completion"]
+ assert "Update failed" not in out
+ # The Desktop hand-off scripts must not read this as a plain "Update complete." (review P4).
+ assert "Desktop app build owed: the update completion did not finish" in out
+ # This process resumes what the lost child never did, and the gateway watcher hears success.
+ assert request["windows_resume"]["resume_needed"] is False
+ assert (Path(request["home"]) / ".update_exit_code").read_text().strip() == "0"
lock = update_lock.UpdateLock()
assert lock.acquire()
lock.release()
+def test_completion_spawn_failure_after_commit_is_owed(transition, monkeypatch, capsys):
+ """Review P2: an OSError while starting the completion (temporary directory, request file,
+ Popen) after the commit point is the same owed ``completion`` follow-up and exit 0."""
+ import tempfile
+
+ root, git, old, new, request = transition
+
+ def no_temporary_directory(*args, **kwargs):
+ raise FileNotFoundError(2, "No usable temporary directory found")
+
+ monkeypatch.setattr(tempfile, "TemporaryDirectory", no_temporary_directory)
+ exit_code, receipt, out = _run_cmd_update(monkeypatch, request, capsys)
+ assert exit_code == 0, out
+ assert receipt["outcome"] == "success"
+ assert [row["step"] for row in receipt["followups"]] == ["completion"]
+ assert "No usable temporary directory" in receipt["followups"][0]["reason"]
+ assert (Path(request["home"]) / ".update_exit_code").read_text().strip() == "0"
+
+
+def test_lost_completion_with_parked_local_changes_stays_partial(transition, monkeypatch, capsys):
+ """The one documented exception survives the owed path: parked user changes still exit 1."""
+ from hermes_cli import update_cmd
+
+ root, git, old, new, request = transition
+ (root / "hermes_cli/update_completion.py").write_text("import os\nos._exit(0)\n")
+ notice = "⚠ Your local changes are parked in stash@{0}; re-apply them by hand."
+ monkeypatch.setattr(update_cmd, "_unrestored_autostash_notice", lambda: notice)
+ exit_code, receipt, out = _run_cmd_update(monkeypatch, request, capsys)
+ assert exit_code == 1, out
+ assert receipt["outcome"] == "partial"
+ assert [row["step"] for row in receipt["followups"]] == ["completion"]
+ assert notice in out
+
+
@pytest.mark.platforms("posix")
@pytest.mark.parametrize("never_built", ["dependencies", "refused", "died"])
@pytest.mark.parametrize("desktop", [True, False])