Repository navigation
[AI-4057] Bound the size of a streamed answer - #2597
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO (security round 1). The counter, the body cap and the debug gate work for the answer, thinking, and tool name and argument bytes, and the cut ends the upstream request. Three gaps leave a response able to hold far more than the limit: S1.1 tool call id, signature and call count are not counted; S1.2 the cap does not cover an error body; S1.3 the body cap is wide. S1.2 is a gap in code this PR does not change, listed because it is the same middleware and the same ticket. Probes and details are in the ticket.
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
Reviewed 557acb56b merged onto current main (674a8d9b0, clean merge). go build ./..., go vet and go test ./internal/llm/... ./internal/llmrouter/ pass on the merged tree. CI: draft, so go and integration are skipped; they run at gh pr ready.
Blocking: R1.1, R1.2, R1.3 (Should fix). R1.4 is a Nit.
Checked and sound:
- A cut response closes the upstream request (the endpoint sees the client leave). It settles as
incomplete/max_output_tokenswith no stream error.llmroutercounts it as served, so nothing fails over or retries. With no usage frame, the row is estimated from the text, as for a token-capped reply. - The body cap applies only to 2xx bodies of the streaming request, so it cannot cut an error body.
withBodyalready reads at most 2048 B. - The debug copy is kept only when debug is on, and capped. The
debug: truemutant atCreatecannot be observed from a test (the puller is unexported insidellm.Stream). Its cost is bounded by the tested cap, so I accept it. - #2527 touches other hunks of
openaicompat.go. It merges cleanly with this PR, and a body cut is settled beforenamed()runs. - The author's question (the
openaiandanthropicpullers): no ticket.custom/<name>builds onlyopenaicompat(internal/llm/custom/custom.go:65-70), and the other two take hosts the operator configures.
… the limit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e stream Pin the limits with the longest reply in chunks that carry usage, with lines ending in a carriage return, and with a body that is not typed as a stream. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ut a joined copy Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A string the SDK reads is a slice of the object around it, so a field beside it that nothing counts stayed alive as long as the response. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…hat it carries The longest reply keeps more room, and an answer of exactly the limit still completes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…unkBytes One chunk can carry many choices or fragments, and each is an event the response holds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
Delta round 2, head dca0aca (fixer commits since 557acb5; the main merge with #2527 not re-reviewed). Built and tested merged onto current main.
Prior findings, each mutation re-run on this head:
| finding | status | mutation |
|---|---|---|
| tool call ids, signatures, calls opened not counted | fixed | callBytes 0, id dropped, signature dropped, each Clone removed: each fails a test |
| error body read whole | fixed | cap removed fails; a cap too small to hold the message fails TestAnErrorSentAsAListStillSaysWhy |
| stream allowance and event bound | fixed | per-choice and per-fragment floors, chunkBytes 33, eventLimit removed, CRLF and CR rules, maxEventBytes = maxStreamBytes, allowance 512 to 128: each fails a test. maxEventBytes back to 2x survives (see below) |
| longest reply with usage on every chunk | fixed | allowance 128 fails a_chunk_with_usage |
| non-event-stream 2xx body cap | fixed | rows for text/plain in place |
| debug copy joins strings / cuts a character | fixed | utf8 back-off removed fails; re-joining the two keeps survives (memory only), accepted |
Checked as well:
- The error cap leaves the vendor's status and message intact. keypool's doer runs inside the middleware's
next, so its 429 peek and spend-cap check read the body before the cap. #2527's mid-stream rate-limit test passes on the merge. - The copies are right. Content, id, name and arguments are slices of the event's JSON, so they are cloned.
reasoning()andsignature()already unmarshal into new strings. - Line ends follow the SDK's scanner, which is what holds the memory. LF and CRLF end a line. A lone CR does not, in the SDK or here, and the SDK already reads no events from a CR-only stream on main.
New findings
- Should fix (inline,
eventLimit): the SDK decodes an admitted event whole, one struct for each JSON value. So what one event costs in memory depends on how many values it holds, not only on its bytes, and an event under maxEventBytes can still cost far more than the answer limit. Fix: in the same reader, count the values of each event ({,[and,outside JSON strings; reset the string state at each line end), and refuse an event past a fixed cap well above a real chunk, on the same MaxBytesError path. Test row: one event of many small choices ends incomplete, with the endpoint left. Controls: one event with a whole tool call whose arguments hold braces, commas and escaped quotes completes, and so does an event with many parallel calls. A prototype passes the openaicompat, llm and llmrouter suites. Details are in AI-4057. - Should fix (inline,
eventLimit.Read): the counter is checked once, after the whole Read. If the event ends in that same Read, the counter is already reset, so an event can pass maxEventBytes by up to one Read. This is also why the 2x mutant survives. Fix: check it in the loop before the reset. Test: one row at the limit and one a byte past it, both computed from maxAnswerBytes (from maxEventBytes, they would move with a mutant). This head fails the second row. With the fix, both the 2x mutant and maxAnswerBytes-1 fail a row.
Suites on the merge: build, vet (with and without integration), gofmt, go test ./internal/llm/... ./internal/llmrouter/ ./internal/keypool/... and -race on openaicompat all pass. CI: the PR is a draft, so go and integration are skipped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO
Delta round 3, head c8e1108 (reviewed commits 64acc9e, e6a2c11, c8e1108; built and tested merged onto current main).
Prior findings
| id | status | check |
|---|---|---|
| R2.1 (values per event) | fixed | The new rows fail on the previous head. Mutants killed: cap removed, cap doubled, in-loop value check removed, text inside strings counted, escapes ignored, values not reset per event, commas or brackets not counted, >=, string state not reset per line. |
| R2.2 (limit checked before the reset) | fixed | one byte past it fails on the previous head. Mutants killed: in-loop byte check removed, maxEventBytes doubled, maxEventBytes - 1. |
| refusing read hands on the event end | fixed | return n instead of return i (made to build) fails TestAnEventOfManySmallValuesIsCutShort and the byte boundary row. The SDK dispatches an event only on an empty line, so holding back the line feed keeps the refused event from being decoded. A valid event earlier in the same read is still delivered (checked). |
Checks
- String state follows JSON: an escaped backslash before the closing quote and an escaped quote inside a string both leave the counter in the right state (checked with probes). A line feed resets it, which is right for valid JSON; an event that would desynchronise the counter is invalid JSON, and the SDK validates the JSON before it decodes it.
- Real chunk shapes stay far under the cap: a usage chunk with all detail fields, a reasoning delta, 200 tool calls in one event, a long tool argument full of braces and escaped quotes, a chunk with search results. LF and CRLF give the same counts.
- An event split over many
data:lines is refused on this head. go testforinternal/llm/...,internal/llmrouter,internal/keypool/...,-raceonopenaicompat,go vet(with and without the integration tag),gofmt: pass. CI: draft, so go/integration are skipped; the other checks pass.
New
- R3.1 [Should fix, test only, non-blocking: the code is correct] no row sends one event over many
data:lines, so a mutant that resets the value count at every line end passes the suite (inline).
The value count must carry across the data lines of one event; a row sends the same choices one per line and expects the response to end incomplete. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test padded each chunk with a 256 KiB JSON field, which the stream decodes, and took about 4.5 s a case on a 2 CPU runner under -race against a 10 s deadline. It now pads with comment lines the stream skips (about 1.9 s a case), and the shared deadline of the limit tests is 60 s. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
C1 fixed in f4fa872: the body-limit test now pads with comment lines the stream skips (about 1.8 s a case under -race on 2 CPUs, was about 4.5 s), and the limit tests share a 60 s deadline. Test file only. |
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO
Delta review of the test fix at f4fa872 (was 80c0d99). The change is test-only, in acceleration/internal/llm/openaicompat/limit_test.go.
- The body-limit test still fails when the body cap is removed, and it passes with the event limit off, so the body cap is what ends the stream.
- The padding is SSE comment lines. The SDK decoder skips them before any event is decoded, and a blank line after each keeps every event under the event limit.
- The shared deadline is now 60 s. A stream that never ends still fails each test: the deadline surfaces as an error, and the outcome assertions fail too.
go test -race ./internal/llm/openaicompat/passes in golang:1.27.4 with 2 CPUs, and on the head merged onto current main.
Prior findings: C1 is fixed. The earlier rounds are not part of this delta, and the package passes in full at the head.
No new findings.
kanat
left a comment
There was a problem hiding this comment.
Text review: 10 unclear of 21
[Should fix] T1.1 code comments (3 or more unclear comments in one PR): items at lines 56, 62, 67, 73, 79, 88, 450, 480, 725. Each has a rewrite in an inline comment. Same facts, split into shorter sentences, no reversed endings.
[Nit] T1.2 PR opening: the ## Why has four sentences and the first is long. It says what was wrong but never what the PR changes. Suggested opening: "A model served over an OpenAI-compatible endpoint could stream an answer of any size into the router. Only the 2 minute response timeout ended it, and max_tokens does not help when the endpoint ignores it. This PR caps the bytes one response may stream, and stops copying every delta into a debug buffer when debug is off."
Not a finding: the comment at line 911 is clear; the rest of the items read clearly.
| // bound on what one response streams is taken from the models instead. | ||
| const replyTokens = 128_000 | ||
|
|
||
| // maxAnswerBytes bounds the answer, thinking and tool calls one response streams. A token of |
There was a problem hiding this comment.
[Should fix] T1.1 Unclear: "32 a token" is missing a word and one sentence holds three reasons. Suggested rewrite:
// maxAnswerBytes is the most answer, thinking and tool call text one response may stream.
// English takes about four bytes a token. 32 bytes a token also covers scripts of three or four
// bytes a character and tokens of long whitespace or code runs. A response past the limit is cut
// short, as a token cap would have cut it.
| // as the token cap would have cut it. | ||
| const maxAnswerBytes = replyTokens * 32 | ||
|
|
||
| // maxStreamBytes bounds the body the answer arrives in: maxAnswerBytes, with 512 bytes a token |
There was a problem hiding this comment.
[Should fix] T1.1 Unclear: the parenthesis and "what Advance never sees" have no clear subject. Rewrite:
// maxStreamBytes is the most bytes the response body may hold. It is maxAnswerBytes plus 512
// bytes a token for the JSON around each piece of text; one token a chunk takes about 200 of
// them. It also stops what Advance never sees, such as one event whose data lines never end.
| // stops what Advance never sees, such as one event whose data lines never end. | ||
| const maxStreamBytes = maxAnswerBytes + replyTokens*512 | ||
|
|
||
| // chunkBytes is the least each choice of a chunk and each tool call fragment cost the limit, |
There was a problem hiding this comment.
[Should fix] T1.1 Unclear: "the least each choice of a chunk ... cost the limit" is hard to parse. Rewrite:
// chunkBytes is the least that each choice in a chunk and each tool call fragment counts toward
// the limit, whatever they carry. A provider can send one byte at a time, and the response holds
// every piece it sends. At 24, the longest reply sent one token a chunk still fits, with a
// quarter of the limit to spare.
| // quarter of the limit to spare. | ||
| const chunkBytes = 24 | ||
|
|
||
| // maxEventBytes bounds one event of the stream, which the SDK holds whole before it decodes |
There was a problem hiding this comment.
[Should fix] T1.1 Unclear: the last sentence packs three ideas. Rewrite:
// maxEventBytes is the most one event of the stream may hold. The SDK keeps a whole event in
// memory before it decodes it, and data lines with no blank line between them join into one
// event. An event never needs more than the answer limit: a real reply sent in one event stays
// well under maxAnswerBytes, even once escaped in JSON.
| // at a few bytes a token even once escaped in JSON, stays well under maxAnswerBytes. | ||
| const maxEventBytes = maxAnswerBytes | ||
|
|
||
| // maxEventValues bounds the JSON values one event holds, counted as the '{', '[' and ',' |
There was a problem hiding this comment.
[Should fix] T1.1 Unclear: four dense sentences. Rewrite:
// maxEventValues is the most JSON values one event may hold. It counts each '{', '[' and ','
// outside strings. The SDK decodes every value into a struct that takes far more memory than the
// bytes it arrived in, so an event under maxEventBytes could still use far more memory than the
// answer limit. params asks for one choice and no logprobs, so a real chunk holds about 20
// values, and one that opens 200 tool calls at once about 1,400. Braces and quotes inside a
// string, such as a tool call's arguments, are not counted.
| // and escaped quotes, is not counted. | ||
| const maxEventValues = 4096 | ||
|
|
||
| // callBytes is what a tool call costs the limit on top of its text: a provider can open a new |
There was a problem hiding this comment.
[Should fix] T1.1 Unclear: "costs the limit" and the 256 reasoning are tangled. Rewrite:
// callBytes is what each new tool call counts toward the limit on top of its text. A provider can
// open a call with a fragment of a few bytes, and the response holds a record for each call, with
// a generated id. 256 bytes is about the size of that record. That keeps the memory of the calls
// near the limit, and no real reply opens enough calls to reach it.
| } | ||
| } | ||
|
|
||
| // eventLimit fails a body once one event in it passes maxEventBytes or maxEventValues, as |
There was a problem hiding this comment.
[Should fix] T1.1 Unclear: "an empty line, or one of a lone carriage return" reads two ways. Rewrite:
// eventLimit fails a body once one event in it passes maxEventBytes or maxEventValues. It fails
// the way http.MaxBytesReader does, so the response ends the same way. An event ends at an empty
// line, as the SDK splits them; a line holding only a carriage return counts as empty.
| } | ||
| continue | ||
| } | ||
| // The event this line ends may have passed the limit in this read, before it is reset. |
There was a problem hiding this comment.
[Should fix] T1.1 Unclear: "before it is reset" and "held back" do not say what happens. Rewrite:
// A line feed ends the event, and the event may have passed the limit in this read. Check it
// before the reset and stop before the line feed, so the SDK never sees the event end and never
// decodes it.
| p.keep(call.Function.Arguments) | ||
| } | ||
| p.text(w, choice.Delta.Content) | ||
| // A string the SDK read is a slice of the JSON object around it, fields nothing counts |
There was a problem hiding this comment.
[Should fix] T1.1 Unclear: "fields nothing counts included" reads two ways. Rewrite:
// The SDK's strings point into the JSON object around them, which holds fields we do not count.
// Copy the text the response keeps so it does not hold that whole object.
## Why The code comments that #2597 added for the streamed-answer limits were hard to follow when read cold. This PR rewrites nine of them in plain sentences. No code changes. ## Changes | Comment | What it explains now | | --- | --- | | `maxAnswerBytes` | what the answer limit counts, and why the bytes-a-token figure is that high | | `maxStreamBytes` | the body limit is the answer limit plus the JSON around each piece of text | | `chunkBytes` | the least each choice and tool call fragment counts toward the limit, and why | | `maxEventBytes` | why one event never needs more than the answer limit | | `maxEventValues` | why values are counted as well as bytes, and what is not counted | | `callBytes` | what each new tool call counts on top of its text | | `eventLimit` | when an event ends and how the failure matches `http.MaxBytesReader` | | line feed check in `eventLimit.Read` | the event is checked before it is reset, and the line feed is not passed on | | string copy in `Advance` | why the text the response keeps is cloned | ## Validation The diff only touches comments in `acceleration/internal/llm/openaicompat/openaicompat.go`. The build, `go vet` and the package tests pass. <details> <summary>Commands</summary> ``` cd acceleration && go build ./... && go vet ./internal/llm/openaicompat/ && go test ./internal/llm/openaicompat/ git diff origin/main --stat # openaicompat.go only ``` The wording of each comment comes from the text review of #2597. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Why
A model served over an OpenAI-compatible endpoint streams its answer into the router, and nothing bounded how many bytes one response could stream: only the 2 minute response timeout ended it.
max_tokensis a request field, which an endpoint may ignore.puller.Advancealso copied every delta into a buffer used for one debug log line, with debug on or off. Detail in AI-4057.How it works
maxAnswerBytesmax_output_tokens. English is about 4 B a token; 32 leaves room for 3-4 byte scripts and long whitespace tokens.chunkBytescallBytesmaxStreamBytesmaxAnswerBytes+ 128,000 × 512 BmaxEventBytesmaxAnswerBytesmaxEventValues{,[,,outside strings). The SDK decodes each into a struct, so the byte limit alone does not bound memory. A real chunk holds about 20 values; one that opens 200 tool calls at once about 1,400.errorByteswithBodyshows its first 2048 bytes. The error keeps its status.rawBytesError bodies are read in part,
errorBytesbefore the status check, so the SDK never reads a longer one whole. Tool calls count on the same limit: each call a chunk opens costscallBytes, and its id, name, arguments and signature count their bytes.A string the SDK decodes is a slice of the JSON object around it, so the answer, a call's id, name and arguments are copied before the response keeps them: a field beside them that nothing counts is not kept alive.
A cut response reuses the status and reason the package already gives
finish_reason: "length"(incomplete(),openaicompat.go); no new status. This is the one code path of everyopenaicompatvendor (custom models, DeepSeek, xAI, Gemini, Cerebras, Qwen, Ollama and the rest), so all of them get the bound.Validation
TestAnEndpointThatNeverStopsIsCutShortAtTheLimit(answer, thinking, tool arguments, tool names)TestAnEndpointThatOpensToolCallsWithoutEndIsCutShort(a new call a chunk, long ids, long signatures)TestAnEndpointThatSendsAByteAtATimeIsCutShort(a byte a chunk, a byte a choice, empty call fragments)TestWhatTheResponseHoldsStaysNearTheLimitTestAnEventThatNeverEndsIsCutShort(event stream and text/plain)TestABodyPastTheLimitIsCutShort(event stream and text/plain)TestAnErrorWhoseBodyNeverEndsIsReadOnlyInPart(400, 500)TestAnAnswerOfExactlyTheLimitCompletesTestAnEventOfTheLimitCompletesAndOnePastIsCutShortTestAnEventOfManySmallValuesIsCutShort(an event, after a comment, over many data lines)TestAnEventOfTheValueLimitCompletesAndOnePastIsCutShortTestTheLongestReplyStreamedATokenAChunkCompletes(bare chunks, chunks with usage, CRLF lines)TestALongAnswerCompletesWholeTestTheDebugLogShowsTheStartOfTheStream,TestTheDebugLogShowsToolCallsAsTheyStreamed,TestTheStreamIsKeptForTheLogOnlyWhenDebugIsOn,TestTheStreamKeptForTheLogEndsOnAWholeCharacterrawBytes, misses tool calls or ends inside a characterEach changed condition and constant was mutated and the matching test fails. Survivors:
debug: trueand joining the tool call's name and arguments beforekeep, which only cost memory and have no output to assert on, and the value ofrawBytes, a log length the tests take from the constant.go test ./internal/llm/... ./internal/llmrouter/ ./internal/keypool/...,go vet(with and without-tags integration) pass.Review rounds: R1 main + security review NO-GO → fixed; delta R2 NO-GO → fixed; delta R3 GO; R3.1 test row added (80c0d99).
🤖 Generated with Claude Code