The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): honor ESTOP in NAS fire webhook and misfire backstop
JulianCruzet95fd5d6816a7
diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.pyindex b9f4d4d384c..4612d089a03 100644--- a/cron/scheduler_provider.py+++ b/cron/scheduler_provider.py@@ -301,6 +301,15 @@ def fire_overdue_jobs(concurrent late external retry is de-duplicated by the store CAS; waits out``cron.misfire_grace_minutes`` so the external retry gets first right. Returns jobs dispatched."""+ # `hermes pause` ESTOP: skip the sweep entirely. No state to unwind — the+ # next housekeeping pass after `hermes resume` catches overdue work up+ # through the existing claim_fire path. Distinct component name from the+ # ticker's "cron" so the log-once mechanism fires independently.+ with contextlib.suppress(ImportError):+ from agent.estop import check_paused as _estop_check_paused+ if _estop_check_paused("cron-misfire", logger):+ return 0+from datetime import datetimeif isinstance(provider, InProcessCronScheduler):diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 5c4a2bf4ae7..e293e90ce2e 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -3511,6 +3511,20 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):job_id = (body or {}).get("job_id")if not job_id:return web.json_response({"error": "missing job_id"}, status=400)+ # `hermes pause` ESTOP: refuse the fire and ask NAS to retry later.+ # Placed after JWT verify (don't leak pause state to unauth callers)+ # and after the drain check (drain is transient shutdown, ESTOP is+ # operator override). 503 + Retry-After reschedules the job via NAS+ # retry or the misfire backstop rather than silently dropping it —+ # matches _CRON_FIRE_RETRY_AFTER_SECONDS in web_routers/cron.py.+ with suppress(ImportError):+ from agent.estop import check_paused as _estop_check_paused+ if _estop_check_paused("cron-webhook", logger):+ return web.json_response(+ {"error": "hermes is paused (ESTOP)", "job_id": job_id},+ status=503,+ headers={"Retry-After": str(60)},+ )from cron.scheduler_provider import provider_supports_split_fire, resolve_cron_schedulerprovider = resolve_cron_scheduler()loop = asyncio.get_running_loop()diff --git a/tests/cron/test_misfire_catchup.py b/tests/cron/test_misfire_catchup.pyindex 53ceb31887b..738b9f15d29 100644--- a/tests/cron/test_misfire_catchup.py+++ b/tests/cron/test_misfire_catchup.py@@ -161,3 +161,51 @@ class TestFireOverdueJobs:assert time.monotonic() - start < 1.0 # returned before the runassert provider.wait_fired(timeout=10)assert provider.fired == [job["id"]]++ def test_estop_engaged_skips_backstop(self, tmp_cron_dir, tmp_path, monkeypatch):+ """Engaged ESTOP → backstop returns 0 and spawns no fire threads.++ Matches the contract at ``agent/estop.py:1-9``: cron skips work,+ in-flight work is untouched. The misfire sweep is the backstop; it+ must yield to operator pause, then resume naturally on disengage.+ """+ from agent import estop++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ estop._logged_components.clear()++ job = create_job(prompt="p", schedule="every 1h")+ _park_in_past(job["id"], minutes=30)+ provider = RecordingProvider()++ estop.engage(reason="ops window")+ try:+ assert fire_overdue_jobs(provider) == 0+ assert provider.fired == []+ assert not provider.wait_fired(timeout=0.5)+ finally:+ estop.disengage()++ def test_estop_release_restores_backstop(self, tmp_cron_dir, tmp_path, monkeypatch):+ """ESTOP release → next sweep catches up via the existing claim_fire path.++ No state to unwind — the sweep's job is already "fire things whose+ scheduled fire never arrived," so a paused sweep just extends that+ window until resume.+ """+ from agent import estop++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ estop._logged_components.clear()++ job = create_job(prompt="p", schedule="every 1h")+ _park_in_past(job["id"], minutes=30)+ provider = RecordingProvider()++ estop.engage(reason="ops window")+ assert fire_overdue_jobs(provider) == 0 # paused — no fire++ estop.disengage()+ assert fire_overdue_jobs(provider) == 1+ assert provider.wait_fired()+ assert provider.fired == [job["id"]]diff --git a/tests/gateway/test_api_server_jobs.py b/tests/gateway/test_api_server_jobs.pyindex c9d483075ce..3d0bf355b95 100644--- a/tests/gateway/test_api_server_jobs.py+++ b/tests/gateway/test_api_server_jobs.py@@ -12,7 +12,7 @@ Covers:import loggingfrom types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom aiohttp import web@@ -557,3 +557,50 @@ class TestCronPromptScanParity:assert "Blocked" in data["error"] or "threat" in data["error"].lower()mock_create.assert_not_called()++# ---------------------------------------------------------------------------+# 19. test_cron_fire_estop+# ---------------------------------------------------------------------------++class TestCronFireEstop:+ """ESTOP must halt the NAS-managed cron fire webhook (Door 2 of the bug report).++ See ``agent/estop.py:1-9`` contract: "the cron scheduler ... skips work;+ in-flight work is never killed." The webhook path was the gap — a managed-cron+ operator running ``hermes pause`` previously kept getting fires through.+ """++ @pytest.mark.asyncio+ async def test_fire_webhook_returns_503_when_estop_engaged(+ self, adapter, tmp_path, monkeypatch+ ):+ """Engaged ESTOP → 503 + Retry-After; claim_fire never reached."""+ from agent import estop++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ estop._logged_components.clear()+ estop.engage(reason="ops window")++ try:+ app = web.Application(middlewares=[cors_middleware])+ app["api_server_adapter"] = adapter+ app.router.add_post("/api/cron/fire", adapter._handle_cron_fire)++ claims = {"sub": "chronos", "aud": "test"}+ async with TestClient(TestServer(app)) as cli:+ with patch(f"{_MOD}._CRON_AVAILABLE", True), patch(+ f"{_MOD}._call_verifier", AsyncMock(return_value=claims)+ ):+ resp = await cli.post(+ "/api/cron/fire",+ json={"job_id": "aabbccddeeff"},+ headers={"Authorization": "Bearer test-token"},+ )+ assert resp.status == 503+ assert resp.headers.get("Retry-After") == "60"+ data = await resp.json()+ assert "paused" in data["error"].lower()+ assert data["job_id"] == "aabbccddeeff"+ finally:+ estop.disengage()+