Skip to content

The agent that grows with you

fix(state): self-heal SessionDB writes after close() races an in-flight worker

teknium19db48053e82d
diff --git a/hermes_state.py b/hermes_state.py
index f57e0937596..2b65c6533c5 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -5053,8 +5053,83 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
self._close_read_conn(conn)
return
with self._lock:
+ if self._conn is None:
+ # close() ran while a reader was still unwinding (#94736
+ # class) — reopen instead of yielding None to a .execute.
+ self._reopen_after_close_locked(context="read")
yield cast(sqlite3.Connection, self._conn)
+ def _reopen_after_close_locked(self, context: str = "write") -> None:
+ """Reopen the writer connection after ``close()`` raced a live caller.
+
+ The #94736 failure shape: a teardown owner (cron ``run_job``'s
+ ``finally``, a delegate timeout owner abandoning its worker, agent
+ ``close()``) calls ``SessionDB.close()`` — which sets ``_conn = None``
+ — while a still-unwinding worker thread has one more transcript flush
+ to land. The next ``_execute_write`` then died on
+ ``'NoneType' object has no attribute 'execute'``, the conversation
+ loop force-ended the turn as ``session_persistence_failed``, and the
+ in-flight tail of the subagent/cron session was silently dropped
+ (delivered as ``last_status: ok``).
+
+ The transcript append is THE critical write — losing it destroys the
+ turn — so at this shared persistence boundary we self-heal: reopen a
+ connection to the same database file and let the write land. The
+ reopen is loud (WARNING names the race) and bounded (only fires when
+ ``_conn`` is ``None``, i.e. after an explicit ``close()`` — the
+ constructor never leaves a live instance with a ``None`` handle).
+ ``__del__`` delegates to ``close()``, so the reopened connection is
+ still released at GC/exit time.
+
+ Caller must hold ``self._lock``. Raises ``sqlite3.OperationalError``
+ with an explicit cause when the reopen itself fails, so the surfaced
+ persistence error names the teardown race instead of the opaque
+ ``NoneType`` attribute error.
+ """
+ if self.read_only:
+ raise sqlite3.ProgrammingError(
+ f"SessionDB for {self.db_path} was closed (read-only handle); "
+ f"cannot serve a {context} after close()"
+ )
+ logger.warning(
+ "state.db connection for %s was closed while a %s was still in "
+ "flight — reopening (teardown/worker race, #94736)",
+ self.db_path,
+ context,
+ )
+ try:
+ conn = _connect_tracked_db(
+ str(self.db_path),
+ check_same_thread=False,
+ timeout=1.0,
+ isolation_level=None,
+ )
+ except Exception as exc:
+ raise sqlite3.OperationalError(
+ f"state.db connection was closed while a {context} was still "
+ f"in flight (a session-teardown path called close() before "
+ f"this worker finished — #94736) and the automatic reopen "
+ f"failed: {exc}"
+ ) from exc
+ try:
+ conn.row_factory = sqlite3.Row
+ self._wal_active = (
+ apply_wal_with_fallback(conn, db_label="state.db") == "wal"
+ )
+ apply_database_pragmas(conn, db_label="state.db")
+ conn.execute("PRAGMA foreign_keys=ON")
+ self._fts_cjk_loaded = load_fts5_cjk_extension(conn)
+ except Exception as exc:
+ self._close_connection_quietly(conn)
+ raise sqlite3.OperationalError(
+ f"state.db reopen after close() succeeded but connection "
+ f"setup failed: {exc}"
+ ) from exc
+ # Schema was initialised by this instance's original open; the file
+ # cannot have lost it, so no _init_schema here (no DDL races with
+ # sibling processes during teardown).
+ self._conn = conn
+
# ── Core write helper ──
@staticmethod
@@ -5355,6 +5430,10 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
while True:
try:
with self._lock:
+ if self._conn is None:
+ # close() ran while this writer was still unwinding
+ # (#94736) — reopen instead of dying on None.execute.
+ self._reopen_after_close_locked(context="write")
self._conn.execute("BEGIN IMMEDIATE")
try:
result = fn(self._conn)
diff --git a/tests/state/test_append_message_after_close_94736.py b/tests/state/test_append_message_after_close_94736.py
new file mode 100644
index 00000000000..5e9b95d512f
--- /dev/null
+++ b/tests/state/test_append_message_after_close_94736.py
@@ -0,0 +1,125 @@
+"""Regression tests for #94736 — append_message after close() raced a live writer.
+
+Subagent/cron sessions were dying mid-run with ``Session DB append_message
+failed: 'NoneType' object has no attribute 'execute'``: a teardown owner
+(cron ``run_job``'s ``finally`` block, a delegate timeout owner abandoning
+its worker, ``AIAgent.close()``) called ``SessionDB.close()`` — which nulls
+``_conn`` — while a still-unwinding worker thread had one more transcript
+flush to land. ``_execute_write`` then hit ``None.execute`` and the
+conversation loop force-ended the turn as ``session_persistence_failed``,
+silently dropping the tail of the session.
+
+The fix self-heals at the shared persistence boundary: when ``_conn`` is
+``None`` (only possible after an explicit ``close()``), the writer reopens
+a connection to the same database file with a loud WARNING, and the write
+lands. These tests exercise the REAL SessionDB against a real sqlite file —
+no mocks of the code under test.
+"""
+
+import logging
+import threading
+
+import pytest
+
+from hermes_state import SessionDB
+
+
+def db(tmp_path):
+ d = SessionDB(db_path=tmp_path / "state.db")
+ yield d
+ d.close()
+
+
+class TestAppendAfterClose:
+ def test_append_message_after_close_reopens_and_lands(self, db, caplog):
+ """The exact #94736 shape: close() then one more transcript flush."""
+ db.create_session("s1", "cli")
+ db.append_message("s1", "user", content="hello")
+
+ db.close()
+ assert db._conn is None
+
+ with caplog.at_level(logging.WARNING, logger="hermes_state"):
+ msg_id = db.append_message(
+ "s1", "assistant", content="flushed after teardown"
+ )
+
+ assert isinstance(msg_id, int) and msg_id > 0
+ rows = db.get_messages("s1")
+ assert [r["role"] for r in rows] == ["user", "assistant"]
+ assert rows[-1]["content"] == "flushed after teardown"
+ # The recovery is loud, not silent.
+ assert any("reopening" in r.message for r in caplog.records)
+
+ def test_reopened_connection_survives_subsequent_writes_and_close(self, db):
+ """The reopened handle is a full writer: more appends work, and a
+ second close() releases it cleanly (idempotent contract)."""
+ db.create_session("s1", "cli")
+ db.close()
+
+ db.append_message("s1", "user", content="a")
+ db.append_message("s1", "assistant", content="b")
+ assert len(db.get_messages("s1")) == 2
+
+ db.close()
+ assert db._conn is None
+ db.close() # idempotent
+
+ def test_read_after_close_recovers_too(self, db):
+ """The locked-read fallback path shares the same guard: a read that
+ lands after close() must not die on None.execute either."""
+ db.create_session("s1", "cli")
+ db.append_message("s1", "user", content="hello")
+ db.close()
+
+ rows = db.get_messages("s1")
+ assert len(rows) == 1
+
+ def test_concurrent_close_during_flush_loses_no_writes(self, tmp_path):
+ """Race a teardown close() against a worker mid-flush (the cron
+ inactivity-timeout shape): every append must land or raise loudly —
+ never vanish into a swallowed NoneType error."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session("s1", "cli")
+
+ n_writes = 40
+ start = threading.Event()
+ errors: list = []
+
+ def _worker():
+ start.wait()
+ for i in range(n_writes):
+ try:
+ db.append_message("s1", "tool", content=f"result {i}")
+ except Exception as exc: # pragma: no cover - failure path
+ errors.append(exc)
+
+ t = threading.Thread(target=_worker)
+ t.start()
+ start.set()
+ # Teardown owner closes mid-flight, twice for good measure.
+ db.close()
+ db.close()
+ t.join(timeout=30)
+ assert not t.is_alive()
+
+ assert errors == [], f"appends died during teardown race: {errors!r}"
+ rows = db.get_messages("s1")
+ assert len(rows) == n_writes
+ db.close()
+
+ def test_read_only_handle_still_refuses_after_close(self, tmp_path):
+ """A read-only cross-profile handle must NOT silently reopen — it
+ raises an explicit error naming the closed handle."""
+ # Initialise a real DB first with a writable handle.
+ writer = SessionDB(db_path=tmp_path / "state.db")
+ writer.create_session("s1", "cli")
+ writer.append_message("s1", "user", content="hello")
+ writer.close()
+
+ ro = SessionDB(db_path=tmp_path / "state.db", read_only=True)
+ ro.close()
+ with pytest.raises(Exception) as excinfo:
+ ro.get_messages("s1")
+ assert "closed" in str(excinfo.value).lower()