Skip to content

The agent that grows with you

fix(gateway): the pause bookkeeping never turns a planned stop into an unplanned one

Teknium329287a70b55
diff --git a/gateway/status.py b/gateway/status.py
index 14025c2b4fa..8d1084df4fb 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, on_consume=None) -> bool:
+def _consume_pid_marker_for_self(path: Path, *, ttl_s: int, on_consume=None, keep: bool = False) -> bool:
parsed = _read_live_pid_marker(path, ttl_s)
if parsed is None:
return False
@@ -1835,7 +1835,8 @@ def _consume_pid_marker_for_self(path: Path, *, ttl_s: int, on_consume=None) ->
matches = _pid_marker_names_self(target_pid, target_start_time)
if matches and on_consume is not None:
on_consume(path, record)
- _unlink_quietly(path)
+ if not keep:
+ _unlink_quietly(path)
return matches
@@ -2071,16 +2072,27 @@ def write_planned_stop_marker(target_pid: int) -> bool:
})
+_PLANNED_STOP_MUTEX_WAIT_S = 2.0
+
+
def consume_planned_stop_marker_for_self() -> bool:
"""Return True when the current process is being intentionally stopped."""
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():
+ try:
+ with update_pause_record._mutex(_PLANNED_STOP_MUTEX_WAIT_S):
+ 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,
+ )
+ 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).
+ 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,
- on_consume=update_pause_record.mark_stop_consumed,
- )
+ _get_planned_stop_marker_path(), ttl_s=_PLANNED_STOP_MARKER_TTL_S, keep=True)
def planned_stop_marker_targets_self() -> bool:
diff --git a/tests/hermes_cli/test_update_pause_boundaries.py b/tests/hermes_cli/test_update_pause_boundaries.py
index d86b631c01b..0da9e794c36 100644
--- a/tests/hermes_cli/test_update_pause_boundaries.py
+++ b/tests/hermes_cli/test_update_pause_boundaries.py
@@ -145,12 +145,11 @@ def test_failed_consumer_checkpoint_keeps_request_and_user_stop_is_not_update_de
# 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()
+ # The checkpoint cannot land: the stop is still planned, and the request stays on disk.
try:
- status.consume_planned_stop_marker_for_self()
- except OSError:
- pass
- else:
- raise AssertionError("consume succeeded without its durable checkpoint")
+ planned = status.consume_planned_stop_marker_for_self()
+ except OSError as exc:
+ planned = type(exc).__name__
retained = path.exists() and r.read()["token"]["stop_sent"] == []
obstruction.rmdir()
marker = json.loads(path.read_text(encoding="utf-8-sig"))
@@ -159,13 +158,43 @@ def test_failed_consumer_checkpoint_keeps_request_and_user_stop_is_not_update_de
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}))
+ print(json.dumps({"planned": planned, "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": [],
+ assert result == {"planned": True, "retained": True, "user_consumed": True, "user_debt": [],
"accepted": True, "sent": [str(result["pid"])], "pid": result["pid"]}
+def test_a_busy_pause_mutex_never_turns_a_planned_stop_into_an_unplanned_one(cell):
+ base, _, launch = cell
+ holder = launch('''
+ with r._mutex():
+ Path(sys.argv[2]).touch()
+ while not Path(sys.argv[3]).exists(): time.sleep(.05)
+ ''', base / "held", base / "release")
+ _wait(base / "held", holder)
+ try:
+ 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"])
+ assert _write_update_planned_stop_marker(home, pid)
+ started = time.monotonic()
+ try:
+ planned = status.consume_planned_stop_marker_for_self()
+ except OSError as exc:
+ planned = type(exc).__name__
+ print(json.dumps({"planned": planned, "seconds": time.monotonic() - started,
+ "retained": (home / ".gateway-planned-stop.json").exists()}))
+ '''))
+ finally:
+ (base / "release").touch()
+ assert result["planned"] is True and result["retained"], result
+ assert result["seconds"] < 5, f"the gateway's shutdown blocked {result['seconds']:.1f}s on the pause mutex"
+
+
def test_recovery_only_accepts_markers_the_live_consumer_accepts(cell):
_, _, launch = cell
result = _result(launch('''