The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): preserve pause debt across marker consumption and adoption
Teknium6e655be477c2
diff --git a/gateway/status.py b/gateway/status.pyindex 51d01e9e706..14025c2b4fa 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -1814,7 +1814,7 @@ def _pid_marker_names_self(target_pid: int, target_start_time: Any) -> bool:return None in (target_start_time, our_start_time) or target_start_time == our_start_time-def _consume_pid_marker_for_self(path: Path, *, ttl_s: int) -> bool:+def _consume_pid_marker_for_self(path: Path, *, ttl_s: int, on_consume=None) -> bool:parsed = _read_live_pid_marker(path, ttl_s)if parsed is None:return False@@ -1833,6 +1833,8 @@ def _consume_pid_marker_for_self(path: Path, *, ttl_s: int) -> bool:if replacer_home is not None and not _same_hermes_home(replacer_home, our_home):return Falsematches = _pid_marker_names_self(target_pid, target_start_time)+ if matches and on_consume is not None:+ on_consume(path, record)_unlink_quietly(path)return matches@@ -2071,9 +2073,14 @@ def write_planned_stop_marker(target_pid: int) -> bool:def consume_planned_stop_marker_for_self() -> bool:"""Return True when the current process is being intentionally stopped."""- return _consume_pid_marker_for_self(- _get_planned_stop_marker_path(), ttl_s=_PLANNED_STOP_MARKER_TTL_S- )+ from hermes_cli import update_pause_record+ # Recovery must see either the request or its checkpoint, never the gap+ # between validating/consuming the marker and scheduling asynchronous stop.+ with update_pause_record._mutex():+ return _consume_pid_marker_for_self(+ _get_planned_stop_marker_path(), ttl_s=_PLANNED_STOP_MARKER_TTL_S,+ on_consume=update_pause_record.mark_stop_consumed,+ )def planned_stop_marker_targets_self() -> bool:diff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.pyindex 471e1f60385..287fe8059df 100644--- a/hermes_cli/update_pause_record.py+++ b/hermes_cli/update_pause_record.py@@ -241,8 +241,8 @@ def write(token: dict, *, owner: dict | None = None, path: Path | None = None) -def mark_stop_requested(token: dict, pids, markers: dict | None = None) -> None:"""Persist, BEFORE the first stop request, the stops this update intends and where each mappedgateway's request (its planned-stop marker) will be written. Intent is not a request: a live- process counts as asked only once :func:`mark_stop_sent` recorded it, or while the request this- update wrote is still on disk (:func:`_asked`)."""+ process counts as asked only once the producer or consumer checkpoints it, or while the+ valid request this update wrote is still on disk (:func:`_asked`)."""token["stop_requested"] = sorted({*map(str, token.get("stop_requested") or []), *(str(int(p)) for p in pids)})token["stop_sent"] = sorted(map(str, token.get("stop_sent") or []))token["stopper_pid"] = os.getpid()@@ -253,7 +253,7 @@ def mark_stop_requested(token: dict, pids, markers: dict | None = None) -> None:def mark_stop_sent(token: dict, pid) -> None:"""Persist that *pid*'s stop request was issued (its planned-stop marker is on disk): from here alive *pid* is draining and keeps its restart debt until it exits. Best effort: the marker itself- is the evidence until this lands, and the token carries it to the next record write."""+ is evidence until this lands; its consumer checkpoints before unlinking it."""token["stop_sent"] = sorted({*map(str, token.get("stop_sent") or []), str(int(pid))})try:write(token, owner=identity())@@ -261,6 +261,25 @@ def mark_stop_sent(token: dict, pid) -> None:print(f" ⚠ Could not record the stop request for gateway {pid}: {exc}")+def mark_stop_consumed(path: Path, marker: dict) -> None:+ """Checkpoint a validated gateway consume BEFORE its marker disappears.++ Called under the pause mutex by the consumer. Preserve the holder's identity;+ this is evidence of a stop, not a transfer of the updater's custody.+ """+ from gateway.status import _same_hermes_home+ pid = str(marker["target_pid"])+ for src, body in _files(record_path()):+ token = body["token"]+ recorded_path = (token.get("stop_markers") or {}).get(pid)+ if (str(token.get("stopper_pid")) != str(marker.get("stopper_pid"))+ or pid not in (token.get("stop_requested") or [])+ or not recorded_path or not _same_hermes_home(recorded_path, path)):+ continue+ token["stop_sent"] = sorted({*map(str, token.get("stop_sent") or []), pid})+ _atomic_write(src, body) # Failure leaves the request intact for recovery.++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()@@ -404,7 +423,9 @@ def adopt_orphans() -> tuple[dict | None, list[Path]]:if won is None:continueclaims.append(won[0])- adopted = merge_into(adopted, drop_never_stopped(dict(won[1]["token"])))+ with _mutex():+ body = read(won[0]) or won[1]+ adopted = merge_into(adopted, drop_never_stopped(dict(body["token"])))return adopted, claims@@ -468,9 +489,16 @@ def _request_on_disk(token: dict, pid: str) -> bool: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_timetry:marker = json.loads(Path(path).read_text(encoding="utf-8-sig"))- return int(marker["target_pid"]) == int(pid) and int(marker["stopper_pid"]) == int(token["stopper_pid"])+ 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)):+ 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 == actualexcept (OSError, ValueError, TypeError, KeyError):return False@@ -526,6 +554,13 @@ def merge_into(token: dict | None, adopted: dict) -> dict:requested = sent = list(adopted.get("identities") or {})token["stop_requested"] = sorted({*map(str, token.get("stop_requested") or []), *map(str, requested)})token["stop_sent"] = sorted({*map(str, token.get("stop_sent") or []), *map(str, sent or [])})+ cold = token.setdefault("cold_start_profiles", {})+ for name, generation in (adopted.get("cold_start_profiles") or {}).items():+ cold.setdefault(name, generation)+ if adopted.get("cold_start_if_installed"):+ token["cold_start_if_installed"] = True+ if "attested_generation" in adopted:+ token.setdefault("attested_generation", adopted["attested_generation"])services = token.setdefault("services", [])services.extend(s for s in adopted.get("services") or [] if s not in services)if services:@@ -541,8 +576,11 @@ def _has_work(token: dict) -> bool:def _resume_claimed(claim_path: Path, body: dict) -> None:- token = drop_never_stopped(dict(body["token"]))- draining = split_draining(token)+ with _mutex():+ # A live consumer may have checkpointed after claim() returned its snapshot.+ body = read(claim_path) or body+ token = drop_never_stopped(dict(body["token"]))+ draining = split_draining(token)token.update(resume_needed=True, recovery=True)try:if _has_work(token):diff --git a/tests/hermes_cli/test_update_pause_boundaries.py b/tests/hermes_cli/test_update_pause_boundaries.pynew file mode 100644index 00000000000..d86b631c01b--- /dev/null+++ b/tests/hermes_cli/test_update_pause_boundaries.py@@ -0,0 +1,224 @@+"""Real-process pause/consume/recovery contracts, not native Windows SCM evidence."""+from __future__ import annotations++import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import textwrap+import time++import pytest++REPO = Path(__file__).resolve().parents[2]+++def _wait(path, process):+ deadline = time.monotonic() + 30+ while not path.exists():+ assert process.poll() is None, process.communicate()+ assert time.monotonic() < deadline, str(path)+ time.sleep(0.01)+++def cell(tmp_path):+ # An unchanged copy owns its private checkout lock/root; never the live install's.+ root = tmp_path / "checkout"+ (root / "hermes_cli").mkdir(parents=True)+ shutil.copyfile(REPO / "hermes_cli/update_pause_record.py", root / "hermes_cli/update_pause_record.py")+ home = tmp_path / "home"+ (home / ".hermes").mkdir(parents=True)+ env = {**os.environ, "HOME": str(home), "USERPROFILE": str(home),+ "HERMES_HOME": str(home / ".hermes"), "PYTHONPATH": str(REPO),+ "PYTHONDONTWRITEBYTECODE": "1"}+ children = []++ def launch(code, *args):+ script = tmp_path / f"child-{len(children)}.py"+ script.write_text(textwrap.dedent('''+ import importlib.util, json, os, sys, time+ from pathlib import Path+ root = Path(sys.argv[1])+ spec = importlib.util.spec_from_file_location("hermes_cli.update_pause_record", root / "hermes_cli/update_pause_record.py")+ r = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = r+ spec.loader.exec_module(r)+ ''') + textwrap.dedent(code), encoding="utf-8")+ proc = subprocess.Popen([sys.executable, str(script), str(root), *map(str, args)],+ cwd=tmp_path, env=env, stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ children.append(proc)+ return proc++ yield tmp_path, home / ".hermes", launch+ for proc in children:+ if proc.poll() is None:+ proc.kill()+ proc.communicate(timeout=10)+++def _result(proc):+ out, err = proc.communicate(timeout=30)+ assert proc.returncode == 0, (out, err)+ return json.loads(out.splitlines()[-1])++[email protected]("claim_first", [False, True])+def test_consumption_checkpoints_debt_before_unlink_and_producer_death(cell, claim_first):+ base, home, launch = cell+ consumer = launch('''+ from gateway.status import consume_planned_stop_marker_for_self+ Path(sys.argv[2]).write_text(str(os.getpid()), encoding="utf-8")+ while not Path(sys.argv[3]).exists(): time.sleep(.01)+ accepted = consume_planned_stop_marker_for_self()+ Path(sys.argv[4]).write_text(json.dumps(accepted), encoding="utf-8")+ while True: time.sleep(.05)+ ''', base / "ready", base / "consume", base / "consumed")+ _wait(base / "ready", consumer)+ owner = launch('''+ from hermes_cli import update_cmd_windows as w+ from types import SimpleNamespace+ pid = int(sys.argv[2])+ home = Path(os.environ["HERMES_HOME"])+ token = r.record_pause({"resume_needed": True, "profiles": {"default": pid},+ "identities": {str(pid): r.identity(pid)["ct"]}}, None, [])+ # Discovery and the gateway can spell the same profile path differently.+ r.mark_stop_requested(token, [pid], {pid: home / ".." / ".hermes" / ".gateway-planned-stop.json"})+ # The real callback is the first operation after marker publication. Hold it+ # before its checkpoint while another interpreter runs the actual consumer.+ def on_request(pid):+ Path(sys.argv[3]).touch()+ while True: time.sleep(.05)+ w._request_socket_pauses([pid], {pid: SimpleNamespace(profile="default", path=home)},+ set(), on_request=on_request)+ ''', consumer.pid, base / "published")+ _wait(base / "published", owner)+ recovery = None+ if claim_first:+ owner.kill()+ owner.communicate(timeout=10)+ recovery = launch('''+ won = r.claim(r.record_path())+ assert won is not None+ Path(sys.argv[2]).touch()+ while not Path(sys.argv[3]).exists(): time.sleep(.01)+ r._resume_claimed(*won)+ print(json.dumps([body["token"] for _, body in r.orphans()]))+ ''', base / "claimed", base / "recover")+ _wait(base / "claimed", recovery)+ (base / "consume").touch()+ _wait(base / "consumed", consumer)+ assert json.loads((base / "consumed").read_text(encoding="utf-8-sig")) is True+ assert not (home / ".gateway-planned-stop.json").exists()+ if owner.poll() is None:+ owner.kill()+ owner.communicate(timeout=10)+ assert consumer.poll() is None+ if recovery is not None:+ (base / "recover").touch()+ else:+ recovery = launch('''+ r.recover(["status"])+ print(json.dumps([body["token"] for _, body in r.orphans()]))+ ''')+ after = _result(recovery)+ assert len(after) == 1, "consumed request lost all durable restart debt"+ assert after[0]["profiles"] == {"default": consumer.pid}+ assert after[0]["stop_sent"] == [str(consumer.pid)]+++def test_failed_consumer_checkpoint_keeps_request_and_user_stop_is_not_update_debt(cell):+ _, _, launch = cell+ result = _result(launch('''+ from gateway import status+ from hermes_cli.update_cmd_windows import _write_update_planned_stop_marker+ pid = os.getpid()+ home = Path(os.environ["HERMES_HOME"])+ path = home / ".gateway-planned-stop.json"+ token = r.record_pause({"resume_needed": True, "profiles": {"default": pid},+ "identities": {str(pid): r.identity(pid)["ct"]}}, None, [])+ r.mark_stop_requested(token, [pid], {pid: path})+ assert _write_update_planned_stop_marker(home, pid)+ # An actual directory at the atomic writer's temp path rejects publication.+ obstruction = r.record_path().with_name(f"{r.record_path().name}.{pid}.tmp")+ obstruction.mkdir()+ try:+ status.consume_planned_stop_marker_for_self()+ except OSError:+ pass+ else:+ raise AssertionError("consume succeeded without its durable checkpoint")+ retained = path.exists() and r.read()["token"]["stop_sent"] == []+ obstruction.rmdir()+ marker = json.loads(path.read_text(encoding="utf-8-sig"))+ path.write_text(json.dumps({**marker, "stopper_pid": pid + 1}), encoding="utf-8")+ user_consumed = status.consume_planned_stop_marker_for_self()+ user_debt = r.read()["token"]["stop_sent"]+ assert _write_update_planned_stop_marker(home, pid)+ accepted = status.consume_planned_stop_marker_for_self()+ print(json.dumps({"retained": retained, "user_consumed": user_consumed, "user_debt": user_debt,+ "accepted": accepted, "sent": r.read()["token"]["stop_sent"], "pid": pid}))+ '''))+ assert result == {"retained": True, "user_consumed": True, "user_debt": [],+ "accepted": True, "sent": [str(result["pid"])], "pid": result["pid"]}+++def test_recovery_only_accepts_markers_the_live_consumer_accepts(cell):+ _, _, launch = cell+ result = _result(launch('''+ from datetime import datetime, timedelta, timezone+ from gateway import status+ pid = os.getpid()+ home = Path(os.environ["HERMES_HOME"])+ marker_path = home / ".gateway-planned-stop.json"+ token = {"profiles": {"default": pid}, "identities": {str(pid): r.identity(pid)["ct"]},+ "stopper_pid": pid, "stop_requested": [str(pid)], "stop_markers": {str(pid): str(marker_path)}}+ current = status.get_process_start_time(pid)+ assert current is not None+ fresh = {"target_pid": pid, "stopper_pid": pid, "target_start_time": current,+ "written_at": datetime.now(timezone.utc).isoformat()}+ cases = {"valid": fresh,+ "expired": {**fresh, "written_at": (datetime.now(timezone.utc) - timedelta(seconds=120)).isoformat()},+ "wrong_incarnation": {**fresh, "target_start_time": current + 1},+ "malformed": {"target_pid": pid, "stopper_pid": pid}}+ out = {}+ for name, marker in cases.items():+ marker_path.write_text(json.dumps(marker), encoding="utf-8")+ kept = r.drop_never_stopped(dict(token))+ consumed = status.consume_planned_stop_marker_for_self()+ out[name] = {"kept": bool(kept["profiles"]), "consumed": consumed}+ print(json.dumps(out))+ '''))+ assert result["valid"] == {"kept": True, "consumed": True}+ for name in ("expired", "wrong_incarnation", "malformed"):+ assert result[name] == {"kept": False, "consumed": False}, (name, result)+++def test_orphan_adoption_preserves_cold_start_generation_and_current_precedence(cell):+ _, _, launch = cell+ _result(launch('''+ token = {"resume_needed": True, "profiles": {}, "cold_start_if_installed": True,+ "attested_generation": "old-active", "cold_start_profiles": {"beta": "old-beta", "gamma": "old-gamma"}}+ r.write(r.stamp_tree(token), owner=r.UNOWNED)+ print(json.dumps(r.read()["token"]))+ '''))+ adopted = _result(launch('''+ adopted, claims = r.adopt_orphans()+ token = {"resume_needed": True, "profiles": {}, "cold_start_profiles": {"beta": "current-beta"}}+ r.record_pause(token, adopted, claims)+ print(json.dumps(r.read()["token"]))+ '''))+ assert adopted.get("cold_start_if_installed") is True+ assert adopted.get("attested_generation") == "old-active"+ assert adopted.get("cold_start_profiles") == {"beta": "current-beta", "gamma": "old-gamma"}+ again = _result(launch('''+ adopted, claims = r.adopt_orphans()+ r.record_pause({"resume_needed": True, "profiles": {}, "cold_start_if_installed": True,+ "attested_generation": "current-active"}, adopted, claims)+ print(json.dumps(r.read()["token"]))+ '''))+ assert again["attested_generation"] == "current-active"+ assert again["cold_start_profiles"] == adopted["cold_start_profiles"]diff --git a/tests/hermes_cli/test_update_pause_record.py b/tests/hermes_cli/test_update_pause_record.pyindex 336acc9cec1..b0bb17cb8fe 100644--- a/tests/hermes_cli/test_update_pause_record.py+++ b/tests/hermes_cli/test_update_pause_record.py@@ -405,7 +405,8 @@ def test_a_request_on_disk_is_owed_even_before_it_is_recorded_sent(tmp_path):token = r.record_pause({"resume_needed": True, "profiles": {"default": pid},"identities": {str(pid): r.identity(pid)["ct"]}}, None, [])r.mark_stop_requested(token, [pid], markers={pid: marker})- marker.write_text(json.dumps({"target_pid": pid, "stopper_pid": os.getpid()}), encoding="utf-8")+ from hermes_cli.update_cmd_windows import _write_update_planned_stop_marker+ assert _write_update_planned_stop_marker(marker.parent, pid)print("requested", flush=True)time.sleep(120)""", str(gateway.pid), str(marker), env={"HERMES_HOME": str(tmp_path)})