Repository navigation
fix(ai): stagger gateway token refreshes and resume runs they cut - #3742
Conversation
Every completed consent for a connector without a workspace id (Gmail, Outlook, Google Drive, Teams) renewed the connector's default grant: a second account added through Add credential silently replaced the first, and Reconnect on any other row rewrote the default instead (#3711). The pending authorization now carries the intent. Migration 0130 adds app.connector_oauth_states.reconnect_credential_id (NULL = Add, no foreign key); the start door takes an optional credentialId and keeps it only when it names an OAuth grant of that organization and connector. The callback reads the intent from the consumed row alone, re-checks the initiator's membership and developer role, and refuses a Reconnect whose credential is gone before redeeming the code. storeOauth2Grant runs as one transaction under a per-(organization, connector) advisory lock, row-locks the Reconnect target before reading the siblings, and lets a pure planner decide: Add stores a new credential under a free name, Reconnect renews exactly its credential (needs-reauth cleared, disabled kept) or saves nothing, Slack keeps one credential per workspace and refuses a Reconnect into another. Every credential create takes the same pair lock, so concurrent first adds no longer die on the name or default index. New fixed pages: credential_missing, account_mismatch, forbidden. The native-Postgres lane checkConnectorOauthIntent proves each case; the claim-race probe's initiator is now a member of its organization.
Connect and Reconnect sent the browser to the same start URL, so nothing told the callback which credential a consent was for (#3711). goToAuthorization now takes an explicit intent: Add credential > Connect starts an Add that names no credential, and a row's Reconnect names that row's id. The parameter name is shared with the start door (lib/shared/connector-consent.ts), so the page and the door cannot drift into a Reconnect that silently lands as an Add.
The connector guides promised that Add credential connects another account and that Reconnect keeps the credential's name and references, while the product renewed the default grant for both (#3711). EN, DE and FR now say what each does: every Connect adds a new credential (named after the connector and numbered, renamed through Edit credential), Slack keeps one credential per workspace, Reconnect renews exactly the row it was chosen on and leaves a disabled credential disabled, and a removed credential, a lost role or another Slack workspace saves nothing. The connectors manual suite asserts the rows by their masked previews, explains how to run the consent boxes against a loopback fake vendor, and gains CONN-F19/F20 and CONN-B7-B10; the automation, pins and error-code registers name the new coverage and pages.
Every refresh of an Anthropic account revokes the access token it replaces. With one refresh threshold for the whole pool, accounts that were refreshed together (the first pass after an outage) fell due at the same instant and stayed in step forever, so each refresh revoked every token in the pool at once. A token was also handed out with no promise of any remaining life, so a run could start seconds before the refresh that cut it (observed 2026-09-28: a Claude Code run failed with "401 OAuth access token has been revoked" two minutes after the 11:00:58 refresh of every account). Each account now plans its refresh earlier than the skew by its own share of half the window between the token's issue and the skew point, read off a hash of its id. Accounts refreshed together fall due at different times and, each on a cycle of its own length, do not fall back into step. A hand-out refreshes only the accounts that are due. AI_GATEWAY_TOKEN_MIN_HANDOUT_SECONDS (default 3600, 0 turns it off) serves an active account whose planned refresh is closer than the floor as available: false, with available_at set to that refresh, so new work waits for the fresh token. The token endpoints report the planned refresh as refresh_at beside the unchanged vendor expires_at.
A Claude Code run served by the subscription broker died with "401 OAuth access token has been revoked" when the AI gateway refreshed its account mid-turn. It settled as an ordinary harness error, so the auto-retry spent one of the three crash-loop attempts and excluded an account that already held a fresh token. A harness error with API status 401 on a turn the broker served now settles as credential_rotated, in both lanes. The retry vends again and resumes the conversation. The first two rotations in a row neither count toward AUTO_RETRY_MAX_ATTEMPTS nor exclude the account, and the third takes the ordinary path, so a dead grant still stops. A rotation after fifteen minutes of work starts a new streak. The task lane decides from its run history, so the failed mark now stamps its code on the row (migration 0130, project_agent_runs.failure_code) and the retry job and the kick plan read it back. The automation lane carries the streak on the agent cursor (planWorkflowAgentRetry). The empty-pool diagnosis names a due token refresh beside a spent quota, since Tale AI gateway now reports both as available: false.
The broker reference and the providers form guide now map refresh_at, the instant Tale AI gateway's refresh ends a token, as the expiry field with a one-hour safety margin (3,600,000 ms), matching the gateway's hand-out floor, instead of the vendor's later expires_at. They also say what happens when a vendor revokes a brokered token in the middle of a turn. The retry fetches a fresh token and continues the conversation, the first two such interruptions in a row neither count toward the automatic retries nor exclude the account, and a turn longer than the token's life (an agent may work 12 hours, an Anthropic token lasts eight) should expect one. The task automation and execution log pages carry the retry rule. English, German and French.
Read without the English, the new German paragraphs doubled a "mit" and bent the streak-reset and long-run sentences out of shape, and one French clause said a refresh "takes place in less than an hour". Same facts, native phrasing.
…ation A free credential rotation kept the attempt number it was parked under, even after two hours of work. A node that had spent its three retries, worked two hours and was then cut by the gateway's refresh stayed at attempt 3, so the next short failure ended the run, while the same attempt failing any other way would have refreshed the budget. With the gateway's hand-out floor, almost every real rotation comes after a quarter of an hour of work, so the free path fared worse than the ordinary one. Past the progress threshold the free re-kick now parks under attempt 0: the budget refreshes, as it does for any failure after progress, and the free re-kick spends none of it. The task lane already did this.
Review of the floor and the stagger found three gaps. The floor was hard. A pool of one account refused all new work for the hour before each refresh, and a pool of two whenever both were near theirs. A platform start that finds no usable token fails, and its auto-retry spends the budget in seconds, so tasks failed that used to run. The floor now holds an account back only while another active account of its vendor, with quota left and outside its own floor, can take the work. When none can, the held-back account with the latest planned refresh is handed out: a turn a refresh may cut, and that then resumes on a fresh token, beats a pool that refuses all work. A due refresh that kept failing flipped the account between error and active, and only the active phase was held back. The floor now applies to every account but an expired one. Cycles of different lengths still meet by chance, and the first pass after an outage or an upgrade finds many accounts due at once. A due account now waits until ten minutes after its vendor's latest refresh, though never past its skew point, so a refresh ends one account's running work at a time. A month of simulated passes never refreshes both accounts of the incident's pool in one pass.
With the gateway's hand-out floor soft, mapping refresh_at with an hour's safety margin would make it hard again on Tale's side: a pool whose accounts are all near their refresh would refuse new work, and a pool of one account would before every refresh. The providers form guide and the broker reference go back to expires_at with the default margin, and describe refresh_at and the strict margin as an explicit trade-off, capped at 3,600,000 ms as the schema is. The standard-field table no longer calls available and available_at quota-only, since Tale AI gateway also reports a due refresh through them. English, German and French.
yannickmonney
left a comment
There was a problem hiding this comment.
Independent scoped review at 03898d07a95a62762136123d9bd723dd85883415: the refresh/floor and bounded retry behavior passed my fresh local replay.
- Gateway: 142/142 tests across accounts, config, routes and rollback.
- Platform: 72/72 tests across task/workflow retry planners, drive/stepper orchestration, broker pool, kick plan and retry job.
- Independent specification check against the actual task and workflow planners: 326 reachable short-failure transitions, including exhaustion, plus three controls around the 15-minute progress threshold. Both lanes matched the expected two-free-rotations policy and finite ordinary retry budget.
One nonblocking wording correction: comments in task_auto_retry.ts (the credential_rotated type and isCredentialRotation), agent_run_host.ts, agent_retry.ts, and migration 0133 still say a broker-backed 401 is the broker refreshing/revoking the token. The classifier observes a broker-served turn plus status 401; it cannot establish that cause. Please align these comments with the PR/docs wording: suspected rotation eligible for bounded recovery. The first two retries can also be attempted for an unrelated authentication failure; the exhaustion controls correctly prevent an unlimited short-failure loop.
Scope: vendor/account-store, SQL and sandbox boundaries in these suites are synthetic; no real provider, agent execution or production test ran. I read the additive nullable-column migration, but did not independently replay the PostgreSQL migration/integration lanes or browser flows in this pass. This is evidence for the reviewed paths, not a full-gate or deployment approval. Keep the documented platform-before-gateway rollout order and current-head native/CI evidence in the handoff.
A gateway token refresh can revoke a token while a task or automation is using it. Spread planned refreshes across accounts, avoid handing out tokens near that refresh when another account can serve, and give broker-backed 401 failures two bounded recovery attempts before they consume the ordinary retry budget.
The gateway spaces refreshes of the same vendor by ten minutes unless an account reaches its expiry-skew deadline. Its hand-out floor is soft: the last active account with quota can still serve. An overdue short-lived token stays held when a healthy alternative exists.
refresh_atreports the planned refresh;expires_atretains the vendor expiry.Task and automation retries preserve the account for the first two consecutive broker-backed 401 failures and request a fresh credential. A third follows ordinary failure handling; fifteen minutes of progress resets the streak. Conversation resumption requires the stored handle and sandbox session. A 401 alone does not prove that rotation caused the failure. Migration
0133_project_agent_runs_failure_code.sqladds the nullable failure classification without rewriting history.EN/DE/FR docs keep
expires_atwith the default five-minute consumer margin, so the gateway can apply its soft floor. They explain the stricterrefresh_atalternative and its pool-exhaustion trade-off. Long turns may still cross a refresh; no fixed vendor token lifetime is assumed.Validation
Merge after #3729 and #3771, whose reviewed changes are integrated here. Shipped recurrence migration 0130 remains unchanged; OAuth uses 0131, recurrence repair 0132, and this change 0133. Deploy the platform retry support before the gateway: a gateway upgrade can make existing accounts due for refresh, and the skew deadline may bypass spacing.