The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): async completion cannot re-pin a route after /stop or /new won the race
teknium12f569002f593
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.pyindex 7a81a090ba2..952f6ffa58d 100644--- a/gateway/run_agent_cache.py+++ b/gateway/run_agent_cache.py@@ -410,13 +410,16 @@ class GatewayAgentCacheMixin:logger.info("Invalidated run generation for %s → %d (%s)", session_key, generation, reason)return generation+ def _current_session_run_generation(self, session_key: str) -> int:+ """Current run generation for ``session_key`` (0 when the key tracks no run)."""+ state = self._peek_session_state(session_key)+ return int(state.persistent.run_generation) if state is not None else 0+def _is_session_run_current(self, session_key: str, generation: int) -> bool:"""Return True when ``generation`` is still current for ``session_key``."""if not session_key:return True- state = self._peek_session_state(session_key)- current = state.persistent.run_generation if state is not None else 0- return int(current) == int(generation)+ return self._current_session_run_generation(session_key) == int(generation)def _bind_adapter_run_generation(self, adapter: Any, session_key: str, generation: int | None) -> None:"""Bind a gateway run generation to the adapter's active-session event."""diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 3e8ba18e3e0..c2101ec3513 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -215,6 +215,9 @@ class GatewayNotificationsMixin:)return Nonepinned_row = None+ # Snapshot the run generation before the row lookup awaits: a /stop or /new landing while+ # the lookup is pending must not let this completion re-point the route afterwards.+ run_generation = self._current_session_run_generation(session_entry.session_key)try:pinned_row = await session_db.get_session(pinned_session_id)except Exception:@@ -254,16 +257,28 @@ class GatewayNotificationsMixin:if target_session_id == session_entry.session_id:return session_entryprior_session_id = session_entry.session_id+ if not self._is_session_run_current(session_entry.session_key, run_generation):+ logger.warning(+ "Async-delegation completion for routing key %s was invalidated while resolving pinned "+ "session %s; leaving the route on %s and dropping injection.",+ session_entry.session_key, pinned_session_id, prior_session_id,+ )+ return Noneif follows_compression:switched = await self.async_session_store.advance_compression_session(session_entry.session_key, prior_session_id, target_session_id,)else:- switched = await self.async_session_store.switch_session(session_entry.session_key, target_session_id)+ # CAS on the session this completion resolved against: a route replaced meanwhile+ # (/new, /resume) wins over the stale completion.+ switched = await self.async_session_store.switch_session(+ session_entry.session_key, target_session_id, expected_session_id=prior_session_id,+ )if switched is None:logger.warning("Async-delegation completion could not bind routing key %s to "- "owning session %s; dropping injection.", session_entry.session_key, target_session_id,+ "owning session %s (route moved or unknown); dropping injection.",+ session_entry.session_key, target_session_id,)return Nonelogger.info(diff --git a/gateway/session.py b/gateway/session.pyindex af2e373d39a..a957f7f1453 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -1171,13 +1171,26 @@ class SessionStore(# Compression repoint is store bookkeeping, not user activity — leave ``updated_at`` alone so a# background compression on an idle session cannot make it look fresh to the# restart-resume freshness gate (#85709).- def switch_session(self, session_key: str, target_session_id: str) -> Optional[SessionEntry]:+ def switch_session(+ self, session_key: str, target_session_id: str, *, expected_session_id: Optional[str] = None,+ ) -> Optional[SessionEntry]:"""Point a session key at an existing session ID (``/resume``): ends the current row and- reopens the target so resume matches the CLI."""+ reopens the target so resume matches the CLI.++ ``expected_session_id`` makes the repoint a compare-and-swap: ``None`` is returned when+ the key no longer points at that session, so a caller that resolved against a snapshot+ across an await (async-delegation re-pin) cannot overwrite a concurrent /new or /resume.+ """with self._lock:old_entry = self._entry_locked(session_key)if old_entry is None:return None+ if expected_session_id is not None and old_entry.session_id != expected_session_id:+ logger.info(+ "Session switch for %s refused: route moved from %s to %s after the caller's snapshot",+ session_key, expected_session_id, old_entry.session_id,+ )+ return Noneif old_entry.session_id == target_session_id:return old_entrynew_entry = self._replace_route_locked(diff --git a/tests/gateway/test_async_delegation_session_binding.py b/tests/gateway/test_async_delegation_session_binding.pyindex d8f19f83d51..9bfc763ece1 100644--- a/tests/gateway/test_async_delegation_session_binding.py+++ b/tests/gateway/test_async_delegation_session_binding.py@@ -114,7 +114,7 @@ class TestGatewayPinningFailsClosed:assert resolved is pinnedgetattr(runner.session_store, "switch_session").assert_called_once_with(- current.session_key, "sess_live"+ current.session_key, "sess_live", expected_session_id=current.session_id,)@pytest.mark.asyncio@@ -217,3 +217,52 @@ class TestResetHandlerInterruptsDelegations:src = inspect.getsource(slash_commands.GatewaySlashCommandsMixin._handle_reset_command)assert "interrupt_for_session" in srcassert "session_reset" in src++[email protected]("boundary", ["none", "revoke", "replace"])+async def test_pending_pin_respects_concurrent_boundary(tmp_path, boundary):+ """A non-compression re-pin that resolved its row across an await must not move the route+ after the run was invalidated (/stop) or the route was replaced (/new, /resume) meanwhile;+ an undisturbed pin still lands. Real store + real resolver; the DB lookup is event-gated.+ Scenario by the #113690 reporter."""+ import asyncio+ from types import SimpleNamespace++ from gateway.config import GatewayConfig, Platform+ from gateway.run import GatewayRunner+ from gateway.session import AsyncSessionStore, SessionSource, SessionStore++ store = SessionStore(tmp_path / "sessions", GatewayConfig())+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="test-chat", chat_type="dm", user_id="test-user")+ entry = store.get_or_create_session(source)+ runner = object.__new__(GatewayRunner)+ runner.session_store = store+ runner._async_session_store = AsyncSessionStore(store)+ generation = runner._begin_session_run_generation(entry.session_key)+ entered, release = asyncio.Event(), asyncio.Event()++ async def get_session(session_id):+ entered.set()+ await release.wait()+ return {"id": session_id, "ended_at": None}++ runner._session_db = SimpleNamespace(get_session=AsyncMock(side_effect=get_session))+ task = asyncio.create_task(runner._resolve_async_delegation_session(entry, "test-pinned"))+ await asyncio.wait_for(entered.wait(), 3)+ expected = "test-pinned"+ if boundary != "none":+ runner._invalidate_session_run_generation(entry.session_key, reason="test boundary")+ assert not runner._is_session_run_current(entry.session_key, generation)+ expected = entry.session_id+ if boundary == "replace":+ store.switch_session(entry.session_key, "test-replacement")+ expected = "test-replacement"+ release.set()+ result = await asyncio.wait_for(task, 3)++ assert store.lookup_by_session_key(entry.session_key).session_id == expected+ if boundary == "none":+ assert result is not None and result.session_id == expected+ else:+ assert result is Nonediff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.pyindex 43e31c14d16..1b7cc376f42 100644--- a/tests/gateway/test_session.py+++ b/tests/gateway/test_session.py@@ -492,6 +492,21 @@ class TestSessionStoreSwitchSession:assert resumed["end_reason"] is Nonedb.close()+ def test_switch_session_expected_session_id_refuses_moved_route(self, tmp_path):+ """With ``expected_session_id`` the repoint is a CAS: a route that moved past the caller's+ snapshot is left alone (None), while a matching snapshot still switches."""+ with patch("gateway.session.SessionStore._ensure_loaded"):+ store = SessionStore(sessions_dir=tmp_path / "sessions", config=GatewayConfig())+ store._loaded = True+ source = SessionSource(platform=Platform.FEISHU, chat_id="chat-2", chat_type="dm", user_id="user-2")+ entry = store.get_or_create_session(source)++ assert store.switch_session(entry.session_key, "target", expected_session_id="someone-else") is None+ assert store.lookup_by_session_key(entry.session_key).session_id == entry.session_id++ switched = store.switch_session(entry.session_key, "target", expected_session_id=entry.session_id)+ assert switched is not None and switched.session_id == "target"+def test_switch_session_rebinds_full_compression_lineage(self, tmp_path):from hermes_state import SessionDB