The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): bound watch-drain requeues with backoff after refused admission
liuhao102401a65bf614c4
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 312f0d27098..07c7c3b6f42 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -67,6 +67,9 @@ _SELF_CLEARING_STORAGE_CAUSES = frozenset({"compression", "compression_closed",# Process-watcher retries of a refused completion: ~5 min at the default 5 s check interval._MAX_COMPLETION_INJECTION_ATTEMPTS = 8_COMPLETION_INJECTION_RETRY_MAX_DELAY = 60+# Drain retries of a refused watch event follow the same bounded-backoff policy, keyed to the+# 2 s drain cadence instead of the watcher's check interval (#140899).+_WATCH_INJECTION_RETRY_BASE_DELAY = 4.0# Durable async-delegation claim transitions: kind -> (tools.async_delegation function, failure log)._DURABLE_CLAIM_OPS = {@@ -710,6 +713,12 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificafrom gateway.run import _drain_gateway_watch_events, _format_gateway_process_notificationwatch_events = _drain_gateway_watch_events(completion_queue)for evt in watch_events:+ next_retry_at = evt.get("_watch_next_retry_at")+ if next_retry_at is not None and next_retry_at > time.monotonic():+ # Backoff between refused injections: hold the event for a later drain tick+ # instead of re-attempting admission every 2 s (#140899).+ completion_queue.put(evt)+ continueasync with self._completion_event_scope(evt):from tools.process_registry_notifications import should_surface_notificationif not should_surface_notification(evt):@@ -730,7 +739,22 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificadelivered = False# The original event: a requeued tick folds again from what is still queued.if delivered is False:- completion_queue.put(evt)+ attempts = int(evt.get("_watch_injection_attempts") or 0) + 1+ evt["_watch_injection_attempts"] = attempts+ if attempts < _MAX_COMPLETION_INJECTION_ATTEMPTS:+ # A refusal may clear (adapter reconnecting, store draining): retry with the+ # same bounded backoff as the process watcher (#139026), never on every tick.+ evt["_watch_next_retry_at"] = time.monotonic() + jittered_backoff(+ attempts, base_delay=_WATCH_INJECTION_RETRY_BASE_DELAY,+ max_delay=_COMPLETION_INJECTION_RETRY_MAX_DELAY, jitter_ratio=0.0)+ completion_queue.put(evt)+ else:+ logger.warning(+ "Watch notification for %s chat=%s (type=%s session_id=%s) was refused "+ "%d times; dropping the queued event",+ evt.get("platform") or "?", evt.get("chat_id") or "?",+ evt.get("type") or "?", evt.get("session_id", "unknown"), attempts,+ )def _adapter_by_platform_value(self, platform_name: str):"""Literal ``p.value == platform_name`` scan over connected adapters (native adapters only)."""diff --git a/tests/gateway/test_background_process_notifications.py b/tests/gateway/test_background_process_notifications.pyindex e4834780e61..edf57f12ccc 100644--- a/tests/gateway/test_background_process_notifications.py+++ b/tests/gateway/test_background_process_notifications.py@@ -9,6 +9,7 @@ Contributed by @PeterFile (PR #593), reimplemented on current main.import asyncioimport contextlib+import itertoolsimport queueimport threadingfrom types import SimpleNamespace@@ -324,6 +325,86 @@ async def test_post_turn_watch_drain_all_injects_from_queued_event_origin(monkeyassert completion_queue.get_nowait() is async_event+async def test_post_turn_watch_drain_refused_event_backs_off_then_drops(monkeypatch, tmp_path, caplog):+ """Regression for #140899: a watch event whose injection is refused must be retried on a+ bounded backoff and finally dropped with ONE warning — never requeued on every 2 s drain+ tick forever (55k attempts over 32 h observed on a live gateway)."""+ import logging++ from gateway import run_notifications+ from gateway.run_notifications import (+ _MAX_COMPLETION_INJECTION_ATTEMPTS,+ _WATCH_INJECTION_RETRY_BASE_DELAY,+ )++ runner = _build_runner(monkeypatch, tmp_path, "all")+ completion_queue = queue.Queue()+ completion_queue.put(_watch_event())++ clock = {"now": 1000.0}+ monkeypatch.setattr(run_notifications.time, "monotonic", lambda: clock["now"])+ attempt_times: list[float] = []++ async def refused(self, synth_text, evt, **kwargs):+ attempt_times.append(clock["now"])+ return False++ monkeypatch.setattr(run_notifications.GatewayNotificationsMixin, "_inject_watch_notification", refused)++ for _ in range(500):+ await runner._drain_watch_notifications(completion_queue)+ clock["now"] += 2.0+ if completion_queue.empty():+ break++ assert len(attempt_times) == _MAX_COMPLETION_INJECTION_ATTEMPTS+ # Backoff, not one attempt per drain tick: successive retries are >= the base delay apart.+ gaps = [b - a for a, b in itertools.pairwise(attempt_times)]+ assert gaps+ assert all(gap >= _WATCH_INJECTION_RETRY_BASE_DELAY for gap in gaps)+ assert completion_queue.empty()+ drops = [r for r in caplog.records+ if r.levelno >= logging.WARNING and "dropping the queued event" in r.message]+ assert len(drops) == 1+ assert f"refused {_MAX_COMPLETION_INJECTION_ATTEMPTS} times" in drops[0].message+++async def test_post_turn_watch_drain_transient_refusal_recovers_without_drop(monkeypatch, tmp_path, caplog):+ """A refusal that clears within the backoff budget delivers on the retry — the cap only+ drops events that stay refused (#140899)."""+ import logging++ from gateway import run_notifications++ runner = _build_runner(monkeypatch, tmp_path, "all")+ completion_queue = queue.Queue()+ completion_queue.put(_watch_event())++ clock = {"now": 1000.0}+ monkeypatch.setattr(run_notifications.time, "monotonic", lambda: clock["now"])+ flaky = {"refusals_left": 2}++ async def flaky_inject(self, synth_text, evt, **kwargs):+ if flaky["refusals_left"]:+ flaky["refusals_left"] -= 1+ return False+ return True++ monkeypatch.setattr(run_notifications.GatewayNotificationsMixin, "_inject_watch_notification", flaky_inject)++ for _ in range(500):+ await runner._drain_watch_notifications(completion_queue)+ clock["now"] += 2.0+ if completion_queue.empty():+ break++ assert completion_queue.empty()+ assert not [r for r in caplog.records+ if r.levelno >= logging.WARNING and "dropping the queued event" in r.message]++@pytest.mark.asyncioasync def test_inject_watch_notification_drops_stale_trigger_reply_anchor(monkeypatch, tmp_path):"""Regression for #52694: the synthetic watch event must not reuse the triggering