Skip to content

The agent that grows with you

fix(gateway): Telegram topic-binding heal cannot re-pin a route /new moved during its lookups

teknium13e408dcc2a74
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index bc3cc7619c0..28d6aafde3f 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -413,8 +413,12 @@ class GatewayTurnMixin:
bound_session_id = canonical_session_id
if bound_session_id and bound_session_id != session_entry.session_id:
# Route through SessionStore so the key → id mapping persists and the previous lane
- # session ends cleanly (in-place mutation split-brained the JSON index).
- switched = await self.async_session_store.switch_session(session_key, bound_session_id)
+ # session ends cleanly (in-place mutation split-brained the JSON index). The two DB
+ # awaits above are a window for /new or /resume to move the route; the CAS on the
+ # snapshot id lets that win instead of being clobbered by a stale binding.
+ switched = await self.async_session_store.switch_session(
+ session_key, bound_session_id, expected_session_id=session_entry.session_id,
+ )
if switched is not None:
session_entry = switched
if bound_session_id and bound_session_id != stored_session_id:
diff --git a/tests/gateway/test_telegram_topic_mode.py b/tests/gateway/test_telegram_topic_mode.py
index a3ce15b32fb..e47e8a8c525 100644
--- a/tests/gateway/test_telegram_topic_mode.py
+++ b/tests/gateway/test_telegram_topic_mode.py
@@ -111,7 +111,7 @@ def _make_runner(session_db=None):
# Default switch_session impl: returns a SessionEntry carrying the target
# session_id. Mirrors SessionStore.switch_session semantics for tests that
# exercise Telegram topic binding rebinds without a real store.
- def _switch_session(session_key, target_session_id):
+ def _switch_session(session_key, target_session_id, *, expected_session_id=None):
return SessionEntry(
session_key=session_key,
session_id=target_session_id,
@@ -493,7 +493,7 @@ async def test_topic_binding_follows_compression_tip_on_read(tmp_path, monkeypat
# requested; capture the requested id for assertion.
switched_to: dict = {}
- def fake_switch(_key, new_session_id):
+ def fake_switch(_key, new_session_id, *, expected_session_id=None):
switched_to["id"] = new_session_id
return SessionEntry(
session_key=topic_key,
@@ -532,6 +532,34 @@ async def test_topic_binding_follows_compression_tip_on_read(tmp_path, monkeypat
assert refreshed["session_id"] == "child-session"
+async def test_topic_binding_heal_switches_with_cas_on_snapshot_session(tmp_path):
+ """The topic-binding heal repoints the route as a compare-and-swap on the session it resolved.
+
+ ``_hmwa_heal_telegram_topic_binding`` awaits two DB lookups between reading the route and
+ calling ``switch_session``; a /new or /resume that lands in that window must win, so the
+ switch is pinned to the snapshot ``session_entry.session_id`` via ``expected_session_id=``.
+ """
+ session_db = SessionDB(db_path=tmp_path / "state.db")
+ session_db.enable_telegram_topic_mode(chat_id="208214988", user_id="208214988")
+ session_db.create_session(session_id="bound-session", source="telegram", user_id="208214988")
+ topic_source = _make_source(thread_id="17585")
+ topic_key = build_session_key(topic_source)
+ session_db.bind_telegram_topic(
+ chat_id="208214988", thread_id="17585", user_id="208214988",
+ session_key=topic_key, session_id="bound-session",
+ )
+ runner = _make_runner(session_db=session_db)
+ snapshot = runner.session_store.get_or_create_session(topic_source)
+ assert snapshot.session_id != "bound-session"
+
+ await runner._hmwa_heal_telegram_topic_binding(topic_source, snapshot, topic_key)
+
+ runner.session_store.switch_session.assert_called_once_with(
+ topic_key, "bound-session", expected_session_id=snapshot.session_id,
+ )
+
+
@pytest.mark.asyncio
async def test_topic_root_command_lists_unlinked_sessions_for_restore(tmp_path, monkeypatch):
import gateway.run as gateway_run
diff --git a/website/docs/developer-guide/gateway-session-lifecycle.md b/website/docs/developer-guide/gateway-session-lifecycle.md
index 0151b31af93..e6c46286fc7 100644
--- a/website/docs/developer-guide/gateway-session-lifecycle.md
+++ b/website/docs/developer-guide/gateway-session-lifecycle.md
@@ -170,7 +170,7 @@ SessionStore(sessions_dir: Path, config: GatewayConfig, has_active_processes_fn=
| `get_or_create_session(source, force_new=False)` | Core entry point. Returns existing or creates new `SessionEntry`. Evaluates explicit suspension and restart recovery state. Creates/ends SQLite records. |
| `update_session(session_key, last_prompt_tokens=None)` | Lightweight metadata update after an interaction. Bumps `updated_at`, optionally records `last_prompt_tokens`. |
| `reset_session(session_key, display_name=None)` | Explicit reset (from `/new` or `/reset`). Creates new `session_id`, sets `is_fresh_reset=True`. Ends old SQLite session, creates new one. |
-| `switch_session(session_key, target_session_id)` | Switch to a different existing session ID (from `/resume`). Ends current SQLite session, reopens target. |
+| `switch_session(session_key, target_session_id, *, expected_session_id=None)` | Switch to a different existing session ID (from `/resume`). Ends current SQLite session, reopens target. With `expected_session_id=` the repoint is a compare-and-swap: returns `None` without switching when the key no longer points at that session, so a caller that resolved against a snapshot across an `await` (async-delegation re-pin, Telegram topic-binding heal) cannot overwrite a concurrent `/new` or `/resume`. |
| `suspend_session(session_key)` | Mark session as `suspended=True` (from `/stop`). Forces auto-reset on next access. |
| `mark_resume_pending(session_key, reason)` | Mark session as `resume_pending=True` (from drain timeout). Preserves session_id on next access. Will NOT override `suspended=True`. |
| `clear_resume_pending(session_key)` | Clear `resume_pending` after a successful resumed turn. Called from gateway after `run_conversation()` returns. |