The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): retarget an admission that reserved the rotated-away route
Teknium3ddf2da123ae
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex e074c5b0417..dc062223ebc 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -108,6 +108,9 @@ class SessionAuthority:# session id -> end_reason of a last-viewer close still waiting for an idle FIFO# (gateway/session_viewer_close); a viewer attaching again cancels it.self.pending_closes = {}+ # Logical owner rotated away by the exhaustion auto-reset -> its session key: an admission+ # that reserved it before the rotation commits on that key's current route instead.+ self.rotated_owners = {}def authorize(self, actor, ref, capability):"""Every handler calls this first, so a later ``self.sessions[ref.session_id]`` is@@ -363,17 +366,22 @@ class SessionAuthority:identity = json.dumps([source.profile, source.platform.value, source.chat_id,source.thread_id, source.user_id], separators=(',', ':'))request_id = str(payload['native_text_v1']['event']['message_id'] or uuid.uuid4().hex)+ committed = [ref] # the row's target: the write may retarget a rotated-away reservation++ def admitted(row):+ committed[0] = SessionRef(self.profile_id, row.get('target_session_id') or ref.session_id)+ return self._admitted(committed[0], event, row)return await tracked_write(self, partial(self._admit_native_write, principal_id='messaging:' + identity, session_id=ref.session_id,request_id=request_id, payload=payload, authorize=self._admission_gate()),- then=partial(self._admitted, ref, event), ordered=True,- after=partial(self._schedule_admitted, ref))+ then=admitted, ordered=True, after=lambda _receipt: self._schedule_admitted(committed[0]))def _admit_native_write(self, *, principal_id, session_id, request_id, payload, authorize):# Off the loop and in admission order: the redelivery reconcile reads the ledger it decides# against, so a concurrent first delivery of the same message cannot slip between them.from gateway.session_ingress_media import drop_capture_lease, reconcile_native_retry, release_unheld_mediafresh = payload.get('native_text_v1', {}).get('media', [])+ session_id = self._current_owner(session_id)try:payload = reconcile_native_retry(self.db, principal_id=principal_id, session_id=session_id,request_id=request_id, payload=payload)@@ -385,6 +393,16 @@ class SessionAuthority:release_unheld_media(self.db, fresh, retain_history=False)raise+ def _current_owner(self, session_id):+ """``session_id`` unless the exhaustion auto-reset rotated it away after this admission+ reserved it: then the live fresh session its route now names (the moved rows' home)."""+ route = self.rotated_owners.get(session_id)+ if route is None:+ return session_id+ entry = self.runner.session_store.lookup_by_session_key(route)+ current = self.logical_owner(entry.session_id) if entry is not None else session_id+ return current if current in self.sessions else session_id+def _admitted(self, ref, event, row):if event is not None:event._gateway_accepted = Truediff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex f3c6a395697..121b05afcdb 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -305,8 +305,9 @@ async def reset_and_rehome_messages(runner, session_key, old_session_id):The rotation (sessions.json) and the move (one SQLite transaction) run in one worker stepordered with native admissions, not atomically across the two stores: a redelivery that- resolves the route to the fresh session commits after the move and dedupes onto the moved row.- Returns ``(entry, release)``. Until the caller runs ``release()``+ resolves the route to the fresh session commits after the move and dedupes onto the moved row,+ and one that reserved the old route before the rotation is retargeted at commit+ (``_admit_native_write``). Returns ``(entry, release)``. Until the caller runs ``release()``(once, after its conversation cleanup and topic binding sync, also on failure) the freshsession's ``claim_gate`` is held, so no scheduler (a redelivery, a moved route wake, thismove) starts a turn there against stale state; ``release()`` then schedules its FIFO."""@@ -330,6 +331,8 @@ async def reset_and_rehome_messages(runner, session_key, old_session_id):return entry, None, []if authority.db.get_session(new.session_id) is None:authority.db.create_session(new.session_id, source=live.source.platform.value)+ # An admission that reserved the old route before this rotation commits after it.+ authority.rotated_owners[old.session_id] = session_keyreturn entry, new, rehome_queued_inputs(authority.db, epoch=authority.epoch, old_session_id=old.session_id,new_session_id=new.session_id, principal_prefix='messaging:')diff --git a/tests/gateway/test_native_fifo_context_exhaustion.py b/tests/gateway/test_native_fifo_context_exhaustion.pyindex a4a1233354e..272d2610ef6 100644--- a/tests/gateway/test_native_fifo_context_exhaustion.py+++ b/tests/gateway/test_native_fifo_context_exhaustion.py@@ -206,3 +206,55 @@ async def test_no_scheduler_starts_the_fresh_fifo_before_reset_cleanup_finishes(assert executed == [("A", old.session_id), ("B", new), ("C", new)]assert events.index("sync:done") < events.index("turn:B")++async def test_admission_reserved_on_the_old_route_commits_on_the_fresh_session(native, monkeypatch):+ """A retry of queued B and a new D that reserved the old route before the reset commit after+ the re-home: B dedupes onto its moved row (same admission id), D queues behind it there."""+ import threading+ from gateway.session_results import execution_result+ runner, authority, db = native.runner, native.authority, native.authority.db+ loop = asyncio.get_running_loop()+ admitted = [await _admit(native, text) for text in ("A", "B", "C")]+ old = admitted[0][1].ref+ reserve_real, held, release = authority._reserve_route, [], threading.Event()++ def held_reserve(src):+ answer = reserve_real(src)+ loop.call_soon_threadsafe(held.append, answer)+ assert release.wait(10)+ return answer++ monkeypatch.setattr(authority, "_reserve_route", held_reserve)+ late = [asyncio.create_task(_admit(native, "B", admitted[1][0])), asyncio.create_task(_admit(native, "D"))]+ for _ in range(250):+ if len(held) == 2:+ break+ await asyncio.sleep(0.02)+ assert [sid for sid, _ in held] == [old.session_id] * 2+ executed, fresh = [], {}++ async def turn(event, source, session_key, run_generation):+ entry = runner.session_store.lookup_by_session_key(session_key)+ executed.append((event.text, entry.session_id))+ captured = execution_result.get()+ if event.text == "A":+ result = {"failed": True, "compression_exhausted": True, "messages": []}+ captured["result"] = result+ _, new_entry = await runner._hmwa_compression_exhaustion_reset(+ result, "context exhausted", entry, session_key, source)+ fresh["sid"] = new_entry.session_id+ else:+ captured["result"] = {"final_response": "reply", "messages": []}+ return "reply"++ monkeypatch.setattr(runner, "_handle_message_with_agent", turn)+ await authority._drain(old) # A exhausts; reset + re-home finish while B/D hold old reservations+ release.set()+ (_, retry), (_, late_d) = await asyncio.gather(*late)+ new = fresh["sid"]+ assert retry.admission_id == admitted[1][1].admission_id+ assert retry.ref.session_id == late_d.ref.session_id == new+ await authority._drain(SessionRef(authority.profile_id, new))+ assert executed == [("A", old.session_id), ("B", new), ("C", new), ("D", new)]+ assert [r["request_id"] for r in list_session_admissions(db, session_id=old.session_id, pending_only=False)] == ["A"]