Skip to content

The agent that grows with you

fix(gateway): skip an unreadable sibling profile.yaml and cache the roster's disk scan

Tekniumc2846b54bbed
diff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.py
index a64f7e3a053..2d7f1940f2d 100644
--- a/gateway/session_group_controls.py
+++ b/gateway/session_group_controls.py
@@ -1,6 +1,7 @@
"""Profile-owned room controls over the canonical hosted service."""
import asyncio
import logging
+import os
from pathlib import Path
import weakref
@@ -409,11 +410,7 @@ def _profiles(authority, actor, home, params, siblings=()):
'skill_count': 0}
if include_sessions and reach is not None:
entry.update(_sibling_sessions(*reach))
- meta_path = target / 'profile.yaml'
- try:
- meta = yaml.safe_load(meta_path.read_text(encoding='utf-8-sig')) if meta_path.is_file() else {}
- except (OSError, yaml.YAMLError):
- meta = {}
+ meta = _discovered_profile_meta(configured, target / 'profile.yaml')
if isinstance(meta, dict):
entry['display_name'] = str(meta.get('display_name') or configured)
if isinstance(meta.get('ui_meta'), dict):
@@ -436,17 +433,67 @@ def _profiles(authority, actor, home, params, siblings=()):
# (RT-38): a host running one gateway per profile serves no siblings, and Desktop drops every
# union agent the active source leaves out, so a default-only answer hid the other bots.
# Metadata only, like any discovery above.
- from hermes_cli.profiles import _get_default_hermes_home, _iter_named_profile_dirs
+ from hermes_cli.profiles import _get_default_hermes_home
root = _get_default_hermes_home()
if root.is_dir():
discovered('default', root)
- for target in _iter_named_profile_dirs():
+ for target in _named_profile_dirs():
discovered(target.name, target)
# ``install_id`` (same value as /api/status) lets a multi-connection client prove which
- # machine answered; the roster trace logged ``answered=-`` without it.
+ # machine answered; the roster trace logged ``answered=-`` without it. It already returns
+ # None for an unreadable root.
from hermes_cli.install_identity import get_install_id
+ return {'profiles': profiles, 'bot_mode_protocol': True, 'install_id': get_install_id() or ''}
+
+
+# The Bots pane polls ``profiles.list`` every 5 s. Re-listing ``profiles/`` and re-parsing every
+# sibling ``profile.yaml`` each time cost ~60 ms at 50 profiles, so both are cached by stat:
+# the directory listing by the mtimes of ``profiles/`` and each entry (a new profile, its
+# identity marker or a tombstone each bump one of them), and a parsed ``profile.yaml`` by
+# (path, mtime_ns, size).
+_NAMED_DIRS_CACHE: dict[str, tuple[tuple, list]] = {}
+_PROFILE_META_CACHE: dict[str, tuple[tuple[int, int], object]] = {}
+
+
+def _named_profile_dirs():
+ from hermes_cli.profiles import _get_profiles_root, _iter_named_profile_dirs
+ profiles_root = _get_profiles_root()
+ try:
+ with os.scandir(profiles_root) as entries:
+ signature = (os.stat(profiles_root).st_mtime_ns,
+ tuple(sorted((entry.name, entry.stat().st_mtime_ns) for entry in entries)))
+ except OSError:
+ signature = None
+ cached = _NAMED_DIRS_CACHE.get(str(profiles_root))
+ if signature is not None and cached and cached[0] == signature:
+ return cached[1]
try:
- install_id = get_install_id() or ''
+ targets = _iter_named_profile_dirs()
+ except OSError as exc:
+ # An unreadable ``profiles/`` drops the siblings, never the authority's own roster.
+ logger.warning('profiles.list: cannot list %s: %s', profiles_root, exc)
+ return []
+ if signature is not None:
+ _NAMED_DIRS_CACHE[str(profiles_root)] = (signature, targets)
+ return targets
+
+
+def _discovered_profile_meta(name, meta_path):
+ """A sibling's parsed ``profile.yaml``, or ``{}``. One unreadable file (a legacy code page,
+ bad YAML, a permission error) degrades that row to basic metadata; it never fails the roster."""
+ import hermes_yaml as yaml
+ try:
+ stat = meta_path.stat()
except OSError:
- install_id = ''
- return {'profiles': profiles, 'bot_mode_protocol': True, 'install_id': install_id}
+ return {}
+ key = (stat.st_mtime_ns, stat.st_size)
+ cached = _PROFILE_META_CACHE.get(str(meta_path))
+ if cached and cached[0] == key:
+ return cached[1]
+ try:
+ meta = yaml.safe_load(meta_path.read_text(encoding='utf-8-sig')) if meta_path.is_file() else {}
+ except (OSError, ValueError, yaml.YAMLError) as exc:
+ logger.warning('profiles.list: skipping unreadable profile.yaml for %s (%s): %s', name, meta_path, exc)
+ meta = {}
+ _PROFILE_META_CACHE[str(meta_path)] = (key, meta)
+ return meta
diff --git a/tests/gateway/test_session_group_controls.py b/tests/gateway/test_session_group_controls.py
index 4a59d36e63b..a91a358299d 100644
--- a/tests/gateway/test_session_group_controls.py
+++ b/tests/gateway/test_session_group_controls.py
@@ -175,3 +175,77 @@ def test_profiles_list_names_every_profile_on_disk_and_its_install(tmp_path, mon
assert rows['writer']['display_name'] == 'Writer Bot'
# Discovery is metadata only: a profile this socket does not route to adds no session fields.
assert 'canonical_session' not in rows['writer'] and 'last_session' not in rows['writer']
+
+
+def _roster_home(tmp_path, monkeypatch):
+ home = tmp_path / 'state'
+ for name in ('helper', 'writer'):
+ (home / 'profiles' / name).mkdir(parents=True)
+ (home / 'profiles' / name / 'config.yaml').write_text('model:\n default: m\n')
+ (home / 'profiles' / 'writer' / 'profile.yaml').write_text('display_name: Writer Bot\n')
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ monkeypatch.setenv('HOME', str(tmp_path / 'user'))
+ (home / 'config.yaml').write_text('model:\n default: fixture-model\n')
+ return home
+
+
+def _list_profiles(home):
+ with SessionDB(home / 'state.db') as db:
+ authority = SimpleNamespace(profile_id=str(home), instance_id='owner', db=db, events={}, sessions={})
+
+ async def probe():
+ connection = AuthorityConnection(authority, object(), {'user_id': 'reader'})
+ return await connection.dispatch({'id': 'r', 'method': 'profiles.list', 'params': {}})
+ return asyncio.run(probe())
+
+
+def test_profiles_list_survives_an_undecodable_sibling_profile_yaml(tmp_path, monkeypatch, caplog):
+ """@dokterdok on #140972: a sibling profile.yaml saved in a legacy Windows code page raised
+ UnicodeDecodeError and failed the healthy default's whole roster. The roster still answers,
+ that profile keeps a basic row, and the unreadable file is logged."""
+ home = _roster_home(tmp_path, monkeypatch)
+ (home / 'profiles' / 'helper' / 'profile.yaml').write_bytes('display_name: Andr\xe9\n'.encode('cp1252'))
+ with caplog.at_level('WARNING', logger='gateway.session_group_controls'):
+ reply = _list_profiles(home)
+ assert 'result' in reply, reply
+ rows = {row['name']: row for row in reply['result']['profiles']}
+ assert list(rows) == ['default', 'helper', 'writer']
+ assert rows['helper']['display_name'] == 'helper'
+ assert rows['writer']['display_name'] == 'Writer Bot'
+ assert any('helper' in record.getMessage() and 'profile.yaml' in record.getMessage()
+ for record in caplog.records)
+
+
+def test_profiles_list_reuses_its_disk_scan_until_a_profile_changes(tmp_path, monkeypatch):
+ """@kshitijk4poor on #140972: the Bots pane polls profiles.list every 5 s, and each call
+ re-enumerated profiles/ and re-parsed every profile.yaml. An unchanged tree is served from
+ cache; a new profile or an edited profile.yaml is picked up on the next call."""
+ import os
+
+ from hermes_cli import profiles
+ import hermes_yaml
+ home = _roster_home(tmp_path, monkeypatch)
+ scans, parses = [], []
+ real_iter, real_load = profiles._iter_named_profile_dirs, hermes_yaml.safe_load
+ monkeypatch.setattr(profiles, '_iter_named_profile_dirs',
+ lambda *a, **k: scans.append(1) or real_iter(*a, **k))
+ monkeypatch.setattr(hermes_yaml, 'safe_load', lambda text: parses.append(text) or real_load(text))
+
+ def sibling_parses():
+ return sum('Writer' in str(text) for text in parses)
+
+ _list_profiles(home)
+ first_scans, first_parses = len(scans), sibling_parses()
+ assert first_scans and first_parses
+ _list_profiles(home)
+ assert (len(scans), sibling_parses()) == (first_scans, first_parses)
+
+ meta = home / 'profiles' / 'writer' / 'profile.yaml'
+ meta.write_text('display_name: Renamed Writer\n')
+ stat = meta.stat()
+ os.utime(meta, ns=(stat.st_atime_ns, stat.st_mtime_ns + 1_000_000_000))
+ (home / 'profiles' / 'scout').mkdir()
+ (home / 'profiles' / 'scout' / 'config.yaml').write_text('model:\n default: m\n')
+ rows = {row['name']: row for row in _list_profiles(home)['result']['profiles']}
+ assert rows['writer']['display_name'] == 'Renamed Writer'
+ assert 'scout' in rows