Skip to content

The agent that grows with you

fix(gateway): fail closed when a named profile has no resolvable home

caya8205-249fb58523f59
diff --git a/gateway/session.py b/gateway/session.py
index b0a6c798f45..85f11d3b6c5 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -1398,19 +1398,33 @@ class SessionStore:
def _db(self, value) -> None:
self._db_pinned = value
- def _profile_home_for_key(self, session_key: Optional[str]) -> Optional[Path]:
- """HERMES_HOME of the profile that owns *session_key*, or None.
-
- None means "resolve exactly the way we always have": multiplexing is
- off, the key carries the legacy ``agent:main`` namespace, or the
- profile has no live directory. A single-profile gateway therefore
- never reaches a different store than before this helper existed.
+ def _named_profile_for_key(self, session_key: Optional[str]) -> Optional[str]:
+ """The non-default profile that owns *session_key*, or None.
+
+ None means the ambient store is authoritative for this key —
+ multiplexing is off, or the key carries the legacy ``agent:main``
+ namespace. It deliberately does NOT cover "that profile has no
+ directory": ownership and resolvability are different questions, and
+ ``_db_for_key`` has to answer them separately.
"""
if not getattr(self.config, "multiplex_profiles", False):
return None
profile = self._profile_from_session_key(session_key)
if not profile or profile == "default":
return None
+ return profile
+
+ def _profile_home_for_key(self, session_key: Optional[str]) -> Optional[Path]:
+ """HERMES_HOME of the profile that owns *session_key*, or None.
+
+ None here means only "no live home to point at" — either the key has
+ no named owner, or that owner's directory could not be resolved.
+ Callers that mutate state must tell those two apart through
+ ``_named_profile_for_key``.
+ """
+ profile = self._named_profile_for_key(session_key)
+ if profile is None:
+ return None
cache = self._profile_home_cache
if profile in cache:
return cache[profile]
@@ -1454,9 +1468,27 @@ class SessionStore:
"""
if self._db_pinned is not _DB_UNPINNED:
return self._db_pinned
+ profile = self._named_profile_for_key(session_key)
+ if profile is None:
+ # No named owner — the ambient store is authoritative, exactly as
+ # it was before this helper existed.
+ return self._db
home = self._profile_home_for_key(session_key)
if home is None:
- return self._db
+ # A named owner we cannot resolve: the profile is not provisioned
+ # yet (the enrollment bridge creates profiles/<name>/ at runtime,
+ # so a key legitimately arrives first), or the lookup failed.
+ # Falling back to the ambient store would put ONE qualified
+ # session identity in two physical stores — the split this helper
+ # exists to remove — because the first lookup would land in root
+ # and the next one, after provisioning, in the profile. Fail
+ # closed instead; callers already handle a missing DB.
+ logger.warning(
+ "gateway.session: profile %r has no resolvable home (key %r); "
+ "refusing to fall back to the ambient store",
+ profile, session_key,
+ )
+ return None
try:
return self._open_session_db_for_active_scope(db_path=home / "state.db")
except Exception:
@@ -4038,7 +4070,17 @@ class SessionStore:
def _append_transcript_message(self, session_id: str, message: Dict[str, Any]) -> None:
"""Write one transcript row. Caller handles retry queuing."""
- self._db_for_session_id(session_id).append_message(
+ _db = self._db_for_session_id(session_id)
+ if _db is None:
+ # A named profile with no resolvable home yet. Defer instead of
+ # writing the row into the ambient store — the caller queues the
+ # message and a later attempt lands it once the profile exists.
+ # Reached via the compression-child id, which is not the id the
+ # entry-point guard in append_to_transcript already checked.
+ raise RuntimeError(
+ f"no owning session store for {session_id}; deferring transcript write"
+ )
+ _db.append_message(
session_id=session_id,
role=message.get("role", "unknown"),
content=message.get("content"),
diff --git a/tests/gateway/test_multiplex_session_db_profile_scope.py b/tests/gateway/test_multiplex_session_db_profile_scope.py
index 5980248519a..56a72449e09 100644
--- a/tests/gateway/test_multiplex_session_db_profile_scope.py
+++ b/tests/gateway/test_multiplex_session_db_profile_scope.py
@@ -625,3 +625,57 @@ def test_profile_home_is_not_memoized_before_the_profile_exists(multiplex_homes)
(root / "profiles" / "latecomer").mkdir(parents=True)
assert store._profile_home_for_key(key) == root / "profiles" / "latecomer"
+
+
+def test_named_owner_without_a_home_never_falls_back_to_root(multiplex_homes):
+ """A named profile that is not provisioned yet must not land in root.
+
+ The enrollment bridge creates ``profiles/<name>/`` at runtime, so a key
+ can arrive before its owner exists. Resolving that to the ambient store
+ would put one qualified session identity in two physical stores — root on
+ the first lookup, the profile store on the next — which is exactly the
+ split this whole change removes. Fail closed instead.
+ """
+ root, _profile = multiplex_homes
+ store = _multiplex_store(root)
+ key = "agent:latecomer:telegram:dm:9"
+
+ assert store._named_profile_for_key(key) == "latecomer"
+ assert store._db_for_key(key) is None
+ assert _session_ids(root / "state.db") == set()
+
+ # Once the bridge provisions it, the same key owns a real store.
+ home = root / "profiles" / "latecomer"
+ home.mkdir(parents=True)
+ db = store._db_for_key(key)
+ assert db is not None
+ db.create_session("20260829_120000_abcdef01", "telegram")
+
+ assert _session_ids(home / "state.db") == {"20260829_120000_abcdef01"}
+ assert _session_ids(root / "state.db") == set()
+
+
+def test_profile_resolution_failure_fails_closed(multiplex_homes, monkeypatch):
+ """A resolver error must not degrade into an ambient write either.
+
+ ``_profile_home_for_key`` swallows lookup exceptions, so without the
+ ownership check the failure would be indistinguishable from "no named
+ owner" and silently route the row to root.
+ """
+ import hermes_cli.profiles as profiles_mod
+
+ root, _profile = multiplex_homes
+ store = _multiplex_store(root)
+ key = "agent:fitness:telegram:dm:1"
+
+ # It resolves while the lookup works.
+ assert store._db_for_key(key) is not None
+ store._profile_home_cache.clear()
+
+ def _boom(_name):
+ raise OSError("profile lookup failed")
+
+ monkeypatch.setattr(profiles_mod, "profile_exists", _boom)
+
+ assert store._db_for_key(key) is None
+ assert _session_ids(root / "state.db") == set()