The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(gateway): the roster's ui_meta fields ride the same memo, keyed on profile.yaml
John Paul Soliva0111d931785c
diff --git a/tests/tui_gateway/test_profiles_list_ui_meta_cache.py b/tests/tui_gateway/test_profiles_list_ui_meta_cache.pynew file mode 100644index 00000000000..9feb0b101be--- /dev/null+++ b/tests/tui_gateway/test_profiles_list_ui_meta_cache.py@@ -0,0 +1,133 @@+"""``profiles.list`` re-parses a profile's ``profile.yaml`` for ui_meta only when it has changed.++The roster polls this every 5s per connection, and the listing already parsed that same file once+(``read_profile_meta``, for description/display_name) before parsing it again here for ui_meta.++The memo must be invisible: an edit — including one made through the ui_meta CAS writer, which+reads the raw document uncached and writes it back — has to show on the very next listing. And+``has_avatar`` is deliberately NOT cached, so an avatar dropped in without touching profile.yaml+still appears.+"""+from __future__ import annotations++from pathlib import Path++import pytest++import tui_gateway.server as srv+from tui_gateway import profile_roster_cache as cache++[email protected](autouse=True)+def _clear_memo():+ cache.invalidate()+ yield+ cache.invalidate()+++def home(tmp_path, monkeypatch) -> Path:+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / "config.yaml").write_text("model:\n provider: openai\n", encoding="utf-8")+ bob = tmp_path / "profiles" / "bob"+ bob.mkdir(parents=True)+ (bob / "config.yaml").write_text("model:\n provider: openai\n", encoding="utf-8")+ (bob / "profile.yaml").write_text(+ "display_name: Bob\nui_meta:\n hermes-bots:\n title: Bob\n"+ "_ui_meta_revisions:\n hermes-bots: 1\n", encoding="utf-8")+ return tmp_path+++def _row(name="bob", **params):+ envelope = srv._methods["profiles.list"](1, {"include_sessions": False, **params})+ return next(p for p in envelope["result"]["profiles"] if p["name"] == name)+++def test_an_edited_ui_meta_shows_on_the_very_next_listing(home):+ assert _row()["ui_meta"]["hermes-bots"]["title"] == "Bob"++ (home / "profiles" / "bob" / "profile.yaml").write_text(+ "display_name: Bob\nui_meta:\n hermes-bots:\n title: Roberta\n"+ "_ui_meta_revisions:\n hermes-bots: 2\n", encoding="utf-8")++ row = _row()+ assert row["ui_meta"]["hermes-bots"]["title"] == "Roberta"+ assert row["ui_meta_revisions"] == {"hermes-bots": 2}+++def test_the_cas_writer_round_trips_through_the_listing(home):+ """The real write path: profiles.configure reads the raw document, mutates and writes it back."""+ before = _row()["ui_meta_revisions"]["hermes-bots"]++ envelope = srv._methods["profiles.configure"](2, {+ "name": "bob",+ "ui_meta": {"hermes-bots": {"title": "Bobby"}},+ "ui_meta_expected_revisions": {"hermes-bots": before},+ })+ assert envelope["result"]["applied"]["ui_meta"] is True++ row = _row()+ assert row["ui_meta"]["hermes-bots"]["title"] == "Bobby"+ assert row["ui_meta_revisions"]["hermes-bots"] == before + 1+++def test_an_avatar_added_without_touching_profile_yaml_is_still_seen(home):+ """``has_avatar`` stays live — that is why it is not part of the cached value."""+ assert _row()["has_avatar"] is False++ assets = home / "profiles" / "bob" / "assets"+ assets.mkdir(parents=True)+ (assets / "avatar.png").write_bytes(b"\x89PNG\r\n\x1a\n")++ assert _row()["has_avatar"] is True+++def test_a_profile_without_profile_yaml_is_not_cached_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")["ui_meta_revisions"] == {}+ assert "ui_meta" not in _row("bare")+ assert cache.profile_yaml_signature(bare) is None++ (bare / "profile.yaml").write_text(+ "ui_meta:\n hermes-bots:\n title: Late\n_ui_meta_revisions:\n hermes-bots: 1\n",+ encoding="utf-8")++ assert _row("bare")["ui_meta"]["hermes-bots"]["title"] == "Late"+++def test_mutating_a_returned_ui_meta_does_not_poison_the_next_listing(home):+ first = _row()+ first["ui_meta"]["hermes-bots"]["title"] = "clobbered"+ first["ui_meta_revisions"]["hermes-bots"] = 999++ row = _row()+ assert row["ui_meta"]["hermes-bots"]["title"] == "Bob"+ assert row["ui_meta_revisions"] == {"hermes-bots": 1}+++def test_an_unchanged_profile_yaml_is_parsed_once_across_repeated_polls(home, monkeypatch):+ """The saving itself. Counted at the server-published name: the module's bodies are rebound."""+ parsed: list = []+ real = srv._read_profile_yaml++ def _counting(profile_dir):+ parsed.append(str(profile_dir))+ return real(profile_dir)++ monkeypatch.setattr(srv, "_read_profile_yaml", _counting)++ for _ in range(3):+ _row()++ bob = str(home / "profiles" / "bob")+ assert parsed.count(bob) == 1, f"profile.yaml re-parsed: {parsed}"+++def test_the_wire_key_order_is_unchanged(home):+ """``ui_meta_revisions`` precedes ``ui_meta``, and ``has_avatar`` follows both."""+ keys = [k for k in _row() if k.startswith("ui_meta") or k == "has_avatar"]++ assert keys == ["ui_meta_revisions", "ui_meta", "has_avatar"]diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.pyindex 272f9bbe10c..fc477683579 100644--- a/tui_gateway/methods_profiles.py+++ b/tui_gateway/methods_profiles.py@@ -241,14 +241,24 @@ def _profile_session_fields(row, profile_path):def _profile_ui_meta_fields(row: dict, profile_dir) -> None:"""Attach ``ui_meta`` / ``ui_meta_revisions`` / ``has_avatar`` from profile.yaml + assets.``ui_meta_revisions`` is always present: it feature-detects gateway-owned CAS for a new profile."""- raw_meta = _read_profile_yaml(profile_dir)- ui_meta, revisions = raw_meta.get("ui_meta"), raw_meta.get("_ui_meta_revisions")- # Key order is wire-visible: ui_meta_revisions precedes ui_meta.- row["ui_meta_revisions"] = _try(lambda: _clean_revisions(revisions), {}) if isinstance(revisions, dict) else {}- if isinstance(ui_meta, dict) and ui_meta:- # YAML promotes unquoted timestamps to datetime/date; the handler's contract is JSON, so- # coerce YAML-only scalars to their ISO string at the boundary (#92506).- row["ui_meta"] = json.loads(json.dumps(ui_meta, default=_yaml_scalar_to_json))+ def _read() -> dict:+ raw_meta = _read_profile_yaml(profile_dir)+ ui_meta, revisions = raw_meta.get("ui_meta"), raw_meta.get("_ui_meta_revisions")+ # Key order is wire-visible: ui_meta_revisions precedes ui_meta.+ fields = {"ui_meta_revisions":+ _try(lambda: _clean_revisions(revisions), {}) if isinstance(revisions, dict) else {}}+ if isinstance(ui_meta, dict) and ui_meta:+ # YAML promotes unquoted timestamps to datetime/date; the handler's contract is JSON, so+ # coerce YAML-only scalars to their ISO string at the boundary (#92506).+ fields["ui_meta"] = json.loads(json.dumps(ui_meta, default=_yaml_scalar_to_json))+ return fields++ # Second parse of this profile.yaml in the same request (``read_profile_meta`` already read it+ # for the row's description/display name) — reused while the file has not moved (#117383). The+ # ui_meta CAS writer below keeps reading it raw and uncached: it writes the document back.+ from tui_gateway.profile_roster_cache import cached_ui_meta_fields++ row.update(cached_ui_meta_fields(profile_dir, _read))# Cheap existence flag so rosters skip a get_asset probe per paint.row["has_avatar"] = _try(lambda: any((profile_dir / "assets" / f"avatar.{e}").is_file() for e in _ASSET_EXTS), False)diff --git a/tui_gateway/profile_roster_cache.py b/tui_gateway/profile_roster_cache.pyindex 8f6adbf4c94..ed5ac15f1c5 100644--- a/tui_gateway/profile_roster_cache.py+++ b/tui_gateway/profile_roster_cache.py@@ -1,63 +1,100 @@-"""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.+"""Memos for ``profiles.list``'s per-profile fields, each keyed on the file(s) it derives from.++The Bots roster polls ``profiles.list`` every 5s PER CONNECTION, and two groups of fields on every+row are recomputed from disk each time even though nothing has changed:++- the **session fields** (``last_session`` / ``worker_session`` / ``canonical_session``) — a+ read-only ``state.db`` open plus a listing query plus the canonical-title lookup, per profile;+- the **ui_meta fields** (``ui_meta`` / ``ui_meta_revisions``) — a second parse of that profile's+ ``profile.yaml``, which the listing body already parsed once for description/display_name.++Both are pure functions of the files they read, so while those files have not moved there is+nothing to recompute: an idle fleet re-derived identical rows every five seconds for every bot.++Signatures carry each file's ``(mtime_ns, size)`` so a write landing inside one mtime tick still+invalidates; ``profile.yaml`` also carries its inode, because the atomic writers rename a temp file+into place. A profile missing the file a memo keys on is never cached — reading it costs nothing,+and one written later must be picked up.++Only DERIVED values live here. The raw readers keep their uncached contract: ``_read_profile_yaml``+is also used by the ui_meta CAS writer, which reads that document, mutates it and writes it back, and+a stale read there would overwrite a newer file.++This is a module of its own because ``methods_profiles``'s bodies are rebound onto ``server.py``'s+globals (``method_ctx.bind_module``), which COPIES module-level dicts rather than sharing them — a+cache declared there would be written to one copy and read from another."""from __future__ import annotations+import copyfrom pathlib import Pathfrom 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]] = {}+# Each keyed by resolved profile path. One entry per profile the roster has painted; a removed+# profile leaves one stale entry, so a memo is dropped whole once it grows past any plausible fleet.+_SESSION_CACHE: dict[str, tuple[tuple, dict]] = {}+_UI_META_CACHE: dict[str, tuple[tuple, dict]] = {}_MAX_ENTRIES = 512_STORE_FILES = ("state.db", "state.db-wal")+def _file_parts(path: Path, *, with_inode: bool = False) -> Optional[tuple]:+ try:+ stat = path.stat()+ except OSError:+ return None+ return (path.name, stat.st_mtime_ns, stat.st_size) + ((stat.st_ino,) if with_inode else ())+++def _cached(cache: dict, key: str, signature: Optional[tuple], compute: Callable[[], dict],+ copier: Callable[[dict], dict]) -> dict[str, Any]:+ """``compute()``'s fields, reused while *signature* holds. No signature means no cache."""+ if signature is None:+ return compute()+ hit = cache.get(key)+ if hit is not None and hit[0] == signature:+ return copier(hit[1])+ fields = compute()+ if len(cache) >= _MAX_ENTRIES:+ cache.clear()+ cache[key] = (signature, copier(fields))+ return fields++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."""+ """``(name, mtime_ns, size)`` per session-store file, or None when the profile has no store.++ The pair the change watcher already trusts for ``sessions.changed``.+ """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))+ parts = [p for p in (_file_parts(base / name) for name in _STORE_FILES) if p is not None]return tuple(parts) or None+def profile_yaml_signature(profile_dir: "str | Path") -> Optional[tuple]:+ """``(name, mtime_ns, size, inode)`` of the profile's ``profile.yaml``, or None when absent."""+ return _file_parts(Path(profile_dir) / "profile.yaml", with_inode=True)++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()+ return _cached(_SESSION_CACHE, str(profile_path), store_signature(profile_path), compute, dict)- 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 cached_ui_meta_fields(profile_dir: "str | Path", compute: Callable[[], dict]) -> dict[str, Any]:+ """``compute()``'s fields, reused while the profile's ``profile.yaml`` has not changed.++ Copied deeply: ``ui_meta`` is a nested mapping the caller hands to a client.+ """+ return _cached(_UI_META_CACHE, str(profile_dir), profile_yaml_signature(profile_dir),+ compute, copy.deepcopy)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)+ """Drop one profile's memos, or all of them. For tests and for a caller that knows better."""+ for cache in (_SESSION_CACHE, _UI_META_CACHE):+ if profile_path is None:+ cache.clear()+ else:+ cache.pop(str(profile_path), None)