Skip to content

The agent that grows with you

fix(gateway): mark every flood redelivery and keep a released flood claim on the timer

Alexander Russell678b0649abed
diff --git a/gateway/delivery_ledger.py b/gateway/delivery_ledger.py
index 39627722870..a4421a63a77 100644
--- a/gateway/delivery_ledger.py
+++ b/gateway/delivery_ledger.py
@@ -39,19 +39,21 @@ _MAX_ROWS = 500
RECOVERED_MARKER = "♻️ Recovered reply — the gateway restarted during delivery, so this may be a duplicate:\n\n"
RECONNECTED_MARKER = ("♻️ Recovered reply — the messaging platform reconnected after the original "
"delivery failed, so this may be a duplicate:\n\n")
-# A chunked reply refused by flood control: the platform may have accepted the first chunk(s) before
-# refusing the rest, and the send result does not say which landed. Neither of the markers above tells
-# the truth here (no restart, no reconnect), so the rate limit gets its own.
-FLOOD_MARKER = ("♻️ Recovered reply — the messaging platform's rate limit refused the original before "
- "every part was accepted, so this may repeat some of it:\n\n")
+# A reply refused by flood control may have gone out as several requests (the adapter chunks long replies,
+# and MarkdownV2 escaping alone can push a reply that fits one message into two), and the platform may have
+# accepted the first chunk(s) before refusing the rest; the send result does not say which landed. The raw
+# length of the stored text says nothing about that, so every flood redelivery carries a marker, and neither
+# of the markers above tells the truth here (no restart, no reconnect): the rate limit gets its own.
+FLOOD_MARKER = ("♻️ Recovered reply — the messaging platform's rate limit refused the original, so part of "
+ "it may already have arrived above:\n\n")
# Runtime replay is fail-closed: only errors whose send contract proves they are transient reconnect
# failures. Permanent rejects (blocked bot, bad auth, missing chat) must not be retried on reconnect.
_RUNTIME_RETRYABLE_ERRORS = frozenset({"send_path_degraded"})
-# A final send the platform refused with flood control is the other transient case, and an unambiguous
-# one: a 429 means the message was never accepted, so redelivering it needs no duplicate marker, and the
-# platform said how long to wait. Adapters fail such sends closed as ``flood_control:<seconds>`` on
+# A final send the platform refused with flood control is the other transient case: a 429 means the refused
+# request was never accepted, and the platform said how long to wait. Adapters fail such sends closed as
+# ``flood_control:<seconds>`` on
# purpose (#91969) so that this ledger owns the wait instead of the send coroutine sleeping through it.
# Before this the row simply sat in ``failed`` until the next restart's sweep, which then redelivered it
# hours late under the "gateway restarted during delivery" marker (ledger-flood-retry).
@@ -59,10 +61,6 @@ FLOOD_ERROR_PREFIX = "flood_control:"
FLOOD_RETRY_DEFAULT_SECONDS = 60.0
FLOOD_RETRY_CAP_SECONDS = 15 * 60.0
FLOOD_RETRY_SLACK_SECONDS = 2.0
-# Telegram's message cap in UTF-16 code units. A reply that fits in one message is one request, so a flood
-# refusal of it proves nothing reached the chat. A longer reply is chunked and the send result does not say
-# which chunks landed before the refusal, so those keep the duplicate marker.
-FLOOD_SINGLE_MESSAGE_UNITS = 4096
def is_flood_error(error: Any) -> bool:
@@ -104,15 +102,6 @@ def flood_not_before(updated_at: Any, last_error: Any) -> float:
return stamp + flood_wait_seconds(last_error)
-def _utf16_units(text: Any) -> int:
- return len(str(text or "").encode("utf-16-le")) // 2
-
-
-def flood_non_delivery_is_certain(last_error: Any, content: Any) -> bool:
- """A flood refusal proves non-delivery only for a reply that went out as one message."""
- return is_flood_error(last_error) and _utf16_units(content) <= FLOOD_SINGLE_MESSAGE_UNITS
-
-
def _runtime_retryable(last_error: Any) -> bool:
text = str(last_error or "").strip().lower()
return text in _RUNTIME_RETRYABLE_ERRORS or is_flood_error(text)
@@ -290,15 +279,19 @@ def _update_state(obligation_id: str, state: str, error: str = "") -> None:
def _claimed_row(oid, session_key, platform, chat_id, thread_id, content, attempts, profile, *,
- needs_marker: bool, runtime: bool = False, flood: bool = False) -> Dict[str, Any]:
- """Claimed-row dict handed back for redelivery. A marked row names its own cause: ``flood`` (a chunked
- reply the rate limit refused part-way) gets FLOOD_MARKER at boot or at runtime, a ``runtime`` reconnect
- replay gets RECONNECTED_MARKER, and a boot-recovered crash keeps the runner's restart marker default."""
+ needs_marker: bool, runtime: bool = False, flood: bool = False,
+ last_error: Optional[str] = None) -> Dict[str, Any]:
+ """Claimed-row dict handed back for redelivery. A marked row names its own cause: ``flood`` (a reply
+ the rate limit refused, possibly after accepting part of it) gets FLOOD_MARKER at boot or at runtime, a
+ ``runtime`` reconnect replay gets RECONNECTED_MARKER, and a boot-recovered crash keeps the runner's
+ restart marker default. ``last_error`` is the row's pre-claim error, carried so a runtime claim that is
+ released unsent goes back to ``failed`` with the same error and keeps its retry eligibility."""
marker = FLOOD_MARKER if flood else (RECONNECTED_MARKER if runtime else None)
return {"obligation_id": oid, "session_key": session_key, "platform": platform, "chat_id": chat_id,
"thread_id": thread_id, "content": content, "needs_marker": needs_marker,
**({"marker": marker} if needs_marker and marker else {}), "profile": profile,
- **({"runtime_recovery": True} if runtime else {}), "attempts": attempts + 1}
+ **({"runtime_recovery": True} if runtime else {}),
+ **({"last_error": last_error} if last_error else {}), "attempts": attempts + 1}
def sweep_recoverable(now: Optional[float] = None, *, deliverable_platforms: Optional[set] = None,
@@ -355,12 +348,11 @@ def sweep_recoverable(now: Optional[float] = None, *, deliverable_platforms: Opt
WHERE obligation_id=? AND (owner_pid IS ? OR owner_pid=?)""",
(pid, started, now, 1 if flood_row else 0, 1 if flood_row else 0, oid, owner_pid, owner_pid))
if cursor.rowcount:
- # pending = never started, redeliver plainly; a flood refusal of a single-message reply =
- # never accepted, likewise plain; anything else (crashed mid-await, other rejection, a
- # chunked reply the platform may have partly accepted) carries the marker.
- plain = state == "pending" or (flood_row and flood_non_delivery_is_certain(last_error, content))
+ # pending = never started, redeliver plainly; anything else (crashed mid-await, other
+ # rejection, a flood refusal whose earlier chunks the platform may have accepted) carries
+ # the marker.
claimed.append(_claimed_row(oid, session_key, platform, chat_id, thread_id, content, attempts,
- adapter_profile, needs_marker=not plain, flood=flood_row))
+ adapter_profile, needs_marker=state != "pending", flood=flood_row))
return claimed
@@ -374,8 +366,8 @@ def sweep_failed_for_runtime(platform: str, now: Optional[float] = None, *,
rejected with ``send_path_degraded`` would stay stranded when only the adapter reconnects; this closes
that gap without weakening ownership: only rows stamped to this exact process instance, only
allowlisted transient errors, same attempts/staleness bounds, every update guarded by the prior owner
- stamp and ``failed`` state. Claimed rows always carry the reconnect marker (the failed send's ack is
- not safe to infer)."""
+ stamp and ``failed`` state. Claimed rows always carry a marker (the failed send's ack is not safe to
+ infer): the reconnect one, or the rate-limit one for a flood-refused row."""
now, (pid, started) = now if now is not None else time.time(), _owner_stamp()
if started is None: # PID alone cannot distinguish this process from a stale row left after PID
return [] # reuse; runtime replay is optional, so fail closed (startup recovery remains).
@@ -412,12 +404,12 @@ def sweep_failed_for_runtime(platform: str, now: Optional[float] = None, *,
WHERE obligation_id=? AND state='failed'
AND owner_pid IS ? AND owner_started_at IS ?""", owner_guard)
if cursor.rowcount:
- # A reconnect-retryable failure's ack may have been lost, so it carries the marker; a flood
- # refusal of a single-message reply was never accepted, so it is redelivered plainly.
+ # The failed send's ack may have been lost (reconnect) or its earlier chunks accepted
+ # (flood): every runtime redelivery carries a marker. The pre-claim error rides along so a
+ # claim released unsent keeps its flood retry eligibility.
claimed.append(_claimed_row(oid, session_key, row_platform, chat_id, thread_id, content,
- attempts, adapter_profile,
- needs_marker=not flood_non_delivery_is_certain(last_error, content),
- runtime=True, flood=is_flood_error(last_error)))
+ attempts, adapter_profile, needs_marker=True, runtime=True,
+ flood=is_flood_error(last_error), last_error=last_error))
return claimed
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 29d50709aac..7e53fe4d574 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -291,11 +291,15 @@ class GatewayStartupMixin:
return claimed
@staticmethod
- async def _release_runtime_claim_quiet(obligation_id, log_fmt: str) -> None:
- """Release a runtime delivery-ledger claim as ``send_path_degraded``; log-only on failure."""
+ async def _release_runtime_claim_quiet(obligation_id, log_fmt: str, error: str = "send_path_degraded") -> None:
+ """Release an unsent runtime delivery-ledger claim; log-only on failure. ``error`` is what the row
+ goes back to ``failed`` with: the claim's own pre-claim error when the caller knows it, so a
+ flood-refused row keeps its ``flood_control:<seconds>`` and stays on the flood timer's list (the
+ release re-stamps ``updated_at``, so it waits the platform's figure once more); else
+ ``send_path_degraded`` (ledger-flood-retry)."""
from gateway.delivery_ledger import release_runtime_claim
try:
- await asyncio.to_thread(release_runtime_claim, obligation_id, "send_path_degraded")
+ await asyncio.to_thread(release_runtime_claim, obligation_id, error)
except Exception:
logger.debug(log_fmt, obligation_id, exc_info=True)
@@ -438,7 +442,8 @@ class GatewayStartupMixin:
# attempt; startup claims keep their state (attempts cap + stale cutoff bound retries).
if adapter is None and row.get("runtime_recovery"):
await self._release_runtime_claim_quiet(
- row["obligation_id"], "failed to release undispatched runtime obligation %s"
+ row["obligation_id"], "failed to release undispatched runtime obligation %s",
+ error=row.get("last_error") or "send_path_degraded",
)
return adapter
@@ -471,7 +476,8 @@ class GatewayStartupMixin:
for row in claimed:
if row["obligation_id"] not in sendable_ids:
await self._release_runtime_claim_quiet(
- row["obligation_id"], "failed to release runtime delivery claim %s"
+ row["obligation_id"], "failed to release runtime delivery claim %s",
+ error=row.get("last_error") or "send_path_degraded",
)
return await self._redeliver_claimed_obligations(sendable)
diff --git a/tests/gateway/test_delivery_ledger_flood_retry.py b/tests/gateway/test_delivery_ledger_flood_retry.py
index 1812ca93fa1..3a008548685 100644
--- a/tests/gateway/test_delivery_ledger_flood_retry.py
+++ b/tests/gateway/test_delivery_ledger_flood_retry.py
@@ -16,10 +16,12 @@ Now:
- the runner arms one timer per adapter identity; the slot stays occupied until the
timer ends, only the running timer may arm its successor into it, and it re-arms
for whatever is still waiting;
-- a flood refusal of a single-message reply proves non-delivery, so that redelivery
- carries no duplicate marker; a chunked reply may have been partly accepted and
- carries one that names the rate limit; a claimed row's stale refusal is cleared so an interrupted resend is
- seen as uncertain by the next boot;
+- every flood redelivery carries a marker that names the rate limit (the platform may
+ have accepted earlier chunks, and the stored text's raw length cannot tell: MarkdownV2
+ escaping alone can turn a one-message reply into two requests); a claimed row's stale
+ refusal is cleared so an interrupted resend is seen as uncertain by the next boot; a
+ claim released unsent (resume flag not clearable, adapter gone) keeps its flood error
+ and so its place on the timer;
- at boot, a dead owner's not-yet-due flood row is adopted rather than resent early.
"""
@@ -146,18 +148,28 @@ def test_flood_not_before_is_the_refusal_time_plus_the_platform_wait():
assert dl.flood_not_before(None, "flood_control:9") == pytest.approx(9.0)
-def test_non_delivery_is_certain_only_for_a_single_message_reply():
- assert dl.flood_non_delivery_is_certain("flood_control:9", "x" * 4096) is True
- assert dl.flood_non_delivery_is_certain("flood_control:9", "x" * 4097) is False
- assert dl.flood_non_delivery_is_certain("flood_control:9", "\U0001F600" * 2049) is False, "UTF-16 units, not chars"
- assert dl.flood_non_delivery_is_certain("send_path_degraded", "x") is False
[email protected]("content", ["x" * 10, "." * 3000, "word " * 1200])
+def test_every_flood_redelivery_carries_the_rate_limit_marker(clock, monkeypatch, content):
+ """Raw length proves nothing about how many requests the adapter made: MarkdownV2 escaping turns 3000
+ dots into 6000 UTF-16 units, two Telegram messages, and the send result does not say which chunk was
+ refused. So there is no length-based certainty; the marker is unconditional, at runtime and at boot."""
+ _record("ob-runtime", content=content)
+ dl.mark_failed("ob-runtime", "flood_control:9")
+ (runtime_row,) = dl.sweep_failed_for_runtime("telegram", now=T0 + 20)
+ assert runtime_row["needs_marker"] is True and runtime_row["marker"] == dl.FLOOD_MARKER
+
+ _record("ob-boot", content=content)
+ dl.mark_failed("ob-boot", "flood_control:9")
+ monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False)
+ boot_rows = {row["obligation_id"]: row for row in dl.sweep_recoverable(now=T0 + 20)}
+ assert boot_rows["ob-boot"]["needs_marker"] is True and boot_rows["ob-boot"]["marker"] == dl.FLOOD_MARKER
# ---------------------------------------------------------------------------
# The runtime sweep: which rows it claims, when, and how it marks them.
# ---------------------------------------------------------------------------
-def test_runtime_sweep_claims_a_due_flood_row_plainly_and_clears_the_stale_refusal(clock):
+def test_runtime_sweep_claims_a_due_flood_row_under_the_rate_limit_marker_and_clears_the_stale_refusal(clock):
_record("ob-flood")
dl.mark_failed("ob-flood", "flood_control:185.0")
_record("ob-degraded")
@@ -168,10 +180,12 @@ def test_runtime_sweep_claims_a_due_flood_row_plainly_and_clears_the_stale_refus
claimed = {row["obligation_id"]: row for row in dl.sweep_failed_for_runtime("telegram", now=T0 + 200)}
assert set(claimed) == {"ob-flood", "ob-degraded"}, "a permanent rejection must never be replayed"
- assert claimed["ob-flood"]["needs_marker"] is False, "a 429 of a single message was never accepted"
- assert "marker" not in claimed["ob-flood"]
+ assert claimed["ob-flood"]["needs_marker"] is True
+ assert claimed["ob-flood"]["marker"] == dl.FLOOD_MARKER
+ assert claimed["ob-flood"]["last_error"] == "flood_control:185.0", "the pre-claim error rides along for a release"
assert claimed["ob-degraded"]["needs_marker"] is True
assert claimed["ob-degraded"]["marker"] == dl.RECONNECTED_MARKER
+ assert claimed["ob-degraded"]["last_error"] == "send_path_degraded"
flood = _row("ob-flood")
assert flood["state"] == "attempting" and flood["attempts"] == 1
assert flood["last_error"] is None, "the claim is a fresh attempt; the old refusal must not survive it"
@@ -219,7 +233,7 @@ def test_boot_sweep_adopts_a_dead_owners_flood_row_inside_its_wait(clock, monkey
assert dl.pending_flood_retries(now=T0 + 30)[0]["not_before"] == pytest.approx(T0 + 185)
-def test_boot_sweep_resends_a_due_flood_row_plainly_and_a_midsend_row_with_the_marker(clock, monkeypatch):
+def test_boot_sweep_resends_a_due_flood_row_under_the_rate_limit_marker_and_a_midsend_row_under_the_restart_one(clock, monkeypatch):
_record("ob-flood")
dl.mark_failed("ob-flood", "flood_control:185.0")
_record("ob-midsend") # crashed mid-await: the platform MAY have it
@@ -227,8 +241,10 @@ def test_boot_sweep_resends_a_due_flood_row_plainly_and_a_midsend_row_with_the_m
claimed = {row["obligation_id"]: row for row in dl.sweep_recoverable(now=T0 + 300)}
- assert claimed["ob-flood"]["needs_marker"] is False
+ assert claimed["ob-flood"]["needs_marker"] is True
+ assert claimed["ob-flood"]["marker"] == dl.FLOOD_MARKER
assert claimed["ob-midsend"]["needs_marker"] is True
+ assert "marker" not in claimed["ob-midsend"], "a crash mid-send is the runner's restart marker"
flood = _row("ob-flood")
assert flood["state"] == "attempting" and flood["last_error"] is None and flood["attempts"] == 1
@@ -245,12 +261,12 @@ def test_boot_sweep_keeps_the_marker_for_a_chunked_flood_refused_reply(clock, mo
def test_an_interrupted_flood_resend_gets_the_marker_on_the_next_boot(clock, monkeypatch):
- """Runtime claim, platform accepts, process dies before mark_delivered: the next boot must not treat
- the old refusal as proof of non-delivery."""
+ """Runtime claim, platform accepts, process dies before mark_delivered: the next boot must see an
+ ordinary interrupted send (restart marker), not a flood row."""
_record("ob-flood")
dl.mark_failed("ob-flood", "flood_control:9")
(claimed,) = dl.sweep_failed_for_runtime("telegram", now=T0 + 20)
- assert claimed["needs_marker"] is False
+ assert claimed["marker"] == dl.FLOOD_MARKER
monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False) # that process is gone
(recovered,) = dl.sweep_recoverable(now=T0 + 60)
@@ -315,7 +331,7 @@ async def test_schedule_flood_redelivery_does_nothing_after_shutdown(monkeypatch
@pytest.mark.asyncio
-async def test_timer_delivers_the_refused_reply_plainly_end_to_end(fake_sleep):
+async def test_timer_delivers_the_refused_reply_under_the_rate_limit_marker_end_to_end(fake_sleep):
_record("ob-flood", content="Here is the plan for today.")
dl.mark_failed("ob-flood", "flood_control:185.0")
adapter = _adapter(success=True)
@@ -325,8 +341,8 @@ async def test_timer_delivers_the_refused_reply_plainly_end_to_end(fake_sleep):
await _drain_timers(runner)
sent = adapter.send.call_args.kwargs
- assert sent["content"] == "Here is the plan for today."
- assert "Recovered reply" not in sent["content"]
+ assert sent["content"] == dl.FLOOD_MARKER + "Here is the plan for today."
+ assert "restarted" not in sent["content"] and "reconnected" not in sent["content"]
assert _row("ob-flood")["state"] == "delivered"
assert fake_sleep == [pytest.approx(187.0)]
@@ -396,7 +412,7 @@ async def test_a_shorter_sibling_timer_does_not_send_the_longer_row_early(fake_s
await _drain_timers(runner)
contents = [c.kwargs["content"] for c in adapter.send.await_args_list]
- assert contents == ["short one", "long one"]
+ assert contents == [dl.FLOOD_MARKER + "short one", dl.FLOOD_MARKER + "long one"]
assert fake_sleep[0] == pytest.approx(12.0)
assert fake_sleep[1] == pytest.approx(175.0), "re-armed for the longer row's REMAINING wait, plus slack"
assert _row("ob-short")["attempts"] == 1 and _row("ob-long")["attempts"] == 1
@@ -415,10 +431,45 @@ async def test_boot_redelivery_arms_a_timer_for_an_adopted_flood_row(fake_sleep,
assert n == 0, "nothing is due at boot"
assert len(runner._flood_redelivery_tasks) == 1
await _drain_timers(runner)
- assert adapter.send.call_args.kwargs["content"] == "adopted at boot"
+ assert adapter.send.call_args.kwargs["content"] == dl.FLOOD_MARKER + "adopted at boot"
assert _row("ob-flood")["state"] == "delivered"
+async def test_a_failed_resume_flag_clear_keeps_the_flood_row_on_the_timer(fake_sleep):
+ """Review finding on the first cut: the unsent claim was released as ``send_path_degraded``, which
+ dropped the row from ``pending_flood_retries`` and ended the timer, stranding the reply until a reconnect
+ or restart. Released with its own flood error, it waits the platform's figure again and is then sent."""
+ _record("ob-flood", content="the plan")
+ dl.mark_failed("ob-flood", "flood_control:30")
+ adapter = _adapter(success=True)
+ runner = _runner(adapter)
+ runner._async_session_store.clear_resume_pending = AsyncMock(
+ side_effect=[RuntimeError("session store locked"), None])
+
+ runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:30")
+ await _drain_timers(runner)
+
+ assert adapter.send.await_count == 1
+ assert _row("ob-flood") == {"state": "delivered", "attempts": 1, "last_error": None, "owner_pid": os.getpid()}, \
+ "the released claim spent no attempt"
+ assert fake_sleep == [pytest.approx(32.0), pytest.approx(32.0)], "re-armed for the platform's figure, not dropped"
+
+
+async def test_a_runtime_claim_whose_adapter_vanished_is_released_with_its_flood_error(clock):
+ _record("ob-flood")
+ dl.mark_failed("ob-flood", "flood_control:9")
+ (row,) = dl.sweep_failed_for_runtime("telegram", now=T0 + 20)
+ runner = _runner(_adapter())
+ runner.adapters = {} # the reconnect that armed the timer is gone again
+
+ assert await runner._obligation_adapter(row) is None
+
+ assert _row("ob-flood") == {"state": "failed", "attempts": 0, "last_error": "flood_control:9", "owner_pid": os.getpid()}
+ assert dl.pending_flood_retries()[0]["platform"] == "telegram", "still the flood timer's business"
+
+
# ---------------------------------------------------------------------------
# The adapter hook: a flood-refused final send arms the timer; other outcomes do not.
# ---------------------------------------------------------------------------