Skip to content

Commit d204ebe

Browse files
authored
fix(codex): recover replies after compaction failure (#125895)
Preserve completed tool work when native Codex compaction fails, close failed compaction progress, and bypass unrelated model/auth failover before isolated finalization. Fixes #125789.
1 parent 6988551 commit d204ebe

5 files changed

Lines changed: 324 additions & 17 deletions

File tree

‎extensions/codex/src/app-server/event-projector.terminal-errors.test.ts‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ import {
33
registerCodexEventProjectorTestLifecycle,
44
expect,
55
it,
6+
THREAD_ID,
67
TURN_ID,
78
createProjector,
89
buildEmptyToolTelemetry,
10+
createParams,
911
readAttemptTerminal,
1012
expectUsageLimitPromptError,
1113
forCurrentTurn,
@@ -15,6 +17,7 @@ import {
1517
turnCompleted,
1618
turnWithStatus,
1719
pendingCommandStarted,
20+
vi,
1821
} from "./event-projector.test-harness.js";
1922

2023
registerCodexEventProjectorTestLifecycle();
@@ -202,6 +205,7 @@ describe("CodexAppServerEventProjector terminal errors", () => {
202205
{ codexErrorInfo: "serverOverloaded", expected: true },
203206
{ codexErrorInfo: "usageLimitExceeded", expected: false },
204207
{ codexErrorInfo: "unauthorized", expected: false },
208+
{ codexErrorInfo: "other", expected: false },
205209
])(
206210
"projects $codexErrorInfo terminal error recovery eligibility as $expected",
207211
async ({ codexErrorInfo, expected }) => {
@@ -212,9 +216,110 @@ describe("CodexAppServerEventProjector terminal errors", () => {
212216
);
213217

214218
expect(projector.settledTurnFailureFinalizationAllowed).toBe(expected);
219+
expect(
220+
readAttemptTerminal(projector.buildResult(buildEmptyToolTelemetry())).promptErrorSource,
221+
).toBe("prompt");
215222
},
216223
);
217224

225+
it("keeps an active native compaction failure scoped through the failed turn", async () => {
226+
const onAgentEvent = vi.fn();
227+
const onContextCompacted = vi.fn();
228+
const projector = await createProjector(
229+
{ ...(await createParams()), onAgentEvent },
230+
{ onContextCompacted },
231+
);
232+
233+
await projector.handleNotification(
234+
forCurrentTurn("item/started", {
235+
item: { type: "contextCompaction", id: "compact-failed" },
236+
}),
237+
);
238+
await projector.handleNotification(
239+
appServerError({
240+
message: "remote compaction failed",
241+
willRetry: false,
242+
codexErrorInfo: "other",
243+
}),
244+
);
245+
246+
expect(readAttemptTerminal(projector.buildResult(buildEmptyToolTelemetry()))).toMatchObject({
247+
promptError: "remote compaction failed",
248+
promptErrorSource: "compaction",
249+
});
250+
expect(projector.settledTurnFailureFinalizationAllowed).toBe(true);
251+
252+
await projector.handleNotification(
253+
forCurrentTurn("turn/completed", {
254+
turn: {
255+
id: TURN_ID,
256+
status: "failed",
257+
error: { message: "remote compaction failed", codexErrorInfo: "other" },
258+
items: [],
259+
},
260+
}),
261+
);
262+
263+
const result = projector.buildResult(buildEmptyToolTelemetry());
264+
expect(readAttemptTerminal(result)).toMatchObject({
265+
promptError: "remote compaction failed",
266+
promptErrorSource: "compaction",
267+
});
268+
expect(projector.settledTurnFailureFinalizationAllowed).toBe(true);
269+
expect(projector.isCompacting()).toBe(false);
270+
expect(result.itemLifecycle).toEqual({ startedCount: 0, completedCount: 0, activeCount: 0 });
271+
expect(result.compactionCount).toBeUndefined();
272+
expect(onContextCompacted).not.toHaveBeenCalled();
273+
expect(
274+
onAgentEvent.mock.calls
275+
.map(([event]) => event)
276+
.filter((event) => event.stream === "compaction"),
277+
).toEqual([
278+
{
279+
stream: "compaction",
280+
data: {
281+
phase: "start",
282+
backend: "codex-app-server",
283+
threadId: THREAD_ID,
284+
turnId: TURN_ID,
285+
itemId: "compact-failed",
286+
},
287+
},
288+
{
289+
stream: "compaction",
290+
data: {
291+
phase: "end",
292+
backend: "codex-app-server",
293+
completed: false,
294+
threadId: THREAD_ID,
295+
turnId: TURN_ID,
296+
itemId: "compact-failed",
297+
},
298+
},
299+
]);
300+
});
301+
302+
it("keeps other errors prompt-scoped after native compaction completes", async () => {
303+
const projector = await createProjector();
304+
const compaction = { item: { type: "contextCompaction", id: "compact-completed" } };
305+
306+
await projector.handleNotification(forCurrentTurn("item/started", compaction));
307+
await projector.handleNotification(forCurrentTurn("item/completed", compaction));
308+
await projector.handleNotification(
309+
appServerError({
310+
message: "unrelated provider failure",
311+
willRetry: false,
312+
codexErrorInfo: "other",
313+
}),
314+
);
315+
316+
expect(readAttemptTerminal(projector.buildResult(buildEmptyToolTelemetry()))).toMatchObject({
317+
promptError: "unrelated provider failure",
318+
promptErrorSource: "prompt",
319+
});
320+
expect(projector.settledTurnFailureFinalizationAllowed).toBe(false);
321+
});
322+
218323
it("uses Codex rate-limit resets for usage-limit app-server errors", async () => {
219324
const resetsAt = Math.ceil(Date.now() / 1000) + 120;
220325
const projector = await createProjector(undefined, {

‎extensions/codex/src/app-server/event-projector.ts‎

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -301,17 +301,19 @@ export class CodexAppServerEventProjector {
301301
case "rawResponseItem/completed":
302302
await this.handleRawResponseItemCompleted(params);
303303
break;
304-
case "error":
304+
case "error": {
305305
this.responseCompletions.clear();
306306
if (params.willRetry === true) {
307307
break;
308308
}
309+
const codexErrorInfo = isJsonObject(params.error) ? params.error.codexErrorInfo : undefined;
310+
const compactionFailure = codexErrorInfo === "other" && this.isCompacting();
309311
this.settledTurnFailureFinalizationAllowed =
310-
(isJsonObject(params.error) ? params.error.codexErrorInfo : undefined) ===
311-
"serverOverloaded";
312+
codexErrorInfo === "serverOverloaded" || compactionFailure;
312313
this.promptError = this.formatCodexErrorMessage(params) ?? "codex app-server error";
313-
this.promptErrorSource = "prompt";
314+
this.promptErrorSource = compactionFailure ? "compaction" : "prompt";
314315
break;
316+
}
315317
case "thread/compacted":
316318
case "turn/started":
317319
case "turn/diff/updated":
@@ -490,17 +492,7 @@ export class CodexAppServerEventProjector {
490492
channelId: this.params.messageChannel ?? this.params.messageProvider ?? undefined,
491493
},
492494
});
493-
this.emitAgentEvent({
494-
stream: "compaction",
495-
data: {
496-
phase: "end",
497-
backend: "codex-app-server",
498-
completed: true,
499-
threadId: this.threadId,
500-
turnId: this.turnId,
501-
itemId,
502-
},
503-
});
495+
this.emitCompactionEnd(itemId, true);
504496
}
505497
this.toolProgressProjection.recordToolMeta(item);
506498
this.toolProgressProjection.rememberCommandAggregateOutputEcho(item);
@@ -522,8 +514,13 @@ export class CodexAppServerEventProjector {
522514
return;
523515
}
524516
this.completedTurn = turn;
517+
const compactionFailure =
518+
turn.status === "failed" &&
519+
(this.promptErrorSource === "compaction" ||
520+
(turn.error?.codexErrorInfo === "other" && this.isCompacting()));
525521
this.settledTurnFailureFinalizationAllowed =
526-
turn.status === "failed" && turn.error?.codexErrorInfo === "serverOverloaded";
522+
turn.status === "failed" &&
523+
(turn.error?.codexErrorInfo === "serverOverloaded" || compactionFailure);
527524
if (turn.status !== "completed") {
528525
this.responseCompletions.clear();
529526
}
@@ -536,7 +533,17 @@ export class CodexAppServerEventProjector {
536533
this.promptError = usageLimitMessage
537534
? createCodexUsageLimitPromptError(usageLimitMessage)
538535
: (turn.error?.message ?? "codex app-server turn failed");
539-
this.promptErrorSource = "prompt";
536+
this.promptErrorSource = compactionFailure ? "compaction" : "prompt";
537+
}
538+
if (compactionFailure) {
539+
// Codex omits item/completed on failure, so the terminal turn must close
540+
// every active structural compaction for state and stream consumers.
541+
const failedCompactionItemIds = [...this.activeCompactionItemIds];
542+
for (const itemId of failedCompactionItemIds) {
543+
this.activeItemIds.delete(itemId);
544+
this.activeCompactionItemIds.delete(itemId);
545+
this.emitCompactionEnd(itemId, false);
546+
}
540547
}
541548
const turnItems = turn.items ?? [];
542549
// The final snapshot is authoritative when item notifications were omitted.
@@ -574,6 +581,20 @@ export class CodexAppServerEventProjector {
574581
await this.reasoningProjection.maybeEndReasoning();
575582
}
576583

584+
private emitCompactionEnd(itemId: string, completed: boolean): void {
585+
this.emitAgentEvent({
586+
stream: "compaction",
587+
data: {
588+
phase: "end",
589+
backend: "codex-app-server",
590+
completed,
591+
threadId: this.threadId,
592+
turnId: this.turnId,
593+
itemId,
594+
},
595+
});
596+
}
597+
577598
private async emitSnapshotOnlyNativeToolProgress(item: CodexThreadItem): Promise<void> {
578599
if (
579600
!shouldSynthesizeToolProgressForItem(item) ||

‎extensions/codex/src/app-server/run-attempt.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4586,6 +4586,83 @@ describe("runCodexAppServerAttempt", () => {
45864586
}
45874587
},
45884588
);
4589+
it("captures settled tool evidence when an active native compaction fails terminally", async () => {
4590+
const storePath = path.join(tempDir, "settled-compaction-failure.sqlite");
4591+
const sessionId = "session-settled-compaction-failure";
4592+
const sessionFile = `agent:main:${sessionId}`;
4593+
const workspaceDir = path.join(tempDir, "workspace-settled-compaction-failure");
4594+
const harness = createStartedThreadHarness();
4595+
const params = createParams(sessionFile, workspaceDir);
4596+
await attachSqliteSessionTarget(params, storePath, sessionId);
4597+
params.prompt = "Finish the task and report the result.";
4598+
const run = runCodexAppServerAttempt(params);
4599+
await harness.waitForMethod("turn/start");
4600+
await harness.notify(
4601+
itemNotification("item/started", {
4602+
type: "commandExecution",
4603+
id: "tool-settled",
4604+
command: "echo completed-work",
4605+
cwd: workspaceDir,
4606+
status: "inProgress",
4607+
}),
4608+
);
4609+
await harness.notify(
4610+
itemNotification("item/completed", {
4611+
type: "commandExecution",
4612+
id: "tool-settled",
4613+
command: "echo completed-work",
4614+
cwd: workspaceDir,
4615+
status: "completed",
4616+
aggregatedOutput: "completed-work\n",
4617+
exitCode: 0,
4618+
durationMs: 12,
4619+
}),
4620+
);
4621+
await harness.notify(
4622+
itemNotification("item/started", { type: "contextCompaction", id: "compact-failed" }),
4623+
);
4624+
await harness.notify({
4625+
method: "error",
4626+
params: {
4627+
threadId: "thread-1",
4628+
turnId: "turn-1",
4629+
error: {
4630+
message: "remote compaction failed",
4631+
codexErrorInfo: "other",
4632+
additionalDetails: null,
4633+
},
4634+
willRetry: false,
4635+
},
4636+
});
4637+
await harness.notify(
4638+
turnCompleted({
4639+
id: "turn-1",
4640+
status: "failed",
4641+
error: {
4642+
message: "remote compaction failed",
4643+
codexErrorInfo: "other",
4644+
additionalDetails: null,
4645+
},
4646+
}),
4647+
);
4648+
4649+
const result = await run;
4650+
4651+
expect(readAttemptTerminal(result)).toMatchObject({
4652+
promptError: "remote compaction failed",
4653+
promptErrorSource: "compaction",
4654+
});
4655+
expect(result.itemLifecycle).toEqual({ startedCount: 1, completedCount: 1, activeCount: 0 });
4656+
expect(result.settledTurnFinalizationContext).toMatchObject({
4657+
source: "openclaw-transcript",
4658+
messages: [
4659+
expect.objectContaining({ role: "user" }),
4660+
expect.objectContaining({ role: "assistant" }),
4661+
expect.objectContaining({ role: "toolResult", toolCallId: "tool-settled" }),
4662+
],
4663+
});
4664+
expect(Object.isFrozen(result.settledTurnFinalizationContext?.messages)).toBe(true);
4665+
});
45894666
it("preserves every command failure from official app-server events", async () => {
45904667
const sessionFile = path.join(tempDir, "session-multi-command-failure.jsonl");
45914668
const workspaceDir = path.join(tempDir, "workspace-multi-command-failure");

0 commit comments

Comments
 (0)