The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: an unreadable saved pause or claim is unknown, never absent
Teknium7bf241ee088c
diff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.pyindex c0799e7b13d..7723837aad9 100644--- a/hermes_cli/update_pause_record.py+++ b/hermes_cli/update_pause_record.py@@ -106,6 +106,10 @@ class RetiredUnknown(OSError):"""The retired-id list exists but cannot be read: which obligations are complete is unknown."""+class RecordUnknown(OSError):+ """A saved pause or claim exists but cannot be read or parsed: what it still owes is unknown."""++@contextmanagerdef _mutex(wait_s: float = _MUTEX_WAIT_S):"""Exclusive kernel lock on the record directory's sidecar (A7). Re-entrant per thread; each@@ -326,12 +330,24 @@ def _atomic_write(path: Path, body: dict) -> None:def read(path: Path | None = None) -> dict | None:+ """The saved body; ``None`` only when the file is absent. One that exists but cannot be read+ (a Windows sharing violation, an AV scanner) or does not parse raises :class:`RecordUnknown`:+ it may be the newest copy of an obligation (its partial progress) or the only one, so it never+ lets an older copy execute nor a new pause replace it. Callers fail closed and retry later."""path = path or record_path()try:- body = json.loads(path.read_text(encoding="utf-8-sig"))- except (OSError, ValueError):+ text = path.read_text(encoding="utf-8-sig")+ except FileNotFoundError:return None- return body if isinstance(body, dict) and isinstance(body.get("token"), dict) else None+ except OSError as exc:+ raise RecordUnknown(f"cannot read the paused-gateway record {path}: {exc}") from exc+ try:+ body = json.loads(text)+ except ValueError:+ body = None+ if not isinstance(body, dict) or not isinstance(body.get("token"), dict):+ raise RecordUnknown(f"the paused-gateway record {path} is malformed; fix or remove it to resume")+ return bodyUNOWNED = {"pid": 0, "ct": None}@@ -494,7 +510,7 @@ def _holder(src: Path, body: dict) -> dict:def _files(path: Path) -> list[tuple[Path, dict]]:- """This checkout's record and claims, readable ones only."""+ """This checkout's record and claims; one that cannot be read raises :class:`RecordUnknown`."""found = []for src in (path, *_claims(path)):body = read(src)@@ -568,12 +584,10 @@ def retire_redundant(path: Path | None = None) -> None:def _prune_retired(path: Path) -> None:- """Forget retired ids no file carries any more — only when every candidate file was readable- (one Windows would not let us read may still carry a retired id)."""+ """Forget retired ids no file carries any more (a carrier that cannot be read raises first)."""retired = _retired(path)- candidates = [p for p in (path, *_claims(path)) if p.exists()]- bodies = [read(p) for p in candidates]- if not retired or None in bodies:+ bodies = [body for body in map(read, (path, *_claims(path))) if body is not None]+ if not retired:returncarried = {str(b["token"].get("pause_id")) for b in bodies}keep = retired & carrieddiff --git a/tests/hermes_cli/test_update_pause_record.py b/tests/hermes_cli/test_update_pause_record.pyindex b02e8fdb0df..9c762b3cf13 100644--- a/tests/hermes_cli/test_update_pause_record.py+++ b/tests/hermes_cli/test_update_pause_record.py@@ -599,6 +599,68 @@ def test_an_unreadable_retired_list_claims_nothing_and_forgets_nothing(tmp_path,+# --- Review A: a carrier that cannot be read is unknown, never absent ---------------------------+def _unreadable(path: Path, how: str) -> None:+ if how == "malformed":+ path.write_text("{trunc", encoding="utf-8")+ else:+ path.chmod(0) # stands in for a Windows read refusal (sharing violation, AV scanner)++[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root reads a mode-000 file")[email protected]("how", ["refused", "malformed"])+def test_an_unreadable_newer_carrier_never_lets_its_older_copy_execute(tmp_path, monkeypatch, how):+ """Partial progress left the newer claim owing only beta beside an older alpha+beta copy of the+ same obligation (its unlink was refused). That claim becoming unreadable must not resurrect alpha."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ src = pause_record.record_path()+ pause_id = "d" * 32+ pause_record.write({"pause_id": pause_id, "resume_needed": True, "profiles": {"alpha": 11, "beta": 12}},+ owner=pause_record.UNOWNED)+ newer = src.with_name(f"{src.name}.999.deadbeef.claim")+ pause_record._atomic_write(newer, {"install_root": str(REPO), "claimer": pause_record.UNOWNED, "rev": 1,+ "token": {"pause_id": pause_id, "resume_needed": True, "profiles": {"beta": 12}}})++ def owed() -> list[dict]:+ try:+ return [body["token"]["profiles"] for _src, body in pause_record.orphans()]+ except OSError: # unknown: recovery reports it and claims nothing+ return []++ assert owed() == [{"beta": 12}], "premise: the furthest-progressed copy executes"+ _unreadable(newer, how)+ try:+ assert {"alpha": 11, "beta": 12} not in owed(), "completed alpha would be restarted again"+ assert pause_record.claim(src) is None, "the older copy was claimed past an unreadable newer one"+ finally:+ newer.chmod(0o644)+ assert src.exists() and newer.exists(), "a carrier was deleted while its state was unknown"++[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root reads a mode-000 file")[email protected]("how", ["refused", "malformed"])+def test_an_unreadable_orphan_is_never_overwritten_by_a_new_pause(tmp_path, monkeypatch, how):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ src = pause_record.record_path()+ pause_record.write({"pause_id": "e" * 32, "resume_needed": True, "profiles": {"alpha": 11}}, owner=pause_record.UNOWNED)+ saved = src.read_bytes()+ _unreadable(src, how)+ try:+ with pytest.raises(OSError):+ pause_record.write({"pause_id": "f" * 32, "resume_needed": True, "profiles": {"beta": 12}},+ owner=pause_record.identity())+ finally:+ src.chmod(0o644)+ if how == "refused":+ assert src.read_bytes() == saved, "alpha's saved restart obligation was replaced"+ else:+ assert src.read_text(encoding="utf-8") == "{trunc", "an unknown record was replaced"+ src.write_bytes(saved) # readable control: the new pause folds the orphan in+ token = {"pause_id": "f" * 32, "resume_needed": True, "profiles": {"beta": 12}}+ pause_record.write(token, owner=pause_record.identity())+ assert pause_record.read()["token"]["profiles"] == {"alpha": 11, "beta": 12}++# --- Review W3: record hygiene --------------------------------------------------------------------def test_a_refused_publish_leaves_no_temp_beside_the_record(tmp_path, monkeypatch):target = tmp_path / "records" / "record.json"