Skip to content

The agent that grows with you

fix(state): stop unbounded state.db repair loop from filling the disk

jirathip-k27d661e17193
diff --git a/hermes_state.py b/hermes_state.py
index 60e63ba8ee0..ca78943f9e7 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1854,22 +1854,55 @@ def _bump_schema_cookie(conn: sqlite3.Connection) -> None:
_MAX_PERSISTENT_REPAIR_ATTEMPTS = 3
_MAX_MALFORMED_BACKUPS = 3
+# Head/tail bytes sampled by ``_db_fingerprint``. Enough to change whenever
+# the DB is genuinely repaired, truncated or restored (SQLite rewrites the
+# header on any real recovery), while staying O(1) on a multi-GB file.
+_FINGERPRINT_SAMPLE_BYTES = 65536
+
+# Free-space floor for the pre-repair forensic backup. The backup is a full
+# raw copy of the damaged DB, so a repair loop on a large state.db is a disk
+# amplifier: the reported incident wrote 98MB every ~10s until the volume was
+# nearly full, which would have taken down every agent on the host. Refuse
+# the copy unless the volume would still hold this much afterwards.
+_REPAIR_BACKUP_MIN_FREE_BYTES = 2 * 1024 * 1024 * 1024 # 2 GiB
+
def _repair_ledger_path(db_path: Path) -> Path:
return db_path.with_name(db_path.name + ".repair-attempts.json")
def _db_fingerprint(db_path: Path) -> "Optional[str]":
- """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; 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).
+ """Cheap identity for a damaged DB file: size + a bounded content sample.
+
+ Deliberately EXCLUDES mtime. The original ledger keyed on
+ ``size:mtime_ns`` on the assumption that "nothing can successfully write
+ to a damaged file", but that does not hold for the malformed-schema
+ class: the DB still opens and accepts writes (only ``sqlite_master`` is
+ unreadable), so live writers, WAL checkpoints and the in-place repair
+ strategies themselves all move mtime between passes. Every pass then
+ looked like a NEW file — the attempt counter reset to 1 forever, never
+ reaching ``_MAX_PERSISTENT_REPAIR_ATTEMPTS``, and the ``_backup_db_file``
+ dedupe (which compares mtime too) never matched, so each pass wrote
+ another full-size forensic copy. Observed: a repair every ~10s, a fresh
+ 98MB copy each time, 2.3GB in 20 minutes, disk heading to zero.
+
+ Hashing a multi-GB corrupt file on every open is the repeated cost this
+ ledger exists to avoid, so sample instead of digesting the whole file:
+ size plus the head/tail slices that any real repair, truncation or
+ restore necessarily changes. Stable across passes that merely touch
+ mtime; still resets the attempt count after genuine recovery.
"""
try:
st = db_path.stat()
- return f"{st.st_size}:{st.st_mtime_ns}"
+ with open(db_path, "rb") as fh:
+ head = fh.read(_FINGERPRINT_SAMPLE_BYTES)
+ if st.st_size > _FINGERPRINT_SAMPLE_BYTES:
+ fh.seek(max(0, st.st_size - _FINGERPRINT_SAMPLE_BYTES))
+ tail = fh.read(_FINGERPRINT_SAMPLE_BYTES)
+ else:
+ tail = b""
+ digest = hashlib.sha256(head + tail).hexdigest()[:32]
+ return f"{st.st_size}:{digest}"
except OSError:
return None
@@ -2018,15 +2051,18 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":
# Dedupe (#86747): a repair loop used to copy the SAME damaged bytes
# on every restart — ~900MB a pass, 89GB over 11 days in the
# reporting install. If the newest existing backup already matches
- # this file (size + mtime preserved by copy2), reuse it.
+ # this file, reuse it.
+ #
+ # Matching on mtime made this dedupe miss exactly when it mattered
+ # most: the malformed-SCHEMA class still accepts writes, so live
+ # writers and the in-place repair strategies move mtime between
+ # passes and every pass wrote another full-size copy (2.3GB in 20
+ # minutes). Compare the content fingerprint instead, which is stable
+ # while the damaged bytes are.
try:
- src_stat = db_path.stat()
+ src_fp = _db_fingerprint(db_path)
for existing in _existing_malformed_backups(db_path)[:1]:
- est = existing.stat()
- if (
- est.st_size == src_stat.st_size
- and est.st_mtime_ns == src_stat.st_mtime_ns
- ):
+ if src_fp is not None and _db_fingerprint(existing) == src_fp:
logger.info(
"Reusing existing forensic backup %s (identical to the "
"damaged DB).", existing,
@@ -2034,6 +2070,26 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":
return existing, None
except OSError:
pass
+ # Disk guard: this is a full raw copy of a possibly multi-GB DB. On a
+ # host whose volume is already nearly full — which a preceding repair
+ # loop may itself have caused — taking it can finish off the disk and
+ # take down every process on the machine. Refuse while there is still
+ # room to refuse in.
+ try:
+ src_size = db_path.stat().st_size
+ free = shutil.disk_usage(db_path.parent).free
+ if free - src_size < _REPAIR_BACKUP_MIN_FREE_BYTES:
+ reason = (
+ f"only {free / 1e9:.1f}GB free on {db_path.parent}; copying "
+ f"the {src_size / 1e9:.1f}GB damaged DB would leave less than "
+ f"{_REPAIR_BACKUP_MIN_FREE_BYTES / 1e9:.1f}GB. Free disk space, "
+ "then retry (or recover manually with `sqlite3 "
+ f"{db_path} \".recover\"`)."
+ )
+ logger.error("Refusing forensic backup of %s: %s", db_path, reason)
+ return None, reason
+ except OSError:
+ pass
shutil.copy2(db_path, backup_path)
for suffix in ("-wal", "-shm"):
sidecar = db_path.with_name(db_path.name + suffix)
diff --git a/tests/test_state_db_repair_loop_mtime.py b/tests/test_state_db_repair_loop_mtime.py
new file mode 100644
index 00000000000..7a625d31f43
--- /dev/null
+++ b/tests/test_state_db_repair_loop_mtime.py
@@ -0,0 +1,168 @@
+"""Regression: the state.db repair-loop guards must survive an mtime change.
+
+Incident (2026-08-17): a malformed-SCHEMA state.db sent Hermes into an
+unbounded repair loop that wrote a fresh 98MB forensic copy every ~10s —
+2.3GB in 20 minutes, disk heading to zero, whole agent fleet at risk.
+
+The #86747 guards were already present and did NOT hold, because both keyed
+on ``size:mtime_ns``:
+
+* ``_db_fingerprint`` -> the ledger's attempt counter reset to 1 on every
+ pass, so ``_MAX_PERSISTENT_REPAIR_ATTEMPTS`` was never reached;
+* ``_backup_db_file``'s dedupe compared mtime, so it never matched and each
+ pass wrote another full-size copy.
+
+Unlike the b-tree damage of #86747, the malformed-SCHEMA class still opens
+and accepts writes (only ``sqlite_master`` is unreadable), so live writers,
+WAL checkpoints and the in-place repair strategies all move mtime between
+passes. These tests pin the guards to content, not mtime, and add the
+missing free-space refusal.
+"""
+
+from __future__ import annotations
+
+import os
+import time
+from pathlib import Path
+from unittest.mock import patch
+
+import hermes_state
+from hermes_state import (
+ _MAX_MALFORMED_BACKUPS,
+ _MAX_PERSISTENT_REPAIR_ATTEMPTS,
+ _REPAIR_BACKUP_MIN_FREE_BYTES,
+ _backup_db_file,
+ _db_fingerprint,
+ _existing_malformed_backups,
+ _persistent_repair_attempts_exhausted,
+ _record_repair_outcome,
+)
+
+
+def _damaged_db(tmp_path: Path, size: int = 200_000) -> Path:
+ db = tmp_path / "state.db"
+ db.write_bytes(b"SQLite format 3\x00" + os.urandom(size))
+ return db
+
+
+# ---------------------------------------------------------------------------
+# Fingerprint stability
+# ---------------------------------------------------------------------------
+
+
+def test_fingerprint_survives_mtime_change(tmp_path):
+ """A touched-but-unchanged file keeps its identity (the incident's core)."""
+ db = _damaged_db(tmp_path)
+ before = _db_fingerprint(db)
+ time.sleep(0.01)
+ os.utime(db, None) # live writer / WAL checkpoint / in-place repair pass
+ assert _db_fingerprint(db) == before
+
+
+def test_fingerprint_changes_when_contents_change(tmp_path):
+ """Genuine recovery must still reset the attempt budget."""
+ db = _damaged_db(tmp_path)
+ before = _db_fingerprint(db)
+ db.write_bytes(b"SQLite format 3\x00" + os.urandom(200_000))
+ assert _db_fingerprint(db) != before
+
+
+def test_fingerprint_changes_on_truncation(tmp_path):
+ db = _damaged_db(tmp_path)
+ before = _db_fingerprint(db)
+ with open(db, "r+b") as fh:
+ fh.truncate(1024)
+ assert _db_fingerprint(db) != before
+
+
+# ---------------------------------------------------------------------------
+# Attempt ledger
+# ---------------------------------------------------------------------------
+
+
+def test_attempt_budget_exhausts_despite_mtime_churn(tmp_path):
+ """The loop must terminate even when every pass touches the file."""
+ db = _damaged_db(tmp_path)
+ for _ in range(_MAX_PERSISTENT_REPAIR_ATTEMPTS):
+ assert not _persistent_repair_attempts_exhausted(db)
+ _record_repair_outcome(db, repaired=False)
+ time.sleep(0.01)
+ os.utime(db, None)
+ assert _persistent_repair_attempts_exhausted(db)
+
+
+def test_successful_repair_clears_budget(tmp_path):
+ db = _damaged_db(tmp_path)
+ for _ in range(_MAX_PERSISTENT_REPAIR_ATTEMPTS):
+ _record_repair_outcome(db, repaired=False)
+ assert _persistent_repair_attempts_exhausted(db)
+ _record_repair_outcome(db, repaired=True)
+ assert not _persistent_repair_attempts_exhausted(db)
+
+
+# ---------------------------------------------------------------------------
+# Backup dedupe
+# ---------------------------------------------------------------------------
+
+
+def test_backup_dedupes_across_mtime_change(tmp_path):
+ """Repeated passes over identical bytes must not each write a new copy."""
+ db = _damaged_db(tmp_path)
+ first, err = _backup_db_file(db)
+ assert err is None and first is not None
+ for _ in range(5):
+ time.sleep(0.01)
+ os.utime(db, None)
+ again, err = _backup_db_file(db)
+ assert err is None
+ assert again == first, "a touched-but-identical DB was copied again"
+ assert len(_existing_malformed_backups(db)) == 1
+
+
+def test_backup_retention_cap_still_holds(tmp_path):
+ """Genuinely different damaged states are kept, but bounded."""
+ db = _damaged_db(tmp_path)
+ for _ in range(_MAX_MALFORMED_BACKUPS + 3):
+ db.write_bytes(b"SQLite format 3\x00" + os.urandom(200_000))
+ _backup_db_file(db)
+ assert len(_existing_malformed_backups(db)) <= _MAX_MALFORMED_BACKUPS
+
+
+# ---------------------------------------------------------------------------
+# Free-space guard
+# ---------------------------------------------------------------------------
+
+
+def test_backup_refused_when_disk_would_be_exhausted(tmp_path):
+ """A nearly-full volume must not be finished off by the forensic copy."""
+ db = _damaged_db(tmp_path)
+ tight = type(
+ "Usage", (), {"total": 0, "used": 0, "free": _REPAIR_BACKUP_MIN_FREE_BYTES // 2}
+ )()
+ with patch("shutil.disk_usage", return_value=tight):
+ path, reason = _backup_db_file(db)
+ assert path is None
+ assert reason is not None and "free" in reason.lower()
+ assert not _existing_malformed_backups(db)
+
+
+def test_backup_allowed_with_ample_disk(tmp_path):
+ db = _damaged_db(tmp_path)
+ roomy = type(
+ "Usage", (), {"total": 0, "used": 0, "free": _REPAIR_BACKUP_MIN_FREE_BYTES * 10}
+ )()
+ with patch("shutil.disk_usage", return_value=roomy):
+ path, reason = _backup_db_file(db)
+ assert reason is None and path is not None
+
+
+def test_repair_aborts_when_backup_refused_for_disk(tmp_path):
+ """Refused backup is a HARD STOP — never mutate the only damaged copy."""
+ db = _damaged_db(tmp_path)
+ tight = type(
+ "Usage", (), {"total": 0, "used": 0, "free": _REPAIR_BACKUP_MIN_FREE_BYTES // 2}
+ )()
+ with patch("shutil.disk_usage", return_value=tight):
+ report = hermes_state.repair_state_db_schema(db)
+ assert not report.get("repaired")
+ assert "free" in (report.get("error") or "").lower()