Skip to content

Commit 6d2644a

Browse files
ruel225obviyus
andauthored
fix(agents): separate retry count from API key position (#115507)
API-key rotation tracked retry count and key position separately but exposed key position through the callback field named `attempt`. Callbacks now receive the one-based per-key execution in `attempt` and the zero-based key position in `apiKeyIndex`, while rotation order and same-key retry behavior stay unchanged. Fixes #102938. Co-authored-by: ruel225 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent abf412a commit 6d2644a

2 files changed

Lines changed: 49 additions & 8 deletions

File tree

‎src/agents/api-key-rotation.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,4 +350,45 @@ describe("executeWithApiKeyRotation", () => {
350350
}),
351351
);
352352
});
353+
354+
it("reports retry count and key position across same-key retries and rotation", async () => {
355+
const retryCallbacks: Array<{ attempt: number; apiKeyIndex: number }> = [];
356+
const rotationCallbacks: Array<{ attempt: number; apiKeyIndex: number }> = [];
357+
const executedKeys: string[] = [];
358+
const sleep = vi.fn(async () => undefined);
359+
const transientError = Object.assign(new Error("controlled transient"), {
360+
code: "ECONNRESET",
361+
});
362+
363+
await expect(
364+
executeWithApiKeyRotation({
365+
provider: "openai",
366+
apiKeys: ["key-1", "key-2"],
367+
transientRetry: { attempts: 2, baseDelayMs: 0, maxDelayMs: 0, sleep },
368+
execute: async (apiKey) => {
369+
executedKeys.push(apiKey);
370+
if (executedKeys.length < 4) {
371+
throw transientError;
372+
}
373+
return "ok";
374+
},
375+
shouldRetry: ({ attempt, apiKeyIndex }) => {
376+
retryCallbacks.push({ attempt, apiKeyIndex });
377+
return retryCallbacks.length === 2;
378+
},
379+
onRetry: ({ attempt, apiKeyIndex }) => {
380+
rotationCallbacks.push({ attempt, apiKeyIndex });
381+
},
382+
}),
383+
).resolves.toBe("ok");
384+
385+
expect(executedKeys).toEqual(["key-1", "key-1", "key-2", "key-2"]);
386+
expect(sleep).toHaveBeenCalledTimes(2);
387+
expect(retryCallbacks).toEqual([
388+
{ attempt: 1, apiKeyIndex: 0 },
389+
{ attempt: 2, apiKeyIndex: 0 },
390+
{ attempt: 1, apiKeyIndex: 1 },
391+
]);
392+
expect(rotationCallbacks).toEqual([{ attempt: 2, apiKeyIndex: 0 }]);
393+
});
353394
});

‎src/agents/api-key-rotation.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ import { collectProviderApiKeys, isApiKeyRateLimitError } from "./live-auth-keys
1919
type ApiKeyRetryParams = {
2020
apiKey: string;
2121
error: unknown;
22-
attempt: number;
22+
attempt: number; // One-based execution count for the current key.
23+
apiKeyIndex: number; // Zero-based position of the current key.
2324
};
2425

2526
type ExecuteWithApiKeyRotationOptions<T> = {
@@ -59,25 +60,24 @@ export async function executeWithApiKeyRotation<T>(
5960
const transientRetry = resolveTransientProviderRetryOptions(params.transientRetry);
6061
keyLoop: for (const [apiKeyIndex, apiKey] of keys.entries()) {
6162
const maxOperationAttempts = resolveTransientProviderAttempts(transientRetry);
62-
for (let attemptNumber = 1; attemptNumber <= maxOperationAttempts; attemptNumber += 1) {
63+
for (let attempt = 1; attempt <= maxOperationAttempts; attempt += 1) {
6364
transientRetry?.signal?.throwIfAborted();
6465
try {
6566
return await params.execute(apiKey);
6667
} catch (error) {
6768
transientRetry?.signal?.throwIfAborted();
6869
lastError = error;
6970
const message = formatErrorMessage(error);
70-
const rotateKey = params.shouldRetry
71-
? params.shouldRetry({ apiKey, error, attempt: apiKeyIndex, message })
72-
: isApiKeyRateLimitError(message);
71+
const retry = { apiKey, error, attempt, apiKeyIndex, message };
72+
const rotateKey = params.shouldRetry?.(retry) ?? isApiKeyRateLimitError(message);
7373

7474
if (rotateKey) {
7575
// A rotation signal consumes the current key and moves to the next key
7676
// without running same-key transient retry logic.
7777
if (apiKeyIndex + 1 >= keys.length) {
7878
break;
7979
}
80-
params.onRetry?.({ apiKey, error, attempt: apiKeyIndex, message });
80+
params.onRetry?.(retry);
8181
break;
8282
}
8383

@@ -89,14 +89,14 @@ export async function executeWithApiKeyRotation<T>(
8989
message,
9090
provider: params.provider,
9191
apiKeyIndex,
92-
attemptNumber,
92+
attemptNumber: attempt,
9393
maxAttempts: maxOperationAttempts,
9494
})
9595
) {
9696
break keyLoop;
9797
}
9898

99-
const delayMs = resolveTransientProviderDelayMs(transientRetry, attemptNumber);
99+
const delayMs = resolveTransientProviderDelayMs(transientRetry, attempt);
100100
// Same-key transient retries are bounded by provider policy and keep the
101101
// current key stable so auth rotation only handles key-specific failures.
102102
const sleep = transientRetry.sleep ?? sleepWithAbort;

0 commit comments

Comments
 (0)