Skip to content

The agent that grows with you

perf(gateway): the roster poll reuses a profile's session fields while its store has not moved

John Paul Soliva8889060bbf22
diff --git a/tests/tui_gateway/test_profiles_list_session_field_cache.py b/tests/tui_gateway/test_profiles_list_session_field_cache.py
new file mode 100644
index 00000000000..af2751cbaf3
--- /dev/null
+++ b/tests/tui_gateway/test_profiles_list_session_field_cache.py
@@ -0,0 +1,119 @@
+"""``profiles.list`` reuses a profile's session fields only while its session store has not moved.
+
+The Bots roster polls this every 5s per connection and the session fields are a pure function of
+the profile's ``state.db``, so an idle fleet re-opened every bot's store every five seconds. The
+memo must be invisible: a write anywhere in the store has to show up on the very next poll, or the
+roster silently paints a stale preview.
+"""
+from __future__ import annotations
+
+import pytest
+
+import tui_gateway.server as srv
+from hermes_state import SessionDB
+from tui_gateway import profile_roster_cache as cache
+
+
[email protected](autouse=True)
+def _clean_memo():
+ cache.invalidate()
+ yield
+ cache.invalidate()
+
+
+def home(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "profiles" / "bob").mkdir(parents=True)
+ return tmp_path
+
+
+def _seed(profile_dir, session_id: str, title: str, text: str = "hello") -> None:
+ db = SessionDB(db_path=profile_dir / "state.db")
+ try:
+ db.create_session(session_id=session_id, source="cli")
+ db.set_session_title(session_id, title)
+ db.append_message(session_id=session_id, role="user", content=text)
+ finally:
+ db.close()
+
+
+def _rows(params=None):
+ return srv._methods["profiles.list"](1, params or {})["result"]["profiles"]
+
+
+def _row(name):
+ return next(p for p in _rows() if p["name"] == name)
+
+
+def test_a_new_session_shows_up_on_the_very_next_poll(home):
+ bob = home / "profiles" / "bob"
+ _seed(bob, "20260920_000001_a", "first chat")
+ assert _row("bob")["last_session"]["title"] == "first chat"
+
+ _seed(bob, "20260920_000002_b", "second chat")
+
+ # The memo keys on the store's signature, so this must not be the cached answer.
+ assert _row("bob")["last_session"]["title"] == "second chat"
+
+
+def test_a_message_appended_to_an_existing_session_is_not_masked(home):
+ bob = home / "profiles" / "bob"
+ _seed(bob, "20260920_000001_a", "Bot Chat", text="first")
+ before = _row("bob")["canonical_session"]
+
+ db = SessionDB(db_path=bob / "state.db")
+ try:
+ db.append_message(session_id="20260920_000001_a", role="assistant", content="a later reply")
+ finally:
+ db.close()
+
+ after = _row("bob")["canonical_session"]
+ assert after != before, "an append inside the store was served from the memo"
+
+
+def test_a_profile_without_a_store_is_not_memoised_and_picks_one_up(home):
+ bare = home / "profiles" / "bare"
+ bare.mkdir()
+ (bare / "config.yaml").write_text("model:\n provider: openai\n", encoding="utf-8")
+ assert _row("bare")["last_session"] is None
+ assert cache.store_signature(bare) is None # nothing to key on, so nothing is cached
+
+ _seed(bare, "20260920_000003_c", "now it exists")
+
+ assert _row("bare")["last_session"]["title"] == "now it exists"
+
+
+def test_one_profile_s_rows_never_answer_for_another(home):
+ bob, ann = home / "profiles" / "bob", home / "profiles" / "ann"
+ ann.mkdir()
+ _seed(bob, "20260920_000001_a", "bob's chat")
+ _seed(ann, "20260920_000002_b", "ann's chat")
+
+ rows = {p["name"]: p for p in _rows()}
+
+ assert rows["bob"]["last_session"]["title"] == "bob's chat"
+ assert rows["ann"]["last_session"]["title"] == "ann's chat"
+
+
+def test_an_unchanged_store_is_read_once_across_repeated_polls(home, monkeypatch):
+ """The saving itself: the 5s poll stops reopening a store that has not moved."""
+ bob = home / "profiles" / "bob"
+ _seed(bob, "20260920_000001_a", "steady")
+
+ opens: list = []
+ real = SessionDB
+
+ def _counting(*args, **kwargs):
+ opens.append(kwargs.get("db_path"))
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr("hermes_state.SessionDB", _counting)
+
+ _rows()
+ after_first = len(opens)
+ _rows()
+ _rows()
+
+ assert after_first >= 1, "the first poll must actually read the store"
+ assert len(opens) == after_first, "an unchanged store was reopened by a later poll"
diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.py
index 54b1c1525df..272f9bbe10c 100644
--- a/tui_gateway/methods_profiles.py
+++ b/tui_gateway/methods_profiles.py
@@ -217,17 +217,25 @@ def _profile_session_fields(row, profile_path):
"""Attach last_session / worker_session / canonical_session to a roster row. The DB is a
read-only attach (a writable ``SessionDB()`` waits up to 20s for the write lock + runs DDL
and stalled the 5s roster poll); no/unreadable DB -> every field None (the readers swallow)."""
- db_path = Path(profile_path) / "state.db"
- db = None
- if _try(db_path.exists, False):
- db = _try(lambda: _lazy("hermes_state", "SessionDB")(db_path=db_path, read_only=True), None)
- try:
- row["last_session"], row["worker_session"] = _latest_profile_session_rows(db)
- # Resolved server-side on every listing so no client carries a session pointer.
- row["canonical_session"] = _canonical_session_row(db, profile_path)
- finally:
- if db is not None:
- _best_effort(db.close)
+ def _read() -> dict:
+ db_path = Path(profile_path) / "state.db"
+ db = None
+ if _try(db_path.exists, False):
+ db = _try(lambda: _lazy("hermes_state", "SessionDB")(db_path=db_path, read_only=True), None)
+ try:
+ last, worker = _latest_profile_session_rows(db)
+ # Resolved server-side on every listing so no client carries a session pointer.
+ return {"last_session": last, "worker_session": worker,
+ "canonical_session": _canonical_session_row(db, profile_path)}
+ finally:
+ if db is not None:
+ _best_effort(db.close)
+
+ # These three are a pure function of the profile's session store, and the roster re-asks every
+ # 5s per connection — so they are reused while that store has not moved (#117257).
+ from tui_gateway.profile_roster_cache import cached_session_fields
+
+ row.update(cached_session_fields(profile_path, _read))
def _profile_ui_meta_fields(row: dict, profile_dir) -> None:
diff --git a/tui_gateway/profile_roster_cache.py b/tui_gateway/profile_roster_cache.py
new file mode 100644
index 00000000000..8f6adbf4c94
--- /dev/null
+++ b/tui_gateway/profile_roster_cache.py
@@ -0,0 +1,63 @@
+"""Memo for ``profiles.list``'s per-profile session fields, keyed on the session store's signature.
+
+The Bots roster polls ``profiles.list`` every 5s PER CONNECTION, and its session fields
+(``last_session`` / ``worker_session`` / ``canonical_session``) are read from that profile's
+``state.db`` — an open plus a listing query plus the canonical-title lookup, per profile, per poll.
+They are a pure function of that store, so while the store has not moved there is nothing to
+recompute: an idle fleet re-derived the same rows every five seconds for every bot it has.
+
+The signature is the one the change watcher already trusts for ``sessions.changed`` — the newest
+mtime across ``state.db`` and its ``-wal`` sidecar — plus each file's size, so a write that lands
+inside one mtime tick still invalidates. A profile with no store is not cached: it has nothing to
+read, so the call is already cheap and a future store must be picked up.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+# Keyed by resolved profile path. One entry per profile the roster has painted; a removed profile
+# leaves one stale entry, so the whole memo is dropped once it grows past any plausible fleet.
+_CACHE: dict[str, tuple[tuple, dict]] = {}
+_MAX_ENTRIES = 512
+
+_STORE_FILES = ("state.db", "state.db-wal")
+
+
+def store_signature(profile_path: "str | Path") -> Optional[tuple]:
+ """``(name, mtime_ns, size)`` per session-store file, or None when the profile has no store."""
+ base = Path(profile_path)
+ parts: list[tuple[str, int, int]] = []
+ for name in _STORE_FILES:
+ try:
+ stat = (base / name).stat()
+ except OSError:
+ continue
+ parts.append((name, stat.st_mtime_ns, stat.st_size))
+ return tuple(parts) or None
+
+
+def cached_session_fields(profile_path: "str | Path", compute: Callable[[], dict]) -> dict[str, Any]:
+ """``compute()``'s fields, reused while the profile's session store has not moved."""
+ signature = store_signature(profile_path)
+ if signature is None:
+ return compute()
+
+ key = str(profile_path)
+ hit = _CACHE.get(key)
+ if hit is not None and hit[0] == signature:
+ return dict(hit[1])
+
+ fields = compute()
+ if len(_CACHE) >= _MAX_ENTRIES:
+ _CACHE.clear()
+ _CACHE[key] = (signature, dict(fields))
+ return dict(fields)
+
+
+def invalidate(profile_path: "str | Path | None" = None) -> None:
+ """Drop one profile's memo, or all of them. For tests and for a caller that knows better."""
+ if profile_path is None:
+ _CACHE.clear()
+ else:
+ _CACHE.pop(str(profile_path), None)