Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
47beb41
fix(core): recover model requests rejected with HTTP 413 via one-shot…
yiliang114 Aug 28, 2026
cdc35be
fix(core): suppress post-compact restoration on payload-overflow comp…
yiliang114 Aug 28, 2026
0d5d3c9
fix(core): keep part siblings and slim functionCall args in 413 slimming
yiliang114 Aug 28, 2026
ecae69c
fix(core): keep cause-wrapped 413 status on the actionable error
yiliang114 Aug 28, 2026
db32264
fix(core): give 413 recovery outcome-accurate advice instead of uncon…
yiliang114 Aug 28, 2026
676fd2f
fix(core,cli): report payload_overflow trigger reason for 413-driven …
yiliang114 Aug 28, 2026
646932c
fix(core): label and log the 413 recovery path accurately for oncall
yiliang114 Aug 28, 2026
b3abd08
fix(core): anchor 413 recovery accounting on a local history estimate
yiliang114 Aug 28, 2026
73cbac7
fix(core): keep 413 recoveries off the cache-sharing side-query path
yiliang114 Aug 28, 2026
e368a6c
test(core): pin the maxFiles half of payload-overflow restoration sup…
yiliang114 Aug 28, 2026
faddd02
Merge remote-tracking branch 'origin/main' into prmerge-10408
qwencoder Aug 28, 2026
95eef8c
test(core): cast the restoration-suppression fake config to Config
yiliang114 Aug 28, 2026
7bc0446
Merge branch 'main' into fix/issue-10380-model-request-413
yiliang114 Aug 30, 2026
46aace5
fix(core): handle payload-overflow compaction edge cases
yiliang114 Aug 31, 2026
cda0ea9
Merge branch 'main' into fix/issue-10380-model-request-413
yiliang114 Aug 31, 2026
c3dc520
test(core): make 413 compaction fixtures carry a realistically large …
yiliang114 Aug 31, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
210 changes: 210 additions & 0 deletions packages/core/src/core/llm-chat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18415,5 +18415,215 @@ describe('LlmChat', async () => {
vi.useRealTimers();
}
});
describe('issue #10380: HTTP 413 request-body overflow recovery', () => {
// A reverse proxy in front of an OpenAI-compatible endpoint can reject
// the serialized request body (HTTP 413) even when the token count is
// below the auto-compaction threshold. The send must recover through the
// same one-shot reactive compression path as token-based overflow, and
// give an actionable error when recovery cannot fit under the limit.
function sdkStyle413(): Error {
return Object.assign(
new Error(
'413 POST https://gateway.internal/v1/chat/completions: Request Entity Too Large\n' +
'<html>\n<head><title>413 Request Entity Too Large</title></head>\n' +
'<body>\n<center><h1>413 Request Entity Too Large</h1></center>\n' +
'<hr><center>nginx</center>\n</body>\n</html>',
),
{ status: 413 },
);
}

function noopThen(result: {
newHistory: Content[] | null;
info: ChatCompressionInfo;
}) {
// First call is the pre-send cheap gate; the second is the reactive
// overflow attempt (mirrors the plan-exit reactive tests above).
return vi
.spyOn(ChatCompressionService.prototype, 'compress')
.mockResolvedValueOnce({
newHistory: null,
info: {
originalTokenCount: 0,
newTokenCount: 0,
compressionStatus: CompressionStatus.NOOP,
},
})
.mockResolvedValueOnce(result);
}

async function consumeStream(
stream: AsyncGenerator<StreamEvent>,
): Promise<StreamEvent[]> {
const events: StreamEvent[] = [];
for await (const event of stream) {
events.push(event);
}
return events;
}

it('classifies a model-request 413 as recoverable and compacts once before retrying', async () => {
const compressSpy = noopThen({
newHistory: [{ role: 'user', parts: [{ text: 'summary' }] }],
info: {
originalTokenCount: 90_000,
newTokenCount: 4_000,
compressionStatus: CompressionStatus.COMPRESSED,
},
});
vi.mocked(mockContentGenerator.generateContentStream)
.mockRejectedValueOnce(sdkStyle413())
.mockImplementationOnce(async () =>
streamResponse(
stopResponse([{ text: 'recovered after compaction' }]),
),
);

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'next prompt' },
'prompt-id-413-recovery',
);
const events = await consumeStream(stream);

expect(compressSpy).toHaveBeenCalledTimes(2);
expect(compressSpy.mock.calls[1]?.[1]).toEqual(
expect.objectContaining({ requestPayloadTooLarge: true }),
);
expect(
events.some((event) => event.type === StreamEventType.COMPRESSED),
).toBe(true);
expect(
events.some((event) => event.type === StreamEventType.RETRY),
).toBe(true);
expect(
mockContentGenerator.generateContentStream,
).toHaveBeenCalledTimes(2);
const retryRequest = vi.mocked(
mockContentGenerator.generateContentStream,
).mock.calls[1]![0] as { contents: Content[] };
expect(JSON.stringify(retryRequest.contents)).toContain('summary');
});

it('surfaces an actionable error when the retried request still exceeds the body limit', async () => {
const compressSpy = noopThen({
newHistory: [{ role: 'user', parts: [{ text: 'summary' }] }],
info: {
originalTokenCount: 90_000,
newTokenCount: 4_000,
compressionStatus: CompressionStatus.COMPRESSED,
},
});
vi.mocked(mockContentGenerator.generateContentStream)
.mockRejectedValueOnce(sdkStyle413())
.mockRejectedValueOnce(sdkStyle413());

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'next prompt' },
'prompt-id-413-still-too-large',
);
await expect(consumeStream(stream)).rejects.toThrow(
/start a new session/i,
);
// One pre-send cheap gate + one reactive attempt; no compression loop.
expect(compressSpy).toHaveBeenCalledTimes(2);
});

it('surfaces an actionable error when compaction cannot recover the 413', async () => {
const compressSpy = noopThen({
newHistory: null,
info: {
originalTokenCount: 90_000,
newTokenCount: 90_000,
compressionStatus:
CompressionStatus.COMPRESSION_FAILED_EMPTY_SUMMARY,
},
});
vi.mocked(
mockContentGenerator.generateContentStream,
).mockRejectedValueOnce(sdkStyle413());

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'next prompt' },
'prompt-id-413-compression-failed',
);
await expect(consumeStream(stream)).rejects.toThrow(
/start a new session/i,
);
expect(compressSpy).toHaveBeenCalledTimes(2);
expect(
mockContentGenerator.generateContentStream,
).toHaveBeenCalledTimes(1);
});

it('keeps token-wording overflow on the original reactive path', async () => {
// Regression guard: the 413 classification must not change how
// provider-reported context-length wording is recovered.
const compressSpy = noopThen({
newHistory: [{ role: 'user', parts: [{ text: 'summary' }] }],
info: {
originalTokenCount: 135_000,
newTokenCount: 40_000,
compressionStatus: CompressionStatus.COMPRESSED,
},
});
vi.mocked(mockContentGenerator.generateContentStream)
.mockRejectedValueOnce(
new Error('prompt is too long: 135000 tokens > 128000 maximum'),
)
.mockImplementationOnce(async () =>
streamResponse(stopResponse([{ text: 'recovered' }])),
);

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'overflow prompt' },
'prompt-id-wording-overflow',
);
await consumeStream(stream);

expect(compressSpy).toHaveBeenCalledTimes(2);
expect(compressSpy.mock.calls[1]?.[1]).toEqual(
expect.not.objectContaining({ requestPayloadTooLarge: true }),
);
});

it('keeps the deep 413 status on the actionable error for cause-wrapped failures', async () => {
// Detection walks the .cause chain, so the status copy onto the
// actionable error must use the same deep lookup — otherwise
// downstream status bucketing records unknown for cause-wrapped
// 413s (#10380).
const causeWrapped413 = (): Error =>
new Error('request failed', { cause: sdkStyle413() });
noopThen({
newHistory: [{ role: 'user', parts: [{ text: 'summary' }] }],
info: {
originalTokenCount: 90_000,
newTokenCount: 4_000,
compressionStatus: CompressionStatus.COMPRESSED,
},
});
vi.mocked(mockContentGenerator.generateContentStream)
.mockRejectedValueOnce(causeWrapped413())
.mockRejectedValueOnce(causeWrapped413());

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'next prompt' },
'prompt-id-413-cause-wrapped-status',
);
let caught: unknown;
try {
await consumeStream(stream);
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(Error);
expect((caught as Error).message).toMatch(/start a new session/i);
expect((caught as { status?: number }).status).toBe(413);
});
});
});
});
57 changes: 55 additions & 2 deletions packages/core/src/core/llm-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@ import {
import type { UiTelemetryService } from '../telemetry/uiTelemetry.js';
import { type ChatCompressionInfo, CompressionStatus } from './turn.js';
import { getContextLengthExceededInfo } from '../utils/contextLengthError.js';
import {
getRequestPayloadTooLargeInfo,
REQUEST_PAYLOAD_TOO_LARGE_RECOVERY_MESSAGE,
} from '../utils/request-payload-error.js';
import {
getStartupContextLength,
isSystemReminderContent,
Expand Down Expand Up @@ -507,6 +511,13 @@ interface TryCompressOptions {
* on the user's stated concern.
*/
customInstructions?: string;
/**
* Set when this compression is triggered by an HTTP 413 request-body
* overflow instead of a token-count overflow (#10380). The compaction
* side-query then slims oversized tool-result text so it can itself fit
* under the same gateway body limit.
*/
requestPayloadTooLarge?: boolean;
}

// Model-output validation errors (protocol tag leaks, malformed tool calls)
Expand Down Expand Up @@ -2372,6 +2383,7 @@ export class LlmChat {
requestGenerationConfig: options?.requestGenerationConfig,
trigger: options?.trigger,
customInstructions: options?.customInstructions,
requestPayloadTooLarge: options?.requestPayloadTooLarge,
signal,
});
// The service owns the compression outcome; LlmChat owns the input
Expand Down Expand Up @@ -3563,9 +3575,23 @@ export class LlmChat {
}

const contextOverflow = getContextLengthExceededInfo(error);
if (contextOverflow.isExceeded) {
// A reverse proxy in front of the endpoint can reject the
// serialized request with a bare HTTP 413 (no token wording)
// even below the token-based compaction threshold; recover it
// through this same one-shot reactive path (#10380).
const requestPayloadOverflow = getRequestPayloadTooLargeInfo(error);
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
if (
contextOverflow.isExceeded ||
requestPayloadOverflow.isTooLarge
) {
// Whether this pass (or a previous one) spent the one-shot
// payload-overflow recovery; when it did and the error is
// still a payload overflow, the wrap below turns it into an
// actionable error (#10380).
let attemptedPayloadRecovery = false;
if (!exactRoute && !reactiveCompressionAttempted) {
reactiveCompressionAttempted = true;
attemptedPayloadRecovery = requestPayloadOverflow.isTooLarge;
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
// Only the provider-reported actual count is authoritative.
// Limit/config/default fallbacks are projections and must
// keep the estimated marker in compression banners.
Expand All @@ -3577,7 +3603,9 @@ export class LlmChat {
cgConfig?.contextWindowSize ??
DEFAULT_TOKEN_LIMIT;
debugLogger.warn(
'Context length exceeded; attempting reactive compression.',
requestPayloadOverflow.isTooLarge
? 'Request body rejected with HTTP 413; attempting reactive compression.'
: 'Context length exceeded; attempting reactive compression.',
);
try {
const reactiveInfo = await self.tryCompress(
Expand All @@ -3593,6 +3621,7 @@ export class LlmChat {
requestGenerationConfig: params.config,
requestRouteKey,
trigger: 'auto',
requestPayloadTooLarge: requestPayloadOverflow.isTooLarge,
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
},
);

Expand Down Expand Up @@ -3689,11 +3718,35 @@ export class LlmChat {
);
}
} else {
attemptedPayloadRecovery =
requestPayloadOverflow.isTooLarge &&
reactiveCompressionAttempted &&
!exactRoute;
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
debugLogger.warn(
'Reactive compression already attempted; ' +
'propagating the context overflow error to caller.',
);
}
if (attemptedPayloadRecovery) {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
// The one-shot recovery is spent: compaction either was
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
// already attempted or could not shrink the request below
// the gateway's byte limit. Re-sending the same history
// would keep failing every prompt, so surface an
// actionable next step instead of the bare 413 (#10380).
const actionableError = new Error(
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
REQUEST_PAYLOAD_TOO_LARGE_RECOVERY_MESSAGE,
{ cause: error },
);
// Reuse the cause-aware lookup that detected the 413: the
// shallow top-level getErrorStatus misses cause-wrapped
// statuses, and the actionable error would lose its .status
// for downstream bucketing (#10380).
const payloadStatus = requestPayloadOverflow.status;
if (payloadStatus !== undefined) {
Object.assign(actionableError, { status: payloadStatus });
}
lastError = actionableError;
}
break;
}

Expand Down
Loading
Loading