The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): canonical store refusals map to 400/503 instead of a blanket 409
Teknium6977bda9ab24
diff --git a/gateway/platforms/api_server_authority_runs.py b/gateway/platforms/api_server_authority_runs.pyindex 60e31f48f36..805b1fde45b 100644--- a/gateway/platforms/api_server_authority_runs.py+++ b/gateway/platforms/api_server_authority_runs.py@@ -12,14 +12,19 @@ def _authority(adapter):return active_authority(adapter.gateway_runner)+# Malformed input is 400 and a retryable refusal 503; every other reason (ownership, generation,+# identity) keeps the documented 409, as /v1/runs clients already branch on it.+_STORE_ERROR_STATUS = {'invalid_params': 400, 'runtime_draining': 503, 'storage_unavailable': 503}++def store_error_response(_openai_error, exc):"""A refused store call -> HTTP: a ``RuntimeStoreError`` keeps its reason; any other failure- (SQLite writer patience exhausted, I/O) is ``storage_unavailable``, a retryable 503."""+ (SQLite writer patience exhausted, I/O) is ``storage_unavailable``."""from aiohttp import web- if isinstance(exc, RuntimeStoreError):- return web.json_response(_openai_error(exc.reason, code=exc.reason), status=409)- return web.json_response(_openai_error('storage_unavailable', code='storage_unavailable'),- status=503, headers={'Retry-After': '1'})+ reason = exc.reason if isinstance(exc, RuntimeStoreError) else 'storage_unavailable'+ status = _STORE_ERROR_STATUS.get(reason, 409)+ return web.json_response(_openai_error(reason, code=reason), status=status,+ headers={'Retry-After': '1'} if status == 503 else None)def run_admission(adapter, run_id):diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex dcb8a05ad29..e0aef9bd458 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -1036,7 +1036,8 @@ class OpenAICompatRoutesMixin:return (result, usage), Noneexcept RuntimeStoreError as exc:from gateway.platforms.api_server import _openai_error- return None, web.json_response(_openai_error(exc.reason, code=exc.reason), status=409)+ from gateway.platforms.api_server_authority_runs import store_error_response+ return None, store_error_response(_openai_error, exc)except Exception as e:logger.error("Error running agent for %s: %s", log_label, e, exc_info=True)message = "" if getattr(e, "_notification_presentation_suppressed", False) is True else f"Internal server error: {e}"@@ -1302,7 +1303,8 @@ class OpenAICompatRoutesMixin:self, request, body, gateway_session_key, durable_key, idempotency_scope, idempotency_key)except RuntimeStoreError as exc:from gateway.platforms.api_server import _openai_error- return web.json_response(_openai_error(exc.reason, code=exc.reason), status=409)+ from gateway.platforms.api_server_authority_runs import store_error_response+ return store_error_response(_openai_error, exc)if error is not None:return errorsession_id, user_message = context['session_id'], context['user_message']diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 96fd4aa946d..9de9052b988 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -1337,13 +1337,13 @@ async def _handle_run_approval(self, request: web.Request, *, _api_server) -> weasync def _respond_authority_run(self, run_id, body, *, kind, _api_server):- from gateway.platforms.api_server_authority_runs import respond_run+ from gateway.platforms.api_server_authority_runs import respond_run, store_error_responsefrom hermes_state_runtime import RuntimeStoreErrortry:result = await respond_run(self, run_id, body, kind=kind)return web.json_response({'run_id': run_id, **result})except RuntimeStoreError as exc:- return _json_error(_api_server._openai_error, exc.reason, code=exc.reason, status=409)+ return store_error_response(_api_server._openai_error, exc)async def _handle_run_clarify(self, request, *, _api_server):@@ -1428,12 +1428,12 @@ async def _handle_stop_run(self, request: web.Request, *, _api_server) -> web.Re# admission: its stop is the legacy in-process task cancel below, never ``stop_run``.if (getattr(self.gateway_runner, 'session_authority', None) is not Noneand not (task is not None and status.get("delivery_id"))):- from gateway.platforms.api_server_authority_runs import stop_run+ from gateway.platforms.api_server_authority_runs import stop_run, store_error_responsefrom hermes_state_runtime import RuntimeStoreErrortry:return web.json_response(await stop_run(self, run_id))except RuntimeStoreError as exc:- return _json_error(_openai_error, exc.reason, code=exc.reason, status=409)+ return store_error_response(_openai_error, exc)if status.get("status") in TERMINAL_STATUSES:return web.json_response(status)if agent is None and task is None:@@ -1463,14 +1463,13 @@ async def _handle_resolve_unknown_run(body = await request.json()except (ValueError, LookupError): # bad JSON/UTF-8 (ValueError) or unknown charset: no bodybody = None- from gateway.platforms.api_server_authority_runs import resolve_unknown_run+ from gateway.platforms.api_server_authority_runs import resolve_unknown_run, store_error_responsefrom hermes_state_runtime import RuntimeStoreErrortry:result = await resolve_unknown_run(self, run_id, body)return web.json_response({'run_id': run_id, **result})except RuntimeStoreError as exc:- return _json_error(- _api_server._openai_error, exc.reason, code=exc.reason, status=409)+ return store_error_response(_api_server._openai_error, exc)async def _sweep_orphaned_runs(self) -> None:diff --git a/tests/gateway/test_api_store_error_status.py b/tests/gateway/test_api_store_error_status.pynew file mode 100644index 00000000000..6ed2db9e9b4--- /dev/null+++ b/tests/gateway/test_api_store_error_status.py@@ -0,0 +1,33 @@+"""Canonical API refusals keep their retry semantics on the wire: a retiring profile's+admission is a retryable 503 (Retry-After), a malformed control body is 400, and a+generation/ownership refusal stays 409."""+import pytest++from tests.gateway.test_api_unknown_resolution import _AUTH_HEADERS, _close_fixture, _restarted_api_runs+++async def test_store_refusal_reasons_map_to_retryable_or_client_status(tmp_path, monkeypatch):+ client, adapters, store, owner, unknown, _follower, _executed, tasks = (+ await _restarted_api_runs(tmp_path, monkeypatch))+ path = "/v1/runs/" + unknown["request_id"] + "/resolve-unknown"+ body = {"admission_id": unknown["admission_id"], "execution_generation": unknown["generation"]}+ try:+ cases = (+ ("POST", path, body | {"extra": True}, 400, "invalid_params"),+ ("POST", path, body | {"execution_generation": unknown["generation"] + 1}, 409, "stale_generation"),+ ("POST", "/v1/runs/" + unknown["request_id"] + "/stop", None, 409, "unknown_execution"),+ )+ for method, url, payload, status, code in cases:+ response = await client.request(method, url, json=payload, headers=_AUTH_HEADERS)+ assert (response.status, (await response.json())["error"]["code"]) == (status, code), url+ # A retiring (hot-unserved) profile refuses after the entry drain check: retry later, not a conflict.+ owner.retiring = True+ refused = await client.post("/v1/runs", json={"input": "LATER", "session_id": "api-session"},+ headers={**_AUTH_HEADERS, "Idempotency-Key": "retiring-run"})+ assert refused.status == 503, await refused.text()+ assert (await refused.json())["error"]["code"] == "runtime_draining"+ assert refused.headers.get("Retry-After")+ finally:+ owner.retiring = False+ await _close_fixture(client, adapters, store, tasks)diff --git a/tests/gateway/test_api_unknown_resolution.py b/tests/gateway/test_api_unknown_resolution.pyindex 7b1360c7f18..bb0deff9aa7 100644--- a/tests/gateway/test_api_unknown_resolution.py+++ b/tests/gateway/test_api_unknown_resolution.py@@ -230,7 +230,7 @@ async def test_http_resolve_unknown_refuses_stale_or_foreign_admission()for body, code in attempts:response = await client.post(run_path, json=body, headers=_AUTH_HEADERS)- assert response.status == 409+ assert response.status == (400 if code == "invalid_params" else 409)assert (await response.json())["error"]["code"] == code# A refused resolution must not release the FIFO: let any drain it scheduled run to the end