The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): terminalize durable runs during gateway shutdown
joaomarcos3293964fb9f3
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 721b6d9f50b..509eea277a6 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -1208,6 +1208,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):def interrupt_active_runs(self, reason: str) -> int:"""Interrupt every adapter-owned agent during shutdown (they are not in``GatewayRunner._running_agents``): exactly the set the drain waits on. Returns count."""+ run_ids = {+ run_id for run_id, task in self._active_run_tasks.items() if not task.done()+ } | set(self._active_run_agents)+ _api_runs._mark_shutdown_interrupted_runs(self, run_ids)# Dedupe by identity: an agent in both registries must be interrupted once.agents = {id(agent): agent for agent in (*self._active_run_agents.values(), *self._shutdown_interruptible_agents.values())diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 0acfed5a85f..86a5c89c47b 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -128,6 +128,7 @@ def _initialize_run_state(self, *, store_factory) -> None:self._run_idempotency_ids: set[str] = set()self._run_stream_subscribers: set[str] = set()self._stopping_run_ids: set[str] = set()+ self._shutdown_interrupted_run_ids: set[str] = set()(self._run_owners, self._run_streams, self._run_streams_created, self._active_run_agents,self._active_run_tasks, self._run_statuses, self._run_approval_sessions,@@ -182,6 +183,21 @@ def _set_run_status(self, run_id: str, status: str, **fields: Any) -> Dict[str,return current+def _mark_shutdown_interrupted_runs(self, run_ids) -> None:+ """Publish the shutdown outcome before cooperative interruption can race teardown."""+ for run_id in run_ids:+ self._shutdown_interrupted_run_ids.add(run_id)+ try:+ self._set_run_status(+ run_id,+ "interrupted",+ error="Gateway shutdown interrupted the run.",+ last_event="run.interrupted",+ )+ except Exception:+ logger.exception("[api_server] failed to record shutdown for run %s", run_id)++def _make_run_event_callback(self, run_id: str, loop: "asyncio.AbstractEventLoop", *, _api_server):"""Return a callback that pushes structured events to the run SSE queue."""redact_sensitive_text = _api_server.redact_sensitive_text@@ -392,7 +408,7 @@ def _forget_run(self, run_id: str, *tables) -> None:def _retire_live_run(self, run_id: str) -> None:"""Retire agent/task/approval control state once the executor-backed task is done."""_forget_run(self, run_id, self._active_run_agents, self._active_run_tasks, self._run_approval_sessions,- self._stopping_run_ids)+ self._stopping_run_ids, self._shutdown_interrupted_run_ids)def _drop_run_transport(self, run_id: str) -> None:@@ -652,6 +668,10 @@ async def _execute_run(self, run: _RunLaunch, *, _api_server) -> None:def _finish(status: str, extra: Optional[dict] = None, **fields: Any) -> None:"""Terminal status, then best-effort ``run.<status>`` event; key order is wire shape."""extra = extra or {}+ if run_id in self._shutdown_interrupted_run_ids:+ status = "interrupted"+ fields = {"error": "Gateway shutdown interrupted the run."}+ extra = {}self._set_run_status(run_id, status, **fields, last_event=f"run.{status}", **extra)with suppress(Exception):run.put_event(_run_event(run_id, f"run.{status}", **fields, **extra))diff --git a/tests/gateway/test_api_server_active_work_drain.py b/tests/gateway/test_api_server_active_work_drain.pyindex 78a90ba0346..a25798c6ab0 100644--- a/tests/gateway/test_api_server_active_work_drain.py+++ b/tests/gateway/test_api_server_active_work_drain.py@@ -8,6 +8,7 @@ turns once the gateway starts draining."""import asyncio+import hashlibimport threadingfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch@@ -18,6 +19,7 @@ from aiohttp.test_utils import TestClient, TestServerfrom gateway.config import Platform, PlatformConfigfrom gateway.platforms.api_server import APIServerAdapter+from gateway.platforms.api_server_run_idempotency import RunIdempotencyStorefrom gateway.run import _INTERRUPT_REASON_GATEWAY_SHUTDOWNfrom hermes_state import SessionDBfrom tests.gateway.restart_test_helpers import make_restart_runner@@ -410,6 +412,66 @@ class TestInterruptActiveRuns:class TestShutdownInterruptReachesEveryApiTurn:+ @pytest.mark.parametrize("late_outcome", ["success", "failure"])+ @pytest.mark.asyncio+ async def test_shutdown_terminalizes_durable_run_before_late_completion(+ self, tmp_path, late_outcome+ ):+ runner, _adapter = make_restart_runner()+ api = APIServerAdapter(PlatformConfig(enabled=True))+ api._run_idempotency_store.close()+ api._run_idempotency_store = RunIdempotencyStore(str(tmp_path / "idem.db"))+ runner.adapters = {Platform.API_SERVER: api}+ app = _make_admission_app(api)++ loop = asyncio.get_running_loop()+ started = asyncio.Event()+ release = threading.Event()+ agent = _parked_agent(loop, started, release)+ if late_outcome == "failure":+ def _late_failure(user_message=None, conversation_history=None, task_id=None):+ loop.call_soon_threadsafe(started.set)+ release.wait(_TURN_UNBLOCK_TIMEOUT)+ raise RuntimeError("late failure")++ agent.run_conversation.side_effect = _late_failure+ run_id = None+ try:+ with patch.object(api, "_create_agent", return_value=agent):+ async with TestClient(TestServer(app)) as client:+ request = asyncio.ensure_future(+ client.post(+ "/v1/runs",+ json={"input": "hello"},+ headers={"Idempotency-Key": "shutdown-run"},+ )+ )+ await asyncio.wait_for(started.wait(), _TURN_UNBLOCK_TIMEOUT)+ response = await request+ assert response.status == 202+ run_id = (await response.json())["run_id"]++ runner._interrupt_running_agents(_INTERRUPT_REASON_GATEWAY_SHUTDOWN)+ for _ in range(100):+ if run_id not in api._active_run_tasks:+ break+ await asyncio.sleep(0.01)+ finally:+ release.set()+ api._run_idempotency_store.close()++ scope = hashlib.sha256(b"default\0unauthenticated-test-listener").hexdigest()+ status_store = RunIdempotencyStore(str(tmp_path / "idem.db"))+ try:+ record = status_store.status_for_run(scope, run_id)+ finally:+ status_store.close()+ assert record is not None+ assert record["status"]["status"] == "interrupted"+ assert record["status"]["last_event"] == "run.interrupted"+ assert record["status"]["error"] == "Gateway shutdown interrupted the run."+ assert api._shutdown_interrupted_run_ids == set()+@pytest.mark.asyncioasync def test_chat_completions_turn_is_interrupted(self):"""A non-``/v1/runs`` API turn, end to end through the real handler.