Skip to content

Commit 6124d47

Browse files
authored
fix(compaction): summarize the prepared window and always restore audited identifiers (#129423)
* fix(compaction): restore omitted source identifiers * fix: log ChatGPT stream termination reasons * fix(compaction): summarize the prepared window and always restore audited identifiers Two safeguard defects made auto-compaction fail closed on tool-heavy sessions: 1. When the prepared window held only tool calls/results, the safeguard replaced it with sessionManager.getBranch() — the whole branch from root. Since #112988 made /new a reset entry inside the same transcript, that branch spans every reset and prior compaction (3,565 messages / 5.2 MB on the reporting session), so one compaction became dozens of sequential model calls until the 900s watchdog fired ("Compaction timed out"). The #78390 reason for that fallback (preparation omitting custom messages) is handled by core projectSessionEntryMessage now. Summarize only the prepared window; decide "nothing to summarize" from the boundary-scoped context (buildSessionContext), never the raw branch. Delete the fallback and its sessions_send replay sanitizers, which only existed for it. 2. #122824 moved the identifier oracle to the messages before the recent-turns split, so audited identifiers can live only in preserved turns that are capped at 600 chars/message and 8K per section. The deterministic restore added in #128968 ran only when the artifact exceeded 16K chars; an under-budget body that omits an identifier still failed the audit (missing_identifiers -> guard_blocked). Run the retention plan whenever a strict identifier is missing from the body, and only emit the truncation marker when body text was actually trimmed. * fix(compaction): fund audit sections first and cap the identifier list The retention plan protected the model-written "## Pending user asks" and "## Exact identifiers" sections verbatim. Each re-distill fed the previous summary back, so the identifier list only grew: on the reporting session it was 13,568 of a 13,953-char summary, every other section an empty heading, and the next compaction cancelled with "required quality facts exceed finalized artifact budget" because the protected content alone passed the 16K cap. Protect only what the audit requires (headings, bounded latest-ask context, the audited identifiers). Fund the two audit-bearing sections first so an oversized earlier section cannot starve them, but cap each at 25% of the content budget; the remainder is split across decisions, TODOs, and constraints. * fix(ai): log only structured ChatGPT stream termination facts projectProviderError keeps provider message/body text after credential redaction, so logging errorMessage could persist prompt- or response-derived content. Log timing, stop classification, the error class name, and the projection's structured errorCode/errorType instead, and cover a provider failure whose message must not reach the transport log. * fix(ai): classify ChatGPT stream termination locally Provider error code/type fields are provider-controlled text, so the transport warning logs a fixed local failure category (timeout, caller-abort, provider-failure, transport) plus timing instead. The failed-response test feeds hostile code/type/message values and asserts none reach the log. * fix(compaction): recover omitted conversation from the boundary-scoped range Replace the deleted whole-branch fallback with the bounded safety net it was meant to be: when the prepared window holds no real conversation, project the branch entries the preparation covered — after the last reset/compaction boundary, before firstKeptEntryId — through the core context builder and summarize that range if it contains conversation the preparation dropped. It can never reach behind a boundary, so it cannot re-read the whole session. * fix(compaction): make the audit-section cap hard even when the summary fits Two holes let the identifier snowball survive the 25% share cap: a summary that still fit the 16K budget skipped the retention plan entirely, so a 13.9K identifier dump was fed unchanged into the next re-distill; and the surplus loop handed unused budget back to the protected sections whenever the optional sections were empty — exactly the degraded shape in production. Rebuild whenever an audit section exceeds its cap, and return surplus to the optional sections only. Also classify a direct non-OK HTTP reply (CodexApiError) as a provider failure in the stream-termination diagnostic, with a direct-400 test that keeps provider text out of the log. --------- Co-authored-by: VACInc <[email protected]>
1 parent f1c60c7 commit 6124d47

6 files changed

Lines changed: 644 additions & 657 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1667,7 +1667,7 @@ src/agents/agent-bundle-mcp-runtime-shared.ts 2
16671667
src/agents/agent-bundle-mcp-runtime.ts 9
16681668
src/agents/agent-command-restart-recovery.ts 3
16691669
src/agents/agent-command.ts 1
1670-
src/agents/agent-hooks/compaction-safeguard.ts 19
1670+
src/agents/agent-hooks/compaction-safeguard.ts 14
16711671
src/agents/agent-model-discovery.ts 5
16721672
src/agents/agent-project-settings-snapshot.ts 5
16731673
src/agents/agent-run-terminal-delivery.ts 1

‎packages/ai/src/providers/openai-chatgpt-responses-streaming.test.ts‎

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,80 @@ describe("OpenAI ChatGPT Responses inference streaming", () => {
262262
expect(fetchMock).not.toHaveBeenCalled();
263263
});
264264

265+
it("logs the caller abort reason with bounded ChatGPT transport metadata", async () => {
266+
const logWarn = vi.fn();
267+
configureAiTransportHost({ logWarn });
268+
const controller = new AbortController();
269+
class AbortedWebSocket extends EventTarget {
270+
constructor() {
271+
super();
272+
queueMicrotask(() => this.dispatchEvent(new Event("open")));
273+
}
274+
275+
send(): void {
276+
controller.abort(new Error("Compaction timed out"));
277+
}
278+
279+
close(): void {}
280+
}
281+
vi.stubGlobal("WebSocket", AbortedWebSocket);
282+
const fetchMock = vi.fn();
283+
vi.stubGlobal("fetch", fetchMock);
284+
285+
const result = await streamOpenAICodexResponses(model, context, {
286+
apiKey: createJwt({
287+
"https://api.openai.com/auth": { chatgpt_account_id: "acct-1" },
288+
}),
289+
signal: controller.signal,
290+
}).result();
291+
292+
expect(result).toMatchObject({ stopReason: "aborted", errorMessage: "Request was aborted" });
293+
expect(logWarn).toHaveBeenCalledWith(
294+
"openai-transport",
295+
"ChatGPT Responses stream terminated",
296+
{
297+
api: "openai-chatgpt-responses",
298+
elapsedMs: expect.any(Number),
299+
failureKind: "caller-abort",
300+
model: "gpt-5.6-luna",
301+
provider: "openai",
302+
stopReason: "aborted",
303+
transport: "auto",
304+
},
305+
);
306+
expect(fetchMock).not.toHaveBeenCalled();
307+
});
308+
309+
it("classifies a direct HTTP rejection as a provider failure without logging its text", async () => {
310+
const logWarn = vi.fn();
311+
configureAiTransportHost({ logWarn });
312+
const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
313+
new Response(
314+
JSON.stringify({
315+
error: { message: "hostile prompt echo in a 400 body", code: "invalid_request" },
316+
}),
317+
{ status: 400, statusText: "Bad Request" },
318+
),
319+
);
320+
vi.stubGlobal("fetch", fetchMock);
321+
322+
const result = await streamOpenAICodexResponses(model, context, {
323+
apiKey: createJwt({
324+
"https://api.openai.com/auth": { chatgpt_account_id: "acct-1" },
325+
}),
326+
transport: "sse",
327+
}).result();
328+
329+
expect(result.stopReason).toBe("error");
330+
expect(logWarn).toHaveBeenCalledTimes(1);
331+
const logged = logWarn.mock.calls[0]?.[2];
332+
expect(logged).toMatchObject({ stopReason: "error", failureKind: "provider-failure" });
333+
const serialized = JSON.stringify(logged);
334+
for (const hostile of ["hostile", "invalid_request", "400 body"]) {
335+
expect(serialized).not.toContain(hostile);
336+
}
337+
});
338+
265339
it.each(["sse", "websocket"] as const)(
266340
"preserves failed response identity and provider error details over %s",
267341
async (transport) => {
@@ -270,9 +344,15 @@ describe("OpenAI ChatGPT Responses inference streaming", () => {
270344
response: {
271345
id: "resp_failed",
272346
status: "failed",
273-
error: { code: "invalid_prompt", message: "rejected" },
347+
error: {
348+
code: "invalid_prompt",
349+
type: "hostile type: user prompt echoed here",
350+
message: "rejected",
351+
},
274352
},
275353
};
354+
const logWarn = vi.fn();
355+
configureAiTransportHost({ logWarn });
276356
const fetchMock = vi.fn();
277357
vi.stubGlobal("fetch", fetchMock);
278358

@@ -323,6 +403,23 @@ describe("OpenAI ChatGPT Responses inference streaming", () => {
323403
errorMessage: "invalid_prompt: rejected",
324404
},
325405
});
406+
// Provider message text reaches the stream consumer only; the transport
407+
// log keeps timing and classification and never the message body.
408+
expect(logWarn).toHaveBeenCalledTimes(1);
409+
const logged = logWarn.mock.calls[0]?.[2];
410+
expect(logged).toEqual({
411+
api: "openai-chatgpt-responses",
412+
elapsedMs: expect.any(Number),
413+
failureKind: "provider-failure",
414+
model: "gpt-5.6-luna",
415+
provider: "openai",
416+
stopReason: "error",
417+
transport,
418+
});
419+
const serialized = JSON.stringify(logged);
420+
for (const hostile of ["rejected", "invalid_prompt", "hostile type", "echoed"]) {
421+
expect(serialized).not.toContain(hostile);
422+
}
326423
if (transport === "websocket") {
327424
expect(fetchMock).not.toHaveBeenCalled();
328425
}

‎packages/ai/src/providers/openai-chatgpt-responses.ts‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,26 @@ function isRequestTimeoutError(
243243
);
244244
}
245245

246+
type StreamFailureKind = "timeout" | "caller-abort" | "provider-failure" | "transport";
247+
248+
/** Local-only failure category for transport diagnostics; never provider text. */
249+
function classifyStreamFailure(
250+
error: unknown,
251+
signal: AbortSignal | undefined,
252+
requestTimedOut: boolean,
253+
): StreamFailureKind {
254+
if (requestTimedOut) {
255+
return "timeout";
256+
}
257+
if (signal?.aborted) {
258+
return "caller-abort";
259+
}
260+
// CodexApiError carries a non-OK HTTP reply; both are provider decisions, not transport faults.
261+
return error instanceof ResponsesStreamFailure || error instanceof CodexApiError
262+
? "provider-failure"
263+
: "transport";
264+
}
265+
246266
function formatRequestTimeoutError(timeoutMs: number, cause: unknown): Error {
247267
return new Error(`Request timed out after ${timeoutMs}ms`, {
248268
cause: cause instanceof Error ? cause : undefined,
@@ -288,6 +308,7 @@ export const streamOpenAICodexResponses: StreamFunction<
288308
const stream = new AssistantMessageEventStream();
289309

290310
void (async () => {
311+
const startedAt = Date.now();
291312
let requestTimeoutMs: number | undefined;
292313
let requestTimeoutSignal: AbortSignal | undefined;
293314
let activeSignal: AbortSignal | undefined;
@@ -621,16 +642,31 @@ export const streamOpenAICodexResponses: StreamFunction<
621642
});
622643
stream.end();
623644
} catch (error) {
624-
const normalizedError =
645+
const requestTimedOut =
625646
isRequestTimeoutError(error, options?.signal, requestTimeoutSignal, requestTimeoutMs) &&
626-
requestTimeoutMs !== undefined
647+
requestTimeoutMs !== undefined;
648+
const normalizedError =
649+
requestTimedOut && requestTimeoutMs !== undefined
627650
? formatRequestTimeoutError(requestTimeoutMs, error)
628651
: error;
629652
for (const block of output.content) {
630653
// partialJson is only a streaming scratch buffer; never persist it.
631654
delete (block as { partialJson?: string }).partialJson;
632655
}
633656
const terminal = projectProviderError(normalizedError, options?.signal);
657+
// Log only locally-derived facts: timing and a fixed failure category. No
658+
// projected provider field (message, body, code, type, name) is logged —
659+
// all of them are provider-controlled text that can carry prompt- or
660+
// response-derived content.
661+
getAiTransportHost().logWarn("openai-transport", "ChatGPT Responses stream terminated", {
662+
provider: model.provider,
663+
api: model.api,
664+
model: model.id,
665+
transport: options?.transport || "auto",
666+
elapsedMs: Math.max(0, Date.now() - startedAt),
667+
stopReason: terminal.stopReason,
668+
failureKind: classifyStreamFailure(error, options?.signal, requestTimedOut),
669+
});
634670
Object.assign(output, terminal);
635671
stream.push({ type: "error", reason: terminal.stopReason, error: output });
636672
stream.end();

0 commit comments

Comments
 (0)