Skip to content

The agent that grows with you

fix(state): identify duplicate SessionDB holders

EvanZhu0721e088a092f809
diff --git a/hermes_state.py b/hermes_state.py
index d4b4ee1d00d..16231d54e4f 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -535,6 +535,18 @@ class SessionDB(
self.db_path = db_path or _default_db_path()
_ensure_test_isolation(self.db_path) # before any connection/pragma/mkdir
self.read_only = read_only
+ # Keep only the opening call site, never a frame (which pins caller locals).
+ self._creation_site = "unknown"
+ caller = None
+ try:
+ caller = sys._getframe(1)
+ self._creation_site = (
+ f"{caller.f_globals.get('__name__', '?')}.{caller.f_code.co_name}:{caller.f_lineno}"
+ )
+ except Exception:
+ pass # Diagnostic metadata must not prevent opening the database.
+ finally:
+ del caller
self._lock = threading.Lock()
# Read-path split (WAL only): reads borrow from a BOUNDED read-only pool so they
# never queue behind writer flushes on self._lock (see _read_ctx); unbounded
diff --git a/hermes_state_readpool.py b/hermes_state_readpool.py
index 50c55daee79..6eefb841c6f 100644
--- a/hermes_state_readpool.py
+++ b/hermes_state_readpool.py
@@ -167,6 +167,7 @@ class _PathReadBudget:
warn = (handles > _HANDLES_PER_PATH_WARN and not self._duplicate_handles_warned)
if warn:
self._duplicate_handles_warned = True
+ creation_sites = ", ".join(sorted(member._creation_site for member in self._members))
if warn:
# Writer connections cannot be capped; the only bound is not opening
# redundant handles, so make the duplicate visible before it's an incident.
@@ -177,8 +178,9 @@ class _PathReadBudget:
# one.
"%d live SessionDB handles on %s in this process; each holds "
"its own writer connection (read connections are capped at %d "
- "for the file). A long-lived process should share one handle per path.",
- handles, db.db_path, _READ_POOL_MAX,
+ "for the file). A long-lived process should share one handle per path. "
+ "Created at: %s",
+ handles, db.db_path, _READ_POOL_MAX, creation_sites,
)
def acquire(self, requester: "SessionDB") -> bool:
diff --git a/tests/hermes_state/test_session_db_read_conn_pool.py b/tests/hermes_state/test_session_db_read_conn_pool.py
index 0cafe6b62e2..ab2ef470631 100644
--- a/tests/hermes_state/test_session_db_read_conn_pool.py
+++ b/tests/hermes_state/test_session_db_read_conn_pool.py
@@ -641,24 +641,33 @@ def test_fd_soft_limit_fails_open_for_importable_resource_stub(monkeypatch):
@pytest.mark.requires_wal
def test_duplicate_handles_on_one_path_are_reported(db, caplog):
- """Writer connections cannot be capped, so duplicates must be visible."""
+ """The one-shot warning must identify earlier holders, not just the last opener."""
import logging
+ import re
from hermes_state import SessionDB
from hermes_state_readpool import _HANDLES_PER_PATH_WARN
+ def open_extra_handle():
+ return SessionDB(db_path=db.db_path)
+
extra = []
try:
with caplog.at_level(logging.WARNING, logger="hermes_state"):
- for _ in range(_HANDLES_PER_PATH_WARN):
- extra.append(SessionDB(db_path=db.db_path))
- assert any(
- "live SessionDB handles on" in r.getMessage()
+ for _ in range(_HANDLES_PER_PATH_WARN + 1):
+ extra.append(open_extra_handle())
+ warnings = [
+ r.getMessage()
for r in caplog.records
- ), (
- f"{_HANDLES_PER_PATH_WARN + 1} handles on one file went unreported; "
- f"each holds a writer connection nothing bounds"
- )
+ if "live SessionDB handles on" in r.getMessage()
+ ]
+ assert len(warnings) == 1
+ warning = warnings[0]
+ assert f"{_HANDLES_PER_PATH_WARN + 1} live SessionDB handles on {db.db_path}" in warning
+ # The fixture returned before any duplicate was opened. Its creation
+ # site must still be available when another caller triggers the warning.
+ assert re.search(rf"{re.escape(__name__)}\.db:\d+", warning)
+ assert len(re.findall(rf"{re.escape(__name__)}\.open_extra_handle:\d+", warning)) == _HANDLES_PER_PATH_WARN
finally:
for d in extra:
d.close()
@@ -685,3 +694,43 @@ def test_read_only_handles_do_not_count_toward_the_duplicate_writer_warning(db,
finally:
for d in extra:
d.close()
+
+
+def test_handle_diagnostics_do_not_retain_the_creators_frame(tmp_path):
+ """Remembering where a handle opened must not retain its caller's locals."""
+ import gc
+ import weakref
+
+ class Context:
+ pass
+
+ def open_handle():
+ context = Context()
+ return SessionDB(db_path=tmp_path / "state.db"), weakref.ref(context)
+
+ handle, context_ref = open_handle()
+ try:
+ gc.collect()
+ assert context_ref() is None
+ finally:
+ handle.close()
+
+
+def test_handle_diagnostics_unavailable_does_not_block_database(tmp_path, monkeypatch):
+ """An audit hook denying frame access must not deny session storage."""
+ from types import SimpleNamespace
+
+ import hermes_state
+
+ def deny_frame_access(depth):
+ raise PermissionError("frame access denied")
+
+ # Replace only this module's sys reference; pytest/logging keep the real one.
+ module_sys = SimpleNamespace(**vars(hermes_state.sys))
+ module_sys._getframe = deny_frame_access
+ monkeypatch.setattr(hermes_state, "sys", module_sys)
+
+ with SessionDB(db_path=tmp_path / "state.db") as handle:
+ handle.create_session(session_id="available", source="cli", model="m")
+ assert handle.get_session("available")["id"] == "available"
+ assert handle._creation_site == "unknown"