Skip to content

Commit a6951d2

Browse files
fix(llm-retry): address code review comments
- Fix P1: Make unit capture optional in regex to handle messages without explicit units (defaults to seconds) - Fix P2: Reorder error checks - check status codes first, then only check timeout/message when not 4xx - Fix P2: Add comprehensive JSDoc comments for isRetryableLlmError and extractRetryAfterMs - Fix P2: Simplify type-safe prompt wrapper using Parameters<> and typeof
1 parent bb24a1a commit a6951d2

3 files changed

Lines changed: 67 additions & 25 deletions

File tree

‎src/agents/pi-embedded-runner/llm-retry.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,4 +212,19 @@ describe("extractRetryAfterMs", () => {
212212
expect(extractRetryAfterMs({ message: "retry in 5 seconds" })).toBe(5000);
213213
expect(extractRetryAfterMs({ message: "reset after 10 ms" })).toBe(10);
214214
});
215+
216+
it("handles messages without explicit unit (defaults to seconds)", () => {
217+
expect(extractRetryAfterMs({ message: "retry in 5" })).toBe(5000);
218+
expect(extractRetryAfterMs({ message: "reset after 10" })).toBe(10000);
219+
expect(extractRetryAfterMs({ message: "retry in 2.5" })).toBe(2500);
220+
});
221+
222+
it("handles optional unit in regex correctly", () => {
223+
// When unit is omitted, default to seconds (multiply by 1000)
224+
expect(extractRetryAfterMs({ message: "retry in 3" })).toBe(3000);
225+
// When unit is "ms", don't multiply
226+
expect(extractRetryAfterMs({ message: "retry in 3ms" })).toBe(3);
227+
// When unit is "s", multiply by 1000
228+
expect(extractRetryAfterMs({ message: "retry in 3s" })).toBe(3000);
229+
});
215230
});

‎src/agents/pi-embedded-runner/llm-retry.ts‎

Lines changed: 49 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,19 @@ const DEFAULT_RETRY_CONFIG = {
3737

3838
/**
3939
* Check if an error is retryable for LLM calls.
40+
*
41+
* @remarks
42+
* This function checks the error's HTTP status code, error code, and message to determine
43+
* whether it should be retried. The logic is:
44+
* - Do not retry on client errors (4xx) except 429 (rate limit)
45+
* - Do not retry on billing errors (402)
46+
* - Retry on rate limit (429)
47+
* - Retry on server errors (5xx)
48+
* - Retry on network errors (ETIMEDOUT, ESOCKETTIMEDOUT, ECONNRESET, ECONNABORTED)
49+
* - Retry on timeout errors (only when not a 4xx status code)
50+
*
51+
* @param err - The error to check, which may be an object with status, statusCode, code, or message properties.
52+
* @returns `true` if the error is retryable, `false` otherwise.
4053
*/
4154
export function isRetryableLlmError(err: unknown): boolean {
4255
if (!err) {
@@ -47,35 +60,41 @@ export function isRetryableLlmError(err: unknown): boolean {
4760
const status = errorObj.status ?? errorObj.statusCode;
4861
const message = errorObj.message ?? "";
4962

50-
// Retry on rate limit (429)
51-
if (status === 429) {
52-
return true;
63+
// Check status codes first (more reliable than message parsing)
64+
// Do not retry on client errors (400, 401, 403, 404, 408)
65+
if (status === 400 || status === 401 || status === 403 || status === 404 || status === 408) {
66+
return false;
5367
}
5468

55-
// Retry on server errors (500, 502, 503, 504)
56-
if (status === 500 || status === 502 || status === 503 || status === 504) {
57-
return true;
69+
// Do not retry on billing errors (402)
70+
if (status === 402) {
71+
return false;
5872
}
5973

60-
// Retry on network errors
61-
const code = (errorObj.code ?? "").toUpperCase();
62-
if (["ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNRESET", "ECONNABORTED"].includes(code)) {
74+
// Retry on rate limit (429)
75+
if (status === 429) {
6376
return true;
6477
}
6578

66-
// Retry on timeout errors
67-
if (/timeout|timed out|deadline exceeded|deadline_exceeded/i.test(message)) {
79+
// Retry on server errors (500, 502, 503, 504)
80+
if (status === 500 || status === 502 || status === 503 || status === 504) {
6881
return true;
6982
}
7083

71-
// Do not retry on client errors (400, 401, 403, 404)
72-
if (status === 400 || status === 401 || status === 403 || status === 404) {
73-
return false;
74-
}
84+
// Only check timeout message if there's no 4xx status code
85+
// (timeout messages in 4xx responses indicate client-side timeouts that shouldn't be retried)
86+
const is4xx = status !== undefined && status >= 400 && status < 500;
87+
if (!is4xx) {
88+
// Retry on timeout errors (only for non-4xx status codes)
89+
if (/timeout|timed out|deadline exceeded|deadline_exceeded/i.test(message)) {
90+
return true;
91+
}
7592

76-
// Do not retry on billing errors (402)
77-
if (status === 402) {
78-
return false;
93+
// Retry on network errors
94+
const code = (errorObj.code ?? "").toUpperCase();
95+
if (["ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNRESET", "ECONNABORTED"].includes(code)) {
96+
return true;
97+
}
7998
}
8099

81100
// Default: do not retry unknown errors
@@ -84,6 +103,16 @@ export function isRetryableLlmError(err: unknown): boolean {
84103

85104
/**
86105
* Extract retry-after delay from error response headers or body.
106+
*
107+
* @remarks
108+
* This function checks the error's headers and message for retry delay hints:
109+
* - `Retry-After` header (RFC 7231, in seconds)
110+
* - `x-ratelimit-reset` header (Unix timestamp, converted to relative ms)
111+
* - `x-ratelimit-reset-after` header (seconds)
112+
* - Message patterns like "retry in 5s" or "reset after 100ms"
113+
*
114+
* @param err - The error to check, which may have headers and/or message properties.
115+
* @returns The retry delay in milliseconds, or `undefined` if no delay is found.
87116
*/
88117
export function extractRetryAfterMs(err: unknown): number | undefined {
89118
if (!err || typeof err !== "object") {
@@ -127,7 +156,7 @@ export function extractRetryAfterMs(err: unknown): number | undefined {
127156
// Check error message for retry delay hints
128157
const message = errorObj.message ?? "";
129158
const retryInMatch = message.match(
130-
/retry\s+in\s+([0-9.]+)\s*(ms|milliseconds?|seconds?|secs?|s)/i,
159+
/retry\s+in\s+([0-9.]+)\s*(ms|milliseconds?|seconds?|secs?|s)?/i,
131160
);
132161
if (retryInMatch?.[1]) {
133162
const value = parseFloat(retryInMatch[1]);
@@ -138,7 +167,7 @@ export function extractRetryAfterMs(err: unknown): number | undefined {
138167
}
139168

140169
const resetAfterMatch = message.match(
141-
/reset\s+after\s+([0-9.]+)\s*(ms|milliseconds?|seconds?|secs?|s)/i,
170+
/reset\s+after\s+([0-9.]+)\s*(ms|milliseconds?|seconds?|secs?|s)?/i,
142171
);
143172
if (resetAfterMatch?.[1]) {
144173
const value = parseFloat(resetAfterMatch[1]);

‎src/agents/pi-embedded-runner/run/attempt.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1382,18 +1382,16 @@ export async function runEmbeddedAttempt(
13821382
}
13831383

13841384
// Wrap prompt method with LLM retry logic
1385-
// Use type-safe wrapper to preserve the original signature
13861385
const originalPrompt = activeSession.prompt.bind(activeSession);
1387-
const promptWrapper: typeof activeSession.prompt = (prompt, options) => {
1388-
return withLlmRetry(() => originalPrompt(prompt, options), {
1386+
activeSession.prompt = (async (...args: Parameters<typeof originalPrompt>) => {
1387+
return withLlmRetry(() => originalPrompt(...args), {
13891388
attempts: 8,
13901389
minDelayMs: 1000,
13911390
maxDelayMs: 32000,
13921391
jitter: 0.1,
13931392
signal: runAbortController.signal,
13941393
});
1395-
};
1396-
activeSession.prompt = promptWrapper;
1394+
}) as typeof originalPrompt;
13971395

13981396
try {
13991397
const prior = await sanitizeSessionHistory({

0 commit comments

Comments
 (0)