Skip to content

The agent that grows with you

fix(api): API admission writes run off the owner loop in admission order

Teknium47b24028dd8b
diff --git a/gateway/platforms/api_server_response_admissions.py b/gateway/platforms/api_server_response_admissions.py
index 67b7ebd2571..b08789e9bad 100644
--- a/gateway/platforms/api_server_response_admissions.py
+++ b/gateway/platforms/api_server_response_admissions.py
@@ -82,27 +82,35 @@ def admitted_context(admitted, *, replay=False):
terminal_replay=replay or row['status'] == 'terminal')
-def _admit(adapter, durable_key, request_id, binding, run_kwargs, model):
- """No await between the final lookup and admission: simultaneous observers converge."""
- from gateway.session_api_turn import admit_api_turn
+def _admit_steps(adapter, durable_key, request_id, binding, run_kwargs, model):
+ """The final lookup and the admission are one API admission drive (``run_steps_off_loop``
+ serializes them per authority): simultaneous observers converge on one admission."""
+ from gateway.session_api_turn import admit_api_steps
store = adapter._current_response_store()
if not store.bind_request_key(durable_key[0], binding, model=model):
raise RuntimeStoreError('admission_conflict')
admitted = find_admission(adapter, durable_key, request_id)
- replay = admitted is not None
- if admitted is None:
- try:
- admitted = admit_api_turn(adapter, request_id=request_id,
- **{'route_source': 'global', 'confirmed_runtime_lock': False,
- 'session_history_delivery': '', **run_kwargs})
- except Exception:
- # A definite pre-admission refusal does not reserve a poisoned identity. If storage
- # cannot prove absence, leave the binding intact for later recovery.
- if find_admission(adapter, durable_key, request_id) is None:
- store.forget_unadmitted_request(durable_key[0])
- raise
- store.bind_request_admission(durable_key[0], admitted[2]['admission_id'])
- return admitted_context(admitted, replay=replay)
+ if admitted is not None:
+ return (*admitted, True)
+ try:
+ admitted = yield from admit_api_steps(adapter, request_id=request_id,
+ **{'route_source': 'global', 'confirmed_runtime_lock': False,
+ 'session_history_delivery': '', **run_kwargs})
+ except Exception:
+ # A definite pre-admission refusal does not reserve a poisoned identity. If storage
+ # cannot prove absence, leave the binding intact for later recovery.
+ if find_admission(adapter, durable_key, request_id) is None:
+ store.forget_unadmitted_request(durable_key[0])
+ raise
+ store.bind_request_admission(durable_key[0], admitted[2]['admission_id'])
+ return (*admitted, False)
+
+
+async def _admit(adapter, durable_key, request_id, binding, run_kwargs, model):
+ from gateway.session_api_turn import admit_api_turn_async
+ *admitted, replay = await admit_api_turn_async(
+ adapter, _admit_steps(adapter, durable_key, request_id, binding, run_kwargs, model))
+ return admitted_context(tuple(admitted), replay=replay)
def _stored_owner(adapter, session_id):
@@ -168,7 +176,7 @@ async def prepare_context(adapter, request, body, gateway_session_key, durable_k
gateway_session_key=gateway_session_key, bind_declared_conversation=declared_selected,
**overrides, route=route, relay_metadata=_request_relay_metadata(body))
if durable_key:
- return _admit(adapter, durable_key, request_id, request_binding(adapter, request, durable_key),
- run_kwargs, body.get('model', adapter._model_name)), None
+ return await _admit(adapter, durable_key, request_id, request_binding(adapter, request, durable_key),
+ run_kwargs, body.get('model', adapter._model_name)), None
return dict(session_id=session_id, user_message=user_message, conversation_history=history,
instructions=instructions, run_kwargs=run_kwargs, run_agent=adapter._run_agent), None
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index ace07b29ee5..264c1560f5e 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -660,16 +660,16 @@ def _run_user_message(raw_input, _openai_error) -> tuple:
return user_message, None
-def _admit_run_to_authority(
+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."""
- from gateway.session_api_turn import admit_api_turn
+ from gateway.session_api_turn import admit_api_turn_async
from hermes_state_runtime import RuntimeStoreError
try:
with self._profile_scope(launch.request_profile):
- launch.admission = admit_api_turn(self, user_message=launch.user_message,
+ launch.admission = await admit_api_turn_async(self, user_message=launch.user_message,
conversation_history=launch.conversation_history, active_run_id=run_id,
run_owner_scope=self._run_owners[run_id],
turn_author=launch.turn_author,
@@ -808,7 +808,7 @@ async def _handle_runs(self, request: web.Request, *, _api_server) -> web.Respon
# why it is decided BEFORE ``admit_api_turn`` would bind the chat as an API conversation.
admitted = await self._admit_to_live_bot_chat(session_id, user_message, turn_author) if selected_session_id else None
if admitted is None and getattr(self.gateway_runner, 'session_authority', None) is not None:
- refused = _admit_run_to_authority(
+ refused = await _admit_run_to_authority(
self, launch, run_id, session_history_delivery, _declared_selected,
idempotency_scope, idempotency_key, _openai_error)
if refused is not None:
diff --git a/gateway/session_api.py b/gateway/session_api.py
index 7efaf400692..307692bde51 100644
--- a/gateway/session_api.py
+++ b/gateway/session_api.py
@@ -1,6 +1,8 @@
"""Server-only binding of API transcript identities to the existing TurnRunner."""
-import json
+import asyncio
+from functools import partial
import hashlib
+import json
from gateway.config import Platform
from gateway.session import SessionEntry, SessionSource, _is_path_unsafe
@@ -35,8 +37,63 @@ def _pin_api_identity(runner, source, *, transport_profile=None):
return identity.transport_profile if identity is not None else None
+def run_steps(steps):
+ """Drive a write-step generator (see ``run_steps_off_loop``) inline: tests and sync callers."""
+ result = error = None
+ while True:
+ try:
+ write = steps.throw(error) if error is not None else steps.send(result)
+ except StopIteration as done:
+ return done.value
+ try:
+ result, error = write(), None
+ except Exception as exc: # thrown back into the steps, which decide
+ result, error = None, exc
+
+
+async def run_steps_off_loop(authority, steps, *, orphaned=None):
+ """Drive a write-step generator on the owner loop, each yielded SQLite write in a worker thread
+ in admission order (``tracked_write(ordered=True)``): a held writer must not freeze every session.
+ The whole drive is one tracked, shielded task, so a cancelled caller cannot separate a commit
+ from the steps after it; ``orphaned(result)`` then runs when the drive completes."""
+ from gateway.session_runtime_workers import track_mutation, tracked_write
+
+ async def drive():
+ result = error = None
+ while True:
+ try:
+ write = steps.throw(error) if error is not None else steps.send(result)
+ except StopIteration as done:
+ return done.value
+ try:
+ result, error = await tracked_write(authority, write, ordered=True), None
+ except Exception as exc: # thrown back into the steps, which decide
+ result, error = None, exc
+ async def serialized():
+ # One API admission drive at a time per authority: its lookups, binding and admission stay
+ # one step relative to every other API door, as they were when admission ran on the loop.
+ lock = getattr(authority, '_api_admissions', None)
+ if lock is None:
+ lock = authority._api_admissions = asyncio.Lock()
+ async with lock:
+ return await drive()
+ task = track_mutation(authority, serialized())
+ try:
+ return await asyncio.shield(task)
+ except asyncio.CancelledError:
+ if orphaned is not None:
+ task.add_done_callback(lambda done: done.cancelled() or done.exception() or orphaned(done.result()))
+ raise
+
+
def bind_api_session(authority, session_id, *, hosted_dispatch=None, declared_key=None):
"""Only the authenticated API edge may reserve an API source; never public RPC."""
+ return run_steps(bind_api_steps(authority, session_id, hosted_dispatch=hosted_dispatch,
+ declared_key=declared_key))
+
+
+def bind_api_steps(authority, session_id, *, hosted_dispatch=None, declared_key=None):
+ """``bind_api_session`` as write steps (``run_steps``): the binding transaction is yielded."""
authority._require_admission_open()
if not isinstance(session_id, str) or not session_id or _is_path_unsafe(session_id):
raise RuntimeStoreError('invalid_params')
@@ -75,6 +132,7 @@ def bind_api_session(authority, session_id, *, hosted_dispatch=None, declared_ke
def write(conn):
_epoch(conn, authority.epoch)
+ authority._require_admission_open() # a drain that began while this waited on the writer wins
from hermes_state_mutation_retirement import RETIRED_PREFIX
if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (RETIRED_PREFIX + session_id,)).fetchone():
raise RuntimeStoreError('not_found')
@@ -118,7 +176,7 @@ def bind_api_session(authority, session_id, *, hosted_dispatch=None, declared_ke
(route, _json(entry.to_dict()), now.timestamp()))
conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
(_BINDING_PREFIX + session_id, _json(receipt)))
- authority.db._execute_write(write)
+ yield partial(authority.db._execute_write, write)
return restore_api_session(authority, session_id)
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index dbb2e6d2d0e..7bfbff3e080 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -9,7 +9,7 @@ import re
import uuid
from gateway.config import Platform
-from gateway.session_api import bind_api_session, restore_api_session
+from gateway.session_api import bind_api_steps, restore_api_session, run_steps, run_steps_off_loop
from gateway.session_results import admission_result
from hermes_state_runtime import RuntimeStoreError, admit_session_input, _epoch, _json
@@ -138,6 +138,28 @@ def api_policy_scope():
def admit_api_turn(adapter, **kwargs):
+ """Admit inline (sync callers and tests); the HTTP doors use ``admit_api_turn_async``."""
+ return run_steps(admit_api_steps(adapter, **kwargs))
+
+
+async def admit_api_turn_async(adapter, steps=None, **kwargs):
+ """``admit_api_turn`` (or *steps*, a generator ending in ``admit_api_steps``) with every SQLite
+ write off the owner loop, in admission order."""
+ from gateway.session_authorities import active_authority
+ authority = active_authority(adapter.gateway_runner)
+ if authority is None:
+ raise RuntimeStoreError('profile_mismatch')
+ return await run_steps_off_loop(authority, steps or admit_api_steps(adapter, **kwargs), orphaned=schedule_orphan)
+
+
+def schedule_orphan(admitted):
+ """A caller cancelled while its admission committed never observes it: its drain runs anyway."""
+ authority, ref, row = admitted[:3]
+ if row['status'] == 'queued':
+ authority._schedule(ref)
+
+
+def admit_api_steps(adapter, **kwargs):
# ``/p/<profile>/`` middleware scoped this request; the routed home's authority admits it.
from gateway.session_authorities import active_authority
authority = active_authority(adapter.gateway_runner)
@@ -188,17 +210,21 @@ def admit_api_turn(adapter, **kwargs):
payload['api_turn_v1']['turn_author'] = author
request_id = kwargs.get('request_id') or kwargs.get('active_run_id') or uuid.uuid4().hex
if not isinstance(kwargs['user_message'], list):
- return _admit_api_payload(authority, adapter, sid, request_id, payload, settings, declared_key, kwargs)
+ return (yield from _admit_api_payload(authority, adapter, sid, request_id, payload, settings, declared_key, kwargs))
from gateway.session_api_media import commit_api_images
from gateway.session_ingress_media import release_unheld_media
payload['api_turn_v1']['media'] = commit_api_images(kwargs['user_message'])
+ # Retained bytes belong to an accepted admission. A refused request (or an exact retry of a
+ # retired one, whose references were erased) owns nothing, so its bytes are collected unless
+ # another admission holds them.
+ release = partial(release_unheld_media, authority.db, payload['api_turn_v1']['media'])
try:
- return _admit_api_payload(authority, adapter, sid, request_id, payload, settings, declared_key, kwargs)
- finally:
- # Retained bytes belong to an accepted admission. A refused request (or an exact retry of
- # a retired one, whose references were erased) owns nothing, so its bytes are collected
- # unless another admission holds them. Capture, admission and release share this loop.
- release_unheld_media(authority.db, payload['api_turn_v1']['media'])
+ admitted = yield from _admit_api_payload(authority, adapter, sid, request_id, payload, settings, declared_key, kwargs)
+ except Exception:
+ yield release
+ raise
+ yield release
+ return admitted
def _admit_api_payload(authority, adapter, sid, request_id, payload, settings, declared_key, kwargs):
@@ -209,11 +235,11 @@ def _admit_api_payload(authority, adapter, sid, request_id, payload, settings, d
check_api_settings(adapter, settings)
from gateway.session_contract import SessionRef
return authority, SessionRef(authority.profile_id, sid), row
- ref = bind_api_session(authority, sid, hosted_dispatch=kwargs.get("room_dispatch"), declared_key=declared_key)
+ ref = yield from bind_api_steps(authority, sid, hosted_dispatch=kwargs.get("room_dispatch"), declared_key=declared_key)
check_api_turn(authority, ref, payload)
- row = admit_session_input(authority.db, epoch=authority.epoch, principal_id='api',
- session_id=sid, request_id=request_id, payload=payload,
- _authorize_write=partial(_one_target, sid, request_id))
+ row = yield partial(admit_session_input, authority.db, epoch=authority.epoch, principal_id='api',
+ session_id=sid, request_id=request_id, payload=payload,
+ _authorize_write=authority._admission_gate(partial(_one_target, sid, request_id)))
return authority, ref, row
@@ -279,7 +305,7 @@ def _recover_api_turns(adapter, authority):
async def run_api_turn(adapter, *, approval_notify_callback=None, approval_session_key=None, **kwargs):
- admitted = admit_api_turn(adapter, **kwargs)
+ admitted = await admit_api_turn_async(adapter, **kwargs)
if approval_notify_callback is None or not approval_session_key:
return await observe_api_turn(admitted, **kwargs)
# A streaming surface advertises its own run id (``chatcmpl-*`` / ``run_*``): bind it to this
diff --git a/tests/gateway/test_api_admission_off_loop.py b/tests/gateway/test_api_admission_off_loop.py
new file mode 100644
index 00000000000..7883bc7aa9e
--- /dev/null
+++ b/tests/gateway/test_api_admission_off_loop.py
@@ -0,0 +1,57 @@
+"""API admission never blocks the shared owner loop on a held SQLite writer (every HTTP door)."""
+import asyncio
+import sqlite3
+import threading
+import time
+
+import pytest
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer
+
+KEY = 'off-loop-admission-key-long-enough'
+HOLD_S = 1.5
+AUTH = {'Authorization': 'Bearer ' + KEY}
+
+DOORS = [
+ ('chat', '/v1/chat/completions', {'messages': [{'role': 'user', 'content': 'hi'}]}, {}, 200),
+ ('responses', '/v1/responses', {'input': 'hi'}, {'Idempotency-Key': 'resp-1'}, 200),
+ ('runs', '/v1/runs', {'input': 'hi'}, {}, 202),
+]
+
+
[email protected]('name,path,body,headers,expected', DOORS, ids=[d[0] for d in DOORS])
+async def test_admission_waits_for_the_writer_off_the_owner_loop(api, owner, monkeypatch, name, path, body,
+ headers, expected):
+ from gateway.platforms import api_server_runs
+
+ async def handle(event):
+ from gateway.session_results import execution_result
+ execution_result.get()['result'] = {'final_response': 'ok', 'messages': []}
+ return 'ok'
+
+ async def no_execution(*args, **kwargs):
+ pass
+ owner.runner._handle_message = handle
+ monkeypatch.setattr(api_server_runs, '_execute_run', no_execution)
+ api._api_key = KEY
+ app = web.Application()
+ app.router.add_post(path, getattr(api, {'chat': '_handle_chat_completions', 'responses': '_handle_responses',
+ 'runs': '_handle_runs'}[name]))
+ async with TestClient(TestServer(app)) as client:
+ # Another process holds the profile's state.db writer for HOLD_S (a long transaction).
+ holder = sqlite3.connect(owner.db.db_path, timeout=0, isolation_level=None, check_same_thread=False)
+ holder.execute('BEGIN IMMEDIATE')
+ threading.Timer(HOLD_S, lambda: holder.execute('COMMIT')).start()
+ request = asyncio.create_task(client.post(path, json=body, headers={**AUTH, **headers}))
+ gaps, last = [], time.monotonic()
+ while not request.done():
+ await asyncio.sleep(0.02)
+ now = time.monotonic()
+ gaps.append(now - last)
+ last = now
+ response = await request
+ holder.close()
+ assert response.status == expected, await response.text()
+ # Other sessions, timers and sockets kept running while the admission waited on the writer.
+ assert max(gaps) < HOLD_S / 3, f'owner loop stalled {max(gaps):.2f}s behind the admission write'