Skip to content

feat(proxy): stream Chat Completions answers with our tool search (#879) - #883

Merged
amiddavid merged 2 commits into
mainfrom
feat/stream-splice-879
Nov 4, 2026
Merged

amiddavid merged 2 commits into
mainfrom
feat/stream-splice-879

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change (needs a human developer's yes before merge)

Live, gpt-5.5, plain gateway: on main the first content byte arrived at 100% of wall time on every request. With this PR, an answer that writes text and then searches shows its first words at 21% to 48% of wall time (2.1 s to 3.2 s, against 5.1 s to 10.6 s wall).

This PR reuses the sseSplicer (proxy/ssepeek.go). It adds no second splicer.

Summary

  • feat(tooldefer): our own tool search for models without defer_loading (#825) #875 answers our search in band. On Chat Completions it held the whole stream to do it.
  • The sseSplicer already forwards Anthropic events as they arrive, and holds from the first event of a call to a proxy tool. This PR teaches it the Chat Completions chunk format.
  • Only 3 parts depend on the format: how a call is found, how a later round is renumbered, and how the stream is closed. Holding, the hand-back, the splice and the retain bound are shared.

What changed

  • proxy/ssepeek.go:
    • newChatSSESplicer: the same sseSplicer, with a chat flag.
    • chatProxyToolCallName: finds a call to a proxy tool. In Chat Completions, a call's name arrives on the first chunk of choices[].delta.tool_calls[] for its index. Later chunks carry only arguments, so they never match.
    • rewriteChat: round 1's chunks go out byte for byte. A follow-up round's chunks get round 1's chunk id, and their tool-call index moves past the calls the client already holds. So the client reads one answer.
    • terminateChat: if the follow-up has no end, it sends the held round's closing chunks (finish_reason, usage, [DONE]), never a chunk with the held call. With no end anywhere, it sends an error chunk.
    • opened(): the client holds text or a call. A round that opens with our call counts as buffered on /stats, as on Anthropic.
  • proxy/proxy.go, the serve loop:
    • A Chat Completions stream that declares our search goes through the splicer. context_guru_tools is added to the tools that pass holds.
    • feat(tooldefer): our own tool search for models without defer_loading (#825) #875's full-buffer branch for Chat Completions is removed.
    • The rest of the loop does not change: a search alone is answered in band (with AppendTools), a search with a client tool call is handed back whole, and the next request answers it.
    • MarkInBandFollowUp stays where it was. It does nothing on OpenAI, which caches automatically.
  • A held call of ours that reaches the client is not counted as an sse_*_after_stream leak. mixed_searches and the stored call record already count it, so a second counter would count it twice.
  • A follow-up round's reasoning_content streams to the client after round 1's text. The splicer keeps it: it is the model's own output, and dropping it loses data.
  • Responses API: no change, follow-up Stream Responses API answers with our tool search (follow-up to #879) #884. In a deferred thread, our search still holds the whole Responses stream. Finding our call would fit: its name arrives in response.output_item.added. The splice does not fit the sseSplicer cleanly:
    • response.completed carries the whole output array. A spliced stream needs ONE such event that merges both rounds, so the splicer would build an event, not only forward one.
    • The client chains its next turn on the response id (previous_response_id). Only the follow-up's stored response has our answer and the loaded tool. Which id the client gets is a behavior choice, not a rewrite.
    • Every event carries a sequence_number, which must stay in order across both rounds.

Fail open

  • A chunk that does not parse goes out as it came. It does not hide a later call of ours.
  • A stream that will not rebuild, a follow-up that will not build, the round cap or an upstream error: the client gets the held bytes as they came (handBack), as on Anthropic. No byte is dropped.
  • Past the 16 MB retain bound, the round goes out whole and nothing is held.

Data dependence

None. Nothing new is stored. docs/data-dependence.md does not change.

How it was tested

  • Unit tests, proxy/ssepeek_chat_test.go, with recorded gpt-5.5 chunk shapes:
    • text only, reasoning then text, a call to another tool: the client gets the stream byte for byte;
    • our call alone: the text before it streams at once, the call is held, the follow-up is spliced with one id and index 0, and the stream rebuilds to the loaded tool's call;
    • our call first: counted as buffered;
    • a mixed answer: the client's call streams, and prefix + hand-back gives the stream byte for byte;
    • a later round's indexes and id;
    • a malformed chunk; a truncated turn (error chunk); the retain bound; detection on argument and text chunks.
  • End to end, proxy/tooldefer_search_test.go, with a streaming upstream: the in-band splice, a text answer byte for byte in one round, and the mixed call.
  • Mutations. Each one failed tests, and the tests passed again after the restore:
    1. Detection off: 9 tests fail.
    2. No index shift on a later round: TestChatSpliceRenumbersALaterRound fails.
    3. No hand-back on Chat: 4 tests fail (mixed, malformed, retain bound, end-to-end mixed).
  • Race tests on the eval box, all ok:
    • CGO_ENABLED=1 go test -race -count=1 ./expand/... ./schema/... ./tooldefer/...
    • CGO_ENABLED=1 go test -race -count=1 ./proxy/... (484 s)
    • After those runs, one comment in proxy/proxy.go changed. No code changed.
  • Live check. Local builds of main and of this branch with --preset ultrahigh, against the plain gateway (not Context Guru), gpt-5.5, stream: true, a nonce in every prompt. Each request had its own tool names and 3 seeded sessions, so 3 large tools were deferred on every request. Times are first content byte / wall, in seconds:
Answer main (#875, full buffering) This PR
Text, no tool 2.98 / 2.98, 2.36 / 2.36, 2.06 / 2.06 1.52 / 2.02, 2.85 / 3.38, 1.85 / 2.41
Opens with our search, then the loaded tool 5.08 / 5.08 9.60 / 9.67, 4.42 / 4.48
Text, then our search, then the loaded tool 9.23 / 9.23, 6.95 / 6.95 3.24 / 6.78, 2.18 / 10.62, 2.08 / 5.06
  • Rows with fewer runs: the model sometimes called get_order instead of searching. Those runs are left out.
  • Every client stream on this PR: one chunk id, one [DONE], tool-call indexes from 0, no context_guru_tools call, and the loaded tool called with {"order_id":"ORD-42"}.
  • An answer that opens with our search waits for the follow-up on both builds. That is expected: there is no text to send first.
  • /stats on this PR: add_backs: 5, mixed_searches: 0.
  • Spend: under $0.50. The captured state and the binaries were deleted after the run.
  • GLM and Kimi are covered by unit tests only (their reasoning_content chunks). Not tested live: GLM, Kimi, and a real agent client.

Open questions

Technical notes

Fixes #879

🤖 Generated with Claude Code

In ultrahigh threads with deferred tools on models that are not Claude,
the proxy held the whole Chat Completions stream to answer a call to
context_guru_tools (#875). Now the sseSplicer, which already does this
for Anthropic streams, also reads Chat Completions chunks. Text and
reasoning stream at once. The splicer holds only from the first chunk of
a call to a proxy tool, and splices the in-band follow-up into the same
stream with round 1's chunk id and shifted tool-call indexes.

Fixes #879

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.317 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 537a5847cc24 blocking

Verdict: blocking

Findings

  1. proxy/ssepeek.go:600 — a truncated single-round Chat stream gets no terminator and no error chunk
    • What fails: the upstream dies mid-stream in round 1 (no finish_reason, no [DONE]), and the round called no proxy tool. pass returns withheld=nil. The serve loop calls sp.terminate(prevWithheld) with prevWithheld=nil (proxy/proxy.go:2236). terminate passes the !sp.ended check (ssepeek.go:463), but terminateChat returns early at line 600 (withheld == nil && sp.rounds <= 1). The client's stream ends with no [DONE] and no error chunk. It cannot tell a truncated answer from a complete one.
    • Proof: terminate only reaches terminateChat when !sp.ended, so the stream did not close. The guard's comment ("the client got the upstream's bytes, exactly") is wrong in exactly this state: the bytes are a partial answer. The Anthropic twin sends an error event in the same state (ssepeek.go:484-495, the !sp.ended fallback in terminate), and terminateChat itself sends the error chunk when rounds > 1 with withheld == nil (the loop over a nil reader falls to line 624). So round 1 truncated = silence, round 2 truncated = error chunk. terminateChat's own doc (ssepeek.go:596-598, "With no [DONE] anywhere, it ends the stream with an error chunk") does not hold for round 1. TestChatSpliceTerminatesATruncatedTurn covers only the two-round case.
    • Fix: drop the sp.rounds <= 1 half of the guard. With withheld == nil the reader is empty, the loop falls through to the !sp.ended check, and a truncated round 1 gets the same error chunk as every other round. A stream that ended cleanly is already excluded by the sp.ended check in terminate. Add a one-round truncation test.

Non-blocking

  • proxy/proxy.go:1821 — a leaked search call is counted nowhere on two paths. countLeak no-ops for ClientSearchName ("counted where it is decided"). Past sseRetainMaxBytes (proxy.go:2230-2237) and after an AggregateSSE failure (bail), the client receives the raw call and neither MixedSearches nor noteSearchCalls runs. The call is still answered on the next request (repairSearchResults scans the transcript itself, tooldefer/clientsearch.go:630-691), so the impact is observability only. The old buffered path behaved the same on the aggregation failure, but the retain bound is new for this dialect.
  • proxy/ssepeek.go:572 — reasoning under delta.reasoning leaves said false. rewriteChat only reads content and reasoning_content. A gateway that streams reasoning as delta.reasoning (some OpenAI-compatible ones do) keeps said=false, so opened() misfiles a streamed answer as buffered (proxy.go:2148-2154). Metric mislabel only; the splice itself is unaffected.
  • proxy/ssepeek.go:234-237 — pass parses the Anthropic shape first, then throws it away. For a chat splicer, proxyToolCallName runs before chatProxyToolCallName overwrites it. The cheap reject makes this near-free; noting it only because the code reads as if both were needed.
  • proxy/ssepeek.go:504 — a delta that batches two calls withholds the client's bytes too. Chat Completions allows several tool_calls entries in one delta. If a gateway puts a client call's arguments and our call's first chunk in one delta, the whole chunk is withheld and the client call's arguments reach the client only on hand-back. OpenAI and the gateways I know emit one entry per chunk, so this stays a note.

What I checked

  • Read the full diff (proxy/proxy.go, proxy/ssepeek.go, proxy/ssepeek_chat_test.go, proxy/tooldefer_search_test.go) and the code around each change: the whole serve loop, all of ssepeek.go, applyClientSearch and the note/search helpers in proxy/tooldefer.go, ApplySearch/repairSearchResults/NoteCalls in tooldefer/clientsearch.go, WireFor in schema/wire.go, AggregateSSE in expand/sse.go.
  • Traced the case selection: wire == WireOpenAI implies provider == openai (WireFor returns the provider), so the Anthropic-vs-chat splicer choice cannot mix dialects. di.search is set only for provider == OpenAI on a client wire (proxy/tooldefer.go:394), so Responses-with-search still buffers (unchanged case), and no other provider loses the old isSSE && searchOn buffering.
  • Traced round 2+ splicing: rounds counts only rounds that reached sp.round (a failed doUpstream does not), so a hand-back after an upstream failure stays verbatim (later=false). Index shift, id rewrite, opened(), prevWithheld and every bail site (round cap, aggregation failure, mixed call, upstream failure mid-stream, retain bound) walked line by line.
  • Checked the finish_reason byte-pattern against escaped JSON strings in content and arguments: the backslash before the quote breaks the match, so no false ended from model text.
  • Checked the fail-open rules: every bail hands the withheld bytes back, handBack forwards them through rewriteChat, and nothing is dropped on the success path that the client needs (round 1's usage chunk is dropped, same as the Anthropic splice drops round 1's message_delta).
  • Live tests were not approved, so I did not build or run anything. The new tests (7 splicer tests, 3 end-to-end streamed tests) cover the main paths; the one-round truncation path in finding 1 is the gap.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.317 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 537a5847cc24 blocking

Verdict: blocking

One finding. It is narrow: it needs an upstream that cuts a stream mid-answer. Everything else I
checked holds, including the fail-open paths and the byte-exact pass-through.

Findings

  1. proxy/ssepeek.go:600 — a truncated one-round Chat stream ends with no terminator and no error chunk
    • What fails: round 1, no call to a proxy tool, the upstream cuts the body mid-answer (no
      finish_reason, no [DONE]). The client's stream just stops. It gets no [DONE] and no
      error chunk, so it cannot tell a cut answer from a complete one. The Anthropic path sends an
      error event for the same input (ssepeek.go:483-495), and the PR text promises the same:
      "With no [DONE] anywhere, it ends the stream with an error chunk."
    • Proof: trace the round. pass keeps cut = -1 (no proxy call), hits the read error, and
      returns withheld = nil (ssepeek.go:263-271). serve then runs
      sp.terminate(prevWithheld) with prevWithheld = nil, because round 1 had nothing to keep
      (proxy/proxy.go:2230-2237). terminate passes its guard: ended is false (no [DONE], no
      string finish_reason was forwarded) and msgStart is true (ssepeek.go:462-469).
      terminateChat(nil) returns at withheld == nil && sp.rounds <= 1 (ssepeek.go:600-602),
      before the error chunk at ssepeek.go:624-627. The guard's comment, "the client got the
      upstream's bytes, exactly", is false for a truncated stream: the client got a partial answer
      with no marker that it is partial.
    • Fix: the ambiguity is real — a gateway may also close cleanly after a complete answer that
      omits [DONE], which the early return protects on purpose (PR technical notes). But pass
      can tell the two apart: readSSEEvent returns a read error with a non-empty partial event
      only when the cut landed mid-event. Have pass report that fact, and let terminateChat
      keep the early return only for a clean close. A cut stream then gets the error chunk, as on
      Anthropic and as documented.

Non-blocking

  • ssepeek.go:549 — the finish_reason test is a byte scan of the whole chunk. A content chunk
    whose text contains "finish_reason":" (an agent writing OpenAI SDK code) sets ended without a
    real finish. Harm is confined to terminate: a later truncation then sends no error chunk, and a
    withheld round's [DONE] is not forwarded. Consider parsing choices[].finish_reason on chunks
    already being parsed.
  • ssepeek.go:572 — said misses reasoning under a non-standard key. A gateway that streams
    reasoning as reasoning (not reasoning_content) leaves said false, so a round that opened
    with reasoning and then our call counts as sse_buffered and zeroes the TTFB. Metric only; the
    bytes are correct. The gateway used live (gpt-5.5) and GLM/Kimi use reasoning_content.
  • ssepeek.go:599-631 — bail can forward closing chunks twice. bail runs handBack(withheld)
    then terminate(withheld) over the same bytes. When the withheld round was truncated (no
    [DONE], no finish_reason), terminateChat re-forwards its closing chunks (for example the
    usage chunk) before the error chunk. The Anthropic path has the same shape with message_delta,
    so this is inherited, and a repeated usage chunk is harmless.
  • proxy/proxy.go:1821-1822 — the countLeak comment overstates the cover. Past the 16 MB retain
    bound a leaked search call reaches the client with no counter and no noteLeakedSearches call.
    The next request still answers it, because repairSearchResults re-reads the call from the
    transcript on the Chat wire. Worth one sentence in the comment, not more.
  • Test gap. No test covers a follow-up round that streams text (all follow-up rounds in the
    tests call tools), and none covers a truncated round 1 without a call — the finding above.

What I checked

  • The full diff (proxy/proxy.go, proxy/ssepeek.go, both test files) and the code around each
    change: the whole serve round loop, ssepeek.go in full, schema/wire.go, tooldefer
    (ApplySearch, repairSearchResults, HasClientSearch, ClientWire), expand.AggregateSSE
    (aggregateChatSSE).
  • Wire routing: the splice case fires only for wire == WireOpenAI (Chat Completions). Responses
    keeps its old buffered path, because WireFor never returns WireOpenAI for a Responses route.
    searchOn can only be true on a client wire, so no dialect falls between the cases.
  • Byte-exactness: round 1 with no proxy call passes through untouched (fast path returns the event
    verbatim; parsed chunks rebuild np == payload). The mixed hand-back rebuilds the stream exactly,
    because round 1 has base == 0 and later == false, so no renumbering runs. Pinned by tests.
  • Renumbering: round sets base = blocks before the round's events; forwarded calls extend
    blocks; withheld calls are counted only when handed back, at the same base. Round 2's id is
    rewritten to round 1's. Indexes follow the calls the client holds. Consistent on every path I
    traced, including the retain-bound hand-back and the round-cap bail.
  • Fail-open: a chunk that does not parse goes out as it came; handBack is the same transform as
    the forward, so round 1 is byte-for-byte; past 16 MB the round goes out whole and the call is
    answered on the next request (repairSearchResults re-reads it from the transcript).
  • The continuation loop on the spliced path: AggregateSSE supports Chat chunks, SearchCalls
    runs on the aggregated round, the alone/mixed split is unchanged, and the leak accounting for
    context_guru_tools lands in mixed_searches or the stored call record as the PR claims.
  • The PR description names the behavior change at the top, per the repo rule, and states data
    dependence: none. Agreed — nothing new is stored.

…879)

A one-round Chat Completions stream that the upstream cut mid-answer
ended with no [DONE] and no error chunk, because terminateChat returned
early for any single round with nothing withheld. pass now records
whether the read ended on a clean EOF or was cut off (a partial event,
or a read error). terminateChat keeps the early return only for a clean
close, so a gateway that omits [DONE] still gets its bytes exactly, and
a cut stream gets the error chunk, as on Anthropic.

Also from review round 1: the Chat splicer no longer runs the Anthropic
detector first; delta.reasoning counts as streamed text for opened();
the countLeak comment names the two paths where a search call is counted
nowhere.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 1 fixes are in cb1c8a01 (a new commit on top, no force-push).

Blocking finding (both reviewers): fixed

  • pass now records how the read ended. A partial event or a read error that is not an EOF means the upstream cut the round off (cutOff). A clean EOF between events does not.
  • terminateChat keeps the early return only for a clean close: one round, nothing held, no cut. A gateway that ends a complete answer without [DONE] still gets its bytes exactly.
  • A cut one-round stream now gets the error chunk, as on Anthropic and as the doc says.
  • New tests:
    • TestChatSpliceOneRoundCutGetsAnErrorChunk: a cut mid-event, and a read error between events. The client gets its bytes, then the error chunk.
    • TestChatSpliceOneRoundCleanCloseStaysExact: a clean close without [DONE] stays byte for byte.
    • The two-round case (TestChatSpliceTerminatesATruncatedTurn) does not change, and it passes.
  • Mutations. Each one failed a test:
    1. Early return without the cutOff check: TestChatSpliceOneRoundCutGetsAnErrorChunk fails.
    2. cutOff always true: TestChatSpliceOneRoundCleanCloseStaysExact fails.

Non-blocking notes

  • Done: the Chat splicer no longer runs the Anthropic detector before its own (reviewer 2).
  • Done: delta.reasoning now counts as streamed text for opened() and in terminateChat (both reviewers).
  • Done: the countLeak comment now names the 2 paths where a search call is counted nowhere: past the retain bound, and after a failed rebuild. The next request still answers the call from the transcript (both reviewers).
  • Not changed: the finish_reason byte scan (reviewer 1). Inside a JSON string, the quote is escaped (\"), so "finish_reason":" in model text cannot match. Reviewer 2 checked the same thing.
  • Not changed: one delta with 2 tool calls (reviewer 2). OpenAI and the gateways we use send one call per chunk. If it happens, the client's arguments arrive late, on hand-back, and no byte is lost.
  • Not changed: closing chunks sent twice in bail (reviewer 1). The Anthropic path has the same shape, and a repeated usage chunk does no harm. A change would touch both dialects, so it is out of scope here.
  • Not changed: a test with a text follow-up round (reviewer 1). The id rewrite and the [DONE] handling are the same for text and tool chunks, and existing tests cover them. I can add the test if you want it.

Tests (eval box, CGO_ENABLED=1 go test -race -count=1)

  • ./expand/... ./schema/... ./tooldefer/...: ok
  • ./proxy/...: ok (500 s)

🤖 Generated with Claude Code

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session fresh 1 of 2 2 of 2 cb1c8a01b919 approve

Verdict: approve

Findings

None. The blocking finding from round 1 is fixed.

Non-blocking

None. The round 1 non-blocking notes were addressed or correctly left unchanged.

What I checked

  • Last review: round 1, 537a584, 2026-11-04T07:23:26Z
  • New commits read: 1 (cb1c8a0 "fix(proxy): end a cut-off one-round Chat stream with an error chunk")
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review:
    • Author's comment at 07:36:40Z: states the fix is in cb1c8a0, describes the changes, confirms tests pass
    • Commit cb1c8a0: adds cutOff field, updates pass to detect cut streams, updates terminateChat guard, adds 2 new tests

Round 1 blocking finding: fixed

Both reviewers found the same defect: a truncated one-round Chat stream (no proxy call, upstream cuts mid-answer) ended with no terminator and no error chunk. The client could not tell a cut answer from a complete one.

The fix in cb1c8a0:

  1. pass now detects how the read ended (ssepeek.go:267-269). A partial event (len(e) > 0) or a read error that is not EOF means the upstream cut the round off. sp.cutOff is set to true. A clean EOF between events leaves it false.

  2. terminateChat keeps the early return only for a clean close (ssepeek.go:606-609). The guard now checks !sp.cutOff. One round, nothing withheld, and a clean close: the client gets the upstream's bytes exactly (a gateway that omits [DONE] after a complete answer). A cut stream fails the guard and gets the error chunk at line 624-627.

  3. Two new tests cover both paths (ssepeek_chat_test.go:270-308):

    • TestChatSpliceOneRoundCutGetsAnErrorChunk: a cut mid-event and a read error between events. The client gets its bytes, then the error chunk.
    • TestChatSpliceOneRoundCleanCloseStaysExact: a clean close without [DONE] stays byte for byte.

The fix is correct. The ambiguity is resolved: pass can tell a cut stream from a clean close, and terminateChat acts on that fact. A cut one-round stream now gets the error chunk, as on Anthropic and as the doc says (ssepeek.go:598). A gateway that ends a complete answer without [DONE] still gets its bytes exactly.

Round 1 non-blocking notes: addressed or correctly unchanged

  • Done: the Chat splicer no longer runs the Anthropic detector first (ssepeek.go:234-240). chatProxyToolCallName runs directly for a chat splicer.
  • Done: delta.reasoning now counts as streamed text for opened() (ssepeek.go:577) and in terminateChat (ssepeek.go:623). A gateway that streams reasoning as reasoning (not reasoning_content) no longer misfiles the round as buffered.
  • Done: the countLeak comment now names the 2 paths where a search call is counted nowhere (proxy.go:1821-1824): past the retain bound, and after a failed rebuild. The next request still answers the call from the transcript.
  • Not changed: the finish_reason byte scan (ssepeek.go:554-556). Inside a JSON string, the quote is escaped (\"), so "finish_reason":" in model text cannot match. The scan is safe.
  • Not changed: one delta with 2 tool calls (reviewer 2's note). OpenAI and the gateways in use send one call per chunk. If it happens, the client's arguments arrive late, on hand-back, and no byte is lost. Out of scope.
  • Not changed: closing chunks sent twice in bail (reviewer 1's note). The Anthropic path has the same shape, and a repeated usage chunk does no harm. A change would touch both dialects, so it is out of scope here.
  • Not changed: a test with a text follow-up round (reviewer 1's note). The id rewrite and the [DONE] handling are the same for text and tool chunks, and existing tests cover them. Not needed.

Code review of cb1c8a0

I read the full diff and the code around each change:

  • proxy/proxy.go:1821-1824: the countLeak comment now names the 2 paths where a search call is counted nowhere. The next request still answers it from the transcript (tooldefer.ApplySearch). Correct.

  • proxy/ssepeek.go:132: new field cutOff bool. Correct.

  • proxy/ssepeek.go:234-240: the Chat splicer no longer runs the Anthropic detector first. chatProxyToolCallName runs directly for a chat splicer. Correct.

  • proxy/ssepeek.go:267-269: pass sets cutOff when the read ended on a partial event or a read error that is not EOF. A clean EOF between events leaves it false. Correct.

  • proxy/ssepeek.go:577: delta.reasoning now counts as streamed text for opened(). Correct.

  • proxy/ssepeek.go:606-609: terminateChat keeps the early return only for a clean close (!sp.cutOff). A cut stream fails the guard and gets the error chunk. Correct.

  • proxy/ssepeek.go:623: delta.reasoning now counts as streamed text in terminateChat. Correct.

  • proxy/ssepeek_chat_test.go:257-308: two new tests. TestChatSpliceOneRoundCutGetsAnErrorChunk covers a cut mid-event and a read error between events. TestChatSpliceOneRoundCleanCloseStaysExact covers a clean close without [DONE]. Both tests are correct and cover the fix.

The fix is complete, correct, and well-tested. No new defects introduced.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session fresh 2 of 2 2 of 2 cb1c8a01b919 approve

Verdict: approve

Findings

None. The blocking finding from round 1 is fixed, and all non-blocking notes were addressed or have valid reasons for not changing.

Non-blocking

None.

What I checked

  • Last review: round 1, 537a584, 2026-11-04T07:21:11Z
  • New commits read: 1 commit
    • cb1c8a0: "fix(proxy): end a cut-off one-round Chat stream with an error chunk (#879)"
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review:
    • Author's comment at 2026-11-04T07:36:40Z describing all fixes
    • Commit cb1c8a0 with the implementation

Round 1 blocking finding: fixed

Both reviewers found the same issue: a truncated one-round Chat stream ended with no terminator and no error chunk. The fix is correct:

  • pass now sets cutOff = len(e) > 0 || err != io.EOF (ssepeek.go:267-269). A partial event or a read error that is not EOF means the upstream cut the round off.
  • terminateChat keeps the early return only when !sp.cutOff (ssepeek.go:606). A clean EOF between events (gateway omitting [DONE] after a complete answer) stays byte-exact. A cut stream gets the error chunk.
  • New tests cover both cases:
    • TestChatSpliceOneRoundCutGetsAnErrorChunk: mid-event cut and read error between events both get the error chunk.
    • TestChatSpliceOneRoundCleanCloseStaysExact: clean close without [DONE] stays byte for byte.

The logic is sound. A clean EOF arrives only between events (readSSEEvent returns err == io.EOF with len(e) == 0). A partial event or another read error sets cutOff = true, and terminateChat then sends the error chunk as documented.

Round 1 non-blocking notes: addressed

  • Chat splicer no longer runs Anthropic detector first (reviewer 2): fixed. pass now checks sp.chat and calls only chatProxyToolCallName for Chat (ssepeek.go:234-238).
  • delta.reasoning now counts as streamed text (both reviewers): fixed. Added to said check in rewriteChat (ssepeek.go:577) and to the closing-chunk test in terminateChat (ssepeek.go:622).
  • countLeak comment expanded (both reviewers): fixed. The comment now names the two paths where a search call is counted nowhere: past the retain bound and after a failed rebuild (proxy.go:1821-1824). The next request still answers the call from the transcript.

Round 1 non-blocking notes: not changed, with valid reasons

  • finish_reason byte scan (reviewer 1): not changed. Inside a JSON string, the quote is escaped (\"), so "finish_reason":" in model text cannot match. The scan is safe.
  • One delta with 2 tool calls (reviewer 2): not changed. OpenAI and the gateways in use send one call per chunk. If it happens, the client's arguments arrive late on hand-back, and no byte is lost. Out of scope.
  • Closing chunks sent twice in bail (reviewer 1): not changed. The Anthropic path has the same shape, and a repeated usage chunk does no harm. A change would touch both dialects, out of scope.
  • Test with a text follow-up round (reviewer 1): not changed. The id rewrite and [DONE] handling are the same for text and tool chunks, and existing tests cover them. The author offered to add it if wanted; I agree it is not needed.

Code review of cb1c8a0

  • Read the full diff (proxy/proxy.go, proxy/ssepeek.go, proxy/ssepeek_chat_test.go) and the code around each change.
  • Traced the cutOff flag: set in pass at the exact point where the read ended (ssepeek.go:267-269), checked in terminateChat (ssepeek.go:606), and never reset between rounds (correct: each round's pass overwrites it).
  • Verified the early return logic: withheld == nil && sp.rounds <= 1 && !sp.cutOff. All three conditions must hold for a byte-exact pass-through. A cut stream fails the third, a withheld call fails the first, and a multi-round stream fails the second. Correct.
  • Checked the new tests: TestChatSpliceOneRoundCutGetsAnErrorChunk covers both a partial event (mid-event cut) and a read error between events. TestChatSpliceOneRoundCleanCloseStaysExact covers the clean close case. Both pass the right inputs and check the right outputs.
  • Verified the delta.reasoning additions: added to the said check in rewriteChat (ssepeek.go:577) and to the closing-chunk test in terminateChat (ssepeek.go:622). Both are correct.
  • Checked the Anthropic detector removal: pass now checks sp.chat first and calls only the right detector (ssepeek.go:234-238). No wasted work.
  • Verified the countLeak comment: it now names both paths (proxy.go:1821-1824) and explains that the next request still answers the call. Accurate.

Fail-open and data dependence

  • Fail-open: unchanged. A chunk that does not parse goes as it came. Past the retain bound, the round goes out whole. A cut stream gets an error chunk, not silence.
  • Data dependence: unchanged. The PR stores no new data. The cutOff flag is runtime state only.

Tests

The author reports tests passed on the eval box with -race -count=1. The new tests cover the fix, and the existing tests still pass. No test gap remains.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 3, same head, GLM first. Rounds 1 and 2: GLM timed out both times (30-minute limit), so Bob wrote the reviews. The owner approved the behavior change and asked for one more GLM try, then Bob again if GLM does not post. No code changed since round 2: head cb1c8a01.

🤖 Generated with Claude Code

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session resumed 2 of 2 3 of 3 cb1c8a01b919 approve

Verdict: approve

Findings

None. The head did not move since round 2. No new commits, no new code to review.

Non-blocking

None.

What I checked

  • Last review: round 2, cb1c8a0, 2026-11-04T08:12:23Z
  • New commits read: 0 (head unchanged)
    • Command: git log --stat cb1c8a01b919a43eb13a13220db26dd47214d5ec..HEAD
    • Output: (empty)
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Comment by amiddavid at 2026-11-04T09:15:38Z: procedural note stating this is round 3, same head, no code changed since round 2

Summary

The head is the same as in round 2 (cb1c8a0). No new commits, no new code changes. The only new item is a procedural comment confirming this is round 3 with the same head.

Round 2 verdict was approve. The blocking finding from round 1 was fixed in cb1c8a0. All non-blocking notes were addressed or have valid reasons for not changing. The fix is correct, complete, and well-tested.

No new findings. The approval from round 2 stands.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session resumed 1 of 2 3 of 3 cb1c8a01b919 approve

Verdict: approve

Findings

None. No code changes since round 2. The blocking finding from round 1 remains fixed.

Non-blocking

None.

What I checked

  • Last review: round 2, cb1c8a0, 2026-11-04T08:12:21Z
  • New commits read: 0 (head unchanged)
    git log --stat cb1c8a01b919a43eb13a13220db26dd47214d5ec..HEAD
    (empty output)
    
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Comment by amiddavid at 09:15:38Z: procedural note that this is round 3 with the same head, GLM timed out, Bob reviewing again

No code changes

The head is cb1c8a0, same as round 2. No new commits. The fix from round 1 remains in place and correct.

No new conversation items requiring action

The only new item is a procedural comment at 09:15:38Z explaining that this is round 3 with the same head. It does not raise new findings or request changes.

Round 1 and 2 status unchanged

  • The blocking finding (truncated one-round Chat stream) was fixed in cb1c8a0 and approved by both reviewers in round 2.
  • All non-blocking notes were addressed or have valid reasons for not changing.
  • Tests passed on the eval box with -race -count=1.

The PR is ready to merge.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 4, same head, GLM only. Round 3 meant to try GLM first, but the script puts the reviewer's last backend first, so Bob ran again. This round runs GLM with fallback off (owner's request). No code changed: head cb1c8a01.

🤖 Generated with Claude Code

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.317 offload-review skill, @amiddavid's session fresh 2 of 2 4 of 6 cb1c8a01b919 approve

Verdict: approve

Findings

None. The head did not move since round 3. No new commits, no new code to review.

Non-blocking

None.

What I checked

  • Last review: round 3, cb1c8a0, 2026-11-04T09:17:10Z
  • New commits read: 0 (head unchanged)
    • Command: git log --stat cb1c8a01b919a43eb13a13220db26dd47214d5ec..HEAD
    • Output: (empty)
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Comment by the author at 2026-11-04T09:20:15Z: procedural note. Round 4 runs GLM only, with fallback off. No code changed since round 2. Nothing to act on.

Head confirmed

The worktree head is cb1c8a01b919a43eb13a13220db26dd47214d5ec. It matches the round 3 head. The base is a85a8669. Two commits in the PR, both reviewed in rounds 1 and 2.

Fix still in place

I re-read the round 1 blocking finding and its fix at the current head:

  • pass sets sp.cutOff = len(e) > 0 || err != io.EOF on the read exit (ssepeek.go:269). A partial event or a non-EOF read error marks a cut round. A clean EOF between events does not.
  • Every round exits the read loop through that error branch, so each pass overwrites cutOff. No stale value can leak into terminateChat.
  • terminateChat keeps the early return only for a clean close: withheld == nil && sp.rounds <= 1 && !sp.cutOff (ssepeek.go:606). A cut one-round stream gets the error chunk, as on Anthropic and as the doc comment says.
  • The reasoning key counts as streamed text in both the said check and the closing-chunk test (ssepeek.go:616-618).
  • The Chat splicer runs only chatProxyToolCallName (ssepeek.go:238-242). The Anthropic detector no longer runs first.
  • Both new tests exist: TestChatSpliceOneRoundCutGetsAnErrorChunk (ssepeek_chat_test.go:271) and TestChatSpliceOneRoundCleanCloseStaysExact (ssepeek_chat_test.go:300).

Earlier findings

  • Round 1 blocking finding (both reviewers): truncated one-round Chat stream got no terminator. Fixed in cb1c8a0, verified above.
  • Round 1 non-blocking notes: all addressed in cb1c8a0 or rejected with a reason I checked in round 2. The reasons hold: the escaped-quote argument on the finish_reason scan is correct, and the one-delta-two-calls case matches the gateways in use. Nothing new to add.

No action from the new comment

The 09:20:15Z comment is procedural only. It asks for this round's reviewer choice, not for code. No request to check.

No new findings. The approval from rounds 2 and 3 stands.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.317 offload-review skill, @amiddavid's session fresh 1 of 2 4 of 6 cb1c8a01b919 approve

Verdict: approve

No new commits since round 3. The head is cb1c8a0. No new findings.

My context is fresh this round. Rounds 2 and 3 were Bob. My own last GLM review was
round 1, against sha 537a584. So this round I verified the fix commit cb1c8a0 myself,
line by line, instead of trusting the round 2 and 3 reports.

Findings

None.

Non-blocking

  • ssepeek.go:469 — a chat round cut before its first event sends no error chunk. terminate
    returns early when !sp.msgStart, and msgStart is set only by the first forwarded chunk
    (ssepeek.go:547). An upstream that returns 200 and cuts with zero events leaves the client an
    empty body, not an error chunk. The Anthropic twin has the same guard, so this is a shared
    design choice, and an empty stream is detectable as empty. Not serious enough for a finding.

What I checked

  • Last review: round 3, cb1c8a0, 2026-11-04T09:17:18Z
  • New commits read: 0 (head unchanged)
    git log --stat cb1c8a01b919a43eb13a13220db26dd47214d5ec..HEAD
    (empty output)
    
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Comment by the author at 2026-11-04T09:20:15Z: procedural. Round 4 runs GLM only, no code
      changed. Nothing to act on.

Round 1 blocking finding: fixed, re-verified by me this round

A cut one-round Chat stream ended with no [DONE] and no error chunk. The fix in cb1c8a0:

  1. pass records how the read ended (ssepeek.go:269): cutOff = len(e) > 0 || err != io.EOF.
    I traced readSSEEvent (ssepeek.go:398-410): a clean EOF comes between events with
    len(e) == 0; a mid-event EOF returns the partial bytes with io.EOF; a broken connection
    returns a non-EOF error. So cutOff is true exactly when the round was cut.
  2. terminateChat keeps the early return only for a clean close (ssepeek.go:606). A cut
    round 1 falls through, the nil-withheld reader hits EOF at once, and !sp.ended sends the
    error chunk (ssepeek.go:632-635). I walked the full path in proxy.go: pass returns
    withheld = nil, the withheld == nil branch at proxy.go:2232-2239 calls
    sp.terminate(prevWithheld), and terminate passes its !sp.ended && sp.msgStart guard.
  3. cutOff cannot go stale across rounds: every pass assigns it at its read error, and a
    round 1 cut ends the turn before any round 2 (the error path bails). A round 2 that runs
    overwrites it. A round 2 that never runs means round 1 was cut, so true is correct.
  4. Both new tests pin the behavior: TestChatSpliceOneRoundCutGetsAnErrorChunk (mid-event cut
    and non-EOF read error, ssepeek_chat_test.go:275-297) and
    TestChatSpliceOneRoundCleanCloseStaysExact (byte-exact clean close, ssepeek_chat_test.go:301-308).
    The mid-event case also checks that the partial bytes themselves still reach the client.

Round 1 non-blocking notes: fixed or correctly rejected

  • Fixed: the chat splicer no longer runs the Anthropic detector first (ssepeek.go:236-240).
  • Fixed: delta.reasoning counts as streamed text in rewriteChat (ssepeek.go:578) and in
    terminateChat's closing-chunk test (ssepeek.go:623).
  • Fixed: the countLeak comment names the two uncounted paths (proxy.go:1821-1824).
  • Rejected, reason checked and accepted: the finish_reason byte scan stays
    (ssepeek.go:555). The reason is right: inside a JSON string a quote is escaped (\"), so
    model text cannot produce the literal bytes "finish_reason":". I checked the encoding; the
    backslash breaks the match.
  • Rejected, accepted: one delta with two tool calls. Gateways in use emit one call per
    chunk, and no byte is lost — the client's arguments arrive on hand-back.
  • Rejected, accepted: closing chunks forwarded twice in bail. The Anthropic path has the
    same shape, a repeated usage chunk is harmless, and a fix would touch both dialects.
  • Rejected, accepted: a text follow-up round test. The id rewrite and [DONE] handling are
    the same code path for text and tool chunks.

Rules

  • Fail-open: unchanged. A chunk that does not parse goes out as it came. A cut stream now gets
    an error chunk, which is the documented behavior, not a failure.
  • Data dependence: unchanged. cutOff is runtime state only. No new data is stored.
  • Live tests were not approved. I read the code only.

@amiddavid
amiddavid merged commit 2d12a0c into main Nov 4, 2026
5 checks passed
amiddavid added a commit that referenced this pull request Nov 4, 2026
The first commit was built from a tree older than #883. It removed the
Chat streaming splicer, its tests and a countLeak case. This commit sets
every file back to origin/main, so the only proxy changes left are the
additive /stats `preset` field, its golden test and the Prometheus
exemption.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: New/ToDo

Development

Successfully merging this pull request may close these issues.

feat(tooldefer): stream Chat Completions answers in deferred sessions, and hold only our search call

1 participant