Skip to content

The agent that grows with you

fix: close leaked SessionDB connections on exception paths (#83226)

RelaxJonh1db4801063b9
diff --git a/hermes_state.py b/hermes_state.py
index 0e7a094c4ce..675a0b24a31 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -4022,6 +4022,31 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
conn, self._conn = self._conn, None
self._close_connection_quietly(conn)
+ def __del__(self) -> None:
+ """Safety net: close the connection if the caller forgot.
+
+ ``atexit.register`` in ``__init__`` pins this instance alive until
+ interpreter exit, which prevents GC from collecting orphaned
+ ``SessionDB`` instances on exception paths. When callers forget
+ ``.close()``, the sqlite FDs leak until the process exits (EMFILE).
+
+ A ``__del__`` finalizer is the last-resort guard: it fires when the
+ GC collects the object, which *can* happen once ``atexit`` is
+ unregistered (via ``close()``) **or** when the atexit-held
+ reference is the only remaining root and the interpreter is
+ shutting down. During normal interpreter teardown the order of
+ module cleanup is undefined, so we guard every attribute access.
+ """
+ try:
+ conn = self.__dict__.get("_conn")
+ except Exception:
+ return
+ if conn is not None:
+ try:
+ conn.close()
+ except Exception:
+ pass
+
# ── Chunked FTS rebuild engine (v23 opt-in optimize) ──
#
# `optimize_fts_storage()` (the `hermes sessions optimize-storage`