From 2a34a538b63bd3f3a53ff176f1a087d9e8b73e36 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 24 Nov 2026 16:11:43 -0600 Subject: [PATCH] fix(antigravity): a swarm's usage limit holds only swarms, and an ordinary limit never holds a swarm Google's Antigravity CLI bills swarms to its own pool (project default-cli-project on the stable endpoint). Seen live: a swarm 429 held the whole agent for an hour while the same account's ordinary route answered. Usage-limit evidence is now keyed by credential and quota scope: a run's context may name a providerQuotaScope (absent = the default quota, which is every row saved before), swarm selection records the CLI's scope, and the pre-dispatch hold learns a pending run's scope read-only (selection itself runs later, after workspace preparation). A wake held for a limit is not a Stop, so its retry still runs the swarm and the three-attempt cap is unchanged. The heartbeat failure path also keeps the refusal's plain sentence as the run error, so the agent's error reason is never the Runner's command JSON. Co-Authored-By: Claude Opus 5.5 --- .../heartbeat-provider-limit-wait.test.ts | 55 +++++++++++++++++++ .../src/services/antigravity-swarm-refusal.ts | 7 +++ .../src/services/antigravity-swarm.db.test.ts | 36 +++++++++++- server/src/services/antigravity-swarm.ts | 29 +++++++++- server/src/services/heartbeat.ts | 6 ++ .../services/heartbeat/provider-limit-wait.ts | 22 +++++++- .../services/heartbeat/run-completion.test.ts | 22 ++++++++ .../src/services/heartbeat/run-completion.ts | 4 ++ .../native-runtime/native-startup-retry.ts | 28 ++++++++++ 9 files changed, 203 insertions(+), 6 deletions(-) diff --git a/server/src/__tests__/heartbeat-provider-limit-wait.test.ts b/server/src/__tests__/heartbeat-provider-limit-wait.test.ts index 53a267155e8..47a814b335a 100644 --- a/server/src/__tests__/heartbeat-provider-limit-wait.test.ts +++ b/server/src/__tests__/heartbeat-provider-limit-wait.test.ts @@ -624,4 +624,59 @@ describePostgres("heartbeat provider usage limit wait", () => { expect(successor.contextSnapshot).toMatchObject({ wakeCommentId: commentId }); }, 60_000); }); + + describe("quota-scoped holds (Google's Antigravity CLI bills swarms to its own pool)", () => { + const SWARM = { providerQuotaScope: "antigravity_cli" }; + // The live swarm refusal: Google's CLI out of quota while the same account's ordinary route answered. + const swarmLimited = (minutesAgo: number) => ({ ...rateLimited(minutesAgo, { + provider: "antigravity", phase: "turn", message: "Google refused the swarm: this account is out of quota for now. Try again later." }), + errorCode: "native_provider_usage_limit" }); + + async function defer(f: { companyId: string; agentId: string; issueId: string }, scope: string | null) { + const [agent] = await db.select().from(agents).where(eq(agents.id, f.agentId)); + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running", + invocationSource: "automation", triggerDetail: "system", contextSnapshot: { issueId: f.issueId } }).returning(); + const deps = { + setRunStatusIfRunning: vi.fn(async () => ({ updated: true, run: { ...run, status: "cancelled" } })), + setWakeupStatus: vi.fn(async () => undefined), + appendRunEvent: vi.fn(async () => undefined), + scheduleBoundedRetryForRun: vi.fn(async () => ({ outcome: "scheduled" })), + releaseIssueExecutionAndPromote: vi.fn(async () => undefined), + finalizeAgentStatus: vi.fn(async () => undefined), + providerQuotaScope: vi.fn(async () => scope), + }; + const deferred = await createProviderLimitWait(db, deps as never) + .deferRunForProviderLimit(run, agent, { resumingAdmittedRun: false, conversation: false }); + return { deferred, deps }; + } + + it("lets ordinary work run after a swarm hit the CLI's quota", async () => { + const f = await seed([{ ...swarmLimited(5), contextSnapshot: SWARM }]); + expect((await defer(f, null)).deferred).toBe(false); + }); + + it("holds the next swarm after a swarm hit the CLI's quota, in plain words", async () => { + const f = await seed([{ ...swarmLimited(5), contextSnapshot: SWARM }]); + const { deferred, deps } = await defer(f, "antigravity_cli"); + expect(deferred).toBe(true); + const [, , patch] = deps.setRunStatusIfRunning.mock.calls[0] as unknown as [string, string, { error: string; resultJson: Record }]; + expect(patch.error).toMatch(/^Swarms are out of quota for now\. Paperclip will try again after .+; other work on this agent continues\.$/); + expect(patch.resultJson.providerLimitWait).toMatchObject({ quotaScope: "antigravity_cli" }); + // A later successful swarm clears it; an ordinary success does not. + const ordinaryOk = await seed([{ ...swarmLimited(10), contextSnapshot: SWARM }, + { status: "succeeded", startedAt: new Date(Date.now() - 3 * 60_000), finishedAt: new Date(Date.now() - 2 * 60_000) }]); + expect((await defer(ordinaryOk, "antigravity_cli")).deferred).toBe(true); + const swarmOk = await seed([{ ...swarmLimited(10), contextSnapshot: SWARM }, + { status: "succeeded", startedAt: new Date(Date.now() - 3 * 60_000), finishedAt: new Date(Date.now() - 2 * 60_000), contextSnapshot: SWARM }]); + expect((await defer(swarmOk, "antigravity_cli")).deferred).toBe(false); + }); + + it("does not hold a swarm for an ordinary-route limit, and old unscoped evidence still holds ordinary work", async () => { + const f = await seed([rateLimited(5)]); + expect((await defer(f, "antigravity_cli")).deferred).toBe(false); + const { deferred, deps } = await defer(await seed([rateLimited(5)]), null); + expect(deferred).toBe(true); + expect((deps.setRunStatusIfRunning.mock.calls[0] as unknown as [string, string, { error: string }])[2].error).toMatch(/^This agent's provider usage limit/); + }); + }); }); diff --git a/server/src/services/antigravity-swarm-refusal.ts b/server/src/services/antigravity-swarm-refusal.ts index e29aa66d1a1..f207c3a6af6 100644 --- a/server/src/services/antigravity-swarm-refusal.ts +++ b/server/src/services/antigravity-swarm-refusal.ts @@ -6,6 +6,13 @@ */ export const ANTIGRAVITY_SWARM_UNAVAILABLE = "antigravity_swarm_unavailable"; +/** + * The provider quota a swarm draws on. Google's Antigravity CLI bills a separate + * pool from the same account's ordinary route (seen live: the CLI's pool was + * exhausted while the connection answered), so its limits hold only swarms. + */ +export const ANTIGRAVITY_CLI_QUOTA_SCOPE = "antigravity_cli"; + /** The activity a signed-in user's /swarm request records (the request's only proof). */ export const ANTIGRAVITY_SWARM_REQUESTED_ACTION = "issue.antigravity_swarm_requested"; diff --git a/server/src/services/antigravity-swarm.db.test.ts b/server/src/services/antigravity-swarm.db.test.ts index 9e032567e7a..a27a7ca3615 100644 --- a/server/src/services/antigravity-swarm.db.test.ts +++ b/server/src/services/antigravity-swarm.db.test.ts @@ -3,7 +3,7 @@ import { and, eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { activityLog, agentWakeupRequests, agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; -import { ANTIGRAVITY_SWARM_REQUESTED_ACTION, recordAntigravitySwarmRequest, resolveAntigravitySwarmRun } from "./antigravity-swarm.js"; +import { ANTIGRAVITY_SWARM_REQUESTED_ACTION, antigravitySwarmQuotaScope, recordAntigravitySwarmRequest, resolveAntigravitySwarmRun } from "./antigravity-swarm.js"; import { instanceSettingsService } from "./instance-settings.js"; import { issueService } from "./issues.js"; import { deliveredQueuedCommentIds } from "./queued-comment-delivery.js"; @@ -171,6 +171,40 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", ( await expect(automatic(f, (await insertRun(f, {})).id)).rejects.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(/three attempts/) }); }); + it("records the CLI's quota scope on the swarm it selects, and names it before dispatch while the request is unfulfilled", async () => { + const f = await seed(); + const scope = (runId: string, context: Record = { issueId: f.issue.id }) => + antigravitySwarmQuotaScope(db, { companyId: f.company.id, issueId: f.issue.id, runId, agent: f.agent, context }); + // Before selection (the usage-limit hold runs first), a pending request already names the CLI's quota. + const first = await insertRun(f, {}); + expect(await scope(first.id, { issueId: f.issue.id, antigravitySwarmCommentId: f.comment.id })).toBe("antigravity_cli"); + expect(await automatic(f, first.id)).toMatchObject({ request: expect.any(String) }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, first.id)))[0]!.contextSnapshot) + .toMatchObject({ antigravitySwarmCommentId: f.comment.id, providerQuotaScope: "antigravity_cli" }); + await setStatus(first.id, "succeeded"); + // Fulfilled: later work is ordinary and draws on the default quota. + expect(await scope((await insertRun(f, {})).id)).toBeNull(); + const other = await seed({ record: "none" }); + expect(await antigravitySwarmQuotaScope(db, { companyId: other.company.id, issueId: other.issue.id, runId: randomUUID(), agent: other.agent, + context: { issueId: other.issue.id } })).toBeNull(); + }); + + it("treats a wake held for the CLI's quota as not yet run: its retry runs the swarm, and the three-attempt cap still applies", async () => { + const f = await seed(); + const held = await insertRun(f, { status: "cancelled", errorCode: "provider_limit_wait", finishedAt: new Date(), + contextSnapshot: { issueId: f.issue.id, antigravitySwarmCommentId: f.comment.id } }); + expect(await resolve(f, { runId: (await insertRun(f, { retryOfRunId: held.id })).id, + context: { issueId: f.issue.id, wakeReason: "provider_limit_retry" } })).toMatchObject({ request: expect.any(String) }); + const g = await seed(); + for (let attempt = 0; attempt < 3; attempt++) { + await insertRun(g, { status: "cancelled", errorCode: "provider_limit_wait", contextSnapshot: { issueId: g.issue.id, antigravitySwarmCommentId: g.comment.id } }); + const run = await insertRun(g, {}); + expect(await automatic(g, run.id)).toMatchObject({ request: expect.any(String) }); + await setStatus(run.id, "failed"); + } + await expect(automatic(g, (await insertRun(g, {})).id)).rejects.toMatchObject({ message: expect.stringMatching(/three attempts/) }); + }); + it("starts exactly one swarm for one request when two wakes arrive together", async () => { const f = await seed(); const [a, b] = [await insertRun(f, {}), await insertRun(f, {})]; diff --git a/server/src/services/antigravity-swarm.ts b/server/src/services/antigravity-swarm.ts index 41fa8f64ca0..89c759a1a23 100644 --- a/server/src/services/antigravity-swarm.ts +++ b/server/src/services/antigravity-swarm.ts @@ -24,7 +24,8 @@ import { queuedCommentIdsFromRunContext, queuedCommentIdsFromWakePayload } from */ export const ANTIGRAVITY_SWARM_COMMAND = "swarm" as const; export { ANTIGRAVITY_SWARM_REQUESTED_ACTION, ANTIGRAVITY_SWARM_UNAVAILABLE, isAntigravityAgent } from "./antigravity-swarm-refusal.js"; -import { ANTIGRAVITY_SWARM_REQUESTED_ACTION, ANTIGRAVITY_SWARM_UNAVAILABLE, isAntigravityAgent } from "./antigravity-swarm-refusal.js"; +import { ANTIGRAVITY_CLI_QUOTA_SCOPE, ANTIGRAVITY_SWARM_REQUESTED_ACTION, ANTIGRAVITY_SWARM_UNAVAILABLE, isAntigravityAgent } from "./antigravity-swarm-refusal.js"; +import { PROVIDER_QUOTA_SCOPE_CONTEXT_KEY } from "./native-runtime/native-startup-retry.js"; /** Automatic wakes (recovery, sweeps) attempt one swarm request at most this often; the user can always ask again. */ export const ANTIGRAVITY_SWARM_AUTOMATIC_ATTEMPTS = 3; @@ -162,6 +163,25 @@ export async function resolveAntigravitySwarmRun(db: Db, input: { type SwarmDecision = AntigravitySwarmSelection | { refusal: string } | null; +/** + * Read-only, before dispatch (the usage-limit hold runs before selection, which + * needs the prepared workspace): the quota this run would draw on. A run that + * would serve an unfulfilled recorded /swarm request draws on the CLI's quota. + * Selection still decides; a wrong guess here only lets one run reach the + * provider, which then reports its own limit. + */ +export async function antigravitySwarmQuotaScope(db: Db, input: { + companyId: string; issueId: string; runId: string; agent: { id: string; adapterType: string; adapterConfig: unknown }; context: unknown; +}): Promise { + if (!isAntigravityAgent(input.agent)) return null; + const requested = await recordedRequest(db, { ...input, remote: false, planning: false }); + if (!requested) return null; + const [fulfilled] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.status, "succeeded"), + sql`${heartbeatRuns.contextSnapshot}->>'antigravitySwarmCommentId' = ${requested.commentId}`)).limit(1); + return fulfilled ? null : ANTIGRAVITY_CLI_QUOTA_SCOPE; +} + /** The recorded user /swarm request this run serves, if any (before any replacement). */ async function recordedRequest(db: Db, input: Parameters[1]): Promise<{ commentId: string; body: string } | null> { const marked = requestedAntigravitySwarmCommentId(input.context); @@ -216,7 +236,9 @@ async function selectSwarm(tx: Db, input: Parameters>'antigravitySwarmCommentId' = ${commentId}`)); + sql`${heartbeatRuns.contextSnapshot}->>'antigravitySwarmCommentId' = ${commentId}`, + // A wake held for a usage limit never started; its scheduled retry is this request's next attempt, not a Stop. + sql`${heartbeatRuns.errorCode} is distinct from 'provider_limit_wait'`)); if (attempts.some(run => run.status === "succeeded")) return null; if (attempts.some(run => ["queued", "running"].includes(run.status))) return { refusal: "A swarm for this request is already running." }; // The user asked for this attempt: it is the request's first run (the @@ -244,7 +266,8 @@ async function selectSwarm(tx: Db, input: Parameters { + const issueId = readNonEmptyString(parseObject(run.contextSnapshot).issueId); + return issueId ? antigravitySwarmQuotaScope(db, { companyId: run.companyId, issueId, runId: run.id, agent, context: run.contextSnapshot }) : null; + }, }); async function executeRunAttempt( diff --git a/server/src/services/heartbeat/provider-limit-wait.ts b/server/src/services/heartbeat/provider-limit-wait.ts index 88b1be10b87..bbc33cb6e83 100644 --- a/server/src/services/heartbeat/provider-limit-wait.ts +++ b/server/src/services/heartbeat/provider-limit-wait.ts @@ -6,9 +6,15 @@ import { logger } from "../../middleware/logger.js"; import { AI_CONNECTION_POOL_WAIT_RETRY_REASON } from "../../modules/run-dispatch/index.js"; import { aiRuntimeConnectionBindingSchema } from "@paperclipai/shared"; import { - agentHasProviderLimitEvidence, agentProviderLimitCooldown, runProviderLimitCredential, type ProviderLimitCredential, + agentHasProviderLimitEvidence, agentProviderLimitCooldown, runProviderLimitCredential, runProviderQuotaScope, type ProviderLimitCredential, } from "../native-runtime/native-startup-retry.js"; + +/** Plain words for the work a scoped quota serves. */ +function quotaScopeLabel(scope: string): string { + return scope === ANTIGRAVITY_CLI_QUOTA_SCOPE ? "Swarms" : "Some requests for this agent"; +} import { aiConnectionService } from "../ai-connections.js"; +import { ANTIGRAVITY_CLI_QUOTA_SCOPE } from "../antigravity-swarm-refusal.js"; import { parseObject } from "../../adapters/utils.js"; import { logActivity, publishActivity } from "../activity-log.js"; import { notifyScheduledRetryDispatch } from "../run-dispatch-notifications.js"; @@ -36,6 +42,11 @@ export interface ProviderLimitWaitDependencies { * environment (a low-trust task's own environment). */ sshAuthentication?: (agent: Agent, run: HeartbeatRun) => Promise; + /** + * The provider quota the pending run would draw on (PROVIDER_QUOTA_SCOPE_CONTEXT_KEY), + * decided read-only before dispatch; null is the credential's default quota. + */ + providerQuotaScope?: (agent: Agent, run: HeartbeatRun) => Promise; } /** How an SSH environment signs the harness in; null when no SSH environment applies. */ @@ -71,10 +82,12 @@ export function createProviderLimitWait(db: Db, deps: ProviderLimitWaitDependenc // The limit belongs to the credential it was reported on. A run that would // use another account, or whose limited account was revoked, is not held. // Most agents have no live limit, so resolving the account waits for one. + let quotaScope: string | null = null; const cooldown = await agentHasProviderLimitEvidence(db, { companyId: run.companyId, agentId: run.agentId, runId: run.id, now, }).then(async limited => { if (!limited) return null; + quotaScope = deps.providerQuotaScope ? await deps.providerQuotaScope(agent, run) : runProviderQuotaScope(run.contextSnapshot); const ssh = options.sshAuthentication !== undefined ? options.sshAuthentication : deps.sshAuthentication ? await deps.sshAuthentication(agent, run) : null; // Dispatch checks again once the environment, and so the account, is known. @@ -82,6 +95,7 @@ export function createProviderLimitWait(db: Db, deps: ProviderLimitWaitDependenc return agentProviderLimitCooldown(db, { companyId: run.companyId, agentId: run.agentId, runId: run.id, now, credential: await agentProviderLimitCredential(db, agent, run.responsibleUserId, ssh), + quotaScope, }); }).catch((err: unknown) => { // Missing evidence must not stop work; the provider still reports its own limit. @@ -90,7 +104,10 @@ export function createProviderLimitWait(db: Db, deps: ProviderLimitWaitDependenc }); if (!cooldown) return false; const resetAt = cooldown.resetAt.toISOString(); - const message = cooldown.resetReported + const message = quotaScope !== null + // A limit on a separate quota (such as Google's Antigravity CLI for swarms) holds only that kind of work. + ? `${quotaScopeLabel(quotaScope)} are out of quota for now. Paperclip will try again after ${resetAt}; other work on this agent continues.` + : cooldown.resetReported ? `This agent's provider usage limit has a reported reset at ${resetAt}. Work is held; a retry must recheck availability before starting work.` : `This agent's provider usage limit has no reported reset time. Work is held; a retry can recheck availability after ${resetAt}; the limit may still apply then.`; const cancelled = await setRunStatusIfRunning(run.id, "cancelled", { @@ -100,6 +117,7 @@ export function createProviderLimitWait(db: Db, deps: ProviderLimitWaitDependenc providerLimitWait: { resetAt, resetReported: cooldown.resetReported, category: cooldown.category, sourceRunId: cooldown.sourceRunId, grantId: cooldown.grantId, actionUrl: `/agents/${agent.id}/runtime`, + ...(quotaScope !== null ? { quotaScope } : {}), }, cancellation: { source: "control_plane", expected: true, initiator: { type: "system" }, diff --git a/server/src/services/heartbeat/run-completion.test.ts b/server/src/services/heartbeat/run-completion.test.ts index a6e7a8c324e..eb500f25b0a 100644 --- a/server/src/services/heartbeat/run-completion.test.ts +++ b/server/src/services/heartbeat/run-completion.test.ts @@ -1142,6 +1142,28 @@ describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)( expect(f.deps.enqueueWakeup).not.toHaveBeenCalled(); }); + it("gives a swarm the route refused at session.open a plain run error and agent error reason, which clears on the next success", async () => { + const f = await fixture(); + const plain = "Swarm is not available with Gemini 4 Neon (Low) yet, so nothing was changed: choose another model for this agent, such as Gemini 4 Argon, and send /swarm again."; + const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "startup", category: "model_unavailable", + message: plain, retryability: "requires_action" }; + const raw = `PRP command session.open failed: {"commandType":"session.open","result":{"code":"command_execution_failed","message":"failed to start ACPX provider: ACPX sidecar command session.open was rejected (retryable=false, classification=antigravity_swarm_unavailable)","providerFailure":${JSON.stringify(providerFailure)}},"status":"failed"}`; + const [issue] = await db.insert(issues).values({ companyId: f.run.companyId, title: "Swarm", status: "in_progress", assigneeAgentId: f.agent.id }).returning(); + await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issue!.id, contextSnapshot: { issueId: issue!.id } }).where(eq(heartbeatRuns.id, f.run.id)); + await db.insert(nativeRunFinalizations).values({ companyId: f.run.companyId, issueId: issue!.id, runId: f.run.id, + phase: "terminal_failure", failureCode: "antigravity_swarm_unavailable" }); + const statuses = createHeartbeatAgentStatus(db); + f.deps.finalizeAgentStatus.mockImplementation(statuses.finalizeAgentStatus); + await f.completion.failRun(f.failure(Object.assign(new Error(raw), { runnerCommandResult: { result: { providerFailure } } }))); + expect(await read(f.run.id)).toMatchObject({ status: "failed", errorCode: "antigravity_swarm_unavailable", error: plain }); + const [refused] = await db.select().from(agents).where(eq(agents.id, f.agent.id)); + expect(refused!.errorReason ?? null).not.toMatch(/PRP command|[{}]|antigravity_swarm/); + if (refused!.status === "error") expect(refused!.errorReason).toBe(plain); + await statuses.finalizeAgentStatus(f.agent.id, "succeeded"); + const [recovered] = await db.select().from(agents).where(eq(agents.id, f.agent.id)); + expect(recovered).toMatchObject({ status: "idle", errorReason: null }); + }); + it("names a full sandbox disk that the sandbox provider reported during setup", async () => { const f = await fixture(); const refusal = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, diff --git a/server/src/services/heartbeat/run-completion.ts b/server/src/services/heartbeat/run-completion.ts index 1c557b95b71..fb01a7a1851 100644 --- a/server/src/services/heartbeat/run-completion.ts +++ b/server/src/services/heartbeat/run-completion.ts @@ -1345,6 +1345,10 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC // replaying an unfinished turn) nothing retries it, so offer Retry instead. const message = interruptedExactResume ? describeRefusedExactResume(interruptedExactResume, thrownMessage) + // A refused /swarm explains itself in one plain sentence (its provider failure); the + // Runner's command JSON stays in the run's log and recovery history, not in the error. + : failureErrorCode === ANTIGRAVITY_SWARM_UNAVAILABLE && providerFailure?.message.trim() + ? redactFailureText(providerFailure.message.trim()) : !storageUnavailable ? thrownMessage : failureErrorCode === STORAGE_UNAVAILABLE_CODE ? storageUnavailableMessage(err) : storageUnavailableHeldMessage(err); const failureCause = GENERIC_RUN_FAILURE_CODES.has(failureErrorCode) ? thrownFailureCause : null; diff --git a/server/src/services/native-runtime/native-startup-retry.ts b/server/src/services/native-runtime/native-startup-retry.ts index 627d33d049e..d0f2a80240e 100644 --- a/server/src/services/native-runtime/native-startup-retry.ts +++ b/server/src/services/native-runtime/native-startup-retry.ts @@ -43,6 +43,29 @@ export type ProviderLimitCredential = const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +/** + * The run-context key naming the provider quota a run draws on when one + * credential reaches more than one quota (for example Google's Antigravity CLI, + * which bills a different pool than the same account's ordinary route). A limit + * holds only runs on the same credential AND the same quota scope. Absent (all + * rows saved before scopes existed, and every ordinary run) is the credential's + * default quota. + */ +export const PROVIDER_QUOTA_SCOPE_CONTEXT_KEY = "providerQuotaScope"; +const QUOTA_SCOPE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/; + +/** The quota scope a run recorded; null is the credential's default quota. */ +export function runProviderQuotaScope(contextSnapshot: unknown): string | null { + const value = contextSnapshot && typeof contextSnapshot === "object" + ? (contextSnapshot as Record)[PROVIDER_QUOTA_SCOPE_CONTEXT_KEY] : undefined; + return typeof value === "string" && QUOTA_SCOPE_PATTERN.test(value) ? value : null; +} + +function quotaScopeEvidenceFilter(scope: string | null) { + const recorded = sql`${heartbeatRuns.contextSnapshot} ->> ${PROVIDER_QUOTA_SCOPE_CONTEXT_KEY}`; + return scope === null ? sql`${recorded} is null` : sql`${recorded} = ${scope}`; +} + /** The credential a run used, from the account it recorded when it started. */ export function runProviderLimitCredential(contextSnapshot: unknown): ProviderLimitCredential { const grantId = recordedGrantId(contextSnapshot); @@ -122,6 +145,8 @@ export async function agentProviderLimitCooldown(db: Db, input: { failure?: ProviderFailure | null; /** The credential being checked. The caller's failure was reported on it. */ credential: ProviderLimitCredential; + /** The quota scope being checked (see PROVIDER_QUOTA_SCOPE_CONTEXT_KEY); null or absent is the default quota. */ + quotaScope?: string | null; now: Date; }): Promise { if (isProviderQuotaActionRequired({ resultJson: { providerFailure: input.failure } }, input.now)) return null; @@ -144,6 +169,8 @@ export async function agentProviderLimitCooldown(db: Db, input: { gte(heartbeatRuns.startedAt, new Date(now - NATIVE_PROVIDER_LIMIT_WINDOW_MS)), ...(input.runId ? [ne(heartbeatRuns.id, input.runId)] : []), ...credentialEvidenceFilter(input.credential), + // Another quota's limits, and its successes, say nothing about this one. + quotaScopeEvidenceFilter(input.quotaScope ?? null), or( eq(heartbeatRuns.status, "succeeded"), inArray(heartbeatRuns.errorCode, PROVIDER_LIMIT_ERROR_CODES), @@ -215,6 +242,7 @@ export async function planNativeStartupRetry(input: { failure: input.failure, // The failure was reported on the account this run started with. credential: runProviderLimitCredential(run?.contextSnapshot), + quotaScope: runProviderQuotaScope(run?.contextSnapshot), now: input.now, })).then((cooldown) => cooldown?.resetAt ?? null, (error: unknown) => { logger.warn({ err: error, runId: input.binding.runId }, "native provider limit evidence unavailable");