fix(gateway): redeliver a flood-refused final reply once the penalty passes, without a false duplicate marker

The Telegram adapter fails a flood-controlled final send closed as
flood_control:<seconds> so the send coroutine never sleeps a long penalty
(#91969), on the understanding that the delivery ledger owns the wait. The
ledger did not: sweep_failed_for_runtime only replayed send_path_degraded
rows, so a flood-refused row sat in 'failed' until the next restart, whose
sweep_recoverable then redelivered it hours late prefixed with "Recovered
reply, the gateway restarted during delivery, so this may be a duplicate".
Observed: a reply refused at 08:58 UTC (both the MarkdownV2 send and the
plain fallback got flood_control:185) arrived at 12:15 UTC after a restart,
labelled as a possible duplicate although the platform had never accepted it.

Ledger (gateway/delivery_ledger.py):
- flood_control rows are runtime-retryable, but only once their own deadline
  has passed: the refusal's updated_at plus the platform's wait
  (flood_not_before). Neither an early timer nor a reconnect sweep spends a
  redelivery attempt inside the penalty window.
- A flood refusal of a reply that fits in one Telegram message (4096 UTF-16
  units) proves non-delivery, so that redelivery carries no duplicate marker.
  A chunked reply may have had its first chunk accepted before the refusal
  and keeps the marker.
- Claiming a flood row clears the stale refusal (last_error NULL, state
  'attempting'), so a resend interrupted before mark_delivered is seen as
  uncertain by the next boot and gets the marker.
- At boot, a dead owner's flood row that is not yet due is adopted (owner
  re-stamped, no attempt spent) instead of being resent early.
- pending_flood_retries() lists this process's waiting flood rows per adapter
  identity with the earliest deadline.

Runner (gateway/run_startup.py):
- _schedule_flood_redelivery arms one timer per adapter identity that runs
  the existing runtime sweep after the wait (capped at 15 minutes per sleep;
  the row's deadline, not the timer, decides eligibility, so a capped timer
  wakes early, sends nothing, and re-arms for the remainder). The slot stays
  occupied until the timer ends and only the running timer may arm its
  successor into it, so a refusal during the sweep can never strand the row.
- _arm_flood_timers_for_waiting_rows runs after every redelivery pass (boot
  and runtime), covering adopted rows, rows skipped as not yet due, and rows
  refused again.

Adapter (gateway/platforms/base.py): _finalize_delivery_obligation arms the
timer on a flood_control failure, best-effort inside the existing try.

Tests: 35 in tests/gateway/test_delivery_ledger_flood_retry.py, with a
controllable clock shared by ledger and runner. Each guard was mutation
tested. Existing ledger, reconnect and redelivery suites (131 tests) pass.
This commit is contained in:
Alexander Russell
2026-09-05 16:02:53 +03:00
committed by Teknium
parent 0d8bba885c
commit ae900cba9c
4 changed files with 704 additions and 19 deletions
+141 -15
View File
@@ -39,11 +39,84 @@ _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")
# 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
# 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).
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:
"""True for the adapters' fail-closed flood result (``flood_control:<seconds>``)."""
return str(error or "").strip().lower().startswith(FLOOD_ERROR_PREFIX)
def flood_wait_seconds(error: Any, default: float = FLOOD_RETRY_DEFAULT_SECONDS) -> float:
"""The wait the platform asked for, read from ``flood_control:<seconds>``; ``default`` when unreadable."""
text = str(error or "").strip().lower()
wait = default
if text.startswith(FLOOD_ERROR_PREFIX):
try:
wait = float(text[len(FLOOD_ERROR_PREFIX):].strip())
except ValueError:
wait = default
return wait if wait > 0 else default
def flood_retry_delay(seconds: Any) -> float:
"""How long a redelivery timer sleeps for a wait of ``seconds``: capped so a huge or bogus value cannot
park the timer for hours (the row's own deadline, not the timer, decides eligibility when it fires),
plus a little slack so the timer lands after the deadline rather than on it."""
try:
wait = float(seconds)
except (TypeError, ValueError):
wait = FLOOD_RETRY_DEFAULT_SECONDS
return min(max(wait, 0.0), FLOOD_RETRY_CAP_SECONDS) + FLOOD_RETRY_SLACK_SECONDS
def flood_not_before(updated_at: Any, last_error: Any) -> float:
"""Earliest moment a flood-refused row may be resent: the refusal's timestamp (``mark_failed`` sets
``updated_at``) plus the platform's wait. Enforced by the sweeps so neither an early timer nor a
reconnect sweep spends a redelivery attempt inside the penalty window."""
try:
stamp = float(updated_at or 0.0)
except (TypeError, ValueError):
stamp = 0.0
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)
def _db_path():
return get_hermes_home() / "state.db"
@@ -217,11 +290,14 @@ 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) -> Dict[str, Any]:
"""Claimed-row dict handed back for redelivery; ``runtime`` adds the reconnect-marker fields."""
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."""
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": RECONNECTED_MARKER} if runtime else {}), "profile": profile,
**({"marker": marker} if needs_marker and marker else {}), "profile": profile,
**({"runtime_recovery": True} if runtime else {}), "attempts": attempts + 1}
@@ -243,12 +319,12 @@ def sweep_recoverable(now: Optional[float] = None, *, deliverable_platforms: Opt
rows = conn.execute(
"""SELECT obligation_id, session_key, platform, chat_id, thread_id,
content, state, attempts, created_at,
owner_pid, owner_started_at, adapter_profile
owner_pid, owner_started_at, adapter_profile, last_error, updated_at
FROM delivery_obligations
WHERE state IN ('pending', 'attempting', 'failed')"""
).fetchall()
for (oid, session_key, platform, chat_id, thread_id, content, state, attempts, created_at,
owner_pid, owner_started_at, adapter_profile) in rows:
owner_pid, owner_started_at, adapter_profile, last_error, updated_at) in rows:
if _owner_alive(owner_pid, owner_started_at):
continue # a live gateway still owns this row
if attempts >= MAX_ATTEMPTS or (now - created_at) > STALE_AFTER_SECONDS: # exhausted -> abandoned
@@ -259,15 +335,32 @@ def sweep_recoverable(now: Optional[float] = None, *, deliverable_platforms: Opt
if ((deliverable_platforms is not None and platform not in deliverable_platforms)
or (deliverable_targets is not None and (platform, adapter_profile) not in deliverable_targets)):
continue # no adapter this boot — claiming would spend an attempt on a no-op
flood_row = state == "failed" and is_flood_error(last_error)
if flood_row and now < flood_not_before(updated_at, last_error):
# Still inside the platform's wait: adopt the dead owner's row without spending an attempt
# (state and error kept) so this process's flood timer can claim it once the wait passes.
conn.execute(
"""UPDATE delivery_obligations
SET owner_pid=?, owner_started_at=?
WHERE obligation_id=? AND (owner_pid IS ? OR owner_pid=?)""",
(pid, started, oid, owner_pid, owner_pid))
continue
# A claimed flood row is resent as a fresh attempt: clear the stale refusal so an interrupted
# resend is seen as 'attempting' with no error by the next boot and gets the marker.
cursor = conn.execute(
"""UPDATE delivery_obligations
SET owner_pid=?, owner_started_at=?, attempts=attempts+1,
updated_at=?
SET owner_pid=?, owner_started_at=?, attempts=attempts+1, updated_at=?,
state=CASE WHEN ? THEN 'attempting' ELSE state END,
last_error=CASE WHEN ? THEN NULL ELSE last_error END
WHERE obligation_id=? AND (owner_pid IS ? OR owner_pid=?)""",
(pid, started, now, oid, owner_pid, owner_pid))
if cursor.rowcount: # pending = never started, redeliver plainly; else carry marker
(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))
claimed.append(_claimed_row(oid, session_key, platform, chat_id, thread_id, content, attempts,
adapter_profile, needs_marker=state != "pending"))
adapter_profile, needs_marker=not plain, flood=flood_row))
return claimed
@@ -292,14 +385,14 @@ def sweep_failed_for_runtime(platform: str, now: Optional[float] = None, *,
rows = conn.execute(
"""SELECT obligation_id, session_key, platform, chat_id, thread_id,
content, attempts, created_at, owner_pid,
owner_started_at, last_error, adapter_profile
owner_started_at, last_error, adapter_profile, updated_at
FROM delivery_obligations
WHERE state='failed' AND platform=?""", (platform,)).fetchall()
for (oid, session_key, row_platform, chat_id, thread_id, content, attempts, created_at,
owner_pid, owner_started_at, last_error, adapter_profile) in rows:
owner_pid, owner_started_at, last_error, adapter_profile, updated_at) in rows:
# Exact process-start matching prevents PID reuse from stealing work.
if (adapter_profile != expected_profile or owner_pid != pid or owner_started_at != started
or str(last_error or "").strip().lower() not in _RUNTIME_RETRYABLE_ERRORS):
or not _runtime_retryable(last_error)):
continue
owner_guard = (now, oid, owner_pid, owner_started_at)
if attempts >= MAX_ATTEMPTS or (now - created_at) > STALE_AFTER_SECONDS: # exhausted -> abandoned
@@ -309,17 +402,50 @@ 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)
continue
if is_flood_error(last_error) and now < flood_not_before(updated_at, last_error):
continue # the platform's wait has not passed; the flood timer comes back for it
# The claim clears the stale error: this is a fresh attempt, and if it is interrupted the next
# boot must see 'attempting' with no proof of non-delivery, hence the marker.
cursor = conn.execute(
"""UPDATE delivery_obligations
SET state='attempting', attempts=attempts+1, updated_at=?
SET state='attempting', attempts=attempts+1, updated_at=?, last_error=NULL
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.
claimed.append(_claimed_row(oid, session_key, row_platform, chat_id, thread_id, content,
attempts, adapter_profile, needs_marker=True, runtime=True))
attempts, adapter_profile,
needs_marker=not flood_non_delivery_is_certain(last_error, content),
runtime=True, flood=is_flood_error(last_error)))
return claimed
def pending_flood_retries(now: Optional[float] = None) -> List[Dict[str, Any]]:
"""This process's flood-refused rows that still await redelivery, one entry per adapter identity
with the earliest deadline (``not_before``). The runner arms one redelivery timer per entry, so a
row adopted at boot, skipped because its wait had not passed, or refused again is never stranded.
Rows past the attempts cap or stale cutoff are left for the sweeps to abandon."""
now, (pid, started) = now if now is not None else time.time(), _owner_stamp()
if started is None:
return []
with _DB_LOCK, _transaction() as conn:
rows = conn.execute(
"""SELECT platform, adapter_profile, updated_at, last_error, attempts, created_at
FROM delivery_obligations
WHERE state='failed' AND owner_pid IS ? AND owner_started_at IS ?""", (pid, started)).fetchall()
earliest: Dict[tuple, float] = {}
for platform, adapter_profile, updated_at, last_error, attempts, created_at in rows:
if not is_flood_error(last_error) or attempts >= MAX_ATTEMPTS or (now - created_at) > STALE_AFTER_SECONDS:
continue
due = flood_not_before(updated_at, last_error)
key = (platform, adapter_profile or "default")
if key not in earliest or due < earliest[key]:
earliest[key] = due
return [{"platform": platform, "profile": profile, "not_before": due}
for (platform, profile), due in sorted(earliest.items())]
def _prune(now: Optional[float] = None) -> None:
now = now if now is not None else time.time()
try:
+9 -2
View File
@@ -3750,9 +3750,11 @@ class BasePlatformAdapter(ABC):
delivery_adapter: "BasePlatformAdapter") -> None:
"""Mark the ledger row delivered/failed (best-effort). On ``send_path_degraded`` with a
replacement adapter live, trigger another redelivery sweep (the watcher's may have run
before this failure landed; atomic claiming keeps it idempotent)."""
before this failure landed; atomic claiming keeps it idempotent). On a flood-control refusal
arm the runner's timed redelivery, so the reply goes out once the penalty has passed instead
of waiting for the next restart (ledger-flood-retry)."""
try:
from gateway.delivery_ledger import mark_delivered, mark_failed
from gateway.delivery_ledger import is_flood_error, mark_delivered, mark_failed
if getattr(result, "success", False):
await asyncio.to_thread(mark_delivered, obligation_id)
return
@@ -3765,6 +3767,11 @@ class BasePlatformAdapter(ABC):
if live is not delivery_adapter and callable(redeliver):
await redeliver(event.source.platform,
profile=getattr(delivery_adapter, "_owner_profile", None))
elif is_flood_error(error):
schedule = getattr(self.gateway_runner, "_schedule_flood_redelivery", None)
if callable(schedule):
schedule(event.source.platform,
profile=getattr(delivery_adapter, "_owner_profile", None), error=error)
except Exception:
logger.debug("delivery ledger update failed", exc_info=True)
+86 -2
View File
@@ -299,12 +299,92 @@ class GatewayStartupMixin:
except Exception:
logger.debug(log_fmt, obligation_id, exc_info=True)
def _schedule_flood_redelivery(self, platform, *, profile: Optional[str] = None, error: str = "",
wait_seconds: Optional[float] = None):
"""Retry a flood-refused final reply once the platform's penalty has passed (ledger-flood-retry).
Adapters fail a flood-controlled final send closed as ``flood_control:<seconds>`` so the send
coroutine never sleeps a long penalty (#91969), on the understanding that the delivery ledger
owns the wait. Nothing did: the row sat in ``failed`` until the next restart's sweep, which then
redelivered it hours late under the "gateway restarted during delivery" marker. This arms one
timer per adapter identity that runs the existing runtime sweep after the wait (read from
``error``, or given as ``wait_seconds`` for rows already in the ledger). The sweep claims every
row whose own deadline has passed and leaves the rest, and the timer re-arms for whatever is
still waiting, so a capped sleep or a shorter sibling never sends early. Bounded like every
redelivery by the ledger's attempts cap and stale cutoff. Returns the delay, or None when a timer
for this identity is already waiting."""
from gateway.delivery_ledger import flood_retry_delay, flood_wait_seconds
pvalue = getattr(platform, "value", str(platform))
key = (pvalue, profile or "default")
pending = getattr(self, "_flood_redelivery_tasks", None)
if pending is None:
pending = self._flood_redelivery_tasks = {}
existing = pending.get(key)
try:
caller_task = asyncio.current_task()
except RuntimeError:
caller_task = None
# One live timer per identity, except that the running timer itself (a refusal during its sweep,
# rows still inside their wait afterwards) may arm its successor into the slot: a timer must never
# block its own re-arm, and the slot stays occupied until the task ends so nothing observing it
# mistakes a sweep in progress for a finished timer.
if existing is not None and not existing.done() and existing is not caller_task:
return None
delay = flood_retry_delay(wait_seconds if wait_seconds is not None else flood_wait_seconds(error))
async def _redeliver_after_wait():
try:
await asyncio.sleep(delay)
if not getattr(self, "_running", True):
return
target = platform if isinstance(platform, Platform) else Platform(pvalue)
await self._redeliver_failed_obligations_for_platform(target, profile=profile)
self._arm_flood_timers_for_waiting_rows()
except asyncio.CancelledError:
raise
except Exception:
logger.debug("flood-control redelivery for %s failed", key, exc_info=True)
finally:
if pending.get(key) is asyncio.current_task():
pending.pop(key, None)
try:
task = asyncio.get_running_loop().create_task(
_redeliver_after_wait(), name="flood-redelivery:%s:%s" % key)
except RuntimeError:
return None
pending[key] = task
logger.info("Flood control refused a final reply on %s (%s); ledger redelivery scheduled in %.0fs",
key[0], key[1], delay)
return delay
def _arm_flood_timers_for_waiting_rows(self) -> int:
"""Arm a redelivery timer for every adapter identity that still owns a flood-refused row: rows
adopted from a dead owner at boot, rows a sweep skipped because their wait had not passed, rows
refused again on redelivery. Best-effort; returns how many timers were armed."""
try:
from gateway.delivery_ledger import pending_flood_retries
waiting = pending_flood_retries()
except Exception:
logger.debug("could not list waiting flood-refused rows", exc_info=True)
return 0
armed = 0
now = time.time()
for item in waiting:
try:
if self._schedule_flood_redelivery(
item["platform"], profile=item["profile"], wait_seconds=item["not_before"] - now) is not None:
armed += 1
except Exception:
logger.debug("could not arm a flood redelivery timer for %r", item, exc_info=True)
return armed
async def _redeliver_claimed_obligations(self, claimed: list) -> int:
"""Redeliver final responses for claimed rows (network half of the split): runs inside the
bounded boot-send task, so a flood-limited send can be abandoned by the restore gate without
reopening the turn-replay window. Returns the redelivered count."""
if not claimed:
return 0
# No early return on an empty claim: the boot sweep may have ADOPTED flood-refused rows that are
# not due yet, and those still need their timer armed below.
try:
from gateway.delivery_ledger import RECOVERED_MARKER, mark_delivered, mark_failed
except Exception:
@@ -336,6 +416,10 @@ class GatewayStartupMixin:
await asyncio.to_thread(
mark_failed, row["obligation_id"], str(getattr(result, "error", "") or "send failed")
)
# Whatever is still waiting on a flood penalty (adopted at boot, skipped as not yet due, refused
# again just now) gets a timer, so no flood-refused reply waits for the next restart.
with _log_suppressed(logging.DEBUG, "arming flood redelivery timers failed", exc_info=True):
self._arm_flood_timers_for_waiting_rows()
return redelivered
async def _obligation_adapter(self, row: dict):
@@ -0,0 +1,468 @@
"""A flood-refused final reply is redelivered once the penalty passes, plainly when that is safe.
Adapters fail a flood-controlled final send closed as ``flood_control:<seconds>`` so
the send coroutine never sleeps a long penalty (#91969). The comment there says the
delivery ledger owns the wait. It did not: ``sweep_failed_for_runtime`` only replayed
``send_path_degraded`` rows, so a flood-refused row sat in ``failed`` until the next
restart's ``sweep_recoverable``, which redelivered it hours late under the "gateway
restarted during delivery" marker. On 5 Sep 2026 a reply refused at 08:58 arrived at
12:15 that way, labelled as a possible duplicate although the platform had never
accepted it.
Now:
- ``flood_control:*`` rows are runtime-retryable, but only once their own deadline
(refusal time plus the platform's wait) has passed; neither an early timer nor a
reconnect sweep spends an attempt inside the penalty window;
- 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;
- at boot, a dead owner's not-yet-due flood row is adopted rather than resent early.
"""
from __future__ import annotations
import asyncio
import os
import time as _time
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from gateway import delivery_ledger as dl
from gateway import run_startup
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import SendResult
T0 = 1_700_000_000.0
@pytest.fixture(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))
yield
@pytest.fixture
def clock(monkeypatch):
"""A controllable wall clock shared by the ledger and the runner (both call ``time.time``)."""
now = [T0]
monkeypatch.setattr(_time, "time", lambda: now[0])
return now
def _record(oid, *, platform="telegram", chat_id="5230977008", content="the final answer", profile=None):
dl.record_obligation(
obligation_id=oid, session_key=f"agent:main:{platform}:dm:{chat_id}", platform=platform,
chat_id=chat_id, thread_id=None, content=content, adapter_profile=profile)
dl.mark_attempting(oid)
def _row(oid):
with dl._connect() as conn:
r = conn.execute(
"SELECT state, attempts, last_error, owner_pid FROM delivery_obligations WHERE obligation_id=?", (oid,)
).fetchone()
return None if r is None else {"state": r[0], "attempts": r[1], "last_error": r[2], "owner_pid": r[3]}
def _runner(adapter):
from gateway.run import GatewayRunner
runner = object.__new__(GatewayRunner)
runner.adapters = {Platform.TELEGRAM: adapter}
runner._profile_adapters = {}
runner._active_profile_name = lambda: "default"
runner._running = True
store = MagicMock()
store.clear_resume_pending = AsyncMock()
store._store = None
runner.session_store = None
runner._async_session_store = store
return runner
def _adapter(success=True, error="", side_effect=None):
adapter = MagicMock()
if side_effect is not None:
adapter.send = AsyncMock(side_effect=side_effect)
else:
adapter.send = AsyncMock(return_value=SendResult(success=success, error=error))
return adapter
async def _drain_timers(runner):
"""Await every flood timer, including successors armed while awaiting."""
while runner._flood_redelivery_tasks:
await asyncio.gather(*list(runner._flood_redelivery_tasks.values()))
# ---------------------------------------------------------------------------
# Classification, waits, deadlines, certainty.
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("error, expected", [
("flood_control:185.0", True),
("FLOOD_CONTROL:9", True),
("send_path_degraded", False),
("Forbidden: bot was blocked by the user", False),
("", False),
(None, False),
])
def test_is_flood_error(error, expected):
assert dl.is_flood_error(error) is expected
@pytest.mark.parametrize("error, expected", [
("flood_control:185.0", 185.0),
("flood_control:5820", 5820.0), # a 97-minute penalty is kept as the platform stated it
("flood_control:abc", 60.0), # unreadable -> default
("flood_control:0", 60.0),
("send_path_degraded", 60.0),
])
def test_flood_wait_seconds(error, expected):
assert dl.flood_wait_seconds(error) == pytest.approx(expected)
@pytest.mark.parametrize("seconds, expected", [
(185.0, 187.0), # the wait plus slack
(5820, 902.0), # capped: the timer wakes early and re-checks, it never sends early
(-5, 2.0), # already due -> just the slack
("abc", 62.0),
])
def test_flood_retry_delay(seconds, expected):
assert dl.flood_retry_delay(seconds) == pytest.approx(expected)
def test_flood_not_before_is_the_refusal_time_plus_the_platform_wait():
assert dl.flood_not_before(T0, "flood_control:185.0") == pytest.approx(T0 + 185.0)
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
# ---------------------------------------------------------------------------
# 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):
_record("ob-flood")
dl.mark_failed("ob-flood", "flood_control:185.0")
_record("ob-degraded")
dl.mark_failed("ob-degraded", "send_path_degraded")
_record("ob-blocked")
dl.mark_failed("ob-blocked", "Forbidden: bot was blocked by the user")
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-degraded"]["needs_marker"] is True
assert claimed["ob-degraded"]["marker"] == dl.RECONNECTED_MARKER
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"
assert _row("ob-blocked")["state"] == "failed"
def test_runtime_sweep_leaves_a_flood_row_inside_its_wait_and_reports_its_deadline(clock):
_record("ob-short")
dl.mark_failed("ob-short", "flood_control:10")
_record("ob-long")
dl.mark_failed("ob-long", "flood_control:185")
claimed = dl.sweep_failed_for_runtime("telegram", now=T0 + 12)
assert [r["obligation_id"] for r in claimed] == ["ob-short"], "the 185s row is still inside its penalty"
assert _row("ob-long") == {"state": "failed", "attempts": 0, "last_error": "flood_control:185", "owner_pid": os.getpid()}
waiting = dl.pending_flood_retries(now=T0 + 12)
assert waiting == [{"platform": "telegram", "profile": "default", "not_before": pytest.approx(T0 + 185)}]
def test_a_chunked_reply_refused_by_flood_control_keeps_the_marker(clock):
_record("ob-long-text", content="word " * 1200) # ~6000 chars: two Telegram messages
dl.mark_failed("ob-long-text", "flood_control:9")
(row,) = dl.sweep_failed_for_runtime("telegram", now=T0 + 20)
assert row["needs_marker"] is True, "chunk 1 may have landed before chunk 2 was refused"
assert row["marker"] == dl.FLOOD_MARKER, "no reconnect happened; the marker must name the rate limit"
# ---------------------------------------------------------------------------
# The boot sweep: adopt what is not due, resend what is, stay honest after a crash.
# ---------------------------------------------------------------------------
def test_boot_sweep_adopts_a_dead_owners_flood_row_inside_its_wait(clock, monkeypatch):
_record("ob-flood")
dl.mark_failed("ob-flood", "flood_control:185.0")
monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False)
claimed = dl.sweep_recoverable(now=T0 + 30)
assert claimed == [], "not due yet: resending now would burn an attempt inside the penalty"
row = _row("ob-flood")
assert row["state"] == "failed" and row["attempts"] == 0 and row["owner_pid"] == os.getpid()
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):
_record("ob-flood")
dl.mark_failed("ob-flood", "flood_control:185.0")
_record("ob-midsend") # crashed mid-await: the platform MAY have it
monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False)
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-midsend"]["needs_marker"] is True
flood = _row("ob-flood")
assert flood["state"] == "attempting" and flood["last_error"] is None and flood["attempts"] == 1
def test_boot_sweep_keeps_the_marker_for_a_chunked_flood_refused_reply(clock, monkeypatch):
_record("ob-long-text", content="word " * 1200) # two Telegram messages; chunk 1 may have landed
dl.mark_failed("ob-long-text", "flood_control:9")
monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False)
(row,) = dl.sweep_recoverable(now=T0 + 300)
assert row["needs_marker"] is True
assert row["marker"] == dl.FLOOD_MARKER, "no restart interrupted this send; the marker must name the rate limit"
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."""
_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
monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False) # that process is gone
(recovered,) = dl.sweep_recoverable(now=T0 + 60)
assert recovered["needs_marker"] is True
assert "marker" not in recovered, "the refusal was cleared by the claim: this is an ordinary restart recovery"
# ---------------------------------------------------------------------------
# The runner: timers wait the platform's figure, never block their own successor,
# never send early, and stop at shutdown.
# ---------------------------------------------------------------------------
@pytest.fixture
def fake_sleep(monkeypatch, clock):
"""asyncio.sleep advances the shared clock instead of waiting."""
slept: list[float] = []
real_sleep = asyncio.sleep
async def _sleep(delay):
slept.append(delay)
clock[0] += delay
await real_sleep(0)
monkeypatch.setattr(run_startup.asyncio, "sleep", _sleep)
return slept
@pytest.mark.asyncio
async def test_schedule_flood_redelivery_waits_then_runs_the_runtime_sweep(fake_sleep):
runner = _runner(_adapter())
runner._redeliver_failed_obligations_for_platform = AsyncMock(return_value=1)
delay = runner._schedule_flood_redelivery(Platform.TELEGRAM, profile=None, error="flood_control:185.0")
again = runner._schedule_flood_redelivery(Platform.TELEGRAM, profile=None, error="flood_control:30")
assert delay == pytest.approx(187.0)
assert again is None, "a second refusal while the timer is armed must not arm another"
assert len(runner._flood_redelivery_tasks) == 1
await _drain_timers(runner)
assert fake_sleep == [pytest.approx(187.0)]
runner._redeliver_failed_obligations_for_platform.assert_awaited_once_with(Platform.TELEGRAM, profile=None)
assert runner._flood_redelivery_tasks == {}, "a finished timer frees its slot"
@pytest.mark.asyncio
async def test_schedule_flood_redelivery_does_nothing_after_shutdown(monkeypatch):
runner = _runner(_adapter())
runner._redeliver_failed_obligations_for_platform = AsyncMock(return_value=1)
real_sleep = asyncio.sleep
async def _sleep(delay):
runner._running = False # the gateway stopped while the timer was waiting
await real_sleep(0)
monkeypatch.setattr(run_startup.asyncio, "sleep", _sleep)
runner._schedule_flood_redelivery("telegram", error="flood_control:5")
await _drain_timers(runner)
runner._redeliver_failed_obligations_for_platform.assert_not_awaited()
@pytest.mark.asyncio
async def test_timer_delivers_the_refused_reply_plainly_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)
runner = _runner(adapter)
runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:185.0")
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 _row("ob-flood")["state"] == "delivered"
assert fake_sleep == [pytest.approx(187.0)]
@pytest.mark.asyncio
async def test_a_chunked_reply_is_redelivered_under_the_rate_limit_marker(fake_sleep):
_record("ob-long-text", content="word " * 1200) # two Telegram messages; chunk 1 may have landed
dl.mark_failed("ob-long-text", "flood_control:9")
adapter = _adapter(success=True)
runner = _runner(adapter)
runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:9")
await _drain_timers(runner)
sent = adapter.send.call_args.kwargs["content"]
assert sent.startswith(dl.FLOOD_MARKER)
assert "reconnected" not in sent and "restarted" not in sent
assert _row("ob-long-text")["state"] == "delivered"
@pytest.mark.asyncio
async def test_a_redelivery_refused_again_arms_a_successor_timer(fake_sleep):
"""The bug Codex caught in the first cut: the running timer must not block its own re-arm."""
_record("ob-flood")
dl.mark_failed("ob-flood", "flood_control:10")
adapter = _adapter(side_effect=[SendResult(success=False, error="flood_control:30.0"), SendResult(success=True)])
runner = _runner(adapter)
runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:10")
await _drain_timers(runner)
assert adapter.send.await_count == 2
assert fake_sleep == [pytest.approx(12.0), pytest.approx(32.0)], "the successor waits the NEW refusal's figure"
assert _row("ob-flood")["state"] == "delivered"
assert _row("ob-flood")["attempts"] == 2
assert runner._flood_redelivery_tasks == {}
@pytest.mark.asyncio
async def test_a_capped_timer_wakes_early_but_never_sends_early(fake_sleep):
"""A 2000s penalty: the timer sleeps at most 15 min at a time, finds the row not yet due, re-arms for the
remainder, and sends exactly once when the platform's deadline has actually passed."""
_record("ob-flood")
dl.mark_failed("ob-flood", "flood_control:2000")
adapter = _adapter(success=True)
runner = _runner(adapter)
runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:2000")
await _drain_timers(runner)
assert adapter.send.await_count == 1
assert fake_sleep == [pytest.approx(902.0), pytest.approx(902.0), pytest.approx(198.0)]
assert _row("ob-flood")["state"] == "delivered" and _row("ob-flood")["attempts"] == 1
@pytest.mark.asyncio
async def test_a_shorter_sibling_timer_does_not_send_the_longer_row_early(fake_sleep):
_record("ob-short", content="short one")
dl.mark_failed("ob-short", "flood_control:10")
_record("ob-long", content="long one")
dl.mark_failed("ob-long", "flood_control:185")
adapter = _adapter(success=True)
runner = _runner(adapter)
assert runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:10") == pytest.approx(12.0)
assert runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:185") is None
await _drain_timers(runner)
contents = [c.kwargs["content"] for c in adapter.send.await_args_list]
assert contents == ["short one", "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
@pytest.mark.asyncio
async def test_boot_redelivery_arms_a_timer_for_an_adopted_flood_row(fake_sleep, monkeypatch):
_record("ob-flood", content="adopted at boot")
dl.mark_failed("ob-flood", "flood_control:120")
monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False)
adapter = _adapter(success=True)
runner = _runner(adapter)
n = await runner._redeliver_pending_obligations() # the boot path: claim + redeliver
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 _row("ob-flood")["state"] == "delivered"
# ---------------------------------------------------------------------------
# The adapter hook: a flood-refused final send arms the timer; other outcomes do not.
# ---------------------------------------------------------------------------
def _telegram_adapter_with_runner():
from plugins.platforms.telegram.adapter import TelegramAdapter
adapter = TelegramAdapter(PlatformConfig(enabled=True, token="test-token", extra={}))
runner = MagicMock()
runner._schedule_flood_redelivery = MagicMock(return_value=187.0)
runner._redeliver_failed_obligations_for_platform = AsyncMock(return_value=0)
adapter.gateway_runner = runner
adapter._final_delivery_adapter = lambda source: adapter
return adapter, runner
def _event():
return SimpleNamespace(source=SimpleNamespace(platform=Platform.TELEGRAM, chat_id="5230977008", thread_id=None),
text="what should I eat", message_id="77")
@pytest.mark.asyncio
async def test_flood_refused_final_send_arms_the_timer():
adapter, runner = _telegram_adapter_with_runner()
_record("ob-x")
await adapter._finalize_delivery_obligation(
"ob-x", SendResult(success=False, error="flood_control:185.0"), _event(), adapter)
assert _row("ob-x")["state"] == "failed"
runner._schedule_flood_redelivery.assert_called_once_with(
Platform.TELEGRAM, profile=None, error="flood_control:185.0")
@pytest.mark.asyncio
@pytest.mark.parametrize("result", [
SendResult(success=True),
SendResult(success=False, error="send_path_degraded"),
SendResult(success=False, error="Forbidden: bot was blocked by the user"),
])
async def test_other_outcomes_do_not_arm_the_flood_timer(result):
adapter, runner = _telegram_adapter_with_runner()
_record("ob-y")
await adapter._finalize_delivery_obligation("ob-y", result, _event(), adapter)
runner._schedule_flood_redelivery.assert_not_called()