The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): give up a refused notice only on a permanent refusal
Teknium742dc2b6cae1
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex a4c943d836b..148bac90213 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -71,6 +71,13 @@ _COMPLETION_INJECTION_RETRY_MAX_DELAY = 60# 2 s drain cadence instead of the watcher's check interval (#140899)._WATCH_INJECTION_RETRY_BASE_DELAY = 4.0++def _refusal_retry_at(step: int) -> float:+ """When a refused queued notice is next offered: exponential from the drain base, capped."""+ return time.monotonic() + jittered_backoff(+ step, base_delay=_WATCH_INJECTION_RETRY_BASE_DELAY,+ max_delay=_COMPLETION_INJECTION_RETRY_MAX_DELAY, jitter_ratio=0.0)+# Durable async-delegation claim transitions: kind -> (tools.async_delegation function, failure log)._DURABLE_CLAIM_OPS = {"drop": ("drop_completion_delivery", "Could not drop durable completion claim"),@@ -739,23 +746,34 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificadelivered = False# The original event: a requeued tick folds again from what is still queued.if delivered is False:- 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 (output remains available via "- "process(action='log'))",- evt.get("platform") or "?", evt.get("chat_id") or "?",- evt.get("type") or "?", evt.get("session_id", "unknown"), attempts,- )+ self._requeue_refused_watch_event(completion_queue, evt)++ @staticmethod+ def _requeue_refused_watch_event(completion_queue, evt: dict) -> None:+ """Retry a refused watch event on a bounded backoff, never on every 2 s tick (#140899).++ Only a permanent refusal (``gateway.wake.PERMANENT_REFUSAL_REASONS``: the route or the+ session's ownership no longer matches) counts toward the cap that drops it. A transient one+ (a restart's after-turn wait, a parked profile, a full owner FIFO, an adapter reconnecting)+ clears on its own, so the event waits it out however long it lasts.+ """+ from gateway.wake import PERMANENT_REFUSAL_REASONS+ step = int(evt.get("_watch_retry_step") or 0) + 1+ evt["_watch_retry_step"] = step+ if evt.pop("_refusal_reason", None) in PERMANENT_REFUSAL_REASONS:+ refusals = int(evt.get("_watch_injection_attempts") or 0) + 1+ evt["_watch_injection_attempts"] = refusals+ if refusals >= _MAX_COMPLETION_INJECTION_ATTEMPTS:+ logger.warning(+ "Watch notification for %s chat=%s (type=%s session_id=%s) was refused "+ "%d times; dropping the queued event (output remains available via "+ "process(action='log'))",+ evt.get("platform") or "?", evt.get("chat_id") or "?",+ evt.get("type") or "?", evt.get("session_id", "unknown"), refusals,+ )+ return+ evt["_watch_next_retry_at"] = _refusal_retry_at(step)+ completion_queue.put(evt)def _adapter_by_platform_value(self, platform_name: str):"""Literal ``p.value == platform_name`` scan over connected adapters (native adapters only)."""@@ -928,7 +946,7 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificatry:await admit_process_notice(self, authority, adapter, synth_event, evt)except RuntimeStoreError as exc:- raise WakeNotAccepted(str(exc)) from exc+ raise WakeNotAccepted(str(exc), reason=exc.reason) from excelse:await admit_internal_event(adapter, synth_event)return True@@ -937,6 +955,8 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotifica# refused, and one pinned to a gone session is dropped instead of requeued.if not raise_not_accepted and await self._watch_pin_gone(evt, str(exc)):return None+ if not raise_not_accepted:+ evt["_refusal_reason"] = exc.reason # the drain counts only permanent refusalslogger.warning("Watch notification not admitted for %s chat=%s: %s",platform_name, source.chat_id, exc)# Durable callers refund the claim; ordinary watch callers just requeue.@@ -1240,9 +1260,11 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificawith self._completion_delivery_lock:self._mark_completions_delivered_locked((identity,))return True- except WakeNotAccepted:- # Past the watcher's bounded retries a refusal spends its attempt (#141153).- refused = not evt.get("_spend_refusal")+ except WakeNotAccepted as exc:+ # A permanent refusal (route/ownership mismatch) spends its durable attempt, so the row+ # converges to ``dropped`` across restarts too (#141153); a transient one (restart wait,+ # full FIFO) is refunded and never drops a completion the owner will take later.+ refused = not exc.permanentreturn Falsefinally:if identity_claimed and not accepted:@@ -1608,17 +1630,13 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotifica@staticmethoddef _back_off_refused_completions(group: list[dict]) -> None:- """Space out an undelivered async group's retries; past the cap its next refusal spends a- durable delivery attempt (``_spend_refusal``), so a refusal that never clears converges to- ``dropped`` instead of being refunded on every 2 s pass, across restarts (#141153). A single- refusal still refunds: it may clear once the owner's turn settles."""+ """Space out an undelivered async group's retries instead of re-offering it every 2 s pass.+ The backoff only paces; the durable ledger decides when a row gives up (a permanent refusal+ spends a delivery attempt there, so the count survives restarts) (#141153)."""for evt in group:- attempts = int(evt.get("_watch_injection_attempts") or 0) + 1- evt["_watch_injection_attempts"] = attempts- evt["_spend_refusal"] = attempts >= _MAX_COMPLETION_INJECTION_ATTEMPTS- 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)+ step = int(evt.get("_watch_retry_step") or 0) + 1+ evt["_watch_retry_step"] = step+ evt["_watch_next_retry_at"] = _refusal_retry_at(step)@staticmethoddef _redacted_output_tail(session, limit: int) -> str:diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 946ada3ca3f..c1dda057a89 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -62,6 +62,8 @@ async def deliver_heartbeat(runner, event):except Exception:logger.exception("Watch notification injection error")return False+ if delivered is False and prepared is not event:+ event['_refusal_reason'] = prepared.get('_refusal_reason') # the drain requeues the originalif delivered is not False or not _replaced_tick_claimed(runner, prepared):return delivered# The tick it replaced started first and runs with its own output: admit this one alone.diff --git a/gateway/wake.py b/gateway/wake.pyindex fc7d8d4ad20..e0a4d1eeaf9 100644--- a/gateway/wake.py+++ b/gateway/wake.py@@ -35,8 +35,28 @@ def adapter_supports_push(adapter: Any) -> bool:return bool(getattr(adapter, "supports_async_delivery", True))+# Store refusal codes (``RuntimeStoreError.reason``) that refuse a notice for good: the route or the+# session's ownership no longer matches it, so every retry meets the same verdict. Every other refusal+# (``runtime_draining`` during a restart's after-turn wait or a parked profile, ``queue_full``,+# ``session_busy``, ``stale_epoch``, ``runtime_retired``, ``storage_unavailable``, an adapter that+# did not accept) clears on its own: back off, never give the notice up.+PERMANENT_REFUSAL_REASONS = frozenset({+ 'admission_conflict', 'not_found', 'invalid_params', 'permission_denied', 'profile_mismatch',+ 'session_superseded',+})++class WakeNotAccepted(RuntimeError):- """No adapter admission: retry without treating a healthy chat as dead."""+ """No adapter admission: retry without treating a healthy chat as dead. ``reason`` is the+ store's refusal code when the session authority refused it (None: the adapter did not accept)."""++ def __init__(self, message: str = "internal wake not accepted by adapter", *, reason: Optional[str] = None):+ super().__init__(message)+ self.reason = reason++ @property+ def permanent(self) -> bool:+ return self.reason in PERMANENT_REFUSAL_REASONSdef session_owned_by_profile(config: Any, profile: Optional[str], session_id: Any) -> bool:@@ -85,7 +105,7 @@ async def admit_internal_event(adapter: Any, event: Any) -> None:event._gateway_accepted = Falseawait adapter.handle_message(event)if event._gateway_accepted is not True:- raise WakeNotAccepted("internal wake not accepted by adapter")+ raise WakeNotAccepted()async def deliver_wake(adapter: Any, *, text: str, session_id: str = "", source: Any = None,@@ -109,7 +129,7 @@ async def deliver_wake(adapter: Any, *, text: str, session_id: str = "", source:if await admit_route_wake(runner, adapter, source, text, "kanban-wake", category):return # committed to the session FIFO: never interrupts the admitted turnexcept RuntimeStoreError as exc:- raise WakeNotAccepted(str(exc)) from exc+ raise WakeNotAccepted(str(exc), reason=exc.reason) from excsynth_event = MessageEvent(text=text, message_type=MessageType.TEXT, source=source, internal=True,metadata={"notification_category": notification_category})await admit_internal_event(adapter, synth_event)diff --git a/tests/gateway/test_background_process_notifications.py b/tests/gateway/test_background_process_notifications.pyindex 694fc629b8a..e4834780e61 100644--- a/tests/gateway/test_background_process_notifications.py+++ b/tests/gateway/test_background_process_notifications.py@@ -9,7 +9,6 @@ Contributed by @PeterFile (PR #593), reimplemented on current main.import asyncioimport contextlib-import itertoolsimport queueimport threadingfrom types import SimpleNamespace@@ -20,7 +19,6 @@ import pytestfrom gateway.config import GatewayConfig, Platformfrom gateway.run import GatewayRunner, _parse_session_keyfrom gateway.run_notifications import INTERNAL_NOTIFICATION_FOOTER-from tests.module_clock import install_module_clock# ---------------------------------------------------------------------------@@ -326,86 +324,6 @@ 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 (- _COMPLETION_INJECTION_RETRY_MAX_DELAY,- _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 = install_module_clock(monkeypatch, run_notifications)- 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: the wait starts at the base, grows, and stops at the cap.- gaps = [b - a for a, b in itertools.pairwise(attempt_times)]- assert gaps[0] >= _WATCH_INJECTION_RETRY_BASE_DELAY- assert all(b >= a for a, b in itertools.pairwise(gaps)) and gaps[-1] > gaps[0]- assert max(gaps) <= _COMPLETION_INJECTION_RETRY_MAX_DELAY- 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 = install_module_clock(monkeypatch, run_notifications)- 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 triggeringdiff --git a/tests/gateway/test_watch_notification_reset_pin.py b/tests/gateway/test_watch_notification_reset_pin.pyindex 428bcab2e66..4403975632e 100644--- a/tests/gateway/test_watch_notification_reset_pin.py+++ b/tests/gateway/test_watch_notification_reset_pin.py@@ -1,6 +1,7 @@"""A watch notice pinned to a session that ended at a user boundary (/new) is dropped, not requeuedforever: the session authority refuses it ``admission_conflict`` on every drain tick (#141562).Real GatewayRunner, DiscordAdapter, SessionAuthority and drain over SQLite; no agent turn runs."""+import asyncioimport loggingimport queue@@ -64,6 +65,13 @@ def _notice(entry, pinned_session_id, kind='watch_match'):}+def _restart_wait(runner):+ """The restart's after-turn wait: the authority refuses new automation ``runtime_draining``."""+ from gateway.drain_control import open_restart_wait+ runner._running = runner._draining = True+ open_restart_wait(runner)++def _queued_admissions(authority, session_id):from hermes_state_runtime import list_session_admissionsreturn [row for row in list_session_admissions(authority.db, session_id=session_id, pending_only=False)@@ -119,57 +127,6 @@ async def test_notice_pinned_to_a_compression_ancestor_still_admits(monkeypatch,authority.db.close()-async def test_durable_caller_still_gets_the_refusal_for_a_gone_pin(monkeypatch, caplog):- """Completion and delegation callers refund their claim on ``WakeNotAccepted`` after their own- pre-flight; the gone-pin drop is the watch drain's alone and never swallows that refusal."""- from gateway.wake import WakeNotAccepted- runner, authority, entry = await _gateway(monkeypatch)- try:- retired = entry.session_id- runner.session_store.reset_session(entry.session_key)-- with caplog.at_level(logging.WARNING, logger='gateway.run'):- with pytest.raises(WakeNotAccepted, match='admission_conflict'):- await runner._inject_watch_notification(- 'notice', _notice(entry, retired), raise_not_accepted=True)-- assert not [r for r in caplog.records if 'permanently gone' in r.getMessage()]- finally:- authority.db.close()---async def test_refused_notice_pinned_to_a_compression_ancestor_is_retried(monkeypatch, caplog):- """A compression ancestor is not gone: whatever refused its notice, the notice stays queued."""- from gateway import session_automation- from hermes_state_runtime import RuntimeStoreError- runner, authority, entry = await _gateway(monkeypatch)- try:- parent, child = entry.session_id, entry.session_id + '-compressed'- runner.session_store._db_for_key(entry.session_key).publish_compression_child(- parent_session_id=parent, child_session_id=child, source='discord',- require_compression_lease=False, model='offline', model_config={},- system_prompt='offline', messages=[{'role': 'user', 'content': 'retained'}],- )- assert runner.session_store.advance_compression_session(entry.session_key, parent, child)-- async def refuse(*_args):- raise RuntimeStoreError('admission_conflict')- monkeypatch.setattr(session_automation, 'admit_process_notice', refuse)- notice = _notice(entry, parent)- pending = queue.Queue()- pending.put(notice)-- with caplog.at_level(logging.WARNING, logger='gateway.run'):- await runner._drain_watch_notifications(pending)-- assert pending.get_nowait() is notice- assert not [r for r in caplog.records if 'permanently gone' in r.getMessage()]- finally:- authority.db.close()--async def _foreign_pin(runner):"""A live session of another chat: the authority refuses the notice, but nothing proves the pingone, so the refusal stays retryable."""@@ -180,107 +137,126 @@ async def _foreign_pin(runner):@pytest.mark.asyncio-async def test_unproven_refusal_requeues_with_backoff_until_the_cap(monkeypatch, caplog):[email protected]('refusal', ['permanent', 'transient'])+async def test_refused_notice_backs_off_and_only_a_permanent_refusal_drops(monkeypatch, caplog, refusal):+ """A refused watch notice is retried on a bounded backoff, never on every 2 s tick (#140899). A+ route/ownership refusal (``admission_conflict`` for another chat's live session) drops it at the+ cap; a restart's after-turn wait (``runtime_draining``) clears on its own, so the notice waits+ it out however long it lasts and is admitted after."""from gateway import run_notificationsfrom gateway.run_notifications import _MAX_COMPLETION_INJECTION_ATTEMPTSrunner, authority, entry = await _gateway(monkeypatch)try:+ pinned = await _foreign_pin(runner) if refusal == 'permanent' else entry.session_id+ if refusal == 'transient':+ _restart_wait(runner)pending = queue.Queue()- pending.put(_notice(entry, await _foreign_pin(runner)))+ pending.put(_notice(entry, pinned))clock = install_module_clock(monkeypatch, run_notifications)with caplog.at_level(logging.WARNING, logger='gateway.run'):- await runner._drain_watch_notifications(pending)- assert not pending.empty(), 'an unproven refusal is retried'- for _ in range(200):+ for _ in range(2000): # ~33 simulated minutes of drain ticksif pending.empty():break- clock.now += 60await runner._drain_watch_notifications(pending)+ clock.now += 1messages = [r.getMessage() for r in caplog.records]- assert pending.empty()- assert sum('not admitted' in m for m in messages) == _MAX_COMPLETION_INJECTION_ATTEMPTS- assert sum('dropping the queued event' in m for m in messages) == 1- assert not [m for m in messages if 'permanently gone' in m]+ refused = sum('not admitted' in m for m in messages)+ if refusal == 'permanent':+ assert pending.empty()+ assert refused == _MAX_COMPLETION_INJECTION_ATTEMPTS+ assert sum('dropping the queued event' in m for m in messages) == 1+ else:+ assert not pending.empty(), 'a notice refused only by the restart wait is never dropped'+ assert 20 < refused < 60, 'retries are spaced out (capped at 60 s), not attempted every tick'+ runner._draining = False+ clock.now += 120+ await runner._drain_watch_notifications(pending)+ assert pending.empty()+ assert [row['status'] for row in _queued_admissions(authority, entry.session_id)] == ['queued']+ assert not [m for m in messages if 'dropping the queued event' in m]finally:authority.db.close()-async def test_unpinned_refusal_requeues(monkeypatch, caplog):- """A notice that names no pinned session proves nothing gone: its refusal is retried."""- runner, authority, entry = await _gateway(monkeypatch)- try:- notice = _notice(entry, '')- pending = queue.Queue()- pending.put(notice)+_REAL_SLEEP = asyncio.sleep- with caplog.at_level(logging.WARNING, logger='gateway.run'):- await runner._drain_watch_notifications(pending)- assert pending.get_nowait() is notice- assert notice['_watch_injection_attempts'] == 1- assert not [r for r in caplog.records if 'permanently gone' in r.getMessage()]- finally:- authority.db.close()+async def _run_async_watcher(runner, monkeypatch, clock, *, ticks):+ """Run the real async watcher for ``ticks`` passes, one simulated second apart."""+ seen = []++ async def tick(delay):+ seen.append(delay)+ clock.now += 1+ runner._running = len(seen) < ticks+ await _REAL_SLEEP(0)+ monkeypatch.setattr(asyncio, 'sleep', tick)+ runner._running = True+ await runner._async_delegation_watcher(interval=0)+++def _persist_delegation(entry, pinned, delegation_id):+ import time+ from tools import async_delegation as delegation+ evt = dict(_notice(entry, pinned, 'async_delegation'), delegation_id=delegation_id,+ summary='review findings', status='completed', dispatched_at=time.time())+ delegation._persist_dispatch(evt)+ delegation._persist_completion(evt, {'status': 'completed', 'summary': 'review findings'})+ return evt@pytest.mark.asyncio-async def test_unproven_heartbeat_refusal_requeues_the_original_tick(monkeypatch, caplog):- """A liveness tick keeps its own lifecycle: a refusal the pre-flight cannot prove permanent puts- the original tick back (a later tick folds from it); only a gone pin drops it."""+async def test_permanently_refused_completion_converges_to_dropped_across_restarts(monkeypatch):+ """A route/ownership refusal spends a durable delivery attempt in the ledger, so the count+ survives restarts: three processes that each replay the row and retry it for a few minutes+ converge to ``dropped`` instead of each refunding it (#141153)."""+ from gateway import run_notifications+ from tools import async_delegation as delegation+ from tools.process_registry import process_registryrunner, authority, entry = await _gateway(monkeypatch)try:- tick = _notice(entry, await _foreign_pin(runner), 'heartbeat')- pending = queue.Queue()- pending.put(tick)-- with caplog.at_level(logging.WARNING, logger='gateway.run'):- await runner._drain_watch_notifications(pending)+ _persist_delegation(entry, await _foreign_pin(runner), 'refused-1')+ clock = install_module_clock(monkeypatch, run_notifications)+ for _process in range(3):+ # Each process starts from the durable ledger alone: a fresh queue, replayed rows.+ monkeypatch.setattr(process_registry, 'completion_queue', queue.Queue())+ delegation._offered.clear()+ delegation.restore_undelivered_completions(process_registry.completion_queue)+ await _run_async_watcher(runner, monkeypatch, clock, ticks=150)+ row = delegation.get_durable_delegation('refused-1')+ if row['delivery_state'] != 'pending':+ break- assert pending.get_nowait() is tick- assert not [r for r in caplog.records if 'permanently gone' in r.getMessage()]- assert not _queued_admissions(authority, entry.session_id)+ assert (row['delivery_state'], row['delivery_attempts']) == ('dropped', delegation._MAX_DELIVERY_ATTEMPTS)finally:authority.db.close()@pytest.mark.asyncio-async def test_durable_completion_refused_on_every_retry_converges_to_dropped(monkeypatch):- """The async watcher backs off a refused completion and, past its bounded retries, lets the- refusal spend a durable delivery attempt: the row reaches ``dropped`` instead of being refunded- on every 2 s pass and replayed after each restart (#141153)."""- import asyncio- import time+async def test_live_pinned_completion_survives_a_long_restart_wait(monkeypatch):+ """A completion pinned to the LIVE session that the authority refuses only because a restart's+ after-turn wait is open (``runtime_draining``, up to ``restart_after_turn_timeout``) spends no+ delivery attempt however long the wait lasts, and is delivered once admission reopens."""from gateway import run_notificationsfrom tools import async_delegation as delegationfrom tools.process_registry import process_registryrunner, authority, entry = await _gateway(monkeypatch)try:- evt = dict(_notice(entry, await _foreign_pin(runner), 'async_delegation'),- delegation_id='refused-1', summary='review findings', status='completed',- dispatched_at=time.time())- delegation._persist_dispatch(evt)- delegation._persist_completion(evt, {'status': 'completed', 'summary': 'review findings'})+ evt = _persist_delegation(entry, entry.session_id, 'live-1')monkeypatch.setattr(process_registry, 'completion_queue', queue.Queue())process_registry.completion_queue.put(dict(evt))clock = install_module_clock(monkeypatch, run_notifications)- real_sleep, ticks = asyncio.sleep, []-- async def tick(delay):- ticks.append(delay)- clock.now += 1- runner._running = len(ticks) < 4000 and not process_registry.completion_queue.empty()- await real_sleep(0)- monkeypatch.setattr(asyncio, 'sleep', tick)- runner._running = True+ _restart_wait(runner)- await runner._async_delegation_watcher(interval=0)+ await _run_async_watcher(runner, monkeypatch, clock, ticks=1800) # 30 simulated minutes+ row = delegation.get_durable_delegation('live-1')+ assert (row['delivery_state'], row['delivery_attempts']) == ('pending', 0)- row = delegation.get_durable_delegation('refused-1')- assert (row['delivery_state'], row['delivery_attempts']) == ('dropped', delegation._MAX_DELIVERY_ATTEMPTS)- # Eight refunded retries back off ~5 min, then each spent attempt waits a minute.- assert len(ticks) > 500, 'refused retries are spaced out, not re-attempted on every pass'+ runner._draining = False+ await _run_async_watcher(runner, monkeypatch, clock, ticks=120)+ assert delegation.get_durable_delegation('live-1')['delivery_state'] == 'delivered'+ assert [r['status'] for r in _queued_admissions(authority, entry.session_id)] == ['queued']finally:authority.db.close()