The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): ledger-bracket the queued-lane final send
Alexander Russellc237c492cdc7
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex f5084100571..90d8d416be5 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -17,6 +17,7 @@ from pathlib import Pathfrom typing import Any, Dict, Optional, castfrom gateway.config import Platform, _BUILTIN_PLATFORM_VALUES+from gateway.platforms.base import _mark_notify_metadatafrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.session import SessionEntry, SessionSourcefrom gateway.run_shutdown import _log_suppressed, _notice_target_key, _send_error, _send_failed@@ -316,8 +317,12 @@ class GatewayNotificationsMixin:self, response: str, source: SessionSource, adapter,metadata: Optional[Dict[str, Any]] = None, event_message_id: Optional[str] = None,text_already_delivered: bool = False, deliver_media: bool = True, stream_consumer=None,+ session_key: Optional[str] = None,) -> None:- """Deliver a queued response using the normal text+attachment split."""+ """Deliver a queued response using the normal text+attachment split.++ ``session_key`` lets the text send record a delivery-ledger obligation like the normal final+ send does (see ``_send_queued_final_text``); without it the send stays unledgered."""from gateway.run import _strip_response_attachments_for_direct_sendif not text_already_delivered:text_content = _strip_response_attachments_for_direct_send(response, adapter)@@ -357,7 +362,8 @@ class GatewayNotificationsMixin:except Exception as _qe:logger.debug("Queued-lane reconcile edit failed (%s); falling back to send.", _qe)if not _reconciled:- await adapter.send(source.chat_id, text_content, metadata=metadata)+ await self._send_queued_final_text(+ adapter, source, text_content, metadata, event_message_id, session_key)# Failed turns deliver their (normalized failure) text but must not upload attachments as if# they succeeded — mirrors the ``not agent_result.get("failed")`` completed-turn guard.if not deliver_media:@@ -367,6 +373,38 @@ class GatewayNotificationsMixin:thread_metadata=metadata,)+ async def _send_queued_final_text(+ self, adapter, source: SessionSource, text_content: str, metadata: Optional[Dict[str, Any]],+ event_message_id: Optional[str], session_key: Optional[str],+ ):+ """Send a queued-lane final through the adapter's ledger-bracketed final send.++ This lane used to call ``adapter.send`` bare and discard the result. A final refused here+ (flood control, a transport that just died) was gone for good: no delivery-ledger row was ever+ written, so neither the boot sweep nor the runtime redelivery could see it, and the queued+ follow-up ran as if the answer had landed. The normal final send records the obligation before+ the send and finalizes it from the result; this routes the queued lane through that same method+ so both lanes recover the same way. The event carries the inbound message id, so the obligation+ id matches the one the normal lane would compute for the same turn (idempotent re-record), and+ the reply is marked notify-worthy like every other user-visible final. Adapters without the+ base contract (relay doubles, third-party plugins) and sends without a session key keep the+ plain send. Returns the SendResult, or None when the adapter's send returned nothing+ (queued-final-ledger)."""+ bracketed = getattr(adapter, "_send_final_text", None)+ if session_key and callable(bracketed):+ results: list = []+ await bracketed(+ MessageEvent(text="", source=source, message_id=event_message_id), session_key,+ text_content, _mark_notify_metadata(metadata), False, 0, results.append)+ result = results[-1] if results else None+ else:+ result = await adapter.send(source.chat_id, text_content, metadata=metadata)+ if not getattr(result, "success", False):+ logger.warning(+ "Queued-lane final send to %s failed: %s", getattr(source, "chat_id", "?"),+ getattr(result, "error", None) or "no result")+ return result+def _schedule_update_notification_watch(self) -> None:"""Ensure a background task is watching for update completion."""existing_task = getattr(self, "_update_notification_task", None)diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex ae56c08d6cd..25ab2612fd8 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -3383,6 +3383,8 @@ class GatewayTurnMixin:metadata=turn_ctx._status_thread_metadata, event_message_id=turn_ctx.event_message_id,text_already_delivered=_already_streamed,deliver_media=not _delivery_result.get("failed"), stream_consumer=_sc,+ # The text send records a delivery-ledger obligation under this key (queued-final-ledger).+ session_key=session_key,)except Exception as e:logger.warning("Failed to send first response before queued message: %s", e)diff --git a/tests/gateway/test_queued_final_ledger.py b/tests/gateway/test_queued_final_ledger.pynew file mode 100644index 00000000000..bea5513e398--- /dev/null+++ b/tests/gateway/test_queued_final_ledger.py@@ -0,0 +1,255 @@+"""A queued-lane final is ledger-bracketed like the normal final send.++When a follow-up is queued behind a turn (a message typed while the agent worked, a+subagent batch reporting back), the first response is delivered by the queued lane in+``run_turn.py`` before the follow-up runs. That lane called ``adapter.send`` bare and+discarded the result: no delivery-ledger row was recorded, so a final refused there+(flood control, a transport that had just died) was lost for good. Neither the boot+sweep nor the runtime redelivery could see it, and the follow-up ran as if the answer+had landed. On 5 Sep 2026 two long replies were lost this way within an hour, both+refused by Telegram flood control while a delegation batch arrived the same second.++Now the queued lane routes its text send through the adapter's ``_send_final_text``,+the same ledger-bracketed method the normal lane uses: the obligation is recorded+before the send under the id the normal lane would compute for the same turn, the+result finalizes it, and the reply is marked notify-worthy like every other final.+The reconcile-by-edit path is unchanged. Adapters without the base contract and+sends without a session key keep the plain send.+"""++from __future__ import annotations++import logging+import os+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway import delivery_ledger as dl+from gateway.config import Platform, PlatformConfig+from gateway.platforms.base import BasePlatformAdapter, SendResult++SESSION_KEY = "agent:main:telegram:dm:5230977008"+CHAT = "5230977008"+INBOUND_ID = "5301"+TEXT = "**Yes.** I would make room for one island trip and one Balkan trip."++[email protected](autouse=True)+def _fresh_db(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setattr(dl, "_db_path", lambda: home / "state.db")+ monkeypatch.setattr(dl, "_owner_stamp", lambda: (os.getpid(), 202))+ monkeypatch.setattr(dl, "ledger_enabled", lambda config=None: True)+ yield+++def _rows():+ with dl._connect() as conn:+ cur = conn.execute(+ "SELECT obligation_id, session_key, state, attempts, last_error, content, chat_id, platform"+ " FROM delivery_obligations")+ return [dict(zip(("obligation_id", "session_key", "state", "attempts", "last_error", "content",+ "chat_id", "platform"), r)) for r in cur.fetchall()]+++def _source():+ return SimpleNamespace(platform=Platform.TELEGRAM, chat_id=CHAT, thread_id=None, chat_type="dm")+++def _telegram_adapter(send_result=None):+ """A real Telegram adapter (the base contract) whose transport send is a mock."""+ from plugins.platforms.telegram.adapter import TelegramAdapter++ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="test-token", extra={}))+ runner = MagicMock()+ runner._adapter_for_source = MagicMock(return_value=adapter)+ runner._schedule_flood_redelivery = MagicMock(return_value=187.0)+ adapter.gateway_runner = runner+ adapter.send = AsyncMock(return_value=send_result or SendResult(success=True, message_id="900"))+ adapter.edit_message = AsyncMock(return_value=SendResult(success=False, error="message to edit not found"))+ return adapter+++def _plain_adapter():+ """A relay-style double without the base contract: only ``send`` and the media helpers."""+ return SimpleNamespace(+ name="relay", extract_media=BasePlatformAdapter.extract_media,+ send=AsyncMock(return_value=SendResult(success=True, message_id="p1")))+++def _runner():+ from gateway.run import GatewayRunner++ return object.__new__(GatewayRunner)+++async def _deliver(adapter, *, session_key=SESSION_KEY, stream_consumer=None, metadata=None, text=TEXT):+ from gateway.run import GatewayRunner++ await GatewayRunner._deliver_queued_first_response(+ _runner(), text, source=_source(), adapter=adapter, metadata=metadata, event_message_id=INBOUND_ID,+ text_already_delivered=False, deliver_media=False, stream_consumer=stream_consumer,+ session_key=session_key)+++# ---------------------------------------------------------------------------+# The bracket: record before the send, finalize from the result.+# ---------------------------------------------------------------------------++async def test_a_delivered_queued_final_is_recorded_and_marked_delivered():+ adapter = _telegram_adapter()++ await _deliver(adapter)++ rows = _rows()+ assert len(rows) == 1+ assert rows[0]["state"] == "delivered"+ assert rows[0]["session_key"] == SESSION_KEY+ assert rows[0]["content"] == TEXT+ assert (rows[0]["platform"], rows[0]["chat_id"]) == ("telegram", CHAT)+ adapter.send.assert_awaited_once()+++async def test_the_obligation_id_is_the_one_the_normal_lane_would_use():+ """Same turn, same text: re-recording from either lane is idempotent, never a second row."""+ adapter = _telegram_adapter()++ await _deliver(adapter)++ assert _rows()[0]["obligation_id"] == dl.compute_obligation_id(SESSION_KEY, INBOUND_ID, TEXT)+++async def test_a_flood_refused_queued_final_stays_in_the_ledger_as_failed(caplog):+ """The row survives the refusal, so the sweeps (and a flood timer, where present) can redeliver."""+ adapter = _telegram_adapter(SendResult(success=False, error="flood_control:185.0"))++ with caplog.at_level(logging.WARNING, logger="gateway.run"):+ await _deliver(adapter)++ rows = _rows()+ assert len(rows) == 1+ assert rows[0]["state"] == "failed"+ assert rows[0]["last_error"] == "flood_control:185.0"+ assert any("Queued-lane final send" in r.getMessage() and "flood_control:185.0" in r.getMessage()+ for r in caplog.records)+++async def test_any_other_refusal_is_recorded_as_failed_too():+ adapter = _telegram_adapter(SendResult(success=False, error="Forbidden: bot was blocked by the user"))++ await _deliver(adapter)++ assert _rows()[0]["state"] == "failed"+ assert "blocked" in _rows()[0]["last_error"]+++async def test_the_queued_final_is_sent_like_the_normal_final():+ """Reply anchor on the inbound message and a notify-worthy copy of the thread metadata."""+ adapter = _telegram_adapter()+ metadata = {"thread_id": "topic-7"}++ await _deliver(adapter, metadata=metadata)++ kwargs = adapter.send.await_args.kwargs+ assert kwargs["chat_id"] == CHAT+ assert kwargs["content"] == TEXT+ assert kwargs["reply_to"] == INBOUND_ID+ assert kwargs["metadata"]["notify"] is True+ assert kwargs["metadata"]["thread_id"] == "topic-7"+ assert metadata == {"thread_id": "topic-7"} # the caller's dict is cloned, not mutated+++# ---------------------------------------------------------------------------+# What is unchanged: reconcile-by-edit, plain adapters, no session key.+# ---------------------------------------------------------------------------++async def test_reconcile_by_edit_records_no_obligation():+ adapter = _telegram_adapter()+ adapter.edit_message = AsyncMock(return_value=SendResult(success=True, message_id="sealed-9"))+ sc = SimpleNamespace(message_id="sealed-9", _turn_split_delivery=False)++ await _deliver(adapter, stream_consumer=sc)++ adapter.edit_message.assert_awaited_once()+ adapter.send.assert_not_awaited()+ assert _rows() == []+++async def test_a_failed_reconcile_edit_falls_through_to_the_bracketed_send():+ adapter = _telegram_adapter() # edit_message fails by default+ sc = SimpleNamespace(message_id="sealed-9", _turn_split_delivery=False)++ await _deliver(adapter, stream_consumer=sc)++ adapter.send.assert_awaited_once()+ assert _rows()[0]["state"] == "delivered"+++async def test_an_adapter_without_the_base_contract_keeps_the_plain_send():+ adapter = _plain_adapter()++ await _deliver(adapter, metadata={"thread_id": "t"})++ adapter.send.assert_awaited_once_with(CHAT, TEXT, metadata={"thread_id": "t"})+ assert _rows() == []+++async def test_without_a_session_key_the_plain_send_is_kept():+ """No key, no ledger row possible: the send still happens, unbracketed, as before."""+ adapter = _telegram_adapter()++ await _deliver(adapter, session_key=None, metadata={"thread_id": "t"})++ adapter.send.assert_awaited_once_with(CHAT, TEXT, metadata={"thread_id": "t"})+ assert _rows() == []+++async def test_a_plain_send_failure_is_still_logged(caplog):+ adapter = _plain_adapter()+ adapter.send = AsyncMock(return_value=SendResult(success=False, error="flood_control:30.0"))++ with caplog.at_level(logging.WARNING, logger="gateway.run"):+ await _deliver(adapter)++ assert any("Queued-lane final send" in r.getMessage() for r in caplog.records)+++# ---------------------------------------------------------------------------+# The call site hands the session key over.+# ---------------------------------------------------------------------------++async def test_the_queued_lane_receives_the_session_key_from_the_turn():+ from gateway.run import GatewayRunner++ runner = _runner()+ runner._run_agent_stream_confirmed_final_delivery = MagicMock(return_value=False)+ runner._is_intentional_silence = MagicMock(return_value=False)+ runner._pop_post_delivery_callback = MagicMock(return_value=None)+ runner._deliver_queued_first_response = AsyncMock()+ turn_ctx = SimpleNamespace(+ session_key=SESSION_KEY, stream_consumer_holder=[None], source=_source(),+ _status_thread_metadata={"thread_id": None}, event_message_id=INBOUND_ID, run_generation=3)+ adapter = _telegram_adapter()++ await GatewayRunner._run_agent_deliver_first_response(+ runner, turn_ctx, adapter, {"final_response": TEXT}, {}, None)++ runner._deliver_queued_first_response.assert_awaited_once()+ kwargs = runner._deliver_queued_first_response.await_args.kwargs+ assert kwargs["session_key"] == SESSION_KEY+ assert kwargs["event_message_id"] == INBOUND_ID+ assert kwargs["text_already_delivered"] is False