The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): spend a refused notice's attempt only on a proven-permanent refusal
Teknium8e4eeb039367
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 148bac90213..f0ca76d2162 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -752,15 +752,14 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificadef _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.+ Only a refusal proven permanent (``WakeNotAccepted.permanent``: the route has no session,+ or the payload is invalid) counts toward the cap that drops it. A transient one (a restart's+ after-turn wait, a parked profile, a full owner FIFO) or one whose owner may still appear (an+ unowned or foreign-pinned notice) waits it out however long it lasts."""- from gateway.wake import PERMANENT_REFUSAL_REASONSstep = int(evt.get("_watch_retry_step") or 0) + 1evt["_watch_retry_step"] = step- if evt.pop("_refusal_reason", None) in PERMANENT_REFUSAL_REASONS:+ if evt.pop("_refusal_permanent", False):refusals = int(evt.get("_watch_injection_attempts") or 0) + 1evt["_watch_injection_attempts"] = refusalsif refusals >= _MAX_COMPLETION_INJECTION_ATTEMPTS:@@ -951,12 +950,15 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificaawait admit_internal_event(adapter, synth_event)return Trueexcept WakeNotAccepted as exc:- # Durable callers ran the pre-flight already; a watch notice is classified only once- # 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)):+ # Permanent only on proof: a pin the authority's state shows gone (/new, #141562) or a+ # final code. An unowned or foreign-pinned refusal may still find its owner (d6635ffe03b).+ from gateway.wake import PERMANENT_REFUSAL_REASONS+ pin_gone = await self._watch_pin_gone(evt, str(exc), log=not raise_not_accepted)+ exc.permanent = pin_gone or exc.reason in PERMANENT_REFUSAL_REASONS+ if pin_gone and not raise_not_accepted:return Noneif not raise_not_accepted:- evt["_refusal_reason"] = exc.reason # the drain counts only permanent refusals+ evt["_refusal_permanent"] = exc.permanent # 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.@@ -1261,9 +1263,9 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificaself._mark_completions_delivered_locked((identity,))return Trueexcept 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.+ # A proven-permanent refusal spends its durable attempt, so the row converges to+ # ``dropped`` across restarts too (#141153); any other (restart wait, full FIFO, an owner+ # not yet proven) is refunded and never drops a completion the owner will take later.refused = not exc.permanentreturn Falsefinally:diff --git a/gateway/run_notifications_ownership.py b/gateway/run_notifications_ownership.pyindex eeb84435220..3b2dc09ff3b 100644--- a/gateway/run_notifications_ownership.py+++ b/gateway/run_notifications_ownership.py@@ -138,8 +138,8 @@ class GatewayNotificationOwnershipMixin:session_id = parentreturn "terminal", session_id, None- async def _watch_pin_gone(self, evt: dict, refusal: str) -> bool:- """True (logged once) when a refused watch notice is pinned to a permanently-gone session.+ async def _watch_pin_gone(self, evt: dict, refusal: str, *, log: bool = True) -> bool:+ """True (logged once with ``log``) when a refused notice is pinned to a permanently-gone session.The session authority admits a notice only into its pinned session or that session'scompression continuation, so after /new it refuses the notice on every retry and the drain@@ -154,6 +154,8 @@ class GatewayNotificationOwnershipMixin:verdict, _owner, _target = await cast(Any, self)._classify_completion_owner(pinned, session_key)if verdict != "terminal":return False+ if not log:+ return Truelogger.warning("Dropping %s notification of process %s: pinned session %s is permanently gone (closed ""at a user boundary such as /new, or no longer an owner); the route now runs %s and "diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex c1dda057a89..e29c0080332 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -63,7 +63,7 @@ async def deliver_heartbeat(runner, event):logger.exception("Watch notification injection error")return Falseif delivered is False and prepared is not event:- event['_refusal_reason'] = prepared.get('_refusal_reason') # the drain requeues the original+ event['_refusal_permanent'] = prepared.get('_refusal_permanent') # 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 e0a4d1eeaf9..77dcb855306 100644--- a/gateway/wake.py+++ b/gateway/wake.py@@ -35,28 +35,25 @@ 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+# Store refusal codes (``RuntimeStoreError.reason``) that refuse a notice for good by themselves: the+# route has no session (``not_found``) or the payload is malformed (``invalid_params``). A bare+# ``admission_conflict`` proves nothing: an unowned completion, or one pinned to a live session the+# route does not run, may still find its owner (d6635ffe03b), so it is permanent only when the+# authority's state proves the pin gone (``refusal_proven_permanent``). 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',-})+# ``session_busy``, ``stale_epoch``, ...) clears on its own: back off, never give the notice up.+PERMANENT_REFUSAL_REASONS = frozenset({'not_found', 'invalid_params'})class WakeNotAccepted(RuntimeError):"""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)."""+ store's refusal code when the session authority refused it (None: the adapter did not accept);+ ``permanent`` is set once the refusal is proven final (``refusal_proven_permanent``)."""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_REASONS+ self.permanent = Falsedef session_owned_by_profile(config: Any, profile: Optional[str], session_id: Any) -> bool:diff --git a/tests/gateway/test_watch_notification_reset_pin.py b/tests/gateway/test_watch_notification_reset_pin.pyindex 4403975632e..6a524e440e6 100644--- a/tests/gateway/test_watch_notification_reset_pin.py+++ b/tests/gateway/test_watch_notification_reset_pin.py@@ -129,25 +129,33 @@ async def test_notice_pinned_to_a_compression_ancestor_still_admits(monkeypatch,async def _foreign_pin(runner):"""A live session of another chat: the authority refuses the notice, but nothing proves the pin- gone, so the refusal stays retryable."""+ gone (its owner may still appear, d6635ffe03b), so the refusal stays retryable."""from gateway.config import Platformadapter = runner.adapters[Platform.DISCORD]other = adapter.build_source(chat_id='43', chat_type='dm', user_id='42')return runner.session_store.get_or_create_session(other).session_id+def _route_gone(runner, entry):+ """A route that no longer holds a session (/stop suspended it): refused ``not_found`` for good."""+ assert runner.session_store.suspend_session(entry.session_key)+ return entry.session_id++@pytest.mark.asyncio[email protected]('refusal', ['permanent', 'transient'])[email protected]('refusal', ['permanent', 'foreign', '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."""+ proven-permanent refusal (``not_found``: the route holds no session) drops it at the cap. A+ notice pinned to another chat's live session (``admission_conflict``) or refused by a restart's+ after-turn wait (``runtime_draining``) is never dropped: it waits however long it takes."""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+ pinned = {'permanent': lambda: _route_gone(runner, entry), 'transient': lambda: entry.session_id}.get(+ refusal)+ pinned = pinned() if pinned else await _foreign_pin(runner)if refusal == 'transient':_restart_wait(runner)pending = queue.Queue()@@ -167,15 +175,16 @@ async def test_refused_notice_backs_off_and_only_a_permanent_refusal_drops(monkeassert pending.empty()assert refused == _MAX_COMPLETION_INJECTION_ATTEMPTSassert 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'+ return+ assert not pending.empty(), 'a notice whose refusal may still clear is never dropped'+ assert 20 < refused < 60, 'retries are spaced out (capped at 60 s), not attempted every tick'+ assert not [m for m in messages if 'dropping the queued event' in m]+ if refusal == 'transient':runner._draining = Falseclock.now += 120await 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()@@ -209,15 +218,16 @@ def _persist_delegation(entry, pinned, delegation_id):@pytest.mark.asyncioasync 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)."""+ """A proven-permanent refusal (``not_found``: the route holds no session) 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_notificationsfrom tools import async_delegation as delegationfrom tools.process_registry import process_registryrunner, authority, entry = await _gateway(monkeypatch)try:- _persist_delegation(entry, await _foreign_pin(runner), 'refused-1')+ _persist_delegation(entry, _route_gone(runner, entry), '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.@@ -260,3 +270,26 @@ async def test_live_pinned_completion_survives_a_long_restart_wait(monkeypatch):assert [r['status'] for r in _queued_admissions(authority, entry.session_id)] == ['queued']finally:authority.db.close()+++async def test_foreign_pinned_completion_spends_nothing_across_restarts(monkeypatch):+ """A completion pinned to another chat's live session is refused ``admission_conflict`` but+ nothing proves its owner gone (d6635ffe03b): replayed by three processes for minutes each, it+ spends no delivery attempt, unlike a proven-permanent refusal (#141153)."""+ from gateway import run_notifications+ from tools import async_delegation as delegation+ from tools.process_registry import process_registry+ runner, authority, entry = await _gateway(monkeypatch)+ try:+ _persist_delegation(entry, await _foreign_pin(runner), 'foreign-1')+ clock = install_module_clock(monkeypatch, run_notifications)+ for _process in range(3):+ 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('foreign-1')+ assert (row['delivery_state'], row['delivery_attempts']) == ('pending', 0)+ finally:+ authority.db.close()