Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions src/server/responses/adapter-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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.
Expand Down
24 changes: 24 additions & 0 deletions src/server/responses/antigravity-fault-rotation.ts
Original file line number Diff line number Diff line change
@@ -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;
}
1 change: 1 addition & 0 deletions structure/transports/responses.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions tests/helpers/responses-core-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
27 changes: 27 additions & 0 deletions tests/server/server-google-antigravity-oauth-401-replay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading