Skip to content

The agent that grows with you

fix: config watcher and config backups race conditions

Maciej Lisiewskic3ddf7563bff
diff --git a/hermes_cli/config_backups.py b/hermes_cli/config_backups.py
index a20a466f457..cc90cbb213f 100644
--- a/hermes_cli/config_backups.py
+++ b/hermes_cli/config_backups.py
@@ -10,7 +10,6 @@ for the same reason is skipped, and only the newest ``keep`` per reason survive,
from __future__ import annotations
-import filecmp
import logging
import shutil
import time
@@ -55,7 +54,9 @@ def backup_config(config_path: Path, reason: str, *, keep: int = DEFAULT_KEEP) -
root.mkdir(parents=True, exist_ok=True)
_sweep_legacy_siblings(config_path, root)
existing = list_config_backups(config_path, reason)
- if existing and filecmp.cmp(config_path, existing[0], shallow=False):
+ # Not filecmp.cmp: its process-wide cache keys on (size, mtime), so an equal-size edit
+ # within one mtime tick of an earlier comparison is reported identical and never backed up.
+ if existing and config_path.read_bytes() == existing[0].read_bytes():
return None
dest = root / f"{config_path.name}.{reason}.{time.strftime('%Y%m%d-%H%M%S')}"
if dest.is_symlink() or dest.exists(): # never write through a planted link
diff --git a/tests/hermes_cli/test_config_backups.py b/tests/hermes_cli/test_config_backups.py
index 468f4e7fc47..0ee2d235162 100644
--- a/tests/hermes_cli/test_config_backups.py
+++ b/tests/hermes_cli/test_config_backups.py
@@ -1,4 +1,5 @@
"""config.yaml backups: one dir, deduped, bounded — never a pile of siblings in HERMES_HOME."""
+import os
from pathlib import Path
from hermes_cli.config_backups import backup_config, list_config_backups
@@ -23,6 +24,24 @@ def test_repeat_backups_dedupe_and_rotate(tmp_path: Path, monkeypatch):
assert [p.name for p in tmp_path.iterdir() if p.is_file()] == ["config.yaml"]
+def test_same_size_edit_within_one_mtime_tick_is_still_backed_up(tmp_path: Path, monkeypatch):
+ # Coarse-timestamp filesystems leave an immediate rewrite with the old mtime; dedupe must
+ # compare content, not trust a (size, mtime) signature.
+ cfg = tmp_path / "config.yaml"
+ cfg.write_text("model: a\n")
+ stamps = iter(f"2026010100000{i}" for i in range(10))
+ monkeypatch.setattr("hermes_cli.config_backups.time.strftime", lambda _fmt: next(stamps))
+
+ assert backup_config(cfg, "pre-setup") is not None
+ assert backup_config(cfg, "pre-setup") is None
+ before = cfg.stat()
+ cfg.write_text("model: b\n")
+ os.utime(cfg, ns=(before.st_atime_ns, before.st_mtime_ns))
+
+ second = backup_config(cfg, "pre-setup")
+ assert second is not None and second.read_text() == "model: b\n"
+
+
def test_legacy_siblings_move_but_user_named_copies_stay(tmp_path: Path):
cfg = tmp_path / "config.yaml"
cfg.write_text("model: a\n")
diff --git a/tests/tui_gateway/test_change_watcher.py b/tests/tui_gateway/test_change_watcher.py
index 2c484deed6d..8e8feb3f049 100644
--- a/tests/tui_gateway/test_change_watcher.py
+++ b/tests/tui_gateway/test_change_watcher.py
@@ -290,6 +290,43 @@ def test_pairing_probe_reuses_live_profile_roots_until_the_profile_set_moves(wat
assert sorted(live_calls) == ["play", "work", "work"]
+def test_second_ledger_with_the_same_mtime_still_broadcasts_pairing_changed(watcher_home):
+ """Coarse-timestamp filesystems give two ledgers written in one tick the same mtime; a
+ newest-mtime signature cannot see the second one, so the badge for it never appears."""
+ home, events = watcher_home
+ store = home / "platforms" / "pairing"
+ store.mkdir(parents=True)
+ first = store / "telegram-pending.json"
+ first.write_text("{}", encoding="utf-8")
+ server._broadcast_watched_changes(now=0.0)
+
+ second = store / "discord-pending.json"
+ second.write_text("{}", encoding="utf-8")
+ pinned = first.stat().st_mtime_ns
+ os.utime(second, ns=(pinned, pinned))
+ server._broadcast_watched_changes(now=10.0)
+
+ assert events == [("pairing.changed", {})]
+
+
+def test_sibling_projects_db_write_in_the_same_mtime_tick_broadcasts(watcher_home, monkeypatch):
+ """One served profile's projects.db write that lands in the same timestamp tick as
+ another's must not be masked by a newest-mtime-across-homes signature."""
+ home, events = watcher_home
+ coder_home = home / "profiles" / "coder"
+ coder_home.mkdir(parents=True)
+ monkeypatch.setattr(server, "_served_profile_homes", {coder_home})
+ (home / "projects.db").write_text("x", encoding="utf-8")
+ server._broadcast_watched_changes(now=0.0)
+
+ (coder_home / "projects.db").write_text("x", encoding="utf-8")
+ pinned = (home / "projects.db").stat().st_mtime_ns
+ os.utime(coder_home / "projects.db", ns=(pinned, pinned))
+ server._broadcast_watched_changes(now=10.0)
+
+ assert ("projects.changed", {}) in events
+
+
def test_rate_limit_churn_does_not_broadcast_pairing_changed(watcher_home):
"""_rate_limits.json moves on every unauthorized DM, including ones that
produce no new row — signalling on it would refetch for nothing."""
diff --git a/tui_gateway/change_watcher.py b/tui_gateway/change_watcher.py
index 20f87ccfabd..866ff7371ea 100644
--- a/tui_gateway/change_watcher.py
+++ b/tui_gateway/change_watcher.py
@@ -63,6 +63,20 @@ def _newest_mtime_ns(paths) -> int | None:
return max((m for m in map(_watcher_mtime_ns, paths) if m is not None), default=None)
+def _files_sig(paths) -> tuple:
+ """Sorted ``(path, mtime_ns, size)`` per stat-able file in ``paths``.
+
+ For multi-file signatures, unlike a newest-mtime max: a file added, removed or rewritten in
+ the same timestamp tick as the current newest one (coarse-mtime filesystems) still moves it.
+ """
+ entries = []
+ for path in paths:
+ with contextlib.suppress(OSError):
+ st = path.stat()
+ entries.append((str(path), st.st_mtime_ns, st.st_size))
+ return tuple(sorted(entries))
+
+
def _skin_sig() -> tuple[str, float | None]:
"""(active skin name, its user-file mtime). Built-ins have no file, so only
their name moves; a user skin's mtime lets an in-place color edit repaint too."""
@@ -276,18 +290,18 @@ def _sessions_sig():
def _projects_sig():
- """Newest mtime across projects.db (+ WAL) for the watcher home and every served
+ """Per-file stat signature of projects.db (+ WAL) for the watcher home and every served
sibling profile. The CLI and other windows write projects.db directly — nothing in
their process touches this gateway's transports — so the file is the only shared
signal, exactly like state.db (#53046, #56757)."""
- return _newest_mtime_ns(
+ return _files_sig(
root / name
for root in (_watcher_home(), *_served_profile_homes)
for name in ("projects.db", "projects.db-wal"))
def _pairing_sig():
- """Newest mtime across every profile's pairing ledgers (legacy ``pairing/`` and
+ """Per-file stat signature of every profile's pairing ledgers (legacy ``pairing/`` and
``platforms/pairing/``): the gateway process writes pending codes, so the files are the only
shared signal (a pairing request moves nothing in gateway_state.json)."""
entries = []
@@ -296,7 +310,7 @@ def _pairing_sig():
# Only the ledgers: _rate_limits.json moves on every unauthorized DM.
entries += [
e for e in root.iterdir() if e.name.endswith(("-pending.json", "-approved.json"))]
- return _newest_mtime_ns(entries)
+ return _files_sig(entries)
# Live-profile pairing roots, cached on (home, ``profiles/`` dir mtime) with a TTL. The liveness