The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): serialize replaced probe and reopen on close in residual entry points (#116244)
Mohamad Kansofc1b0d4ee016
diff --git a/hermes_state.py b/hermes_state.pyindex 4cecffde835..7e17bd704e9 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -1045,7 +1045,8 @@ class SessionDB("not a database" in err_msg or is_malformed_db_error(exc)or self._is_fts_write_corruption_error(exc)):- self._raise_if_db_replaced()+ with self._lock:+ self._raise_if_db_replaced()# Corrupt FTS shadow tables fail every write via the sync triggers while canonical# rows are intact: detach the derived indexes atomically and retry (never rebuild here).if self._enter_fts_fail_open(exc):diff --git a/hermes_state_fts.py b/hermes_state_fts.pyindex af96e898ad6..2160efd1d3b 100644--- a/hermes_state_fts.py+++ b/hermes_state_fts.py@@ -357,9 +357,11 @@ class SessionFtsSetupMixin:if not self._fts_enabled or not self._is_fts_write_corruption_error(exc):return Falseself._raise_if_db_corrupt()- self._halt_if_db_generation_changed()try:with self._lock:+ self._raise_if_db_replaced()+ if self._conn is None:+ self._reopen_after_close_locked(context="write")self._conn.execute("BEGIN IMMEDIATE")try:self._conn.execute(diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex 7e393c4f958..84b3b41b2fb 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -343,13 +343,15 @@ class SessionMaintenanceMixin:VACUUM reads every page and commits the result back, turning contained damage into anamplified one (#105670). Same guard ``_execute_write`` applies to every write."""self._raise_if_db_corrupt()- self._raise_if_db_replaced()optimized = 0try:optimized = self.optimize_fts() # manages its own lockexcept Exception as exc:logger.warning("FTS optimize before VACUUM failed: %s", exc)with self._lock:+ self._raise_if_db_replaced()+ if self._conn is None:+ self._reopen_after_close_locked(context="write")# PASSIVE, not TRUNCATE: a manual `hermes sessions vacuum` runs in a transient CLI# process; a TRUNCATE reset here would race a live gateway writer.self._try_checkpoint("PASSIVE", "WAL checkpoint (PASSIVE) before VACUUM failed: %s")diff --git a/hermes_state_search.py b/hermes_state_search.pyindex 4f797ae5ad3..553c39f3537 100644--- a/hermes_state_search.py+++ b/hermes_state_search.py@@ -1254,9 +1254,11 @@ class SessionSearchMixin:handle never issues ``'optimize'``: it rewrites index segments in place and would compoundstructural damage (or a split WAL generation) instead of leaving it diagnosable."""self._raise_if_db_corrupt()- self._raise_if_db_replaced()optimized = 0with self._lock:+ self._raise_if_db_replaced()+ if self._conn is None:+ self._reopen_after_close_locked(context="write")for tbl in self._present_fts_tables():try:self._conn.execute(f"INSERT INTO {tbl}({tbl}) VALUES('optimize')")@@ -1285,7 +1287,6 @@ class SessionSearchMixin:and at next startup."""self._raise_if_db_corrupt()- self._raise_if_db_replaced()rebuilt = 0with fts_rebuild_admission(self.db_path) as admitted:if not admitted:@@ -1293,6 +1294,9 @@ class SessionSearchMixin:"Deferred in-place FTS rebuild: another process holds the rebuild authority for this state.db.")return 0with self._lock:+ self._raise_if_db_replaced()+ if self._conn is None:+ self._reopen_after_close_locked(context="write")for tbl in self._present_fts_tables():try:self._conn.execute(f"INSERT INTO {tbl}({tbl}) VALUES('rebuild')")diff --git a/tests/hermes_state/test_clean_close_residual_poison.py b/tests/hermes_state/test_clean_close_residual_poison.pynew file mode 100644index 00000000000..383818a7a0a--- /dev/null+++ b/tests/hermes_state/test_clean_close_residual_poison.py@@ -0,0 +1,141 @@+"""Tests verifying clean SessionDB.close() does not poison residual entry points.++Reproduces and guards against issue #116244:+- optimize_fts()+- rebuild_fts()+- vacuum()+- _execute_write() SQLite-error handling+"""+import json+import sqlite3+import threading+import pytest+from hermes_state import SessionDB++[email protected]("case", range(5))[email protected]("entry", ["normal", "optimize", "rebuild", "vacuum", "error_branch"])+def test_clean_close_never_causes_false_sticky_loss(tmp_path, monkeypatch, entry, case):+ path = tmp_path / "synthetic.db"+ db = SessionDB(db_path=path)+ db.create_session("synthetic", "cli")+ conn = db._conn+ assert db._db_sidecar_identity and path.with_name(path.name + "-wal").exists()+ lock, close, guard = db._lock, db._close_connection_quietly, db._raise_if_db_replaced+ closed, progress, second = threading.Event(), threading.Event(), threading.Event()+ calls = 0+ errors = []+ close_errors = []+ post_errors = []++ def is_writer():+ return threading.current_thread().name == "synthetic-writer"++ class ObservedLock:+ def __enter__(self):+ if is_writer():+ progress.set()+ lock.acquire()+ return self++ def __exit__(self, *args):+ lock.release()+ if is_writer() and entry == "error_branch" and calls == 1:+ second.set()++ def observed_guard():+ nonlocal calls+ if is_writer():+ calls += 1+ try:+ return guard()+ finally:+ if is_writer():+ progress.set()++ def paused_close(connection):+ close(connection)+ if connection is conn:+ assert not path.with_name(path.name + "-wal").exists(), "real close did not end WAL"+ closed.set()+ assert progress.wait(10), "writer reached neither guard nor lock"++ monkeypatch.setattr(db, "_lock", ObservedLock())+ monkeypatch.setattr(db, "_close_connection_quietly", paused_close)+ monkeypatch.setattr(db, "_raise_if_db_replaced", observed_guard)++ def closer():+ try:+ db.close()+ except BaseException as e:+ close_errors.append(type(e).__name__ + ": " + str(e))++ def inject_error(c):+ exc = sqlite3.DatabaseError("fts5: corrupt structure (deliberate synthetic injection)")+ exc.sqlite_errorcode = getattr(sqlite3, "SQLITE_CORRUPT_VTAB", 267)+ raise exc++ def writer():+ try:+ if entry == "normal":+ db.append_message("synthetic", "tool", content="normal-during-close")+ elif entry == "optimize":+ db.optimize_fts()+ elif entry == "rebuild":+ db.rebuild_fts()+ elif entry == "vacuum":+ db.vacuum()+ else:+ db._execute_write(inject_error)+ except BaseException as e:+ errors.append(type(e).__name__ + ": " + str(e))++ tc = threading.Thread(target=closer, name="synthetic-closer")+ tw = threading.Thread(target=writer, name="synthetic-writer")+ try:+ if entry == "error_branch":+ tw.start()+ assert second.wait(10), "second generation guard not reached"+ tc.start()+ else:+ tc.start()+ assert closed.wait(10)+ tw.start()+ tw.join(15)+ tc.join(15)+ assert not tw.is_alive() and not tc.is_alive(), "barrier deadlock is not a safety pass"+ assert not close_errors, close_errors+ assert not any("AssertionError" in x for x in errors), errors+ sticky = bool(db._db_wal_generation_lost)+ try:+ db.append_message("synthetic", "tool", content="after-legitimate-close")+ except Exception as e:+ post_errors.append(type(e).__name__ + ": " + str(e))+ reader = sqlite3.connect(f"file:{path}?mode=ro", uri=True)+ try:+ rows = reader.execute("SELECT count(*) FROM messages").fetchone()[0]+ finally:+ reader.close()+ observed = {+ "entry": entry,+ "case": case,+ "guard_calls": calls,+ "sticky": sticky,+ "errors": errors,+ "post_errors": post_errors,+ "rows": rows,+ "injected_sqlite_error": entry == "error_branch",+ }+ print("OBSERVED " + json.dumps(observed), flush=True)+ assert not sticky and not post_errors, observed+ assert rows == (2 if entry == "normal" else 1), observed+ finally:+ progress.set()+ closed.set()+ second.set()+ if tc.ident is not None:+ tc.join(15)+ if tw.ident is not None:+ tw.join(15)+ monkeypatch.undo()+ db.close()