The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): an unreadable retired list never makes a completed pause owed again
Tekniumb29247ef8bd6
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 2e0c1dd7714..7ff26be2002 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -942,7 +942,8 @@ def _pause_windows_gateways_for_update() -> dict | None:import gateway.status # noqa: F401 — fail before the first stop, not half-way through itfrom hermes_cli.gateway import _capture_gateway_argvfrom hermes_cli import update_pause_record as pause_record- adopted, claims = pause_record.adopt_orphans()+ with _abort_on_error("Could not read the gateways an earlier update paused"):+ adopted, claims = pause_record.adopt_orphans()profile_processes, service_gateways, service_gateway_pids, running_pids = _discover_windows_gateways()if not running_pids:return _cold_start_pause_token(adopted, claims)diff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.pyindex a71e8975c57..fc08695cbb8 100644--- a/hermes_cli/update_pause_record.py+++ b/hermes_cli/update_pause_record.py@@ -27,6 +27,8 @@ whose id another file carries as a copy, never as a second obligation, and the nretires it. Completing an obligation first adds its ids to ``<record stem>.retired`` (atomic), thenunlinks its files: an unlink Windows refuses (a reader holding the file withoutFILE_SHARE_DELETE) leaves a copy that is redundant by id, never an obligation that executes again.+The list is read only under the mutex, and only its absence means "nothing retired": a list that+cannot be read means unknown, so nothing is claimed and the list is never rewritten from that read."""from __future__ import annotations@@ -92,8 +94,12 @@ class RecordBusy(OSError):"""Another process held the record mutex past the bounded wait."""+class RetiredUnknown(OSError):+ """The retired-id list exists but cannot be read: which obligations are complete is unknown."""++@contextmanager-def _mutex():+def _mutex(wait_s: float = _MUTEX_WAIT_S):"""Exclusive kernel lock on the record directory's sidecar (A7). Re-entrant in-process."""global _mutex_depthif _mutex_depth:@@ -108,7 +114,7 @@ def _mutex():path.parent.mkdir(parents=True, exist_ok=True)fd = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_BINARY", 0), 0o644)try:- deadline = time.monotonic() + _MUTEX_WAIT_S+ deadline = time.monotonic() + wait_swhile not update_lock._try_lock(fd):if time.monotonic() > deadline:raise RecordBusy(f"{path} is held by another process")@@ -323,21 +329,30 @@ def _retired_path(path: Path) -> Path:def _retired(path: Path) -> set[str]:+ """The completed obligation ids (call under the mutex). Only an absent list is empty: one that+ exists but cannot be read raises :class:`RetiredUnknown`, so a completed obligation is never+ claimed again and the list is never rewritten from a read that failed."""+ target = _retired_path(path)try:- ids = json.loads(_retired_path(path).read_text(encoding="utf-8-sig")).get("ids")- except (OSError, ValueError, AttributeError):+ ids = json.loads(target.read_text(encoding="utf-8-sig")).get("ids")+ except FileNotFoundError:return set()- return {str(i) for i in ids} if isinstance(ids, list) else set()+ except (OSError, ValueError, AttributeError) as exc:+ raise RetiredUnknown(f"cannot read the retired paused-gateway list {target}: {exc}") from exc+ if not isinstance(ids, list):+ raise RetiredUnknown(f"the retired paused-gateway list {target} is malformed")+ return {str(i) for i in ids}def _retire(path: Path, carriers: list[tuple[Path, dict]]) -> None:"""Complete the obligations *carriers* hold (call under the mutex): their ids (and every id- they absorbed) go on the durable retired list FIRST; a failed write raises and deletes+ they absorbed) go on the durable retired list FIRST; a failed read or write raises and deletesnothing. Then the files go; one that cannot be deleted is a redundant copy from here on."""ids = {str(i) for _src, body in carriersfor i in [body["token"].get("pause_id"), *(body["token"].get("absorbed") or [])] if i}- if not ids <= _retired(path):- _atomic_write(_retired_path(path), {"schema": 1, "ids": sorted(_retired(path) | ids)})+ retired = _retired(path)+ if not ids <= retired:+ _atomic_write(_retired_path(path), {"schema": 1, "ids": sorted(retired | ids)})for src, _body in carriers:with suppress(OSError):src.unlink()@@ -392,9 +407,13 @@ def _survey(path: Path) -> tuple[list[tuple[Path, dict]], set[Path], set[Path]]:def orphans(path: Path | None = None) -> list[tuple[Path, dict]]:"""``(file, body)`` for every obligation of this checkout whose holder is dead — one file per- obligation id; empty while another update is live (it adopts them itself)."""+ obligation id; empty while another update is live (it adopts them itself). Surveyed under the+ mutex (a mutator replaces the retired list meanwhile); raises when the list cannot be read."""path = path or record_path()- found, held, redundant = _survey(path)+ if not path.exists() and not _claims(path):+ return []+ with _mutex():+ found, held, redundant = _survey(path)found = [(src, body) for src, body in found if src not in held and src not in redundant]if not found or _live_update_elsewhere():return []diff --git a/tests/hermes_cli/test_update_pause_record.py b/tests/hermes_cli/test_update_pause_record.pyindex b0bb17cb8fe..937fd39bde9 100644--- a/tests/hermes_cli/test_update_pause_record.py+++ b/tests/hermes_cli/test_update_pause_record.py@@ -465,3 +465,39 @@ def test_our_own_pid_is_ours_only_at_our_exact_creation_time():def test_a_record_naming_our_pid_without_a_creation_time_is_a_previous_incarnation():assert not pause_record.identity_is_live({"pid": os.getpid(), "ct": None})+++# --- R9: the retired list never fails open ------------------------------------------------------[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root reads a mode-000 file")+def test_an_unreadable_retired_list_claims_nothing_and_forgets_nothing(tmp_path, monkeypatch):+ """Mode 000 on the real list stands in for a Windows read refusal (a sharing violation, an AV+ scanner): which obligations are complete is then unknown, never "none"."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ src = pause_record.record_path()+ retired = src.with_suffix(".retired")+ done = "a" * 32 # completed earlier; Windows kept its record file+ pause_record.write({"pause_id": done, "resume_needed": True, "profiles": {"default": 4242}},+ owner=pause_record.UNOWNED)+ pause_record._atomic_write(retired, {"schema": 1, "ids": [done]})+ assert pause_record.orphans() == []+ other = src.with_name(f"{src.name}.999.deadbeef.claim") # an obligation completing meanwhile+ pause_record._atomic_write(other, {"install_root": str(REPO), "claimer": pause_record.UNOWNED,+ "token": {"pause_id": "b" * 32}})++ def owed() -> list[str]:+ try:+ return [body["token"]["pause_id"] for _src, body in pause_record.orphans()]+ except OSError: # unknown: recovery reports it and claims nothing+ return []++ retired.chmod(0)+ try:+ assert done not in owed(), "a completed obligation is owed again while its list is unreadable"+ assert pause_record.claim(src) is None, "a completed obligation was claimed again"+ with pytest.raises(OSError), pause_record._mutex():+ pause_record._retire(src, [(other, json.loads(other.read_text(encoding="utf-8-sig")))])+ assert other.exists(), "a retirement that could not be recorded deleted its carrier"+ finally:+ retired.chmod(0o644)+ assert json.loads(retired.read_text(encoding="utf-8-sig"))["ids"] == [done], "the history was rewritten"+ assert done not in owed()