The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): fence recovery boundary and orphan donors to the owning profile
beardthelion1e12c22d3c03
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.pyindex 4a0a245fdc0..0ca0130494d 100644--- a/hermes_state_gateway.py+++ b/hermes_state_gateway.py@@ -92,6 +92,7 @@ _PEER_BY_TUPLE_SQL = f"""{_PEER_SELECT_HEAD} WHERE s.source = ?AND COALESCE(b.chat_id, '') = COALESCE(s.chat_id, '')AND COALESCE(b.chat_type, '') = COALESCE(s.chat_type, '')AND COALESCE(b.thread_id, '') = COALESCE(s.thread_id, '')+ AND (? IS NULL OR COALESCE(b.profile_name, ?) = ?)AND b.ended_at IS NOT NULLAND b.end_reason IN ({_RESET_END_REASONS_SQL})AND b.ended_at@@ -107,7 +108,7 @@ _ORPHAN_DONOR_COLUMNS = ()_ORPHANS_SQL = f"""SELECT o.id, o.source, o.user_id, o.started_at,- o.parent_session_id,+ o.parent_session_id, o.profile_name,{_sql_session_last_active("o")} AS last_active,(SELECT COUNT(*) FROM messages mWHERE m.session_id = o.id) AS message_count@@ -120,12 +121,18 @@ _ORPHANS_SQL = f"""AND {_sql_json_extract('o.model_config', '$._delegate_from')} IS NULLORDER BY o.started_at ASC"""+# Donor profile fence: the donor's effective profile (NULL reads as the store's own, the same convention+# the peer-tuple recovery predicate uses) must equal the orphan's. A sibling profile's keyed row in a+# shared legacy store would otherwise stamp its ``agent:<other>:`` routing identity onto this profile's+# orphan. Stores outside the profile tree derive no owner and keep the historical unfenced behavior.+_ORPHAN_DONOR_PROFILE_FENCE_SQL = "AND (? IS NULL OR COALESCE(d.profile_name, ?) = ?)"_ORPHAN_LINEAGE_DONOR_SQL = f"""SELECT {_ORPHAN_DONOR_COLUMNS}FROM sessions dWHERE d.id = ?AND d.session_key IS NOT NULLAND COALESCE(d.source, '') = COALESCE(?, '')+ {_ORPHAN_DONOR_PROFILE_FENCE_SQL}"""_ORPHAN_CONTIGUITY_DONORS_SQL = f"""SELECT {_ORPHAN_DONOR_COLUMNS}, {_sql_session_last_active("d")} AS last_active@@ -138,6 +145,7 @@ _ORPHAN_CONTIGUITY_DONORS_SQL = f"""OR d.user_id = ?)AND {_sql_session_last_active("d")} BETWEEN ? AND ?AND {_sql_session_last_active("d")} < ?+ {_ORPHAN_DONOR_PROFILE_FENCE_SQL}ORDER BY last_active DESCLIMIT 2"""@@ -448,7 +456,8 @@ class SessionGatewayMixin:explicit non-recoverable end_reason) must block fallback to an *older* row for the same peer. Eachcandidate is therefore rejected when a boundary row for the peer ended *after* the candidate's lastactivity — if the conversation's most recent event is an intentional reset, recovery returns nothing- rather than reaching behind it.+ rather than reaching behind it. The boundary row carries the same profile predicate as the+ candidate: a sibling profile's reset must not suppress this profile's recovery."""if not session_key:return None@@ -465,7 +474,8 @@ class SessionGatewayMixin:# minted). Stores outside the tree derive no owner and keep the historical unfenced behavior.owner = self._own_profile_name()row = conn.execute(- _PEER_BY_TUPLE_SQL, (source, user_id, chat_id, chat_type, thread_id, owner, owner, owner)+ _PEER_BY_TUPLE_SQL,+ (source, user_id, chat_id, chat_type, thread_id, owner, owner, owner, owner, owner, owner),).fetchone()return self._session_row_dict(row) if row else None@@ -475,18 +485,24 @@ class SessionGatewayMixin:is a keyed row of the same source; no time window) or ``contiguity`` (exactly one keyed same-sourcerow with compatible ``user_id`` fell quiet within *max_gap_s* of the orphan's start and is olderthan its last activity). Ambiguity is reported ``adoptable=False`` with a reason, never guessed —- mis-adopting splices one person's conversation into another's chat. Branch/delegate/tool rows are+ mis-adopting splices one person's conversation into another's chat. The donor must share the+ orphan's effective profile (NULL reads as this store's own): a sibling profile's keyed row in a+ shared legacy store must never stamp its routing identity here. Branch/delegate/tool rows areexcluded: unkeyed by design, not damage."""gap = self._ORPHAN_ADOPTION_MAX_GAP_S if max_gap_s is None else float(max_gap_s)+ owner = self._own_profile_name()records: List[Dict[str, Any]] = []with self._read_ctx() as conn:for orphan in conn.execute(_ORPHANS_SQL).fetchall():donor = Nonereason = ""+ orphan_owner = orphan["profile_name"] or ownerif orphan["parent_session_id"]:evidence = "lineage"donor = conn.execute(- _ORPHAN_LINEAGE_DONOR_SQL, (orphan["parent_session_id"], orphan["source"])).fetchone()+ _ORPHAN_LINEAGE_DONOR_SQL,+ (orphan["parent_session_id"], orphan["source"], owner, owner, orphan_owner),+ ).fetchone()if donor is None:reason = "parent session carries no gateway identity of this source"else:@@ -495,7 +511,8 @@ class SessionGatewayMixin:candidates = conn.execute(_ORPHAN_CONTIGUITY_DONORS_SQL,(orphan["id"], orphan["source"], orphan["user_id"], orphan["user_id"],- started - gap, started + gap, orphan["last_active"]),+ started - gap, started + gap, orphan["last_active"],+ owner, owner, orphan_owner),).fetchall()if not candidates:reason = f"no keyed predecessor fell quiet within {gap:.0f}s of this session's start"@@ -526,16 +543,20 @@ class SessionGatewayMixin:either row makes this a no-op. Non-NULL orphan columns are preserved."""if not orphan_id or not donor_id or orphan_id == donor_id:return False+ owner = self._own_profile_name()def _do(conn):donor = conn.execute("SELECT session_key, chat_id, chat_type, thread_id, user_id, "- "origin_json, display_name, source FROM sessions WHERE id = ?",+ "origin_json, display_name, source, profile_name FROM sessions WHERE id = ?",(donor_id,),).fetchone()orphan = conn.execute(- "SELECT session_key, source FROM sessions WHERE id = ?", (orphan_id,)).fetchone()+ "SELECT session_key, source, profile_name FROM sessions WHERE id = ?",+ (orphan_id,)).fetchone()if (donor is None or orphan is None or not donor["session_key"] or orphan["session_key"]- or (donor["source"] or "") != (orphan["source"] or "")):+ or (donor["source"] or "") != (orphan["source"] or "")+ or (owner is not None+ and (donor["profile_name"] or owner) != (orphan["profile_name"] or owner))):return False# Belt-and-suspenders for gateway routing metadata (#59527): the gateway re-records the peer on# the child after rotation (d5b4879d4), but a hard crash between child creation and that writediff --git a/tests/hermes_state/test_hermes_state.py b/tests/hermes_state/test_hermes_state.pyindex e74c826ef67..ed1724dd8e0 100644--- a/tests/hermes_state/test_hermes_state.py+++ b/tests/hermes_state/test_hermes_state.py@@ -5236,6 +5236,79 @@ def test_peer_fallback_never_adopts_a_sibling_profiles_row(tmp_path, monkeypatchstore.close()+def test_peer_fallback_reset_boundary_is_profile_fenced(tmp_path, monkeypatch):+ """The recovery reset fence must not cross profiles either.++ A sibling profile's newer session_reset row for the same peer tuple used+ to suppress THIS profile's otherwise recoverable session: the NOT EXISTS+ boundary subquery carried every peer predicate but profile_name. The+ profile's own reset still fences recovery, and a store outside the+ profile tree (no derivable owner) keeps the historical unfenced behavior.+ """+ 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"}++ def recover():+ return store.find_latest_gateway_session_for_peer(+ source="telegram", session_key="agent:main:telegram:dm:42", **peer+ )++ store.create_session("own", "telegram", session_key="agent:main:telegram:dm:42:old",+ profile_name="default", **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'")+ )++ # A sibling profile's later reset for the same tuple must NOT fence+ # this profile's recovery.+ store.create_session("sibling-reset", "telegram",+ session_key="agent:bot2:telegram:dm:42", profile_name="bot2", **peer)+ store.append_message("sibling-reset", "user", "/new")+ store.end_session("sibling-reset", "session_reset")++ assert recover()["id"] == "own"++ # The profile's OWN later reset still fences recovery.+ store.create_session("own-reset", "telegram",+ session_key="agent:main:telegram:dm:42:r2", profile_name="default", **peer)+ store.append_message("own-reset", "user", "/new")+ store.end_session("own-reset", "session_reset")++ assert recover() is None+ finally:+ store.close()++ # Outside the profile tree there is no owner: every boundary counts.+ (tmp_path / "elsewhere").mkdir()+ unfenced = SessionDB(db_path=tmp_path / "elsewhere" / "state.db")+ try:+ peer = {"user_id": "42", "chat_id": "42", "chat_type": "dm"}+ unfenced.create_session("own", "telegram", session_key="agent:main:telegram:dm:42:old",+ profile_name="default", **peer)+ unfenced.append_message("own", "user", "conversation")+ unfenced._execute_write(+ lambda c: c.execute("UPDATE sessions SET last_activity_at = 1 WHERE id = 'own'")+ )+ unfenced.create_session("sibling-reset", "telegram",+ session_key="agent:bot2:telegram:dm:42", profile_name="bot2", **peer)+ unfenced.append_message("sibling-reset", "user", "/new")+ unfenced.end_session("sibling-reset", "session_reset")++ assert unfenced.find_latest_gateway_session_for_peer(+ source="telegram", session_key="agent:main:telegram:dm:42", **peer+ ) is None+ finally:+ unfenced.close()++def test_child_inherits_parent_profile_only_within_its_key_namespace(db):"""#88381: parent→child ``profile_name`` COALESCE is fenced by ``agent:<ns>:``.diff --git a/tests/hermes_state/test_orphan_gateway_session_repair.py b/tests/hermes_state/test_orphan_gateway_session_repair.pyindex dabc4d24576..b4557aa00be 100644--- a/tests/hermes_state/test_orphan_gateway_session_repair.py+++ b/tests/hermes_state/test_orphan_gateway_session_repair.py@@ -308,3 +308,85 @@ class TestAdoption:db, "no_key_donor", keyed=False, started_at=time.time() - 100)assert db.adopt_orphaned_gateway_session(orphan, "no_key_donor") is False+++def _profiled_store(tmp_path, monkeypatch):+ """A ``<HERMES_HOME>/state.db`` store, so ``_own_profile_name()`` returns ``default``."""+ 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)+ return SessionDB(db_path=root / "state.db")+++def _stamp_profile(db, session_id, profile_name):+ with db._lock:+ db._conn.execute(+ "UPDATE sessions SET profile_name = ? WHERE id = ?",+ (profile_name, session_id),+ )+ db._conn.commit()+++class TestDonorProfileFence:+ """A donor carries the routing identity adoption stamps onto the orphan, so a+ donor from a sibling profile in a shared legacy store would splice this+ profile's orphan into the sibling's ``agent:<ns>:`` namespace. Donor and+ orphan must share an effective profile (NULL reads as the store's own)."""++ def test_contiguity_donor_must_share_the_orphans_profile(self, tmp_path, monkeypatch):+ store = _profiled_store(tmp_path, monkeypatch)+ try:+ stale, orphan = _incident(store) # orphan auto-stamped 'default'+ _stamp_profile(store, stale, "bot2")+ record = store.find_orphaned_gateway_sessions()[0]+ assert record["adoptable"] is False+ assert record["donor_id"] is None++ # A legacy NULL-stamped row still reads as this store's own.+ _stamp_profile(store, stale, None)+ record = store.find_orphaned_gateway_sessions()[0]+ assert record["adoptable"] is True+ assert record["donor_id"] == stale++ # A bot2 orphan may still adopt a bot2 donor inside a shared store.+ _stamp_profile(store, orphan, "bot2")+ _stamp_profile(store, stale, "bot2")+ record = store.find_orphaned_gateway_sessions()[0]+ assert record["adoptable"] is True+ assert record["session_key"] == PEER["session_key"]+ finally:+ store.close()++ def test_lineage_donor_must_share_the_orphans_profile(self, tmp_path, monkeypatch):+ store = _profiled_store(tmp_path, monkeypatch)+ try:+ stale, _ = _incident(store, parent_link=True)+ _stamp_profile(store, stale, "bot2")+ record = store.find_orphaned_gateway_sessions()[0]+ assert record["adoptable"] is False+ assert record["donor_id"] is None+ finally:+ store.close()++ def test_adoption_reverify_refuses_a_cross_profile_pair(self, tmp_path, monkeypatch):+ store = _profiled_store(tmp_path, monkeypatch)+ try:+ stale, orphan = _incident(store)+ _stamp_profile(store, stale, "bot2")+ assert store.adopt_orphaned_gateway_session(orphan, stale) is False+ assert store.get_session(orphan)["session_key"] is None+ assert store.get_session(stale)["end_reason"] == "agent_close"+ finally:+ store.close()++ def test_unowned_store_keeps_unfenced_donor_matching(self, db):+ # ``db`` lives outside the profile tree: no derivable owner, so the+ # historical behavior (any compatible keyed predecessor) stands.+ stale, _ = _incident(db)+ _stamp_profile(db, stale, "bot2")+ record = db.find_orphaned_gateway_sessions()[0]+ assert record["adoptable"] is True+ assert record["donor_id"] == stale