The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): one drain predicate for the fire gate and the adapter
kshitijk4poor77bf0d7f737b
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex b24537a1cc4..38d4eef3d9f 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -1303,10 +1303,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):def _gateway_is_draining() -> bool:"""Whether the owning gateway currently refuses new agent turns."""try:+ from gateway.platforms.api_server_fire_startup import runner_is_drainingfrom gateway.run import _gateway_runner_refrunner = _gateway_runner_ref()- return bool(runner and (getattr(runner, "_draining", False)- or getattr(runner, "_external_drain_active", False)))+ return bool(runner) and runner_is_draining(runner)except Exception:return Falsediff --git a/gateway/platforms/api_server_fire_startup.py b/gateway/platforms/api_server_fire_startup.pyindex d2f255f3c2b..50d5693e441 100644--- a/gateway/platforms/api_server_fire_startup.py+++ b/gateway/platforms/api_server_fire_startup.py@@ -22,6 +22,11 @@ FIRE_STARTUP_WAIT_SECONDS = 7.0_POLL_SECONDS = 0.1+def runner_is_draining(runner: Any) -> bool:+ """Whether ``runner`` refuses new work (an in-process drain, or one an external supervisor started)."""+ return bool(getattr(runner, "_draining", False) or getattr(runner, "_external_drain_active", False))++async def refuse_until_started(runner: Any, job_id: str, *, received_at: float) -> Optional["web.Response"]:"""None once ``runner`` has finished starting (``_running``: every platform connect attempted and itsadapters published), or when there is no runner to ask (a self-hosted api_server, a test double).@@ -30,20 +35,21 @@ async def refuse_until_started(runner: Any, job_id: str, *, received_at: float)``received_at`` is the loop time the handler was entered: time already spent verifying the tokencounts against the budget."""+ if runner is None:+ return Noneloop = asyncio.get_running_loop()deadline = received_at + FIRE_STARTUP_WAIT_SECONDS- while runner is not None:+ while True:# Re-checked after every poll: the handler's drain check ran before this wait, and a gateway that# starts draining meanwhile (a restart keeps _running True; a stop mid-boot never sets it) must not# claim the fire.- draining = getattr(runner, "_draining", False) or getattr(runner, "_external_drain_active", False)+ draining = runner_is_draining(runner)if not draining and getattr(runner, "_running", True):return Noneif draining or loop.time() >= deadline:return web.json_response({"error": "gateway unreachable; retry", "job_id": job_id}, status=503, headers={"Retry-After": "60"})await asyncio.sleep(_POLL_SECONDS)- return Noneasync def live_adapters_once_started(diff --git a/tests/cron/test_cron_relay_dm_origin_user_id.py b/tests/cron/test_cron_relay_dm_origin_user_id.pyindex 26e8751bebd..ee4df72d50c 100644--- a/tests/cron/test_cron_relay_dm_origin_user_id.py+++ b/tests/cron/test_cron_relay_dm_origin_user_id.py@@ -73,7 +73,8 @@ def test_cold_adapter_send_reaches_the_transport_with_user_id(monkeypatch):"""End to end through the live lane: what the connector sees on the wire for a cold-cache relay DM."""monkeypatch.setattr(sd, "_maybe_mirror_cron_delivery", lambda *a, **k: None)loop = asyncio.new_event_loop()- threading.Thread(target=loop.run_forever, daemon=True).start()+ th = threading.Thread(target=loop.run_forever, daemon=True)+ th.start()try:relay = _Relay()t = _target(@@ -84,4 +85,6 @@ def test_cold_adapter_send_reaches_the_transport_with_user_id(monkeypatch):t, "hi", [], target_errors=target_errors, delivery_errors=delivery_errors, unverified_targets=[])finally:loop.call_soon_threadsafe(loop.stop)+ th.join(5)+ loop.close()assert [m.get("user_id") for m in relay.sent] == [DM_USER]diff --git a/tests/gateway/test_cron_fire_startup_gate.py b/tests/gateway/test_cron_fire_startup_gate.pyindex d25899ed826..9576c8c9391 100644--- a/tests/gateway/test_cron_fire_startup_gate.py+++ b/tests/gateway/test_cron_fire_startup_gate.py@@ -156,17 +156,17 @@ async def test_started_gateway_is_accepted_immediately(adapter, provider):async def test_slow_token_verify_spends_the_startup_budget(adapter, provider, monkeypatch):"""The budget runs from handler entry: a slow JWKS fetch plus a full wait would outlast the dashboardforwarder's timeout, NAS would retry while this handler still ran the job, and it would run twice."""- monkeypatch.setattr(api_server_fire_startup, "FIRE_STARTUP_WAIT_SECONDS", 1.5)+ monkeypatch.setattr(api_server_fire_startup, "FIRE_STARTUP_WAIT_SECONDS", 0.3)async def _slow_verifier(**_kw):- await asyncio.sleep(2.0)+ await asyncio.sleep(0.4)return {"purpose": "cron_fire"}monkeypatch.setattr("plugins.cron_providers.chronos.verify.get_fire_verifier", lambda: _slow_verifier)runner = SimpleNamespace(_draining=False, _external_drain_active=False, _running=False, adapters={})async def _finish_startup(): # inside a wait measured from the gate, outside one measured from entry- await asyncio.sleep(2.5)+ await asyncio.sleep(0.5)runner._running = Truefinisher = asyncio.ensure_future(_finish_startup())diff --git a/website/docs/developer-guide/chronos-managed-cron-contract.md b/website/docs/developer-guide/chronos-managed-cron-contract.mdindex c7d4c34f400..e9ea6d481a7 100644--- a/website/docs/developer-guide/chronos-managed-cron-contract.md+++ b/website/docs/developer-guide/chronos-managed-cron-contract.md@@ -166,6 +166,10 @@ There is deliberately no in-dashboard execution fallback. The verifier is- invalid/missing/forged/expired/wrong-aud/wrong-purpose token → **401**, noexecution.- missing `job_id` → **400**.+ - gateway still starting (a scale-to-zero wake) → the fire waits up to 7 s,+ counted from receipt, for the gateway to finish starting. If it doesn't, or+ a drain begins meanwhile → **503** `{"error": "gateway unreachable; retry"}`+ with `Retry-After: 60`, nothing claimed (NAS retries).- valid → **202 `{"status": "accepted", "job_id": "..."}`** immediately, andthe job runs in the background. 202-before-run means a long agent turn nevertrips the relay's HTTP timeout.