Skip to content

Commit 688b35e

Browse files
committed
fix(agents): recover from invalid compaction summaries
1 parent 121c6c1 commit 688b35e

22 files changed

Lines changed: 1393 additions & 69 deletions

‎extensions/qa-lab/src/providers/mock-openai/mock-openai-contracts.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ import { writeJson } from "../shared/http-json.js";
88
export type ResponsesInputItem = Record<string, unknown>;
99

1010
export type MockOpenAiRequestKind = "agent-initial" | "compaction-summary" | "tool-continuation";
11+
export type MockCompactionSummaryFaultMode =
12+
| "none"
13+
| "empty-output-once"
14+
| "reasoning-only-output-once";
1115

1216
type MockOpenAiRequestOutcome = "success" | "error";
1317

@@ -127,6 +131,7 @@ export type MockOpenAiRequestSnapshot = {
127131
providerVariant: MockOpenAiProviderVariant;
128132
imageInputCount: number;
129133
requestKind: MockOpenAiRequestKind;
134+
compactionSummaryFaultMode: MockCompactionSummaryFaultMode;
130135
outcome: MockOpenAiRequestOutcome;
131136
errorCode?: string;
132137
rawByteLength: number;

‎extensions/qa-lab/src/providers/mock-openai/mock-openai-responses-websocket.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import { startQaMockOpenAiServer } from "./server.js";
66
const cleanups: Array<() => Promise<void>> = [];
77
const QA_COMPACTION_RETRY_PROMPT =
88
"Compaction retry mutating tool check. Current durable context marker: QA-COMPACTION-DURABLE-MARKER. Create compaction-retry-summary.txt.";
9+
const QA_COMPACTION_SUMMARY_INSTRUCTIONS =
10+
"You are a context summarization assistant. Produce a structured summary. Do not continue.";
911

1012
afterEach(async () => {
1113
while (cleanups.length > 0) {
@@ -409,6 +411,49 @@ describe("QA mock OpenAI Responses WebSocket", () => {
409411
]);
410412
});
411413

414+
it.each([
415+
{
416+
faultMode: "empty-output-once",
417+
marker: "QA-COMPACTION-EMPTY-OUTPUT-ONCE-websocket",
418+
recoveredMarker: "QA-COMPACTION-EMPTY-RECOVERED-SUMMARY",
419+
},
420+
{
421+
faultMode: "reasoning-only-output-once",
422+
marker: "QA-COMPACTION-REASONING-ONLY-OUTPUT-ONCE-websocket",
423+
recoveredMarker: "QA-COMPACTION-REASONING-RECOVERED-SUMMARY",
424+
},
425+
] as const)("preserves $faultMode compaction recovery on WebSocket", async (testCase) => {
426+
const server = await startServer();
427+
const socket = await connectResponsesWebSocket(server.baseUrl);
428+
const request = {
429+
type: "response.create",
430+
model: "gpt-5.6-sol",
431+
stream: true,
432+
instructions: QA_COMPACTION_SUMMARY_INSTRUCTIONS,
433+
input: [
434+
{
435+
role: "user",
436+
content: [
437+
{ type: "input_text", text: `<conversation>${testCase.marker}</conversation>` },
438+
],
439+
},
440+
],
441+
};
442+
443+
const first = readCompletedResponse(await collectResponseEvents(socket, request));
444+
expect(JSON.stringify(first.output)).not.toContain(testCase.recoveredMarker);
445+
const recovered = readCompletedResponse(await collectResponseEvents(socket, request));
446+
expect(JSON.stringify(recovered.output)).toContain(testCase.recoveredMarker);
447+
448+
const requests = (await fetch(`${server.baseUrl}/debug/requests`).then((response) =>
449+
response.json(),
450+
)) as Array<Record<string, unknown>>;
451+
expect(requests.map((entry) => entry.compactionSummaryFaultMode)).toEqual([
452+
testCase.faultMode,
453+
"none",
454+
]);
455+
});
456+
412457
it("rejects a response delta whose previous response belongs to another connection", async () => {
413458
const server = await startServer();
414459
const socket = await connectResponsesWebSocket(server.baseUrl);

‎extensions/qa-lab/src/providers/mock-openai/server.test.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ const QA_COMPACTION_RETRY_CODE_MODE_WRITE_RESULT = {
6262
const QA_COMPACTION_RETRY_PROMPT =
6363
"Compaction retry mutating tool check. Current durable context marker: QA-COMPACTION-DURABLE-MARKER. Create compaction-retry-summary.txt.";
6464
const QA_COMPACTION_RETRY_OVERFLOW_PADDING = "x".repeat(300_000);
65+
const QA_COMPACTION_EMPTY_RECOVERY_SUMMARY_MARKER = "QA-COMPACTION-EMPTY-RECOVERED-SUMMARY";
66+
const QA_COMPACTION_REASONING_RECOVERY_SUMMARY_MARKER = "QA-COMPACTION-REASONING-RECOVERED-SUMMARY";
6567
const QA_COMPACTION_SUMMARY_INSTRUCTIONS = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
6668
6769
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;
@@ -2350,6 +2352,150 @@ describe("qa mock openai server", () => {
23502352
expect(summaryRequest.allInputText).toContain("[Chunk 1 - oldest messages]");
23512353
});
23522354

2355+
it.each([
2356+
{
2357+
faultMode: "empty-output-once",
2358+
markerPrefix: "QA-COMPACTION-EMPTY-OUTPUT-ONCE",
2359+
recoveredMarker: QA_COMPACTION_EMPTY_RECOVERY_SUMMARY_MARKER,
2360+
reasoningOnly: false,
2361+
},
2362+
{
2363+
faultMode: "reasoning-only-output-once",
2364+
markerPrefix: "QA-COMPACTION-REASONING-ONLY-OUTPUT-ONCE",
2365+
recoveredMarker: QA_COMPACTION_REASONING_RECOVERY_SUMMARY_MARKER,
2366+
reasoningOnly: true,
2367+
},
2368+
] as const)(
2369+
"injects one coded overflow for $faultMode scenario markers",
2370+
async ({ markerPrefix }) => {
2371+
const server = await startMockServer();
2372+
const body = {
2373+
model: "gpt-5.6-luna",
2374+
instructions: `Runtime: embedded | sessionId=compaction-output-${markerPrefix}`,
2375+
input: [makeUserInput(`${markerPrefix}-http\n${"x".repeat(100_000)}`)],
2376+
};
2377+
2378+
const first = await postNonStreamingResponses(server, body);
2379+
expect(first.status).toBe(400);
2380+
expect(await first.json()).toMatchObject({
2381+
error: { code: "context_length_exceeded" },
2382+
});
2383+
expect((await postNonStreamingResponses(server, body)).status).toBe(200);
2384+
2385+
const requests = requireArray(
2386+
await getJson(server, "/debug/requests"),
2387+
"compaction output overflow requests",
2388+
).map((request) => requireRecord(request, "compaction output overflow request"));
2389+
expect(requests).toHaveLength(2);
2390+
expect(Number(requests[0]?.rawByteLength)).toBeLessThan(256 * 1024);
2391+
expect(requests[0]).toMatchObject({
2392+
requestKind: "agent-initial",
2393+
compactionSummaryFaultMode: "none",
2394+
outcome: "error",
2395+
errorCode: "context_length_exceeded",
2396+
});
2397+
expect(requests[1]).toMatchObject({
2398+
requestKind: "agent-initial",
2399+
compactionSummaryFaultMode: "none",
2400+
outcome: "success",
2401+
});
2402+
},
2403+
);
2404+
2405+
it.each([
2406+
{
2407+
faultMode: "empty-output-once",
2408+
markerPrefix: "QA-COMPACTION-EMPTY-OUTPUT-ONCE",
2409+
recoveredMarker: QA_COMPACTION_EMPTY_RECOVERY_SUMMARY_MARKER,
2410+
reasoningOnly: false,
2411+
},
2412+
{
2413+
faultMode: "reasoning-only-output-once",
2414+
markerPrefix: "QA-COMPACTION-REASONING-ONLY-OUTPUT-ONCE",
2415+
recoveredMarker: QA_COMPACTION_REASONING_RECOVERY_SUMMARY_MARKER,
2416+
reasoningOnly: true,
2417+
},
2418+
] as const)(
2419+
"scopes $faultMode compaction faults to one scenario session",
2420+
async ({ faultMode, markerPrefix, recoveredMarker, reasoningOnly }) => {
2421+
const server = await startMockServer();
2422+
const requestFor = (session: string) => ({
2423+
model: "gpt-5.6-luna",
2424+
instructions: QA_COMPACTION_SUMMARY_INSTRUCTIONS,
2425+
input: `<conversation>\n${markerPrefix}-${session}\nretain current work\n</conversation>\n\nCreate a structured summary.`,
2426+
});
2427+
2428+
const first = await expectOpenAiNonStreamingResponsesJson(server, requestFor("session-a"));
2429+
if (reasoningOnly) {
2430+
expect(JSON.stringify(first)).toContain("reasoning_compaction_summary_fault");
2431+
expect(JSON.stringify(first)).not.toContain(recoveredMarker);
2432+
} else {
2433+
expect(outputText(first)).toBe("");
2434+
}
2435+
const recovered = await expectOpenAiNonStreamingResponsesJson(
2436+
server,
2437+
requestFor("session-a"),
2438+
);
2439+
const recoveredText = outputText(recovered);
2440+
expect(recoveredText).toContain(recoveredMarker);
2441+
expect(recoveredText).toContain(`${markerPrefix}-session-a`);
2442+
expect(recoveredText).toContain("## Decisions");
2443+
expect(recoveredText).toContain("## Open TODOs");
2444+
expect(recoveredText).toContain("## Constraints/Rules");
2445+
expect(recoveredText).toContain("## Pending user asks");
2446+
expect(recoveredText).toContain("## Exact identifiers");
2447+
const independent = await expectOpenAiNonStreamingResponsesJson(
2448+
server,
2449+
requestFor("session-b"),
2450+
);
2451+
if (reasoningOnly) {
2452+
expect(JSON.stringify(independent)).toContain("reasoning_compaction_summary_fault");
2453+
expect(JSON.stringify(independent)).not.toContain(recoveredMarker);
2454+
} else {
2455+
expect(outputText(independent)).toBe("");
2456+
}
2457+
2458+
const requests = requireArray(
2459+
await getJson(server, "/debug/requests"),
2460+
"compaction output fault requests",
2461+
).map((request) => requireRecord(request, "compaction output fault request"));
2462+
expect(requests.map((request) => request.compactionSummaryFaultMode)).toEqual([
2463+
faultMode,
2464+
"none",
2465+
faultMode,
2466+
]);
2467+
expect(requests.every((request) => request.requestKind === "compaction-summary")).toBe(true);
2468+
},
2469+
);
2470+
2471+
it("classifies developer-role compaction instructions before applying a typed fault", async () => {
2472+
const server = await startMockServer();
2473+
const response = await expectOpenAiNonStreamingResponsesJson(server, {
2474+
model: "gpt-5.6-luna",
2475+
input: [
2476+
{
2477+
role: "developer",
2478+
content: [{ type: "input_text", text: QA_COMPACTION_SUMMARY_INSTRUCTIONS }],
2479+
},
2480+
makeUserInput(
2481+
"<conversation>QA-COMPACTION-EMPTY-OUTPUT-ONCE-developer-wire</conversation>",
2482+
),
2483+
],
2484+
});
2485+
2486+
expect(outputText(response)).toBe("");
2487+
const requests = requireArray(
2488+
await getJson(server, "/debug/requests"),
2489+
"developer-role compaction requests",
2490+
).map((request) => requireRecord(request, "developer-role compaction request"));
2491+
expect(requests).toEqual([
2492+
expect.objectContaining({
2493+
requestKind: "compaction-summary",
2494+
compactionSummaryFaultMode: "empty-output-once",
2495+
}),
2496+
]);
2497+
});
2498+
23532499
it("handles staged scalar compaction summaries and promotes the durable merge without state leakage", async () => {
23542500
const server = await startMockServer();
23552501
const genericChunkPayload = await expectOpenAiNonStreamingResponsesJson(server, {

0 commit comments

Comments
 (0)