The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): no post-commit receipt-store, restart-IPC or profile-sync path fails the update (D5)
Tekniumca666575bb54
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex 8c49bf1946d..3e297e48c63 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -1644,7 +1644,7 @@ def _recover_after_restart_phase_abort(from hermes_cli.update_abort_recovery import _owed_stale_serve_rowsfrom hermes_cli.update_cmd import (_abort_recovery_is_complete, _recover_gateway_restart_after_abort, _surviving_pre_update_serve_runtimes,- _warn_stale_serve_runtimes, _write_gateway_update_exit_code,+ _warn_stale_serve_runtimes,)logger.debug("Gateway restart during update failed: %s", e)out.phase_errors.append(str(e))@@ -1704,11 +1704,10 @@ def _recover_after_restart_phase_abort(or _owed_stale_serve_rows(_stale_runtime_rows)or _serve_units_failed):+ # Owed restart (C3): verification records the follow-up; the /update marker stays committed.out.incomplete = True_warn_gateway_restart_phase_aborted(e, _surviving)_warn_stale_serve_runtimes(_stale_runtime_rows)- if gateway_mode:- _write_gateway_update_exit_code(False)out.record_receipt(phase_error=str(e), fresh_recovery=_recovery_result)@@ -1727,7 +1726,7 @@ def _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode: bool):Never raises: a phase abort runs fresh-child recovery and fails closed unlessevery planned gateway is verifiably covered."""- from hermes_cli.update_cmd import _m, _write_gateway_update_exit_code+ from hermes_cli.update_cmd import _m# All bookkeeping is declared before the try so abort recovery and fleet reconciliation# can read it even if the phase raises early. ``pre_restart_gateway_pids`` stays empty# until we are about to stop/drain, so an early exception has nothing to fail closed on,@@ -1787,9 +1786,8 @@ def _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode: bool):_restart_manual_gateways(out, _drain_budget)if out.failed_or_stale_units:+ # Owed restart (C3): verification records the follow-up; the /update marker stays committed.out.incomplete = True- if gateway_mode:- _write_gateway_update_exit_code(False)_warn_incomplete_gateway_fleet_restart(out.failed_or_stale_units)out.record_receipt()_force_kill_stuck_gateways(out.killed_pids)diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 2dd7c35d03e..21b490525a1 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -1331,15 +1331,15 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:def _resume_windows_gateways_and_merge_outcome(outcome, _windows_gateway_resume, gateway_mode: bool):"""Resume gateways paused for a Windows update and fold the token into ``outcome``'s systemd/launchd-stylebookkeeping so reconciliation never reports a healthy gateway as unaccounted. Must never abort the update."""- from hermes_cli.update_cmd import _m, _write_gateway_update_exit_code+ from hermes_cli.update_cmd import _mtry:_m()._resume_windows_gateways_after_update(_windows_gateway_resume)except Exception as _windows_resume_exc:+ # Owed restart, not a failed update (C3): verification records the ``gateway_restart``+ # follow-up; the gateway's /update marker keeps the committed result.outcome.incomplete = Trueoutcome.phase_errors.append(str(_windows_resume_exc))print(f" ⚠ Windows gateway service restart incomplete: {_windows_resume_exc}")- if gateway_mode:- _write_gateway_update_exit_code(False)if not isinstance(_windows_gateway_resume, dict):returndiff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex d609adf5ab9..d6ba20863e5 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -132,16 +132,21 @@ def _resume_receipt(data: dict) -> None:def _read_terminal_receipt(request: dict) -> dict | None:- from hermes_cli.update_receipt import _receipt_dir+ from hermes_cli import update_receipt# The ROOT home's receipts (the run's own file), never latest.json: another# profile/context may have finalized more recently.- directory = _receipt_dir()- for path in directory.glob(f"update_*_{request['receipt']['update_id']}.json"):- data = json.loads(path.read_text(encoding="utf-8-sig"))- if data.get("update_id") == request["receipt"]["update_id"] and data.get("finished_at"):- return data- return None+ update_id = request["receipt"]["update_id"]+ try:+ for path in update_receipt._receipt_dir().glob(f"update_*_{update_id}.json"):+ data = json.loads(path.read_text(encoding="utf-8-sig"))+ if data.get("update_id") == update_id and data.get("finished_at"):+ return data+ except (OSError, ValueError):+ pass+ # The store refused the terminal write after the commit point (loudly): this process still+ # holds the correlated terminal record it finalized, so the exit status never turns into 1.+ return update_receipt.finalized_receipt(update_id)def _running_record(request: dict) -> dict | None:diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex c8aec94bc12..cb764ceeb6e 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -45,6 +45,8 @@ from typing import Any, Optionallogger = logging.getLogger(__name__)_RECEIPT_KEEP = 20 # keep the last N receipts per profile home+#: Terminal records finalized by THIS process, by update id (see ``finalized_receipt``).+_FINALIZED: dict[str, dict[str, Any]] = {}COMMAND_BOUNDARY_STOP_REASON = "completed at command boundary"# Receipt state is per-CONTEXT, not a module global: a nested@@ -330,7 +332,8 @@ def persist_running_receipt() -> None:#: Follow-up steps whose failure leaves the source-update tail owed (``source-completion-pending``).-TAIL_FOLLOWUPS = frozenset({"dependencies", "launchers", "build", "maintenance", "config_migration", "completion"})+TAIL_FOLLOWUPS = frozenset({"dependencies", "launchers", "build", "maintenance", "profile_sync",+ "config_migration", "completion"})#: Follow-ups that mean the BUILD stage did not succeed (C3: the receipt names what actually failed):#: the products or the launchers the build publishes failed, or the tail raised before proving them.@@ -466,6 +469,9 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reasonreceipt.finalize(outcome)if stop_reason:receipt.data["stop_reason"] = stop_reason+ # The terminal facts exist before the store is touched; a store that refuses the write+ # (after the commit point) must not erase them for this process's own caller.+ _FINALIZED[str(receipt.data.get("update_id"))] = receipt.dataif fleet is not None:receipt.data["fleet"] = fleet# Manual serve restart obligations outlive one receipt rotation: carry the previous@@ -592,6 +598,17 @@ def _publish_shared_metrics(data: dict[str, Any]) -> None:record_update_receipt(data)+def finalized_receipt(update_id: str) -> Optional[dict[str, Any]]:+ """The terminal record this process finalized for ``update_id``, published or not.++ The completion child answers its parent from this when the receipt store refused the+ terminal write: the run is still correlated and terminal, only its archive is missing+ (already reported by ``⚠ Update receipt not written``).+ """+ data = _FINALIZED.get(str(update_id))+ return copy.deepcopy(data) if data is not None else None++def finalize_pending_update_receipt(exit_code: Optional[int] = None, stop_reason: str = "") -> Optional[Path]:"""Command-boundary safety net: persist a still-open receipt, if any. Never raises.diff --git a/tests/hermes_cli/test_update_completion_process.py b/tests/hermes_cli/test_update_completion_process.pyindex 013f13e9611..a5f7610288a 100644--- a/tests/hermes_cli/test_update_completion_process.py+++ b/tests/hermes_cli/test_update_completion_process.py@@ -157,7 +157,9 @@ def transition(tmp_path):"def record_stage(*args, **kwargs): pass\n""def record_build_stage(*args, **kwargs): pass\n""def record_skip(*args, **kwargs): pass\n"- "TAIL_FOLLOWUPS = frozenset({'dependencies', 'launchers', 'build', 'maintenance', 'config_migration', 'completion'})\n"+ "TAIL_FOLLOWUPS = frozenset({'dependencies', 'launchers', 'build', 'maintenance', 'profile_sync',\n"+ " 'config_migration', 'completion'})\n"+ "finalized_receipt = lambda update_id: None\n""def record_followup(step, reason, **kwargs):\n"" print(f' ⚠ Update follow-up {step!r} did not finish: {reason}')\n"" r = _current.get()\n"diff --git a/tests/hermes_cli/test_update_post_commit_safety.py b/tests/hermes_cli/test_update_post_commit_safety.pyindex 555f535eac4..66cd90d0ea5 100644--- a/tests/hermes_cli/test_update_post_commit_safety.py+++ b/tests/hermes_cli/test_update_post_commit_safety.py@@ -57,6 +57,7 @@ _CHILD = textwrap.dedent('''from hermes_cli import update_cmd_fleet_verify as verify, update_cmd_maint as maintentered = cell / "migration-entered"gateway_migrate.maybe_auto_migrate_after_update = lambda: entered.write_text("entered")+ real_restart = update_cmd._restart_gateway_fleet_after_updateupdate_cmd._restart_gateway_fleet_after_update = lambda plan, gateway_mode: fleet._GatewayRestartOutcome(incomplete=False, phase_errors=[], pre_restart_gateway_pids=[], restarted_services=[],failed_or_stale_units=[], relaunched_profiles=[], externally_supervised_profiles=[], killed_pids=set())@@ -65,6 +66,43 @@ _CHILD = textwrap.dedent('''maint._refresh_dashboard_after_update = lambda **kwargs: Noneverify._print_legacy_units_warning = lambda: Noneverify._collect_fleet_snapshot = lambda *args: []+ windows_resume = None+ marker = home / ".update_exit_code"+ if mode.startswith("ipc-"):+ # Barrier: verification starts after the restart phase returned. A gateway /update reader+ # polling the marker can consume it from here on, before the run ever finalizes.+ verify._print_legacy_units_warning = lambda: (cell / "marker-at-verify").write_text(+ marker.read_text() if marker.exists() else "absent")+ if mode in ("ipc-failed-unit", "ipc-abort"):+ # The real restart phase; only the host's service manager and process table are replaced.+ from hermes_cli import gateway as gateway_module+ update_cmd._restart_gateway_fleet_after_update = real_restart+ fleet._restart_manual_gateways = lambda out, budget: None+ fleet._force_kill_stuck_gateways = lambda pids: None+ if mode == "ipc-failed-unit":+ gateway_module.find_gateway_pids = lambda **kwargs: []+ fleet._restart_systemd_gateway_units = lambda restarted, failed, *rest: failed.append(+ "hermes-gateway-probe.service")+ else:+ def unavailable(*args, **kwargs):+ raise RuntimeError("systemctl unavailable")+ gateway_module.find_gateway_pids = unavailable+ fleet._restart_systemd_gateway_units = unavailable+ update_cmd._recover_gateway_restart_after_abort = lambda plan, **kwargs: {}+ if mode == "ipc-windows":+ # The Windows service manager refuses the paused gateway's restart.+ from hermes_cli import main as hermes_main+ def scm(token):+ if token and token.get("resume_needed"):+ raise RuntimeError("Could not restart Windows gateway service(s): HermesGatewayProbe")+ hermes_main._resume_windows_gateways_after_update = scm+ update_cmd._resume_windows_gateways_after_update = scm+ windows_resume = {"resume_needed": True, "services": ["HermesGatewayProbe"],+ "service_profiles": {"HermesGatewayProbe": "probe"}}+ if mode == "profile-sync":+ def profile_sync():+ raise SystemExit("profile skill sync exited 3")+ maint._sync_profiles_after_update = profile_syncfrom hermes_cli import update_receiptfrom hermes_cli.venv_sync import arm_completion, completion_pending_patharm_completion(source)@@ -73,25 +111,37 @@ _CHILD = textwrap.dedent('''# The completion process never inherits the parent's open receipt context.update_receipt._current.reset(update_receipt._current.get().current_token)request = {"schema": 1, "source": str(source), "home": str(home), "branch": "main", "desktop": False,- "assume_yes": True, "gateway_mode": False, "no_gateway_restart": mode == "config-ro",+ "assume_yes": True, "gateway_mode": mode.startswith("ipc-"),+ "no_gateway_restart": mode == "config-ro","pre_update_version": None, "snapshot_id": None, "sibling_snapshots": {}, "plan": None,- "receipt": receipt, "windows_resume": None}+ "receipt": receipt, "windows_resume": windows_resume}if mode == "config-ro":home.chmod(0o555) # a late filesystem failure: the profile home refuses the config write- from hermes_cli.update_completion import _finish+ if mode.startswith("receipts-blocked"):+ # The receipt store fails after the commit point: its directory is now an ordinary file.+ import shutil+ shutil.rmtree(update_receipt._receipt_dir())+ update_receipt._receipt_dir().write_text("not a directory")+ from hermes_cli.update_completion import _finish, _settle_after_committry:- code = _finish(request, cell / "result.json")+ if mode == "receipts-blocked-settle":+ code = _settle_after_commit(request, cell / "result.json", "dependencies", "dependency sync refused")+ else:+ code = _finish(request, cell / "result.json")finally:home.chmod(0o755)latest = update_receipt.read_latest_receipt() or {}+ result = json.loads((cell / "result.json").read_text()) if (cell / "result.json").exists() else None(cell / "summary.json").write_text(json.dumps({- "code": code, "outcome": latest.get("outcome"),+ "code": code, "outcome": latest.get("outcome"), "update_id": receipt["update_id"], "result": result,"followups": [row["step"] for row in latest.get("followups", [])],"stages": {mark["name"]: mark["outcome"] for mark in latest.get("stages", [])},"config_version": yaml.safe_load((home / "config.yaml").read_text())["_config_version"],"latest_config_version": DEFAULT_CONFIG["_config_version"],"pending": completion_pending_path(source).is_file(),"stamp": (source / "install-stamp.json").is_file(),+ "marker_at_verify": (cell / "marker-at-verify").read_text() if (cell / "marker-at-verify").exists() else None,+ "marker_final": marker.read_text() if marker.exists() else None,"migration_entered": entered.is_file()}))''')@@ -105,7 +155,9 @@ def _run_completion(tmp_path: Path, mode: str, *, sqlite: str | None = None) ->(root_home / name).mkdir(parents=True, exist_ok=True)env = _child_env(HOME=str(cell / "home"), HERMES_HOME=str(profile), 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_CONFIG_HOME=str(cell / "home/.config"), XDG_CACHE_HOME=str(cell / "home/.cache"),+ XDG_STATE_HOME=str(cell / "home/.local/state"),+ HERMES_GATEWAY_LOCK_DIR=str(cell / "home/.local/state/hermes/gateway-locks"))if sqlite is not None:payload = json.dumps({"base_prefix": sys.base_prefix, "executable": sys.executable,"python_version": list(sys.version_info[:3]),@@ -158,6 +210,52 @@ def test_config_format_write_failure_is_owed_not_reported_complete(tmp_path):assert summary["stages"].get("build") == "success", summary["stages"][email protected]("posix")[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root ignores directory modes")+def test_profile_sync_followup_keeps_the_tail_owed(tmp_path):+ summary = _run_completion(tmp_path, "profile-sync")+ assert summary["code"] == 0, summary["output"]+ assert summary["outcome"] == "success"+ assert summary["followups"] == ["profile_sync"]+ # A profile sync that did not finish is tail work: retried by the next launch, never stamped done.+ assert summary["pending"] is True+ assert summary["stamp"] is False++[email protected]("posix")[email protected]("path", ["finish", "settle"])+def test_receipt_store_failure_after_commit_keeps_exit_zero_and_a_correlated_receipt(tmp_path, path):+ """The receipt store is written after the commit point: losing it is loud, never exit 1."""+ summary = _run_completion(tmp_path, f"receipts-blocked-{path}")+ assert "Update receipt not written" in summary["output"]+ assert summary["code"] == 0, summary["output"]+ result = summary["result"]+ assert result["exit_code"] == 0+ # run_completion's correlation gate: this run's id, terminal, and its outcome agrees with exit 0.+ receipt = result["receipt"]+ assert receipt is not None, summary["output"]+ assert receipt["update_id"] == summary["update_id"]+ assert receipt["finished_at"]+ assert receipt["outcome"] == "success"+ # Retry obligations are unchanged: owed dependencies stay armed, a finished tail is cleared.+ if path == "settle":+ assert [row["step"] for row in receipt["followups"]] == ["dependencies"]+ assert summary["pending"] is (path == "settle")++[email protected]("posix")[email protected]("branch", ["failed-unit", "abort", "windows"])+def test_restart_failure_is_owed_and_never_reported_as_a_failed_update(tmp_path, branch):+ """The gateway /update reader hears the committed success; the restart is a follow-up."""+ summary = _run_completion(tmp_path, f"ipc-{branch}")+ assert summary["code"] == 0, summary["output"]+ assert summary["outcome"] == "success"+ assert "gateway_restart" in summary["followups"], summary["output"]+ # What a reader sees between the failed restart and the run's finalize, and at the end.+ assert summary["marker_at_verify"] == "0", summary["output"]+ assert summary["marker_final"] == "0"++_RECEIPT_CHILD = textwrap.dedent('''import json, sysroot_checkout, action = sys.argv[1:3]