The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a takeover finish child that cannot start after the commit is owed, not failed
Tekniumda91b1fe8c97
diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.pyindex 3430bca0add..51334f4da83 100644--- a/hermes_cli/_update_takeover.py+++ b/hermes_cli/_update_takeover.py@@ -166,32 +166,66 @@ def main() -> int:update_receipt.begin_update_receipt(previous=old_receipt, correlation_id=old_receipt.get("update_id"))request["update_id"] = update_receipt.current_correlation_id()try:- python, env = prepare(request)- request["receipt"] = update_receipt._current.get().data- context.write_text(json.dumps(request), encoding="utf-8")- # This file is new too. Direct execution bypasses normal launch-time- # update liveness checks while the waiting parent still holds its lock.- command = [str(python), "-I", "-B", "-X", "utf8", str(Path(request["root"]) / "hermes_cli/update_finish.py"),- str(context), str(result)]- from hermes_cli.update_custody import popen_post_commit-- # update_finish builds the checkout: POSIX lock fd; Windows bound to the job (or leased).- with popen_post_commit(command, label="update finish child", cwd=request["root"], env=env) as child:- try:- code = child.wait()- except BaseException:- child.kill()- raise- if code != 0 and not result.is_file():- _record_failure(request, result, code, f"completion child exited {code} without acknowledgement")- return code- except Exception as exc:- print(f"Update preparation failed: {exc}", file=sys.stderr, flush=True)- _record_failure(request, result, 1, f"historical takeover preparation failed: {exc}")- return 1+ try:+ python, env = prepare(request)+ request["receipt"] = update_receipt._current.get().data+ context.write_text(json.dumps(request), encoding="utf-8")+ except Exception as exc:+ print(f"Update preparation failed: {exc}", file=sys.stderr, flush=True)+ _record_failure(request, result, 1, f"historical takeover preparation failed: {exc}")+ return 1+ try:+ return _run_finish_child(request, context, result, python, env)+ except Exception as exc: # health: allow BLE001 -- post-commit boundary: the tree moved and the tail is armed+ _record_owed_finish(request, result, f"the update finish child could not run ({exc})")+ return 0finally:lock.release()+def _run_finish_child(request: dict, context: Path, result: Path, python: Path, env: dict) -> int:+ # This file is new too. Direct execution bypasses normal launch-time+ # update liveness checks while the waiting parent still holds its lock.+ command = [str(python), "-I", "-B", "-X", "utf8", str(Path(request["root"]) / "hermes_cli/update_finish.py"),+ str(context), str(result)]+ from hermes_cli.update_custody import popen_post_commit++ # update_finish builds the checkout: POSIX lock fd; Windows bound to the job (or leased).+ with popen_post_commit(command, label="update finish child", cwd=request["root"], env=env) as child:+ try:+ code = child.wait()+ except BaseException:+ child.kill()+ raise+ if code != 0 and not result.is_file():+ _record_failure(request, result, code, f"completion child exited {code} without acknowledgement")+ return code+++def _record_owed_finish(request: dict, result: Path, detail: str) -> None:+ """The historical updater already moved the tree and ``prepare`` armed the completion tail, so a+ finish child that could not be started or resumed is an owed follow-up, never a failed update:+ the next launch runs the tail. Receipt finalized with exit 0. Never raises."""+ from contextlib import suppress++ print(f" ⚠ The update is installed, but its finishing steps did not run: {detail}. "+ "The next `hermes` launch finishes them.", file=sys.stderr, flush=True)+ saved = None+ # Receipt/exit-code writes are best effort: a committed update exits 0 whatever they hit.+ with suppress(Exception): # health: allow BLE001 -- post-commit boundary: a receipt error never fails the update+ from hermes_cli import update_receipt++ update_receipt.record_step("historical_takeover", False, f"owed: {detail}")+ saved = update_receipt.finalize_pending_update_receipt(0, f"committed; finishing steps owed: {detail}")+ if request.get("gateway_mode"):+ with suppress(Exception): # health: allow BLE001 -- post-commit boundary: see above+ from hermes_constants import get_hermes_home++ (get_hermes_home() / ".update_exit_code").write_text("0\n", encoding="utf-8")+ with suppress(OSError): # no result file: the old updater keeps its own receipt and resumes+ result.write_text(json.dumps({"receipt_handled": saved is not None, "resume_handled": False}),+ encoding="utf-8")++if __name__ == "__main__":raise SystemExit(main())diff --git a/tests/hermes_cli/test_old_updater_takeover.py b/tests/hermes_cli/test_old_updater_takeover.pyindex ab539fad64a..ee7f0c9082d 100644--- a/tests/hermes_cli/test_old_updater_takeover.py+++ b/tests/hermes_cli/test_old_updater_takeover.py@@ -537,3 +537,46 @@ def test_takeover_arms_the_host_record_without_application_dependencies(tmp_pathassert child.returncode == 0, child.stdout + child.stderrrecord = json.loads((lock_dir / "host-update-restart.json").read_text(encoding="utf-8-sig"))assert record["expected_sha"] == head+++def test_a_finish_child_that_cannot_start_after_the_commit_is_owed_not_failed(tmp_path, monkeypatch, capsys):+ """The historical updater already moved the tree and prepare() armed the tail. A Popen/resume+ OSError starting update_finish used to land in the preparation catch-all: receipt failed,+ .update_exit_code=1, exit 1 for a committed update (review C7, invariant 3)."""+ from hermes_cli import _update_takeover, update_custody, update_lock, update_receipt+ from hermes_constants import get_hermes_home++ class _Lock:+ holder = None++ def __init__(self, **_kwargs):+ pass++ def acquire(self):+ return True++ def release(self):+ pass++ def no_child(*_args, **_kwargs):+ raise OSError(12, "Cannot allocate memory")++ monkeypatch.setattr(update_lock, "UpdateLock", _Lock)+ monkeypatch.setattr(_update_takeover, "prepare", lambda request: (Path(sys.executable), dict(os.environ)))+ monkeypatch.setattr(update_custody, "popen_post_commit", no_child)+ saved = []+ real_finalize = update_receipt.finalize_pending_update_receipt+ monkeypatch.setattr(update_receipt, "finalize_pending_update_receipt",+ lambda code=None, reason="": saved.append(code) or real_finalize(code, reason))+ root = tmp_path / "root"+ root.mkdir()+ context, result = tmp_path / "context.json", tmp_path / "result.json"+ context.write_text(json.dumps({"root": str(root), "gateway_mode": True, "receipt": {}}), encoding="utf-8")+ monkeypatch.setattr(sys, "argv", ["_update_takeover", str(context), str(result)])++ assert _update_takeover.main() == 0++ assert saved == [0]+ assert (get_hermes_home() / ".update_exit_code").read_text(encoding="utf-8").strip() == "0"+ assert json.loads(result.read_text(encoding="utf-8"))["resume_handled"] is False+ assert "finishing steps did not run" in capsys.readouterr().err