Skip to content

Commit f3f2732

Browse files
committed
fix(agents): preserve retry budget for tool progress
1 parent 2523566 commit f3f2732

6 files changed

Lines changed: 171 additions & 10 deletions

File tree

‎src/agents/embedded-agent-runner/run-loop.ts‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,12 @@ import {
4444
DEFAULT_REASONING_ONLY_RETRY_LIMIT,
4545
} from "./run/incomplete-turn.js";
4646
import { measureEmbeddedAgentPreparation } from "./run/preparation-timing.js";
47+
import {
48+
beginRunAttempt,
49+
createRunRetryBudget,
50+
isRunRetryBudgetExhausted,
51+
recordRunRetry,
52+
} from "./run/retry-budget.js";
4753
import { handleRetryLimitExhaustion } from "./run/retry-limit.js";
4854
import { prepareEmbeddedRunRuntime } from "./run/runtime-preparation.js";
4955
import { createEmbeddedRunSessionPromptState } from "./run/session-prompt-state.js";
@@ -174,14 +180,14 @@ export async function runPreparedEmbeddedLoop(
174180
const maxReasoningOnlyRetryAttempts = DEFAULT_REASONING_ONLY_RETRY_LIMIT;
175181
const maxEmptyResponseRetryAttempts = DEFAULT_EMPTY_RESPONSE_RETRY_LIMIT;
176182

177-
const MAX_RUN_LOOP_ITERATIONS = resolveMaxRunRetryIterations(profileCandidates.length);
183+
const MAX_RUN_RETRY_ATTEMPTS = resolveMaxRunRetryIterations(profileCandidates.length);
184+
const runRetryBudget = createRunRetryBudget(MAX_RUN_RETRY_ATTEMPTS);
178185
const contextRecoveryState = createEmbeddedRunContextRecoveryState();
179186
let bootstrapPromptWarningSignaturesSeen =
180187
params.bootstrapPromptWarningSignaturesSeen ??
181188
(params.bootstrapPromptWarningSignature ? [params.bootstrapPromptWarningSignature] : []);
182189
const usageAccumulator = createUsageAccumulator();
183190
let lastRunPromptUsage: ReturnType<typeof normalizeUsage> | undefined;
184-
let runLoopIterations = 0;
185191
let overloadProfileRotations = 0;
186192
const terminalRetryState = createEmbeddedRunTerminalRetryState();
187193
let sameModelIdleTimeoutRetries = 0;
@@ -285,14 +291,14 @@ export async function runPreparedEmbeddedLoop(
285291
let latestMcpAppChannelView: McpAppChannelView | undefined;
286292
while (true) {
287293
refreshPreparedRuntimeSnapshot();
288-
if (runLoopIterations >= MAX_RUN_LOOP_ITERATIONS) {
294+
if (isRunRetryBudgetExhausted(runRetryBudget)) {
289295
const message =
290-
`Exceeded retry limit after ${runLoopIterations} attempts ` +
291-
`(max=${MAX_RUN_LOOP_ITERATIONS}).`;
296+
`Exceeded retry limit after ${runRetryBudget.attemptsDispatched} attempts ` +
297+
`(counted attempts=${runRetryBudget.attemptsCounted}, max=${runRetryBudget.maxAttempts}).`;
292298
log.error(
293299
`[run-retry-limit] sessionKey=${params.sessionKey ?? params.sessionId} ` +
294-
`provider=${provider}/${modelId} attempts=${runLoopIterations} ` +
295-
`maxAttempts=${MAX_RUN_LOOP_ITERATIONS}`,
300+
`provider=${provider}/${modelId} attempts=${runRetryBudget.attemptsDispatched} ` +
301+
`countedAttempts=${runRetryBudget.attemptsCounted} maxAttempts=${runRetryBudget.maxAttempts}`,
296302
);
297303
const retryLimitDecision = resolveRunFailoverDecision({
298304
stage: "retry_limit",
@@ -319,14 +325,14 @@ export async function runPreparedEmbeddedLoop(
319325
livenessState: "blocked",
320326
});
321327
}
322-
runLoopIterations += 1;
328+
beginRunAttempt(runRetryBudget);
323329
const runtimeAuthRetry: boolean = authRetryPending;
324330
authRetryPending = false;
325331
attemptedThinking.add(thinkLevel);
326332
const codexAppServerRecoveryRetryAvailable = hasCodexAppServerRecoveryRetryBudget({
327333
alreadyRetried: codexAppServerRecoveryRetries > 0,
328-
runLoopIterations,
329-
maxRunLoopIterations: MAX_RUN_LOOP_ITERATIONS,
334+
runLoopIterations: runRetryBudget.attemptsCounted,
335+
maxRunLoopIterations: runRetryBudget.maxAttempts,
330336
});
331337
const dispatch = await prepareAndDispatchEmbeddedRunAttempt({
332338
runInput: input,
@@ -382,6 +388,7 @@ export async function runPreparedEmbeddedLoop(
382388
normalizedAttempt.bootstrapPromptWarningSignaturesSeen;
383389
lastRunPromptUsage = normalizedAttempt.lastRunPromptUsage;
384390
accumulatedReplayState = normalizedAttempt.replayState;
391+
recordRunRetry(runRetryBudget, normalizedAttempt.retryKind);
385392
continue;
386393
}
387394
bootstrapPromptWarningSignaturesSeen = normalizedAttempt.bootstrapPromptWarningSignaturesSeen;

‎src/agents/embedded-agent-runner/run.attempt-normalization.direct.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,10 @@ describe("normalizeEmbeddedRunAttempt", () => {
138138
);
139139

140140
expect(result.action).toBe("retry");
141+
if (result.action !== "retry") {
142+
throw new Error(`expected retry, got ${result.action}`);
143+
}
144+
expect(result.retryKind).toBe("recovery");
141145
expect(state.continueFromCurrentTranscript).not.toHaveBeenCalled();
142146
});
143147

@@ -157,9 +161,52 @@ describe("normalizeEmbeddedRunAttempt", () => {
157161
);
158162

159163
expect(result.action).toBe("retry");
164+
if (result.action !== "retry") {
165+
throw new Error(`expected retry, got ${result.action}`);
166+
}
167+
expect(result.retryKind).toBe("recovery");
160168
expect(state.continueFromCurrentTranscript).toHaveBeenCalledOnce();
161169
});
162170

171+
it("marks a successful no-op mid-turn retry as a progress continuation", async () => {
172+
const state = makePromptState();
173+
const attempt = makeAttempt({
174+
route: "truncate_tool_results_only",
175+
source: "mid-turn",
176+
handled: true,
177+
truncatedCount: 0,
178+
});
179+
attempt.toolMetas = [{ toolName: "read", isError: false }];
180+
181+
const result = await normalizeEmbeddedRunAttempt(makeNormalizationInput(attempt, state));
182+
183+
expect(result.action).toBe("retry");
184+
if (result.action !== "retry") {
185+
throw new Error(`expected retry, got ${result.action}`);
186+
}
187+
expect(result.retryKind).toBe("progress_continuation");
188+
expect(state.continueFromCurrentTranscript).toHaveBeenCalledOnce();
189+
});
190+
191+
it("keeps a failed no-op mid-turn retry in the recovery budget", async () => {
192+
const state = makePromptState();
193+
const attempt = makeAttempt({
194+
route: "truncate_tool_results_only",
195+
source: "mid-turn",
196+
handled: true,
197+
truncatedCount: 0,
198+
});
199+
attempt.toolMetas = [{ toolName: "read", isError: true }];
200+
201+
const result = await normalizeEmbeddedRunAttempt(makeNormalizationInput(attempt, state));
202+
203+
expect(result.action).toBe("retry");
204+
if (result.action !== "retry") {
205+
throw new Error(`expected retry, got ${result.action}`);
206+
}
207+
expect(result.retryKind).toBe("recovery");
208+
});
209+
163210
it("keeps replay state unsafe after a later clean attempt", async () => {
164211
const state = makePromptState();
165212
const dirty = await normalizeEmbeddedRunAttempt(

‎src/agents/embedded-agent-runner/run.midturn-precheck-retry.test-support.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ describe("runEmbeddedAgent mid-turn precheck retry", () => {
5959
handled: true,
6060
truncatedCount: 0,
6161
},
62+
toolMetas: [{ toolName: "read", meta: "step=1" }],
6263
latestMcpAppChannelView: { viewId: "view-before-retry" },
6364
}),
6465
)

‎src/agents/embedded-agent-runner/run/attempt-normalization.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
type createIdleTimeoutBreakerState,
2828
} from "./idle-timeout-breaker.js";
2929
import { resolveReplayInvalidFlag } from "./incomplete-turn.js";
30+
import { resolveRunRetryKind, type RunRetryKind } from "./retry-budget.js";
3031
import { handleRetryLimitExhaustion } from "./retry-limit.js";
3132
import type { dispatchEmbeddedRunAttempt } from "./run-attempt-dispatch.js";
3233
import {
@@ -65,6 +66,7 @@ export async function normalizeEmbeddedRunAttempt(input: {
6566
| { action: "complete"; result: EmbeddedAgentRunResult }
6667
| {
6768
action: "retry";
69+
retryKind: RunRetryKind;
6870
bootstrapPromptWarningSignaturesSeen: string[];
6971
lastRunPromptUsage: ReturnType<typeof normalizeUsage> | undefined;
7072
replayState: ReplayState;
@@ -259,8 +261,14 @@ export async function normalizeEmbeddedRunAttempt(input: {
259261
if (retryingFromTranscript) {
260262
sessionPromptState.continueFromCurrentTranscript();
261263
}
264+
const retryKind = resolveRunRetryKind({
265+
preflightRecovery,
266+
retryingFromTranscript,
267+
toolMetas: attempt.toolMetas,
268+
});
262269
return {
263270
action: "retry",
271+
retryKind,
264272
bootstrapPromptWarningSignaturesSeen,
265273
lastRunPromptUsage,
266274
replayState,
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import { describe, expect, it } from "vitest";
2+
import {
3+
beginRunAttempt,
4+
createRunRetryBudget,
5+
isRunRetryBudgetExhausted,
6+
recordRunRetry,
7+
resolveRunRetryKind,
8+
} from "./retry-budget.js";
9+
10+
describe("run retry budget", () => {
11+
it("allows more than 32 progressing continuations", () => {
12+
const budget = createRunRetryBudget(32);
13+
14+
for (let step = 0; step < 33; step += 1) {
15+
beginRunAttempt(budget);
16+
recordRunRetry(
17+
budget,
18+
resolveRunRetryKind({
19+
preflightRecovery: {
20+
route: "truncate_tool_results_only",
21+
truncatedCount: 0,
22+
},
23+
retryingFromTranscript: true,
24+
toolMetas: [{ toolName: "read", meta: `step=${step}`, isError: false }],
25+
}),
26+
);
27+
}
28+
29+
expect(budget).toEqual({ attemptsDispatched: 33, attemptsCounted: 0, maxAttempts: 32 });
30+
expect(isRunRetryBudgetExhausted(budget)).toBe(false);
31+
});
32+
33+
it("still stops 32 retries that make no progress", () => {
34+
const budget = createRunRetryBudget(32);
35+
36+
for (let retry = 0; retry < 32; retry += 1) {
37+
beginRunAttempt(budget);
38+
recordRunRetry(budget, "recovery");
39+
}
40+
41+
expect(isRunRetryBudgetExhausted(budget)).toBe(true);
42+
});
43+
44+
it("does not erase retries used before a progress continuation", () => {
45+
const budget = createRunRetryBudget(32);
46+
for (let retry = 0; retry < 31; retry += 1) {
47+
beginRunAttempt(budget);
48+
recordRunRetry(budget, "recovery");
49+
}
50+
51+
beginRunAttempt(budget);
52+
recordRunRetry(budget, "progress_continuation");
53+
expect(budget.attemptsCounted).toBe(31);
54+
55+
beginRunAttempt(budget);
56+
recordRunRetry(budget, "recovery");
57+
expect(isRunRetryBudgetExhausted(budget)).toBe(true);
58+
});
59+
});
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
export type RunRetryKind = "progress_continuation" | "recovery";
2+
3+
type RunRetryBudget = {
4+
attemptsDispatched: number;
5+
attemptsCounted: number;
6+
maxAttempts: number;
7+
};
8+
9+
export function createRunRetryBudget(maxAttempts: number): RunRetryBudget {
10+
return { attemptsDispatched: 0, attemptsCounted: 0, maxAttempts };
11+
}
12+
13+
export function isRunRetryBudgetExhausted(budget: RunRetryBudget): boolean {
14+
return budget.attemptsCounted >= budget.maxAttempts;
15+
}
16+
17+
export function beginRunAttempt(budget: RunRetryBudget): void {
18+
budget.attemptsDispatched += 1;
19+
budget.attemptsCounted += 1;
20+
}
21+
22+
export function resolveRunRetryKind(params: {
23+
preflightRecovery: { route: string; truncatedCount?: number };
24+
retryingFromTranscript: boolean;
25+
toolMetas: Array<{ isError?: boolean; meta?: string; toolName: string }>;
26+
}): RunRetryKind {
27+
return params.retryingFromTranscript &&
28+
params.preflightRecovery.route === "truncate_tool_results_only" &&
29+
params.preflightRecovery.truncatedCount === 0 &&
30+
params.toolMetas.some((tool) => tool.isError !== true)
31+
? "progress_continuation"
32+
: "recovery";
33+
}
34+
35+
export function recordRunRetry(budget: RunRetryBudget, kind: RunRetryKind): void {
36+
if (kind === "progress_continuation") {
37+
budget.attemptsCounted = Math.max(0, budget.attemptsCounted - 1);
38+
}
39+
}

0 commit comments

Comments
 (0)