Skip to content

The agent that grows with you

fix(gateway): read the flood re-arm ledger synchronously so a mid-sweep refusal is not lost

Alexander Russelle41e5e236be9
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 6c42fa15528..58ebf22d823 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -355,7 +355,7 @@ class GatewayStartupMixin:
return
target = platform if isinstance(platform, Platform) else Platform(pvalue)
await self._redeliver_failed_obligations_for_platform(target, profile=profile)
- await self._arm_flood_timers_for_waiting_rows()
+ self._arm_flood_timers_for_waiting_rows()
except asyncio.CancelledError:
raise
except Exception:
@@ -376,13 +376,19 @@ class GatewayStartupMixin:
key[0], key[1], delay)
return delay
- async def _arm_flood_timers_for_waiting_rows(self) -> int:
+ 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."""
+ refused again on redelivery. Best-effort; returns how many timers were armed.
+
+ The ledger read is synchronous on purpose. A running timer clears its slot right after this
+ call, and a concurrent flood refusal's ``_schedule_flood_redelivery`` is declined while that
+ slot is occupied; reading in a worker thread would let that refusal's row be recorded during
+ the yield, after this snapshot was taken but before the slot is freed, and its timer request
+ would be lost. A single indexed SELECT on a small table does not need to leave the loop."""
try:
from gateway.delivery_ledger import pending_flood_retries
- waiting = await asyncio.to_thread(pending_flood_retries)
+ waiting = pending_flood_retries()
except Exception:
logger.debug("could not list waiting flood-refused rows", exc_info=True)
return 0
@@ -441,7 +447,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):
- await self._arm_flood_timers_for_waiting_rows()
+ 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 bb207e1ee50..579bc754e18 100644
--- a/tests/gateway/test_delivery_ledger_flood_retry.py
+++ b/tests/gateway/test_delivery_ledger_flood_retry.py
@@ -1,4 +1,4 @@
-"""A flood-refused final reply is redelivered once the penalty passes, plainly when that is safe.
+"""A flood-refused final reply is redelivered once the penalty passes.
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
@@ -6,8 +6,8 @@ delivery ledger owns the wait. It did not: ``sweep_failed_for_runtime`` only rep
``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.
+12:15 that way, labelled as a possible duplicate although whether the platform had
+accepted any part of it was unknowable.
Now:
- ``flood_control:*`` rows are runtime-retryable, but only once their own deadline
@@ -487,6 +487,35 @@ async def test_a_shorter_refusal_replaces_a_longer_timer_that_is_still_asleep(fa
assert runner._flood_redelivery_tasks == {} and runner._flood_redelivery_slots == {}
+async def test_a_row_refused_while_the_timer_sweeps_is_armed_by_that_same_timer(fake_sleep):
+ """A final refused during the timer's own redelivery send lands in the ledger after the sweep
+ started. The timer's synchronous post-sweep arm reads the ledger once the sends are done and
+ picks it up, so the row is never left without a timer."""
+ _record("ob-first")
+ dl.mark_failed("ob-first", "flood_control:10")
+ adapter = _adapter(success=True)
+ runner = _runner(adapter)
+ fired = {"done": False}
+
+ async def _send(**kwargs):
+ if not fired["done"]:
+ fired["done"] = True
+ _record("ob-second", content="refused mid-sweep")
+ dl.mark_failed("ob-second", "flood_control:10")
+ # A concurrent refusal's schedule request is declined while this timer holds the slot.
+ runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:10")
+ return SendResult(success=True, message_id="9")
+
+ adapter.send = AsyncMock(side_effect=_send)
+ runner._schedule_flood_redelivery(Platform.TELEGRAM, error="flood_control:10")
+ await _drain_timers(runner)
+
+ assert _row("ob-first")["state"] == "delivered"
+ assert _row("ob-second")["state"] == "delivered", "the mid-sweep refusal was armed by the same timer"
+ assert runner._flood_redelivery_tasks == {} and runner._flood_redelivery_slots == {}
+
+
@pytest.mark.asyncio
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