Skip to content

The agent that grows with you

fix(api): /v1/runs admission storage failure answers 503 and keeps no ghost reservation

Teknium592ac7246abf
diff --git a/gateway/platforms/api_server_authority_runs.py b/gateway/platforms/api_server_authority_runs.py
index c2ed1f30c06..60e31f48f36 100644
--- a/gateway/platforms/api_server_authority_runs.py
+++ b/gateway/platforms/api_server_authority_runs.py
@@ -12,6 +12,16 @@ def _authority(adapter):
return active_authority(adapter.gateway_runner)
+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."""
+ 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'})
+
+
def run_admission(adapter, run_id):
authority = _authority(adapter)
if authority is None:
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index a1c8b61bcfe..96fd4aa946d 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -668,8 +668,10 @@ async def _admit_run_to_authority(
self, launch, run_id, session_history_delivery, _declared_selected,
idempotency_scope, idempotency_key, _openai_error,
) -> Optional[web.Response]:
- """Admit a /v1/runs turn to the session authority FIFO -> ``None``, or the 409 refusal."""
+ """Admit a /v1/runs turn to the session authority FIFO -> ``None``, or the refusal."""
+ from gateway.platforms.api_server_authority_runs import run_admission, store_error_response
from gateway.session_api_turn import admit_api_turn_async
+ from gateway.session_contract import SessionRef
from hermes_state_runtime import RuntimeStoreError
try:
with self._profile_scope(launch.request_profile):
@@ -681,7 +683,13 @@ async def _admit_run_to_authority(
session_history_delivery='1' if session_history_delivery else '',
bind_declared_conversation=_declared_selected,
**launch.agent_kwargs)
- except RuntimeStoreError as exc:
+ except Exception as exc: # health: allow BLE001 -- answered below; a committed admission is kept
+ # A storage failure after the admission committed (a later media-release write) still
+ # owns that run: forgetting it would let a keyed retry admit the same work twice.
+ owned = None if isinstance(exc, RuntimeStoreError) else await asyncio.to_thread(run_admission, self, run_id)
+ if owned is not None:
+ launch.admission = (owned[0], SessionRef(owned[0].profile_id, owned[1]['target_session_id']), owned[1])
+ return None
# A refused admission owns no run: drop every reservation so an exact
# retry is refused again instead of replaying a run nobody executes.
_forget_run(
@@ -689,7 +697,7 @@ async def _admit_run_to_authority(
self._run_statuses, self._run_owners, self._run_idempotency_ids)
if idempotency_key:
self._run_idempotency_store.forget(idempotency_scope, idempotency_key)
- return _json_error(_openai_error, exc.reason, code=exc.reason, status=409)
+ return store_error_response(_openai_error, exc)
return None
diff --git a/tests/gateway/test_api_runs_admission_storage_error.py b/tests/gateway/test_api_runs_admission_storage_error.py
new file mode 100644
index 00000000000..74efff4df48
--- /dev/null
+++ b/tests/gateway/test_api_runs_admission_storage_error.py
@@ -0,0 +1,61 @@
+"""POST /v1/runs whose admission write loses the state.db writer answers a retryable 503 and
+keeps no reservation: an exact Idempotency-Key retry then runs the work, never replays a ghost."""
+import asyncio
+import sqlite3
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import GatewayConfig
+from gateway.session import SessionStore
+from gateway.session_authority import initialize_session_authority
+from hermes_state import SessionDB
+from tests.gateway.test_api_unknown_resolution import _AUTH_HEADERS, _adapter, _runs_client
+
+
+async def test_locked_admission_write_is_503_and_exact_retry_runs(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ store = SessionStore(tmp_path / "sessions", GatewayConfig())
+ db = SessionDB(tmp_path / "state.db")
+ executed = []
+
+ async def answer(event):
+ from gateway.session_results import execution_result
+ executed.append(event.text)
+ execution_result.get()["result"] = {"final_response": "ACK", "messages": []}
+ return "ACK"
+
+ runner = SimpleNamespace(_session_db=db, session_store=store, _draining=False, _handle_message=answer)
+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="lock-owner")
+ adapter = _adapter(runner, db)
+ runner._adapter_for_source = lambda source: adapter
+ monkeypatch.setattr(SessionDB, "_WRITE_PATIENCE_S", 0.3)
+ client = _runs_client(adapter)
+ await client.start_server()
+ headers = {**_AUTH_HEADERS, "Idempotency-Key": "locked-run"}
+ body = {"input": "LOCKED", "session_id": "api-session"}
+ # Another process holds the state.db writer past this owner's write patience.
+ holder = sqlite3.connect(tmp_path / "state.db", isolation_level=None)
+ holder.execute("BEGIN IMMEDIATE")
+ try:
+ refused = await client.post("/v1/runs", json=body, headers=headers)
+ assert refused.status == 503, await refused.text()
+ assert (await refused.json())["error"]["code"] == "storage_unavailable"
+ assert refused.headers.get("Retry-After")
+ assert not adapter._run_statuses and not adapter._run_owners and not adapter._run_idempotency_ids
+ holder.execute("ROLLBACK")
+ retry = await client.post("/v1/runs", json=body, headers=headers)
+ assert retry.status == 202, await retry.text()
+ assert (await retry.json())["replayed"] is False
+ await asyncio.wait_for(asyncio.gather(*adapter._active_run_tasks.values()), 10)
+ assert executed == ["LOCKED"]
+ finally:
+ holder.close()
+ for task in adapter._active_run_tasks.values():
+ task.cancel()
+ await client.close()
+ adapter._response_store.close()
+ adapter._run_idempotency_store.close()
+ authority.db.close()
+ store.close_all_db_handles()