Skip to content

The agent that grows with you

fix(state): bound state.db read connections per FILE, and stop opening two gateway handles

joaomarcose8c41568ca84
diff --git a/gateway/run.py b/gateway/run.py
index ab4a56f7558..56086ec6ce0 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -7861,6 +7861,32 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
self._session_db_handle_cache = cache
def _open():
+ # Borrow the SessionStore's handle for this path rather than
+ # opening a second one. Both caches resolve the SAME
+ # ``_default_db_path()``, so the process was holding two writer
+ # connections and two read pools against one state.db — the fd
+ # budget doubled for nothing, and doubled again per profile on a
+ # multiplexed gateway (#98573). The store owns the handle and
+ # sweeps it at shutdown; this cache holds only the async wrapper.
+ #
+ # A borrowed wrapper cannot go stale in practice: the store's
+ # cache only drops handles in close_all_db_handles() (shutdown),
+ # and while the store's own open is failing there is nothing to
+ # borrow, so nothing is cached here either.
+ store = getattr(self, "session_store", None)
+ borrowed = getattr(store, "_db", None) if store is not None else None
+ if borrowed is not None:
+ wrapper = AsyncSessionDB(borrowed)
+ # close_all_session_db_handles() must not close what the store
+ # owns; the store's own sweep already does, and it runs first.
+ wrapper.__dict__["_hermes_borrowed_handle"] = True
+ return wrapper
+ if store is not None:
+ # The store exists and its handle is unavailable (failed open
+ # or backoff). Opening our own here would resurrect exactly
+ # the duplicate this borrows away from, so report the same
+ # unavailability the store is already reporting.
+ raise RuntimeError("SessionStore SQLite handle unavailable")
try:
return AsyncSessionDB(SessionDB())
except Exception as exc:
@@ -7902,8 +7928,14 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
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.
+
+ Wrappers around a handle BORROWED from ``session_store`` (#98573) are
+ drained but not closed: the store owns that connection and its own
+ sweep — which runs first in the shutdown sequence — closes it.
"""
def _close(db) -> None:
+ if getattr(db, "__dict__", {}).get("_hermes_borrowed_handle"):
+ return
inner = getattr(db, "_db", db)
if inner is None or not hasattr(inner, "close"):
return
diff --git a/hermes_state.py b/hermes_state.py
index 2b65c6533c5..143dd99add9 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -367,8 +367,9 @@ DEFAULT_DB_PATH = get_hermes_home() / "state.db"
# query; short enough that transient fd pressure doesn't strand the read pool.
_READ_OPEN_RETRY_SECONDS = 60.0
-# Hard ceiling on read-only connections ALIVE at once per SessionDB — pooled
-# idle ones and checked-out ones together.
+# Hard ceiling on read-only connections ALIVE at once against one database
+# FILE — pooled idle ones and checked-out ones together, summed over every
+# SessionDB in this process that points at that file. See _PathReadBudget.
#
# Deliberately one constant for both the pool's maxsize and the permit count,
# because bounding only the pool bounds the wrong thing. A LifoQueue caps how
@@ -385,6 +386,90 @@ _READ_OPEN_RETRY_SECONDS = 60.0
# the correct trade against a process-wide wedge the supervisor cannot see.
_READ_POOL_MAX = 8
+
+class _PathReadBudget:
+ """The read-connection permits for ONE database file, shared process-wide.
+
+ ``_READ_POOL_MAX`` used to be enforced by a ``BoundedSemaphore`` owned by
+ each SessionDB, which bounded the wrong noun: the descriptors are spent on
+ a *file*, so N SessionDB objects on one state.db each got their own
+ allowance and peak scaled as ``N x (1 + _READ_POOL_MAX)``. A long-lived
+ gateway holds at least two (``SessionStore`` and ``GatewayRunner`` open
+ independent handles per profile path) and the count grows with the profile
+ count, which is how a healthy process walked into EMFILE — #98573.
+
+ Holding the permits here instead makes the ceiling mean what its docstring
+ always claimed: read connections ALIVE at once against this path.
+
+ One consequence has to be handled rather than documented away. A pooled
+ idle connection keeps its permit, so the first instance to warm up would
+ otherwise pin all eight and every later instance — a cron job's transient
+ handle, a second profile's store — would be permanently demoted to the
+ locked writer connection. That is why a permit miss first reclaims an
+ IDLE connection from a peer instance on the same path: idle descriptors
+ are transferable, in-use ones are not.
+ """
+
+ def __init__(self) -> None:
+ self.permits = threading.BoundedSemaphore(_READ_POOL_MAX)
+ self._lock = threading.Lock()
+ # Weak so a SessionDB that is dropped without close() cannot pin its
+ # peers' budget object; __del__ still runs close() and returns the
+ # permits.
+ self._members: "weakref.WeakSet[SessionDB]" = weakref.WeakSet()
+
+ def register(self, db: "SessionDB") -> None:
+ with self._lock:
+ self._members.add(db)
+
+ def acquire(self, requester: "SessionDB") -> bool:
+ """Take a permit, reclaiming an idle peer connection if need be."""
+ if self.permits.acquire(blocking=False):
+ return True
+ if not self._reclaim_idle(requester):
+ return False
+ # Another thread may take the freed permit first; that is a legitimate
+ # loss, and the caller degrades to the writer lock rather than looping.
+ return self.permits.acquire(blocking=False)
+
+ def _reclaim_idle(self, requester: "SessionDB") -> bool:
+ """Close one idle pooled connection held by a peer. True if one went."""
+ with self._lock:
+ peers = [db for db in self._members if db is not requester]
+ for peer in peers:
+ if peer._evict_one_idle_read_conn():
+ return True
+ return False
+
+
+# canonical db path -> the permits for that file. Weak values: the budget
+# lives exactly as long as some SessionDB on that path holds a strong
+# reference to it, so a test that churns tmp_path databases does not grow
+# this map for the life of the process.
+_read_budgets: "weakref.WeakValueDictionary[str, _PathReadBudget]" = (
+ weakref.WeakValueDictionary()
+)
+_read_budgets_lock = threading.Lock()
+
+
+def _read_budget_key(db_path) -> str:
+ """Canonicalise a db path so two spellings share one budget."""
+ try:
+ return str(Path(db_path).resolve())
+ except OSError:
+ return str(db_path)
+
+
+def _read_budget_for(db_path) -> _PathReadBudget:
+ key = _read_budget_key(db_path)
+ with _read_budgets_lock:
+ budget = _read_budgets.get(key)
+ if budget is None:
+ budget = _PathReadBudget()
+ _read_budgets[key] = budget
+ return budget
+
+
# Import-time snapshot used by _default_db_path() to detect a deliberately
# re-pointed DEFAULT_DB_PATH (tests monkeypatch the constant directly).
_IMPORT_DEFAULT_DB_PATH = DEFAULT_DB_PATH
@@ -4567,7 +4652,16 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# reader that cannot get a permit must degrade to the writer lock, not
# queue here — blocking would convert fd exhaustion into a stall, which
# is the same outage with a different stack trace.
- self._read_permits = threading.BoundedSemaphore(_READ_POOL_MAX)
+ #
+ # Permits are shared per DATABASE PATH, not per instance: the
+ # descriptors they ration belong to the file, and one process holds
+ # several SessionDB objects on the same state.db (#98573). See
+ # _PathReadBudget.
+ self._read_budget = _read_budget_for(self.db_path)
+ self._read_budget.register(self)
+ # Bound to the semaphore itself so every release site
+ # (_close_read_conn and the _get_read_conn failure paths) is unchanged.
+ self._read_permits = self._read_budget.permits
# Count of reads that found no permit and fell back to the locked
# writer connection. Not load-bearing; it is the only externally
# visible signal that the ceiling is actually being reached, so a
@@ -4885,7 +4979,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# Take the descriptor permit BEFORE the open, so concurrent openers
# race for permits rather than for file descriptors. Non-blocking:
# losing the race means "use the writer connection", not "wait".
- if not self._read_permits.acquire(blocking=False):
+ if not self._read_budget.acquire(self):
with self._read_conns_lock:
self._read_permit_exhausted += 1
logger.debug(
@@ -4948,6 +5042,23 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
raise
return conn
+ def _evict_one_idle_read_conn(self) -> bool:
+ """Close one connection sitting idle in this instance's pool.
+
+ Called by _PathReadBudget when a peer SessionDB on the same file wants
+ a permit this instance is holding but not using. Only the idle set is
+ reachable from here — a checked-out connection is not in the queue —
+ so this can never pull a connection out from under a live reader.
+
+ Returns whether a connection (and therefore a permit) was released.
+ """
+ try:
+ conn = self._read_pool.get_nowait()
+ except queue.Empty:
+ return False
+ self._close_read_conn(conn)
+ return True
+
def _discard_partial_read_conn(self, conn) -> None:
"""Close a connection that failed between open and hand-off.
diff --git a/tests/gateway/test_session_db_handle_sharing.py b/tests/gateway/test_session_db_handle_sharing.py
new file mode 100644
index 00000000000..d874c882cf0
--- /dev/null
+++ b/tests/gateway/test_session_db_handle_sharing.py
@@ -0,0 +1,158 @@
+"""One gateway process must not hold two SessionDB handles on one state.db.
+
+Regression coverage for #98573. ``SessionStore`` and ``GatewayRunner`` each
+cached a handle per resolved path, and both resolve the SAME
+``_default_db_path()``. The process therefore held two writer connections and
+two independent read pools against one file, so the descriptor budget doubled
+for nothing -- and doubled again per profile on a multiplexed gateway, until a
+long-lived process passed the 256 soft ``RLIMIT_NOFILE`` a service manager
+hands it and unrelated code paths started failing with EMFILE while the
+process stayed alive.
+
+The runner now borrows the store's handle and caches only the async wrapper.
+Ownership follows: the store closes the connection, the runner does not.
+"""
+
+import threading
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from gateway.config import GatewayConfig
+from gateway.run import GatewayRunner, _SESSION_DB_UNPINNED
+from gateway.session import SessionStore
+from gateway.session_db_recovery import RecoverableHandleCache
+
+
+def _live_count(path) -> int:
+ """Live-connection count the tracking registry holds for *path*."""
+ import hermes_cli.sqlite_safe_read as mod
+
+ with mod._live_lock:
+ return mod._live_connections.get(mod._key(path), 0)
+
+
+def home(tmp_path, monkeypatch):
+ """A gateway home under tmp_path, with path resolution going through it."""
+ import hermes_state
+
+ root = tmp_path / "hermes"
+ root.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ # The suite-wide fixture re-points DEFAULT_DB_PATH, which trips the
+ # deliberate escape hatch in _default_db_path() and would pin every lookup
+ # to one fixed path. Restore the import-time snapshot so resolution runs
+ # through get_hermes_home() the way production does; HERMES_HOME above
+ # keeps it inside tmp_path. Same reasoning as
+ # test_multiplex_session_db_profile_scope.py.
+ monkeypatch.setattr(
+ hermes_state, "DEFAULT_DB_PATH", hermes_state._IMPORT_DEFAULT_DB_PATH
+ )
+ return root
+
+
+def store(home):
+ with patch("gateway.session.SessionStore._ensure_loaded"):
+ s = SessionStore(sessions_dir=home / "sessions", config=GatewayConfig())
+ s._loaded = True
+ yield s
+ s.close_all_db_handles()
+
+
+def _runner_with(store) -> GatewayRunner:
+ """A GatewayRunner with only what the handle path touches.
+
+ Built with ``object.__new__`` deliberately: ``GatewayRunner.__init__``
+ starts platforms, executors and schedulers, none of which this contract
+ involves, and the method under test already supports this shape (it
+ rebuilds the cache when ``__init__`` did not).
+ """
+ runner = object.__new__(GatewayRunner)
+ runner.session_store = store
+ runner._session_db_pinned = _SESSION_DB_UNPINNED
+ runner._session_db_handles = {}
+ runner._session_db_handles_lock = threading.Lock()
+ runner._session_db_handle_cache = RecoverableHandleCache(
+ handles=runner._session_db_handles,
+ lock=runner._session_db_handles_lock,
+ )
+ runner._session_db_init_error = None
+ return runner
+
+
+def test_runner_borrows_the_stores_handle_instead_of_opening_a_second(store):
+ """The runner's SessionDB must BE the store's, not a twin of it."""
+ store_db = store._db
+ assert store_db is not None, "fixture must have a usable SQLite handle"
+ path = Path(store_db.db_path)
+ before = _live_count(path)
+ assert before >= 1, "the store's writer connection should be live"
+
+ runner = _runner_with(store)
+ wrapper = runner._open_session_db_for_active_scope()
+
+ assert wrapper is not None
+ assert wrapper._db is store_db, (
+ "the runner opened its own SessionDB; one process now holds two writer "
+ "connections and two read pools against one state.db"
+ )
+ assert _live_count(path) == before, (
+ f"live connections went {before} -> {_live_count(path)}; resolving the "
+ f"runner's handle must not cost a descriptor"
+ )
+
+
+def test_runner_shutdown_sweep_leaves_the_borrowed_handle_open(store):
+ """Ownership: the store closes its connection, the runner must not.
+
+ The shutdown sequence sweeps the store first and the runner second, so a
+ runner that closed the borrowed handle would be closing an already-closed
+ connection -- harmless today, and a use-after-close the moment the two
+ sweeps are reordered or one of them is made conditional.
+ """
+ store_db = store._db
+ path = Path(store_db.db_path)
+ runner = _runner_with(store)
+ assert runner._open_session_db_for_active_scope() is not None
+
+ runner.close_all_session_db_handles()
+
+ assert _live_count(path) >= 1, "the runner closed the handle the store owns"
+ assert store_db._conn is not None, "borrowed writer connection was closed"
+ # The wrapper cache is still drained -- not closing is not the same as not
+ # forgetting.
+ assert runner._session_db_handles == {}
+
+
+def test_runner_without_a_session_store_still_opens_its_own(home):
+ """Lightweight runners (no store wired) keep the standalone behaviour."""
+ runner = object.__new__(GatewayRunner)
+ runner._session_db_pinned = _SESSION_DB_UNPINNED
+ runner._session_db_handles = {}
+ runner._session_db_handles_lock = threading.Lock()
+ runner._session_db_handle_cache = RecoverableHandleCache(
+ handles=runner._session_db_handles,
+ lock=runner._session_db_handles_lock,
+ )
+ runner._session_db_init_error = None
+
+ wrapper = runner._open_session_db_for_active_scope()
+ try:
+ assert wrapper is not None
+ assert wrapper._db is not None
+ finally:
+ runner.close_all_session_db_handles()
+
+
+def test_unavailable_store_handle_does_not_resurrect_a_second_open(store):
+ """When the store has no handle, the runner reports it -- it does not open one."""
+ store._db = None # pins the store's handle to "unavailable"
+ runner = _runner_with(store)
+
+ assert runner._open_session_db_for_active_scope() is None
+ assert runner._session_db_handles == {}, (
+ "a duplicate handle was cached on the store's failure path"
+ )
diff --git a/tests/test_session_db_read_conn_pool.py b/tests/test_session_db_read_conn_pool.py
index 3d2dabcd3d0..31ba614bf55 100644
--- a/tests/test_session_db_read_conn_pool.py
+++ b/tests/test_session_db_read_conn_pool.py
@@ -384,3 +384,100 @@ def test_close_returns_every_permit(db):
for _ in range(_READ_POOL_MAX):
assert db._read_permits.acquire(blocking=False), "close() stranded a permit"
assert not db._read_permits.acquire(blocking=False), "close() over-released"
+
+
+# ── The ceiling belongs to the FILE, not to the SessionDB object (#98573) ──
+#
+# Every test above uses ONE SessionDB, which is exactly why the permit lived on
+# the instance for a month without anyone noticing: a per-object cap looks
+# bounded in every single-instance test and scales with deployment shape in
+# production. A gateway holds at least two handles on one state.db --
+# SessionStore and GatewayRunner opened independent ones per profile path --
+# so peak descriptors were `instances x (1 + _READ_POOL_MAX)` and grew with the
+# profile count until the process hit RLIMIT_NOFILE while staying alive.
+
+
+def test_peak_is_bounded_across_two_SessionDBs_on_one_path(db):
+ """Two handles on one file must share one read-connection ceiling."""
+ from hermes_state import SessionDB, _READ_POOL_MAX
+
+ second = SessionDB(db_path=db.db_path)
+ try:
+ n = 48
+ ready = threading.Barrier(n + 1)
+ release = threading.Event()
+ checked_out = []
+ lock = threading.Lock()
+
+ def worker(i):
+ target = db if i % 2 == 0 else second
+ conn = target._checkout_read_conn()
+ if conn is not None:
+ with lock:
+ checked_out.append((target, conn))
+ ready.wait(timeout=30)
+ release.wait(timeout=30)
+
+ threads = [threading.Thread(target=worker, args=(i,)) for i in range(n)]
+ for t in threads:
+ t.start()
+
+ ready.wait(timeout=30)
+ peak_live = _live_count(db.db_path)
+ peak_checked_out = len(checked_out)
+ release.set()
+ for t in threads:
+ t.join(timeout=30)
+
+ for target, conn in checked_out:
+ target._close_read_conn(conn)
+
+ assert peak_checked_out <= _READ_POOL_MAX, (
+ f"{peak_checked_out} read connections checked out across two "
+ f"SessionDBs; the ceiling is {_READ_POOL_MAX}. The permit is "
+ f"per-instance again, so the fd budget scales with handle count."
+ )
+ # +2 for the writer connection each instance holds.
+ assert peak_live <= _READ_POOL_MAX + 2, (
+ f"{peak_live} live connections at peak against one file; ceiling is "
+ f"{_READ_POOL_MAX} read (+2 writers)"
+ )
+ finally:
+ second.close()
+
+
+def test_idle_permits_are_reclaimed_from_a_peer_instance(db):
+ """A peer's IDLE pooled connections must not starve a new handle.
+
+ Permits are held for a connection's whole life, pooled-idle included, so
+ sharing them per path without this would hand the whole budget to whichever
+ handle warmed up first and demote every later one -- a cron job's transient
+ SessionDB, a second profile's store -- to the locked writer connection for
+ the life of the process. Trading one bug for a quieter one.
+ """
+ from hermes_state import SessionDB, _READ_POOL_MAX
+
+ # Warm every permit into db's IDLE pool.
+ held = [db._checkout_read_conn() for _ in range(_READ_POOL_MAX)]
+ assert all(c is not None for c in held)
+ for c in held:
+ db._read_pool.put_nowait(c)
+ assert db._read_pool.qsize() == _READ_POOL_MAX
+ assert not db._read_permits.acquire(blocking=False), "budget should be spent"
+
+ second = SessionDB(db_path=db.db_path)
+ try:
+ conn = second._checkout_read_conn()
+ assert conn is not None, (
+ "a peer holding only IDLE connections starved the new handle; "
+ "the read path silently degraded to the writer lock"
+ )
+ assert db._read_pool.qsize() == _READ_POOL_MAX - 1, (
+ "reclaim must close exactly one idle peer connection"
+ )
+ assert _live_count(db.db_path) <= _READ_POOL_MAX + 2
+ second._close_read_conn(conn)
+ finally:
+ second.close()