Skip to content

The agent that grows with you

fix(gateway): ledger a queued chain's terminal reply under its own inbound id

Alexander Russell6532d9d8dae4
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 9db82e46feb..228148bdb48 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -3652,8 +3652,13 @@ class BasePlatformAdapter(ABC):
if not await asyncio.to_thread(ledger_enabled):
return None
source = event.source
+ # ``ledger_message_id`` wins when set: a queued chain's final answers the last message
+ # of the chain, not the event that opened it (see ``MessageEvent.ledger_message_id``).
+ _ledger_id = getattr(event, "ledger_message_id", None)
+ if _ledger_id is None:
+ _ledger_id = getattr(event, "message_id", "")
obligation_id = compute_obligation_id(
- session_key, str(getattr(event, "message_id", "") or ""), text_content)
+ session_key, str(_ledger_id or ""), text_content)
await asyncio.to_thread(
record_obligation, obligation_id=obligation_id, session_key=session_key,
platform=str(getattr(source.platform, "value", source.platform)),
diff --git a/gateway/platforms/event.py b/gateway/platforms/event.py
index 29fbf983bfd..d5353e3a48c 100644
--- a/gateway/platforms/event.py
+++ b/gateway/platforms/event.py
@@ -45,6 +45,13 @@ class MessageEvent:
source: SessionSource = None
raw_message: Any = None
message_id: Optional[str] = None
+ # Delivery-ledger identity for the final send, when it differs from ``message_id``. A queued
+ # (/queue) chain answers the LAST message of the chain, so its final send has to be ledgered
+ # under that message's id. Keyed on the opening event's id instead, two chained turns carrying
+ # the same text collide on one obligation id and the earlier turn's row is overwritten (a
+ # refused first reply then reads as delivered). Reply routing is unaffected: the reply anchor
+ # still comes from this event.
+ ledger_message_id: Optional[str] = None
# Platform update id (Telegram ``update_id``): ``/restart`` records it so the new gateway
# advances past it even if PTB's shutdown ACK times out.
platform_update_id: Optional[int] = None
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 4eb8f1e0bf8..59baa0a286f 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -1974,6 +1974,15 @@ class GatewayTurnMixin:
)
_turn_seconds = time.monotonic() - _turn_started_monotonic
+ # A queued (/queue) chain answered the LAST message of the chain, so the outer final
+ # send (bracketed by the adapter against this event) must be ledgered under that
+ # message's id or it collides with an earlier turn's row carrying the same text. Reply
+ # routing is untouched: the anchor still comes from this event.
+ if isinstance(agent_result, dict):
+ _terminal_inbound = agent_result.get("queued_terminal_inbound_id")
+ if _terminal_inbound:
+ event.ledger_message_id = str(_terminal_inbound)
+
await self._hmwa_stop_typing_for_turn(event, source)
if not self._is_session_run_current(_quick_key, run_generation):
@@ -3506,7 +3515,16 @@ class GatewayTurnMixin:
event_message_id=next_message_id, inbound_message_id=next_inbound_id,
channel_prompt=next_channel_prompt, message_type=next_message_type,
)
- return _preserve_queued_followup_history_offset(result, followup_result)
+ merged = _preserve_queued_followup_history_offset(result, followup_result)
+ # The TERMINAL turn of the chain owns the ledger identity for the outer final send, which
+ # the adapter brackets against the event that OPENED the chain. Without this the terminal
+ # reply is recorded under the first message's id, so a first reply that was refused (flood
+ # control) has its outstanding row replaced and marked delivered by an identical-text
+ # terminal reply, and is never redelivered. A deeper recursion has already set its own id,
+ # so only fill the key while it is still absent: the innermost turn wins.
+ if isinstance(merged, dict) and "queued_terminal_inbound_id" not in merged:
+ merged = {**merged, "queued_terminal_inbound_id": next_inbound_id}
+ return merged
async def _run_agent_cleanup_turn_tasks(
self, turn_ctx: TurnContext, *, progress_task: Any, log_task: Any, interrupt_monitor: "asyncio.Task",
diff --git a/tests/gateway/test_queued_final_ledger.py b/tests/gateway/test_queued_final_ledger.py
index 9f52459fd42..ef19e15f41f 100644
--- a/tests/gateway/test_queued_final_ledger.py
+++ b/tests/gateway/test_queued_final_ledger.py
@@ -336,3 +336,112 @@ async def test_a_chained_queued_turn_carries_its_own_inbound_id():
runner._run_agent.assert_awaited_once()
assert runner._run_agent.await_args.kwargs["inbound_message_id"] == "6002"
assert runner._run_agent.await_args.kwargs["event_message_id"] is None
+
+
+# ---------------------------------------------------------------------------
+# A chain's terminal reply must not overwrite an earlier turn's row.
+# ---------------------------------------------------------------------------
+
+async def test_the_terminal_turn_of_a_chain_is_ledgered_under_its_own_inbound_id():
+ """Two turns of one queued chain answering with the SAME text must keep two ledger rows.
+
+ The outer final send is bracketed by the adapter against the event that OPENED the chain. Keyed
+ on that event's id, a terminal reply carrying the same text as an earlier refused reply computes
+ the earlier row's obligation id, replaces its outstanding row and marks it delivered, so the
+ refused reply is never redelivered. ``MessageEvent.ledger_message_id`` carries the terminal
+ turn's own inbound id so the rows stay distinct. ``_send_with_retry`` is stubbed here because
+ the retry ladder is covered elsewhere and this pins the ledger identity only.
+ """
+ from gateway.platforms.base import MessageEvent
+
+ same_text = "Done."
+ adapter = _telegram_adapter()
+ # Turn A (inbound 101): its queued final is refused by flood control and stays outstanding.
+ adapter._send_with_retry = AsyncMock(
+ return_value=SendResult(success=False, error="flood_control:30.0"))
+ await _deliver(adapter, text=same_text, anchor="101", inbound_id="101")
+
+ first = _rows()
+ assert len(first) == 1
+ assert first[0]["state"] == "failed"
+ turn_a_id = first[0]["obligation_id"]
+
+ # Turn B is the chain's TERMINAL turn (inbound 102). The adapter still holds turn A's event, so
+ # only the ledger override distinguishes the row.
+ adapter._send_with_retry = AsyncMock(return_value=SendResult(success=True, message_id="901"))
+ event = MessageEvent(text="hi again", source=_source(), message_id="101",
+ ledger_message_id="102")
+ await adapter._send_final_text(event, SESSION_KEY, same_text, {}, False, 0, lambda _r: None)
+
+ rows = {r["obligation_id"]: r for r in _rows()}
+ assert len(rows) == 2, "the terminal reply reused the earlier turn's obligation id"
+ assert rows[turn_a_id]["state"] == "failed", \
+ "turn A's refused reply was overwritten and would never be redelivered"
+ assert rows[dl.compute_obligation_id(SESSION_KEY, "102", same_text)]["state"] == "delivered"
+
+
+async def test_an_unchained_turn_still_keys_on_its_own_event_id():
+ """No override means no behaviour change: the event's own id keys the row, as before."""
+ from gateway.platforms.base import MessageEvent
+
+ adapter = _telegram_adapter()
+ adapter._send_with_retry = AsyncMock(return_value=SendResult(success=True, message_id="902"))
+ event = MessageEvent(text="hi", source=_source(), message_id=INBOUND_ID)
+
+ assert event.ledger_message_id is None
+ await adapter._send_final_text(event, SESSION_KEY, TEXT, {}, False, 0, lambda _r: None)
+
+ assert _rows()[0]["obligation_id"] == dl.compute_obligation_id(SESSION_KEY, INBOUND_ID, TEXT)
+
+
+def _chain_runner_and_ctx(followup_return):
+ """A runner whose recursive ``_run_agent`` returns ``followup_return``, plus a topic turn."""
+ from gateway.run import GatewayRunner
+
+ runner = _runner()
+ runner._MAX_INTERRUPT_DEPTH = 8
+ runner._run_agent = AsyncMock(return_value=followup_return)
+ runner._run_agent_deliver_first_response = AsyncMock()
+ runner._is_goal_continuation_event = MagicMock(return_value=False)
+ runner._session_key_for_source = MagicMock(return_value=TOPIC_SESSION_KEY)
+ runner._prepare_profile_scoped_inbound_message_text = AsyncMock(return_value="the follow-up")
+ runner._reply_anchor_for_event = MagicMock(return_value=None)
+ runner._adapter_for_source = MagicMock(return_value=None)
+ runner._refresh_agent_cache_message_count = AsyncMock()
+ topic = _source(chat_id="-1001", thread_id="7", chat_type="supergroup")
+ turn_ctx = SimpleNamespace(
+ source=topic, session_id="sid", session_key=TOPIC_SESSION_KEY, run_generation=1,
+ _interrupt_depth=0, history=[], _status_thread_metadata={"thread_id": "7"},
+ context_prompt=None, result_holder=[None])
+ pending_event = SimpleNamespace(
+ source=topic, message_id="6002", channel_prompt=None, message_type=None)
+ return GatewayRunner, runner, turn_ctx, pending_event
+
+
+async def test_the_chain_returns_the_terminal_inbound_id_to_the_outer_bracket():
+ """The outer handler needs the terminal turn's id to ledger the final send under it."""
+ GatewayRunner, runner, turn_ctx, pending_event = _chain_runner_and_ctx(
+ {"final_response": "done", "messages": []})
+
+ merged = await GatewayRunner._run_agent_queued_followup(
+ runner, turn_ctx, adapter=None, pending="hi again", pending_event=pending_event,
+ response="resp", result={"interrupted": True, "messages": []}, stream_task=None)
+
+ assert merged["queued_terminal_inbound_id"] == "6002"
+
+
+async def test_a_deeper_chain_keeps_the_innermost_inbound_id():
+ """Chained follow-ups nest, and the LAST message answered owns the ledger identity, so an id
+ already set by a deeper recursion must not be overwritten on the way out."""
+ GatewayRunner, runner, turn_ctx, pending_event = _chain_runner_and_ctx(
+ {"final_response": "done", "messages": [], "queued_terminal_inbound_id": "6003"})
+
+ merged = await GatewayRunner._run_agent_queued_followup(
+ runner, turn_ctx, adapter=None, pending="hi again", pending_event=pending_event,
+ response="resp", result={"interrupted": True, "messages": []}, stream_task=None)
+
+ assert merged["queued_terminal_inbound_id"] == "6003"