Skip to content

The agent that grows with you

fix(gateway): keep finalized bound API routes; hold the owner lock across /new

unsupportedpastels439e874e2f6a
diff --git a/gateway/session.py b/gateway/session.py
index 45478880371..d5df27577dd 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -949,11 +949,12 @@ class SessionStore(
checks = None
if not force_new and observed is not None:
sid = observed.session_id
- # A local route the authority holds by receipt is never stale: a stamped row is
+ # A local or API route the authority holds by receipt is never stale: a stamped row is
# reopened by its next admitted turn, never replaced (#140642).
checks = _RouteChecks(
sid, self._compression_tip_for_session_id(sid),
- self._is_session_ended_in_db(sid) and self._local_receipt_target(observed) is None,
+ self._is_session_ended_in_db(sid) and self._local_receipt_target(observed) is None
+ and not self._api_bound(observed),
self._route_reset_reason(observed),
)
# Phase 2 (lock): apply the decisions to _entries.
diff --git a/gateway/session_api.py b/gateway/session_api.py
index cbd0314a501..242a848b814 100644
--- a/gateway/session_api.py
+++ b/gateway/session_api.py
@@ -269,6 +269,15 @@ def bind_api_steps(authority, session_id, *, hosted_dispatch=None, declared_key=
return restore_api_session(authority, session_id)
+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``)."""
+ target = authority.physical_target(ref)
+ row = authority.db.get_session(target)
+ if row is not None and row.get('end_reason') is not None:
+ authority.db.reopen_session(target)
+
+
def api_storage_source(db, session_id, fallback):
if fallback != 'api_server':
return fallback
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 28398b7ef34..256582304c1 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -1065,8 +1065,11 @@ class SessionAuthority:
if current is None or current['status'] != 'queued':
return False, first
if first is not None and live.source.platform == Platform.API_SERVER:
+ from gateway.session_api import reopen_api_session
from gateway.session_api_turn import check_api_turn
+ from gateway.session_runtime_workers import tracked_write
check_api_turn(self, ref, first['payload'])
+ await tracked_write(self, partial(reopen_api_session, self, ref))
if first is not None and self._classic_turn_holds(live.route):
# A classic turn (fallback wake, CLI handoff, legacy resume) holds the route's slot:
# a claim now would hand this row to its busy path and settle it unrun. The head
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index f1aaf2452df..c503e5e72ce 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -507,6 +507,17 @@ async def admit_automation(authority, adapter, event, identity, replaces=None):
_ROUTE_WAKE_PRODUCERS = frozenset({'kanban-wake', 'loop-tick'})
+def route_owner_lock(runner, session_id):
+ """*session_id*'s live owner's ``mutation_lock`` (a no-op without one). Held across a route
+ rotation and ``move_route_wakes``: its drain refuses a wake on the rotated route, so it must not
+ claim one the move has not taken yet."""
+ import contextlib
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner)
+ live = authority.sessions.get(authority.logical_owner(session_id)) if authority and session_id else None
+ return live.mutation_lock if live is not None else contextlib.nullcontext()
+
+
async def move_route_wakes(runner, session_key, old_session_id):
"""After the route rotated (/new, /reset, compression-exhaustion reset), carry the old owner's
still-queued route wakes to the fresh session, as main's #114456 kept a parked internal wake
diff --git a/gateway/session_lifecycle.py b/gateway/session_lifecycle.py
index 66b0404ca2d..048b0871b38 100644
--- a/gateway/session_lifecycle.py
+++ b/gateway/session_lifecycle.py
@@ -116,6 +116,29 @@ class SessionLifecycleMixin:
except (RuntimeStoreError, sqlite3.Error, KeyError, TypeError, AttributeError):
return None
+ def _api_bound(self, entry: Optional[SessionEntry]) -> bool:
+ """*entry*'s API route is the one its binding receipt names (``bind_api_session``). Like a
+ local receipt route it moves only through the authority, and its next admitted turn reopens a
+ stamped row (``reopen_api_session``): replacing it forked the caller's conversation onto a
+ minted id every later run on it refused (``admission_conflict``)."""
+ origin = getattr(entry, "origin", None)
+ if origin is None or getattr(origin, "platform", None) is None or origin.platform.value != "api_server":
+ return False
+ db = self._db_for_key(entry.session_key)
+ if db is None or getattr(db, "_read_ctx", None) is None:
+ return False
+ import json
+ import sqlite3
+
+ from hermes_state_local import API_BINDING_PREFIX
+ try:
+ with db._read_ctx() as conn:
+ saved = conn.execute("SELECT value FROM state_meta WHERE key=?",
+ (API_BINDING_PREFIX + str(origin.chat_id),)).fetchone()
+ return saved is not None and json.loads(saved[0])["entry"]["session_key"] == entry.session_key
+ except (sqlite3.Error, ValueError, KeyError, TypeError):
+ return False
+
def _route_reset_reason(self, entry: SessionEntry) -> Optional[str]:
"""Only explicit suspension replaces a routed conversation; time never does."""
return "suspended" if entry.suspended else None
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index 8dfb87502a0..e46c41f946b 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -222,10 +222,11 @@ class GatewaySessionCommandsMixin:
parent_session_id=str(getattr(old_entry, "session_id", "") or ""))
_reset_process_scoped_tool_state()
- new_entry = await self.async_session_store.reset_session(session_key)
_old_sid = old_entry.session_id if old_entry else None
- from gateway.session_automation import move_route_wakes
- await move_route_wakes(self, session_key, _old_sid) # main #114456: a parked wake survives /new
+ from gateway.session_automation import move_route_wakes, route_owner_lock
+ async with route_owner_lock(self, _old_sid):
+ new_entry = await self.async_session_store.reset_session(session_key)
+ await move_route_wakes(self, session_key, _old_sid) # main #114456: a parked wake survives /new
await self._fire_session_reset_hooks(source, session_key, _old_sid,
new_entry.session_id if new_entry else None)
# Scoped to the profile serving this source so a multiplexed /new banner reports the
diff --git a/tests/gateway/test_api_route_heal_minted.py b/tests/gateway/test_api_route_heal_minted.py
index ae81053001b..9d15d55adc8 100644
--- a/tests/gateway/test_api_route_heal_minted.py
+++ b/tests/gateway/test_api_route_heal_minted.py
@@ -40,6 +40,43 @@ def test_bind_takes_the_route_back_from_an_empty_minted_session(owner, bound_bef
assert owner.runner.session_store._entries[route].session_id == 'api-stable'
+def test_a_finalized_bound_row_keeps_its_route_across_later_runs(owner):
+ """The live #54878 shape: the bound row is finalized, then its caller runs twice more."""
+ ref = bind_api_session(owner, 'api-stable')
+ source = owner.sessions['api-stable'].source
+ owner.db.end_session('api-stable', 'cli_close')
+
+ for turn in ('two', 'three'):
+ assert bind_api_session(owner, 'api-stable') == ref
+ assert owner.runner.session_store.get_or_create_session(source).session_id == 'api-stable'
+ owner.db.append_message('api-stable', 'user', turn)
+
+
+async def test_the_next_admitted_turn_reopens_a_finalized_api_row(tmp_path, monkeypatch):
+ from gateway import session_api_turn, session_finite
+ from tests.gateway.test_session_authority_cancel_settlement import REF, _authority, _submit
+
+ db, authority = _authority(tmp_path, monkeypatch, platform=Platform.API_SERVER)
+ monkeypatch.setattr(session_api_turn, 'check_api_turn', lambda authority, ref, payload: None)
+ ended = []
+
+ async def execute(authority, ref, row):
+ ended.append(db.get_session('s')['end_reason'])
+ return 'done'
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+ db.end_session('s', 'cli_close')
+
+ with db:
+ authority._schedule = lambda ref: None
+ await _submit(authority, 'turn')
+ del authority._schedule
+ authority._schedule(REF)
+ await authority.sessions['s'].task
+
+ assert ended == [None]
+
+
def test_bind_still_refuses_a_route_held_by_a_used_session(owner):
_mint_on_route(owner, 'api-stable')
owner.db.append_message('minted', 'user', 'a conversation of its own')
diff --git a/tests/gateway/test_new_moves_automation_wake.py b/tests/gateway/test_new_moves_automation_wake.py
index 6a151791acb..cbf5bf8f927 100644
--- a/tests/gateway/test_new_moves_automation_wake.py
+++ b/tests/gateway/test_new_moves_automation_wake.py
@@ -9,7 +9,8 @@ from tests.waiting import async_wait_until
@pytest.mark.asyncio
-async def test_new_moves_a_queued_wake_to_the_fresh_session(monkeypatch):
[email protected]('settles_mid_reset', [False, True])
+async def test_new_moves_a_queued_wake_to_the_fresh_session(monkeypatch, settles_mid_reset):
from gateway.config import GatewayConfig, Platform, PlatformConfig
from gateway.platforms.base import SendResult
from gateway.platforms.event import MessageEvent
@@ -51,6 +52,16 @@ async def test_new_moves_a_queued_wake_to_the_fresh_session(monkeypatch):
captured['result'] = {'final_response': 'reply', 'messages': []}
return 'reply'
monkeypatch.setattr(runner, '_handle_message_with_agent', turn)
+ if settles_mid_reset:
+ # The old turn settles after the rotation, before the wake moves: its drain wakes up there.
+ reset = runner.async_session_store.reset_session
+
+ async def reset_then_settle(session_key):
+ entry = await reset(session_key)
+ finish.set()
+ await asyncio.sleep(0.5) # health: allow HX013 -- the window the old drain must NOT claim in
+ return entry
+ monkeypatch.setattr(runner.async_session_store, 'reset_session', reset_then_settle)
await adapter.handle_message(MessageEvent(text='A', source=source, message_id='A'))
await asyncio.wait_for(running.wait(), 10)