Skip to content

The agent that grows with you

fix(state): scope salvage to repair-connection durability + live-writer guard

kshitijk4poor3bdc2165c3e8
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]
new file mode 100644
index 00000000000..7601ad77630
--- /dev/null
+++ b/contributors/emails/[email protected]
@@ -0,0 +1,2 @@
+dhanesh
+# PR #90747 salvage (state.db repair durability) via #91852
diff --git a/hermes_state.py b/hermes_state.py
index ad51583096e..60e63ba8ee0 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1860,30 +1860,16 @@ def _repair_ledger_path(db_path: Path) -> Path:
def _db_fingerprint(db_path: Path) -> "Optional[str]":
- """Cheap identity for a damaged DB file: device + inode + size.
+ """Cheap identity for a damaged DB file: size + mtime_ns.
Hashing a multi-GB corrupt file on every open is exactly the kind of
- repeated cost this ledger exists to avoid.
-
- ``mtime_ns`` was the original third component, justified as "stable for a
- file nothing can successfully write to". That premise is false, and it
- is the defect that let the 2026-08-18/19 incident run unbounded: on FTS
- corruption this module deliberately keeps "canonical writes enabled with
- FTS detached", so the gateway kept writing and mtime churned. Every
- repair pass re-keyed the ledger and reset the counter to 1 — three real
- passes (00:14, 00:35, 00:45) each recorded ``failed_attempts: 1``, so the
- cap could never be reached and the damaging surgery could retry forever.
-
- Device+inode is stable across those writes. ``size`` is retained so an
- in-place restore that reuses the inode still reads as a different file.
- In WAL mode commits land in the ``-wal`` sidecar, so the main database's
- size holds steady between checkpoints — a checkpoint that grows the file
- grants a fresh budget, which is the intended "the file materially
- changed" signal rather than the per-write churn that broke the cap.
+ repeated cost this ledger exists to avoid; size+mtime is stable for a
+ file nothing can successfully write to, and any successful repair,
+ truncation or manual restore changes it (resetting the attempt count).
"""
try:
st = db_path.stat()
- return f"{st.st_dev}:{st.st_ino}:{st.st_size}"
+ return f"{st.st_size}:{st.st_mtime_ns}"
except OSError:
return None
@@ -2206,76 +2192,6 @@ def _reapply_durability_barriers(conn: sqlite3.Connection) -> bool:
return False
-def verify_state_db_integrity(
- db_path: Path,
- *,
- max_bytes: int = 2 << 30,
-) -> Dict[str, Any]:
- """Proactively verify ``db_path``. Returns a report; never raises.
-
- Repair has only ever run *reactively* — when a caller already hit a
- malformed error on open. A database torn in pages that no query happens
- to touch stays live and keeps accepting writes until something finally
- lands on the damage. On 2026-08-19 that gap was 11 hours: the tear
- landed in pages holding rows written at 02:18-02:22 and was not seen
- until 13:36, across two gateway restarts that both reported a clean start.
-
- ``PRAGMA integrity_check`` walks every page, so it is O(file size) — the
- same reason :func:`hermes_cli.backup.verify_sqlite_integrity` caps it.
- Above ``max_bytes`` this degrades to an O(1) structural probe rather than
- pegging a CPU for minutes at gateway startup.
-
- Report keys:
- ``ok`` — False only on positive evidence of damage.
- ``problems`` — integrity_check rows that were not "ok".
- ``checked`` — "full" | "probe" | "absent" | "error".
- """
- report: Dict[str, Any] = {"ok": True, "problems": [], "checked": "absent"}
- try:
- if not db_path.is_file():
- return report
- size = db_path.stat().st_size
- if size == 0:
- # A zero-byte file is handled by the dedicated zeroed-DB path.
- return report
- except OSError as exc:
- report["checked"] = "error"
- report["problems"] = [f"stat failed: {exc}"]
- return report
-
- conn = None
- try:
- conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=5.0)
- if size > max_bytes:
- report["checked"] = "probe"
- conn.execute("PRAGMA schema_version").fetchone()
- conn.execute("SELECT count(*) FROM sqlite_master").fetchone()
- return report
- report["checked"] = "full"
- rows = conn.execute("PRAGMA integrity_check").fetchall()
- problems = [str(r[0]) for r in rows if r and str(r[0]).lower() != "ok"]
- if problems:
- report["ok"] = False
- report["problems"] = problems
- except sqlite3.DatabaseError as exc:
- # The DB refused to open or parse — positive evidence of damage.
- report["ok"] = False
- report["checked"] = "error"
- report["problems"] = [str(exc)]
- except Exception as exc:
- # Environmental (permissions, locks): not proof of corruption, so do
- # not claim damage — but do not claim health either.
- report["checked"] = "error"
- report["problems"] = [str(exc)]
- finally:
- if conn is not None:
- try:
- conn.close()
- except Exception:
- pass
- return report
-
-
def _db_opens_cleanly(db_path: Path) -> Optional[str]:
"""Probe a DB on a fresh connection. Returns None if healthy, else a reason.
@@ -2416,6 +2332,16 @@ def _live_writer_holds_db(db_path: Path) -> bool:
Fails **open** (returns False) on anything other than a positive
busy/locked signal: refusing to repair a database that nobody is actually
holding would strand the very self-heal path this guard protects.
+
+ Scope: the WAL-index exclusive lock is what makes this detect a holder, so
+ the guard is effective in WAL mode. On SQLite builds carrying the WAL-reset
+ bug and on NFS/SMB, Hermes deliberately runs ``state.db`` in
+ ``journal_mode=DELETE`` (see :func:`apply_wal_with_fallback`); there a held
+ reader takes only a SHARED lock, ``BEGIN IMMEDIATE`` still acquires
+ RESERVED, and this probe returns False. In that mode repair is serialised
+ only by the cross-process repairer lock rather than by this holder probe.
+ The 2026-08 incident that motivated the guard was in WAL mode, which this
+ covers; broadening detection to DELETE mode is left to a follow-up.
"""
probe = None
try:
diff --git a/tests/test_state_db_repair_live_writer_guard.py b/tests/test_state_db_repair_live_writer_guard.py
index e468f1a2ce4..8288cb322bd 100644
--- a/tests/test_state_db_repair_live_writer_guard.py
+++ b/tests/test_state_db_repair_live_writer_guard.py
@@ -1,40 +1,31 @@
-"""Regression: the state.db repair path must be bounded and must never run
-surgery against a database another connection is still writing.
+"""Regression: the state.db repair path must never run surgery against a
+database another connection is still writing.
Incident (2026-08-18/19): FTS5 shadow-table corruption escalated into b-tree
page damage across `system_prompts`, `session_model_usage` and the `sessions`
-index. Two defects in this module turned a contained, rebuildable FTS fault
-into unrecoverable data loss (292 `delivery_obligations` rows):
-
-1. `_db_fingerprint` keyed the persistent attempt ledger on ``size:mtime_ns``,
- documented as "stable for a file nothing can successfully write to". That
- premise is false: on FTS corruption hermes_state deliberately keeps
- "canonical writes enabled with FTS detached", so the gateway kept writing
- and mtime churned. Every repair pass re-keyed the ledger and reset the
- counter to 1 — three real passes (00:14, 00:35, 00:45) all recorded
- ``failed_attempts: 1``, so `_MAX_PERSISTENT_REPAIR_ATTEMPTS` could never
- be reached and the damaging surgery could retry forever.
-
-2. `repair_state_db_schema` ran its REINDEX/FTS-rebuild strategies while other
- connections still held the database open. The caller closes only its own
- `self._conn`; the incident process held seven descriptors on state.db.
- Rewriting b-tree pages under concurrent writers is what spread the damage
- out of the FTS shadow tables and into the canonical tables.
+index. `repair_state_db_schema` ran its REINDEX/FTS-rebuild strategies while
+other connections still held the database open. The caller closes only its own
+`self._conn`; the incident process held seven descriptors on state.db.
+Rewriting b-tree pages under concurrent writers is what spread the damage out
+of the FTS shadow tables and into the canonical tables.
+
+(The companion repair-attempt-ledger fingerprint fix — keying the budget on
+something stable across ongoing writes so the cap can actually be reached — is
+tracked separately in the fingerprint/repair-loop salvage PR #88425, which
+preserves @jirathip-k's #88224 diagnosis and credit. This file covers only the
+live-writer guard.)
"""
from __future__ import annotations
import sqlite3
-import time
import uuid
from pathlib import Path
+import pytest
+
from hermes_state import (
SessionDB,
- _MAX_PERSISTENT_REPAIR_ATTEMPTS,
- _db_fingerprint,
- _persistent_repair_attempts_exhausted,
- _record_repair_outcome,
repair_state_db_schema,
)
@@ -58,71 +49,28 @@ def _make_wal_db(tmp_path: Path) -> Path:
return db
-def _write_once(db: Path) -> None:
- """Simulate the gateway's ongoing canonical writes (FTS detached)."""
- handle = SessionDB(db_path=db)
- sid = handle.create_session(session_id=str(uuid.uuid4()), source="cli")
- handle.append_message(sid, role="user", content="canonical write")
- handle.close()
-
-
# ---------------------------------------------------------------------------
-# Defect 1: the ledger fingerprint must survive ongoing writes
-# ---------------------------------------------------------------------------
-
-
-def test_fingerprint_is_stable_while_the_gateway_keeps_writing(tmp_path):
- """Identity must track the FILE, not its mtime/contents.
-
- A corrupt state.db still accepts canonical writes, so a mtime- or
- content-derived fingerprint changes constantly and silently re-keys the
- attempt ledger.
- """
- db = _make_wal_db(tmp_path)
- before = _db_fingerprint(db)
-
- time.sleep(0.01)
- _write_once(db)
-
- assert _db_fingerprint(db) == before
-
-
-def test_repair_budget_is_exhausted_despite_ongoing_writes(tmp_path):
- """Three failed passes must exhaust the budget even with writes between.
-
- This is the exact incident shape: three real repair attempts, each
- separated by gateway writes, all recorded ``failed_attempts: 1``.
- """
- db = _make_wal_db(tmp_path)
-
- for _ in range(_MAX_PERSISTENT_REPAIR_ATTEMPTS):
- _record_repair_outcome(db, repaired=False)
- time.sleep(0.01)
- _write_once(db)
-
- assert _persistent_repair_attempts_exhausted(db) is True
-
-
-def test_successful_repair_still_clears_the_budget(tmp_path):
- """A healed database must not inherit a spent budget."""
- db = _make_wal_db(tmp_path)
-
- for _ in range(_MAX_PERSISTENT_REPAIR_ATTEMPTS):
- _record_repair_outcome(db, repaired=False)
- assert _persistent_repair_attempts_exhausted(db) is True
-
- _record_repair_outcome(db, repaired=True)
-
- assert _persistent_repair_attempts_exhausted(db) is False
-
-
-# ---------------------------------------------------------------------------
-# Defect 2: repair must refuse to operate under a live writer
+# Repair must refuse to operate under a live writer
# ---------------------------------------------------------------------------
def test_repair_refuses_while_another_connection_holds_the_db(tmp_path):
- """Surgery under concurrent writers is what spread the corruption."""
+ """Surgery under concurrent writers is what spread the corruption.
+
+ Gated on ``requires_wal``: ``_live_writer_holds_db`` detects an
+ out-of-process holder via ``PRAGMA locking_mode=EXCLUSIVE`` + a
+ ``BEGIN IMMEDIATE`` that a concurrent connection makes fail with
+ SQLITE_BUSY through the WAL index. On SQLite builds carrying the
+ WAL-reset bug (and on NFS/SMB) Hermes deliberately runs ``state.db`` in
+ ``journal_mode=DELETE``, where a held reader takes only a SHARED lock and
+ ``BEGIN IMMEDIATE`` can still acquire RESERVED — so the probe cannot see
+ the holder and the guard fails open. In DELETE mode repair is instead
+ serialised only by the cross-process repairer lock (see
+ ``_live_writer_holds_db``'s docstring). The conftest auto-skips this test
+ where WAL is unusable rather than assert a guarantee the runtime doesn't
+ make there.
+ """
db = _make_wal_db(tmp_path)
holder = sqlite3.connect(str(db))
diff --git a/tests/test_state_db_write_durability.py b/tests/test_state_db_write_durability.py
index fb012ad6a10..eeac5e3e56b 100644
--- a/tests/test_state_db_write_durability.py
+++ b/tests/test_state_db_write_durability.py
@@ -1,5 +1,4 @@
-"""Regression: state.db repair-path writes must be durable on macOS, and a
-torn database must be detected proactively rather than 11 hours later.
+"""Regression: state.db repair-path writes must be durable on macOS.
Incident (2026-08-19, recurrence of 2026-08-18/19): `state.db` was recovered
clean at 01:02, tore again in the pages holding rows written 02:18-02:22, and
@@ -11,22 +10,21 @@ integrity_check` on the file reported the torn-b-tree signature:
Tree 5 page 60788 cell 4: Rowid 34637 out of order
Page 50549..52587: never used
-Two defects:
-
-1. hermes_state already knows macOS `fsync()` does not guarantee write
- ordering, and mitigates it with `synchronous=FULL` +
- `checkpoint_fullfsync=1` (see `_enforce_macos_synchronous_full`, whose
- docstring names this exact failure: "a WAL checkpoint race with process
- termination ... can leave the main DB with half-written btree pages").
- Those pragmas are per-connection and were applied only via
- `apply_wal_with_fallback()`. The repair path opened `state.db` with a bare
- `sqlite3.connect()` five times and then ran REINDEX, VACUUM and
- `writable_schema` surgery through it — the operations that rewrite nearly
- every page of the file — with no barrier at all.
-
-2. Repair only ran reactively, when a caller already hit a malformed error
- (`SessionDB` open). Nothing checked the file proactively, so a torn
- database stayed live and accepted writes for hours before anyone noticed.
+The defect: hermes_state already knows macOS `fsync()` does not guarantee
+write ordering, and mitigates it with `synchronous=FULL` +
+`checkpoint_fullfsync=1` (see `_enforce_macos_synchronous_full`, whose
+docstring names this exact failure: "a WAL checkpoint race with process
+termination ... can leave the main DB with half-written btree pages").
+Those pragmas are per-connection and were applied only via
+`apply_wal_with_fallback()`. The repair path opened `state.db` with a bare
+`sqlite3.connect()` five times and then ran REINDEX, VACUUM and
+`writable_schema` surgery through it — the operations that rewrite nearly
+every page of the file — with no barrier at all.
+
+(The proactive `verify_state_db_integrity()` gate the original PR #90747 also
+carried is deferred to the follow-up that wires it into gateway startup —
+PR #91754 — since it ships as dead code without that caller. This file covers
+only the repair-connection durability half.)
"""
from __future__ import annotations
@@ -42,7 +40,6 @@ import hermes_state
from hermes_state import (
_connect_repair_durable,
repair_state_db_schema,
- verify_state_db_integrity,
)
@@ -148,63 +145,3 @@ def test_repair_still_works_through_durable_connection(tmp_path: Path) -> None:
assert conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0] == 1
finally:
conn.close()
-
-
-# ── Defect 2: proactive verification gate ───────────────────────────────
-
-
-def test_verify_state_db_integrity_passes_on_healthy_db(tmp_path: Path) -> None:
- db = _make_db(tmp_path)
- result = verify_state_db_integrity(db)
- assert result["ok"] is True
- assert result["problems"] == []
-
-
-def test_verify_state_db_integrity_detects_torn_btree(tmp_path: Path) -> None:
- """A torn database must be reported, not silently accepted."""
- db = _make_db(tmp_path)
- # Grow past one page, then corrupt an interior/leaf page directly — the
- # same class of damage as "2nd reference to page" / "never used".
- conn = sqlite3.connect(str(db))
- conn.execute("PRAGMA journal_mode=DELETE")
- conn.executemany(
- "INSERT INTO messages (body) VALUES (?)",
- [(f"row-{i}" * 40,) for i in range(500)],
- )
- conn.commit()
- conn.close()
-
- page_size = 4096
- raw = bytearray(db.read_bytes())
- # Scribble over a data page (page 3+), leaving the header page intact so
- # the file still opens — that is what makes this class so long-lived.
- start = page_size * 4
- raw[start:start + page_size] = b"\xff" * page_size
- db.write_bytes(bytes(raw))
-
- result = verify_state_db_integrity(db)
- assert result["ok"] is False
- assert result["problems"], "torn pages reported no problems"
-
-
-def test_verify_state_db_integrity_skips_pragma_when_oversized(
- tmp_path: Path,
-) -> None:
- """Must degrade to an O(1) probe rather than pegging a CPU for minutes.
-
- `PRAGMA integrity_check` walks every page, so an unbounded check at
- startup would hang the gateway on a multi-GB state.db.
- """
- db = _make_db(tmp_path)
- result = verify_state_db_integrity(db, max_bytes=1)
- assert result["ok"] is True
- assert result["checked"] == "probe"
-
-
-def test_verify_state_db_integrity_missing_file_is_not_a_failure(
- tmp_path: Path,
-) -> None:
- """A first run has no state.db yet; that must not look like corruption."""
- result = verify_state_db_integrity(tmp_path / "absent.db")
- assert result["ok"] is True
- assert result["checked"] == "absent"