The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(conformance): make the journal-mode matrix honest — steer the child resolver, audit the effective mode
kshitijk4poor905fdda100c9
diff --git a/tests/conformance/persistence/README.md b/tests/conformance/persistence/README.mdindex cc1d21cf123..036a12d2c82 100644--- a/tests/conformance/persistence/README.md+++ b/tests/conformance/persistence/README.md@@ -26,10 +26,15 @@ process mid-write.interrupt the journal write itself).- Every wait is deadline-bounded; coordination uses file barriers, neversleeps-for-correctness.-- Journal-mode matrix per cell: the resolver's default, explicit `DELETE`,- and explicit `WAL` — the WAL run **skips** where the environment's- downgrade gates refuse it (the tracking issue's 3.50.4 caveat), and every- assertion message records the mode actually in effect.+- Journal-mode matrix (cells 1 and 3): the resolver's default, explicit+ `DELETE`, and explicit `WAL` — each leg steers the child's own resolver+ via an isolated `HERMES_HOME` config, then **audits the on-disk mode after+ the run** and skips when the environment didn't honor the request (e.g.+ the resolver's WAL-reset downgrade gate, the tracking issue's 3.50.4+ caveat). A leg that ran in a different mode never counts as evidence for+ the advertised one. Cell 2 runs on the resolver's default only (the+ consume-once property is journal-mode-independent: it rests on a single+ predicated UPDATE).## Semanticsdiff --git a/tests/conformance/persistence/_harness.py b/tests/conformance/persistence/_harness.pyindex 708b94093e3..90ca6009345 100644--- a/tests/conformance/persistence/_harness.py+++ b/tests/conformance/persistence/_harness.py@@ -35,7 +35,13 @@ POLL_INTERVAL = 0.02def spawn_child(script_body: str, *, cwd: Path | None = None, env: dict | None = None) -> subprocess.Popen:"""Run ``script_body`` in a fresh interpreter with the repo importable."""child_env = dict(os.environ)- child_env["PYTHONPATH"] = str(REPO_ROOT)+ # Prepend, don't clobber: CI images may rely on an inherited PYTHONPATH+ # for dependencies — losing it would fail child imports while the parent+ # collects fine, surfacing only as an opaque wait_for deadline.+ inherited = child_env.get("PYTHONPATH")+ child_env["PYTHONPATH"] = (+ f"{REPO_ROOT}{os.pathsep}{inherited}" if inherited else str(REPO_ROOT)+ )child_env["PYTHONUNBUFFERED"] = "1"if env:child_env.update(env)@@ -48,12 +54,31 @@ def spawn_child(script_body: str, *, cwd: Path | None = None, env: dict | None =)-def wait_for(predicate, *, deadline: float = CHILD_DEADLINE, what: str = "condition") -> None:- """Poll ``predicate`` until true or fail loudly at the deadline."""+def wait_for(+ predicate,+ *,+ deadline: float = CHILD_DEADLINE,+ what: str = "condition",+ child: "subprocess.Popen | None" = None,+) -> None:+ """Poll ``predicate`` until true or fail loudly at the deadline.++ When ``child`` is given and it exits before the predicate turns true,+ fail IMMEDIATELY with its captured stderr — a crashed writer must be an+ instant diagnostic, not a 60s opaque deadline.+ """end = time.monotonic() + deadlinewhile time.monotonic() < end:if predicate():return+ if child is not None and child.poll() is not None:+ err = b""+ if child.stderr is not None:+ err = child.stderr.read() or b""+ raise AssertionError(+ f"child exited early (rc={child.returncode}) while waiting "+ f"for {what}; stderr:\n{err.decode(errors='replace')[-2000:]}"+ )time.sleep(POLL_INTERVAL)raise AssertionError(f"deadline ({deadline}s) waiting for {what}")@@ -91,21 +116,6 @@ def on_disk_journal_mode(db_path: Path) -> str:conn.close()-def force_journal_mode(db_path: Path, mode: str) -> str:- """Set an explicit journal mode on a fresh DB; return the effective mode.-- SQLite may refuse the switch (downgrade gates, live readers); callers- compare the returned mode and ``pytest.skip`` when the request didn't- stick — mirroring the resolver's behavior instead of fighting it.- """- conn = sqlite3.connect(str(db_path))- try:- row = conn.execute(f"PRAGMA journal_mode={mode}").fetchone()- return str(row[0]) if row else "unknown"- finally:- conn.close()--def integrity_ok(db_path: Path) -> bool:conn = sqlite3.connect(str(db_path))try:@@ -113,3 +123,37 @@ def integrity_ok(db_path: Path) -> bool:return bool(row) and str(row[0]).lower() == "ok"finally:conn.close()+++def make_hermes_home(base: Path, journal_mode: str) -> Path:+ """Create an isolated HERMES_HOME whose config pins ``database.journal_mode``.++ The journal-mode matrix legs must steer the CHILD's own resolver:+ pre-seeding the DB file alone is not enough, because ``SessionDB.__init__``+ runs ``apply_wal_with_fallback()`` which upgrades a non-WAL file to WAL+ whenever the configured mode (default ``wal``) says so — on healthy+ SQLite the DELETE leg would silently run in WAL.+ """+ home = base / f"hermes-home-{journal_mode}"+ home.mkdir(parents=True, exist_ok=True)+ (home / "config.yaml").write_text(+ f"database:\n journal_mode: {journal_mode}\n", encoding="utf-8"+ )+ return home+++def effective_mode_or_skip(db_path: Path, requested_mode: str | None) -> str:+ """Record the on-disk journal mode; skip if a requested leg wasn't honored.++ A leg that ran in a different mode than advertised must never count as+ green evidence for the advertised mode.+ """+ import pytest++ mode = on_disk_journal_mode(db_path)+ if requested_mode is not None and mode.upper() != requested_mode.upper():+ pytest.skip(+ f"journal_mode={requested_mode} not honored by this environment "+ f"(effective {mode}) — matrix leg not probeable here"+ )+ return modediff --git a/tests/conformance/persistence/test_cell1_prefix_durability.py b/tests/conformance/persistence/test_cell1_prefix_durability.pyindex 960a9fc1d9d..8427c6b0654 100644--- a/tests/conformance/persistence/test_cell1_prefix_durability.py+++ b/tests/conformance/persistence/test_cell1_prefix_durability.py@@ -19,9 +19,10 @@ from pathlib import Pathimport pytestfrom tests.conformance.persistence._harness import (+ effective_mode_or_skip,integrity_ok,kill9_and_reap,- on_disk_journal_mode,+ make_hermes_home,spawn_child,wait_for,)@@ -31,7 +32,7 @@ import json, sysfrom pathlib import Pathfrom hermes_state import SessionDB-db_path = Path(sys.argv[0]) if False else Path({db_path!r})+db_path = Path({db_path!r})journal = Path({journal!r})db = SessionDB(db_path=db_path)db.create_session("cell1", source="conformance")@@ -78,37 +79,43 @@ def test_acknowledged_appends_survive_sigkill(tmp_path, requested_mode):db_path = tmp_path / "state.db"journal = tmp_path / "acked.jsonl"+ child_env = {}if requested_mode is not None:- # Pre-create the DB file in the requested mode; skip when the- # environment refuses it (resolver downgrade gates — the tracking- # issue's 3.50.4 WAL caveat).- from tests.conformance.persistence._harness import force_journal_mode-- effective = force_journal_mode(db_path, requested_mode)- if effective.upper() != requested_mode.upper():- pytest.skip(- f"journal_mode={requested_mode} not deployable here "- f"(got {effective})"- )-- child = spawn_child(WRITER.format(db_path=str(db_path), journal=str(journal)))+ # Steer the CHILD's own resolver via an isolated HERMES_HOME config:+ # pre-seeding the file alone is not enough — SessionDB.__init__ runs+ # apply_wal_with_fallback(), which upgrades a non-WAL file to WAL+ # whenever the configured mode says so (the resolver's downgrade+ # gates may still refuse; effective_mode_or_skip audits post-run).+ child_env["HERMES_HOME"] = str(+ make_hermes_home(tmp_path, requested_mode.lower())+ )++ child = spawn_child(+ WRITER.format(db_path=str(db_path), journal=str(journal)), env=child_env+ )try:wait_for(lambda: len(_acknowledged(journal)) >= 200,what=">=200 acknowledged appends",+ child=child,)# The kill must interrupt a LIVE writer — a child that already# exited would turn this into a clean-shutdown test.assert child.poll() is None, (f"writer exited early (rc={child.returncode}): "- f"{child.stderr.read().decode(errors='replace')[-1500:]}"+ f"{(child.stderr.read() if child.stderr else b'').decode(errors='replace')[-1500:]}")finally:kill9_and_reap(child)- mode = on_disk_journal_mode(db_path)+ # A leg that ran in a different mode than requested is no evidence for+ # the requested mode — skip it rather than silently double-counting WAL.+ mode = effective_mode_or_skip(db_path, requested_mode)acked = _acknowledged(journal)- assert len(acked) >= 200+ assert len(acked) >= 200, (+ f"[journal_mode={mode}] only {len(acked)} acknowledged appends "+ "journaled before the kill — harness window too small"+ )pass1 = _recover(db_path)pass2 = _recover(db_path)diff --git a/tests/conformance/persistence/test_cell2_consume_once.py b/tests/conformance/persistence/test_cell2_consume_once.pyindex 84694475945..37473221757 100644--- a/tests/conformance/persistence/test_cell2_consume_once.py+++ b/tests/conformance/persistence/test_cell2_consume_once.py@@ -13,8 +13,6 @@ each calls ``SessionDB.claim_handoff()`` on the same pending session.from __future__ import annotations-from pathlib import Path-from tests.conformance.persistence._harness import (on_disk_journal_mode,reap,@@ -40,7 +38,10 @@ while not barrier.exists():db = SessionDB(db_path=db_path)won = db.claim_handoff("cell2")-sys.exit(0 if won else 1)+# Disjoint codes: 0=won, 10=lost. An unhandled exception exits 1, which must+# NEVER be confusable with a clean "lost the claim" — a run where one+# claimant wins and seven CRASH is not a consume-once proof.+sys.exit(0 if won else 10)"""N_CLAIMANTS = 8@@ -80,7 +81,7 @@ def test_exactly_one_claimant_wins(tmp_path):mode = on_disk_journal_mode(db_path)codes = [rc for rc, _, _ in results]- assert all(rc in (0, 1) for rc in codes), (+ assert all(rc in (0, 10) for rc in codes), (f"[journal_mode={mode}] claimant crashed/timed out: {codes}; "f"stderr: {[e[-300:] for _, _, e in results if e]}")diff --git a/tests/conformance/persistence/test_cell3_rotation_atomicity.py b/tests/conformance/persistence/test_cell3_rotation_atomicity.pyindex 926b9b998f4..a8a700ddeb5 100644--- a/tests/conformance/persistence/test_cell3_rotation_atomicity.py+++ b/tests/conformance/persistence/test_cell3_rotation_atomicity.py@@ -25,9 +25,10 @@ from pathlib import Pathimport pytestfrom tests.conformance.persistence._harness import (+ effective_mode_or_skip,integrity_ok,kill9_and_reap,- on_disk_journal_mode,+ make_hermes_home,spawn_child,wait_for,)@@ -81,32 +82,41 @@ def test_rotation_is_atomic_under_sigkill(tmp_path, requested_mode):db_path = tmp_path / "state.db"journal = tmp_path / "rotations.jsonl"+ child_env = {}if requested_mode is not None:- from tests.conformance.persistence._harness import force_journal_mode-- effective = force_journal_mode(db_path, requested_mode)- if effective.upper() != requested_mode.upper():- pytest.skip(- f"journal_mode={requested_mode} not deployable here "- f"(got {effective})"- )+ # Steer the CHILD's own resolver via an isolated HERMES_HOME config:+ # pre-seeding the file alone is not enough — SessionDB.__init__ runs+ # apply_wal_with_fallback(), which upgrades a non-WAL file to WAL+ # whenever the configured mode says so (the resolver's downgrade+ # gates may still refuse; effective_mode_or_skip audits post-run).+ child_env["HERMES_HOME"] = str(+ make_hermes_home(tmp_path, requested_mode.lower())+ )- child = spawn_child(ROTATOR.format(db_path=str(db_path), journal=str(journal)))+ child = spawn_child(+ ROTATOR.format(db_path=str(db_path), journal=str(journal)), env=child_env+ )try:wait_for(lambda: _completed_rotations(journal) >= 50,what=">=50 completed rotations",+ child=child,)assert child.poll() is None, (f"rotator exited early (rc={child.returncode}): "- f"{child.stderr.read().decode(errors='replace')[-1500:]}"+ f"{(child.stderr.read() if child.stderr else b'').decode(errors='replace')[-1500:]}")finally:kill9_and_reap(child)- mode = on_disk_journal_mode(db_path)+ # A leg that ran in a different mode than requested is no evidence for+ # the requested mode — skip it rather than silently double-counting WAL.+ mode = effective_mode_or_skip(db_path, requested_mode)acked = _completed_rotations(journal)- assert acked >= 50+ assert acked >= 50, (+ f"[journal_mode={mode}] only {acked} rotations acknowledged before "+ "the kill — harness window too small"+ )conn = sqlite3.connect(str(db_path))try: