The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api-server): every SessionDB call in the session handlers leaves the event loop
teknium1f639e1717090
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex cd97e677c03..05c7a32a3d2 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -2811,13 +2811,14 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):# which would fail `hermes peer dm` resolution and mint transient sessions — same accident# the tui_gateway lookups heal.from tools.bot_mode_probe import BOT_CHAT_TITLE- stale = (- await asyncio.to_thread(db.get_session_by_title, title_filter)- if title_filter == BOT_CHAT_TITLE else None- )- if stale and stale.get("archived") and await asyncio.to_thread(- db.unarchive_recoverable_session, stale["id"]- ):++ def _resurrect() -> bool:+ # Lookup + unarchive (a WRITE with the full write patience) as one worker-thread+ # hop: a contended lock parks this thread, never the event loop (#113772).+ stale = db.get_session_by_title(title_filter)+ return bool(stale and stale.get("archived") and db.unarchive_recoverable_session(stale["id"]))++ if title_filter == BOT_CHAT_TITLE and await asyncio.to_thread(_resurrect):sessions = await _list()except Exception:pass # resolution degrades to today's no-row behavior@@ -3060,7 +3061,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):lock_error = self._runtime_lock_error(runtime_request)if lock_error is not None:return None, lock_error- if not self._persist_session_runtime_lock(session_id, runtime_request):+ if not await asyncio.to_thread(self._persist_session_runtime_lock, session_id, runtime_request):return None, _error_response("Could not persist the requested session model lock", 500, code="model_lock_persistence_failed")lock_active = bool(runtime_request.get("require_model_lock"))@@ -3312,7 +3313,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):lock_error = self._runtime_lock_error(runtime_request)if lock_error is not None:return lock_error- if not self._persist_session_runtime_lock(session_id, runtime_request):+ if not await asyncio.to_thread(self._persist_session_runtime_lock, session_id, runtime_request):return _error_response("Could not persist the requested session model lock", 500, code="model_lock_persistence_failed")requested = runtime_request.get("requested") or {}diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex 96adfa5753b..96f4183d0f6 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -860,7 +860,7 @@ class OpenAICompatRoutesMixin:_declared_selected = not stored_session_id and bool(gateway_session_key)session_id = (stored_session_id- or self._declared_conversation_session(gateway_session_key)+ or await asyncio.to_thread(self._declared_conversation_session, gateway_session_key)or str(uuid.uuid4()))stream = _coerce_request_bool(body.get("stream"), default=False)route, agent_overrides, selection_error = self._select_request_route(diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 53025b7450d..0c9396ca491 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -505,7 +505,8 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Res# An explicit or chained session owns its routing key and is never rebound to the header._declared_selected = not session_id and bool(gateway_session_key)selected_session_id = session_id or (- self._declared_conversation_session(gateway_session_key) if _declared_selected else None)+ await asyncio.to_thread(self._declared_conversation_session, gateway_session_key)+ if _declared_selected else None)# A client-addressed id from before a compression rotation must adopt the live tip (#98619):# history loads from it, the turn writes to it, and a detached delivery row persisted to it# is what the next same-id run consumes below.diff --git a/tests/gateway/test_session_api.py b/tests/gateway/test_session_api.pyindex 8bfe23482a2..1973d947e0b 100644--- a/tests/gateway/test_session_api.py+++ b/tests/gateway/test_session_api.py@@ -172,6 +172,32 @@ async def test_list_sessions_resurrects_bot_chat_off_the_event_loop(adapter, sesassert not session_db.get_session(session_id)["archived"]+async def test_session_model_lock_persists_off_the_event_loop(adapter, session_db, monkeypatch):+ """POST /api/sessions/{id}/model writes the lock row through a worker thread: the same+ contended-write class as the Bot Chat resurrection, on a sibling handler."""+ session_id = session_db.create_session("lock-off-loop", "api_server", model="gpt-5.5")+ loop_thread = threading.get_ident()+ seen = []+ real = session_db.update_session_runtime_lock++ def record(*args, **kwargs):+ seen.append(threading.get_ident())+ return real(*args, **kwargs)++ monkeypatch.setattr(session_db, "update_session_runtime_lock", record)+ app = _create_session_app(adapter)+ _register_session_model_route(app, adapter)+ with patch.object(adapter, "_resolve_route", return_value=None):+ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(+ f"/api/sessions/{session_id}/model",+ json={"provider": "nous", "model": "x-ai/grok-4.5", "require_model_lock": True})+ assert resp.status == 200, await resp.text()+ assert seen and all(tid != loop_thread for tid in seen)+ assert session_db.get_session(session_id)["model"] == "x-ai/grok-4.5"++@pytest.mark.asyncioasync def test_run_agent_binds_api_session_context_for_tool_env(adapter, monkeypatch):"""API-server request sessions should reach tools and terminal subprocess env."""