From 94801767a4095213628ac384cb00444bdf95f4db Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 17:45:40 -0500 Subject: [PATCH 01/16] AI-4057: bound the size of a streamed answer Co-Authored-By: Claude Opus 5.5 --- .../internal/llm/openaicompat/limit_test.go | 184 ++++++++++++++++++ .../internal/llm/openaicompat/openaicompat.go | 69 ++++++- 2 files changed, 247 insertions(+), 6 deletions(-) create mode 100644 acceleration/internal/llm/openaicompat/limit_test.go diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go new file mode 100644 index 0000000000..f10fef3e7f --- /dev/null +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -0,0 +1,184 @@ +package openaicompat + +import ( + "bytes" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "time" + + "github.com/GetStream/Vision-Agents/acceleration/internal/llm" +) + +// piece is one chunk's worth of an answer that never ends. +var piece = strings.Repeat("a", 16<<10) + +// endless serves an event stream that writes what next returns until the client goes away, +// and closes gone once it notices. +func (s *OpenAICompatSuite) endless(next func() string) (*LLM, <-chan struct{}) { + gone := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer close(gone) + _, _ = io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + flusher := w.(http.Flusher) + for r.Context().Err() == nil { + if _, err := io.WriteString(w, next()); err != nil { + return + } + flusher.Flush() + } + })) + s.T().Cleanup(server.Close) + + provider, err := New(Options{Provider: "test", Model: "test-model", APIKey: "key", BaseURL: server.URL}) + s.Require().NoError(err) + s.T().Cleanup(func() { provider.Close() }) + return provider, gone +} + +// left fails the test unless the endpoint saw the client go away. +func (s *OpenAICompatSuite) left(gone <-chan struct{}) { + select { + case <-gone: + case <-time.After(10 * time.Second): + s.Fail("the request to the endpoint was never cancelled") + } +} + +func (s *OpenAICompatSuite) TestAnEndpointThatNeverStopsIsCutShortAtTheLimit() { + for name, chunk := range map[string]string{ + "answer": textFrame(piece), + "thinking": reasoningFrame(piece), + "tool arguments": toolFrame(0, "", "", piece), + } { + s.Run(name, func() { + provider, gone := s.endless(func() string { return "data: " + chunk + "\n\n" }) + + response, events := s.ask(provider, withTools()) + + s.Equal(llm.StatusIncomplete, response.Status) + s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) + held := 0 + for _, event := range events { + switch event := event.(type) { + case llm.OutputTextDelta: + held += len(event.Delta) + case llm.ReasoningTextDelta: + held += len(event.Delta) + case llm.FunctionCallArgumentsDelta: + held += len(event.Delta) + case llm.ResponseFailed: + s.Fail("a reply cut short at the limit is not the provider failing", event.Err) + } + } + s.LessOrEqual(held, maxAnswerBytes, "what the response holds stays within the limit") + s.LessOrEqual(len(response.OutputText)+len(response.ReasoningText), maxAnswerBytes) + s.Greater(held, maxAnswerBytes-len(piece), "and is cut at the limit rather than before it") + s.left(gone) + }) + } +} + +func (s *OpenAICompatSuite) TestAnEventThatNeverEndsIsCutShort() { + // Data lines with no blank line between them are all one event, which the stream joins + // before any chunk reaches the response. + provider, gone := s.endless(func() string { return "data: " + piece + "\n" }) + + stream, err := provider.Create(s.T().Context(), hello()) + s.Require().NoError(err) + response := drain(stream) + + s.NoError(stream.Err()) + s.Equal(llm.StatusIncomplete, response.Status) + s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) + s.left(gone) +} + +func (s *OpenAICompatSuite) TestAnAnswerOfExactlyTheLimitCompletes() { + s.frames = make([]string, maxAnswerBytes/len(piece)) + for i := range s.frames { + s.frames[i] = textFrame(piece) + } + s.Require().Equal(maxAnswerBytes, len(s.frames)*len(piece)) + + response, _ := s.ask(s.provider(Options{}), hello()) + + s.Equal(llm.StatusCompleted, response.Status) + s.Len(response.OutputText, maxAnswerBytes) +} + +func (s *OpenAICompatSuite) TestTheLongestReplyStreamedATokenAChunkCompletes() { + // The body limit leaves room for a provider that wraps every token in a chunk of its own, + // as most do, around the longest reply a model writes. + token := textFrame("word") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + var body bytes.Buffer + for range replyTokens { + fmt.Fprintf(&body, "data: %s\n\n", token) + } + fmt.Fprint(&body, "data: [DONE]\n\n") + _, _ = w.Write(body.Bytes()) + })) + s.T().Cleanup(server.Close) + provider, err := New(Options{Provider: "test", Model: "test-model", APIKey: "key", BaseURL: server.URL}) + s.Require().NoError(err) + s.T().Cleanup(func() { provider.Close() }) + + response, _ := s.ask(provider, hello()) + + s.Equal(llm.StatusCompleted, response.Status) + s.Len(response.OutputText, replyTokens*len("word")) +} + +func (s *OpenAICompatSuite) TestALongAnswerCompletesWhole() { + var want strings.Builder + for i := range 2000 { + sentence := fmt.Sprintf("Sentence %d of a long answer, with ünïcode and 日本語. ", i) + want.WriteString(sentence) + s.frames = append(s.frames, textFrame(sentence)) + } + s.frames = append(s.frames, usageFrame(10, 0, 30000, 0, "stop")) + + response, _ := s.ask(s.provider(Options{}), hello()) + + s.Equal(llm.StatusCompleted, response.Status) + s.Empty(response.IncompleteReason) + s.Equal(want.String(), response.OutputText) + s.EqualValues(30000, response.Usage.OutputTokens) +} + +func (s *OpenAICompatSuite) TestTheDebugLogShowsTheStartOfTheStream() { + s.frames = []string{textFrame(strings.Repeat("b", rawBytes)), textFrame("the end")} + var logged bytes.Buffer + provider := s.provider(Options{Logger: slog.New(slog.NewTextHandler(&logged, &slog.HandlerOptions{Level: slog.LevelDebug}))}) + + s.ask(provider, hello()) + + line := "" + for l := range strings.Lines(logged.String()) { + if strings.Contains(l, "the model streamed") { + line = l + } + } + s.Contains(line, "raw="+strings.Repeat("b", rawBytes)) + s.NotContains(line, "the end", "the log keeps the first rawBytes of the stream only") +} + +func (s *OpenAICompatSuite) TestTheStreamIsKeptForTheLogOnlyWhenDebugIsOn() { + for _, debug := range []bool{false, true} { + p := &puller{debug: debug} + p.keep(strings.Repeat("c", rawBytes-1)) + p.keep("dd") + if debug { + s.Equal(strings.Repeat("c", rawBytes-1)+"d", p.raw.String()) + } else { + s.Zero(p.raw.Len()) + } + } +} diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index eceed79ad6..b9ca7ad305 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -46,6 +46,26 @@ import ( // already failed as far as the listener is concerned. const defaultTimeout = 2 * time.Minute +// replyTokens is the longest reply any model is documented to write: OpenAI's GPT-5 has +// "128,000 max output tokens" (https://developers.openai.com/api/docs/models/gpt-5). The router +// puts no maximum on max_output_tokens, and an endpoint may ignore the one it is sent, so the +// 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 +// English is about four bytes; 32 a token leaves room for scripts of three and four bytes a +// character and for tokens of long runs of whitespace or code. A response past it is cut short +// 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 +// for the JSON each chunk wraps its piece in (about 200 bytes when one token comes a chunk). It +// stops what Advance never sees, such as one event whose data lines never end. +const maxStreamBytes = maxAnswerBytes + replyTokens*512 + +// rawBytes is how much of the stream the debug log line shows. +const rawBytes = 64 << 10 + // reasoningField is where models that think stream it. It is not part of the OpenAI // schema, so it arrives as an extra field rather than on the delta struct. const reasoningField = "reasoning_content" @@ -278,8 +298,8 @@ func (l *LLM) Create(ctx context.Context, params llm.ResponseParams) (*llm.Strea }, &puller{ llm: l, id: id, turn: params.ID, upstream: upstream, cancel: cancel, ctx: requestCtx, - firstToken: firstToken, - channel: l.channelSplitter(), toolText: l.toolCallSplitter(params), + firstToken: firstToken, debug: l.logger.Enabled(ctx, slog.LevelDebug), + channel: l.channelSplitter(), toolText: l.toolCallSplitter(params), }, ), nil } @@ -366,6 +386,7 @@ func (l *LLM) sniff(refused *error) option.Middleware { if err != nil || response.StatusCode/100 != 2 || response.Body == nil { return response, err } + response.Body = http.MaxBytesReader(nil, response.Body, maxStreamBytes) contentType := response.Header.Get("Content-Type") if eventStream(contentType) { return response, nil @@ -561,8 +582,14 @@ type puller struct { err error done bool - // raw is everything the model streamed, before any splitting, for the debug log. - raw strings.Builder + // streamed counts the bytes of answer, thinking and tool calls, and tooLong is set once + // they pass maxAnswerBytes. + streamed int + tooLong bool + // raw is the start of what the model streamed, before any splitting, for the debug log. It + // is kept only when debug is on. + debug bool + raw strings.Builder // slots maps the index a provider streamed a call under to where it is recorded, and // ids the call recorded at each slot. @@ -591,10 +618,17 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { w.Usage(usageOf(chunk.Usage)) } + if p.streamed += size(chunk); p.streamed > maxAnswerBytes { + // The chunk that passes the limit is dropped, so what the response holds stays under it. + p.tooLong = true + p.cancel() + p.finish(w) + return false + } for _, choice := range chunk.Choices { - p.raw.WriteString(choice.Delta.Content) + p.keep(choice.Delta.Content) for _, call := range choice.Delta.ToolCalls { - p.raw.WriteString(call.Function.Name + call.Function.Arguments) + p.keep(call.Function.Name + call.Function.Arguments) } p.text(w, choice.Delta.Content) w.ReasoningText(reasoning(choice.Delta.JSON.ExtraFields)) @@ -614,6 +648,25 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { return true } +// size is how many bytes of answer, thinking and tool calls a chunk carries. +func size(chunk openai.ChatCompletionChunk) int { + n := 0 + for _, choice := range chunk.Choices { + n += len(choice.Delta.Content) + len(reasoning(choice.Delta.JSON.ExtraFields)) + for _, call := range choice.Delta.ToolCalls { + n += len(call.Function.Name) + len(call.Function.Arguments) + } + } + return n +} + +// keep adds text to the debug log's copy of the stream, up to rawBytes. +func (p *puller) keep(text string) { + if p.debug { + p.raw.WriteString(text[:min(len(text), max(0, rawBytes-p.raw.Len()))]) + } +} + // text records a piece of the answer, as thinking when it is inside the thought channel. func (p *puller) text(w *llm.ResponseWriter, delta string) { if p.channel == nil { @@ -738,7 +791,11 @@ func (p *puller) finish(w *llm.ResponseWriter) { if late := context.Cause(p.ctx); err != nil && errors.Is(late, errNoFirstToken) { err = late } + _, overBody := errors.AsType[*http.MaxBytesError](err) switch { + case p.tooLong || overBody: + // The endpoint streamed more than any model writes in one reply. + w.Incomplete(llm.ReasonMaxOutputTokens) case err == nil && p.chunks == 0: // The server closed the stream without a single chunk. A real answer of nothing still // sends one, with its finish reason or its usage, so a stream of none, or of comments From 557acb56bfa8e3981a5e81848b9a736813a3d355 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 17:47:35 -0500 Subject: [PATCH 02/16] AI-4057: bound the tests of an endless stream by a deadline Co-Authored-By: Claude Opus 5.5 --- .../internal/llm/openaicompat/limit_test.go | 26 ++++++++++++++----- .../internal/llm/openaicompat/openaicompat.go | 3 +-- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index f10fef3e7f..4c2a231c98 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -2,6 +2,7 @@ package openaicompat import ( "bytes" + "context" "fmt" "io" "log/slog" @@ -40,6 +41,21 @@ func (s *OpenAICompatSuite) endless(next func() string) (*LLM, <-chan struct{}) return provider, gone } +// askBounded is ask under a deadline, so a stream that is never cut short fails the test in +// seconds rather than running for the whole response timeout. +func (s *OpenAICompatSuite) askBounded(provider *LLM, params llm.ResponseParams) (llm.Response, []llm.Event) { + ctx, cancel := context.WithTimeout(s.T().Context(), 10*time.Second) + defer cancel() + stream, err := provider.Create(ctx, params) + s.Require().NoError(err) + var events []llm.Event + for stream.Next() { + events = append(events, stream.Current()) + } + s.NoError(stream.Err(), "a reply cut short at the limit is not the provider failing") + return stream.Response(), events +} + // left fails the test unless the endpoint saw the client go away. func (s *OpenAICompatSuite) left(gone <-chan struct{}) { select { @@ -54,11 +70,12 @@ func (s *OpenAICompatSuite) TestAnEndpointThatNeverStopsIsCutShortAtTheLimit() { "answer": textFrame(piece), "thinking": reasoningFrame(piece), "tool arguments": toolFrame(0, "", "", piece), + "tool names": toolFrame(0, "", piece, ""), } { s.Run(name, func() { provider, gone := s.endless(func() string { return "data: " + chunk + "\n\n" }) - response, events := s.ask(provider, withTools()) + response, events := s.askBounded(provider, withTools()) s.Equal(llm.StatusIncomplete, response.Status) s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) @@ -70,7 +87,7 @@ func (s *OpenAICompatSuite) TestAnEndpointThatNeverStopsIsCutShortAtTheLimit() { case llm.ReasoningTextDelta: held += len(event.Delta) case llm.FunctionCallArgumentsDelta: - held += len(event.Delta) + held += len(event.Name) + len(event.Delta) case llm.ResponseFailed: s.Fail("a reply cut short at the limit is not the provider failing", event.Err) } @@ -88,11 +105,8 @@ func (s *OpenAICompatSuite) TestAnEventThatNeverEndsIsCutShort() { // before any chunk reaches the response. provider, gone := s.endless(func() string { return "data: " + piece + "\n" }) - stream, err := provider.Create(s.T().Context(), hello()) - s.Require().NoError(err) - response := drain(stream) + response, _ := s.askBounded(provider, hello()) - s.NoError(stream.Err()) s.Equal(llm.StatusIncomplete, response.Status) s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) s.left(gone) diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index b9ca7ad305..1351b153ec 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -583,7 +583,7 @@ type puller struct { err error done bool // streamed counts the bytes of answer, thinking and tool calls, and tooLong is set once - // they pass maxAnswerBytes. + // they pass maxAnswerBytes, which ends the response: finish closes the request. streamed int tooLong bool // raw is the start of what the model streamed, before any splitting, for the debug log. It @@ -621,7 +621,6 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { if p.streamed += size(chunk); p.streamed > maxAnswerBytes { // The chunk that passes the limit is dropped, so what the response holds stays under it. p.tooLong = true - p.cancel() p.finish(w) return false } From 8083bdab93ab7636e2918b63f34677eb57b27461 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 18:04:25 -0500 Subject: [PATCH 03/16] AI-4057: count tool call ids, signatures and each call opened against the limit Co-Authored-By: Claude Opus 5.5 --- .../internal/llm/openaicompat/limit_test.go | 26 +++++++++++++++++ .../internal/llm/openaicompat/openaicompat.go | 29 +++++++++++++++---- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index 4c2a231c98..9237d79d30 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -100,6 +100,32 @@ func (s *OpenAICompatSuite) TestAnEndpointThatNeverStopsIsCutShortAtTheLimit() { } } +func (s *OpenAICompatSuite) TestAnEndpointThatOpensToolCallsWithoutEndIsCutShort() { + long := strings.Repeat("i", 16<<10) + for name, call := range map[string]func(i int) string{ + "a new call a chunk": func(i int) string { return fmt.Sprintf(`{"choices":[{"delta":{"tool_calls":[{"index":%d}]}}]}`, i) }, + "a long id a call": func(i int) string { return toolFrame(i, fmt.Sprint(i)+long, "", "") }, + "a long signature a call": func(i int) string { return signedToolFrame(i, fmt.Sprint("c", i), "", "", long) }, + } { + s.Run(name, func() { + i := 0 + provider, gone := s.endless(func() string { i++; return "data: " + call(i) + "\n\n" }) + + response, _ := s.askBounded(provider, withTools()) + + s.Equal(llm.StatusIncomplete, response.Status) + s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) + held := 0 + for _, call := range response.ToolCalls { + held += len(call.ID) + len(call.Name) + len(call.Arguments) + len(call.Signature) + } + s.LessOrEqual(len(response.ToolCalls), maxAnswerBytes/callBytes, "each call the response holds counts against the limit") + s.LessOrEqual(held, maxAnswerBytes, "and so do their ids and signatures") + s.left(gone) + }) + } +} + func (s *OpenAICompatSuite) TestAnEventThatNeverEndsIsCutShort() { // Data lines with no blank line between them are all one event, which the stream joins // before any chunk reaches the response. diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index 1351b153ec..5ca8b16941 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -63,6 +63,12 @@ const maxAnswerBytes = replyTokens * 32 // stops what Advance never sees, such as one event whose data lines never end. const maxStreamBytes = maxAnswerBytes + replyTokens*512 +// callBytes is what a tool call costs the limit on top of its text: a provider can open a new +// call with a fragment of a few bytes, and each one is a call the response holds, with an id +// generated for it. 256 is about what that record takes, so the calls a response holds stay +// near the limit too, and no real reply opens enough calls to notice it. +const callBytes = 256 + // rawBytes is how much of the stream the debug log line shows. const rawBytes = 64 << 10 @@ -618,7 +624,7 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { w.Usage(usageOf(chunk.Usage)) } - if p.streamed += size(chunk); p.streamed > maxAnswerBytes { + if p.streamed += p.size(chunk); p.streamed > maxAnswerBytes { // The chunk that passes the limit is dropped, so what the response holds stays under it. p.tooLong = true p.finish(w) @@ -647,13 +653,17 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { return true } -// size is how many bytes of answer, thinking and tool calls a chunk carries. -func size(chunk openai.ChatCompletionChunk) int { +// size is how many bytes of answer, thinking and tool calls a chunk carries, with callBytes +// for each call it opens. +func (p *puller) size(chunk openai.ChatCompletionChunk) int { n := 0 for _, choice := range chunk.Choices { n += len(choice.Delta.Content) + len(reasoning(choice.Delta.JSON.ExtraFields)) for _, call := range choice.Delta.ToolCalls { - n += len(call.Function.Name) + len(call.Function.Arguments) + n += len(call.ID) + len(call.Function.Name) + len(call.Function.Arguments) + len(signature(call.JSON.ExtraFields)) + if p.opens(call.Index, call.ID) { + n += callBytes + } } } return n @@ -732,8 +742,8 @@ func (p *puller) slot(index int64, id string) int64 { if p.slots == nil { p.slots, p.ids = map[int64]int64{}, map[int64]string{} } - slot, known := p.slots[index] - if !known || (id != "" && p.ids[slot] != "" && p.ids[slot] != id) { + slot := p.slots[index] + if p.opens(index, id) { slot = int64(len(p.ids)) p.slots[index] = slot p.ids[slot] = "" @@ -744,6 +754,13 @@ func (p *puller) slot(index int64, id string) int64 { return slot } +// opens reports whether a tool call fragment starts a call of its own rather than adding to +// one already recorded. +func (p *puller) opens(index int64, id string) bool { + slot, known := p.slots[index] + return !known || (id != "" && p.ids[slot] != "" && p.ids[slot] != id) +} + // said reports whether a chunk carries any of the answer: text, thinking or a tool call. A // chunk with only the assistant role, which vLLM sends before the prompt is processed, does // not. From 0ce640e66bbd013e8b402106612df72e70a09940 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 18:07:41 -0500 Subject: [PATCH 04/16] AI-4057: count each chunk against the limit and bound one event of the 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 --- .../internal/llm/openaicompat/limit_test.go | 135 ++++++++++++++---- .../internal/llm/openaicompat/openaicompat.go | 46 +++++- 2 files changed, 149 insertions(+), 32 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index 9237d79d30..dc9560b4ec 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -9,6 +9,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync/atomic" "time" "github.com/GetStream/Vision-Agents/acceleration/internal/llm" @@ -20,14 +21,23 @@ var piece = strings.Repeat("a", 16<<10) // endless serves an event stream that writes what next returns until the client goes away, // and closes gone once it notices. func (s *OpenAICompatSuite) endless(next func() string) (*LLM, <-chan struct{}) { + provider, gone, _ := s.endlessAs("text/event-stream", next) + return provider, gone +} + +// endlessAs is endless under another Content-Type, and counts the bytes the endpoint sent. +func (s *OpenAICompatSuite) endlessAs(contentType string, next func() string) (*LLM, <-chan struct{}, *atomic.Int64) { gone := make(chan struct{}) + var sent atomic.Int64 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer close(gone) _, _ = io.Copy(io.Discard, r.Body) - w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Content-Type", contentType) flusher := w.(http.Flusher) for r.Context().Err() == nil { - if _, err := io.WriteString(w, next()); err != nil { + n, err := io.WriteString(w, next()) + sent.Add(int64(n)) + if err != nil { return } flusher.Flush() @@ -38,7 +48,7 @@ func (s *OpenAICompatSuite) endless(next func() string) (*LLM, <-chan struct{}) provider, err := New(Options{Provider: "test", Model: "test-model", APIKey: "key", BaseURL: server.URL}) s.Require().NoError(err) s.T().Cleanup(func() { provider.Close() }) - return provider, gone + return provider, gone, &sent } // askBounded is ask under a deadline, so a stream that is never cut short fails the test in @@ -94,7 +104,7 @@ func (s *OpenAICompatSuite) TestAnEndpointThatNeverStopsIsCutShortAtTheLimit() { } s.LessOrEqual(held, maxAnswerBytes, "what the response holds stays within the limit") s.LessOrEqual(len(response.OutputText)+len(response.ReasoningText), maxAnswerBytes) - s.Greater(held, maxAnswerBytes-len(piece), "and is cut at the limit rather than before it") + s.Greater(held, maxAnswerBytes-2*len(piece), "and is cut at the limit rather than before it") s.left(gone) }) } @@ -126,54 +136,119 @@ func (s *OpenAICompatSuite) TestAnEndpointThatOpensToolCallsWithoutEndIsCutShort } } -func (s *OpenAICompatSuite) TestAnEventThatNeverEndsIsCutShort() { - // Data lines with no blank line between them are all one event, which the stream joins - // before any chunk reaches the response. - provider, gone := s.endless(func() string { return "data: " + piece + "\n" }) +func (s *OpenAICompatSuite) TestAnEndpointThatSendsAByteAChunkIsCutShort() { + provider, gone := s.endless(func() string { return "data: " + textFrame("a") + "\n\n" }) - response, _ := s.askBounded(provider, hello()) + response, events := s.askBounded(provider, hello()) s.Equal(llm.StatusIncomplete, response.Status) s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) + s.LessOrEqual(len(events), maxAnswerBytes/chunkBytes, "each chunk counts against the limit, not only what it carries") s.left(gone) } +func (s *OpenAICompatSuite) TestAnEventThatNeverEndsIsCutShort() { + // Data lines with no blank line between them are all one event, which the stream joins + // before any chunk reaches the response. + for _, contentType := range []string{"text/event-stream", "text/plain"} { + for name, line := range map[string]string{ + "data lines": "data: " + piece + "\n", + // The SDK drops one carriage return a line, so a line of two is not empty. + "lines of carriage returns": "data: " + piece + "\n\r\r\n", + "a line with no end": piece, + } { + s.Run(contentType+" "+name, func() { + // The first line opens a data field, so the body reads as an event stream. + opened := false + provider, gone, sent := s.endlessAs(contentType, func() string { + if !opened { + opened = true + return "data: " + line + } + return line + }) + + response, _ := s.askBounded(provider, hello()) + + s.Equal(llm.StatusIncomplete, response.Status) + s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) + s.left(gone) + s.Less(sent.Load(), int64(maxStreamBytes/2), "it is cut at the event's limit, well before the body's") + }) + } + } +} + +func (s *OpenAICompatSuite) TestABodyPastTheLimitIsCutShort() { + // Bytes outside the answer, such as a field the response does not read, count only against + // the body's limit. + chunk := strings.Replace(textFrame("a"), `"choices"`, `"padding":"`+strings.Repeat("p", 256<<10)+`","choices"`, 1) + for _, contentType := range []string{"text/event-stream", "text/plain"} { + s.Run(contentType, func() { + provider, gone, sent := s.endlessAs(contentType, func() string { return "data: " + chunk + "\n\n" }) + + response, _ := s.askBounded(provider, hello()) + + s.Equal(llm.StatusIncomplete, response.Status) + s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) + s.left(gone) + s.GreaterOrEqual(sent.Load(), int64(maxStreamBytes), "it is the body's limit that cut it") + }) + } +} + func (s *OpenAICompatSuite) TestAnAnswerOfExactlyTheLimitCompletes() { + // Each chunk costs chunkBytes besides its text, so the last one is that much shorter. s.frames = make([]string, maxAnswerBytes/len(piece)) for i := range s.frames { s.frames[i] = textFrame(piece) } + text := maxAnswerBytes - len(s.frames)*chunkBytes + s.frames[len(s.frames)-1] = textFrame(piece[:len(piece)-len(s.frames)*chunkBytes]) s.Require().Equal(maxAnswerBytes, len(s.frames)*len(piece)) response, _ := s.ask(s.provider(Options{}), hello()) s.Equal(llm.StatusCompleted, response.Status) - s.Len(response.OutputText, maxAnswerBytes) + s.Len(response.OutputText, text) } func (s *OpenAICompatSuite) TestTheLongestReplyStreamedATokenAChunkCompletes() { - // The body limit leaves room for a provider that wraps every token in a chunk of its own, - // as most do, around the longest reply a model writes. - token := textFrame("word") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, _ = io.Copy(io.Discard, r.Body) - w.Header().Set("Content-Type", "text/event-stream") - var body bytes.Buffer - for range replyTokens { - fmt.Fprintf(&body, "data: %s\n\n", token) - } - fmt.Fprint(&body, "data: [DONE]\n\n") - _, _ = w.Write(body.Bytes()) - })) - s.T().Cleanup(server.Close) - provider, err := New(Options{Provider: "test", Model: "test-model", APIKey: "key", BaseURL: server.URL}) - s.Require().NoError(err) - s.T().Cleanup(func() { provider.Close() }) + // The limits leave room for a provider that wraps every token in a chunk of its own, as + // most do, around the longest reply a model writes: with usage on every chunk and a long + // model id, as some servers stream it, or with lines that end in a carriage return too. + type stream struct{ chunk, eol string } + for name, token := range map[string]stream{ + "a bare chunk": {textFrame("word"), "\n"}, + "carriage returns": {textFrame("word"), "\r\n"}, + "a chunk with usage": {`{"id":"chatcmpl-8f3c2a1e9b7d4c6a8e2f1b3d5c7a9e0f","object":"chat.completion.chunk","created":1732600000,` + + `"model":"accounts/fireworks/models/llama-v3p3-70b-instruct","system_fingerprint":"fp_6b9a1c2d3e",` + + `"choices":[{"index":0,"delta":{"content":"word"},"logprobs":null,"finish_reason":null}],` + + `"usage":{"prompt_tokens":1834,"completion_tokens":1000,"total_tokens":2834,` + + `"prompt_tokens_details":{"cached_tokens":1024},"completion_tokens_details":{"reasoning_tokens":0}}}`, "\n"}, + } { + s.Run(name, func() { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + var body bytes.Buffer + for range replyTokens { + fmt.Fprintf(&body, "data: %s%s%s", token.chunk, token.eol, token.eol) + } + fmt.Fprint(&body, "data: [DONE]\n\n") + _, _ = w.Write(body.Bytes()) + })) + s.T().Cleanup(server.Close) + provider, err := New(Options{Provider: "test", Model: "test-model", APIKey: "key", BaseURL: server.URL}) + s.Require().NoError(err) + s.T().Cleanup(func() { provider.Close() }) - response, _ := s.ask(provider, hello()) + response, _ := s.ask(provider, hello()) - s.Equal(llm.StatusCompleted, response.Status) - s.Len(response.OutputText, replyTokens*len("word")) + s.Equal(llm.StatusCompleted, response.Status) + s.Len(response.OutputText, replyTokens*len("word")) + }) + } } func (s *OpenAICompatSuite) TestALongAnswerCompletesWhole() { diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index 5ca8b16941..14e545e884 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -63,6 +63,17 @@ const maxAnswerBytes = replyTokens * 32 // stops what Advance never sees, such as one event whose data lines never end. const maxStreamBytes = maxAnswerBytes + replyTokens*512 +// chunkBytes is what each chunk costs the limit on top of what it carries: a provider can send +// a byte a chunk, and each one is an event the response holds. At 16 the longest reply still +// fits streamed a token a chunk, as long as its tokens average 16 bytes or less of the 32 the +// limit leaves each. +const chunkBytes = 16 + +// maxEventBytes bounds one event of the stream, which the SDK holds whole before it decodes +// it: data lines with no blank line between them all join into one. Twice maxAnswerBytes leaves +// room for an event that carries the whole answer, escaped in JSON. +const maxEventBytes = 2 * maxAnswerBytes + // callBytes is what a tool call costs the limit on top of its text: a provider can open a new // call with a fragment of a few bytes, and each one is a call the response holds, with an id // generated for it. 256 is about what that record takes, so the calls a response holds stay @@ -392,7 +403,7 @@ func (l *LLM) sniff(refused *error) option.Middleware { if err != nil || response.StatusCode/100 != 2 || response.Body == nil { return response, err } - response.Body = http.MaxBytesReader(nil, response.Body, maxStreamBytes) + response.Body = &eventLimit{body: http.MaxBytesReader(nil, response.Body, maxStreamBytes)} contentType := response.Header.Get("Content-Type") if eventStream(contentType) { return response, nil @@ -413,6 +424,37 @@ func (l *LLM) sniff(refused *error) option.Middleware { } } +// eventLimit fails a body once one event in it passes maxEventBytes, as MaxBytesReader fails +// one past its limit, so the response ends the same way. An event ends at an empty line, or +// one of a lone carriage return, as the SDK splits them. +type eventLimit struct { + body io.ReadCloser + // line and event count the bytes since the last line and event ended, and cr is whether + // the last of them was a carriage return. + line, event int + cr bool +} + +func (e *eventLimit) Read(b []byte) (int, error) { + n, err := e.body.Read(b) + for _, c := range b[:n] { + if c != '\n' { + e.line, e.event, e.cr = e.line+1, e.event+1, c == '\r' + continue + } + if e.line == 0 || (e.line == 1 && e.cr) { + e.event = 0 + } + e.line = 0 + } + if e.event > maxEventBytes { + return n, &http.MaxBytesError{Limit: maxEventBytes} + } + return n, err +} + +func (e *eventLimit) Close() error { return e.body.Close() } + // eventStream reports whether a Content-Type names an event stream. A parameter Go cannot // parse, as in "text/event-stream; charset", does not make it something else. func eventStream(contentType string) bool { @@ -624,7 +666,7 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { w.Usage(usageOf(chunk.Usage)) } - if p.streamed += p.size(chunk); p.streamed > maxAnswerBytes { + if p.streamed += chunkBytes + p.size(chunk); p.streamed > maxAnswerBytes { // The chunk that passes the limit is dropped, so what the response holds stays under it. p.tooLong = true p.finish(w) From 643d93650cd5019727980f313ecc9b4cf232f4ab Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 18:09:51 -0500 Subject: [PATCH 05/16] AI-4057: read only the start of an error's body Co-Authored-By: Claude Opus 5.5 --- .../internal/llm/openaicompat/limit_test.go | 41 +++++++++++++++++++ .../internal/llm/openaicompat/openaicompat.go | 14 ++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index dc9560b4ec..2c326dd9ee 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -3,6 +3,7 @@ package openaicompat import ( "bytes" "context" + "errors" "fmt" "io" "log/slog" @@ -12,6 +13,8 @@ import ( "sync/atomic" "time" + "github.com/openai/openai-go/v3" + "github.com/GetStream/Vision-Agents/acceleration/internal/llm" ) @@ -197,6 +200,44 @@ func (s *OpenAICompatSuite) TestABodyPastTheLimitIsCutShort() { } } +func (s *OpenAICompatSuite) TestAnErrorWhoseBodyNeverEndsIsReadOnlyInPart() { + for _, status := range []int{http.StatusBadRequest, http.StatusInternalServerError} { + s.Run(http.StatusText(status), func() { + var sent atomic.Int64 + gone := make(chan struct{}, 8) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { gone <- struct{}{} }() + _, _ = io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = io.WriteString(w, `{"error":{"message":"no","padding":"`) + for r.Context().Err() == nil { + n, err := io.WriteString(w, piece) + sent.Add(int64(n)) + if err != nil { + return + } + w.(http.Flusher).Flush() + } + })) + s.T().Cleanup(server.Close) + provider, err := New(Options{Provider: "test", Model: "test-model", APIKey: "key", BaseURL: server.URL}) + s.Require().NoError(err) + s.T().Cleanup(func() { provider.Close() }) + ctx, cancel := context.WithTimeout(s.T().Context(), 10*time.Second) + defer cancel() + + _, err = provider.Create(ctx, hello()) + + apiError, ok := errors.AsType[*openai.Error](err) + s.Require().True(ok, "the error is the endpoint's, with its status: %v", err) + s.Equal(status, apiError.StatusCode) + s.left(gone) + s.Less(sent.Load(), int64(16<<20), "only the start of the body is read") + }) + } +} + func (s *OpenAICompatSuite) TestAnAnswerOfExactlyTheLimitCompletes() { // Each chunk costs chunkBytes besides its text, so the last one is that much shorter. s.frames = make([]string, maxAnswerBytes/len(piece)) diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index 14e545e884..c2bed224b2 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -80,6 +80,11 @@ const maxEventBytes = 2 * maxAnswerBytes // near the limit too, and no real reply opens enough calls to notice it. const callBytes = 256 +// errorBytes is how much of an error's body is read. The SDK reads all of it to find the +// message, which is a short JSON object, and withBody shows its first 2048 bytes; a body +// longer than this is not a message anyone reads. +const errorBytes = 16 << 10 + // rawBytes is how much of the stream the debug log line shows. const rawBytes = 64 << 10 @@ -400,9 +405,16 @@ func lengthRefused(err error) bool { func (l *LLM) sniff(refused *error) option.Middleware { return func(request *http.Request, next option.MiddlewareNext) (*http.Response, error) { response, err := next(request) - if err != nil || response.StatusCode/100 != 2 || response.Body == nil { + if err != nil || response.Body == nil { return response, err } + if response.StatusCode/100 != 2 { + response.Body = struct { + io.Reader + io.Closer + }{io.LimitReader(response.Body, errorBytes), response.Body} + return response, nil + } response.Body = &eventLimit{body: http.MaxBytesReader(nil, response.Body, maxStreamBytes)} contentType := response.Header.Get("Content-Type") if eventStream(contentType) { From cc4abe8a137643735dfce4d0e0790eef97eec6d9 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 18:11:21 -0500 Subject: [PATCH 06/16] AI-4057: keep the debug copy of the stream to whole characters, without a joined copy Co-Authored-By: Claude Opus 5.5 --- .../internal/llm/openaicompat/limit_test.go | 13 +++++++++++++ .../internal/llm/openaicompat/openaicompat.go | 16 ++++++++++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index 2c326dd9ee..9eaa849cd0 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -338,3 +338,16 @@ func (s *OpenAICompatSuite) TestTheStreamIsKeptForTheLogOnlyWhenDebugIsOn() { } } } + +func (s *OpenAICompatSuite) TestTheStreamKeptForTheLogEndsOnAWholeCharacter() { + for _, text := range []string{"é", "日本", "👋"} { + p := &puller{debug: true} + p.keep(strings.Repeat("c", rawBytes-1)) + p.keep(text) + s.Equal(strings.Repeat("c", rawBytes-1), p.raw.String(), "a character the limit would cut is left out whole") + } + p := &puller{debug: true} + p.keep(strings.Repeat("c", rawBytes)) + p.keep("\xa9 a byte that starts no character") + s.Len(p.raw.String(), rawBytes) +} diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index c2bed224b2..6815ddddea 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -29,6 +29,7 @@ import ( "sync" "sync/atomic" "time" + "unicode/utf8" "github.com/openai/openai-go/v3" "github.com/openai/openai-go/v3/option" @@ -687,7 +688,8 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { for _, choice := range chunk.Choices { p.keep(choice.Delta.Content) for _, call := range choice.Delta.ToolCalls { - p.keep(call.Function.Name + call.Function.Arguments) + p.keep(call.Function.Name) + p.keep(call.Function.Arguments) } p.text(w, choice.Delta.Content) w.ReasoningText(reasoning(choice.Delta.JSON.ExtraFields)) @@ -723,11 +725,17 @@ func (p *puller) size(chunk openai.ChatCompletionChunk) int { return n } -// keep adds text to the debug log's copy of the stream, up to rawBytes. +// keep adds text to the debug log's copy of the stream, up to rawBytes and the last whole +// character before it. func (p *puller) keep(text string) { - if p.debug { - p.raw.WriteString(text[:min(len(text), max(0, rawBytes-p.raw.Len()))]) + if !p.debug { + return + } + n := min(len(text), max(0, rawBytes-p.raw.Len())) + for n > 0 && n < len(text) && !utf8.RuneStart(text[n]) { + n-- } + p.raw.WriteString(text[:n]) } // text records a piece of the answer, as thinking when it is inside the thought channel. From 25d32343f0940a05f0272c8833dc8ff6c3f8630d Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 18:15:01 -0500 Subject: [PATCH 07/16] AI-4057: copy what the response keeps out of the JSON it was read from 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 --- .../internal/llm/openaicompat/limit_test.go | 41 +++++++++++++++++++ .../internal/llm/openaicompat/openaicompat.go | 13 +++--- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index 9eaa849cd0..4c4479e0fc 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -9,6 +9,7 @@ import ( "log/slog" "net/http" "net/http/httptest" + "runtime" "strings" "sync/atomic" "time" @@ -139,6 +140,46 @@ func (s *OpenAICompatSuite) TestAnEndpointThatOpensToolCallsWithoutEndIsCutShort } } +func (s *OpenAICompatSuite) TestWhatTheResponseHoldsStaysNearTheLimit() { + // A field the response does not read, beside each piece it does, is counted only against + // the body's limit, so the response must not keep it alive. + unread := `"unread":"` + strings.Repeat("u", 64<<10) + `",` + for name, chunk := range map[string]func(i int) string{ + "the answer": func(i int) string { + return strings.Replace(textFrame(fmt.Sprint(i)), `"content"`, unread+`"content"`, 1) + }, + "a call's id": func(i int) string { + return strings.Replace(toolFrame(i, fmt.Sprint("c", i), "", ""), `"function"`, unread+`"function"`, 1) + }, + "a call's name and arguments": func(i int) string { + return strings.Replace(toolFrame(i, "", "f", "{}"), `"function":{`, `"function":{`+unread, 1) + }, + } { + s.Run(name, func() { + i := 0 + provider, gone := s.endless(func() string { i++; return "data: " + chunk(i) + "\n\n" }) + before := liveHeap() + + response, events := s.askBounded(provider, withTools()) + + held := liveHeap() - before + s.Equal(llm.StatusIncomplete, response.Status) + s.left(gone) + s.Less(held, int64(4*maxAnswerBytes), "the response and its events hold %d bytes", held) + runtime.KeepAlive(response) + runtime.KeepAlive(events) + }) + } +} + +// liveHeap is what the heap holds once garbage is collected. +func liveHeap() int64 { + runtime.GC() + var stats runtime.MemStats + runtime.ReadMemStats(&stats) + return int64(stats.HeapAlloc) +} + func (s *OpenAICompatSuite) TestAnEndpointThatSendsAByteAChunkIsCutShort() { provider, gone := s.endless(func() string { return "data: " + textFrame("a") + "\n\n" }) diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index 6815ddddea..4726d0b9c4 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -691,14 +691,17 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { p.keep(call.Function.Name) 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 + // included, so what the response keeps is copied out of it. + p.text(w, strings.Clone(choice.Delta.Content)) w.ReasoningText(reasoning(choice.Delta.JSON.ExtraFields)) for _, call := range choice.Delta.ToolCalls { + id := strings.Clone(call.ID) w.FunctionCall( - p.slot(call.Index, call.ID), - call.ID, - call.Function.Name, - call.Function.Arguments, + p.slot(call.Index, id), + id, + strings.Clone(call.Function.Name), + strings.Clone(call.Function.Arguments), signature(call.JSON.ExtraFields), ) } From e68ac60919c7e05e66c18975d9da4ce85a39eaaf Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 18:19:41 -0500 Subject: [PATCH 08/16] AI-4057: count a chunk as at least chunkBytes rather than on top of what it carries The longest reply keeps more room, and an answer of exactly the limit still completes. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/llm/openaicompat/limit_test.go | 11 ++++------- .../internal/llm/openaicompat/openaicompat.go | 11 +++++------ 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index 4c4479e0fc..c0f65af82d 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -108,7 +108,7 @@ func (s *OpenAICompatSuite) TestAnEndpointThatNeverStopsIsCutShortAtTheLimit() { } s.LessOrEqual(held, maxAnswerBytes, "what the response holds stays within the limit") s.LessOrEqual(len(response.OutputText)+len(response.ReasoningText), maxAnswerBytes) - s.Greater(held, maxAnswerBytes-2*len(piece), "and is cut at the limit rather than before it") + s.Greater(held, maxAnswerBytes-len(piece)-callBytes, "and is cut at the limit rather than before it") s.left(gone) }) } @@ -183,11 +183,11 @@ func liveHeap() int64 { func (s *OpenAICompatSuite) TestAnEndpointThatSendsAByteAChunkIsCutShort() { provider, gone := s.endless(func() string { return "data: " + textFrame("a") + "\n\n" }) - response, events := s.askBounded(provider, hello()) + response, _ := s.askBounded(provider, hello()) s.Equal(llm.StatusIncomplete, response.Status) s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) - s.LessOrEqual(len(events), maxAnswerBytes/chunkBytes, "each chunk counts against the limit, not only what it carries") + s.LessOrEqual(len(response.OutputText), maxAnswerBytes/chunkBytes, "each chunk counts against the limit as at least chunkBytes") s.left(gone) } @@ -280,19 +280,16 @@ func (s *OpenAICompatSuite) TestAnErrorWhoseBodyNeverEndsIsReadOnlyInPart() { } func (s *OpenAICompatSuite) TestAnAnswerOfExactlyTheLimitCompletes() { - // Each chunk costs chunkBytes besides its text, so the last one is that much shorter. s.frames = make([]string, maxAnswerBytes/len(piece)) for i := range s.frames { s.frames[i] = textFrame(piece) } - text := maxAnswerBytes - len(s.frames)*chunkBytes - s.frames[len(s.frames)-1] = textFrame(piece[:len(piece)-len(s.frames)*chunkBytes]) s.Require().Equal(maxAnswerBytes, len(s.frames)*len(piece)) response, _ := s.ask(s.provider(Options{}), hello()) s.Equal(llm.StatusCompleted, response.Status) - s.Len(response.OutputText, text) + s.Len(response.OutputText, maxAnswerBytes) } func (s *OpenAICompatSuite) TestTheLongestReplyStreamedATokenAChunkCompletes() { diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index 4726d0b9c4..de3d47e402 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -64,11 +64,10 @@ const maxAnswerBytes = replyTokens * 32 // stops what Advance never sees, such as one event whose data lines never end. const maxStreamBytes = maxAnswerBytes + replyTokens*512 -// chunkBytes is what each chunk costs the limit on top of what it carries: a provider can send -// a byte a chunk, and each one is an event the response holds. At 16 the longest reply still -// fits streamed a token a chunk, as long as its tokens average 16 bytes or less of the 32 the -// limit leaves each. -const chunkBytes = 16 +// chunkBytes is the least a chunk costs the limit, whatever it carries: a provider can send a +// byte a chunk, and each one is an event the response holds. At 24 the longest reply streamed +// a token a chunk still fits, with a quarter of the limit to spare. +const chunkBytes = 24 // maxEventBytes bounds one event of the stream, which the SDK holds whole before it decodes // it: data lines with no blank line between them all join into one. Twice maxAnswerBytes leaves @@ -679,7 +678,7 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { w.Usage(usageOf(chunk.Usage)) } - if p.streamed += chunkBytes + p.size(chunk); p.streamed > maxAnswerBytes { + if p.streamed += max(chunkBytes, p.size(chunk)); p.streamed > maxAnswerBytes { // The chunk that passes the limit is dropped, so what the response holds stays under it. p.tooLong = true p.finish(w) From 21257bf7b27098ad43c4d25a6b221af805bb9f36 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 18:22:40 -0500 Subject: [PATCH 09/16] AI-4057: count each choice and each tool call fragment as at least chunkBytes One chunk can carry many choices or fragments, and each is an event the response holds. Co-Authored-By: Claude Opus 5.5 --- .../internal/llm/openaicompat/limit_test.go | 24 +++++++++++++------ .../internal/llm/openaicompat/openaicompat.go | 19 ++++++++------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index c0f65af82d..b72784da01 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -180,15 +180,25 @@ func liveHeap() int64 { return int64(stats.HeapAlloc) } -func (s *OpenAICompatSuite) TestAnEndpointThatSendsAByteAChunkIsCutShort() { - provider, gone := s.endless(func() string { return "data: " + textFrame("a") + "\n\n" }) +func (s *OpenAICompatSuite) TestAnEndpointThatSendsAByteAtATimeIsCutShort() { + many := func(n int, piece string) string { return strings.TrimSuffix(strings.Repeat(piece+",", n), ",") } + for name, chunk := range map[string]string{ + "a byte a chunk": textFrame("a"), + "a byte a choice": `{"choices":[` + many(1000, `{"delta":{"content":"a"}}`) + `]}`, + "an empty fragment of a call": `{"choices":[{"delta":{"tool_calls":[` + many(1000, `{"index":0}`) + `]}}]}`, + } { + s.Run(name, func() { + provider, gone := s.endless(func() string { return "data: " + chunk + "\n\n" }) - response, _ := s.askBounded(provider, hello()) + response, events := s.askBounded(provider, withTools()) - s.Equal(llm.StatusIncomplete, response.Status) - s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) - s.LessOrEqual(len(response.OutputText), maxAnswerBytes/chunkBytes, "each chunk counts against the limit as at least chunkBytes") - s.left(gone) + s.Equal(llm.StatusIncomplete, response.Status) + s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) + // Besides the deltas, a few events open and settle the response. + s.LessOrEqual(len(events), maxAnswerBytes/chunkBytes+8, "each piece counts against the limit as at least chunkBytes") + s.left(gone) + }) + } } func (s *OpenAICompatSuite) TestAnEventThatNeverEndsIsCutShort() { diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index de3d47e402..54c054671c 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -64,9 +64,10 @@ const maxAnswerBytes = replyTokens * 32 // stops what Advance never sees, such as one event whose data lines never end. const maxStreamBytes = maxAnswerBytes + replyTokens*512 -// chunkBytes is the least a chunk costs the limit, whatever it carries: a provider can send a -// byte a chunk, and each one is an event the response holds. At 24 the longest reply streamed -// a token a chunk still fits, with a quarter of the limit to spare. +// chunkBytes is the least each choice of a chunk and each tool call fragment cost the limit, +// whatever they carry: a provider can send a byte at a time, and each piece is an event the +// response holds. At 24 the longest reply streamed a token a chunk still fits, with a +// quarter of the limit to spare. const chunkBytes = 24 // maxEventBytes bounds one event of the stream, which the SDK holds whole before it decodes @@ -678,7 +679,7 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { w.Usage(usageOf(chunk.Usage)) } - if p.streamed += max(chunkBytes, p.size(chunk)); p.streamed > maxAnswerBytes { + if p.streamed += p.size(chunk); p.streamed > maxAnswerBytes { // The chunk that passes the limit is dropped, so what the response holds stays under it. p.tooLong = true p.finish(w) @@ -712,17 +713,19 @@ func (p *puller) Advance(w *llm.ResponseWriter) bool { } // size is how many bytes of answer, thinking and tool calls a chunk carries, with callBytes -// for each call it opens. +// for each call it opens and at least chunkBytes for each choice and each fragment. func (p *puller) size(chunk openai.ChatCompletionChunk) int { n := 0 for _, choice := range chunk.Choices { - n += len(choice.Delta.Content) + len(reasoning(choice.Delta.JSON.ExtraFields)) + m := len(choice.Delta.Content) + len(reasoning(choice.Delta.JSON.ExtraFields)) for _, call := range choice.Delta.ToolCalls { - n += len(call.ID) + len(call.Function.Name) + len(call.Function.Arguments) + len(signature(call.JSON.ExtraFields)) + c := len(call.ID) + len(call.Function.Name) + len(call.Function.Arguments) + len(signature(call.JSON.ExtraFields)) if p.opens(call.Index, call.ID) { - n += callBytes + c += callBytes } + m += max(chunkBytes, c) } + n += max(chunkBytes, m) } return n } From 5df5c0925e1bd535fa7c6028b326759f8b547a72 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 18:30:21 -0500 Subject: [PATCH 10/16] AI-4057: test that the debug log shows tool calls as they streamed Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/llm/openaicompat/limit_test.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index b72784da01..b2ebffe1bf 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -374,6 +374,16 @@ func (s *OpenAICompatSuite) TestTheDebugLogShowsTheStartOfTheStream() { s.NotContains(line, "the end", "the log keeps the first rawBytes of the stream only") } +func (s *OpenAICompatSuite) TestTheDebugLogShowsToolCallsAsTheyStreamed() { + s.frames = []string{toolFrame(0, "call_1", "lookup", "abc"), toolFrame(0, "", "", "def")} + var logged bytes.Buffer + provider := s.provider(Options{Logger: slog.New(slog.NewTextHandler(&logged, &slog.HandlerOptions{Level: slog.LevelDebug}))}) + + s.ask(provider, withTools()) + + s.Contains(logged.String(), "raw=lookupabcdef") +} + func (s *OpenAICompatSuite) TestTheStreamIsKeptForTheLogOnlyWhenDebugIsOn() { for _, debug := range []bool{false, true} { p := &puller{debug: debug} From dca0aca0a868593819ceae19dcd7e90ef135de9c Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 18:35:24 -0500 Subject: [PATCH 11/16] AI-4057: bound one event of the stream by the answer limit Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/llm/openaicompat/openaicompat.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index d9e8123718..5c07e4a9dc 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -71,9 +71,10 @@ const maxStreamBytes = maxAnswerBytes + replyTokens*512 const chunkBytes = 24 // maxEventBytes bounds one event of the stream, which the SDK holds whole before it decodes -// it: data lines with no blank line between them all join into one. Twice maxAnswerBytes leaves -// room for an event that carries the whole answer, escaped in JSON. -const maxEventBytes = 2 * maxAnswerBytes +// it: data lines with no blank line between them all join into one. One event cannot usefully +// carry more answer than the whole response may hold, and a real reply sent whole in one event, +// at a few bytes a token even once escaped in JSON, stays well under maxAnswerBytes. +const maxEventBytes = maxAnswerBytes // callBytes is what a tool call costs the limit on top of its text: a provider can open a new // call with a fragment of a few bytes, and each one is a call the response holds, with an id From 64acc9eb9d057ee6342c598232f237bb2efa13c7 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 19:12:34 -0500 Subject: [PATCH 12/16] AI-4057: check an event's limit before its end resets the count Co-Authored-By: Claude Opus 5.5 --- .../internal/llm/openaicompat/limit_test.go | 22 +++++++++++++++++++ .../internal/llm/openaicompat/openaicompat.go | 4 ++++ 2 files changed, 26 insertions(+) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index b2ebffe1bf..caad53ec00 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -233,6 +233,28 @@ func (s *OpenAICompatSuite) TestAnEventThatNeverEndsIsCutShort() { } } +func (s *OpenAICompatSuite) TestAnEventOfTheLimitCompletesAndOnePastIsCutShort() { + // A field the response does not read pads the event, so only the event's limit decides. + head, tail := `{"padding":"`, `","choices":[{"delta":{"content":"a"}}]}` + for name, tc := range map[string]struct { + counted int + want llm.ResponseStatus + }{ + "at the limit": {maxAnswerBytes, llm.StatusCompleted}, + "one byte past it": {maxAnswerBytes + 1, llm.StatusIncomplete}, + } { + s.Run(name, func() { + // Every byte of the event's lines counts but the line feeds, "data: " included. + pad := tc.counted - len("data: ") - len(head) - len(tail) + s.frames = []string{head + strings.Repeat("p", pad) + tail, textFrame("b")} + + response, _ := s.ask(s.provider(Options{}), hello()) + + s.Equal(tc.want, response.Status) + }) + } +} + func (s *OpenAICompatSuite) TestABodyPastTheLimitIsCutShort() { // Bytes outside the answer, such as a field the response does not read, count only against // the body's limit. diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index 5c07e4a9dc..07c728ff60 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -456,6 +456,10 @@ func (e *eventLimit) Read(b []byte) (int, error) { e.line, e.event, e.cr = e.line+1, e.event+1, c == '\r' continue } + // The event this line ends may have passed the limit in this read, before it is reset. + if e.event > maxEventBytes { + return n, &http.MaxBytesError{Limit: maxEventBytes} + } if e.line == 0 || (e.line == 1 && e.cr) { e.event = 0 } From e6a2c11f51196e28dfb64806102d6d956998f93b Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 19:14:26 -0500 Subject: [PATCH 13/16] AI-4057: bound the JSON values one event of the stream holds Co-Authored-By: Claude Opus 5.5 --- .../internal/llm/openaicompat/limit_test.go | 59 +++++++++++++++++++ .../internal/llm/openaicompat/openaicompat.go | 41 +++++++++---- 2 files changed, 90 insertions(+), 10 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index caad53ec00..3cb1362518 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -3,6 +3,7 @@ package openaicompat import ( "bytes" "context" + "encoding/json" "errors" "fmt" "io" @@ -255,6 +256,64 @@ func (s *OpenAICompatSuite) TestAnEventOfTheLimitCompletesAndOnePastIsCutShort() } } +func (s *OpenAICompatSuite) TestAnEventOfManySmallValuesIsCutShort() { + // Each choice is a few bytes, so the event is well under maxEventBytes and its choices + // under the answer limit, but the SDK would decode each into a struct of its own. + many := strings.TrimSuffix(strings.Repeat(`{"delta":{"content":"a"}},`, 20_000), ",") + provider, gone := s.endless(func() string { return `data: {"choices":[` + many + "]}\n\n" }) + + response, _ := s.askBounded(provider, hello()) + + s.Equal(llm.StatusIncomplete, response.Status) + s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) + s.Empty(response.OutputText, "the event is refused before it is decoded") + s.left(gone) +} + +func (s *OpenAICompatSuite) TestAnEventOfTheValueLimitCompletesAndOnePastIsCutShort() { + for name, tc := range map[string]struct { + values int + want llm.ResponseStatus + }{ + "at the limit": {maxEventValues, llm.StatusCompleted}, + "one value past it": {maxEventValues + 1, llm.StatusIncomplete}, + } { + s.Run(name, func() { + // The chunk opens 4 values, '{' '[' '{' '{', and ',"x":[' 2 more; the list's + // commas are the rest, one fewer than its items. + items := tc.values - 6 + 1 + list := strings.TrimSuffix(strings.Repeat("0,", items), ",") + s.frames = []string{`{"choices":[{"delta":{"content":"a"}}],"x":[` + list + `]}`, textFrame("b")} + + response, _ := s.ask(s.provider(Options{}), hello()) + + s.Equal(tc.want, response.Status) + }) + } +} + +func (s *OpenAICompatSuite) TestARealEventOfManyCharactersOrCallsCompletes() { + // Code in a tool call's arguments holds braces, commas and escaped quotes, all inside + // a JSON string, sent whole in one event. + code, err := json.Marshal(map[string]string{"code": strings.Repeat(`f(a, {b: [1, "c\\"]}), `, 20_000)}) + s.Require().NoError(err) + var calls []string + for i := range 200 { + calls = append(calls, fmt.Sprintf(`{"index":%d,"id":"call_%d","type":"function","function":{"name":"lookup","arguments":"{\"q\":%d}"}}`, i+1, i, i)) + } + s.frames = []string{ + toolFrame(0, "c0", "write", string(code)), + `{"choices":[{"index":0,"delta":{"tool_calls":[` + strings.Join(calls, ",") + `]}}]}`, + } + + response, _ := s.ask(s.provider(Options{}), withTools()) + + s.Equal(llm.StatusCompleted, response.Status) + s.Require().Len(response.ToolCalls, 201) + s.Equal(string(code), response.ToolCalls[0].Arguments, "the arguments arrive whole") + s.Equal(`{"q":199}`, response.ToolCalls[200].Arguments) +} + func (s *OpenAICompatSuite) TestABodyPastTheLimitIsCutShort() { // Bytes outside the answer, such as a field the response does not read, count only against // the body's limit. diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index 07c728ff60..145fffe96d 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -76,6 +76,15 @@ const chunkBytes = 24 // 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 ',' +// outside strings. The SDK decodes an event into a struct for each value, and each takes far +// more memory than the few bytes it can arrive in, so an event under maxEventBytes could still +// hold far more than the answer limit. params asks for one choice and no logprobs, so a real +// chunk holds about 20 values even with usage, and one that opens 200 tool calls at once about +// 1,400. Text inside a string, such as a tool call's arguments with their braces +// 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 // call with a fragment of a few bytes, and each one is a call the response holds, with an id // generated for it. 256 is about what that record takes, so the calls a response holds stay @@ -438,15 +447,17 @@ func (l *LLM) sniff(refused *error) option.Middleware { } } -// eventLimit fails a body once one event in it passes maxEventBytes, as MaxBytesReader fails -// one past its limit, so the response ends the same way. An event ends at an empty line, or -// one of a lone carriage return, as the SDK splits them. +// eventLimit fails a body once one event in it passes maxEventBytes or maxEventValues, as +// MaxBytesReader fails one past its limit, so the response ends the same way. An event ends at +// an empty line, or one of a lone carriage return, as the SDK splits them. type eventLimit struct { body io.ReadCloser // line and event count the bytes since the last line and event ended, and cr is whether - // the last of them was a carriage return. - line, event int - cr bool + // the last of them was a carriage return. values counts the event's JSON values; quoted + // and escaped are whether a string, and an escape in it, is open. A string cannot hold a + // line feed, so a line ends any string. + line, event, values int + cr, quoted, escaped bool } func (e *eventLimit) Read(b []byte) (int, error) { @@ -454,18 +465,28 @@ func (e *eventLimit) Read(b []byte) (int, error) { for _, c := range b[:n] { if c != '\n' { e.line, e.event, e.cr = e.line+1, e.event+1, c == '\r' + switch { + case e.escaped: + e.escaped = false + case e.quoted: + e.quoted, e.escaped = c != '"', c == '\\' + case c == '"': + e.quoted = true + case c == '{' || c == '[' || c == ',': + e.values++ + } continue } // The event this line ends may have passed the limit in this read, before it is reset. - if e.event > maxEventBytes { + if e.event > maxEventBytes || e.values > maxEventValues { return n, &http.MaxBytesError{Limit: maxEventBytes} } if e.line == 0 || (e.line == 1 && e.cr) { - e.event = 0 + e.event, e.values = 0, 0 } - e.line = 0 + e.line, e.quoted, e.escaped = 0, false, false } - if e.event > maxEventBytes { + if e.event > maxEventBytes || e.values > maxEventValues { return n, &http.MaxBytesError{Limit: maxEventBytes} } return n, err From c8e11085a2ba490dbbb100cab1ef0146b1e1b59d Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 19:17:48 -0500 Subject: [PATCH 14/16] AI-4057: end the stream before an event past a limit is decoded Co-Authored-By: Claude Opus 5.5 --- .../internal/llm/openaicompat/limit_test.go | 37 +++++++++++++------ .../internal/llm/openaicompat/openaicompat.go | 5 ++- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index 3cb1362518..d4d6343e80 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -240,9 +240,11 @@ func (s *OpenAICompatSuite) TestAnEventOfTheLimitCompletesAndOnePastIsCutShort() for name, tc := range map[string]struct { counted int want llm.ResponseStatus + text string }{ - "at the limit": {maxAnswerBytes, llm.StatusCompleted}, - "one byte past it": {maxAnswerBytes + 1, llm.StatusIncomplete}, + "at the limit": {maxAnswerBytes, llm.StatusCompleted, "ab"}, + // The stream ends before the event is decoded. + "one byte past it": {maxAnswerBytes + 1, llm.StatusIncomplete, ""}, } { s.Run(name, func() { // Every byte of the event's lines counts but the line feeds, "data: " included. @@ -252,31 +254,41 @@ func (s *OpenAICompatSuite) TestAnEventOfTheLimitCompletesAndOnePastIsCutShort() response, _ := s.ask(s.provider(Options{}), hello()) s.Equal(tc.want, response.Status) + s.Equal(tc.text, response.OutputText) }) } } func (s *OpenAICompatSuite) TestAnEventOfManySmallValuesIsCutShort() { // Each choice is a few bytes, so the event is well under maxEventBytes and its choices - // under the answer limit, but the SDK would decode each into a struct of its own. - many := strings.TrimSuffix(strings.Repeat(`{"delta":{"content":"a"}},`, 20_000), ",") - provider, gone := s.endless(func() string { return `data: {"choices":[` + many + "]}\n\n" }) + // under the answer limit, but the SDK would decode each into a struct of its own. params + // asks for one choice, and 2,000 is far more than any real chunk carries. + many := strings.TrimSuffix(strings.Repeat(`{"delta":{"content":"a"}},`, 2_000), ",") + for name, before := range map[string]string{ + "an event": "", + "after a comment with an open quote": ": \"\n", + } { + s.Run(name, func() { + provider, gone := s.endless(func() string { return before + `data: {"choices":[` + many + "]}\n\n" }) - response, _ := s.askBounded(provider, hello()) + response, _ := s.askBounded(provider, hello()) - s.Equal(llm.StatusIncomplete, response.Status) - s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) - s.Empty(response.OutputText, "the event is refused before it is decoded") - s.left(gone) + s.Equal(llm.StatusIncomplete, response.Status) + s.Equal(llm.ReasonMaxOutputTokens, response.IncompleteReason) + s.Empty(response.OutputText, "the event is refused before it is decoded") + s.left(gone) + }) + } } func (s *OpenAICompatSuite) TestAnEventOfTheValueLimitCompletesAndOnePastIsCutShort() { for name, tc := range map[string]struct { values int want llm.ResponseStatus + text string }{ - "at the limit": {maxEventValues, llm.StatusCompleted}, - "one value past it": {maxEventValues + 1, llm.StatusIncomplete}, + "at the limit": {maxEventValues, llm.StatusCompleted, "ab"}, + "one value past it": {maxEventValues + 1, llm.StatusIncomplete, ""}, } { s.Run(name, func() { // The chunk opens 4 values, '{' '[' '{' '{', and ',"x":[' 2 more; the list's @@ -288,6 +300,7 @@ func (s *OpenAICompatSuite) TestAnEventOfTheValueLimitCompletesAndOnePastIsCutSh response, _ := s.ask(s.provider(Options{}), hello()) s.Equal(tc.want, response.Status) + s.Equal(tc.text, response.OutputText) }) } } diff --git a/acceleration/internal/llm/openaicompat/openaicompat.go b/acceleration/internal/llm/openaicompat/openaicompat.go index 145fffe96d..d65588abb0 100644 --- a/acceleration/internal/llm/openaicompat/openaicompat.go +++ b/acceleration/internal/llm/openaicompat/openaicompat.go @@ -462,7 +462,7 @@ type eventLimit struct { func (e *eventLimit) Read(b []byte) (int, error) { n, err := e.body.Read(b) - for _, c := range b[:n] { + for i, c := range b[:n] { if c != '\n' { e.line, e.event, e.cr = e.line+1, e.event+1, c == '\r' switch { @@ -478,8 +478,9 @@ func (e *eventLimit) Read(b []byte) (int, error) { continue } // The event this line ends may have passed the limit in this read, before it is reset. + // The line feed is held back, so the SDK never sees the event end and never decodes it. if e.event > maxEventBytes || e.values > maxEventValues { - return n, &http.MaxBytesError{Limit: maxEventBytes} + return i, &http.MaxBytesError{Limit: maxEventBytes} } if e.line == 0 || (e.line == 1 && e.cr) { e.event, e.values = 0, 0 From 80c0d99d74ec550aea76961c391fd161744199a5 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 19:41:09 -0500 Subject: [PATCH 15/16] AI-4057: test an event split over many data lines past the value limit 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 --- acceleration/internal/llm/openaicompat/limit_test.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index d4d6343e80..f62d93e364 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -264,12 +264,16 @@ func (s *OpenAICompatSuite) TestAnEventOfManySmallValuesIsCutShort() { // under the answer limit, but the SDK would decode each into a struct of its own. params // asks for one choice, and 2,000 is far more than any real chunk carries. many := strings.TrimSuffix(strings.Repeat(`{"delta":{"content":"a"}},`, 2_000), ",") - for name, before := range map[string]string{ - "an event": "", - "after a comment with an open quote": ": \"\n", + // The same choices, one per data line: the SDK joins the lines into one event. + oneLineEach := "data: {\"choices\":[\n" + strings.Repeat("data: {\"delta\":{\"content\":\"a\"}},\n", 1999) + + "data: {\"delta\":{\"content\":\"a\"}}]}\n\n" + for name, body := range map[string]string{ + "an event": `data: {"choices":[` + many + "]}\n\n", + "after a comment with an open quote": ": \"\n" + `data: {"choices":[` + many + "]}\n\n", + "over many data lines": oneLineEach, } { s.Run(name, func() { - provider, gone := s.endless(func() string { return before + `data: {"choices":[` + many + "]}\n\n" }) + provider, gone := s.endless(func() string { return body }) response, _ := s.askBounded(provider, hello()) From f4fa8721f0df303c2a7b7c8b832f87a233fb542c Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 20:22:55 -0500 Subject: [PATCH 16/16] [AI-4057] Reach the body limit faster in its test under -race 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 --- .../internal/llm/openaicompat/limit_test.go | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/acceleration/internal/llm/openaicompat/limit_test.go b/acceleration/internal/llm/openaicompat/limit_test.go index f62d93e364..124ed9f353 100644 --- a/acceleration/internal/llm/openaicompat/limit_test.go +++ b/acceleration/internal/llm/openaicompat/limit_test.go @@ -57,9 +57,10 @@ func (s *OpenAICompatSuite) endlessAs(contentType string, next func() string) (* } // askBounded is ask under a deadline, so a stream that is never cut short fails the test in -// seconds rather than running for the whole response timeout. +// seconds rather than running for the whole response timeout. The deadline is far above the +// longest a cut takes (about 8s under -race on 2 CPUs), and far below the test timeout. func (s *OpenAICompatSuite) askBounded(provider *LLM, params llm.ResponseParams) (llm.Response, []llm.Event) { - ctx, cancel := context.WithTimeout(s.T().Context(), 10*time.Second) + ctx, cancel := context.WithTimeout(s.T().Context(), 60*time.Second) defer cancel() stream, err := provider.Create(ctx, params) s.Require().NoError(err) @@ -334,10 +335,21 @@ func (s *OpenAICompatSuite) TestARealEventOfManyCharactersOrCallsCompletes() { func (s *OpenAICompatSuite) TestABodyPastTheLimitIsCutShort() { // Bytes outside the answer, such as a field the response does not read, count only against // the body's limit. - chunk := strings.Replace(textFrame("a"), `"choices"`, `"padding":"`+strings.Repeat("p", 256<<10)+`","choices"`, 1) + // The padding is comment lines, which the stream skips without decoding, so what the + // test waits on is the body being read, not parsed: under -race on a small runner, + // decoding padding inside a chunk made the limit slow to reach. + padding := ": " + strings.Repeat("p", 1<<20) + "\n\n" for _, contentType := range []string{"text/event-stream", "text/plain"} { s.Run(contentType, func() { - provider, gone, sent := s.endlessAs(contentType, func() string { return "data: " + chunk + "\n\n" }) + // The first chunk opens a data field, so the body reads as an event stream. + opened := false + provider, gone, sent := s.endlessAs(contentType, func() string { + if !opened { + opened = true + return "data: " + textFrame("a") + "\n\n" + } + return padding + }) response, _ := s.askBounded(provider, hello())