Skip to content

fix(subscriptions): a pull-dispatched terminal triggers SUB-003 (#2643) - #2651

Merged
vybe merged 1 commit into
devfrom
fix/2643-pull-terminal-subscription-switch
Sep 9, 2026
Merged

vybe merged 1 commit into
devfrom
fix/2643-pull-terminal-subscription-switch

Conversation

@dolho

@dolho dolho commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes the last SUB-003 gap on the pull path. Split out of #2638 (gap 5).

The bug

services/pull_coordination_service.py::apply_task_result is a CAS-won terminal writer and carried every other terminal hook — the #1578 completion event, the #1804 activity close — but no SUB-003 hook. A pull-owned turn the provider refused therefore:

  • recorded no subscription_rate_limit_events row, so the subscription was never skip-listed and no usage card or pressure badge counted it;
  • never called handle_subscription_failure, so the agent stayed pinned to the subscription that had just refused it;
  • landed FAILED with nothing downstream distinguishing it from any other failure. (An earlier draft of this line said the redelivery_governor treats billing as a correlated code here and would pause the recovering re-delivery. That is wrong on the pull path in both directions, and the "Deliberately not in scope" section below has it right: record_terminal_failure has exactly one caller, task_execution_service.py:2556 on the push apply_result, so the pull sink never arms the governor; and lease_reaper_service, which is the pull re-delivery path, never consults it. Corrected here so the claim does not outlive the PR in the squash commit.)

Everything the push path gained in #441 / #471 / #792, and everything #2638 added on top, was unreachable from a pull-dispatched turn.

Inert today (PULL_MODE_PILOT_AGENTS gates the path and nobody is piloted) — which is exactly why it needed a test rather than a soak. Piloting a subscription-backed agent would have silently removed SUB-003 from that agent, with nothing saying so.

The fix

One hook on the CAS-won branch, beside the two it sits with. Three properties are load-bearing.

The vocabularies do not line up. The worker's typed error_code calls the quota class billing (result_callback._STATUS_MAP maps an agent 429 to it); this subsystem calls it rate_limit. _switch_failure_kind is the map, and it is an allowlist — a code it has not heard of switches nothing, because "switch unless the code looks benign" would churn an agent through every subscription it owns the first time a worker reports an unfamiliar crash class.

CAS-won branch only. A replayed terminal short-circuits above the write and a late one loses the CAS, so neither spends a second switch (the #1083 rule). Past that gate handle_subscription_failure owns the rest: it records the event unconditionally, then takes the #799 per-agent agent_switch_lock and re-reads under it, so two failures racing on one agent still switch once.

A SUCCESS terminal is excluded, on the merits. The gate is error_code rather than the FAILED/CANCELLED split — a worker that labels a quota refusal cancelled still refused for a quota reason — but a turn the provider served is evidence the subscription works, so a stray error_code riding a success must not move the agent off it. It is also the one branch where the sink never binds err_text, so an ungated hook would raise NameError and turn a committed, billed terminal into a 500. (Found while writing the tests, not after.)

The sink is synchronous and its caller async, so the call goes through the new subscription_auto_switch.spawn_subscription_failure — the same wrapper shape as spawn_task_terminal_event (#1578) and spawn_close_execution_activity (#1804): one coroutine (wrapping a pre-built one leaves two objects to close and still warns "never awaited"), a strong reference held until it finishes, a raising switch logged and swallowed, and no-running-loop treated as a clean skip. It runs after a committed, billed terminal and must never be able to turn one into a 500.

Acceptance criteria

Deliberately not in scope

The pull sink still has no #526 AUTH dispatch breaker and no redelivery_governor.record_terminal_failure. apply_result has both. Neither is a SUB-003 concern, and both change failure semantics on a path this PR only reads — named here and in the flow doc so they are not mistaken for done.

Verification

23 passed   tests/unit/test_2643_pull_terminal_subscription_switch.py
109 passed  + test_1578_task_completion_events.py + test_1804_recovery_closes_activity.py
672 passed, 3 skipped   the pull + subscription + governor families

Mutation-checked — each of these turns the suite red:

  • a pass-through failure-kind map (billing → billing) → 3 failures;
  • hoisting the call above if won: → the lost-CAS test and the AST pin;
  • dropping the SUCCESS exclusion → the NameError test.

Docs: docs/memory/feature-flows/subscription-auto-switch.md gains the two pull rows in the trigger-surface table and a #2643 section carrying the reasoning above.

Fixes #2643. Related to #1081.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP

`pull_coordination_service.apply_task_result` is a CAS-won terminal
writer and carried every OTHER terminal hook — the #1578 completion
event, the #1804 activity close — but no SUB-003 hook. So a pull-owned
turn the provider refused:

  * recorded no `subscription_rate_limit_events` row, so the subscription
    was never skip-listed and no usage card or pressure badge counted it;
  * never called `handle_subscription_failure`, so the agent stayed
    pinned to the subscription that had just refused it;
  * landed FAILED, where `redelivery_governor` treats `billing` as a
    correlated code — so the re-delivery that might have recovered it is
    the thing most likely to be paused.

Everything the push path gained in #441/#471/#792, and everything #2638
added on top, was unreachable from a pull-dispatched turn.

Inert today (`PULL_MODE_PILOT_AGENTS` gates the path and nobody is
piloted), which is why it needed a test rather than a soak: piloting a
subscription-backed agent would have silently removed SUB-003 from that
agent with nothing saying so.

Three properties are load-bearing.

**The vocabularies do not line up.** The worker's typed `error_code`
calls the quota class `billing` (`result_callback._STATUS_MAP` maps an
agent 429 to it); this subsystem calls it `rate_limit`. `_switch_failure_kind`
is the map, and it is an ALLOWLIST — a code it has not heard of switches
nothing, because "switch unless the code looks benign" would churn an
agent through every subscription it owns the first time a worker reports
an unfamiliar crash class.

**CAS-won branch only**, beside the two hooks it sits with. A replayed
terminal short-circuits above the write and a late one loses the CAS, so
neither spends a second switch (the #1083 rule). Past that gate,
`handle_subscription_failure` owns the rest: it records the event
unconditionally, then takes the #799 per-agent `agent_switch_lock` and
re-reads under it, so two failures racing on one agent still switch once.

**A SUCCESS terminal is excluded, on the merits.** The gate is
`error_code` rather than the FAILED/CANCELLED split — a worker that
labels a quota refusal `cancelled` still refused for a quota reason — but
a turn the provider SERVED is evidence the subscription works, so a stray
`error_code` riding a success must not move the agent off it. It is also
the one branch where the sink never binds `err_text`, so an ungated hook
would raise NameError and turn a committed, billed terminal into a 500.

Re-delivery, stated explicitly per AC #3: this hook re-delivers nothing.
A switched agent's next re-delivery is expected to succeed IF the lease
reaper re-queues the row (under `MAX_REDELIVERY`) and the #1085 governor
is not paused — and `billing` is exactly the class the governor counts,
so a fleet-wide quota event can legitimately hold re-delivery back even
after a successful switch. The switch is not wasted then; the next
scheduled or claimed turn benefits.

The sink is sync and its caller async, so the call goes through
`subscription_auto_switch.spawn_subscription_failure` — the same wrapper
shape as `spawn_task_terminal_event` and `spawn_close_execution_activity`:
one coroutine (not a wrapper around a pre-built one, which leaves two
objects to close and still warns "never awaited"), a strong reference
held until it finishes, a raising switch logged and swallowed, and
no-running-loop treated as a clean skip.

Still NOT wired on the pull sink, named so it is not mistaken for done:
the #526 AUTH dispatch breaker and the governor's own
`record_terminal_failure`. `apply_result` has both; neither is a SUB-003
concern.

23 tests, mutation-checked: a pass-through failure-kind map, hoisting the
call above `if won:`, and dropping the SUCCESS exclusion each turn the
suite red. Plus a structural AST pin that the one call site stays inside
the CAS gate.

Related to #2643. Related to #1081.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP
@dolho
dolho requested a review from vybe September 9, 2026 13:22
@vybe

vybe commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-09: on this train. No criticals. I edited the PR body twice — no code touched — flagging both so they aren't silent.

1. Related to #2643 → Fixes #2643. Without the keyword issue-status-on-merge.yml can't see the issue and #2643 strands in status-in-progress. Worth saying plainly since this comes up often: that workflow fires on pull_request closed against dev and only adds status-in-dev — it never closes anything. So Fixes on a dev-targeted PR does not close the issue early; closure still happens at the dev → main release. Related to #1081 is left alone (epic).

2. Corrected a factual claim that would have ridden into the squash commit. The body's third bullet said a pull terminal "landed FAILED, where redelivery_governor treats billing as a correlated code — so the re-delivery that might have recovered it is the thing most likely to be paused." AC #3 repeated it. The governor isn't involved in the pull path in either direction:

  • write side — get_redelivery_governor().record_terminal_failure has exactly one caller, task_execution_service.py:2556, the push apply_result. The pull sink never arms it.
  • read side — consumers are routers/agents.py:1675 (push callback), capacity_manager.py:673, cleanup_service.py:724,969. services/lease_reaper_service.py — the pull re-delivery path — never consults it; grep returns zero.

Your own "Deliberately not in scope" section has this right ("the pull sink still has no redelivery_governor.record_terminal_failure"), so the body contradicted itself and the flow doc carried both versions. Mechanical because the correct fact was already written down two paragraphs later. Left as a note in the body rather than a silent deletion so the record shows what changed.

Why this passed where its sibling #2645 did not, since they touch the same area and the difference is worth stating: #2645 keys on TaskExecutionErrorCode.BILLING, which is never assigned anywhere in src/backend. This PR keys on the validated wire string, and the producer chain is complete and real — docker/base-image/agent_server/services/pull_worker.py:223 _PULL_STATUS_MAP = {503:"auth", 429:"billing", …} → models.py:2139 _PULL_ERROR_CODES + PullTaskResultRequest._check_error_code (422 on anything else) → routers/internal.py:216 → apply_task_result. It also does not touch _assigned_subscription_is_refused, so the fresh_refusing OR db_predicate shape #2645 was ejected for is structurally absent here (grep over the full diff returns nothing).

Verified rather than assumed: the hook at pull_coordination_service.py:528-533 is inside if won: (:461), beside the #1578 emit and the #1804 activity close, so it obeys the execution.md CAS invariant. Exactly-once is enforced, not just tested — an authoritative terminal short-circuits at :396, and a re-delivered worker's second billing terminal loses the CAS at db/schedules/executions.py:436-441,512-515 (status NOT IN (terminal) plus claim_token match), so won=False and no second switch. Downstream, handle_subscription_failure snapshots pre-lock and returns on current_sub_id != sub_at_entry, so two failures racing on one agent still switch once. Tests genuinely execute the path (23 tests across three executing layers; the one read_text() feeds ast.parse as a supplementary shape pin, not a substitute). Local: 23 passed, plus 366 across the related families and 158 over every pre-existing apply_task_result consumer.

Two follow-ups, neither blocking:

  • apply_result (the refactor: fire-and-forget dispatch — a hung turn holds zero backend resource #1083 async push callback) has no SUB-003 hook either — grep over task_execution_service.py:2210-2620 returns zero subscription references; both push hooks live in execute_task's synchronous response handling. DISPATCH_ASYNC defaults false, so that path is dark today, same posture as PULL_MODE_PILOT_AGENTS. But flipping it on for a subscription-backed agent reproduces exactly the bug this PR fixes, on a different flag. Worth an issue.
  • Third copy of the fire-and-forget spawn wrapper (subscription_auto_switch.py:96-140), after event_dispatch_service._spawn_named and activity_service.spawn_close_execution_activity. You're explicit that you're mirroring them, and the one real difference (swallowing inside the coroutine) would have needed an import edge to share. Fine as written; worth a shared leaf when a fourth appears.

Noted for the record, not as an objection: error_code is agent-supplied JSON and now drives a fleet-visible effect — a subscription_rate_limit_events row that skip-lists a shared subscription for 2h across every other agent's candidate selection, plus a container recreate. Not a new trust boundary (an agent server can already force the push-path switch by returning 429), and routers/agents.py:1715-1722 shows the codebase already reasons about this. Flagged so it is a decision on record rather than an oversight.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merge-train: batch validated green on train/20260909-1840 (#2664) — full suite incl. pytest x3 seeds and regression diff.

@vybe
vybe merged commit 294782b into dev Sep 9, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants