The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: an accepted planned stop stays owed for the whole drain
Tekniumcff9e7a0f5f4
diff --git a/gateway/status.py b/gateway/status.pyindex 3fe98e8b662..ed4e6ab505b 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -1970,11 +1970,11 @@ def consume_planned_stop_marker_for_self() -> bool:)except OSError as exc:# The pause bookkeeping (a busy mutex, a checkpoint that cannot be written) never decides- # whether this stop was planned: classify without consuming, so the request stays on- # disk as the evidence recovery reads in place of the checkpoint (it expires by TTL).+ # whether this stop was planned: classify without consuming, and leave a receipt beside the+ # request so recovery keeps this drain owed after the request's TTL (mark_stop_accepted).logger.warning("Planned-stop checkpoint skipped (%s); the stop request stays on disk", exc)- return _consume_pid_marker_for_self(- _get_planned_stop_marker_path(), ttl_s=_PLANNED_STOP_MARKER_TTL_S, keep=True)+ return _consume_pid_marker_for_self(_get_planned_stop_marker_path(), ttl_s=_PLANNED_STOP_MARKER_TTL_S,+ keep=True, on_consume=update_pause_record.mark_stop_accepted)def planned_stop_marker_targets_self() -> bool:diff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.pyindex 7723837aad9..aede61c822d 100644--- a/hermes_cli/update_pause_record.py+++ b/hermes_cli/update_pause_record.py@@ -413,6 +413,20 @@ def mark_stop_consumed(path: Path, marker: dict) -> None:_atomic_write(src, body) # Failure leaves the request intact for recovery.+def _accepted_path(marker_path: Path) -> Path:+ return marker_path.with_name(marker_path.name + ".accepted")+++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."""+ try:+ _atomic_write(_accepted_path(path), dict(marker))+ except OSError as exc:+ print(f" ⚠ Could not record the accepted stop request {path}: {exc}", file=sys.stderr)++def discharge(token: dict, path: Path | None = None) -> None:"""Remove the record only while it still names this pause (decided under the mutex)."""path = path or record_path()@@ -694,16 +708,25 @@ def _without(token: dict, pids: set[str]) -> dict:def _request_on_disk(token: dict, pid: str) -> bool:"""The planned-stop marker this update's stopper wrote for *pid* is still on disk (the gateway'swatcher has not consumed it yet): the request was issued even if the updater died before- :func:`mark_stop_sent`. A marker naming another stopper (a user's ``hermes gateway stop``) is not."""+ :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."""path = (token.get("stop_markers") or {}).get(str(pid))if not path:return False- from gateway.status import _marker_is_stale, _PLANNED_STOP_MARKER_TTL_S, get_process_start_time+ 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))+++def _names_request(token: dict, pid: str, path: Path, ttl_s: int | None) -> bool:+ from gateway.status import _marker_is_stale, get_process_start_timetry:- marker = json.loads(Path(path).read_text(encoding="utf-8-sig"))+ 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 _marker_is_stale(marker.get("written_at") or "", _PLANNED_STOP_MARKER_TTL_S)):+ or (ttl_s is not None and _marker_is_stale(marker.get("written_at") or "", ttl_s))):return Falseexpected, actual = marker.get("target_start_time"), get_process_start_time(int(pid))# Match the consumer's optional birth fingerprint, including unavailable clocks.diff --git a/tests/hermes_cli/test_update_pause_record.py b/tests/hermes_cli/test_update_pause_record.pyindex 9c762b3cf13..ed0c499a0de 100644--- a/tests/hermes_cli/test_update_pause_record.py+++ b/tests/hermes_cli/test_update_pause_record.py@@ -661,6 +661,41 @@ def test_an_unreadable_orphan_is_never_overwritten_by_a_new_pause(tmp_path, monkassert pause_record.read()["token"]["profiles"] == {"alpha": 11, "beta": 12}+# --- Review B: an accepted stop stays owed for the whole drain -----------------------------------[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root writes a read-only directory")[email protected]("consumed", [True, False])+def test_an_accepted_stop_the_record_could_not_checkpoint_outlives_the_request_ttl(tmp_path, monkeypatch, consumed):+ """Producer and consumer checkpoints both refused (a read-only record directory stands in for+ a Windows replace refusal), the updater gone, the gateway (this process) still draining past the+ request's TTL: recovery keeps it owed. A request nobody consumed still expires (control)."""+ from datetime import datetime, timedelta, timezone++ 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)+ try:+ pause_record.mark_stop_sent(token, pid) # refused: best effort+ if consumed:+ assert status.consume_planned_stop_marker_for_self() is True+ finally:+ root.chmod(0o755)+ saved = pause_record.read()["token"]+ assert saved["stop_sent"] == [], "premise: no checkpoint landed"+ 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")+ owed = pause_record.drop_never_stopped(dict(saved))["profiles"]+ assert owed == ({"p": pid} if consumed else {}), "a gateway draining an accepted stop lost its restart debt"++# --- Review W3: record hygiene --------------------------------------------------------------------def test_a_refused_publish_leaves_no_temp_beside_the_record(tmp_path, monkeypatch):target = tmp_path / "records" / "record.json"