Skip to content

The agent that grows with you

fix(gateway): adopted flood rows clear resume flags and legacy profiles reach the timer

Alexander Russell289ece2e5945
diff --git a/gateway/delivery_ledger.py b/gateway/delivery_ledger.py
index a4421a63a77..6e22c7a0357 100644
--- a/gateway/delivery_ledger.py
+++ b/gateway/delivery_ledger.py
@@ -51,12 +51,12 @@ FLOOD_MARKER = ("♻️ Recovered reply — the messaging platform's rate limit
# 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: 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).
+# 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.
FLOOD_ERROR_PREFIX = "flood_control:"
FLOOD_RETRY_DEFAULT_SECONDS = 60.0
FLOOD_RETRY_CAP_SECONDS = 15 * 60.0
@@ -305,7 +305,14 @@ def sweep_recoverable(now: Optional[float] = None, *, deliverable_platforms: Opt
must only be spent on a real send, else a platform that failed to connect burns one attempt per boot
and hits the cap having never been sent once (the stale cutoff still bounds untouched rows).
``deliverable_targets`` further scopes multiplexed gateways by exact ``(platform, adapter_profile)``
- so one connected bot cannot spend another disconnected bot's retry budget."""
+ so one connected bot cannot spend another disconnected bot's retry budget.
+
+ A flood-refused row still inside its wait is adopted (owner re-stamped, no attempt spent) and
+ returned flagged ``adopted`` with its ``not_before``: the caller clears its session's resume flag
+ like any other claimed row, since the answer is in the ledger, but must not send it; the flood
+ timer does once the wait has passed. A legacy row without ``adapter_profile`` is normalised to
+ ``'default'`` on claim or adoption (the caller only accepts such rows when it is not multiplexed),
+ because the runtime sweep matches profiles exactly and could otherwise never claim it."""
now, (pid, started) = now if now is not None else time.time(), _owner_stamp()
claimed: List[Dict[str, Any]] = []
with _DB_LOCK, _transaction() as conn:
@@ -332,17 +339,25 @@ def sweep_recoverable(now: Optional[float] = None, *, deliverable_platforms: Opt
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(
+ cursor = conn.execute(
"""UPDATE delivery_obligations
- SET owner_pid=?, owner_started_at=?
+ SET owner_pid=?, owner_started_at=?,
+ adapter_profile=COALESCE(adapter_profile, 'default')
WHERE obligation_id=? AND (owner_pid IS ? OR owner_pid=?)""",
(pid, started, oid, owner_pid, owner_pid))
+ if cursor.rowcount:
+ claimed.append({
+ "obligation_id": oid, "session_key": session_key, "platform": platform,
+ "chat_id": chat_id, "thread_id": thread_id, "content": content,
+ "profile": adapter_profile or "default", "attempts": attempts,
+ "adopted": True, "not_before": flood_not_before(updated_at, last_error)})
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=?,
+ adapter_profile=COALESCE(adapter_profile, 'default'),
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=?)""",
@@ -352,7 +367,8 @@ def sweep_recoverable(now: Optional[float] = None, *, deliverable_platforms: Opt
# 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=state != "pending", flood=flood_row))
+ adapter_profile or "default", needs_marker=state != "pending",
+ flood=flood_row))
return claimed
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 4fea4c2483a..5757ef260e1 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -3752,7 +3752,7 @@ class BasePlatformAdapter(ABC):
replacement adapter live, trigger another redelivery sweep (the watcher's may have run
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)."""
+ of waiting for the next restart."""
try:
from gateway.delivery_ledger import is_flood_error, mark_delivered, mark_failed
if getattr(result, "success", False):
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 7e53fe4d574..6c42fa15528 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -258,7 +258,8 @@ class GatewayStartupMixin:
A session with a recoverable obligation already produced its answer — the turn completed and only
delivery is owed — so clearing ``resume_pending`` here prevents the resume path from re-running (and
re-paying for) a turn whose output we hold, regardless of how long the sends ahead of redelivery
- take (#91969).
+ take (#91969). Flood-refused rows adopted inside their wait come back flagged ``adopted``: their
+ flags are cleared here too, and ``_redeliver_claimed_obligations`` leaves them to the timer.
"""
try:
from gateway.delivery_ledger import ledger_enabled, sweep_recoverable
@@ -296,7 +297,7 @@ class GatewayStartupMixin:
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)."""
+ ``send_path_degraded``."""
from gateway.delivery_ledger import release_runtime_claim
try:
await asyncio.to_thread(release_runtime_claim, obligation_id, error)
@@ -305,7 +306,7 @@ class GatewayStartupMixin:
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).
+ """Retry a flood-refused final reply once the platform's penalty has passed.
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
@@ -316,34 +317,45 @@ class GatewayStartupMixin:
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."""
+ for this identity is already waiting with an earlier or equal deadline."""
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 = {}
+ slots = getattr(self, "_flood_redelivery_slots", None)
+ if slots is None:
+ slots = self._flood_redelivery_slots = {}
existing = pending.get(key)
try:
caller_task = asyncio.current_task()
except RuntimeError:
caller_task = None
+ delay = flood_retry_delay(wait_seconds if wait_seconds is not None else flood_wait_seconds(error))
+ due_at = time.time() + delay
# 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.
+ # mistakes a sweep in progress for a finished timer. A timer still asleep is replaced by a shorter
+ # one (a 10s refusal must not wait behind a 185s sibling); the shorter timer re-arms for the longer
+ # row after its sweep, so the longer wait is kept, only not imposed on both.
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))
+ waiting = slots.get(key)
+ if waiting is None or not waiting["sleeping"] or due_at >= waiting["due_at"] - 1.0:
+ return None
+ existing.cancel()
+ slot = {"due_at": due_at, "sleeping": True}
async def _redeliver_after_wait():
try:
await asyncio.sleep(delay)
+ slot["sleeping"] = False
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()
+ await self._arm_flood_timers_for_waiting_rows()
except asyncio.CancelledError:
raise
except Exception:
@@ -351,6 +363,7 @@ class GatewayStartupMixin:
finally:
if pending.get(key) is asyncio.current_task():
pending.pop(key, None)
+ slots.pop(key, None)
try:
task = asyncio.get_running_loop().create_task(
@@ -358,17 +371,18 @@ class GatewayStartupMixin:
except RuntimeError:
return None
pending[key] = task
+ slots[key] = slot
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:
+ async 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()
+ waiting = await asyncio.to_thread(pending_flood_retries)
except Exception:
logger.debug("could not list waiting flood-refused rows", exc_info=True)
return 0
@@ -396,6 +410,10 @@ class GatewayStartupMixin:
return 0
redelivered = 0
for row in claimed:
+ if row.get("adopted"):
+ # Adopted at boot inside its flood wait: its resume flag is cleared with the others, and
+ # the timer armed below sends it once the platform's deadline has passed.
+ continue
adapter = await self._obligation_adapter(row)
if adapter is None:
continue
@@ -423,7 +441,7 @@ class GatewayStartupMixin:
# 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()
+ await self._arm_flood_timers_for_waiting_rows()
return redelivered
async def _obligation_adapter(self, row: dict):
diff --git a/tests/gateway/test_delivery_ledger_flood_retry.py b/tests/gateway/test_delivery_ledger_flood_retry.py
index 3a008548685..bb207e1ee50 100644
--- a/tests/gateway/test_delivery_ledger_flood_retry.py
+++ b/tests/gateway/test_delivery_ledger_flood_retry.py
@@ -22,7 +22,10 @@ Now:
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.
+- at boot, a dead owner's not-yet-due flood row is adopted rather than resent early, and
+ returned flagged so its session's resume flag is cleared (the answer is in the ledger)
+ without the row being sent inside the penalty; a legacy row without a profile is
+ normalised to 'default' so the timer's runtime sweep can claim it.
"""
from __future__ import annotations
@@ -75,6 +78,28 @@ def _row(oid):
return None if r is None else {"state": r[0], "attempts": r[1], "last_error": r[2], "owner_pid": r[3]}
+def _owner(oid):
+ """(owner_pid, owner_started_at, adapter_profile) of a row."""
+ with dl._connect() as conn:
+ return conn.execute(
+ "SELECT owner_pid, owner_started_at, adapter_profile FROM delivery_obligations"
+ " WHERE obligation_id=?", (oid,)).fetchone()
+
+
+DEAD_OWNER = (999_999, 1)
+
+
+def _record_for_dead_owner(oid, error, **kwargs):
+ """A flood-refused row whose last owner is gone: what a restart finds in the ledger."""
+ live = dl._owner_stamp
+ dl._owner_stamp = lambda: DEAD_OWNER
+ try:
+ _record(oid, **kwargs)
+ dl.mark_failed(oid, error)
+ finally:
+ dl._owner_stamp = live
+
+
def _runner(adapter):
from gateway.run import GatewayRunner
@@ -221,16 +246,37 @@ def test_a_chunked_reply_refused_by_flood_control_keeps_the_marker(clock):
# ---------------------------------------------------------------------------
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")
+ _record_for_dead_owner("ob-flood", "flood_control:185.0")
monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False)
- claimed = dl.sweep_recoverable(now=T0 + 30)
+ (adopted,) = dl.sweep_recoverable(now=T0 + 30)
- assert claimed == [], "not due yet: resending now would burn an attempt inside the penalty"
+ assert adopted["adopted"] is True and adopted["not_before"] == pytest.approx(T0 + 185.0), \
+ "returned so the caller clears its resume flag, flagged so nothing sends it inside the penalty"
+ assert adopted["attempts"] == 0 and "marker" not in adopted
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)
+ assert row["state"] == "failed" and row["attempts"] == 0 and row["last_error"] == "flood_control:185.0"
+ assert _owner("ob-flood") == (os.getpid(), 202, "default"), "ownership moved from the dead process"
+
+
+def test_a_legacy_row_without_a_profile_is_normalised_so_the_timer_can_claim_it(clock, monkeypatch):
+ """Rows recorded before ``adapter_profile`` existed carry NULL. The boot sweep accepts them on a
+ non-multiplexed gateway, but the runtime sweep matches the profile exactly and the timer asks for
+ 'default', so an adopted NULL row could only ever wake the timer without being sent."""
+ _record_for_dead_owner("ob-legacy", "flood_control:185.0")
+ with dl._connect() as conn:
+ conn.execute("UPDATE delivery_obligations SET adapter_profile=NULL WHERE obligation_id='ob-legacy'")
+ monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False)
+
+ (adopted,) = dl.sweep_recoverable(
+ now=T0 + 30, deliverable_platforms={"telegram"},
+ deliverable_targets={("telegram", "default"), ("telegram", None)})
+
+ assert adopted["profile"] == "default" and _owner("ob-legacy") == (os.getpid(), 202, "default")
+ assert dl.pending_flood_retries(now=T0 + 30) == [
+ {"platform": "telegram", "profile": "default", "not_before": pytest.approx(T0 + 185.0)}]
+ (claimed,) = dl.sweep_failed_for_runtime("telegram", now=T0 + 200, profile="default")
+ assert claimed["obligation_id"] == "ob-legacy" and claimed["marker"] == dl.FLOOD_MARKER
def test_boot_sweep_resends_a_due_flood_row_under_the_rate_limit_marker_and_a_midsend_row_under_the_restart_one(clock, monkeypatch):
@@ -301,10 +347,10 @@ async def test_schedule_flood_redelivery_waits_then_runs_the_runtime_sweep(fake_
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")
+ again = runner._schedule_flood_redelivery(Platform.TELEGRAM, profile=None, error="flood_control:300")
assert delay == pytest.approx(187.0)
- assert again is None, "a second refusal while the timer is armed must not arm another"
+ assert again is None, "a refusal due no earlier than the armed timer must not arm another"
assert len(runner._flood_redelivery_tasks) == 1
await _drain_timers(runner)
@@ -365,7 +411,7 @@ async def test_a_chunked_reply_is_redelivered_under_the_rate_limit_marker(fake_s
@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."""
+ """A refusal during the sweep must not be blocked by the timer's own slot: it arms its successor."""
_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)])
@@ -418,10 +464,53 @@ async def test_a_shorter_sibling_timer_does_not_send_the_longer_row_early(fake_s
assert _row("ob-short")["attempts"] == 1 and _row("ob-long")["attempts"] == 1
+async def test_a_shorter_refusal_replaces_a_longer_timer_that_is_still_asleep(fake_sleep):
+ """Arrival order reversed: the 185s timer is armed first. Left alone it would hold the 10s row for
+ the full 185s. The shorter refusal replaces the sleeping timer and re-arms for the longer row."""
+ _record("ob-long", content="long one")
+ dl.mark_failed("ob-long", "flood_control:185")
+ _record("ob-short", content="short one")
+ dl.mark_failed("ob-short", "flood_control:10")
+ adapter = _adapter(success=True)
+ runner = _runner(adapter)
+
+ assert runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:185") == pytest.approx(187.0)
+ assert runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:10") == pytest.approx(12.0)
+ assert len(runner._flood_redelivery_tasks) == 1, "one live timer per identity, the shorter one"
+ await _drain_timers(runner)
+
+ contents = [c.kwargs["content"] for c in adapter.send.await_args_list]
+ assert contents == [dl.FLOOD_MARKER + "short one", dl.FLOOD_MARKER + "long one"]
+ assert fake_sleep == [pytest.approx(12.0), pytest.approx(175.0)], "the 187s sleep never happened"
+ assert _row("ob-short")["attempts"] == 1 and _row("ob-long")["attempts"] == 1
+ assert runner._flood_redelivery_tasks == {} and runner._flood_redelivery_slots == {}
+
+
+async def test_a_timer_already_sweeping_is_not_replaced(fake_sleep):
+ """Once the sleep is over the timer may be mid-send; a refusal arriving then arms nothing extra and
+ the successor logic (the running timer re-arming itself) takes over."""
+ runner = _runner(_adapter())
+ seen = []
+
+ async def _sweep(target, profile=None):
+ async def _refusal_from_another_task():
+ return runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:1")
+
+ seen.append(await asyncio.create_task(_refusal_from_another_task()))
+ return 0
+
+ runner._redeliver_failed_obligations_for_platform = _sweep
+ runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:60")
+ await _drain_timers(runner)
+
+ assert seen == [None], "a refusal from outside the running timer cannot cancel it mid-sweep"
+
+
@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")
+ _record_for_dead_owner("ob-flood", "flood_control:120", content="adopted at boot")
monkeypatch.setattr(dl, "_owner_alive", lambda pid, started: False)
adapter = _adapter(success=True)
runner = _runner(adapter)
@@ -429,6 +518,10 @@ async def test_boot_redelivery_arms_a_timer_for_an_adopted_flood_row(fake_sleep,
n = await runner._redeliver_pending_obligations() # the boot path: claim + redeliver
assert n == 0, "nothing is due at boot"
+ adapter.send.assert_not_awaited()
+ runner._async_session_store.clear_resume_pending.assert_awaited_once_with(
+ "agent:main:telegram:dm:5230977008"), "the answer is in the ledger: the turn must not be re-run"
+ assert _owner("ob-flood") == (os.getpid(), 202, "default")
assert len(runner._flood_redelivery_tasks) == 1
await _drain_timers(runner)
assert adapter.send.call_args.kwargs["content"] == dl.FLOOD_MARKER + "adopted at boot"