Skip to content

The agent that grows with you

fix(api): don't tell a queued API caller to retry during a restart

unsupportedpastelsf3b1c821ea46
diff --git a/gateway/platforms/api_server_authority_runs.py b/gateway/platforms/api_server_authority_runs.py
index 805b1fde45b..1899ab4b64f 100644
--- a/gateway/platforms/api_server_authority_runs.py
+++ b/gateway/platforms/api_server_authority_runs.py
@@ -22,6 +22,11 @@ def store_error_response(_openai_error, exc):
(SQLite writer patience exhausted, I/O) is ``storage_unavailable``."""
from aiohttp import web
reason = exc.reason if isinstance(exc, RuntimeStoreError) else 'storage_unavailable'
+ if reason == 'admission_queued':
+ # Accepted and still queued for the next owner, so not retryable: no Retry-After, and
+ # x-should-retry tells the OpenAI/Anthropic SDKs not to retry the 503 on their own.
+ return web.json_response(_openai_error(str(exc), err_type='server_error', code=reason), status=503,
+ headers={'x-should-retry': 'false'})
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)
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 9de9052b988..f94b5c8f3d5 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -1104,6 +1104,13 @@ async def _execute_run(self, run: _RunLaunch, *, _api_server) -> None:
logger.warning("Provider resolution failed for run=%s: %s", run_id, exc)
_finish("failed", error=exc.user_text())
except Exception as exc:
+ if getattr(exc, "reason", None) == "admission_queued":
+ # Still queued at a retiring owner: the next owner runs it once, and GET /v1/runs/{id}
+ # reads that row. A run.failed here would invite a poller to resubmit it.
+ self._set_run_status(run_id, "queued", last_event="run.queued")
+ with suppress(Exception):
+ loop.call_soon(run.put_event, _run_event(run_id, "run.queued", message=str(exc)))
+ return
logger.exception("[api_server] run %s failed", run_id)
_finish("failed", error=_redact_api_error_text(exc))
finally:
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index 2d0c47144ec..c0e22a66f91 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -25,6 +25,18 @@ _SETTING_KEYS = ('ephemeral_system_prompt', 'requested_model', 'requested_provid
_OWNER_SCOPE_RE = re.compile(r'[0-9a-f]{64}')
+class AdmissionQueued(RuntimeStoreError):
+ """The owner retired while this API admission was still queued. Unlike a refused request, the
+ input is committed: the row stays queued and the next owner runs it exactly once, so a client
+ that resends it submits the work twice. ``str()`` is the message every API surface shows."""
+
+ MESSAGE = 'Hermes is restarting. Your input is saved and will run once when it is back; do not resend it.'
+
+ def __init__(self):
+ super().__init__('admission_queued')
+ self.args = (self.MESSAGE,)
+
+
def api_settings(authority, ref):
with authority.db._read_ctx() as conn:
saved = conn.execute('SELECT value FROM state_meta WHERE key=?',
@@ -374,6 +386,13 @@ async def observe_api_turn(admitted, **kwargs):
authority._publish_pending(ref)
authority._schedule(ref)
await asyncio.shield(waiter)
+ except RuntimeStoreError as exc:
+ # Retirement releases every observer with runtime_draining, the same reason a refused
+ # request gets. This one's input is admitted: say so while the row is still queued.
+ current = get_session_admission(authority.db, admission_id=row['admission_id']) or {}
+ if exc.reason == 'runtime_draining' and current.get('status') == 'queued':
+ raise AdmissionQueued() from exc
+ raise
finally:
# Shielding keeps the canonical turn alive past a cancelled request; only this
# request's observer leaves, and the entry itself goes once the last one is gone.
diff --git a/tests/gateway/test_api_admission_queued_on_drain.py b/tests/gateway/test_api_admission_queued_on_drain.py
new file mode 100644
index 00000000000..bcf0787cdd5
--- /dev/null
+++ b/tests/gateway/test_api_admission_queued_on_drain.py
@@ -0,0 +1,86 @@
+"""An API caller whose input is still queued when the gateway retires is told it is saved (#134889).
+
+Retirement releases every observer with runtime_draining, which the HTTP layer answered with a
+retryable 503 + Retry-After: the answer a refused request gets. The row stayed queued and ran
+exactly once under the next owner, so a client that retried on the 503 submitted the work twice.
+"""
+import asyncio
+import json
+
+import pytest
+
+from gateway import run_runtime
+from gateway.platforms.api_server import _openai_error
+from gateway.platforms.api_server_authority_runs import store_error_response
+from gateway.session_api_turn import AdmissionQueued, observe_api_turn
+from gateway.session_contract import Submission
+from hermes_state_runtime import RuntimeStoreError, get_session_admission
+from tests.gateway.test_profile_retire_stops_turns import ACTOR, REF, _Agent, _authority
+from tests.waiting import async_wait_until
+
+
+async def _observe_queued_then(tmp_path, monkeypatch, release):
+ """One running turn holds the authority busy; a second session's API admission is queued and
+ observed. ``release(authority, admission_id)`` ends the observation; returns (outcome, row)."""
+ from gateway import session_finite
+ agent = _Agent()
+ db, authority, execute, _returned = _authority(tmp_path, agent)
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+ monkeypatch.setattr(run_runtime, 'TURN_SETTLE_SECONDS', 1.0, raising=False)
+ monkeypatch.setattr('gateway.session_cron.unbind_owner', lambda authority: None)
+ try:
+ with db:
+ await authority.submit(ACTOR, Submission(request_id='running', ref=REF, payload={'text': 'a'}, intent='queue'))
+ await asyncio.wait_for(asyncio.to_thread(agent.started.wait, 5), 6)
+ authority.sessions['t'] = type(authority.sessions['s'])(authority.sessions['s'].source, 'route-t')
+ db.create_session('t', source='test')
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ ref = REF.__class__('owned', 't')
+ receipt = await authority.submit(ACTOR, Submission(
+ request_id='queued-api', ref=ref, payload={'text': 'b'}, intent='queue'))
+ observer = asyncio.ensure_future(observe_api_turn(
+ (authority, ref, get_session_admission(db, admission_id=receipt.admission_id))))
+ await async_wait_until(lambda: receipt.admission_id in authority.waiters,
+ timeout=5, what='the API observer registered')
+ await release(authority, receipt.admission_id)
+ outcome = (await asyncio.gather(observer, return_exceptions=True))[0]
+ return outcome, get_session_admission(db, admission_id=receipt.admission_id)
+ finally:
+ agent.release.set()
+ await async_wait_until(lambda: all(task.done() for task in run_runtime._authority_tasks(authority)),
+ timeout=10, what="the authority's tasks finished")
+ db.close()
+
+
+async def test_retirement_tells_a_queued_api_observer_its_input_is_saved(tmp_path, monkeypatch):
+ async def retire(authority, _admission_id):
+ assert await run_runtime._retire_profile_authority(authority) is True
+
+ outcome, row = await _observe_queued_then(tmp_path, monkeypatch, retire)
+ assert isinstance(outcome, AdmissionQueued), outcome
+ assert outcome.reason == 'admission_queued' and 'do not resend' in str(outcome)
+ assert row['status'] == 'queued' # durable: the next owner runs it once
+
+
+async def test_other_observer_failures_keep_their_reason(tmp_path, monkeypatch):
+ async def busy(authority, admission_id):
+ authority.waiters[admission_id].set_exception(RuntimeStoreError('session_busy'))
+
+ outcome, _row = await _observe_queued_then(tmp_path, monkeypatch, busy)
+ assert type(outcome) is RuntimeStoreError and outcome.reason == 'session_busy'
+
+
+def test_admission_queued_is_a_503_the_sdks_do_not_retry():
+ response = store_error_response(_openai_error, AdmissionQueued())
+ assert response.status == 503
+ assert response.headers.get('x-should-retry') == 'false' and 'Retry-After' not in response.headers
+ error = json.loads(response.body)['error']
+ assert error['code'] == 'admission_queued' and error['message'] == AdmissionQueued.MESSAGE
+
+
+def test_a_refused_request_stays_a_retryable_503():
+ response = store_error_response(_openai_error, RuntimeStoreError('runtime_draining'))
+ assert response.status == 503 and response.headers['Retry-After'] == '1'
+ assert 'x-should-retry' not in response.headers