Skip to content

The agent that grows with you

fix(cron): stop retry storms when the gateway is deliberately stopped (OOF-266)

Shannon Sands48221569231b
diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.py
index abe11f12cf8..8e846a132ee 100644
--- a/hermes_cli/web_routers/cron.py
+++ b/hermes_cli/web_routers/cron.py
@@ -44,12 +44,21 @@ _delete_cron_job_sync = late("_delete_cron_job_sync")
_find_cron_job_profile = late("_find_cron_job_profile")
_fire_cron_job_for_profile = late("_fire_cron_job_for_profile")
_forward_cron_fire_to_gateway = late("_forward_cron_fire_to_gateway")
+_gateway_intentionally_stopped = late("_gateway_intentionally_stopped")
_notify_cron_provider_for_profile = late("_notify_cron_provider_for_profile")
_call_cron_for_profile = late("_call_cron_for_profile")
_raise_if_cron_registration_error = late("_raise_if_cron_registration_error")
load_config = late("load_config")
cfg_get = late("cfg_get")
+# Retry-After hint (seconds) stamped on retryable cron-fire 503s. Sized to
+# clear the common transient windows — a scale-to-zero wake or an s6 gateway
+# restart completes well within a minute — so a scheduler that honors it
+# spaces its next attempt PAST the outage window instead of burning its whole
+# retry budget inside it (OOF-266). Honored by QStash once NAS propagates it;
+# harmless (ignored) until then.
+_CRON_FIRE_RETRY_AFTER_SECONDS = 60
+
@router.get("/api/cron/jobs")
async def list_cron_jobs(profile: str = "all"):
@@ -183,6 +192,42 @@ async def cron_fire_webhook(request: Request):
forwarded = await _forward_cron_fire_to_gateway(profile, job_id, auth)
if forwarded is None:
+ # Gateway unreachable. Split by OPERATOR INTENT (OOF-266):
+ #
+ # - Deliberately stopped gateway (durable desired_state == "stopped",
+ # written only by the s6 lifecycle commands): retrying can never
+ # succeed until a human starts the gateway again, so the retry
+ # budget is pure waste and the resulting 503→502 storms page the
+ # NAS on-call for a non-incident. Drop with 200 + a structured log
+ # line, mirroring NAS's own instance_stopped drop in the relay.
+ # The fire is NOT lost silently: the log names job and profile,
+ # and the gateway's Chronos provider reconciles + re-arms every
+ # job on its next startup (plugins/cron_providers/chronos
+ # start() -> reconcile()), so fires resume when the operator
+ # starts the gateway.
+ #
+ # - Transient window (scale-to-zero wake, restart, crash loop —
+ # desired_state is "running" or unknown): keep the retryable 503,
+ # but stamp Retry-After so a scheduler that honors it spaces its
+ # next attempt past the wake/restart window instead of exhausting
+ # the whole retry budget inside it.
+ if await _run_cron_dashboard_io(_gateway_intentionally_stopped, profile):
+ _log.info(
+ "cron fire dropped: gateway for profile %r is deliberately "
+ "stopped (desired_state=stopped); job %s will resume via "
+ "Chronos reconcile on next gateway start",
+ profile, job_id,
+ )
+ return JSONResponse(
+ {
+ "status": "gateway_stopped",
+ "detail": "gateway deliberately stopped; fire dropped, "
+ "jobs re-arm on next gateway start",
+ "job_id": job_id,
+ "profile": profile,
+ },
+ status_code=200,
+ )
return JSONResponse(
{
"error": "gateway unreachable; retry",
@@ -190,11 +235,19 @@ async def cron_fire_webhook(request: Request):
"profile": profile,
},
status_code=503,
+ headers={"Retry-After": str(_CRON_FIRE_RETRY_AFTER_SECONDS)},
)
status_code, gateway_body = forwarded
if isinstance(gateway_body, dict):
gateway_body.setdefault("job_id", job_id)
- return JSONResponse(gateway_body, status_code=status_code)
+ headers = (
+ # The gateway's own 503s (draining, admission failure) are equally
+ # transient — give the scheduler the same spacing hint.
+ {"Retry-After": str(_CRON_FIRE_RETRY_AFTER_SECONDS)}
+ if status_code == 503
+ else None
+ )
+ return JSONResponse(gateway_body, status_code=status_code, headers=headers)
@router.get("/api/cron/blueprints")
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 2cc53ece62d..dd6df807d0e 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -12709,7 +12709,11 @@ async def _forward_cron_fire_to_gateway(
gateway is unreachable (not started yet after a scale-to-zero wake,
restarting, or api_server disabled) — the caller maps that to 503 so NAS
retries per the Chronos contract (non-2xx = retryable; the store CAS
- de-dupes the eventual double fire).
+ de-dupes the eventual double fire), UNLESS the profile's gateway was
+ deliberately stopped (see :func:`_gateway_intentionally_stopped`), in
+ which case the caller drops the fire with 200 — retrying into an
+ operator-stopped gateway can never succeed and only burns scheduler
+ retries (OOF-266).
"""
_profile_name, home = _cron_profile_home(profile)
url = _gateway_fire_endpoint(_profile_name, home)
@@ -12737,6 +12741,43 @@ async def _forward_cron_fire_to_gateway(
return resp.status_code, body
+def _gateway_intentionally_stopped(profile: Optional[str]) -> bool:
+ """True when the profile's gateway is stopped BY OPERATOR INTENT.
+
+ Reads the durable ``desired_state`` field of the profile's
+ ``gateway_state.json`` — written exclusively by the s6 lifecycle
+ commands (``hermes gateway stop`` persists ``"stopped"``; start and
+ restart persist ``"running"``, see service_manager's
+ ``_write_gateway_desired_state``). This is the same operator-intent
+ signal container-boot reconciliation trusts, and it is precisely NOT
+ set to "stopped" during transient windows (crash loops, drains,
+ scale-to-zero wakes, restarts) — so it cleanly splits "retry will
+ eventually succeed" from "retry can never succeed".
+
+ Deliberately does NOT fall back to the volatile ``gateway_state``
+ runtime field: a legacy file without ``desired_state`` (or a gateway
+ that crashed before persisting) must stay on the retryable-503 path.
+ Failing open to "not intentionally stopped" is the safe direction —
+ the worst case is retries against a dead gateway, which is exactly
+ today's behavior.
+
+ Exception-safe: any resolution or parse failure returns False.
+ """
+ import json as _json
+
+ try:
+ _name, home = _cron_profile_home(profile)
+ state_file = home / "gateway_state.json"
+ if not state_file.exists():
+ return False
+ data = _json.loads(state_file.read_text(encoding="utf-8"))
+ if not isinstance(data, dict):
+ return False
+ return data.get("desired_state") == "stopped"
+ except Exception:
+ return False
+
+
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_cron_fire_dashboard.py b/tests/hermes_cli/test_cron_fire_dashboard.py
index bfbadfce914..a8c08df9395 100644
--- a/tests/hermes_cli/test_cron_fire_dashboard.py
+++ b/tests/hermes_cli/test_cron_fire_dashboard.py
@@ -250,3 +250,191 @@ def test_fire_endpoint_multiplex_profile_prefix(tmp_path, monkeypatch):
assert url == "http://127.0.0.1:8642/p/worker_alpha/api/cron/fire"
+# ── OOF-266: intentional-stop drop + Retry-After on transient 503 ─────────
+
+
+def test_gateway_unreachable_503_carries_retry_after(monkeypatch):
+ """Transient unreachable window (wake/restart) -> 503 WITH Retry-After so
+ the scheduler spaces retries past the window instead of exhausting its
+ budget inside it (OOF-266)."""
+
+ async def fake_forward(profile, job_id, authorization):
+ return None # unreachable
+
+ monkeypatch.setattr(
+ "plugins.cron_providers.chronos.verify.get_fire_verifier",
+ lambda: (lambda **kw: {"purpose": "cron_fire"}),
+ )
+ monkeypatch.setattr(web_server, "_find_cron_job_profile", lambda jid: "default")
+ monkeypatch.setattr(web_server, "_forward_cron_fire_to_gateway", fake_forward)
+ monkeypatch.setattr(
+ web_server, "_gateway_intentionally_stopped", lambda p: False
+ )
+
+ client, pa, ph = _client(auth_required=False)
+ try:
+ resp = client.post("/api/cron/fire",
+ headers={"Authorization": "Bearer nas-jwt"},
+ json={"job_id": "j4"})
+ assert resp.status_code == 503
+ assert resp.headers.get("Retry-After") == "60"
+ finally:
+ _restore(pa, ph)
+ client.close()
+
+
+def test_gateway_intentionally_stopped_drops_with_200(monkeypatch):
+ """Operator-stopped gateway (durable desired_state == "stopped") -> the
+ fire is DROPPED with 200: retrying can never succeed until a human starts
+ the gateway, so burning the scheduler retry budget only produces
+ 502-retry storms at NAS (OOF-266). Jobs re-arm via the Chronos provider's
+ reconcile on the next gateway start."""
+ executed = []
+
+ async def fake_forward(profile, job_id, authorization):
+ return None # unreachable — gateway process is down
+
+ monkeypatch.setattr(
+ "plugins.cron_providers.chronos.verify.get_fire_verifier",
+ lambda: (lambda **kw: {"purpose": "cron_fire"}),
+ )
+ monkeypatch.setattr(web_server, "_find_cron_job_profile", lambda jid: "default")
+ monkeypatch.setattr(web_server, "_forward_cron_fire_to_gateway", fake_forward)
+ monkeypatch.setattr(
+ web_server, "_gateway_intentionally_stopped", lambda p: True
+ )
+ monkeypatch.setattr(web_server, "_fire_cron_job_for_profile",
+ lambda p, j: executed.append((p, j)))
+
+ client, pa, ph = _client(auth_required=False)
+ try:
+ resp = client.post("/api/cron/fire",
+ headers={"Authorization": "Bearer nas-jwt"},
+ json={"job_id": "j5"})
+ assert resp.status_code == 200
+ assert resp.json().get("status") == "gateway_stopped"
+ assert executed == [] # dropped, never locally executed
+ finally:
+ _restore(pa, ph)
+ client.close()
+
+
+def test_stopped_check_only_consulted_when_gateway_unreachable(monkeypatch):
+ """A reachable gateway's response passes through untouched — the
+ intentional-stop check must not run (a stale desired_state file must
+ never shadow a live gateway)."""
+ consulted = []
+
+ async def fake_forward(profile, job_id, authorization):
+ return 202, {"status": "accepted", "job_id": job_id}
+
+ def fake_stopped(profile):
+ consulted.append(profile)
+ return True # would drop if (wrongly) consulted
+
+ monkeypatch.setattr(
+ "plugins.cron_providers.chronos.verify.get_fire_verifier",
+ lambda: (lambda **kw: {"purpose": "cron_fire"}),
+ )
+ monkeypatch.setattr(web_server, "_find_cron_job_profile", lambda jid: "default")
+ monkeypatch.setattr(web_server, "_forward_cron_fire_to_gateway", fake_forward)
+ monkeypatch.setattr(web_server, "_gateway_intentionally_stopped", fake_stopped)
+
+ client, pa, ph = _client(auth_required=False)
+ try:
+ resp = client.post("/api/cron/fire",
+ headers={"Authorization": "Bearer nas-jwt"},
+ json={"job_id": "j6"})
+ assert resp.status_code == 202
+ assert consulted == []
+ finally:
+ _restore(pa, ph)
+ client.close()
+
+
+def test_gateway_own_503_also_carries_retry_after(monkeypatch):
+ """The gateway's OWN 503 (draining / admission failure) is equally
+ transient — the pass-through stamps the same Retry-After hint. Other
+ statuses stay header-free."""
+
+ async def fake_forward(profile, job_id, authorization):
+ return 503, {"error": "gateway draining"}
+
+ monkeypatch.setattr(
+ "plugins.cron_providers.chronos.verify.get_fire_verifier",
+ lambda: (lambda **kw: {"purpose": "cron_fire"}),
+ )
+ monkeypatch.setattr(web_server, "_find_cron_job_profile", lambda jid: "default")
+ monkeypatch.setattr(web_server, "_forward_cron_fire_to_gateway", fake_forward)
+
+ client, pa, ph = _client(auth_required=False)
+ try:
+ resp = client.post("/api/cron/fire",
+ headers={"Authorization": "Bearer nas-jwt"},
+ json={"job_id": "j7"})
+ assert resp.status_code == 503
+ assert resp.headers.get("Retry-After") == "60"
+ finally:
+ _restore(pa, ph)
+ client.close()
+
+
+# ── _gateway_intentionally_stopped (durable operator intent) ──────────────
+
+
+def _stopped_check_home(monkeypatch, tmp_path):
+ """Point the profile resolver at tmp_path so the check reads our file."""
+ monkeypatch.setattr(
+ web_server, "_cron_profile_home", lambda p: ("default", tmp_path)
+ )
+
+
+def test_intentionally_stopped_true_on_desired_state_stopped(tmp_path, monkeypatch):
+ _stopped_check_home(monkeypatch, tmp_path)
+ (tmp_path / "gateway_state.json").write_text(
+ '{"gateway_state":"stopped","desired_state":"stopped"}', encoding="utf-8"
+ )
+ assert web_server._gateway_intentionally_stopped("default") is True
+
+
+def test_intentionally_stopped_false_when_desired_running(tmp_path, monkeypatch):
+ """Crash loop / transient outage: runtime says stopped but operator intent
+ is running -> stay on the retryable path."""
+ _stopped_check_home(monkeypatch, tmp_path)
+ (tmp_path / "gateway_state.json").write_text(
+ '{"gateway_state":"startup_failed","desired_state":"running"}',
+ encoding="utf-8",
+ )
+ assert web_server._gateway_intentionally_stopped("default") is False
+
+
+def test_intentionally_stopped_false_on_legacy_file_without_desired_state(
+ tmp_path, monkeypatch
+):
+ """Legacy gateway_state.json (no desired_state) must NOT count as
+ intentional — the volatile runtime field can read 'stopped' during
+ transient windows. Fail open to the retryable path."""
+ _stopped_check_home(monkeypatch, tmp_path)
+ (tmp_path / "gateway_state.json").write_text(
+ '{"gateway_state":"stopped"}', encoding="utf-8"
+ )
+ assert web_server._gateway_intentionally_stopped("default") is False
+
+
+def test_intentionally_stopped_false_on_missing_or_bad_file(tmp_path, monkeypatch):
+ _stopped_check_home(monkeypatch, tmp_path)
+ assert web_server._gateway_intentionally_stopped("default") is False
+ (tmp_path / "gateway_state.json").write_text("{not json", encoding="utf-8")
+ assert web_server._gateway_intentionally_stopped("default") is False
+ (tmp_path / "gateway_state.json").write_text('["list"]', encoding="utf-8")
+ assert web_server._gateway_intentionally_stopped("default") is False
+
+
+def test_intentionally_stopped_false_when_profile_resolution_fails(monkeypatch):
+ """Exception-safe: any resolution failure (unknown profile, bad name)
+ returns False — never blocks the retryable path."""
+ def boom(profile):
+ raise RuntimeError("no such profile")
+
+ monkeypatch.setattr(web_server, "_cron_profile_home", boom)
+ assert web_server._gateway_intentionally_stopped("ghost") is False