The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): widen scope-aware session DB resolution to the runner and release cached handles
Teknium6f2dbf3a0552
diff --git a/gateway/run.py b/gateway/run.pyindex e3da8dbd1d3..17ef3b64090 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -6525,6 +6525,14 @@ class TurnRunner:+# Sentinel for "no explicit session DB has been pinned on this runner", so the+# ``_session_db`` property can distinguish "resolve from the active profile+# scope" from a deliberate ``runner._session_db = None`` (which disables+# DB-backed commands and is how many suites construct a bare runner). A plain+# ``None`` cannot express both. Mirrors ``gateway.session._DB_UNPINNED``.+_SESSION_DB_UNPINNED = object()++class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, GatewaySlashCommandsMixin):"""Main gateway controller.@@ -6933,11 +6941,20 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewexcept Exception:logger.debug("approvals.mode startup check skipped", exc_info=True)- # Initialize session database for session_search tool support- self._session_db = None+ # Initialize session database for session_search tool support.+ #+ # Same frozen-handle class of bug as SessionStore._db (#88532): a+ # handle bound here is pinned to the process's root home, but+ # /resume, /title, /history and session search all run inside+ # _profile_runtime_scope on a multiplexed gateway and must see that+ # profile's own state.db. Resolve through a property that caches+ # one AsyncSessionDB per resolved path; priming here keeps startup+ # diagnostics (the #88235 broadcast) at construction time.+ self._session_db_pinned: Any = _SESSION_DB_UNPINNED+ self._session_db_handles: Dict[Path, Any] = {}+ self._session_db_handles_lock = threading.Lock()try:- from hermes_state import AsyncSessionDB, SessionDB- self._session_db = AsyncSessionDB(SessionDB())+ self._open_session_db_for_active_scope(raise_on_error=True)except Exception as e:# WARNING (not DEBUG) so the failure appears in errors.log — matches# cli.py's handling of the same init path. Users hitting NFS-mounted@@ -7050,6 +7067,78 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewself._scale_to_zero_cooldown_until: float = 0.0+ def _open_session_db_for_active_scope(self, raise_on_error: bool = False) -> Any:+ """Return the AsyncSessionDB for the profile scope active on this task.++ Same per-path cache as ``SessionStore._open_session_db_for_active_scope``+ (#88532): ``SessionDB()`` resolves ``_default_db_path()`` at call time+ through the context-local HERMES_HOME override installed by+ ``_profile_runtime_scope``, so resolving per access — instead of once+ in ``__init__`` — is what lets /resume, /title, /history and session+ search on a multiplexed gateway read the *serving profile's* store+ rather than the root one.++ One ``AsyncSessionDB`` is cached per resolved path under a lock, so+ the wrapper identity is stable per profile (callers compare and stash+ it) and two profiles never share a handle. A construction failure is+ cached as ``None`` for that path so a broken store degrades once, not+ per command; ``raise_on_error=True`` (construction-time priming)+ propagates the failure instead so ``__init__`` can record+ ``_session_db_init_error`` for the #88235 broadcast.+ """+ from hermes_state import AsyncSessionDB, SessionDB, _default_db_path++ path = Path(_default_db_path())+ with self._session_db_handles_lock:+ if path in self._session_db_handles:+ return self._session_db_handles[path]+ db = None+ try:+ db = AsyncSessionDB(SessionDB())+ except Exception as e:+ if raise_on_error:+ raise+ logger.warning("SQLite session store not available: %s", e)+ self._session_db_handles[path] = db+ return db++ @property+ def _session_db(self) -> Any:+ """The AsyncSessionDB for the active profile scope, or a pinned override.++ Assigning ``runner._session_db`` pins that value for every subsequent+ read — tests rely on installing fakes or ``None`` this way. Unpinned+ (the production path), each read resolves the active scope so a+ multiplexed profile's slash commands and session search hit its own+ store.+ """+ if self._session_db_pinned is not _SESSION_DB_UNPINNED:+ return self._session_db_pinned+ return self._open_session_db_for_active_scope()++ @_session_db.setter+ def _session_db(self, value) -> None:+ self._session_db_pinned = value++ def close_all_session_db_handles(self) -> None:+ """Close every per-profile AsyncSessionDB this runner opened.++ Shutdown counterpart of the per-path cache above; mirrors+ ``SessionStore.close_all_db_handles``. Handles are drained under the+ lock and closed outside it; a pinned handle is the pinner's to close.+ """+ with self._session_db_handles_lock:+ handles = [db for db in self._session_db_handles.values() if db is not None]+ self._session_db_handles.clear()+ for db in handles:+ inner = getattr(db, "_db", db)+ if inner is None or not hasattr(inner, "close"):+ continue+ try:+ inner.close()+ except Exception as exc:+ logger.debug("SessionDB close error during handle sweep: %s", exc)+def _wire_teams_pipeline_runtime(self) -> None:"""Bind the Teams meeting pipeline runtime to Graph webhook ingress.@@ -14681,6 +14770,25 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew_db.close()except Exception as _e:logger.debug("SessionDB close error: %s", _e)+ # A multiplexed session_store caches one SessionDB per profile+ # path (#88532); reading ``_db`` above only resolved the handle+ # for the shutdown task's own (root) scope. Sweep the rest so+ # secondary profiles' WAL locks are released before --replace+ # brings a new gateway up on the same files.+ _sweep = getattr(+ getattr(self, "session_store", None), "close_all_db_handles", None+ )+ if _sweep is not None:+ try:+ _sweep()+ except Exception as _e:+ logger.debug("SessionDB handle sweep error: %s", _e)+ # Same sweep for the runner's own per-profile session_search+ # handles (slash commands resolve them under profile scopes).+ try:+ GatewayRunner.close_all_session_db_handles(self)+ except Exception as _e:+ logger.debug("Runner SessionDB handle sweep error: %s", _e)GatewayRunner._shutdown_executor(self)logger.info("Shutdown phase: SessionDB close done at +%.2fs",diff --git a/gateway/session.py b/gateway/session.pyindex 8b2b10cf087..3ba5b10c48e 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -1378,6 +1378,36 @@ class SessionStore:def _db(self, value) -> None:self._db_pinned = value+ def close_all_db_handles(self) -> None:+ """Close every SessionDB handle this store opened, one per resolved path.++ A multiplexed gateway accumulates one cached handle per profile it+ served (see ``_open_session_db_for_active_scope``). Reading ``_db``+ at shutdown resolves only the handle for the scope active *then* —+ the root home — so a shutdown that closes just ``store._db`` would+ strand every secondary profile's handle with its WAL write lock held+ until the interpreter exits, recreating the abandoned-handle leak+ that ``SessionDB.close()`` exists to prevent. Restart flows+ (``--replace``) would then hit 'database is locked' opening those+ profiles' stores.++ Handles are drained under the lock but closed outside it, so a+ concurrent resolver blocked in ``_open_session_db_for_active_scope``+ is never made to wait on N ``close()`` calls; it simply opens a+ fresh handle afterwards. ``close()`` failures are swallowed the+ same way the shutdown path treats the primary handle. A pinned+ handle (``store._db = fake``) is deliberately not closed here — the+ pinner owns its lifecycle.+ """+ with self._db_handles_lock:+ handles = [db for db in self._db_handles.values() if db is not None]+ self._db_handles.clear()+ for db in handles:+ try:+ db.close()+ except Exception as exc:+ logger.debug("SessionDB close error during handle sweep: %s", exc)+def _has_active_processes_safe(self, session_key: str, *, context: str) -> bool:"""Return whether a session has active work, failing closed on registry errors."""if self._has_active_processes_fn is None:diff --git a/tests/gateway/test_multiplex_session_db_profile_scope.py b/tests/gateway/test_multiplex_session_db_profile_scope.pyindex 84ce3b396c8..9f25ec44fb9 100644--- a/tests/gateway/test_multiplex_session_db_profile_scope.py+++ b/tests/gateway/test_multiplex_session_db_profile_scope.py@@ -170,3 +170,84 @@ def test_explicitly_pinned_handle_still_wins(multiplex_homes):assert store._db is Nonefinally:reset_hermes_home_override(token)+++def test_close_all_db_handles_sweeps_every_profile_handle(multiplex_homes):+ """Teardown must release every cached per-profile handle, not just the+ one the tearing-down task's own scope resolves.++ Follow-up hardening for the per-path cache: ``gateway/run.py``'s+ teardown path closes ``store._db`` (root scope only); the sweep closes+ the rest so secondary profiles' WAL locks are released before a+ ``--replace`` restart reopens their stores.+ """+ root, profile = multiplex_homes+ store = _make_store(root)++ root_db = store._db+ token = set_hermes_home_override(str(profile))+ try:+ profile_db = store._db+ finally:+ reset_hermes_home_override(token)+ assert root_db is not profile_db++ store.close_all_db_handles()++ # Both handles are closed (connection released) and the cache is empty,+ # so the next access opens a fresh handle rather than a dead one.+ assert root_db._conn is None+ assert profile_db._conn is None+ assert store._db_handles == {}+ fresh = store._db+ assert fresh is not root_db+ assert fresh._conn is not None+ fresh.close()+++def test_runner_session_db_follows_the_active_profile_scope(multiplex_homes):+ """GatewayRunner._session_db is the same frozen-handle class of bug.++ /resume, /title, /history and session search run inside+ ``_profile_runtime_scope`` on a multiplexed gateway and must read the+ serving profile's state.db. Exercise the property on a bare runner shell+ (full construction wires adapters and is irrelevant to the seam under+ test).+ """+ import threading++ from gateway.run import GatewayRunner, _SESSION_DB_UNPINNED++ root, profile = multiplex_homes+ runner = object.__new__(GatewayRunner)+ runner._session_db_pinned = _SESSION_DB_UNPINNED+ runner._session_db_handles = {}+ runner._session_db_handles_lock = threading.Lock()++ root_db = runner._session_db+ assert Path(root_db._db.db_path) == root / "state.db"++ token = set_hermes_home_override(str(profile))+ try:+ profile_db = runner._session_db+ assert Path(profile_db._db.db_path) == profile / "state.db"+ # Cached per path: same wrapper identity on re-access.+ assert runner._session_db is profile_db+ finally:+ reset_hermes_home_override(token)++ assert runner._session_db is root_db++ # Pinning (how suites install fakes / disable the DB) wins across scopes.+ runner._session_db = None+ token = set_hermes_home_override(str(profile))+ try:+ assert runner._session_db is None+ finally:+ reset_hermes_home_override(token)+ runner._session_db_pinned = _SESSION_DB_UNPINNED++ runner.close_all_session_db_handles()+ assert runner._session_db_handles == {}+ assert root_db._db._conn is None+ assert profile_db._db._conn is None