Skip to content

The agent that grows with you

fix: unreadable or unwritable accepted-stop evidence keeps a draining gateway owed

Teknium7b68039222aa
diff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.py
index 6d9deb67584..e7fa2e1db44 100644
--- a/hermes_cli/update_pause_record.py
+++ b/hermes_cli/update_pause_record.py
@@ -457,11 +457,24 @@ def _accepted_path(marker_path: Path) -> Path:
def mark_stop_accepted(path: Path, marker: dict) -> None:
"""The consumer's receipt when it cannot checkpoint into the record (busy mutex, refused
replace): this incarnation accepted the request and drains until it exits, however long past
- the request's TTL. Written beside the marker, in the gateway's own home, never into the record."""
+ the request's TTL. Written beside the marker, in the gateway's own home, never into the record.
+
+ A home that refuses the new file (an ACL, a read-only directory) still lets the kept request be
+ rewritten in place: stamped ``accepted`` it is the receipt. Torn mid-write it reads malformed,
+ which recovery holds as unknown, never as "not asked". The consumer accepts the stop either way."""
try:
_atomic_write(_accepted_path(path), dict(marker))
+ return
+ except OSError as exc:
+ refused = exc
+ try:
+ with open(path, "r+", encoding="utf-8") as fh: # r+: never creates a request that was not there
+ json.dump({**marker, "accepted": True}, fh)
+ fh.truncate()
+ fh.flush()
+ os.fsync(fh.fileno())
except OSError as exc:
- print(f" ⚠ Could not record the accepted stop request {path}: {exc}", file=sys.stderr)
+ print(f" ⚠ Could not record the accepted stop request {path}: {refused}; {exc}", file=sys.stderr)
def discharge(token: dict, path: Path | None = None) -> None:
@@ -742,40 +755,50 @@ def _without(token: dict, pids: set[str]) -> dict:
return token
-def _request_on_disk(token: dict, pid: str) -> bool:
+def _request_on_disk(token: dict, pid: str) -> bool | None:
"""The planned-stop marker this update's stopper wrote for *pid* is still on disk (the gateway's
watcher has not consumed it yet): the request was issued even if the updater died before
:func:`mark_stop_sent` — or the gateway's receipt of accepting it (:func:`mark_stop_accepted`).
- A marker naming another stopper (a user's ``hermes gateway stop``) is not."""
+ A marker naming another stopper (a user's ``hermes gateway stop``) is not. ``None``: one of them
+ exists but cannot be read or parsed — the stop may have been accepted, so it is unknown."""
path = (token.get("stop_markers") or {}).get(str(pid))
if not path:
return False
from gateway.status import _PLANNED_STOP_MARKER_TTL_S
# An unconsumed request expires; the receipt of an accepted one is evidence for the whole drain
# (only the accepting incarnation is ever judged: a later one is not this entry's live process).
- return (_names_request(token, pid, Path(path), _PLANNED_STOP_MARKER_TTL_S)
- or _names_request(token, pid, _accepted_path(Path(path)), None))
+ verdicts = (_names_request(token, pid, Path(path), _PLANNED_STOP_MARKER_TTL_S),
+ _names_request(token, pid, _accepted_path(Path(path)), None))
+ return True if True in verdicts else None if None in verdicts else False
-def _names_request(token: dict, pid: str, path: Path, ttl_s: int | None) -> bool:
+def _names_request(token: dict, pid: str, path: Path, ttl_s: int | None) -> bool | None:
+ """Does *path* hold this stopper's request for *pid*'s incarnation? Only an absent file or a
+ valid one naming something else is ``False``; refused (a sharing violation, an AV scanner) or
+ malformed is ``None``, unknown."""
from gateway.status import _marker_is_stale, get_process_start_time
try:
marker = json.loads(path.read_text(encoding="utf-8-sig"))
- if (int(marker["target_pid"]) != int(pid)
- or int(marker["stopper_pid"]) != int(token["stopper_pid"])
- or (ttl_s is not None and _marker_is_stale(marker.get("written_at") or "", ttl_s))):
- return False
- expected, actual = marker.get("target_start_time"), get_process_start_time(int(pid))
- # Match the consumer's optional birth fingerprint, including unavailable clocks.
- return None in (expected, actual) or expected == actual
+ target, stopper = int(marker["target_pid"]), int(marker["stopper_pid"])
+ except FileNotFoundError:
+ return False
except (OSError, ValueError, TypeError, KeyError):
+ return None
+ if (target != int(pid) or stopper != int(token.get("stopper_pid") or 0)
+ or (ttl_s is not None and not marker.get("accepted")
+ and _marker_is_stale(marker.get("written_at") or "", ttl_s))):
return False
+ expected, actual = marker.get("target_start_time"), get_process_start_time(int(pid))
+ # Match the consumer's optional birth fingerprint, including unavailable clocks.
+ return None in (expected, actual) or expected == actual
-def _asked(token: dict) -> set[str]:
- """Pids this update actually asked to stop: recorded as sent, or whose request is still on disk."""
+def _asked(token: dict) -> tuple[set[str], set[str]]:
+ """``(asked, unknown)``: pids this update actually asked to stop (recorded as sent, or whose
+ request is still on disk), and pids whose request evidence exists but cannot be read."""
sent = {str(p) for p in token.get("stop_sent") or []}
- return sent | {str(p) for p in token.get("stop_requested") or [] if str(p) not in sent and _request_on_disk(token, str(p))}
+ verdicts = {str(p): _request_on_disk(token, str(p)) for p in token.get("stop_requested") or [] if str(p) not in sent}
+ return sent | {p for p, v in verdicts.items() if v}, {p for p, v in verdicts.items() if v is None}
def drop_never_stopped(token: dict) -> dict:
@@ -784,12 +807,14 @@ def drop_never_stopped(token: dict) -> dict:
serving, and a later exit — a user's ``hermes gateway stop`` included — is not this update's to
undo. One it asked may be draining: it keeps its restart debt (:func:`split_draining`). The
evidence is resolved here, once, into ``stop_sent`` (a merge carries it under another stopper).
- No stop record at all (a set from before stop tracking): nothing can be told apart."""
+ Evidence that cannot be read keeps the entry too (it may be draining) but resolves nothing: it is
+ judged again next time. No stop record at all (a set from before stop tracking): nothing can be
+ told apart."""
if token.get("stop_requested") is None:
return token
- asked = _asked(token)
+ asked, unknown = _asked(token)
token["stop_sent"] = sorted(asked)
- return _without(token, _live_pids(token) - asked)
+ return _without(token, _live_pids(token) - asked - unknown)
def split_draining(token: dict) -> dict:
diff --git a/tests/hermes_cli/test_update_pause_stop_evidence.py b/tests/hermes_cli/test_update_pause_stop_evidence.py
new file mode 100644
index 00000000000..d28497c53c8
--- /dev/null
+++ b/tests/hermes_cli/test_update_pause_stop_evidence.py
@@ -0,0 +1,103 @@
+"""Accepted-stop evidence the pause record cannot read or could not write: the debt stays owed.
+
+The gateway is this test process (a live incarnation that accepted the stop and is draining); the
+updater is gone (the record is unowned); every file is real and every refusal is a real one (mode
+000, a read-only directory), standing in for a Windows sharing violation or ACL refusal.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import update_pause_record as pause_record
+
+pytestmark = [
+ pytest.mark.skipif(sys.platform == "win32", reason="POSIX modes stand in for Windows refusals"),
+ pytest.mark.skipif(hasattr(os, "geteuid") and os.geteuid() == 0, reason="root ignores file modes"),
+]
+
+
+def _accepted_then_orphaned(tmp_path: Path, monkeypatch, *, home_writable: bool) -> tuple[Path, str]:
+ """Record a pause of this process, request its stop, let it accept the request while the record
+ refuses the consumer's checkpoint (read-only record directory), then age the request past its
+ TTL and orphan the record. Returns ``(marker, pause_id)``."""
+ from gateway import status
+ root, home = tmp_path / "root", tmp_path / "root" / "profiles" / "p"
+ home.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ pid = os.getpid()
+ marker = status._get_planned_stop_marker_path()
+ token = pause_record.record_pause({"resume_needed": True, "profiles": {"p": pid},
+ "identities": {str(pid): pause_record.identity(pid)["ct"]}}, None, [])
+ pause_record.mark_stop_requested(token, [pid], markers={pid: marker})
+ assert status.write_planned_stop_marker(pid)
+ root.chmod(0o555)
+ if not home_writable:
+ home.chmod(0o555)
+ try:
+ assert status.consume_planned_stop_marker_for_self() is True, "premise: the stop was accepted"
+ finally:
+ home.chmod(0o755)
+ root.chmod(0o755)
+ saved = pause_record.read()["token"]
+ assert saved["stop_sent"] == [], "premise: no checkpoint landed in the record"
+ body = json.loads(marker.read_text(encoding="utf-8"))
+ body["written_at"] = (datetime.now(timezone.utc) - timedelta(seconds=120)).isoformat() # past the TTL
+ marker.write_text(json.dumps(body), encoding="utf-8")
+ pause_record.write(saved, owner=pause_record.UNOWNED) # the updater died
+ return marker, saved["pause_id"]
+
+
+def _owed_after_recovery(pause_id: str) -> dict | None:
+ """Run a launch's recovery; the profiles still owed by the obligation, ``None`` once retired."""
+ pause_record.recover(["status"])
+ path = pause_record.record_path()
+ retired = path.with_suffix(".retired")
+ ids = json.loads(retired.read_text(encoding="utf-8"))["ids"] if retired.exists() else []
+ carriers = [pause_record.read(src) for src in (path, *pause_record._claims(path)) if src.exists()]
+ owed = [body["token"]["profiles"] for body in carriers if body["token"]["pause_id"] == pause_id]
+ assert bool(owed) != (pause_id in ids), "an obligation is either owed or retired, never both or neither"
+ return owed[0] if owed else None
+
+
[email protected]("receipt", ["refused", "malformed", "missing"])
+def test_an_unreadable_accepted_stop_receipt_keeps_the_draining_gateway_owed(tmp_path, monkeypatch, receipt):
+ """R1: a receipt that exists but cannot be read or parsed is unknown evidence: the live draining
+ gateway stays owed (never restarted over, never retired). A receipt that is genuinely absent
+ beside an expired, unconsumed request is the control: that stop was never accepted."""
+ marker, pause_id = _accepted_then_orphaned(tmp_path, monkeypatch, home_writable=True)
+ accepted = pause_record._accepted_path(marker)
+ assert accepted.exists(), "premise: the consumer left its receipt"
+ if receipt == "refused":
+ accepted.chmod(0)
+ elif receipt == "malformed":
+ accepted.write_text("{trunc", encoding="utf-8")
+ else:
+ accepted.unlink()
+ try:
+ owed = _owed_after_recovery(pause_id)
+ finally:
+ if accepted.exists():
+ accepted.chmod(0o644)
+ if receipt == "missing":
+ assert owed is None, "a request nobody accepted must still expire"
+ return
+ assert owed == {"p": os.getpid()}, f"a {receipt} receipt retired a draining gateway's restart debt"
+ # Unknown is judged again, never resolved into "sent": once readable it is a receipt like any other.
+ assert str(os.getpid()) not in pause_record.read(pause_record._claims(pause_record.record_path())[0])["token"]["stop_sent"]
+ assert _owed_after_recovery(pause_id) == {"p": os.getpid()}
+
+
+def test_an_accepted_stop_whose_receipt_cannot_be_written_stays_owed(tmp_path, monkeypatch):
+ """Thread 6: the gateway home refuses new files too, so neither the record checkpoint nor the
+ receipt beside the request can be created; the consumer still accepts the stop. The kept
+ request itself must carry the acceptance, so the debt survives the request's TTL."""
+ marker, pause_id = _accepted_then_orphaned(tmp_path, monkeypatch, home_writable=False)
+ assert not pause_record._accepted_path(marker).exists(), "premise: the receipt could not be created"
+ assert _owed_after_recovery(pause_id) == {"p": os.getpid()}, "an accepted stop lost its restart debt"