Skip to content

The agent that grows with you

fix(gateway): give a bound caller back an API route the heal already forked

unsupportedpastels4e3e66896d33
diff --git a/gateway/session_api.py b/gateway/session_api.py
index 242a848b814..6efec5f40e3 100644
--- a/gateway/session_api.py
+++ b/gateway/session_api.py
@@ -3,11 +3,11 @@ import asyncio
from functools import partial
import hashlib
import json
+import logging
from gateway.config import Platform
from gateway.session import SessionEntry, SessionSource, _is_path_unsafe
from gateway.session_contract import SessionRef
-from gateway.session_local_recovery import unused_session
from hermes_state_runtime import RuntimeStoreError, _epoch, _json
from hermes_state_local import API_BINDING_PREFIX as _BINDING_PREFIX, API_DECLARED_PREFIX as _DECLARED_PREFIX
@@ -251,9 +251,7 @@ def bind_api_steps(authority, session_id, *, hosted_dispatch=None, declared_key=
existing = conn.execute("SELECT entry_json FROM gateway_routing WHERE scope='' AND session_key=?",
(route,)).fetchone()
held = json.loads(existing[0])['session_id'] if existing is not None else session_id
- # The route is derived from this id, so only the stale-route heal (#54878) names another session
- # on it: one it minted that never ran a turn goes back to the caller; anything used still refuses.
- if held != session_id and not unused_session(conn, held):
+ if held != session_id and not _heal_replacement(conn, session_id, held):
raise RuntimeStoreError('admission_conflict')
conn.execute('''INSERT INTO sessions(id,source,title,hidden,started_at) VALUES(?,?,?,?,?)
ON CONFLICT(id) DO NOTHING''', (session_id, storage_source, title,
@@ -269,6 +267,16 @@ def bind_api_steps(authority, session_id, *, hosted_dispatch=None, declared_key=
return restore_api_session(authority, session_id)
+def _heal_replacement(conn, caller, holder):
+ """The route is derived from the caller's id, so only the stale-route heal (#54878) names another
+ session on it, one with no binding of its own: the caller takes the route back, used or not, and
+ the replacement keeps its transcript under its own id. A holder with its own binding refuses."""
+ if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (_BINDING_PREFIX + holder,)).fetchone():
+ return False
+ logging.getLogger(__name__).warning('API route of %s taken back from heal replacement %s', caller, holder)
+ return True
+
+
def reopen_api_session(authority, ref):
"""The drain's admitted turn reopens a finalized API row, as ``reopen_local_session`` does a
local one: the binding keeps the route on it (``SessionStore._api_bound``)."""
@@ -320,7 +328,7 @@ def restore_api_session(authority, session_id):
current = store._entries.get(entry.session_key)
if current is not None and current.session_id not in authority.db.get_compression_lineage(session_id):
with authority.db._read_ctx() as conn:
- if not unused_session(conn, current.session_id): # see the bind's routing check
+ if not _heal_replacement(conn, session_id, current.session_id):
raise RuntimeStoreError('admission_conflict')
store._entries[entry.session_key] = current if current is not None and current.session_id == target else entry
authority.sessions.setdefault(session_id, LiveSession(source, entry.session_key))
diff --git a/tests/gateway/test_api_route_heal_minted.py b/tests/gateway/test_api_route_heal_minted.py
index 9d15d55adc8..1b0b3cfb026 100644
--- a/tests/gateway/test_api_route_heal_minted.py
+++ b/tests/gateway/test_api_route_heal_minted.py
@@ -7,6 +7,7 @@ import pytest
from gateway.config import Platform
from gateway.session import SessionEntry, SessionSource
from gateway.session_api import bind_api_session
+from hermes_state_local import API_BINDING_PREFIX
from hermes_state_runtime import RuntimeStoreError
@@ -77,9 +78,33 @@ async def test_the_next_admitted_turn_reopens_a_finalized_api_row(tmp_path, monk
assert ended == [None]
-def test_bind_still_refuses_a_route_held_by_a_used_session(owner):
+def test_bind_takes_back_a_route_main_forked_onto_a_used_replacement(owner):
+ """What main's heal leaves on a finalized bound route: the route's entry names a minted id that
+ holds the turn the heal ran there. The binding names S, so S gets the route back; the
+ replacement keeps its own transcript."""
+ ref = bind_api_session(owner, 'S')
+ route = owner.sessions['S'].route
+ store = owner.runner.session_store
+ owner.db.create_session('minted', source='api_server')
+ owner.db.append_message('minted', 'user', 'two') # the turn that triggered the heal ran here
+ now = datetime.now()
+ with store._lock:
+ store._ensure_loaded_locked()
+ store._entries[route] = SessionEntry(route, 'minted', now, now, platform=Platform.API_SERVER,
+ origin=owner.sessions['S'].source)
+ store._save_entries()
+
+ assert bind_api_session(owner, 'S') == ref
+ with store._lock:
+ assert store._entries[route].session_id == 'S'
+ assert [m['content'] for m in owner.db.get_messages('minted')] == ['two']
+
+
+def test_bind_still_refuses_a_route_held_by_a_bound_session(owner):
_mint_on_route(owner, 'api-stable')
owner.db.append_message('minted', 'user', 'a conversation of its own')
+ owner.db._execute_write(lambda conn: conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
+ (API_BINDING_PREFIX + 'minted', '{}')))
with pytest.raises(RuntimeStoreError, match='admission_conflict'):
bind_api_session(owner, 'api-stable')