Skip to content

The agent that grows with you

fix(state): cross-process quarantine lock + oversized DB pruning suppression (#68805)

Jasmine Naderi6048696ed05b
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index bcbd01e83ff..e5eaf8496ac 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -1058,6 +1058,11 @@ def create_quick_snapshot(
manifest: Dict[str, int] = {} # rel_path -> file size
failed_dbs: list[str] = [] # present *.db that could not be snapshotted
+ # #68805: track protected DB files skipped for size — they are snapshot
+ # incompleteness just like a failed copy, so pruning must be suppressed
+ # to preserve the older complete snapshot that may contain the only
+ # recoverable database.
+ oversized_skipped: list[str] = []
for rel in _QUICK_STATE_FILES:
src = home / rel
@@ -1078,6 +1083,8 @@ def create_quick_snapshot(
if "/workspaces/" in f"/{sub_rel}/" or "/attachments/" in f"/{sub_rel}/":
continue
if _too_large(sub, sub_rel):
+ if sub.suffix == ".db":
+ oversized_skipped.append(sub_rel)
continue
dst = snap_dir / sub_rel
dst.parent.mkdir(parents=True, exist_ok=True)
@@ -1109,6 +1116,8 @@ def create_quick_snapshot(
continue
if _too_large(src, rel):
+ if src.suffix == ".db":
+ oversized_skipped.append(rel)
continue
dst = snap_dir / rel
@@ -1170,6 +1179,7 @@ def create_quick_snapshot(
"total_size": sum(manifest.values()),
"files": manifest,
"failed_dbs": failed_dbs,
+ "oversized_skipped": oversized_skipped,
}
with open(snap_dir / "manifest.json", "w", encoding="utf-8") as f:
json.dump(meta, f, indent=2)
@@ -1177,17 +1187,27 @@ def create_quick_snapshot(
# Auto-prune. Defaults preserve historical manual /snapshot behavior; callers
# with known high-churn safety snapshots (for example pre-update) can pass a
# smaller keep value so large state.db copies do not accumulate indefinitely.
- # #68805 review: skip pruning when a present DB failed to capture — the
- # incomplete snapshot must not delete the older snapshot that may contain
- # the last good database (the recovery source this hardening is meant to
- # preserve).
- if not failed_dbs:
+ # #68805 review: skip pruning when a present DB failed to capture OR was
+ # skipped for size — either way the snapshot is incomplete and the older
+ # snapshot may contain the only recoverable database.
+ incomplete = failed_dbs or oversized_skipped
+ if not incomplete:
_prune_quick_snapshots(root, keep=_QUICK_DEFAULT_KEEP if keep is None else keep)
else:
+ if oversized_skipped:
+ print(
+ " ⚠ Skipping snapshot prune: DB file(s) skipped for size: "
+ + ", ".join(oversized_skipped)
+ )
+ logger.warning(
+ "Quick snapshot skipped oversized DB file(s): %s",
+ ", ".join(oversized_skipped),
+ )
logger.warning(
- "Skipping snapshot prune because %d DB(s) failed to capture — "
- "preserving older snapshots as recovery source",
- len(failed_dbs),
+ "Skipping snapshot prune because %d DB(s) failed to capture "
+ "and/or %d were oversized — preserving older snapshots as "
+ "recovery source",
+ len(failed_dbs), len(oversized_skipped),
)
logger.info("State snapshot created: %s (%d files)", snap_id, len(manifest))
diff --git a/hermes_state.py b/hermes_state.py
index 441725c617e..181bd5d8f2f 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -15,6 +15,7 @@ Key design decisions:
"""
import asyncio
+import contextlib
import json
import logging
import os
@@ -1605,31 +1606,110 @@ def is_zeroed_state_db(path: Path, *, probe_bytes: int = 100) -> bool:
def quarantine_zeroed_state_db(path: Path) -> Optional[Path]:
- """Move a zeroed state.db aside (preserve bytes) and return quarantine path."""
- try:
- ts = time.strftime("%Y%m%d-%H%M%S")
- except Exception:
- ts = "unknown"
- dest = path.with_name(f"{path.name}.zeroed-{ts}.bak")
- # Avoid clobbering a prior quarantine
- n = 0
- while dest.exists():
- n += 1
- dest = path.with_name(f"{path.name}.zeroed-{ts}-{n}.bak")
+ """Move a zeroed state.db aside (preserve bytes) and return quarantine path.
+
+ Uses a cross-process lock (``#68805``) so two concurrent startups cannot
+ race: the first process moves the zeroed file and the second re-checks
+ under the lock, finding the file already gone (or a fresh DB in its place)
+ instead of clobbering the quarantine.
+ """
+ import platform
+
+ lock_path = path.with_name(path.name + ".quarantine.lock")
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ handle = lock_path.open("a+b")
+ acquired = False
try:
- path.rename(dest)
- except OSError as exc:
- logger.error("Failed to quarantine zeroed %s: %s", path, exc)
- return None
- # Also move empty WAL/SHM if present so a fresh open is clean
- for suffix in ("-wal", "-shm"):
- side = Path(str(path) + suffix)
- if side.exists():
- try:
- side.rename(Path(str(dest) + suffix))
- except OSError:
- pass
- return dest
+ deadline = time.monotonic() + 5.0
+ if platform.system() == "Windows":
+ import msvcrt
+ while True:
+ try:
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
+ acquired = True
+ break
+ except OSError:
+ if time.monotonic() >= deadline:
+ break
+ time.sleep(0.020)
+ else:
+ import fcntl
+ while True:
+ try:
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ acquired = True
+ break
+ except (BlockingIOError, OSError):
+ if time.monotonic() >= deadline:
+ break
+ time.sleep(0.020)
+ if not acquired:
+ logger.warning(
+ "quarantine lock for %s not acquired within 5s — proceeding "
+ "without the cross-process lock (#68805).",
+ path,
+ )
+ # Re-check under the lock: another process may have already quarantined
+ # the file, leaving a fresh DB (or no file at all) in its place.
+ if not path.exists():
+ logger.info(
+ "quarantine_zeroed_state_db: %s already moved by another process",
+ path,
+ )
+ return None
+ if not is_zeroed_state_db(path):
+ logger.info(
+ "quarantine_zeroed_state_db: %s is no longer zeroed (another "
+ "process quarantined it and a fresh DB was created)",
+ path,
+ )
+ return None
+
+ try:
+ ts = time.strftime("%Y%m%d-%H%M%S")
+ except Exception:
+ ts = "unknown"
+ # Unique destination with PID suffix to avoid collision across
+ # concurrent startups that somehow both enter the lock.
+ dest = path.with_name(
+ f"{path.name}.zeroed-{ts}-{os.getpid()}.bak"
+ )
+ # Non-clobbering: if dest somehow exists, append a counter.
+ n = 0
+ while dest.exists():
+ n += 1
+ dest = path.with_name(
+ f"{path.name}.zeroed-{ts}-{os.getpid()}-{n}.bak"
+ )
+ try:
+ path.rename(dest)
+ except OSError as exc:
+ logger.error("Failed to quarantine zeroed %s: %s", path, exc)
+ return None
+ # Also move empty WAL/SHM if present so a fresh open is clean
+ for suffix in ("-wal", "-shm"):
+ side = Path(str(path) + suffix)
+ if side.exists():
+ try:
+ side.rename(Path(str(dest) + suffix))
+ except OSError:
+ pass
+ return dest
+ finally:
+ try:
+ if acquired:
+ if platform.system() == "Windows":
+ import msvcrt
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+ except (OSError, AttributeError):
+ pass
+ finally:
+ handle.close()
class SessionDB:
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index 9de926cacdf..98e0ae8de97 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -1823,6 +1823,56 @@ class TestQuickSnapshot:
# Cleanup the seeded escape source so the test is hermetic.
escape_src.unlink()
+ def test_oversized_db_suppresses_pruning(self, hermes_home, capsys):
+ """#68805: an oversized state.db skipped for size must suppress
+ pruning so the older complete snapshot (containing the only
+ recoverable database) is preserved.
+
+ Reproduces the reviewer's scenario: keep=1 + a state.db exceeding
+ the size cap → the new snapshot omits state.db, failed_dbs stays
+ empty (the file wasn't unreadable, just too large), and without
+ tracking oversized_skipped the older complete snapshot would be
+ pruned — losing the only recovery copy.
+ """
+ import json
+ import time as _t
+ from hermes_cli.backup import create_quick_snapshot, list_quick_snapshots
+
+ # First snapshot: complete (state.db is small, under any cap)
+ first_id = create_quick_snapshot(label="complete", hermes_home=hermes_home)
+ assert first_id is not None
+ first_dir = hermes_home / "state-snapshots" / first_id
+ assert (first_dir / "state.db").exists()
+
+ _t.sleep(1.05) # ensure distinct timestamp
+
+ # Second snapshot: state.db exceeds the 1024-byte cap → skipped for
+ # size, but small config files (32-54 bytes) still land in the manifest.
+ second_id = create_quick_snapshot(
+ label="oversized", hermes_home=hermes_home, max_file_size=1024, keep=1
+ )
+ assert second_id is not None
+ second_dir = hermes_home / "state-snapshots" / second_id
+ assert not (second_dir / "state.db").exists()
+
+ # Manifest must record the oversized skip
+ with open(second_dir / "manifest.json") as f:
+ meta = json.load(f)
+ assert "state.db" in meta.get("oversized_skipped", [])
+
+ # CRITICAL: the first (complete) snapshot must survive pruning
+ # because the second snapshot is incomplete (oversized state.db).
+ all_snaps = list_quick_snapshots(limit=100, hermes_home=hermes_home)
+ snap_ids = {s["id"] for s in all_snaps}
+ assert first_id in snap_ids, (
+ f"Complete snapshot {first_id} was pruned by an incomplete "
+ f"(oversized) snapshot — the recovery copy was lost!"
+ )
+ assert second_id in snap_ids
+
+ out = capsys.readouterr().out
+ assert "skipping state.db" in out.lower() or "skipping snapshot prune" in out.lower()
+
class TestQuickSnapshotProjectsKanban:
"""Regression for #52889: projects.db / kanban.db must survive an upgrade.
diff --git a/tests/test_zeroed_state_db.py b/tests/test_zeroed_state_db.py
index 123853e5258..099942b34e2 100644
--- a/tests/test_zeroed_state_db.py
+++ b/tests/test_zeroed_state_db.py
@@ -39,3 +39,65 @@ def test_sessiondb_opens_fresh_after_zeroed_quarantine(tmp_path, monkeypatch):
assert backups[0].stat().st_size == 4096
finally:
sdb.close()
+
+
+def test_concurrent_quarantine_no_clobber(tmp_path):
+ """#68805: two concurrent startups must not race on quarantine.
+
+ Without the cross-process lock, the second process could move its
+ newly-created empty DB over the first process's quarantine backup,
+ erasing the original damaged-file evidence. With the lock, the
+ second process re-checks under the lock, finds the file no longer
+ zeroed (or gone), and returns without clobbering.
+ """
+ import hermes_state as hs
+ import threading
+ import sqlite3
+
+ db = tmp_path / "state.db"
+ db.write_bytes(bytes(4096)) # zeroed (all-NUL) 4 KB file
+
+ results: list = [None, None]
+ errors: list = [None, None]
+
+ def worker(idx):
+ try:
+ # Each worker opens its own SessionDB on the same path.
+ # The first one quarantines the zeroed file and creates a
+ # fresh DB. The second one should find a valid DB (or no
+ # file) under the lock and NOT clobber the quarantine.
+ sdb = hs.SessionDB(db_path=db)
+ try:
+ results[idx] = "ok"
+ finally:
+ sdb.close()
+ except Exception as exc:
+ errors[idx] = exc
+
+ t1 = threading.Thread(target=worker, args=(0,))
+ t2 = threading.Thread(target=worker, args=(1,))
+ t1.start()
+ t2.start()
+ t1.join(timeout=10)
+ t2.join(timeout=10)
+
+ # Both workers should complete without error
+ assert errors[0] is None, f"Worker 0 raised: {errors[0]}"
+ assert errors[1] is None, f"Worker 1 raised: {errors[1]}"
+
+ # The quarantine backup must survive — exactly one .bak file with
+ # the original 4096 zeroed bytes.
+ backups = list(tmp_path.glob("state.db.zeroed-*.bak"))
+ assert len(backups) >= 1, "At least one quarantine backup must exist"
+ for bak in backups:
+ assert bak.stat().st_size == 4096, (
+ f"Quarantine backup {bak} was clobbered: "
+ f"expected 4096 bytes, got {bak.stat().st_size}"
+ )
+
+ # The live state.db must be a valid (non-zeroed) SQLite database
+ assert db.exists()
+ assert not hs.is_zeroed_state_db(db)
+ conn = sqlite3.connect(str(db))
+ conn.execute("SELECT 1")
+ conn.close()