Skip to content

The agent that grows with you

fix(mcp): event bridge sees WAL commits and same-tick writes

Maciej Lisiewski791191517665
diff --git a/mcp_serve.py b/mcp_serve.py
index e64c1c85add..31a852a43e0 100644
--- a/mcp_serve.py
+++ b/mcp_serve.py
@@ -21,6 +21,8 @@ from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional
+from utils import file_signature, mtime_is_racy
+
logger = logging.getLogger("hermes.mcp_serve")
# mcp 2.0 removed `mcp.server.fastmcp`; `mcp.server.MCPServer` keeps the same
@@ -49,11 +51,24 @@ def _get_sessions_dir() -> Path:
return _hermes_home() / "sessions"
-def _read_state_db_mtime() -> float:
- try:
- return (_hermes_home() / "state.db").stat().st_mtime
- except OSError: # missing file included
- return 0.0
+def _read_state_db_sig() -> tuple:
+ """Per-file stat signature of state.db and its WAL. In WAL mode a commit lands in
+ state.db-wal and leaves state.db untouched until a checkpoint, so the main file alone misses it."""
+ entries = []
+ for name in ("state.db", "state.db-wal"):
+ try:
+ st = (_hermes_home() / name).stat()
+ except OSError: # missing file included
+ continue
+ entries.append((name, *file_signature(st)))
+ return tuple(entries)
+
+
+def _settled_state_db_sig(sig: tuple) -> Optional[tuple]:
+ """``sig``, or None (never equal to a read) while a file's mtime may still hide a same-tick commit."""
+ if any(mtime_is_racy(entry[1]) for entry in sig):
+ return None
+ return sig
def _read_json(path: Path):
@@ -275,7 +290,7 @@ class EventBridge:
self._thread: Optional[threading.Thread] = None
self._last_poll_timestamps: dict[str, float] = {} # session_key -> unix timestamp
self._pending_approvals: dict[str, dict] = {} # populated from events
- self._state_db_mtime: float = 0.0 # skip polling work when state.db is unchanged
+ self._state_db_sig: Optional[tuple] = () # skip polling work when state.db (+ WAL) is unchanged
self._cached_sessions_index: dict = {}
def start(self):
@@ -351,14 +366,14 @@ class EventBridge:
self._new_event.set()
def _establish_baseline(self) -> None:
- """Record per-session latest timestamps and the state.db mtime WITHOUT
+ """Record per-session latest timestamps and the state.db signature WITHOUT
emitting events. Only sessions existing now are baselined; later ones
default to last_seen=0.0 in _poll_once, so their first message is delivered."""
db = _get_session_db()
if not db:
return
try:
- self._state_db_mtime = _read_state_db_mtime()
+ self._state_db_sig = _settled_state_db_sig(_read_state_db_sig())
try:
self._cached_sessions_index = _load_sessions_index()
except Exception:
@@ -395,17 +410,17 @@ class EventBridge:
def _poll_once(self, db):
"""Check for new messages across all sessions.
- One state.db mtime check gates all work, making 200ms polling nearly free.
- The routing index lives in the same file as the messages, so a new
- conversation and its first message land under a single mtime change (no
+ One state.db (+ WAL) stat check gates all work, making 200ms polling nearly free.
+ The routing index lives in the same database as the messages, so a new
+ conversation and its first message land under a single signature change (no
dual-file race that could drop brand-new conversations).
See #8925, #9006.
"""
- db_mtime = _read_state_db_mtime()
- if db_mtime == self._state_db_mtime:
+ db_sig = _read_state_db_sig()
+ if db_sig == self._state_db_sig:
return
- self._state_db_mtime = db_mtime
+ self._state_db_sig = _settled_state_db_sig(db_sig)
# Refresh the index on every change tick: one indexed query, never lags messages.
self._cached_sessions_index = _load_sessions_index()
diff --git a/tests/test_mcp_serve.py b/tests/test_mcp_serve.py
index 9800baaf3b3..f4007424ffb 100644
--- a/tests/test_mcp_serve.py
+++ b/tests/test_mcp_serve.py
@@ -1043,8 +1043,14 @@ class TestEventBridgePollE2E:
conn.close()
return [dict(r) for r in rows]
+ # The index comes from sessions.json: a real SessionDB open would migrate this minimal
+ # DB and move its mtime between the polls.
+ monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: None)
db = TestDB()
bridge = mcp_serve.EventBridge()
+ # Files written within the racy-tick window are always re-read; settle them first.
+ settled = time.time_ns() - 60 * 1_000_000_000
+ os.utime(db_path, ns=(settled, settled))
# First poll — should process
bridge._poll_once(db)
@@ -1174,7 +1180,7 @@ class TestEventBridgePollE2E:
# Bridge has never seen this db state (mtime differs) and has an
# empty cached index — exactly the state after a new conversation's
# first write.
- bridge._state_db_mtime = 0.0
+ bridge._state_db_sig = ()
assert bridge._cached_sessions_index == {}
bridge._poll_once(DB())
@@ -1271,3 +1277,73 @@ class TestEventBridgePollE2E:
assert len(events) == 1
assert events[0]["session_key"] == "agent:main:telegram:dm:fresh"
assert events[0]["content"] == "hello after baseline"
+
+ def test_wal_commit_without_checkpoint_is_delivered(self, tmp_path, monkeypatch):
+ """A WAL-mode commit lands in state.db-wal; state.db's own mtime moves only at a
+ checkpoint, so a gate keyed on the main file alone kept new messages undelivered."""
+ import mcp_serve
+ from hermes_state import SessionDB
+
+ def commit_message(role, content, ts):
+ # Another process's connection: its commit lands in the WAL like a gateway turn's.
+ conn = sqlite3.connect(str(tmp_path / "state.db"))
+ with conn:
+ conn.execute("INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)",
+ ("s1", role, content, ts))
+ conn.close()
+
+ monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: SessionDB(tmp_path / "state.db"))
+ db = SessionDB(tmp_path / "state.db")
+ try:
+ db.create_session("s1", "telegram", session_key="agent:main:telegram:dm:wal",
+ chat_id="wal", chat_type="dm")
+ commit_message("user", "before baseline", 100.0)
+ bridge = mcp_serve.EventBridge()
+ bridge._establish_baseline()
+ # Settle every file, then let one poll record that settled signature.
+ settled = time.time_ns() - 60 * 1_000_000_000
+ for name in ("state.db", "state.db-wal"):
+ os.utime(tmp_path / name, ns=(settled, settled))
+ bridge._poll_once(db)
+ assert bridge.poll_events(after_cursor=0)["events"] == []
+
+ for i in range(5):
+ commit_message("assistant", f"reply {i} after baseline", 101.0 + i)
+ # No checkpoint ran: the main database file is untouched by these commits.
+ os.utime(tmp_path / "state.db", ns=(settled, settled))
+ bridge._poll_once(db)
+ finally:
+ db.close()
+
+ events = bridge.poll_events(after_cursor=0)["events"]
+ assert [e["content"] for e in events] == [f"reply {i} after baseline" for i in range(5)]
+
+ def test_commit_in_the_baseline_mtime_tick_is_delivered(self, tmp_path, monkeypatch):
+ """A commit in the same coarse mtime tick as the bridge's stat leaves the
+ database files' signature unchanged, so a fresh signature must not count as
+ 'nothing changed' (racily clean)."""
+ import mcp_serve
+
+ now = time.time_ns()
+ for name in ("state.db", "state.db-wal"):
+ (tmp_path / name).write_bytes(b"\0" * 4096)
+ os.utime(tmp_path / name, ns=(now, now))
+ monkeypatch.setattr(mcp_serve, "_load_sessions_index", lambda: {
+ "agent:main:telegram:dm:tick": {"session_id": "sid-tick", "platform": "telegram"},
+ })
+ store = [{"id": 1, "role": "user", "content": "before baseline", "timestamp": 100.0}]
+
+ class DB:
+ def get_messages(self, sid):
+ return list(store)
+
+ monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: DB())
+ bridge = mcp_serve.EventBridge()
+ bridge._establish_baseline()
+
+ # Committed within the baseline's mtime tick: no stat field the bridge reads moved.
+ store.append({"id": 2, "role": "assistant", "content": "same tick", "timestamp": 101.0})
+ bridge._poll_once(DB())
+
+ events = bridge.poll_events(after_cursor=0)["events"]
+ assert [e["content"] for e in events] == ["same tick"]
diff --git a/tui_gateway/change_watcher.py b/tui_gateway/change_watcher.py
index 866ff7371ea..734344f6764 100644
--- a/tui_gateway/change_watcher.py
+++ b/tui_gateway/change_watcher.py
@@ -198,7 +198,7 @@ _SESSION_SIGNATURE_FIELDS = (
)
# path -> (database/WAL mtime, session-table digest). The mtime guard keeps the
# normal 0.5 s watch pass stat-only; SQLite is read only after another process
-# actually commits (and for ``_RACY_MTIME_WINDOW_NS`` after it, see _settled_mtime).
+# actually commits (and for ``utils.RACY_MTIME_WINDOW_NS`` after it, see _settled_mtime).
_sessions_db_sig_cache: dict[str, tuple[object, tuple | None]] = {}
@@ -264,13 +264,13 @@ def _session_db_content_sig(db_path: Path):
# SQLite commits in place, so a commit landing in the tick of a read leaves the DB/WAL mtime unchanged.
# A digest read while the mtime is that fresh must not become a cache hit ("racily clean", as in git's
# index): it is cached under a key no mtime equals, so the next tick re-reads the rows.
-_RACY_MTIME_WINDOW_NS = 2_000_000_000
_RACY_MTIME = object()
def _settled_mtime(mtime):
"""``mtime`` when it is old enough to trust as a cache key, else a never-matching sentinel."""
- if mtime is None or time.time_ns() - mtime < _RACY_MTIME_WINDOW_NS:
+ from utils import mtime_is_racy # function-local: bodies are rebound onto server.py's globals
+ if mtime is None or mtime_is_racy(mtime):
return _RACY_MTIME
return mtime
diff --git a/utils.py b/utils.py
index 840def42736..095cbff16e2 100644
--- a/utils.py
+++ b/utils.py
@@ -49,6 +49,17 @@ def file_signature(st: os.stat_result) -> tuple[int, int, int, int]:
return (st.st_mtime_ns, st.st_size, st.st_ino, st.st_ctime_ns)
+# Filesystem timestamps tick coarsely (~4 ms; whole seconds on some filesystems), so a write in the
+# same tick as a stat leaves the signature unchanged. A signature this fresh is "racily clean" (as in
+# git's index) and must not be trusted as "nothing changed since".
+RACY_MTIME_WINDOW_NS = 2_000_000_000
+
+
+def mtime_is_racy(mtime_ns: int) -> bool:
+ """True while ``mtime_ns`` is too recent to rule out a same-tick write after the stat."""
+ return time.time_ns() - mtime_ns < RACY_MTIME_WINDOW_NS
+
+
def _preserve_file_mode(path: Path) -> int | None:
"""Permission bits of *path* if it exists, else ``None``."""
try: