Skip to content

The agent that grows with you

fix(gateway): recover agent after session reaped so messages are not silently dropped

finn76399ec7fdfe889
diff --git a/gateway/run.py b/gateway/run.py
index 399a6539484..803de79e94d 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -18483,6 +18483,55 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
)
self._release_running_agent_state(_quick_key)
+ # #99106: durable-reaped guard. A session whose routing row was
+ # ended in state.db (e.g. ``ws_orphan_reap`` / ``agent_close``) while
+ # the gateway stayed alive keeps its in-memory turn slot alive
+ # (``_is_session_running`` stays True). The priority fast-path would
+ # then queue every next user message into the dead runtime instead of
+ # healing the routing via ``get_or_create_session`` → ``reopen``.
+ # This is the live-gateway variant of #54878 and the #632 detached/
+ # 405 suppressions in production. Evict the stale slot so the next
+ # message falls through to the cold path and re-attaches or creates a
+ # fresh session; /status then correctly shows 代理运行中: 否 before the
+ # heal and a live turn after.
+ if self._is_session_running(_quick_key):
+ try:
+ _reap_store = getattr(self, "session_store", None)
+ # Guard against MagicMock in tests: only run on real SessionStore
+ # (which has a dict _entries and callable _is_session_ended_in_db).
+ _reap_entries = getattr(_reap_store, "_entries", None) if _reap_store else None
+ if not isinstance(_reap_entries, dict):
+ raise TypeError("not a real SessionStore")
+ _reap_lock = getattr(_reap_store, "_lock", None)
+ _is_ended = getattr(_reap_store, "_is_session_ended_in_db", None)
+ if not callable(_is_ended):
+ raise TypeError("missing _is_session_ended_in_db")
+ _reap_sid: str | None = None
+ if _reap_lock is not None:
+ with _reap_lock:
+ _reap_e = _reap_entries.get(_quick_key)
+ _reap_sid = getattr(_reap_e, "session_id", None) if _reap_e else None
+ else:
+ _reap_e = _reap_entries.get(_quick_key)
+ _reap_sid = getattr(_reap_e, "session_id", None) if _reap_e else None
+ if isinstance(_reap_sid, str) and _reap_sid:
+ _ended = _is_ended(_reap_sid)
+ if _ended is True:
+ logger.warning(
+ "Evicting stale _running_agents entry for %s — "
+ "durable session %s is ended (reaped) in state.db; "
+ "healing routing on next message (#99106)",
+ _quick_key,
+ _reap_sid,
+ )
+ self._invalidate_session_run_generation(
+ _quick_key,
+ reason="reaped_session_eviction",
+ )
+ self._release_running_agent_state(_quick_key)
+ except Exception:
+ logger.debug("reaped-session staleness check failed", exc_info=True)
+
if self._is_session_running(_quick_key):
# Resolve the command once; every command's mid-run behavior is
# declared on its CommandDef (busy_policy / busy_handler in