Skip to content

The agent that grows with you

fix(sessions): make set-journal-mode portable and fail closed where it cannot prove quiescence

teknium112fb5eb4761a
diff --git a/hermes_cli/sessions_cmd_journal_mode.py b/hermes_cli/sessions_cmd_journal_mode.py
index 4c9585d9837..9eabdf6bb96 100644
--- a/hermes_cli/sessions_cmd_journal_mode.py
+++ b/hermes_cli/sessions_cmd_journal_mode.py
@@ -9,40 +9,69 @@ ANY foreign process holds the file or a sidecar (``foreign_state_db_holders``),
"""
from __future__ import annotations
-import os
import sqlite3
+import sys
from pathlib import Path
+from typing import Optional
# SQLite file header: bytes 18 (write version) / 19 (read version) are 1 for rollback-journal, 2 for WAL.
_HEADER_VERSION_BYTES = {"delete": (1, 1), "wal": (2, 2)}
+_MODE_BY_HEADER_VERSION = {v: k for k, v in _HEADER_VERSION_BYTES.items()}
def _header_mode(db_path: Path) -> str:
"""Journal mode as the on-disk header reports it (no SQLite connection is open in this process here)."""
- fd = os.open(db_path, os.O_RDONLY)
- try:
- head = os.pread(fd, 20, 0)
- finally:
- os.close(fd)
+ with open(db_path, "rb") as fh:
+ head = fh.read(20)
if len(head) < 20 or head[:16] != b"SQLite format 3\x00":
return "not-a-database"
- return {(1, 1): "delete", (2, 2): "wal"}.get((head[18], head[19]), f"unknown({head[18]}/{head[19]})")
+ return _MODE_BY_HEADER_VERSION.get((head[18], head[19]), f"unknown({head[18]}/{head[19]})")
+
+
+def _refusal(target: str, current: str, platform: str, *, on_cross_vm_fs: bool, force: bool) -> Optional[str]:
+ """Admission checks that need no I/O, with the platform passed as data so tests need not fake the host."""
+ if current == "not-a-database" or current.startswith("unknown("):
+ return (f"its file header reads {current}, so it is not a Hermes SQLite store this command can convert "
+ "(pass --db PATH to point at one).")
+ if target == "wal" and on_cross_vm_fs:
+ return ("WAL shared memory silently corrupts on cross-VM filesystems (virtiofs/9p — Docker Desktop, "
+ "OrbStack, Lima bind mounts). Keep this store on journal_mode=delete or move it to a native "
+ "filesystem.")
+ if platform == "win32" and not force:
+ # foreign_state_db_holders() has no Windows scan and returns [] there: an empty holder list is
+ # "unknown", never "nobody holds it", so the gate must refuse rather than issue a silent all-clear.
+ return ("cannot prove the database is quiet on Windows — no holder scan. Stop the gateway, dashboard, "
+ "cron and every CLI, then re-run with --force.")
+ return None
def cmd_set_journal_mode(args) -> int:
- from hermes_state import DEFAULT_DB_PATH
+ from hermes_state import _default_db_path
from hermes_state_holders import describe_holder_pid, foreign_state_db_holders
- from hermes_state_wal import _set_journal_mode_no_wait, is_sqlite_wal_reset_vulnerable, resolve_journal_mode
+ from hermes_state_wal import (_path_on_cross_vm_fs, _set_journal_mode_no_wait, is_sqlite_wal_reset_vulnerable,
+ resolve_journal_mode)
target = args.mode
- db_path = Path(getattr(args, "db", None) or DEFAULT_DB_PATH)
+ db_path = Path(getattr(args, "db", None) or _default_db_path())
if not db_path.exists():
print(f"No database at {db_path} (nothing to convert).")
return 1
- current = _header_mode(db_path)
+ try:
+ current = _header_mode(db_path)
+ except OSError as exc:
+ print(f"✗ Cannot read {db_path}: {exc}")
+ return 1
if current == target:
print(f"✓ {db_path} is already journal_mode={target}.")
return 0
+ refusal = _refusal(
+ target, current, sys.platform,
+ on_cross_vm_fs=target == "wal" and _path_on_cross_vm_fs(str(db_path)),
+ force=bool(getattr(args, "force", False)),
+ )
+ if refusal:
+ print(f"✗ Refusing to change the journal mode of {db_path}: {refusal}")
+ return 1
if target == "wal" and is_sqlite_wal_reset_vulnerable():
print(f"✗ Refusing to enable WAL: the linked SQLite {sqlite3.sqlite_version} has the WAL-reset bug "
"(https://sqlite.org/wal.html#walresetbug). Upgrade to 3.51.3+ first.")
@@ -56,7 +85,11 @@ def cmd_set_journal_mode(args) -> int:
return 1
# timeout=0: any opener that appeared between the scan and the flip makes the pragma fail with
# 'database is locked' instead of sneaking the switch between a writer's transactions.
- conn = sqlite3.connect(str(db_path), timeout=0.0, isolation_level=None)
+ try:
+ conn = sqlite3.connect(str(db_path), timeout=0.0, isolation_level=None)
+ except (OSError, sqlite3.Error) as exc:
+ print(f"✗ Cannot open {db_path}: {exc}")
+ return 1
try:
try:
reported = _set_journal_mode_no_wait(conn, target.upper())
@@ -65,7 +98,11 @@ def cmd_set_journal_mode(args) -> int:
return 1
finally:
conn.close()
- after = _header_mode(db_path)
+ try:
+ after = _header_mode(db_path)
+ except OSError as exc:
+ print(f"✗ Cannot re-read {db_path} after the switch: {exc}")
+ return 1
if after != target:
print(f"✗ SQLite reported journal_mode={reported or '?'} but the file header reads {after}; not converted.")
return 1
diff --git a/hermes_cli/subcommands/sessions.py b/hermes_cli/subcommands/sessions.py
index b83b2a54b8c..d3d26390d14 100644
--- a/hermes_cli/subcommands/sessions.py
+++ b/hermes_cli/subcommands/sessions.py
@@ -178,6 +178,9 @@ def build_sessions_parser(subparsers, *, cmd_sessions: Callable) -> None:
sessions_set_journal_mode.add_argument("mode", choices=("delete", "wal"), help="Target journal mode")
sessions_set_journal_mode.add_argument("--db", default=None, metavar="PATH",
help="Convert another Hermes SQLite store (e.g. kanban.db) instead of the profile's state.db")
+ _flag(sessions_set_journal_mode, "--force",
+ help="Windows only: proceed without the holder scan (which does not exist there) after stopping "
+ "every Hermes process yourself")
sessions_repair_routing = sessions_subparsers.add_parser(
"repair-routing", help="Re-stamp gateway sessions that lost their routing identity",
diff --git a/tests/hermes_cli/test_sessions_set_journal_mode.py b/tests/hermes_cli/test_sessions_set_journal_mode.py
index 8fbbf27db59..44588a13b21 100644
--- a/tests/hermes_cli/test_sessions_set_journal_mode.py
+++ b/tests/hermes_cli/test_sessions_set_journal_mode.py
@@ -2,7 +2,7 @@
#100896 (@ruangraung): `database.journal_mode: delete` never self-applies to a store that is already WAL because
open never live-downgrades; this command is the sanctioned offline path and must fail closed while any other
-process holds the file.
+process holds the file — or while it cannot prove the file is quiet at all.
"""
import argparse
import sqlite3
@@ -13,6 +13,7 @@ import time
import pytest
from hermes_cli.sessions_cmd import cmd_sessions
+from hermes_cli.sessions_cmd_journal_mode import _refusal
def _wal_store(path):
@@ -24,11 +25,12 @@ def _wal_store(path):
assert path.read_bytes()[18:20] == b"\x02\x02"
-def _args(mode):
- return argparse.Namespace(sessions_action="set-journal-mode", mode=mode, db=None)
+def _args(mode, db=None, force=True):
+ # --force only waives the Windows "no holder scan" refusal; on POSIX the scan still gates the flip,
+ # so passing it keeps the happy path exercised on every lane including windows-latest.
+ return argparse.Namespace(sessions_action="set-journal-mode", mode=mode, db=db, force=force)
[email protected](sys.platform == "win32", reason="holder scan and header probe are POSIX-only")
def test_set_journal_mode_converts_wal_store_offline(tmp_path, monkeypatch, capsys):
db = tmp_path / "state.db"
_wal_store(db)
@@ -45,7 +47,8 @@ def test_set_journal_mode_converts_wal_store_offline(tmp_path, monkeypatch, caps
assert "wal → delete" in capsys.readouterr().out
[email protected](sys.platform == "win32", reason="holder scan is POSIX-only")
[email protected](sys.platform == "win32",
+ reason="foreign_state_db_holders has no Windows scan; the --force refusal covers that lane")
def test_set_journal_mode_refuses_while_another_process_holds_the_store(tmp_path, monkeypatch, capsys):
db = tmp_path / "state.db"
_wal_store(db)
@@ -59,7 +62,7 @@ def test_set_journal_mode_refuses_while_another_process_holds_the_store(tmp_path
deadline = time.monotonic() + 10
while time.monotonic() < deadline and not (tmp_path / "state.db-shm").exists():
time.sleep(0.05)
- assert cmd_sessions(_args("delete")) == 1
+ assert cmd_sessions(_args("delete", force=False)) == 1
finally:
holder.kill()
holder.wait()
@@ -67,3 +70,38 @@ def test_set_journal_mode_refuses_while_another_process_holds_the_store(tmp_path
out = capsys.readouterr().out
assert f"pid {holder.pid}" in out
assert db.read_bytes()[18:20] == b"\x02\x02", "a refused switch must leave the file untouched"
+
+
[email protected]("target,current,platform,cross_vm,force,expected", [
+ # Windows has no holder scan (foreign_state_db_holders returns []): an empty list must never read
+ # as "nobody holds it", so the gate refuses instead of issuing a silent all-clear.
+ ("delete", "wal", "win32", False, False, "no holder scan"),
+ ("delete", "wal", "win32", False, True, None),
+ ("delete", "wal", "linux", False, False, None),
+ # WAL shared memory corrupts on virtiofs/9p, so ENABLING it there is refused, --force or not.
+ ("wal", "delete", "linux", True, False, "cross-VM filesystems"),
+ ("wal", "delete", "win32", True, True, "cross-VM filesystems"),
+ ("delete", "wal", "linux", True, False, None),
+ # A garbage or unrecognised header is reported, never handed to sqlite3 for a raw traceback.
+ ("delete", "not-a-database", "linux", False, False, "not a Hermes SQLite store"),
+ ("delete", "unknown(3/3)", "linux", False, True, "not a Hermes SQLite store"),
+])
+def test_refusal_admission_invariants(target, current, platform, cross_vm, force, expected):
+ reason = _refusal(target, current, platform, on_cross_vm_fs=cross_vm, force=force)
+ if expected is None:
+ assert reason is None
+ else:
+ assert reason is not None and expected in reason
+
+
[email protected]("kind", ["garbage-file", "directory"])
+def test_set_journal_mode_reports_unusable_db_paths_without_a_traceback(kind, tmp_path, capsys):
+ if kind == "garbage-file":
+ bad = tmp_path / "notes.txt"
+ bad.write_bytes(b"this is not a database, not even close\n")
+ else:
+ bad = tmp_path / "a-directory"
+ bad.mkdir()
+
+ assert cmd_sessions(_args("delete", db=str(bad))) == 1
+ assert "✗" in capsys.readouterr().out
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index e02cc54bcd3..efc8e0e5086 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -721,7 +721,12 @@ holds the file or its `-wal`/`-shm` sidecars, switches the mode without
waiting out openers (a holder that appears mid-way makes SQLite refuse instead
of racing it), and verifies the file header reports the new mode. It reminds
you to set `database.journal_mode` to the same value when the config disagrees,
-because the next open re-applies the configured mode.
+because the next open re-applies the configured mode. The holder scan is local
+and POSIX-only, so it cannot see a process in another container or VM sharing
+the volume, and on Windows there is no scan at all — the command refuses there
+outright unless you pass `--force` after stopping every Hermes process
+yourself. Enabling WAL is also refused when the store sits on a cross-VM
+filesystem (virtiofs/9p), where WAL shared memory corrupts silently.
## Importing Sessions from Claude Code and Codex CLI