Skip to content

The agent that grows with you

test(e2e): run the state.db torture chamber and compaction suites in DELETE journal mode too

teknium184a4b3383438
diff --git a/tests/e2e/core/sqlite/_helpers.py b/tests/e2e/core/sqlite/_helpers.py
index 649d7d09c1a..a752ab2e802 100644
--- a/tests/e2e/core/sqlite/_helpers.py
+++ b/tests/e2e/core/sqlite/_helpers.py
@@ -1,11 +1,19 @@
"""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:
+One real ``state.db`` under ``tmp_path``, in either journal mode Hermes deploys (see ``JOURNAL_MODES``); every
+role is a separate OS process running ``_roles.py`` against it (see that module for the journal/report
+protocol). This module owns:
+
+* journal-mode selection through the PRODUCTION decision path: the ``delete`` arm pins the version the
+ children's ``hermes_state_wal.is_sqlite_wal_reset_vulnerable()`` probe sees to a WAL-reset-vulnerable
+ SQLite (the one CI's uv CPython 3.11.14 bundles), so ``apply_wal_with_fallback`` itself picks DELETE
+ exactly as it does for every user on such a build — the same DELETE store its network/FUSE fallbacks end
+ in; nothing in the harness issues a journal-mode pragma;
* 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;
+* a background ``/proc/<pid>/fd`` monitor over OUR children that records any ``(deleted)`` main-file descriptor
+ (a store swapped under a live holder) and, in WAL mode, any ``(deleted)`` ``-wal``/``-shm`` — 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).
@@ -26,12 +34,34 @@ import time
import zlib
from pathlib import Path
+from hermes_cli.sqlite_runtime import is_sqlite_wal_reset_vulnerable
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"
+JOURNAL_MODES = ("wal", "delete")
+# Read ONLY by _roles.py in each child: the SQLite version its production version probe reports.
+SQLITE_PIN_ENV = "HERMES_E2E_SQLITE_VERSION_PIN"
+VULNERABLE_SQLITE = "3.50.4" # bundled by uv's CPython 3.11.14 (the unit CI job): Hermes runs DELETE there
+# DELETE mode holds an EXCLUSIVE lock for every commit's journal+db fsyncs and has no writer fairness: an unpaced
+# append loop starves every other writer and reader. Gateway/TUI writers are paced by turns in the field.
+DELETE_WRITER_PACE = 0.02
+
+
+def linked_sqlite_is_wal_capable() -> bool:
+ """The production predicate on the SQLite this interpreter (and so every child) links."""
+ return not is_sqlite_wal_reset_vulnerable(sqlite3.sqlite_version_info)
+
+
+def skip_unless_deployable(journal: str) -> None:
+ """WAL is not what Hermes runs on a vulnerable SQLite, so that arm is not deployable there; DELETE always is."""
+ if journal == "wal" and not linked_sqlite_is_wal_capable():
+ import pytest
+
+ pytest.skip(f"linked SQLite {sqlite3.sqlite_version} runs Hermes in DELETE mode; the delete arm covers it")
+
def base_seed() -> int:
return int(os.environ.get(SEED_ENV) or DEFAULT_SEED)
@@ -59,17 +89,22 @@ def child_env(home: Path, hermes_home: Path) -> dict:
class Chamber:
"""A private HERMES_HOME + state.db plus the processes playing roles against it."""
- def __init__(self, root: Path, *, journal_mode: str = "wal"):
+ def __init__(self, root: Path, *, journal: str = "wal"):
+ assert journal in JOURNAL_MODES, journal
self.root = root
+ self.mode = journal
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")
+ # The config default in BOTH arms: the delete arm is a default-config user on a vulnerable SQLite.
+ (self.hermes_home / "config.yaml").write_text("database:\n journal_mode: wal\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)
+ if journal == "delete" and linked_sqlite_is_wal_capable():
+ self.env[SQLITE_PIN_ENV] = VULNERABLE_SQLITE
+ self.writer_pace = DELETE_WRITER_PACE if journal == "delete" else 0.0
self.procs: dict[str, subprocess.Popen] = {}
self.writer_runs: list[str] = []
self.reader_seq = 0
@@ -84,8 +119,10 @@ class Chamber:
# -- 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}"
+ if role == "writer":
+ args.setdefault("pace", self.writer_pace)
payload = {"workdir": str(self.work), "name": name, "db": str(self.db),
- "stop": str(self.work / f"{name}.stop"), **args}
+ "stop": str(self.work / f"{name}.stop"), "busy_ok": self.mode == "delete", **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)],
@@ -100,10 +137,12 @@ class Chamber:
return proc
def spawn_cli(self, name: str, *argv: str) -> subprocess.Popen:
- """A real `hermes …` CLI subprocess against this HERMES_HOME."""
+ """A real `hermes …` CLI subprocess against this HERMES_HOME (``hermes_cli.main`` run as ``__main__``
+ by ``_roles.py cli`` so the journal-mode seam applies to it too)."""
stderr = open(self.work / f"{name}.stderr", "wb") # noqa: SIM115 - closed in reap()
+ payload = {"workdir": str(self.work), "name": name, "argv": list(argv)}
proc = subprocess.Popen(
- [sys.executable, "-m", "hermes_cli.main", *argv], cwd=str(REPO_ROOT), env=self.env,
+ [sys.executable, str(ROLES), "cli", json.dumps(payload)], 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]
@@ -183,7 +222,9 @@ class Chamber:
# -- 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"}
+ targets = {str(self.db)}
+ if self.mode == "wal":
+ targets |= {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"
@@ -326,6 +367,34 @@ def fts_problems(db: Path, sample_tokens: list[str]) -> list[str]:
return problems
+def journal_mode_problems(chamber: Chamber, prefix: str = "") -> list[str]:
+ """The store is still in the arm's journal mode, and every production SessionDB role (whose ``ready``
+ event reports ``SessionDB._wal_active``) really ran in it — the seam took, the arm is not vacuous."""
+ problems = []
+ mode = journal_mode(chamber.db)
+ if mode != chamber.mode:
+ problems.append(f"journal_mode is {mode!r} after the episode (arm is {chamber.mode})")
+ want = chamber.mode == "wal"
+ for name in list(chamber.procs):
+ if not name.startswith(prefix):
+ continue
+ ready = [e for e in chamber.events(name) if e.get("event") == "ready" and "wal" in e]
+ if ready and ready[0]["wal"] != want:
+ problems.append(f"{name} opened SessionDB with _wal_active={ready[0]['wal']} in the {chamber.mode} arm")
+ return problems
+
+
+def busy_summary(chamber: Chamber, prefix: str = "") -> dict[str, int]:
+ """DELETE arm only: SQLITE_BUSY refusals the roles waited out, per operation (availability, not integrity)."""
+ out: dict[str, int] = {}
+ for name in list(chamber.procs):
+ if name.startswith(prefix):
+ for e in chamber.events(name):
+ if e.get("event") == "busy":
+ out[e["op"]] = out.get(e["op"], 0) + 1
+ return out
+
+
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."""
diff --git a/tests/e2e/core/sqlite/_roles.py b/tests/e2e/core/sqlite/_roles.py
index f9ddc59d1ac..7221bf23490 100644
--- a/tests/e2e/core/sqlite/_roles.py
+++ b/tests/e2e/core/sqlite/_roles.py
@@ -9,6 +9,10 @@ connection) and reports through append-only files, so a ``kill -9`` loses nothin
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.
+
+Journal-mode seam: with ``HERMES_E2E_SQLITE_VERSION_PIN`` set, the production version probe
+``hermes_state_wal.is_sqlite_wal_reset_vulnerable()`` reports that SQLite version instead of the linked one;
+the real range predicate and ``apply_wal_with_fallback`` then decide the journal mode as they would there.
"""
from __future__ import annotations
@@ -52,6 +56,37 @@ class Out:
os.write(self.report_fd, (json.dumps(event) + "\n").encode())
+def _apply_sqlite_version_pin() -> None:
+ pin = os.environ.get("HERMES_E2E_SQLITE_VERSION_PIN")
+ if not pin:
+ return
+ import hermes_state_wal
+
+ pinned = tuple(int(p) for p in pin.split("."))
+ probe = hermes_state_wal.is_sqlite_wal_reset_vulnerable
+
+ def is_sqlite_wal_reset_vulnerable(version_info=None):
+ return probe(pinned if version_info is None else version_info)
+
+ hermes_state_wal.is_sqlite_wal_reset_vulnerable = is_sqlite_wal_reset_vulnerable
+
+
+def _patient(a: dict, out: Out, op: str, fn, *, deadline: float = 90.0):
+ """Run ``fn()``; in the DELETE arm (``busy_ok``) a SQLITE_BUSY refusal is reported as a ``busy`` event and
+ retried. DELETE mode is documented to block readers on writes (hermes_state_wal), so a busy read/open is an
+ availability event there, never an integrity one. In the WAL arm it propagates and fails the role."""
+ end = time.monotonic() + deadline
+ while True:
+ try:
+ return fn()
+ except sqlite3.OperationalError as exc:
+ busy = any(m in str(exc).lower() for m in ("database is locked", "database is busy"))
+ if not (busy and a.get("busy_ok")) or time.monotonic() > end:
+ raise
+ out.report(event="busy", op=op, error=repr(exc))
+ time.sleep(0.05)
+
+
def _fd_count() -> int:
return len(os.listdir("/proc/self/fd")) if os.path.isdir("/proc/self/fd") else -1
@@ -127,18 +162,22 @@ def role_reader(a: dict, out: Out) -> int:
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())
+ db = _patient(a, out, "open", lambda: SessionDB(db_path=db_path))
+ out.report(event="ready", wal=bool(getattr(db, "_wal_active", False)), fds=_fd_count())
seen: dict[str, int] = {}
passes = 0
+
+ def _pass() -> None:
+ 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))
+
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))
+ _patient(a, out, "read", _pass)
passes += 1
if passes % 5 == 0:
out.report(event="stats", passes=passes, fds=_fd_count(), total=sum(seen.values()))
@@ -161,16 +200,24 @@ def role_churn(a: dict, out: Out) -> int:
db_path = Path(a["db"])
start_fds = _fd_count()
fds_after_warmup = None
+
+ def _hermes_cycle() -> None:
+ db = SessionDB(db_path=db_path)
+ try:
+ db.message_count()
+ finally:
+ db.close()
+
+ def _raw_cycle() -> None:
+ conn = sqlite3.connect(str(db_path), timeout=30.0)
+ try:
+ conn.execute("SELECT count(*) FROM messages").fetchone()
+ finally:
+ conn.close()
+
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()
+ _patient(a, out, "churn", _raw_cycle if i % 2 else _hermes_cycle)
if i == 3:
fds_after_warmup = _fd_count()
except BaseException as exc:
@@ -184,16 +231,23 @@ def role_churn(a: dict, out: Out) -> int:
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:
+
+ def _open_count_close() -> int:
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()
+ try:
+ return conn.execute("SELECT count(*) FROM messages").fetchone()[0]
+ finally:
+ conn.close()
+ from hermes_state import SessionDB
+ db = SessionDB(db_path=db_path)
+ try:
+ return db.message_count()
+ finally:
db.close()
+
+ try:
+ n = _patient(a, out, "open", _open_count_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"):
@@ -217,11 +271,11 @@ 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"]))
+ db = _patient(a, out, "open", lambda: SessionDB(db_path=Path(a["db"])))
out.report(event="ready")
try:
- rebuilt = db.rebuild_fts()
- optimized = db.optimize_fts()
+ rebuilt = _patient(a, out, "fts", db.rebuild_fts)
+ optimized = _patient(a, out, "fts", db.optimize_fts)
except BaseException as exc:
out.report(event="error", error=repr(exc), tb=traceback.format_exc()[-3000:])
return 2
@@ -265,7 +319,7 @@ def role_agent(a: dict, out: Out) -> int:
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 []))
+ resumed=len(history or []), wal=bool(getattr(db, "_wal_active", False)))
bases: list[str] = []
try:
for i in range(int(a["turns"])):
@@ -297,8 +351,20 @@ def role_agent(a: dict, out: Out) -> int:
return 0
+def role_cli(a: dict, out: Out) -> int:
+ """``hermes <argv>``: ``hermes_cli.main`` run as ``__main__``, i.e. ``python -m hermes_cli.main <argv>``."""
+ import runpy
+
+ sys.argv = ["hermes", *a["argv"]]
+ try:
+ runpy.run_module("hermes_cli.main", run_name="__main__", alter_sys=True)
+ except SystemExit as exc:
+ return exc.code if isinstance(exc.code, int) else (0 if exc.code is None else 1)
+ return 0
+
+
ROLES = {
- "agent": role_agent,
+ "agent": role_agent, "cli": role_cli,
"writer": role_writer, "reader": role_reader, "churn": role_churn, "opener": role_opener,
"fts": role_fts, "repair": role_repair,
}
@@ -306,7 +372,9 @@ ROLES = {
def main() -> int:
role, args = sys.argv[1], json.loads(sys.argv[2])
- signal.signal(signal.SIGTERM, _on_sigterm)
+ _apply_sqlite_version_pin()
+ if role != "cli": # the CLI keeps its own SIGTERM handling
+ signal.signal(signal.SIGTERM, _on_sigterm)
out = Out(Path(args["workdir"]), args["name"])
return ROLES[role](args, out)
diff --git a/tests/e2e/core/sqlite/test_compaction_contention.py b/tests/e2e/core/sqlite/test_compaction_contention.py
index 09fd847ffb1..571f2c95431 100644
--- a/tests/e2e/core/sqlite/test_compaction_contention.py
+++ b/tests/e2e/core/sqlite/test_compaction_contention.py
@@ -2,7 +2,9 @@
compaction").
Real ``AIAgent`` processes drive real turns (user -> terminal tool call -> answer) through the loopback fake
-provider on ONE shared WAL ``state.db``, while other processes write to, read and open/close the same file:
+provider on ONE shared ``state.db`` — once per journal mode Hermes deploys (WAL, and the DELETE mode the
+production ``apply_wal_with_fallback`` picks on a WAL-reset-vulnerable SQLite, see ``_helpers``) — while other
+processes write to, read and open/close the same file:
* a gateway-like agent with rolling micro-compaction on (every turn folds the oldest exchange into a summary
and commits it through ``archive_and_compact``);
@@ -18,7 +20,8 @@ turns. Invariants after every episode:
as compacted history (``compacted=1``) — and never live twice;
* the exchanges ``/compress here N`` promised to keep are live exactly once;
* canonical row counts only grow (compaction archives, it never deletes) — sampled continuously from outside
- and by the reader; ``integrity_check`` ok; FTS mirrors canonical rows; no ``(deleted)`` WAL held;
+ and by the reader; ``integrity_check`` ok; FTS mirrors canonical rows; the store stays in the arm's journal
+ mode; no ``(deleted)`` store (nor, in WAL mode, ``-wal``/``-shm``) held;
* the resumed process sends the model every acknowledged user turn exactly once (persisted == sent);
* the plain writer's acked appends are stored exactly once.
"""
@@ -37,15 +40,19 @@ from dataclasses import dataclass
import pytest
from tests.e2e.core.sqlite._helpers import (
+ JOURNAL_MODES,
SEED_ENV,
Chamber,
base_seed,
+ busy_summary,
compress_journal,
counts,
episode_seed,
exactly_once_problems,
fts_problems,
integrity_rows,
+ journal_mode_problems,
+ skip_unless_deployable,
token_flags,
)
from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall, write_hermes_home
@@ -110,15 +117,13 @@ class Rig:
tui_env: dict
[email protected](scope="module")
-def rig(tmp_path_factory):
- v = sqlite3.sqlite_version_info
- if not (v >= (3, 51, 3) or v in ((3, 50, 7), (3, 44, 6))):
- pytest.skip(f"linked SQLite {sqlite3.sqlite_version} runs Hermes in DELETE mode")
[email protected](scope="module", params=JOURNAL_MODES)
+def rig(request, tmp_path_factory):
+ skip_unless_deployable(request.param)
aux = _Aux()
server = FakeLLMServer(_responder, aux=aux)
server.start()
- ch = Chamber(tmp_path_factory.mktemp("compaction"))
+ ch = Chamber(tmp_path_factory.mktemp(f"compaction-{request.param}"), journal=request.param)
ctx = " context_length: 128000\n"
write_hermes_home(ch.hermes_home, server.base_url, extra_config=MICRO_CONFIG + DB_CONFIG)
tui_home = ch.root / "tui-home"
@@ -216,7 +221,7 @@ def _compacted_rows(ch: Chamber, sid: str) -> int:
def _reap_ok(ch: Chamber, name: str, deadline: float = 120.0) -> None:
rc = ch.reap(name, deadline=deadline)
- errors = [e.get("error") for e in ch.events(name) if e.get("event") == "error"]
+ errors = [f"{e.get('error')}\n{e.get('tb', '')}" for e in ch.events(name) if e.get("event") == "error"]
assert rc == 0, f"{name} exited {rc}: {errors}\n{ch.stderr(name)}"
@@ -225,7 +230,7 @@ def test_compaction_episode(rig, fault):
ch = rig.ch
seed = episode_seed(f"compaction:{fault}")
rng = random.Random(seed)
- ctx = f"[fault={fault} seed={seed} base={base_seed()}; replay: {SEED_ENV}={base_seed()}]"
+ ctx = f"[journal={ch.mode} fault={fault} seed={seed} base={base_seed()}; replay: {SEED_ENV}={base_seed()}]"
gw_sid, tui_sid = f"{fault}-gw", f"{fault}-tui"
gw, tui, plain, reader = f"{fault}-agent-gw", f"{fault}-agent-tui", f"{fault}-plain", f"{fault}-reader"
sampler = _GrowOnly(ch)
@@ -273,6 +278,7 @@ def test_compaction_episode(rig, fault):
rows = integrity_rows(ch.db)
if rows != ["ok"]:
problems.append(f"integrity_check: {rows[:5]}")
+ problems += journal_mode_problems(ch, prefix=fault)
problems += sampler.violations
problems += _turn_problems(ch, gw, compacting=True)
problems += _turn_problems(ch, resumed, compacting=True)
@@ -285,4 +291,5 @@ def test_compaction_episode(rig, fault):
for sid in (gw_sid, tui_sid): # vacuity guard: a compaction commit really landed in this episode
if not _compacted_rows(ch, sid):
problems.append(f"no compacted history rows in {sid}: compaction never committed")
- assert not problems, f"{ctx} ({sampler.samples} row-count samples)\n" + "\n".join(problems)
+ busy = busy_summary(ch, fault)
+ assert not problems, f"{ctx} ({sampler.samples} row-count samples, busy waits {busy})\n" + "\n".join(problems)
diff --git a/tests/e2e/core/sqlite/test_torture_chamber.py b/tests/e2e/core/sqlite/test_torture_chamber.py
index f27d92fbc36..7eece48851a 100644
--- a/tests/e2e/core/sqlite/test_torture_chamber.py
+++ b/tests/e2e/core/sqlite/test_torture_chamber.py
@@ -1,6 +1,9 @@
"""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``:
+One ``state.db`` per journal mode Hermes deploys — WAL, and DELETE (what it runs on a WAL-reset-vulnerable
+SQLite and on network/FUSE homes; selected by the production ``apply_wal_with_fallback`` through a pinned
+version probe in every child, see ``_helpers``); 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
@@ -9,14 +12,18 @@ close, POSIX lock cancellation by a stray in-process open/close, chmod flips, co
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);
+* ``PRAGMA integrity_check`` is ``ok``; the store is still in the arm's journal mode and every SessionDB
+ role really ran in it;
+* no child ever held a ``(deleted)`` ``state.db`` descriptor — nor, in WAL mode, ``-wal``/``-shm``
+ (``/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.
+* no role hit an error (DELETE arm: readers block on writes by design, so a SQLITE_BUSY refusal of a read,
+ open or FTS pass is waited out and counted, never an integrity failure); 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.
@@ -34,17 +41,20 @@ import pytest
from tests.conformance.persistence._harness import wait_for
from tests.e2e.core.sqlite._helpers import (
+ JOURNAL_MODES,
SEED_ENV,
Chamber,
acked_tokens,
base_seed,
+ busy_summary,
counts,
episode_seed,
exactly_once_problems,
fts_problems,
integrity_rows,
- journal_mode,
+ journal_mode_problems,
sample,
+ skip_unless_deployable,
)
pytestmark = [
@@ -55,18 +65,10 @@ 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"))
[email protected](scope="module", params=JOURNAL_MODES)
+def chamber(request, tmp_path_factory):
+ skip_unless_deployable(request.param)
+ ch = Chamber(tmp_path_factory.mktemp(f"chamber-{request.param}"), journal=request.param)
_ensure_reader(ch)
yield ch
ch.shutdown()
@@ -112,7 +114,7 @@ def _reap_all(ch: Chamber, names: list[str]) -> None:
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"]
+ errors = [f"{e.get('error')}\n{e.get('tb', '')}" for e in ch.events(name) if e.get("event") == "error"]
assert rc == 0, f"{name} exited {rc}: {errors}\n{ch.stderr(name)}"
@@ -200,7 +202,7 @@ 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 i in range(rng.randint(3, 5)): # each flip is the same fault; process start-up dominates
for f in files:
if f.exists():
os.chmod(f, 0o644) # a permissive mode the next SessionDB open tightens
@@ -338,7 +340,8 @@ def _churn_fd_problems(ch: Chamber, ep: str) -> list[str]:
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()}]"
+ ctx = (f"[journal={chamber.mode} episode={episode} seed={seed} base={base_seed()}; "
+ f"replay: {SEED_ENV}={base_seed()}]")
_ensure_reader(chamber)
before = counts(chamber.db) if chamber.db.exists() else {"__total__": 0}
started = time.monotonic()
@@ -354,9 +357,7 @@ def test_torture_episode(chamber, episode):
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 += journal_mode_problems(chamber)
problems += exactly_once_problems(chamber)
after = counts(chamber.db)
for sid, n in before.items():
@@ -368,7 +369,8 @@ def test_torture_episode(chamber, episode):
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)
+ busy = busy_summary(chamber, episode)
+ assert not problems, f"{ctx} ({time.monotonic() - started:.1f}s, busy waits {busy})\n" + "\n".join(problems)
def test_long_lived_reader_saw_every_episode_grow_only(chamber):