diff --git a/src/server/responses/adapter-dispatch.ts b/src/server/responses/adapter-dispatch.ts index 84d99af5980..ae25eebcbc9 100644 --- a/src/server/responses/adapter-dispatch.ts +++ b/src/server/responses/adapter-dispatch.ts @@ -123,6 +123,7 @@ import { chargeWorkflowSends } from "../../lib/workflow-budget"; import { hasWorkflowSendObserver } from "../../lib/request-execution-budget"; import { isAntigravityAccessDeniedRefusal, isAntigravityValidationRefusal } from "./antigravity-validation-refusal"; import { createAntigravityModelDenialRecovery, recoverAntigravityAccount } from "./antigravity-model-denial-recovery"; +import { isAntigravityFaultRotatable } from "./antigravity-fault-rotation"; import { adapterSendBudgetRefusal } from "../workflow-refusal"; import { AdmissionModelDeniedError, admissionModelDeniedResponse, projectAdmissionModelDeniedLog } from "../admission-model-scope"; import { rejectAnthropicPerMessageEffort } from "../../adapters/anthropic/per-message-effort"; @@ -616,6 +617,8 @@ export async function prepareAdapterExchange( let oauth401ReplayAttempted = transportState.oauth401ReplayAttempted; let antigravityAuthRotationAttempted = false; let antigravityFaultRotationAttempted = false; + const antigravityFaultRotatable = (response: Response) => isAntigravityFaultRotatable(route.providerName, response, + transportState, antigravityPoolActivated, antigravityFaultRotationAttempted); // Direct requests get one reasoning-effort downgrade. Combo candidates may walk down the // published ladder one refused rung at a time; the request send budget bounds those retries. const reasoningEffortDowngradeGuard: { attempted: boolean } = { attempted: false }; @@ -1094,14 +1097,8 @@ export async function prepareAdapterExchange( if (rotated) { upstreamResponse = rotated; continue recovery; } } - // A 502/503/504 that outlived the same-account ladder is replayed once on a live sibling: the - // failing account is cooled briefly (not marked), and one extra ladder bounds the load a - // pool-wide outage can add to a request. - if (route.providerName === "google-antigravity" && [502, 503, 504].includes(upstreamResponse.status) - && transportState.activeAdapter.name === "google" - && antigravityPoolActivated && !antigravityFaultRotationAttempted - && !isNonReplayableResponse(upstreamResponse) - && transportState.genericFailovers < transportState.genericFailoverLimit) { + // A 502/503/504 that outlived the same-account ladder replays once on a live sibling. + if (antigravityFaultRotatable(upstreamResponse)) { antigravityFaultRotationAttempted = true; const rotated = await rotateAntigravityAuth(upstreamResponse, "transient-5xx", sent => rotateAntigravityAccountOnUpstreamFault(antigravityPoolActivated, sent.accountId, sent.generation, route.modelId)); @@ -1652,8 +1649,9 @@ export async function prepareAdapterExchange( } upstreamResponse = result; // The hop's permit is already settled by the dispatch boundary above; continuing - // only skips the remaining arms, it does not abandon a reservation. - if (isNonReplayableResponse(upstreamResponse)) continue recovery; + // only skips the remaining arms, it does not abandon a reservation. A replacement's + // surviving 502/503/504 re-enters recovery so the one-hop fault rotation can run. + if (isNonReplayableResponse(upstreamResponse) || antigravityFaultRotatable(upstreamResponse)) continue recovery; } catch (err) { // A local admission denial is terminal for the whole request: rotating to another // account cannot re-scope the key, so the refusal answers in place of the 429. diff --git a/src/server/responses/antigravity-fault-rotation.ts b/src/server/responses/antigravity-fault-rotation.ts new file mode 100644 index 00000000000..d7c78188ae6 --- /dev/null +++ b/src/server/responses/antigravity-fault-rotation.ts @@ -0,0 +1,24 @@ +import { isNonReplayableResponse } from "../../lib/upstream-retry"; + +/** + * Whether an Antigravity 502/503/504 that outlived the same-account transient ladder may be + * replayed once on a live sibling. The failing account is cooled briefly (not marked), and the + * per-request `attempted` flag keeps a pool-wide outage to one extra ladder per request. + * + * The recovery loop asks this for the response it is holding and again for the response a 429 + * account hop just produced: that hop's replacement can be the 5xx, and without asking here the + * 429 loop would leave recovery with the one-hop fault rotation still unspent. + */ +export function isAntigravityFaultRotatable( + providerName: string, + response: Response, + state: { activeAdapter: { name: string }; genericFailovers: number; genericFailoverLimit: number }, + poolActivated: boolean, + faultRotationAttempted: boolean, +): boolean { + return providerName === "google-antigravity" && [502, 503, 504].includes(response.status) + && state.activeAdapter.name === "google" + && poolActivated && !faultRotationAttempted + && !isNonReplayableResponse(response) + && state.genericFailovers < state.genericFailoverLimit; +} diff --git a/structure/transports/responses.md b/structure/transports/responses.md index 942b578df69..9d7ef92baa9 100644 --- a/structure/transports/responses.md +++ b/structure/transports/responses.md @@ -429,6 +429,7 @@ Final-route normalization in `src/server/responses/core-normalize.ts` decodes cl | `sidecar-execution.ts`, `sidecar-send-budget.ts` | Image/video versus web-search execution, Chat raw-reasoning preference forwarded to both loop bridges under [reasoning display parity](../providers/chat-compat.md#reasoning-display-parity-hidethinkingsummary), per-build adapter prompt estimates for usage logging, shared rotation, and adapter-aware prepaid inference/producer ownership under the [spend contract](responses-spend.md#prepaid-initial-sends). | | `completion-policy.ts`, `run-turn-execution.ts` | Empty-completion eligibility and adapter-owned event turns; refreshed retries reject previously failed key bindings and revalidate after each queued admission; adapter-owned CLI spawns receive the post-setup `IncomingMeta.beforePhysicalSend` fence, with [replacement-key readmission](responses-failover.md#upstream-key-attempt-accounting). | | `adapter-dispatch.ts` | Translated initial dispatch, bounded recovery (including [Anthropic thinking-signature recovery](anthropic-thinking-recovery.md)) and the shared continuation retry counter. Initial and rebuilt adapter budget refusals retain the HTTP 413 [byte-accounting contract](byte-accounting.md#request-copy-accounting); ordinary build errors remain 400. | +| `antigravity-fault-rotation.ts` | The guard for the Antigravity one-hop 502/503/504 sibling replay. `adapter-dispatch.ts` asks it about the response it holds and about the replacement a 429 account hop returns, so a replayable 5xx from that replacement re-enters recovery and can still take the one fault hop under the [rotation contract](responses-failover.md#account-refusal-and-rotation-boundaries). | | `adapter-continuation.ts`, `adapter-delivery.ts` | Continuation event sources and final streaming/buffered bridging; Anthropic routed summaries pass through `src/responses/compaction-summary.ts` before either bridge. A streamed turn with a `clientEncoder` option is handed to `src/server/inference/client-encoder-delivery.ts` instead of the bridge. | Direct Chat delivery preserves the live `localUpstream` getter when adding collector/provenance options, so replacement routes retain their own stall policy. Local preflight/auth responses and tool-guard messages carry process-local ownership through the pipeline and lifetime wrappers for the [Chat client error contract](../data-planes/error-detail.md#client-error-bodies-chat); Responses wire bytes retain their existing formatting. Reusable helpers live in `core-auth.ts`, `core-codex-account.ts`, `core-combo.ts`, `core-combo-failure.ts`, `core-combo-native.ts`, `combo-requested-effort.ts`, `core-errors.ts`, `core-lifetime.ts`, `core-normalize.ts`, `core-opaque-recovery.ts` and `core-replay.ts`. `core-options.ts` owns the public option types diff --git a/tests/helpers/responses-core-source.ts b/tests/helpers/responses-core-source.ts index d4251593e28..98b253558b6 100644 --- a/tests/helpers/responses-core-source.ts +++ b/tests/helpers/responses-core-source.ts @@ -106,6 +106,7 @@ export const RESPONSES_CORE_MODULES = [ "adapter-failure-message.ts", "antigravity-validation-refusal.ts", "antigravity-model-denial-recovery.ts", + "antigravity-fault-rotation.ts", "adapter-continuation.ts", "adapter-delivery.ts", "anthropic-thinking-recovery.ts", diff --git a/tests/server/server-google-antigravity-oauth-401-replay.test.ts b/tests/server/server-google-antigravity-oauth-401-replay.test.ts index 62369a35e73..f6f5b93f65b 100644 --- a/tests/server/server-google-antigravity-oauth-401-replay.test.ts +++ b/tests/server/server-google-antigravity-oauth-401-replay.test.ts @@ -789,6 +789,33 @@ describe("Google Antigravity OAuth upstream 401 replay", () => { } finally { await server.stop(true); } }); + test("a 429 hop whose sibling then answers 5xx takes the one fault hop to a third account", async () => { + await seedOAuth(); + const firstId = getAccountSet("google-antigravity")!.activeAccountId; + const siblingId = await seedSibling(); + await seedThirdSibling(); + saveConfig(antigravityConfig()); + const rateLimited = { status: 429, rawBody: JSON.stringify({ error: { code: 429, status: "RESOURCE_EXHAUSTED", message: "Rate limit exceeded." } }) }; + const observed = installOAuthFetch([rateLimited, rateLimited, rateLimited, 503, 503, 503, 200]); + const server = startServer(0); + try { + const response = await postResponses(server); + expect(observed.chatAuth).toEqual(["Bearer rejected-access", "Bearer rejected-access", "Bearer rejected-access", + "Bearer access-b", "Bearer access-b", "Bearer access-b", "Bearer access-c"]); + expect(response.status).toBe(200); + await response.text(); + expect(observed.chatProjects.at(-1)).toBe("project-c"); + // A keeps its rate-limit cooldown and B gets the short fault cooldown; neither is marked. + const eligible = eligibleFailoverAccounts("google-antigravity", Date.now(), classifyModelFamilyForQuota("google-antigravity", "gemini-3.8-flash")); + expect(eligible).not.toContain(firstId); + expect(eligible).not.toContain(siblingId); + for (const row of getAccountSet("google-antigravity")!.accounts) expect(row.needsReauth).not.toBe(true); + const kinds = readUsageEntries().at(-1)?.attempts?.flatMap(attempt => attempt.recoveryKinds) ?? []; + expect(kinds).toContain("oauth-account-429"); + expect(kinds).toContain("transient-5xx"); + } finally { await server.stop(true); } + }); + test("a 503 on every account stops after one sibling hop and returns the 503", async () => { await seedOAuth(); await seedSibling();