The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(session): fence multiplex peer-fallback recovery and profile inheritance by owner (#74285, #88381)
Teknium7463cd12021f
diff --git a/gateway/session.py b/gateway/session.pyindex a38b9c965cc..8de09eceb6d 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -2209,10 +2209,15 @@ class SessionStore:requested_session_key: str,recovered: Dict[str, Any],) -> bool:- """Prevent non-multiplexed gateways from reviving another profile's row."""- if getattr(self.config, "multiplex_profiles", False):- return True-+ """Prevent a gateway from reviving another profile's row.++ Single-profile: the recovered row's namespace must match the ACTIVE+ profile. Multiplexed: several profiles serve traffic at once, so the+ active profile is meaningless — the requested key carries the profile+ the turn was routed to, and the recovered row must sit in the same+ ``agent:<ns>:`` namespace (#74285). Rows with no key namespace stay+ adoptable in both modes (legacy/keyless data owned by this store).+ """recovered_key = str(recovered.get("session_key") or "")if not recovered_key or recovered_key == requested_session_key:return True@@ -2221,6 +2226,10 @@ class SessionStore:if recovered_profile is None:return True+ if getattr(self.config, "multiplex_profiles", False):+ requested_profile = self._profile_from_session_key(requested_session_key)+ return requested_profile is None or recovered_profile == requested_profile+return recovered_profile == self._active_profile_name()def _generate_session_key(self, source: SessionSource) -> str:@@ -2427,8 +2436,7 @@ class SessionStore:):logger.warning("Gateway session DB recovery ignored %s for %s because "- "multiplex_profiles is disabled and the row belongs to a "- "different profile",+ "the row belongs to a different profile",recovered.get("session_key"),session_key,)@@ -2504,8 +2512,7 @@ class SessionStore:):logger.warning("Gateway session DB recovery ignored %s for %s because "- "multiplex_profiles is disabled and the row belongs to a "- "different profile",+ "the row belongs to a different profile",recovered.get("session_key"),session_key,)diff --git a/hermes_state.py b/hermes_state.pyindex 88c6bd59f3c..eb308a1e5bc 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -5180,6 +5180,18 @@ def classify_session_status(return SESSION_STATUS_COMPLETE+# Parent→child ``profile_name`` inheritance fence (#88381). ``agent:<ns>:...``+# gateway keys encode the profile namespace; a keyless row (CLI / subagent+# lineage) carries none and inherits freely. Two keyed rows must agree on+# ``agent:<ns>:`` — a default child (``agent:main:``) forked from a sibling+# profile's row must not be durably mislabelled as that profile's.+_SAME_KEY_NAMESPACE_SQL = (+ "p.session_key IS NULL OR sessions.session_key IS NULL"+ " OR substr(p.session_key, 1, instr(substr(p.session_key, 7), ':') + 6)"+ " = substr(sessions.session_key, 1, instr(substr(sessions.session_key, 7), ':') + 6)"+)++class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin):"""SQLite-backed session storage with FTS5 search.@@ -7338,7 +7350,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)self._delete_unreferenced_system_prompts(conn)if parent_session_id:conn.execute(- """UPDATE sessions+ f"""UPDATE sessionsSET cwd = COALESCE(sessions.cwd,(SELECT p.cwd FROM sessions pWHERE p.id = sessions.parent_session_id)),@@ -7350,7 +7362,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)WHERE p.id = sessions.parent_session_id)),profile_name = COALESCE(sessions.profile_name,(SELECT p.profile_name FROM sessions p- WHERE p.id = sessions.parent_session_id))+ WHERE p.id = sessions.parent_session_id+ AND ({_SAME_KEY_NAMESPACE_SQL})))WHERE id = ? AND parent_session_id IS NOT NULL""",(session_id,),)@@ -7922,6 +7935,15 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)# tuple so we never cross chats/threads/users.if chat_id is None or chat_type is None:return None+ # Profile fence (#74285): a Telegram DM's peer tuple is identical+ # for every bot (chat_id == user_id, no thread), so a sibling+ # profile's row written into this store before the per-profile+ # partition (legacy data) would otherwise be adopted here. Every+ # profile-tree store has one owner; a row is ours when its+ # profile_name is the owner or NULL (legacy rows this store+ # minted). Stores outside the tree derive no owner and keep the+ # historical unfenced behavior.+ owner = self._own_profile_name()row = conn.execute(f"""SELECT s.*,@@ -7937,6 +7959,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)AND COALESCE(s.chat_id, '') = COALESCE(?, '')AND COALESCE(s.chat_type, '') = COALESCE(?, '')AND COALESCE(s.thread_id, '') = COALESCE(?, '')+ AND (? IS NULL OR COALESCE(s.profile_name, ?) = ?)AND (s.ended_at IS NULL OR s.end_reason IN ({_RECOVERABLE_END_REASONS_SQL}))AND (COALESCE(s.message_count, 0) > 0 OR EXISTS (SELECT 1 FROM messages WHERE messages.session_id = s.id LIMIT 1@@ -7956,7 +7979,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)ORDER BY COALESCE(s.last_activity_at, s.started_at) DESCLIMIT 1""",- (source, user_id, chat_id, chat_type, thread_id),+ (source, user_id, chat_id, chat_type, thread_id, owner, owner, owner),).fetchone()return self._session_row_dict(row) if row else Nonediff --git a/tests/gateway/test_multiplex_phase0.py b/tests/gateway/test_multiplex_phase0.pyindex 836a0d6355f..6558d67f54a 100644--- a/tests/gateway/test_multiplex_phase0.py+++ b/tests/gateway/test_multiplex_phase0.py@@ -172,3 +172,27 @@ class TestSessionStoreUnmultiplexedRecovery:assert recovered.session_id == "sess-coder"assert recovered.session_key == "agent:main:telegram:dm:99"assert store._db.reopened == ["sess-coder"]++ @pytest.mark.parametrize(+ ("recovered_key", "adopted"),+ [+ ("agent:coder:telegram:dm:99", False), # sibling namespace → fail closed+ ("agent:main:telegram:dm:99:v1", True), # same namespace → adoptable+ ],+ ids=["sibling-profile", "same-profile"],+ )+ def test_flag_on_fences_recovery_by_requested_namespace(+ self, tmp_path, recovered_key, adopted+ ):+ """#74285: under multiplexing the guard compares the recovered row's+ ``agent:<ns>:`` against the REQUESTED key, never the active profile."""+ row = {"id": "sess", "started_at": 1700000000, "session_key": recovered_key}+ store = self._store_with_row(tmp_path, row, multiplex_profiles=True)+ store._db_pinned = store._db+ with patch("hermes_cli.profiles.get_active_profile_name", return_value="coder"):+ recovered = store._recover_session_from_db(+ session_key="agent:main:telegram:dm:99",+ source=_src(chat_id="99", chat_type="dm"),+ now=datetime.fromtimestamp(1700000001),+ )+ assert (recovered is not None) is adopteddiff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.pyindex 7e36b1719fe..04e066858de 100644--- a/tests/test_hermes_state.py+++ b/tests/test_hermes_state.py@@ -4355,6 +4355,63 @@ def test_gateway_session_recovery_does_not_cross_newer_reset_boundary() is None+def test_peer_fallback_never_adopts_a_sibling_profiles_row(tmp_path, monkeypatch):+ """#74285: the peer-tuple fallback is fenced by the store's own profile.++ A Telegram DM peer tuple (chat_id == user_id, no thread) is identical for+ every bot, so a legacy sibling-profile row sitting in this store — written+ before the per-profile partition — must lose to the older own row, and+ with no own row recovery must return nothing rather than the sibling's.+ """+ import hermes_state++ root = tmp_path / "hermes"+ root.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(root))+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", hermes_state._IMPORT_DEFAULT_DB_PATH)+ store = SessionDB(db_path=root / "state.db") # owner: default+ try:+ peer = {"user_id": "42", "chat_id": "42", "chat_type": "dm"}+ store.create_session("sibling", "telegram", session_key="agent:bot2:telegram:dm:42",+ profile_name="bot2", **peer)+ store.append_message("sibling", "user", "bot2's conversation")++ def recover():+ return store.find_latest_gateway_session_for_peer(+ source="telegram", session_key="agent:main:telegram:dm:42", **peer+ )++ assert recover() is None # only the sibling exists: fail closed++ store.create_session("own", "telegram", session_key="agent:main:telegram:dm:42:old", **peer)+ store.append_message("own", "user", "default's conversation")+ store._execute_write(+ lambda c: c.execute("UPDATE sessions SET last_activity_at = 1 WHERE id = 'own'")+ )+ assert recover()["id"] == "own" # older own row beats newer sibling row+ finally:+ store.close()+++def test_child_inherits_parent_profile_only_within_its_key_namespace(db):+ """#88381: parent→child ``profile_name`` COALESCE is fenced by ``agent:<ns>:``.++ A default child (``agent:main:``) forked from a sibling profile's row must+ not be durably mislabelled as that profile's; same-namespace and keyless+ (CLI/subagent) children keep inheriting.+ """+ db.create_session("parent", "telegram", session_key="agent:bot2:telegram:dm:42",+ profile_name="bot2")+ db.create_session("cross", "telegram", parent_session_id="parent",+ session_key="agent:main:telegram:dm:42")+ db.create_session("same", "telegram", parent_session_id="parent",+ session_key="agent:bot2:telegram:dm:42:r2")+ db.create_session("keyless", "cli", parent_session_id="parent")+ assert db.get_session("cross")["profile_name"] is None+ assert db.get_session("same")["profile_name"] == "bot2"+ assert db.get_session("keyless")["profile_name"] == "bot2"++