The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: multi-process SQLite torture chamber for state.db integrity (C1)
teknium1adc35881ed53
diff --git a/tests/e2e/core/__init__.py b/tests/e2e/core/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/sqlite/__init__.py b/tests/e2e/core/sqlite/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/sqlite/_helpers.py b/tests/e2e/core/sqlite/_helpers.pynew file mode 100644index 00000000000..649d7d09c1a--- /dev/null+++ b/tests/e2e/core/sqlite/_helpers.py@@ -0,0 +1,377 @@+"""Harness for the multi-process SQLite torture chamber (issue class C1: state.db integrity).++One real ``state.db`` in WAL mode under ``tmp_path``; every role is a separate OS process running+``_roles.py`` against it (see that module for the journal/report protocol). This module owns:++* process lifecycle (spawn / ready / stop / SIGTERM / SIGKILL, PIDs recorded, nothing else touched);+* a background ``/proc/<pid>/fd`` monitor over OUR children that records any ``(deleted)`` ``-wal``/``-shm``+ (or main-file) descriptor — the kernel-level signature of a WAL generation unlinked under a live holder;+* the invariant checks, done in the test process with short-lived bare ``sqlite3`` connections only (the+ test process never imports ``hermes_state``, so it never becomes a foreign holder of the file).++Reuses the conformance harness's deadline polling / SIGKILL reaping (``tests/conformance/persistence``).+"""++from __future__ import annotations++import json+import os+import random+import signal+import sqlite3+import subprocess+import sys+import threading+import time+import zlib+from pathlib import Path++from tests.conformance.persistence._harness import REPO_ROOT, kill9_and_reap, wait_for++ROLES = Path(__file__).with_name("_roles.py")+DEFAULT_SEED = 20260923+SEED_ENV = "HERMES_SQLITE_TORTURE_SEED"+++def base_seed() -> int:+ return int(os.environ.get(SEED_ENV) or DEFAULT_SEED)+++def episode_seed(label: str) -> int:+ return base_seed() + zlib.crc32(label.encode())+++def child_env(home: Path, hermes_home: Path) -> dict:+ """Probe hygiene: private HOME/HERMES_HOME, no provider credentials, repo importable."""+ env = {k: v for k, v in os.environ.items() if not k.endswith("_API_KEY")}+ env.update({+ "HOME": str(home),+ "HERMES_HOME": str(hermes_home),+ "PYTHONUNBUFFERED": "1",+ # The child's HERMES_HOME *is* this chamber's private home, which the live-DB guard reads as+ # "the real Hermes root"; HOME/HERMES_HOME above already keep it off the production install.+ "HERMES_STATE_DB_GUARD_BYPASS": "1",+ "PYTHONPATH": os.pathsep.join(p for p in (str(REPO_ROOT), os.environ.get("PYTHONPATH", "")) if p),+ })+ return env+++class Chamber:+ """A private HERMES_HOME + state.db plus the processes playing roles against it."""++ def __init__(self, root: Path, *, journal_mode: str = "wal"):+ self.root = root+ self.home = root / "home"+ self.hermes_home = self.home / ".hermes"+ self.hermes_home.mkdir(parents=True, exist_ok=True)+ (self.hermes_home / "config.yaml").write_text(+ f"database:\n journal_mode: {journal_mode}\n", encoding="utf-8")+ self.db = self.hermes_home / "state.db"+ self.work = root / "work"+ self.work.mkdir(exist_ok=True)+ self.env = child_env(self.home, self.hermes_home)+ self.procs: dict[str, subprocess.Popen] = {}+ self.writer_runs: list[str] = []+ self.reader_seq = 0+ self.reader_name: str | None = None+ self.deleted_hits: list[tuple[str, int, str]] = []+ self.fd_samples: dict[str, list[int]] = {}+ self._lock = threading.Lock()+ self._monitor_stop = threading.Event()+ self._monitor = threading.Thread(target=self._scan_loop, name="deleted-fd-monitor", daemon=True)+ self._monitor.start()++ # -- lifecycle ---------------------------------------------------------------------------------+ def spawn(self, role: str, name: str, *, env: dict | None = None, **args) -> subprocess.Popen:+ assert name not in self.procs, f"duplicate role name {name}"+ payload = {"workdir": str(self.work), "name": name, "db": str(self.db),+ "stop": str(self.work / f"{name}.stop"), **args}+ stderr = open(self.work / f"{name}.stderr", "wb") # noqa: SIM115 - closed in reap()+ proc = subprocess.Popen(+ [sys.executable, str(ROLES), role, json.dumps(payload)],+ cwd=str(REPO_ROOT), env={**self.env, **(env or {})}, stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL, stderr=stderr,+ )+ proc._stderr_file = stderr # type: ignore[attr-defined]+ with self._lock:+ self.procs[name] = proc+ if role == "writer":+ self.writer_runs.append(name)+ return proc++ def spawn_cli(self, name: str, *argv: str) -> subprocess.Popen:+ """A real `hermes …` CLI subprocess against this HERMES_HOME."""+ stderr = open(self.work / f"{name}.stderr", "wb") # noqa: SIM115 - closed in reap()+ proc = subprocess.Popen(+ [sys.executable, "-m", "hermes_cli.main", *argv], cwd=str(REPO_ROOT), env=self.env,+ stdin=subprocess.DEVNULL, stdout=open(self.work / f"{name}.stdout", "wb"), stderr=stderr, # noqa: SIM115+ )+ proc._stderr_file = stderr # type: ignore[attr-defined]+ with self._lock:+ self.procs[name] = proc+ return proc++ def stderr(self, name: str) -> str:+ path = self.work / f"{name}.stderr"+ return path.read_text(encoding="utf-8", errors="replace")[-3000:] if path.exists() else ""++ def wait_event(self, name: str, event: str, *, deadline: float = 60.0) -> dict:+ found: list[dict] = []++ def _has() -> bool:+ found[:] = [e for e in self.events(name) if e.get("event") in (event, "error")]+ return bool(found)++ self._wait(name, _has, f"{name}:{event}", deadline)+ assert found[0].get("event") == event, f"{name} reported {found[0]}\n{self.stderr(name)}"+ return found[0]++ def wait_acks(self, name: str, n: int, *, deadline: float = 60.0) -> None:+ self._wait(name, lambda: len(self.journal(name)[1]) >= n, f"{n} acks from {name}", deadline)++ def _wait(self, name: str, predicate, what: str, deadline: float) -> None:+ try:+ wait_for(predicate, deadline=deadline, what=what, child=self.procs.get(name))+ except AssertionError as exc:+ tail = [e for e in self.events(name) if e.get("event") == "error"][-1:]+ raise AssertionError(f"{exc}\n{name} stderr:\n{self.stderr(name)}\n{tail}") from None++ def request_stop(self, name: str) -> None:+ (self.work / f"{name}.stop").touch()++ def reap(self, name: str, *, deadline: float = 60.0) -> int:+ proc = self.procs[name]+ try:+ rc = proc.wait(timeout=deadline)+ except subprocess.TimeoutExpired:+ kill9_and_reap(proc)+ raise AssertionError(f"{name} did not exit within {deadline}s\n{self.stderr(name)}") from None+ finally:+ proc._stderr_file.close() # type: ignore[attr-defined]+ return rc++ def stop(self, name: str, *, deadline: float = 60.0) -> int:+ self.request_stop(name)+ return self.reap(name, deadline=deadline)++ def sigterm(self, name: str) -> None:+ self.procs[name].send_signal(signal.SIGTERM)++ def kill9(self, name: str) -> None:+ proc = self.procs[name]+ kill9_and_reap(proc)+ proc._stderr_file.close() # type: ignore[attr-defined]++ def live(self) -> list[tuple[str, subprocess.Popen]]:+ with self._lock:+ return [(n, p) for n, p in self.procs.items() if p.poll() is None]++ def shutdown(self) -> None:+ for name, proc in self.live():+ self.request_stop(name)+ end = time.monotonic() + 20+ for _name, proc in list(self.procs.items()):+ try:+ proc.wait(timeout=max(0.1, end - time.monotonic()))+ except subprocess.TimeoutExpired:+ kill9_and_reap(proc)+ f = getattr(proc, "_stderr_file", None)+ if f is not None and not f.closed:+ f.close()+ self._monitor_stop.set()+ self._monitor.join(timeout=5)++ # -- kernel truth: (deleted) sidecars held by our children --------------------------------------+ def _scan_loop(self) -> None:+ targets = {str(self.db), f"{self.db}-wal", f"{self.db}-shm"}+ while not self._monitor_stop.is_set():+ for name, proc in self.live():+ fd_dir = f"/proc/{proc.pid}/fd"+ try:+ fds = os.listdir(fd_dir)+ except OSError:+ continue+ for fd in fds:+ try:+ link = os.readlink(f"{fd_dir}/{fd}")+ except OSError:+ continue+ if link.endswith(" (deleted)") and link[: -len(" (deleted)")] in targets:+ with self._lock:+ self.deleted_hits.append((name, proc.pid, link))+ self._monitor_stop.wait(0.02)++ def deleted_hits_snapshot(self) -> list[tuple[str, int, str]]:+ with self._lock:+ return sorted(set(self.deleted_hits))++ # -- reports -------------------------------------------------------------------------------------+ def events(self, name: str) -> list[dict]:+ path = self.work / f"{name}.report"+ if not path.exists():+ return []+ out = []+ for line in path.read_text(encoding="utf-8").splitlines():+ if line.strip():+ try:+ out.append(json.loads(line))+ except json.JSONDecodeError:+ pass # torn final line of a SIGKILLed child+ return out++ def errors(self) -> list[tuple[str, dict]]:+ return [(name, e) for name in list(self.procs) for e in self.events(name) if e.get("event") == "error"]++ def journal(self, name: str) -> tuple[dict[str, str], set[str]]:+ """``(intents: tok -> sid, acked tokens)`` for one writer run."""+ path = self.work / f"{name}.journal"+ intents: dict[str, str] = {}+ acked: set[str] = set()+ if not path.exists():+ return intents, acked+ for line in path.read_text(encoding="utf-8").splitlines():+ parts = line.split()+ if len(parts) >= 3 and parts[0] == "I":+ intents[parts[1]] = parts[2]+ elif len(parts) == 2 and parts[0] == "A":+ acked.add(parts[1])+ return intents, acked+++# -- invariants (bare sqlite3, short-lived connections) --------------------------------------------------+++def _connect(db: Path, *, ro: bool = True) -> sqlite3.Connection:+ uri = f"file:{db}?mode=ro" if ro else f"file:{db}"+ return sqlite3.connect(uri, uri=True, timeout=30.0)+++def integrity_rows(db: Path) -> list[str]:+ conn = _connect(db)+ try:+ return [r[0] for r in conn.execute("PRAGMA integrity_check").fetchall()]+ except sqlite3.DatabaseError as exc:+ return [f"integrity_check raised: {exc!r}"]+ finally:+ conn.close()+++def journal_mode(db: Path) -> str:+ conn = _connect(db)+ try:+ return str(conn.execute("PRAGMA journal_mode").fetchone()[0]).lower()+ finally:+ conn.close()+++def counts(db: Path) -> dict[str, int]:+ """Per-session canonical row counts (plus ``__total__``)."""+ conn = _connect(db)+ try:+ rows = conn.execute("SELECT session_id, count(*) FROM messages GROUP BY session_id").fetchall()+ finally:+ conn.close()+ out = {sid: n for sid, n in rows}+ out["__total__"] = sum(out.values())+ return out+++def token_counts(db: Path) -> dict[str, int]:+ """How many canonical rows carry each writer token (first word of the content)."""+ conn = _connect(db)+ try:+ rows = conn.execute("SELECT content FROM messages WHERE content LIKE 'TK%'").fetchall()+ finally:+ conn.close()+ out: dict[str, int] = {}+ for (content,) in rows:+ tok = content.split(" ", 1)[0]+ out[tok] = out.get(tok, 0) + 1+ return out+++def fts_problems(db: Path, sample_tokens: list[str]) -> list[str]:+ """FTS must mirror canonical rows exactly: docsize == source rows for each external-content index,+ FTS5's own 'integrity-check' against the content, and a sample of acked tokens found exactly once."""+ problems: list[str] = []+ conn = _connect(db, ro=False)+ try:+ tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master").fetchall()}+ meta = dict(conn.execute("SELECT key, value FROM state_meta").fetchall()) if "state_meta" in tables else {}+ pending = {k: v for k, v in meta.items() if k.startswith("fts_rebuild") or k in ("fts_stale",)}+ if pending:+ problems.append(f"FTS recovery still pending in state_meta: {pending}")+ canon = conn.execute("SELECT count(*) FROM messages").fetchone()[0]+ pairs = [("messages_fts", "messages_fts_src"), ("messages_fts_trigram", "messages_fts_trigram_src")]+ for fts, src in pairs:+ if fts not in tables:+ problems.append(f"{fts} missing")+ continue+ indexed = conn.execute(f"SELECT count(*) FROM {fts}_docsize").fetchone()[0]+ expected = conn.execute(f"SELECT count(*) FROM {src}").fetchone()[0]+ if indexed != expected:+ problems.append(f"{fts}: {indexed} indexed rows vs {expected} source rows (canonical {canon})")+ try:+ conn.execute(f"INSERT INTO {fts}({fts}, rank) VALUES('integrity-check', 1)")+ except sqlite3.DatabaseError as exc:+ problems.append(f"{fts} integrity-check: {exc}")+ for tok in sample_tokens:+ hits = conn.execute("SELECT count(*) FROM messages_fts WHERE messages_fts MATCH ?",+ (f'"{tok}"',)).fetchone()[0]+ if hits != 1:+ problems.append(f"session search finds acked {tok} {hits}x (expected 1)")+ conn.rollback()+ finally:+ conn.close()+ return problems+++def exactly_once_problems(chamber: Chamber) -> list[str]:+ """Every acknowledged append is stored exactly once; an unacknowledged in-flight append at most once;+ no stored writer row that no writer ever intended."""+ stored = token_counts(chamber.db)+ problems: list[str] = []+ intended: set[str] = set()+ for run in chamber.writer_runs:+ intents, acked = chamber.journal(run)+ intended.update(intents)+ for tok in acked:+ if stored.get(tok, 0) != 1:+ problems.append(f"{run}: acked {tok} stored {stored.get(tok, 0)}x")+ for tok in set(intents) - acked:+ if stored.get(tok, 0) > 1:+ problems.append(f"{run}: in-flight {tok} stored {stored[tok]}x")+ phantom = sorted(set(stored) - intended)+ if phantom:+ problems.append(f"{len(phantom)} stored rows no writer intended, e.g. {phantom[:3]}")+ return problems+++def compress_journal(chamber: Chamber, run: str) -> list[list[str]]:+ """``C`` lines of an agent run: the turn bases each ``/compress here N`` promised to keep verbatim."""+ path = chamber.work / f"{run}.journal"+ if not path.exists():+ return []+ return [line.split()[1:] for line in path.read_text(encoding="utf-8").splitlines() if line.startswith("C ")]+++def token_flags(db: Path, token: str) -> list[tuple[int, int]]:+ """``(active, compacted)`` of every canonical row whose content carries ``token``."""+ conn = _connect(db)+ try:+ rows = conn.execute("SELECT active, compacted FROM messages WHERE content LIKE ?",+ (f"%{token}%",)).fetchall()+ finally:+ conn.close()+ return sorted((int(a), int(c)) for a, c in rows)+++def acked_tokens(chamber: Chamber, runs: list[str]) -> list[str]:+ out: list[str] = []+ for run in runs:+ out.extend(sorted(chamber.journal(run)[1]))+ return out+++def sample(rng: random.Random, items: list[str], k: int) -> list[str]:+ return rng.sample(items, min(k, len(items)))diff --git a/tests/e2e/core/sqlite/_roles.py b/tests/e2e/core/sqlite/_roles.pynew file mode 100644index 00000000000..f9ddc59d1ac--- /dev/null+++ b/tests/e2e/core/sqlite/_roles.py@@ -0,0 +1,315 @@+"""Child-process roles for the SQLite torture chamber.++Run as ``python _roles.py <role> <json-args>``. Every role is a real OS process that opens the shared+``state.db`` through the production ``SessionDB`` (or, for the non-hermes opener, a bare ``sqlite3``+connection) and reports through append-only files, so a ``kill -9`` loses nothing it already reported:++* ``<name>.journal`` — writers: ``I <tok> <sid> <nrows>`` before an append, ``A <tok>`` once it returned.+* ``<name>.report`` — JSON lines: ``ready`` / ``stats`` / ``error`` / ``closed`` events.++Tokens are single FTS words (``TK`` + alnum) so the test can look every acknowledged append up by content,+through ``messages`` and through the FTS indexes.+"""++from __future__ import annotations++import json+import os+import signal+import sqlite3+import sys+import time+import traceback+from pathlib import Path++REPO = Path(__file__).resolve().parents[4]+sys.path.insert(0, str(REPO))++TOOL_FILLER = "y" * 3000 # longer than the FTS tool-content prefix, so the projection is exercised+_stop_requested = False+++def _on_sigterm(_signum, _frame):+ # Gateway/TUI shape: SIGTERM is a graceful shutdown that ends in SessionDB.close() (checkpoint on close).+ global _stop_requested+ _stop_requested = True+++class Out:+ """O_APPEND line writers: every line reaches the page cache before the next action, so it survives+ a SIGKILL of this process (only a kernel crash could lose it)."""++ def __init__(self, workdir: Path, name: str):+ self.journal_fd = os.open(workdir / f"{name}.journal", os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)+ self.report_fd = os.open(workdir / f"{name}.report", os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)++ def journal(self, line: str) -> None:+ os.write(self.journal_fd, (line + "\n").encode())++ def report(self, **event) -> None:+ event.setdefault("pid", os.getpid())+ event.setdefault("t", time.time())+ os.write(self.report_fd, (json.dumps(event) + "\n").encode())+++def _fd_count() -> int:+ return len(os.listdir("/proc/self/fd")) if os.path.isdir("/proc/self/fd") else -1+++def _stray_close(db_path: Path) -> None:+ """What a plugin, a tool read of ~/.hermes or a header probe does: open + close the live files in THIS+ process. POSIX drops every lock this process holds on the inode (sqlite.org/howtocorrupt.html §2.2)."""+ for suffix in ("", "-shm", "-wal"):+ try:+ os.close(os.open(str(db_path) + suffix, os.O_RDONLY))+ except OSError:+ pass+++def _stopping(stop_file: Path) -> bool:+ return _stop_requested or stop_file.exists()+++def role_writer(a: dict, out: Out) -> int:+ """Long-lived writer (gateway- or TUI-like): appends until told to stop, journaling intent + ack."""+ from hermes_state import SessionDB++ db_path, stop_file = Path(a["db"]), Path(a["stop"])+ tag = a["tag"]+ db = SessionDB(db_path=db_path)+ for sid in a["sessions"]:+ if db.get_session(sid) is None:+ db.create_session(sid, a.get("source", "cli"))+ out.report(event="ready", wal=bool(getattr(db, "_wal_active", False)), fds=_fd_count())+ i = 0+ max_appends = int(a.get("max_appends", 10**9))+ try:+ while not _stopping(stop_file) and i < max_appends:+ sid = a["sessions"][i % len(a["sessions"])]+ tok = f"TK{tag}x{os.getpid()}x{i}"+ if a.get("batch_every") and i % a["batch_every"] == 0:+ msgs = [+ {"role": "user", "content": f"{tok}u please run it"},+ {"role": "tool", "content": f"{tok}t {TOOL_FILLER}", "tool_name": "terminal",+ "tool_call_id": f"c{i}"},+ ]+ out.journal(f"I {tok}u {sid} 1")+ out.journal(f"I {tok}t {sid} 1")+ db.append_messages_batch(sid, msgs)+ out.journal(f"A {tok}u")+ out.journal(f"A {tok}t")+ else:+ role = ("user", "assistant")[i % 2]+ out.journal(f"I {tok} {sid} 1")+ db.append_message(sid, role=role, content=f"{tok} turn {i} of {tag}")+ out.journal(f"A {tok}")+ i += 1+ if a.get("stray_every") and i % a["stray_every"] == 0:+ _stray_close(db_path)+ if a.get("pace"):+ time.sleep(a["pace"])+ except BaseException as exc: # a refused/failed append is exactly what the suite exists to catch+ out.report(event="error", error=repr(exc), tb=traceback.format_exc()[-3000:], appends=i)+ return 2+ out.report(event="stats", appends=i, fds=_fd_count())+ try:+ db.close()+ except BaseException as exc:+ out.report(event="error", error=f"close: {exc!r}", tb=traceback.format_exc()[-3000:])+ return 2+ out.report(event="closed", appends=i)+ return 0+++def role_reader(a: dict, out: Out) -> int:+ """Dashboard-like reader: opens a writable SessionDB at startup and polls until stopped. Reports any+ per-session count that went DOWN (no compaction runs in this chamber) and its fd count per pass."""+ from hermes_state import SessionDB++ db_path, stop_file = Path(a["db"]), Path(a["stop"])+ db = SessionDB(db_path=db_path)+ out.report(event="ready", fds=_fd_count())+ seen: dict[str, int] = {}+ passes = 0+ try:+ while not _stopping(stop_file):+ for row in db.list_sessions_rich(limit=200):+ sid = row["id"]+ n = db.message_count(sid)+ if n < seen.get(sid, 0):+ out.report(event="error", error=f"count went down for {sid}: {seen[sid]} -> {n}")+ seen[sid] = max(n, seen.get(sid, 0))+ passes += 1+ if passes % 5 == 0:+ out.report(event="stats", passes=passes, fds=_fd_count(), total=sum(seen.values()))+ time.sleep(a.get("pace", 0.05))+ except BaseException as exc:+ out.report(event="error", error=repr(exc), tb=traceback.format_exc()[-3000:])+ return 2+ out.report(event="stats", passes=passes, fds=_fd_count(), total=sum(seen.values()))+ db.close()+ out.report(event="closed")+ return 0+++def role_churn(a: dict, out: Out) -> int:+ """`hermes sessions list` / doctor / cron-guard shape: open, read, close — ``iterations`` times in one+ process, alternating the production SessionDB with a bare sqlite3 opener (sqlite3 shell, backup tool).+ The fd count must not grow with the number of cycles."""+ from hermes_state import SessionDB++ db_path = Path(a["db"])+ start_fds = _fd_count()+ fds_after_warmup = None+ try:+ for i in range(int(a["iterations"])):+ if i % 2 == 0:+ db = SessionDB(db_path=db_path)+ db.message_count()+ db.close()+ else:+ conn = sqlite3.connect(str(db_path), timeout=30.0)+ conn.execute("SELECT count(*) FROM messages").fetchone()+ conn.close()+ if i == 3:+ fds_after_warmup = _fd_count()+ except BaseException as exc:+ out.report(event="error", error=repr(exc), tb=traceback.format_exc()[-3000:])+ return 2+ out.report(event="stats", start_fds=start_fds, warm_fds=fds_after_warmup, end_fds=_fd_count(),+ iterations=a["iterations"])+ return 0+++def role_opener(a: dict, out: Out) -> int:+ """One short-lived process: open, count, close, exit (the last-close checkpoint path)."""+ db_path = Path(a["db"])+ try:+ if a.get("raw"):+ conn = sqlite3.connect(str(db_path), timeout=30.0)+ n = conn.execute("SELECT count(*) FROM messages").fetchone()[0]+ conn.close()+ else:+ from hermes_state import SessionDB+ db = SessionDB(db_path=db_path)+ n = db.message_count()+ db.close()+ except BaseException as exc:+ # may_fail: the chmod episode opens a read-only file; a clean refusal is correct, damage is not.+ if a.get("may_fail"):+ out.report(event="refused", error=repr(exc))+ return 0+ out.report(event="error", error=repr(exc), tb=traceback.format_exc()[-3000:])+ return 2+ out.report(event="stats", count=n)+ return 0+++def _raw_count(db_path: Path) -> int:+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30.0)+ try:+ return conn.execute("SELECT count(*) FROM messages").fetchone()[0]+ finally:+ conn.close()+++def role_fts(a: dict, out: Out) -> int:+ """Maintenance pass: full FTS rebuild + optimize through SessionDB (cross-process admission)."""+ from hermes_state import SessionDB++ db = SessionDB(db_path=Path(a["db"]))+ out.report(event="ready")+ try:+ rebuilt = db.rebuild_fts()+ optimized = db.optimize_fts()+ except BaseException as exc:+ out.report(event="error", error=repr(exc), tb=traceback.format_exc()[-3000:])+ return 2+ db.close()+ out.report(event="stats", rebuilt=rebuilt, optimized=optimized)+ return 0+++def role_repair(a: dict, out: Out) -> int:+ """`repair_state_db_schema` as the CLI/doctor/startup recovery calls it."""+ from hermes_state_repair import repair_state_db_schema++ db_path = Path(a["db"])+ try:+ before = _raw_count(db_path)+ result = repair_state_db_schema(db_path, backup=bool(a.get("backup", True)))+ after = _raw_count(db_path)+ except BaseException as exc:+ out.report(event="error", error=repr(exc), tb=traceback.format_exc()[-3000:])+ return 2+ out.report(event="stats", before=before, after=after,+ result={k: (str(v) if v is not None else None) for k, v in result.items()})+ return 0+++def role_agent(a: dict, out: Out) -> int:+ """A real AIAgent turn loop on the shared state.db, the LLM behind the loopback fake provider.++ Every turn is ``user(<base>Q) -> tool call (terminal echo <base>T) -> answer(<base>A)``; the journal+ records ``I <base>`` before ``run_conversation`` and ``A <base>`` once it returned (the turn is durable).+ With ``compress_at`` the agent runs ``/compress here <keep>`` after that turn, exactly as the CLI/TUI+ slash command does, and journals ``C <kept bases…>``. ``resume`` reloads history from state.db first+ (a fresh process resuming the session)."""+ from agent.conversation_compression_manual import compress_now, parse_compress_args+ from hermes_state import SessionDB+ from run_agent import AIAgent++ stop_file = Path(a["stop"])+ db = SessionDB(db_path=Path(a["db"]))+ agent = AIAgent(base_url=a["base_url"], api_key="sk-fake-e2e", model="fake-model", quiet_mode=True,+ session_db=db, session_id=a["session_id"], skip_context_files=True, skip_memory=True)+ history = db.get_messages_as_conversation(a["session_id"]) if a.get("resume") else None+ out.report(event="ready", micro=bool(getattr(agent.context_compressor, "_micro_compact_enabled", False)),+ resumed=len(history or []))+ bases: list[str] = []+ try:+ for i in range(int(a["turns"])):+ if _stopping(stop_file):+ break+ base = f"TA{a['tag']}{os.getpid()}N{i}" # TA: agent turns; TK: plain writer rows+ out.journal(f"I {base} {a['session_id']} 3")+ result = agent.run_conversation(f"{base}Q question {i} " + "filler " * 120,+ conversation_history=history)+ history = result["messages"]+ if not any(base + "A" in str(m.get("content") or "") for m in history):+ raise AssertionError(f"turn {i} ended without its answer: {result.get('final_response')!r}")+ out.journal(f"A {base}")+ bases.append(base)+ if a.get("compress_at") is not None and i == int(a["compress_at"]):+ keep = int(a.get("keep", 2))+ res = compress_now(agent, history, parse_compress_args(f"here {keep}"),+ skip_without_window=True)+ if res.status != "compressed":+ raise AssertionError(f"/compress here {keep} did not compress: {res.status}")+ history = res.after_messages+ out.journal("C " + " ".join(bases[-keep:]))+ except BaseException as exc:+ out.report(event="error", error=repr(exc), tb=traceback.format_exc()[-4000:])+ return 2+ out.report(event="stats", turns=len(bases))+ db.close()+ out.report(event="closed")+ return 0+++ROLES = {+ "agent": role_agent,+ "writer": role_writer, "reader": role_reader, "churn": role_churn, "opener": role_opener,+ "fts": role_fts, "repair": role_repair,+}+++def main() -> int:+ role, args = sys.argv[1], json.loads(sys.argv[2])+ signal.signal(signal.SIGTERM, _on_sigterm)+ out = Out(Path(args["workdir"]), args["name"])+ return ROLES[role](args, out)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/e2e/core/sqlite/test_torture_chamber.py b/tests/e2e/core/sqlite/test_torture_chamber.pynew file mode 100644index 00000000000..f27d92fbc36--- /dev/null+++ b/tests/e2e/core/sqlite/test_torture_chamber.py@@ -0,0 +1,380 @@+"""SQLite torture chamber: state.db integrity under real multi-process load (issue class C1).++One WAL ``state.db``; every role is its own OS process running the production ``SessionDB``:+a gateway-like writer, a TUI-like writer, a dashboard-like reader that opens at startup and lives across+episodes, short-lived openers (production ``SessionDB`` and bare ``sqlite3``, plus the real+``hermes sessions list`` / ``sessions stats`` CLI), FTS rebuild/optimize maintenance, and+``repair_state_db_schema``. Each episode injects one fault class — ``kill -9`` mid-write, SIGTERM graceful+close, POSIX lock cancellation by a stray in-process open/close, chmod flips, concurrent FTS rebuilds,+repair against a live and an offline store, FTS corruption, a whole-fleet SIGKILL — and then asserts the+SAME invariants:++* ``PRAGMA integrity_check`` is ``ok`` and the store is still in WAL mode;+* no child ever held a ``(deleted)`` ``state.db``/``-wal``/``-shm`` descriptor (``/proc/<pid>/fd`` scan);+* every acknowledged append is stored exactly once (per-writer intent/ack journals), an in-flight append at+ most once, and no row exists that no writer intended;+* canonical row counts only grow (no compaction runs here), and repair never lowers them;+* FTS mirrors the canonical rows (docsize == source rows, FTS5 ``integrity-check``) and session search+ finds acked messages exactly once;+* no role hit an error; the long-lived reader's and the open/close churner's fd counts stay bounded.++Randomness (ack thresholds, kill points) is seeded per episode; the seed is in every failure message and+``HERMES_SQLITE_TORTURE_SEED`` replays a run.+"""++from __future__ import annotations++import os+import random+import sqlite3+import sys+import time++import pytest++from tests.conformance.persistence._harness import wait_for+from tests.e2e.core.sqlite._helpers import (+ SEED_ENV,+ Chamber,+ acked_tokens,+ base_seed,+ counts,+ episode_seed,+ exactly_once_problems,+ fts_problems,+ integrity_rows,+ journal_mode,+ sample,+)++pytestmark = [+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="/proc fd scan and POSIX lock semantics"),+]++READER_FD_SLACK = 6+CHURN_FD_SLACK = 2+++def _sqlite_wal_capable() -> bool:+ # Mirror of the requires_wal gate: SQLite 3.7.0-3.51.2 (minus backports) has the WAL-reset bug, and+ # Hermes deliberately falls back to DELETE there, so a WAL chamber is not deployable on that runtime.+ v = sqlite3.sqlite_version_info+ return v >= (3, 51, 3) or v in ((3, 50, 7), (3, 44, 6))++[email protected](scope="module")+def chamber(tmp_path_factory):+ if not _sqlite_wal_capable():+ pytest.skip(f"linked SQLite {sqlite3.sqlite_version} runs Hermes in DELETE mode; chamber needs WAL")+ ch = Chamber(tmp_path_factory.mktemp("chamber"))+ _ensure_reader(ch)+ yield ch+ ch.shutdown()+++def _ensure_reader(ch: Chamber) -> None:+ if ch.reader_name and ch.procs[ch.reader_name].poll() is None:+ return+ ch.reader_seq += 1+ ch.reader_name = f"reader{ch.reader_seq}"+ ch.spawn("reader", ch.reader_name, pace=0.02)+ ch.wait_event(ch.reader_name, "ready")+++def _stop_reader(ch: Chamber) -> None:+ if ch.reader_name and ch.procs[ch.reader_name].poll() is None:+ assert ch.stop(ch.reader_name) == 0, ch.stderr(ch.reader_name)+++def _writers(ch: Chamber, ep: str, **kw) -> tuple[str, str]:+ gw, tui = f"{ep}-gw", f"{ep}-tui"+ ch.spawn("writer", gw, tag="g", sessions=["gw-a", "gw-b", "gw-c"], source="telegram", batch_every=7, **kw)+ ch.spawn("writer", tui, tag="t", sessions=["tui-a"], source="tui", batch_every=5, **kw)+ ch.wait_event(gw, "ready")+ ch.wait_event(tui, "ready")+ return gw, tui+++def _background(ch: Chamber, ep: str, *, openers: int = 4, churn: int = 40) -> list[str]:+ names = []+ if churn:+ ch.spawn("churn", f"{ep}-churn", iterations=churn)+ names.append(f"{ep}-churn")+ for i in range(openers):+ name = f"{ep}-open{i}"+ ch.spawn("opener", name, raw=bool(i % 2))+ names.append(name)+ return names+++def _reap_all(ch: Chamber, names: list[str]) -> None:+ for name in names:+ proc = ch.procs[name]+ if proc.returncode is None:+ rc = ch.reap(name)+ errors = [e.get("error") for e in ch.events(name) if e.get("event") == "error"]+ assert rc == 0, f"{name} exited {rc}: {errors}\n{ch.stderr(name)}"+++def _stop_all(ch: Chamber, names: list[str]) -> None:+ for name in names:+ if ch.procs[name].poll() is None:+ ch.request_stop(name)+ _reap_all(ch, names)+++# -- episodes --------------------------------------------------------------------------------------------+++def ep_baseline(ch, ep, rng):+ gw, tui = _writers(ch, ep)+ bg = _background(ch, ep)+ ch.spawn_cli(f"{ep}-cli-list", "sessions", "list")+ ch.spawn_cli(f"{ep}-cli-stats", "sessions", "stats")+ ch.wait_acks(gw, rng.randint(60, 120))+ ch.wait_acks(tui, rng.randint(40, 80))+ _reap_all(ch, bg + [f"{ep}-cli-list", f"{ep}-cli-stats"])+ _stop_all(ch, [gw, tui])+ return [gw, tui]+++def ep_kill9_writer_midwrite(ch, ep, rng):+ gw, tui = _writers(ch, ep)+ ch.spawn("churn", f"{ep}-churn", iterations=400)+ ch.wait_acks(gw, rng.randint(20, 60))+ ch.kill9(gw) # gateway dies mid-append: the in-flight row is either whole or absent+ ch.kill9(f"{ep}-churn") # and a CLI dies holding the file open+ gw2 = f"{ep}-gw2"+ ch.spawn("writer", gw2, tag="g", sessions=["gw-a", "gw-b"], source="telegram", batch_every=3)+ bg = _background(ch, ep, churn=0)+ ch.wait_acks(gw2, rng.randint(30, 60))+ ch.wait_acks(tui, 40)+ _reap_all(ch, bg)+ _stop_all(ch, [gw2, tui])+ return [gw, tui, gw2]+++def ep_sigterm_graceful_close(ch, ep, rng):+ gw, tui = _writers(ch, ep)+ bg = _background(ch, ep, openers=6, churn=60)+ ch.wait_acks(gw, rng.randint(30, 80))+ ch.sigterm(gw)+ ch.sigterm(tui) # both close (checkpoint-on-close) while the churner and openers are mid-cycle+ for name in (gw, tui):+ assert ch.reap(name) == 0, ch.stderr(name)+ assert any(e.get("event") == "closed" for e in ch.events(name)), f"{name} never closed cleanly"+ gw2 = f"{ep}-gw2"+ ch.spawn("writer", gw2, tag="g", sessions=["gw-a"], source="telegram")+ ch.wait_acks(gw2, 30)+ _reap_all(ch, bg)+ _stop_all(ch, [gw2])+ return [gw, tui, gw2]+++def ep_lock_cancellation(ch, ep, rng):+ """Plugins, tool reads of ~/.hermes and header probes open+close state.db inside the writer process,+ which cancels its POSIX locks; a sibling's last close must still not end the writer's WAL generation.+ Field topology: the gateway (+ a TUI) are the only long-lived holders — no dashboard reader pinning the+ file — so a short-lived CLI's close is the last close SQLite can see."""+ _stop_reader(ch)+ gw, tui = _writers(ch, ep, stray_every=rng.randint(2, 4))+ names = []+ target_gw, target_tui = rng.randint(80, 140), rng.randint(60, 100)+ wave = 0+ while len(ch.journal(gw)[1]) < target_gw or len(ch.journal(tui)[1]) < target_tui:+ batch = _background(ch, f"{ep}-w{wave}", openers=4, churn=6)+ _reap_all(ch, batch)+ names += batch+ wave += 1+ assert wave < 200, "writers made no progress"+ for w in (gw, tui):+ rc = ch.procs[w].poll()+ assert rc is None, (f"{w} died (rc={rc}) after {len(ch.journal(w)[1])} acks: {ch.events(w)[-1:]}\n"+ f"deleted sidecars held: {ch.deleted_hits_snapshot()}\n{ch.stderr(w)}")+ _stop_all(ch, [gw, tui])+ _ensure_reader(ch)+ return [gw, tui]+++def ep_chmod_flip(ch, ep, rng):+ gw, tui = _writers(ch, ep)+ files = [ch.db, ch.db.with_name(ch.db.name + "-wal"), ch.db.with_name(ch.db.name + "-shm")]+ try:+ for i in range(rng.randint(6, 10)):+ for f in files:+ if f.exists():+ os.chmod(f, 0o644) # a permissive mode the next SessionDB open tightens+ ch.spawn("opener", f"{ep}-tighten{i}")+ _reap_all(ch, [f"{ep}-tighten{i}"])+ os.chmod(ch.db, 0o400) # read-only main file: new openers may refuse, must not damage+ ch.spawn("opener", f"{ep}-ro{i}", may_fail=True)+ ch.spawn("opener", f"{ep}-rorw{i}", may_fail=True, raw=True)+ _reap_all(ch, [f"{ep}-ro{i}", f"{ep}-rorw{i}"])+ os.chmod(ch.db, 0o600)+ finally:+ for f in files:+ if f.exists():+ os.chmod(f, 0o600)+ n_gw = len(ch.journal(gw)[1])+ ch.wait_acks(gw, n_gw + 20) # still writing after every permission flip+ _stop_all(ch, [gw, tui])+ return [gw, tui]+++def ep_fts_rebuild_concurrent(ch, ep, rng):+ gw, tui = _writers(ch, ep)+ ch.wait_acks(gw, 20)+ ch.spawn("fts", f"{ep}-fts-a")+ ch.spawn("fts", f"{ep}-fts-b")+ ch.spawn("fts", f"{ep}-fts-killed")+ ch.wait_event(f"{ep}-fts-killed", "ready")+ time.sleep(rng.uniform(0.0, 0.05)) # fault-injection jitter, not synchronization+ ch.kill9(f"{ep}-fts-killed") # maintenance killed mid-rebuild+ _reap_all(ch, [f"{ep}-fts-a", f"{ep}-fts-b"])+ rebuilt = [e for n in ("a", "b") for e in ch.events(f"{ep}-fts-{n}") if e.get("event") == "stats"]+ assert len(rebuilt) == 2, rebuilt+ ch.wait_acks(gw, len(ch.journal(gw)[1]) + 20)+ _stop_all(ch, [gw, tui])+ return [gw, tui]+++def _repair(ch: Chamber, name: str) -> dict:+ ch.spawn("repair", name)+ _reap_all(ch, [name])+ stats = [e for e in ch.events(name) if e.get("event") == "stats"]+ assert stats, ch.events(name)+ s = stats[0]+ assert s["after"] >= s["before"], f"repair lowered canonical rows: {s}"+ return s+++def ep_repair_live_then_offline(ch, ep, rng):+ gw, tui = _writers(ch, ep)+ ch.wait_acks(gw, rng.randint(20, 50))+ _repair(ch, f"{ep}-repair-live") # must not cost an acked row (checked by the episode invariants)+ ch.wait_acks(gw, len(ch.journal(gw)[1]) + 20)+ _stop_all(ch, [gw, tui])+ _stop_reader(ch)+ _repair(ch, f"{ep}-repair-offline")+ _ensure_reader(ch)+ return [gw, tui]+++def ep_fts_corruption_fail_open(ch, ep, rng):+ """A corrupt FTS index must not cost a canonical write; repair + the next open restore search."""+ _stop_reader(ch)+ conn = sqlite3.connect(str(ch.db), timeout=30.0)+ try:+ conn.execute("UPDATE messages_fts_data SET block = X'DEADBEEFDEADBEEFDEADBEEFDEADBEEF'")+ conn.commit()+ finally:+ conn.close()+ gw, tui = _writers(ch, ep)+ ch.wait_acks(gw, rng.randint(20, 50))+ ch.wait_acks(tui, 20)+ _repair(ch, f"{ep}-repair-live") # a repair racing live writers must not overwrite their acked rows+ _stop_all(ch, [gw, tui])+ _repair(ch, f"{ep}-repair-offline")+ ch.spawn("opener", f"{ep}-reopen") # the next SessionDB open finishes the stale-FTS recovery+ _reap_all(ch, [f"{ep}-reopen"])+ _ensure_reader(ch)+ return [gw, tui]+++def ep_kill9_everything(ch, ep, rng):+ """Update fleet-restart / OOM-killer shape: every process on the file dies at once, mid-write."""+ gw, tui = _writers(ch, ep, stray_every=5)+ ch.spawn("churn", f"{ep}-churn", iterations=400)+ ch.spawn("fts", f"{ep}-fts")+ ch.wait_acks(gw, rng.randint(30, 90))+ for name in (gw, tui, f"{ep}-churn", f"{ep}-fts", ch.reader_name):+ if ch.procs[name].poll() is None:+ ch.kill9(name)+ gw2 = f"{ep}-gw2"+ ch.spawn("writer", gw2, tag="g", sessions=["gw-a", "tui-a"], source="telegram", batch_every=4)+ _ensure_reader(ch)+ ch.wait_acks(gw2, 30)+ _stop_all(ch, [gw2])+ return [gw, tui, gw2]+++EPISODES = {+ "baseline": ep_baseline,+ "kill9_writer_midwrite": ep_kill9_writer_midwrite,+ "sigterm_graceful_close": ep_sigterm_graceful_close,+ "lock_cancellation": ep_lock_cancellation,+ "chmod_flip": ep_chmod_flip,+ "fts_rebuild_concurrent": ep_fts_rebuild_concurrent,+ "repair_live_then_offline": ep_repair_live_then_offline,+ "fts_corruption_fail_open": ep_fts_corruption_fail_open,+ "kill9_everything": ep_kill9_everything,+}+++def _reader_fd_problems(ch: Chamber) -> list[str]:+ fds = [e["fds"] for e in ch.events(ch.reader_name) if e.get("fds") is not None]+ if len(fds) < 4:+ return []+ warm = max(fds[:3]) # after the first passes the read pool has settled+ if max(fds) > warm + READER_FD_SLACK:+ return [f"{ch.reader_name} fd count grew {warm} -> {max(fds)} over {len(fds)} samples ({fds[-5:]})"]+ return []+++def _churn_fd_problems(ch: Chamber, ep: str) -> list[str]:+ out = []+ for name in ch.procs:+ if not name.startswith(ep) or "churn" not in name:+ continue+ for e in ch.events(name):+ if e.get("event") == "stats" and e.get("warm_fds") is not None:+ if e["end_fds"] > e["warm_fds"] + CHURN_FD_SLACK:+ out.append(f"{name}: fds {e['warm_fds']} after warmup -> {e['end_fds']} after "+ f"{e['iterations']} open/close cycles")+ return out++[email protected]("episode", list(EPISODES))+def test_torture_episode(chamber, episode):+ seed = episode_seed(episode)+ rng = random.Random(seed)+ ctx = f"[episode={episode} seed={seed} base={base_seed()}; replay: {SEED_ENV}={base_seed()}]"+ _ensure_reader(chamber)+ before = counts(chamber.db) if chamber.db.exists() else {"__total__": 0}+ started = time.monotonic()++ runs = EPISODES[episode](chamber, episode, rng)++ # Nothing but the long-lived reader may still be running on the file.+ stragglers = [n for n, _p in chamber.live() if n != chamber.reader_name]+ assert not stragglers, f"{ctx} roles still running: {stragglers}"+ problems: list[str] = []+ problems += [f"{n}: {e.get('error')}\n{e.get('tb', '')}" for n, e in chamber.errors()]+ problems += [f"{name} (pid {pid}) held {link}" for name, pid, link in chamber.deleted_hits_snapshot()]+ rows = integrity_rows(chamber.db)+ if rows != ["ok"]:+ problems.append(f"integrity_check: {rows[:5]}")+ mode = journal_mode(chamber.db)+ if mode != "wal":+ problems.append(f"journal_mode is {mode!r} after the episode (was wal)")+ problems += exactly_once_problems(chamber)+ after = counts(chamber.db)+ for sid, n in before.items():+ if after.get(sid, 0) < n:+ problems.append(f"canonical rows went down for {sid}: {n} -> {after.get(sid, 0)}")+ episode_acks = acked_tokens(chamber, runs)+ if not episode_acks:+ problems.append("episode acknowledged no appends")+ problems += fts_problems(chamber.db, sample(rng, episode_acks, 12))+ problems += _reader_fd_problems(chamber)+ problems += _churn_fd_problems(chamber, episode)+ assert not problems, f"{ctx} ({time.monotonic() - started:.1f}s)\n" + "\n".join(problems)+++def test_long_lived_reader_saw_every_episode_grow_only(chamber):+ """The dashboard reader lives across episodes: it never saw a session shrink and never errored."""+ wait_for(lambda: any(e.get("event") == "stats" for e in chamber.events(chamber.reader_name)),+ what="reader stats")+ errors = [(n, e) for n, e in chamber.errors() if n.startswith("reader")]+ assert not errors, errors+ assert not _reader_fd_problems(chamber)