Skip to content

The agent that grows with you

fix: bind API storage to its selected runtime authority

Tekniumc812ec711b96
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 8bd6ed54782..1cbe0f215dc 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -1624,6 +1624,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
def _open_and_cache_session_db(self, home) -> Optional[Any]:
"""Cached SessionDB for ``home`` (shared by both ``_ensure_session_db*``). Never writes
``self._session_db`` (explicit override only), so no profile pins later requests."""
+ if self.gateway_runner is not None:
+ from gateway.platforms.api_server_store import selected_session_db
+ return selected_session_db(self, home)
from hermes_state_registry import acquire
key = str(home)
with self._session_db_cache_lock:
@@ -1654,6 +1657,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
def _ensure_session_db(self):
"""SessionDB for the active profile home (the runtime scope redirects ``get_hermes_home()``
per profile). Sync, for ``_create_agent``; handlers use ``_ensure_session_db_async``."""
+ if self.gateway_runner is not None:
+ from hermes_constants import get_hermes_home
+ from gateway.platforms.api_server_store import selected_session_db
+ return selected_session_db(self, get_hermes_home())
if self._session_db is not None:
return self._session_db
try:
@@ -1666,6 +1673,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
async def _ensure_session_db_async(self):
"""Async variant: the profile home is captured on the loop thread (its scope is invisible
inside ``to_thread``), only the blocking open runs in the worker, single-flight locked."""
+ if self.gateway_runner is not None:
+ from hermes_constants import get_hermes_home
+ from gateway.platforms.api_server_store import selected_session_db
+ return selected_session_db(self, get_hermes_home())
if self._session_db is not None:
return self._session_db
try:
diff --git a/gateway/platforms/api_server_store.py b/gateway/platforms/api_server_store.py
new file mode 100644
index 00000000000..77e78b4cdad
--- /dev/null
+++ b/gateway/platforms/api_server_store.py
@@ -0,0 +1,15 @@
+"""Runtime-bound API storage selection; borrowed stores are never adapter-owned."""
+from pathlib import Path
+
+
+def selected_session_db(adapter, home):
+ authority = getattr(adapter.gateway_runner, 'session_authority', None)
+ if authority is None:
+ return None
+ if Path(authority.db.db_path).parent.resolve() != Path(home).resolve():
+ # A multiplex route is not evidence that this runtime owns that profile.
+ return None
+ with adapter._session_db_cache_lock:
+ if adapter._session_db_cache_closed:
+ return None
+ return authority.db
diff --git a/tests/gateway/test_api_authority_store.py b/tests/gateway/test_api_authority_store.py
new file mode 100644
index 00000000000..4a664ff9619
--- /dev/null
+++ b/tests/gateway/test_api_authority_store.py
@@ -0,0 +1,64 @@
+"""API storage selection borrows the runtime's store, never another profile's."""
+from types import SimpleNamespace
+
+import pytest
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer
+
+from gateway.config import PlatformConfig
+from gateway.platforms.api_server import APIServerAdapter
+from gateway.session_authority import SessionAuthority
+from hermes_state import SessionDB
+from hermes_state_runtime import begin_runtime_epoch
+
+
+def owned_api(tmp_path, monkeypatch):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ db = SessionDB(tmp_path / 'state.db')
+ runner = SimpleNamespace(_draining=False)
+ runner.session_authority = SessionAuthority(
+ runner, profile_id='default', instance_id='api-test', db=db,
+ epoch=begin_runtime_epoch(db, instance_id='api-test'))
+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={'key': 'owned-api-test-secret'}))
+ adapter.gateway_runner = runner
+ yield adapter, db
+ adapter._close_cached_session_dbs()
+ adapter._response_store.close()
+ adapter._run_idempotency_store.close()
+ db.close()
+
+
+async def test_bound_api_borrows_selected_authority_store(owned_api):
+ adapter, db = owned_api
+ db.create_session('owned-session', source='api_server')
+ assert adapter._ensure_session_db() is db
+ assert await adapter._ensure_session_db_async() is db
+ app = web.Application()
+ app.router.add_get('/api/sessions/{session_id}', adapter._handle_get_session)
+ async with TestClient(TestServer(app)) as client:
+ denied = await client.get('/api/sessions/owned-session')
+ assert denied.status == 401
+ reply = await client.get('/api/sessions/owned-session',
+ headers={'Authorization': 'Bearer owned-api-test-secret'})
+ assert reply.status == 200, await reply.text()
+ assert (await reply.json())['session']['id'] == 'owned-session'
+ adapter._close_cached_session_dbs()
+ assert db.get_session('owned-session')['id'] == 'owned-session'
+
+
+async def test_bound_api_never_opens_unserved_home(owned_api, tmp_path, monkeypatch):
+ adapter, db = owned_api
+ other = tmp_path / 'unserved'
+ monkeypatch.setenv('HERMES_HOME', str(other))
+ # Even an explicit legacy override cannot bypass runtime profile selection.
+ adapter._session_db = db
+ assert adapter._ensure_session_db() is None
+ assert await adapter._ensure_session_db_async() is None
+ assert not (other / 'state.db').exists()
+ adapter.gateway_runner.session_authority = None
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ assert adapter._ensure_session_db() is None
+ assert await adapter._ensure_session_db_async() is None