The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): claim a follower only after the settled turn's marker is released
Teknium506325678179
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex bf86dd56d77..1022adda4b9 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -4378,12 +4378,12 @@ class BasePlatformAdapter(ABC):return result, delivery_adapterasync def _release_turn_marker(self, event: MessageEvent) -> None:- """Clear the crash-recovery marker the runner handed to this delivery lifecycle- (``_turn_marker_handoff``): only once the final reply is ledgered or nothing more is owed,- so no kill leaves a persisted reply with neither marker nor ledger row. Idempotent."""+ """Clear the crash marker handed to this delivery lifecycle only once the final reply is ledgered or+ nothing more is owed (no kill leaves a persisted reply with neither), then wake the drain. Idempotent."""if (getattr(event, "_turn_marker_handoff", False) and getattr(event, "_gateway_active_turn_token", None)and self.gateway_runner is not None):await self.gateway_runner._clear_durable_active_turn(event)+ getattr(event, "_gateway_marker_released", asyncio.Event()).set()async def _send_final_text(self, event: MessageEvent, session_key: str, text_content: str, metadata: dict[str, Any],diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex fcf5318aa87..42bf2000830 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -6,6 +6,7 @@ Transport attachment never constructs an agent or takes a turn lease.from __future__ import annotationsimport asyncio+import contextlibfrom dataclasses import asdict, dataclass, fieldfrom functools import partialimport sqlite3@@ -25,6 +26,8 @@ from hermes_state_runtime import (# Capped backoff for a claim refused by transient storage (writer lock, full disk)._CLAIM_RETRY_MIN_S, _CLAIM_RETRY_MAX_S = 0.25, 5.0+# Longest a settled turn's adapter may hold its adopted crash marker before the follower is claimed.+_MARKER_RELEASE_WAIT_S = 60.0@dataclass@@ -853,9 +856,24 @@ class SessionAuthority:waiter_replies(self).pop(admission_id, None)from gateway.session_ingress import deliver_settledawait deliver_settled(self, admission_id)- waiter = self.waiters.pop(admission_id, None)- if waiter is not None and not waiter.done():- waiter.set_result(response)+ await self._resolve_settled_waiter(admission_id, response)++ async def _resolve_settled_waiter(self, admission_id, response):+ """Hand the settled reply to its waiter. The adapter sending it adopted the turn's crash marker+ and releases it once the reply is ledgered (seconds with auto-TTS); a follower claimed before+ that replaces the one-slot marker, so a kill in between would lose the persisted reply: the+ drain waits for that release (bounded; never while draining or retiring)."""+ adopter = getattr(self, 'marker_adopters', {}).get(admission_id)+ released = None+ if adopter is not None and getattr(adopter, '_gateway_active_turn_token', None):+ released = adopter._gateway_marker_released = asyncio.Event()+ waiter = self.waiters.pop(admission_id, None)+ if waiter is None or waiter.done():+ return+ waiter.set_result(response)+ if released is not None and not (self.runner._draining or self.retiring):+ with contextlib.suppress(TimeoutError):+ await asyncio.wait_for(released.wait(), _MARKER_RELEASE_WAIT_S)async def initialize_session_authority(runner, *, profile_id, instance_id, db=None, register=True):diff --git a/tests/gateway/test_follower_marker_handoff.py b/tests/gateway/test_follower_marker_handoff.pynew file mode 100644index 00000000000..64bd6aaaa68--- /dev/null+++ b/tests/gateway/test_follower_marker_handoff.py@@ -0,0 +1,67 @@+"""A queued follower is not claimed while the settled turn's crash marker is still with its adapter."""+import asyncio+from functools import partial+from types import SimpleNamespace++import pytest+++async def test_follower_is_claimed_only_after_the_settled_turn_released_its_adopted_marker(tmp_path, monkeypatch):+ """The adapter that sends turn one's reply adopted its crash marker and releases it only once the+ reply is in the delivery ledger (seconds with auto-TTS). Claiming the follower first lets its+ mark_turn_active overwrite that one-slot marker: a kill in between leaves the follower's marker+ (cleared at boot as unknown) and turn one's persisted reply is never sent."""+ from gateway.platforms.base import BasePlatformAdapter+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.session import AsyncSessionStore+ from gateway.session_contract import Principal, SessionRef, Submission+ from gateway.session_ingress import admit_message+ from tests.gateway.test_prompt_attachments import _authority++ one_running, follower_queued = asyncio.Event(), asyncio.Event()+ slot_at_follower = []++ async def answer(event):+ if event.text == 'two':+ slot_at_follower.append(store._entries[key].active_turn_token)+ await GatewayRunner._mark_durable_active_turn(runner, event, key)+ if event.text == 'one':+ one_running.set()+ await follower_queued.wait()+ return 'reply to ' + event.text+ authority = await _authority(tmp_path, monkeypatch, answer)+ store = authority.runner.session_store+ source = authority.sessions['s'].source+ key = store.get_or_create_session(source).session_key+ runner = SimpleNamespace(async_session_store=AsyncSessionStore(store))+ runner._clear_durable_active_turn = partial(GatewayRunner._clear_durable_active_turn, runner)+ authority.runner._clear_durable_active_turn = runner._clear_durable_active_turn+ adapter = SimpleNamespace(gateway_runner=runner)+ actor = Principal('human', 'p', frozenset({'session:submit'}), 't')+ ref = SessionRef('p', 's')++ async def admit_native(event):+ return await authority.submit(actor, Submission(event.text, ref, {'text': event.text}, 'queue'))+ monkeypatch.setattr(authority, 'admit_native', admit_native)++ async def adapter_lifecycle(event):+ # BasePlatformAdapter._process_message_background: hand-off on, await the reply, then+ # (auto-TTS, ledger write) release the adopted marker.+ event._turn_marker_handoff = True+ reply = await admit_message(authority, event)+ await asyncio.sleep(0.3)+ await BasePlatformAdapter._release_turn_marker(adapter, event)+ return reply++ first = asyncio.create_task(adapter_lifecycle(MessageEvent(text='one', source=source)))+ await asyncio.wait_for(one_running.wait(), 5)+ follower = await authority.submit(actor, Submission('two', ref, {'text': 'two'}, 'queue'))+ follower_queued.set()+ assert await asyncio.wait_for(first, 10) == 'reply to one'+ from hermes_state_runtime import get_session_admission+ async with asyncio.timeout(10):+ while get_session_admission(authority.db, admission_id=follower.admission_id)['status'] != 'terminal':+ await asyncio.sleep(0.02)+ assert slot_at_follower == [None], "the follower's marker overwrote turn one's before its reply was ledgered"