The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): make state.db synchronous configurable on every platform
Jack Lauef29fc63d726
diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 8c5ef5bc7aa..e9d26f4c152 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -17,6 +17,14 @@ database:# Optional WAL sizing pragmas (integers). Unset = SQLite defaults.# wal_autocheckpoint: 1000 # pages between automatic checkpoints# journal_size_limit: 67108864 # cap the WAL/journal file size in bytes+ #+ # Durability level for every state.db connection: OFF, NORMAL, FULL, EXTRA+ # (or 0-3). Unset leaves SQLite's default, which is baked in at compile time+ # (SQLITE_DEFAULT_WAL_SYNCHRONOUS) and therefore differs between the bundled+ # interpreter, a distro python3 and a Homebrew one. Set it if you need to+ # know which one you are running rather than infer it. macOS is always held+ # at FULL regardless: Darwin's fsync() does not guarantee write ordering.+ # synchronous: FULL# =============================================================================# Runtime Limitsdiff --git a/hermes_state.py b/hermes_state.pyindex 9d016438a9f..8b00bc3d120 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -1596,6 +1596,91 @@ def _log_configured_delete_overridden_once(db_label: str) -> None:# ---------------------------------------------------------------------------# Config-driven database pragmas# ---------------------------------------------------------------------------+# PRAGMA synchronous accepts either an integer or a symbolic name, and operators+# write the names. Mapped here rather than passed through so a typo becomes a+# warning instead of a silently different durability level.+_SYNCHRONOUS_LEVELS: Dict[str, int] = {+ "OFF": 0,+ "NORMAL": 1,+ "FULL": 2,+ "EXTRA": 3,+}+_SYNCHRONOUS_NAMES: Dict[int, str] = {v: k for k, v in _SYNCHRONOUS_LEVELS.items()}+_SYNCHRONOUS_FULL = 2+++def resolve_synchronous_level(raw_value: Any) -> Optional[int]:+ """Map a configured ``database.synchronous`` value to its PRAGMA integer.++ Accepts the symbolic names SQLite documents (``OFF``/``NORMAL``/``FULL``/+ ``EXTRA``, any case) and the equivalent integers ``0``-``3``. Returns None+ for anything else so the caller can warn and leave the level untouched —+ guessing at a malformed durability setting is worse than ignoring it.+ """+ if isinstance(raw_value, bool):+ # bool is an int subclass, and YAML turns a bare `on`/`off` into one.+ # "off" as a durability level is a real choice; True is meaningless.+ return 0 if raw_value is False else None+ if isinstance(raw_value, int):+ return raw_value if raw_value in _SYNCHRONOUS_NAMES else None+ text = str(raw_value).strip()+ if not text:+ return None+ upper = text.upper()+ if upper in _SYNCHRONOUS_LEVELS:+ return _SYNCHRONOUS_LEVELS[upper]+ try:+ value = int(text)+ except (TypeError, ValueError):+ return None+ return value if value in _SYNCHRONOUS_NAMES else None+++def _apply_synchronous_pragma(+ conn: sqlite3.Connection,+ raw_value: Any,+ *,+ db_label: str,+) -> None:+ """Set ``PRAGMA synchronous`` from config, never below FULL on macOS.++ Split out of the integer loop in :func:`apply_database_pragmas` because+ this PRAGMA is not interchangeable with the sizing ones around it. Those+ trade memory or disk for speed; this one decides whether a commit is on+ the platter, so an unrecognised value must not fall through to "SQLite+ default" the way a bad ``cache_size`` harmlessly can.++ The Darwin floor exists because :func:`_enforce_macos_synchronous_full`+ runs during ``apply_wal_with_fallback()`` and this function runs after it,+ so a configured ``NORMAL`` would otherwise silently undo the macOS btree+ protection that fix put there deliberately. Raising the level on macOS is+ allowed; lowering it is refused out loud.+ """+ level = resolve_synchronous_level(raw_value)+ if level is None:+ logger.warning(+ "%s: ignoring unrecognized database.synchronous=%r "+ "(expected OFF, NORMAL, FULL, EXTRA, or 0-3)",+ db_label,+ raw_value,+ )+ return+ if sys.platform == "darwin" and level < _SYNCHRONOUS_FULL:+ logger.warning(+ "%s: refusing database.synchronous=%s on macOS; keeping FULL. "+ "Darwin's fsync() does not guarantee write ordering, so a lower "+ "level readmits the half-written btree pages FULL exists to "+ "prevent.",+ db_label,+ _SYNCHRONOUS_NAMES[level],+ )+ return+ try:+ conn.execute(f"PRAGMA synchronous={level}")+ except sqlite3.OperationalError:+ pass++def apply_database_pragmas(conn: sqlite3.Connection,*,@@ -1618,6 +1703,11 @@ def apply_database_pragmas(* ``temp_store`` — 0=DEFAULT(file), 1=FILE, 2=MEMORY, 3=ALWAYS* ``wal_autocheckpoint`` — WAL auto-checkpoint threshold in pages* ``journal_size_limit`` — max journal/WAL size in bytes+ * ``synchronous`` — durability level: ``OFF``/``NORMAL``/``FULL``/``EXTRA``+ or ``0``-``3``. Unset leaves SQLite's own default, which is a+ *compile-time* constant (``SQLITE_DEFAULT_WAL_SYNCHRONOUS``) and so+ differs between the bundled, distro and Homebrew builds an operator+ might be running. Setting it explicitly is the only way to know.Best-effort: config load or pragma failures are ignored so DB initnever breaks on a malformed ``database:`` section.@@ -1657,6 +1747,14 @@ def apply_database_pragmas(except sqlite3.OperationalError:pass+ # Last, so it wins over nothing and loses to nothing: the sizing pragmas+ # above cannot change durability, and the macOS enforcement ran earlier+ # during WAL activation (see _apply_synchronous_pragma for why that+ # ordering needs an explicit floor rather than an explicit override).+ raw_synchronous = cfg_get(cfg, "database", "synchronous", default=None)+ if raw_synchronous is not None:+ _apply_synchronous_pragma(conn, raw_synchronous, db_label=db_label)+# ---------------------------------------------------------------------------# Malformed-schema recoverydiff --git a/tests/test_state_synchronous_pragma.py b/tests/test_state_synchronous_pragma.pynew file mode 100644index 00000000000..d903a6500b6--- /dev/null+++ b/tests/test_state_synchronous_pragma.py@@ -0,0 +1,228 @@+"""``database.synchronous`` is configurable, validated, and floored on macOS.++Before this, `apply_database_pragmas()` accepted five sizing pragmas and no+durability one, and `_enforce_macos_synchronous_full()` returned early off+Darwin. So on Linux and Windows nothing in the process ever executed+`PRAGMA synchronous` against state.db, and the effective level was whichever+`SQLITE_DEFAULT_WAL_SYNCHRONOUS` the interpreter's SQLite happened to be+compiled with -- invisible from config, unpinnable, and different between+builds. See #90837, where three weeks of corruption forensics were carried out+under the stated assumption of `synchronous=FULL` on Ubuntu.+"""++import sqlite3+import sys++import pytest++import hermes_state+from hermes_state import (+ apply_database_pragmas,+ resolve_synchronous_level,+)+++def _wal_conn(tmp_path):+ conn = sqlite3.connect(str(tmp_path / "state.db"), isolation_level=None)+ conn.execute("PRAGMA journal_mode=WAL")+ return conn+++def _level(conn):+ return conn.execute("PRAGMA synchronous").fetchone()[0]+++def _config(monkeypatch, database_section):+ """Point apply_database_pragmas at an in-memory config.++ It imports `hermes_cli.config` lazily inside the function body, so the+ patch has to land on that module rather than on a name in this one.+ """+ import hermes_cli.config as config_mod++ cfg = {"database": database_section}+ monkeypatch.setattr(config_mod, "load_config_readonly", lambda *a, **k: cfg)+ return cfg+++class TestResolveSynchronousLevel:+ """The parser, in isolation -- a wrong answer here is a silent downgrade."""++ @pytest.mark.parametrize(+ "raw,expected",+ [+ ("OFF", 0),+ ("NORMAL", 1),+ ("FULL", 2),+ ("EXTRA", 3),+ ("full", 2),+ ("Full", 2),+ (" FULL ", 2),+ (0, 0),+ (1, 1),+ (2, 2),+ (3, 3),+ ("2", 2),+ (" 2 ", 2),+ ],+ )+ def test_accepts_documented_spellings(self, raw, expected):+ assert resolve_synchronous_level(raw) == expected++ @pytest.mark.parametrize(+ "raw",+ [+ "PARANOID",+ "",+ " ",+ 4,+ -1,+ "4",+ None,+ [],+ {},+ 2.5,+ "2.0",+ ],+ )+ def test_rejects_everything_else(self, raw):+ assert resolve_synchronous_level(raw) is None++ def test_yaml_off_is_a_level_but_yaml_on_is_not(self):+ """`synchronous: off` is bool False in YAML and means OFF.++ `synchronous: on` is bool True and means nothing -- there is no+ durability level it could map to, so it must be rejected rather than+ coerced to 1 by int(True).+ """+ assert resolve_synchronous_level(False) == 0+ assert resolve_synchronous_level(True) is None+++class TestAppliedFromConfig:+ def test_configured_level_reaches_the_connection(self, tmp_path, monkeypatch):+ _config(monkeypatch, {"synchronous": "NORMAL"})+ conn = _wal_conn(tmp_path)+ try:+ monkeypatch.setattr(sys, "platform", "linux")+ apply_database_pragmas(conn, db_label="state.db")+ assert _level(conn) == 1+ finally:+ conn.close()++ def test_full_reaches_the_connection(self, tmp_path, monkeypatch):+ """The #90837 case: an operator asking for FULL on Linux gets FULL.++ Fails without the patch -- the pragma was never executed at all, so the+ connection kept whatever the build's default was.+ """+ _config(monkeypatch, {"synchronous": "FULL"})+ conn = _wal_conn(tmp_path)+ try:+ monkeypatch.setattr(sys, "platform", "linux")+ conn.execute("PRAGMA synchronous=0")+ assert _level(conn) == 0+ apply_database_pragmas(conn, db_label="state.db")+ assert _level(conn) == 2+ finally:+ conn.close()++ def test_unset_leaves_the_level_alone(self, tmp_path, monkeypatch):+ """No config key must mean no write -- this is the default path."""+ _config(monkeypatch, {"wal_autocheckpoint": 1000})+ conn = _wal_conn(tmp_path)+ try:+ monkeypatch.setattr(sys, "platform", "linux")+ conn.execute("PRAGMA synchronous=0")+ apply_database_pragmas(conn, db_label="state.db")+ assert _level(conn) == 0+ assert conn.execute("PRAGMA wal_autocheckpoint").fetchone()[0] == 1000+ finally:+ conn.close()++ def test_garbage_warns_and_changes_nothing(self, tmp_path, monkeypatch, caplog):+ """A typo must not fall through to a different durability level."""+ _config(monkeypatch, {"synchronous": "PARANOID"})+ conn = _wal_conn(tmp_path)+ try:+ monkeypatch.setattr(sys, "platform", "linux")+ conn.execute("PRAGMA synchronous=2")+ with caplog.at_level("WARNING"):+ apply_database_pragmas(conn, db_label="state.db")+ assert _level(conn) == 2+ assert "PARANOID" in caplog.text+ finally:+ conn.close()++ def test_the_other_pragmas_still_apply(self, tmp_path, monkeypatch):+ """Guardrail for #77630's five keys -- they share the same function."""+ _config(+ monkeypatch,+ {"synchronous": "FULL", "wal_autocheckpoint": 250, "mmap_size": 0},+ )+ conn = _wal_conn(tmp_path)+ try:+ monkeypatch.setattr(sys, "platform", "linux")+ apply_database_pragmas(conn, db_label="state.db")+ assert _level(conn) == 2+ assert conn.execute("PRAGMA wal_autocheckpoint").fetchone()[0] == 250+ assert conn.execute("PRAGMA mmap_size").fetchone()[0] == 0+ finally:+ conn.close()+++class TestMacOSFloor:+ """#64355 enforced FULL on Darwin. Config must not be able to undo it.++ `_enforce_macos_synchronous_full()` runs inside `apply_wal_with_fallback()`,+ which is earlier than `apply_database_pragmas()`, so without an explicit+ floor the config value would simply win by running last.+ """++ def test_lowering_below_full_is_refused_on_darwin(+ self, tmp_path, monkeypatch, caplog+ ):+ _config(monkeypatch, {"synchronous": "NORMAL"})+ conn = _wal_conn(tmp_path)+ try:+ monkeypatch.setattr(sys, "platform", "darwin")+ hermes_state._enforce_macos_synchronous_full(conn)+ assert _level(conn) == 2+ with caplog.at_level("WARNING"):+ apply_database_pragmas(conn, db_label="state.db")+ assert _level(conn) == 2, "config lowered the macOS btree protection"+ assert "macOS" in caplog.text+ finally:+ conn.close()++ def test_raising_above_full_is_allowed_on_darwin(self, tmp_path, monkeypatch):+ """The floor is a floor, not a pin -- EXTRA is strictly safer."""+ _config(monkeypatch, {"synchronous": "EXTRA"})+ conn = _wal_conn(tmp_path)+ try:+ monkeypatch.setattr(sys, "platform", "darwin")+ apply_database_pragmas(conn, db_label="state.db")+ assert _level(conn) == 3+ finally:+ conn.close()++ def test_the_floor_does_not_apply_off_darwin(self, tmp_path, monkeypatch):+ """Linux operators may deliberately choose NORMAL for write volume."""+ _config(monkeypatch, {"synchronous": "NORMAL"})+ conn = _wal_conn(tmp_path)+ try:+ monkeypatch.setattr(sys, "platform", "linux")+ conn.execute("PRAGMA synchronous=2")+ apply_database_pragmas(conn, db_label="state.db")+ assert _level(conn) == 1+ finally:+ conn.close()+++def test_example_config_documents_the_key():+ """An unpinnable durability level is the bug; docs are half the fix."""+ from pathlib import Path++ text = Path(__file__).resolve().parents[1] / "cli-config.yaml.example"+ body = text.read_text(encoding="utf-8")+ assert "synchronous: FULL" in body