Skip to content

The agent that grows with you

fix(state): DELETE-journal readers wait out another process's commit

teknium1c87162285802
diff --git a/hermes_state.py b/hermes_state.py
index 2954eba698d..31ead8fd68f 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -21,7 +21,7 @@ import threading
import time
import uuid
from collections import deque
-from contextlib import contextmanager
+from contextlib import contextmanager, suppress
from pathlib import Path
from hermes_constants import get_hermes_home, mkdir_under_hermes_home
@@ -178,6 +178,11 @@ _READ_OPEN_RETRY_SECONDS = 60.0
# Deliberately NOT for writable opens: a writer owns the transition, so an IOERR there is a real
# storage/fd problem. A persistent IOERR still exhausts the budget and propagates.
_READ_ONLY_IOERR_RETRY_ATTEMPTS, _READ_ONLY_IOERR_RETRY_BACKOFF_S = 3, 0.05
+# SQLite busy handler budget for reads. Under DELETE (rollback-journal) mode a reader needs a SHARED
+# lock, which every commit from another process blocks across its journal+db fsyncs; the writer
+# connection's 1 s timeout exists for writes (they retry at application level) and starved readers
+# into "database is locked" (dashboard 503s, `hermes sessions list` crashes) under a busy gateway.
+_READ_BUSY_TIMEOUT_S = 5.0
def _default_db_path() -> Path:
@@ -687,7 +692,7 @@ class SessionDB(
leaked tracked connection cannot block the forensic backup the writable heal takes next."""
for attempt in range(_READ_ONLY_IOERR_RETRY_ATTEMPTS + 1):
try:
- self._conn = conn = self._connect_read_only(timeout=1.0)
+ self._conn = conn = self._connect_read_only(timeout=_READ_BUSY_TIMEOUT_S)
try:
apply_database_pragmas(conn, db_label="state.db")
cursor = conn.cursor()
@@ -831,7 +836,7 @@ class SessionDB(
return None
conn = None # bound before the try so the handlers can close a half-open one
try:
- conn = self._connect_read_only(timeout=5.0)
+ conn = self._connect_read_only(timeout=_READ_BUSY_TIMEOUT_S)
apply_database_pragmas(conn, db_label="state.db")
if self._fts_cjk_loaded: # registers in the connection, not the file: ro is fine
load_fts5_cjk_extension(conn)
@@ -904,7 +909,18 @@ class SessionDB(
with self._lock:
if self._conn is None: # close() raced a still-unwinding reader
self._reopen_after_close_locked(context="read")
- yield cast(sqlite3.Connection, self._conn)
+ conn = cast(sqlite3.Connection, self._conn)
+ if self._wal_active or self.read_only: # WAL: no SHARED-lock wait; ro: opened with the read budget
+ yield conn
+ return
+ # DELETE-mode writer connection: wait out a sibling's commit like a pooled reader would.
+ previous_ms = conn.execute("PRAGMA busy_timeout").fetchone()[0]
+ conn.execute(f"PRAGMA busy_timeout={int(_READ_BUSY_TIMEOUT_S * 1000)}")
+ try:
+ yield conn
+ finally:
+ with suppress(sqlite3.Error):
+ conn.execute(f"PRAGMA busy_timeout={int(previous_ms)}")
def _reopen_after_close_locked(self, context: str = "write") -> None:
"""Reopen the writer after ``close()`` raced a live caller (a teardown owner
diff --git a/tests/hermes_state/test_delete_mode_read_busy_wait.py b/tests/hermes_state/test_delete_mode_read_busy_wait.py
new file mode 100644
index 00000000000..fa84c5bcff0
--- /dev/null
+++ b/tests/hermes_state/test_delete_mode_read_busy_wait.py
@@ -0,0 +1,62 @@
+"""DELETE-journal readers wait out another process's commit instead of raising ``database is locked``.
+
+Under rollback-journal mode a reader needs a SHARED lock that a sibling process's commit blocks for
+the length of its journal+db fsyncs. Readers used to fail after the writer connection's 1 s busy
+timeout, so the dashboard's /api/sessions returned 503 and ``hermes sessions list`` crashed while a
+gateway was writing. The holder here is a separate process, as in production.
+"""
+
+import subprocess
+import sys
+
+import pytest
+import yaml
+
+from hermes_state import SessionDB
+
+_HOLD_S = 2.0 # longer than the old 1 s read budget, well inside the new one
+
+_HOLDER = """
+import sqlite3, sys, time
+conn = sqlite3.connect(sys.argv[1], isolation_level=None)
+conn.execute("BEGIN EXCLUSIVE")
+print("held", flush=True)
+time.sleep(float(sys.argv[2]))
+conn.execute("COMMIT")
+"""
+
+
+def delete_mode_db(tmp_path, monkeypatch):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text(yaml.safe_dump({"database": {"journal_mode": "delete"}}), encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ db = SessionDB(db_path=home / "state.db")
+ assert db._wal_active is False
+ assert db._conn.execute("PRAGMA journal_mode").fetchone()[0].lower() == "delete"
+ db.create_session("s1", source="cli")
+ db.append_message("s1", role="user", content="hello")
+ yield db
+ db.close()
+
+
[email protected]("read_only", [True, False], ids=["read_only_handle", "writer_handle"])
+def test_delete_mode_read_waits_for_other_process_commit(delete_mode_db, read_only):
+ holder = subprocess.Popen(
+ [sys.executable, "-c", _HOLDER, str(delete_mode_db.db_path), str(_HOLD_S)],
+ stdout=subprocess.PIPE, text=True,
+ )
+ try:
+ assert holder.stdout.readline().strip() == "held"
+ reader = SessionDB(db_path=delete_mode_db.db_path, read_only=True) if read_only else delete_mode_db
+ try:
+ assert [s["id"] for s in reader.list_sessions_rich(limit=10)] == ["s1"]
+ assert reader.session_count() == 1
+ finally:
+ if read_only:
+ reader.close()
+ finally:
+ assert holder.wait(timeout=30) == 0
+ # Writes keep their short busy timeout: they retry at application level with jitter.
+ assert delete_mode_db._conn.execute("PRAGMA busy_timeout").fetchone()[0] == 1000