Repository navigation
feat(proxy): stream Responses answers with our tool search (#884) - #894
Conversation
A stateless Responses request (store:false, no previous_response_id) that declares context_guru_tool_search now goes through the existing sseSplicer. Text streams at once. The stream holds from our call. The follow-up joins the same stream under round 1's id, with one merged response.completed. A request that may chain keeps the full buffering. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| 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 | 14f5db44cf46 |
blocking |
Verdict: blocking
Findings
- proxy/proxy.go:1798 —
respSplicestays true after the 400-retry turns our search off, so the retried original gets the splice the code says it must not get- What fails: a stateless Responses request (
store:false) declares our search. The upstream refuses the rewritten request with 400 or 422. Line 2069 resetsdi, searchOn = nil, false— "nothing to hold or answer from here on". ButrespSplicewas computed once before the loop and is not reset. The retried original (di.orig) then matches the splice case at proxy.go:2167 throughrespSplicealone, withsearchOnfalse. - Result on that path: the retried answer is spliced and inspected, not streamed through. An expand call in it is withheld and answered in band, and a stream without its own terminator gets a synthetic
response.failedappended. On the base commit the same request streams through untouched (case at proxy.go:2229), and the chat and Anthropic wires still do, because their case testssearchOn, which was reset. So this is an edge-case behavior change that only the new flag makes, and it contradicts the comment written one line above the reset. - Proof: proxy.go:1798 sets
respSplice := searchOn && ...before the loop; proxy.go:2069 resetssearchOnonly; proxy.go:2167 reads... || respSplicewith nosearchOn; proxy.go:2187 then callssp.passwithouttooldefer.ClientSearchNamebecausesearchOnis false. - Fix: reset the flag with the state it derives from —
di, searchOn, respSplice = nil, false, falseat proxy.go:2069. Add a test likeTestClientSearchRetriesOriginalOn400on the/openai/v1/responsesroute with"store":falseand an SSE answer.
- What fails: a stateless Responses request (
Non-blocking
- proxy/ssepeek.go:818 —
terminateResponsesdoes not treatdata: [DONE]as a terminator. A gateway that ends a Responses stream with[DONE](the official API does not) gets aresponse.failedappended after the done marker, becausesp.endedis set only byresponse.completed/failed/incomplete. Chat hasisChatDonefor this. Low risk; the event shapes were checked against Codex 0.160.0 and the OpenAI SDK. - proxy/ssepeek.go:801 — the merged usage is written only when the later round's
response.completedcarries a usage object. When it does not, the tokens summed from the earlier rounds are dropped and the client sees no usage. Fail-open direction; no wrong number is reported. - proxy/ssepeek.go:757 —
msgStartis set only byresponse.created. A stream that opens straight into output items (noresponse.created) gets no syntheticresponse.failedwhen it is cut off, becauseterminatereturns early. The protocol always sendsresponse.createdfirst. - Pre-existing, not from this PR:
searchTally.addreadsReadSearchesSSE, which parsescontent_block_start(Anthropic shape only). The deferral ledger therefore counts no searches on a Responses SSE round. The chat splice (#879) has the same gap.
What I checked
- The full diff (proxy.go, ssepeek.go, both test files) and the code around each change.
- The splicer invariants:
withheldalways belongs to the last round that ranround(), andbasematches that round, so no handBack can double-shift an index. Checked the JSON-round-after-stream anomaly, the round-cap exit, the upstream-failure exit, and the 16 MB retain-boundoverpath insidepass. - Index and event numbering:
output_indexremap past the items the client holds,sequence_numbercontinued fromevCount, droppedresponse.created/in_progress/queuedin later rounds, round 1 byte-for-byte. - The merged terminal event:
prevItemssnapshot atround()start plus the follow-up's own list, no duplicates across rounds 2 and 3, usage summed once perresponse.completed(withheld ones included, handBack does not re-add). statelessResponses:store:falseplus noprevious_response_id; a nullprevious_response_idfails safe toward buffering; the string"false"is rejected.- The serve loop wiring: case order at proxy.go:2167,
sp.opened()for an opening call,countLeak,noteLeakedSearchesat the cap,AggregateSSEon the retained round bytes, and the recorder path. - Fail-open paths: mixed client-tool call, aggregation failure,
Continuationfailure, handBack verbatim in round 1. - Tests: read all new tests in ssepeek_responses_test.go and the changed helper in tooldefer_search_test.go. They cover passthrough, withhold-and-merge, keeps-what-the-client-saw, opening call, handBack, cut-off rounds,
statelessResponses, and the end-to-end pair (spliced vs buffered). The 400-retry path on Responses is the one gap (finding 1). - CLAUDE.md rules: fail-open holds on every path I traced; no new data dependence (the splice works on stream bytes only, like the chat splice); no new exported metrics.
amiddavid
left a comment
There was a problem hiding this comment.
| 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 | 14f5db44 |
approve |
Verdict: approve
Findings
None. I traced every new path and found no wrong behavior, no data loss, and no broken
fail-open path. The checks that convinced me:
- Round 1 is byte-for-byte.
rewriteResponses(proxy/ssepeek.go:734) changes nothing in
round 1: thelaterblock is skipped, andnp == payloadreturns the event untouched.
TestResponsesSpliceTextStreamsUntouchedpins it. - The merged
response.completedlists what the client holds.prevItemsis snapshotted
inround()before the round streams (ssepeek.go:189), so a round can never duplicate its
own items. A later round's droppedresponse.created/in_progresscannot reset state. - Fail-open paths hold. I traced
bail(), the upstream-error path, the round cap, the
retain bound, and the hand-back. In each case the client ends with a complete turn:
either the withheld events verbatim (round 1,later == false), or renumbered correctly
(round()has run, sobasematches the items the client holds), or a synthetic
response.failed(ssepeek.go:818).baseadvances only insideround(), so round-1
bytes handed back after a round-2 failure are still renumbered by 0 — verbatim. - The stateless gate is sound.
store:falsemeans the server keeps nothing to chain on,
andprevious_response_idis refused on top (proxy/proxy.go:2488). The string"false"
is rejected (st.Type == gjson.False).expand.Continuationcopies the request body, so
round 2 stays stateless too. - Usage sums once.
addUsageruns only inpass, never inforwardorhandBack, so a
handed-back completed cannot double-count. The merged event reports the sum of every round. - The injected tools are all
type:"function"on this wire (expand.ToolDefRaw,
tooldefer/clientsearch.go:52), so a call always arrives as afunction_callitem, which is
the only shaperesponsesProxyToolCallNameaccepts. No proxy call can slip past the cut.
Non-blocking
- proxy/proxy.go:1798 vs proxy/proxy.go:2069 —
respSpliceis not reset on the deferral
retry. The retry setsdi, searchOn = nil, falsebut leavesrespSplicetrue, so the
retried original-body response still takes the splice path (with the search tool dropped
from the withhold set). The Chat Completions splice resets its equivalent condition. The
outcome is still correct:storeis unchanged indi.orig, so the stateless check holds,
and the splice machinery is dialect-correct for expand/adjudicate calls. Worth a comment
or a reset, for symmetry with the chat path. - ssepeek.go:801 — the usage merge covers only the three top-level counts. Nested
input_tokens_details/output_tokens_detailskeep the last round's values, and a later
response.completedwith no usage object gets no merge at all. Client-side accounting
fidelity only; the proxy's own usage reads each round's raw events. - ssepeek.go:818 —
terminateResponsesignores itswithheldargument. Every call site
runshandBackfirst, so a withheld terminator has already gone out andterminateis a
no-op viasp.ended. Correct, but the signature reads as if the bytes were used.
What I checked
- The full diff:
proxy/proxy.go,proxy/ssepeek.go,proxy/ssepeek_responses_test.go,
proxy/tooldefer_search_test.go. - The code around each change: the whole
serveloop (rounds, retry, bail, cap, upstream
error), all ofssepeek.go, and the sharedpass/forward/rewrite/terminateplumbing. expand/response.go(Continuation for the responses wire — round 2 preservesstore),
expand/expand.go(tool shapes),expand/inject.go,schema/wire.go(WireResponses is
distinct from WireOpenAI, so the chat-splice condition cannot catch a Responses stream),
tooldefer/clientsearch.go,proxy/usage.go(response.usageis a supported SSE path).- State traces: round-1 passthrough, withhold at the call, round-2 renumber
(output_index+base,sequence_number= events written), merged completed, hand-back
in round 1 and round 2, truncated rounds, the retain bound, and the buffering fallback for
a request that may chain. - Tests: all eight new splicer tests plus the end-to-end test, both subtests. They cover
passthrough, withhold + merge, completed/client divergence, the buffered classification,
hand-back, cut-off rounds, andstatelessResponsesitself. - Docs: no stale claim about Responses streaming;
docs/data-dependence.mdneeds no change
(transport only, no new stored-data dependence). - I did not run builds or tests (not approved). I read the code only.
…sage (#884) - The 400 retry now turns respSplice off with searchOn and di. - [DONE] ends a Responses stream: no response.failed follows it. - The merged usage sums the nested *_details counts and is written even when the last round has no usage. - terminateResponses drops its unused argument. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
Round 1 replies (fix commit 4be2ff8)
Tests on box 2, fresh tar sync: 🤖 Generated with Claude Code |
…426 (#884) Codex tries a WebSocket first. The proxy serves HTTP only, and the mux answered 405, so Codex retried 5 times (~9 s) before it fell back to HTTPS. 426 Upgrade Required makes it fall back at once. Any other GET keeps 405. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
WebSocket fast-fail (commit added to this PR, owner approved)
🤖 Generated with Claude Code |
amiddavid
left a comment
There was a problem hiding this comment.
| 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 | resumed | 1 of 2 | 2 of 2 | eb0bef701e6e |
approve |
Verdict: approve
Findings
None. My round-1 finding is fixed, and both new commits are clean.
Earlier findings
- Mine, round 1:
respSplicestays true after the 400 retry — fixed in 4be2ff8. proxy.go:2082 now setsdi, searchOn, respSplice = nil, false, false. I traced the retried request through the case ladder: with the flag reset, the SSE answer takes the plain stream-through case and reaches the client untouched. The newTestResponsesSearchRetriesOriginalOn400pins it — I checked its logic myself: it uses an SSE answer with no terminal event, so without the reset the splicer would append aresponse.failedand the byte-for-byte assert would fail. Sound test. - Mine, round 1 (non-blocking):
[DONE]not a terminator — fixed.rewriteResponsesnow checksisChatDonefirst and setssp.ended(ssepeek.go:745). The event is returned verbatim, so round 1 stays byte-for-byte.TestResponsesSpliceDoneIsATerminatorpins it. - Mine, round 1 (non-blocking): merged usage skipped without a usage object — fixed. The sum is now written unconditionally in the merged completed (ssepeek.go:817), and
addUsagealso sums the nestedinput_tokens_details/output_tokens_detailsnumbers.TestResponsesSpliceSumsUsagecovers both cases; I re-derived its expected numbers (120/10/130, cached 74, reasoning 5; and 100/6/106 without round-2 usage) and they match the sums. Nested paths go throughsjson.Set, which creates the objects when the last event has none. - Mine and reviewer 2's (non-blocking):
terminateResponsesunused argument — fixed. The argument is gone; the comment says why. - Mine, round 1 (non-blocking):
msgStartonly fromresponse.created— not changed, reason accepted. The protocol always opens withresponse.created. Without it the splicer fails open: bytes go as they came. - Mine, round 1 (non-blocking, pre-existing):
ReadSearchesSSEparses Anthropic events only — not changed here, issue #895 opened. Accepted; it predates this PR. - Reviewer 2 approved round 1 and raised no blocking finding. Their three non-blocking items map to points 1, 3 and 4 above. I checked each myself; all fixed or accepted with a reason I verified.
New commits
- 4be2ff8 "reset the Responses splice on the 400 retry, sum nested usage" — reviewed in full. The reset is the one-line fix I proposed. The
[DONE]check sits before the round filter, so it covers every round. The usage write moved out of theIsObjectguard; when the last completed carries a usage object with keys the sum lacks, those keys keep their own values (nothing is zeroed). No new defect. - eb0bef7 "answer a WebSocket upgrade on /openai/v1/responses with 426" — reviewed in full. New
GET /openai/v1/responsesroute: 426 forUpgrade: websocket, 405 withAllow: POSTotherwise. No route conflict inMux(); no upstream call and a fixed message, so nothing leaks; a plain GET keeps its old answer. This is a behavior change (405 → 426 for a WebSocket attempt) and it is named, measured (9 s → 1 s to Codex's fallback) and owner-approved in the PR comment.TestResponsesWebSocketUpgradeGets426covers both branches. I did not verify the codex-rs source claim; the owner approved the pick.
Non-blocking
- ssepeek.go:745 — the
[DONE]check runs before the cheap round-1 prefilter, so every delta now pays a line scan (isChatDone). The chat splicer pays the same. Measured cost only; not worth a change. - proxy.go:548 — the 426 test looks at the
Upgradeheader alone, withoutConnection: Upgrade. A plain GET with a strayUpgrade: websocketheader gets 426 instead of 405. Codex sends both headers, so this cannot misfire in practice.
What I checked
- Last review: round 1, 14f5db4, 2026-11-04T14:08:48Z
- New commits read: 2 — 4be2ff8 (fix(proxy): reset the Responses splice on the 400 retry, sum nested usage), eb0bef7 (feat(proxy): answer a WebSocket upgrade on /openai/v1/responses with 426)
- Read in full: 2 reviews, 2 comments, 0 inline comments (from the three files)
- New items since my last review: reviewer 2's round-1 review (read in full, its non-blocking items checked against the fixes); the author's reply table (each row checked against the diff); the author's WebSocket comment (owner approval for the behavior change); both new commits (reviewed as a first review: full diff plus the code around each hunk).
- The fix commit: the reset line, the
[DONE]early return and its effect on round-1 byte identity, the nested usage sums (re-derived the test's expected numbers by hand), the unconditional usage write, and the dropped argument with its single caller. - The WebSocket commit: route registration against the existing
Mux()patterns, auth and leak surface (fixed strings, no upstream), plain-GET behavior, and the test's two branches. - The three new tests in ssepeek_responses_test.go: read each, traced what it asserts and what its failure would mean. The 400-retry test's mutation claim (fails without the reset) matches my own trace.
- The two "not changed" replies (
msgStart,ReadSearchesSSE): reasons checked and accepted. - CLAUDE.md rules on the new code: fail-open holds (both new paths return fixed responses and revert nothing); the one behavior change is named and owner-approved; no new data dependence; no new exported metrics.
- I did not run builds or tests (not approved). The author reports
go test -race ./proxy/...ok on box 2.
amiddavid
left a comment
There was a problem hiding this comment.
| 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 | resumed | 2 of 2 | 2 of 2 | eb0bef701e |
approve |
Verdict: approve
Findings
None. Both new commits are correct, and every round-1 finding is fixed or answered.
Earlier findings, status
- R1 reviewer 1, finding 1 (blocking) / my non-blocking 1 —
respSplicestayed on after the
400 retry. Fixed in4be2ff8a. The retry now setsdi, searchOn, respSplice = nil, false, false(proxy/proxy.go:2082). I traced the retried round: the splice case no longer matches,
and a marker-free original falls to the plain SSE stream-through and returns, so the client
gets the retried stream untouched.TestResponsesSearchRetriesOriginalOn400pins it with an
answer that has no terminal event — under the old code the splicer would append a
response.failed, so the test fails without the fix. Verified the test's own logic, not the
author's word. - My non-blocking 2 / R1 non-blocking — the usage merge was partial. Fixed.
addUsagenow
sums the nestedinput_tokens_details/output_tokens_detailsnumbers (proxy/ssepeek.go:724),
and the merge writes the sum even when the last round's terminal event has nousage
(ssepeek.go:815).TestResponsesSpliceSumsUsagecovers both cases with real arithmetic
(120/10/130, cached 74, reasoning 5; and the no-usage case keeps round 1's sums). - My non-blocking 3 —
terminateResponsestook an unusedwithheldargument. Fixed. The
argument is gone and the doc comment says why nothing is replayed. - R1 non-blocking —
data: [DONE]did not end a Responses stream. Fixed.
rewriteResponsesnow checksisChatDonefirst and setssp.ended(ssepeek.go:745), so no
response.failedfollows a[DONE]terminator.TestResponsesSpliceDoneIsATerminatorpins
the byte-for-byte output. - R1 non-blocking —
msgStartis set only byresponse.created. Rejected by the author:
the protocol always sendsresponse.createdfirst, and a stream without it fails open —
bytes go as they came, no synthetic event. I checked the reason: it is right. A missing
createdmeans a non-conformant gateway; adding a synthetic terminator there would guess.
Accept. - R1 non-blocking —
ReadSearchesSSEparses Anthropic events only. Deferred to issue #895,
which I verified exists and is open. Pre-existing, out of scope for this PR. Accept.
What I checked in the new commits
4be2ff8a (fix round 1). The respSplice reset, the [DONE] terminator, the nested usage
sum, and the dropped argument — each traced through pass, forward/rewriteResponses,
terminate, and the merge. Two details I proved rather than assumed:
gjson.ForEachon a missing*_detailskey does not iterate. No Go on this machine, so
I proved it from existing tested code:rewriteChatcallsd.Get("tool_calls").ForEachon
every chat chunk (ssepeek.go:622), and its tests pass — if a missing result iterated once,
sp.blockswould grow on every text chunk and the #879 tests would fail. A scalar or nested
object inside the details is guarded byv.Type == gjson.Number, and a badsjsonpath in
the merge is skipped byset— fail-open both ways.- The unconditional usage write is safe when
usageis absent or null.sjson.Set
creates the missing object; on an array or a malformed shape it errors andsetskips.
eb0bef70 (WebSocket 426). The route is a plain mux handler next to the POST route
(proxy/proxy.go:547). Checked:
- No pattern conflict: Go's method-patterned mux keeps
GETandPOSTdistinct, and a
non-websocket GET still gets 405 withAllow: POST, same as the mux's own answer before. - No shadowing:
Mux()is mounted directly incmd/context-guru-proxy/main.go:826, with only
the optional activity-stamping wrapper, so the 426 reaches every client of this binary. - No data, no auth concern: the handler answers 426/405 only and leaks nothing.
- The behavior change is named and has the owner's approval, with live timing (9 s → 1 s), in
the PR comment of 2026-11-04T14:34:07Z. This satisfies the CLAUDE.md rule that an edge-case
behavior change needs a human developer's yes.
Non-blocking
None.
What I checked
- Last review: round 1, 14f5db4, 2026-11-04T14:10:24Z.
- New commits read: 2 —
4be2ff8a"fix(proxy): reset the Responses splice on the 400 retry,
sum nested usage (#894)",eb0bef70"feat(proxy): answer a WebSocket upgrade on
/openai/v1/responses with 426 (#884)". Full diff of both, plus the code around each hunk:
Mux(), the retry block inserve, all touched parts ofssepeek.go, and the four new
tests. - Read in full: 2 reviews, 2 comments, 0 inline comments (from the three saved files).
- New items since my last review:
- Commit
4be2ff8a— reviewed above, fixes verified against the code, not the reply table. - Commit
eb0bef70— reviewed above, including the mount site and mux semantics. - Author reply of 14:22:45 (round-1 fix table) — each row checked; both "not changed"
rows carry reasons I verified (#895 exists and is open; theresponse.createdfail-open
reason is sound). - Author comment of 14:34:07 (WebSocket fast-fail, owner approval) — checked the route, the
test, and the approval claim against the CLAUDE.md rule.
- Commit
- Tests on the box were run by the author (
go test -race ./proxy/...ok, 508 s and 510 s);
I did not run builds or tests myself (not approved). I read the code only.
SummaryLive check of #894 passed for the 426 answer and for stateless streaming with our tool search. Setup
A. 426 to a WebSocket upgrade
B. Stateless streaming with our searchPython openai SDK,
Notes
🤖 Generated with Claude Code |
Behavior change (needs a human's yes)
Who:
ultrahighusers on the OpenAI Responses wire (POST /openai/v1/responses) whose request declares our tool search AND hasstore: falseand noprevious_response_id. Codex CLI over HTTP is one.Old: the proxy held the whole stream. The answer reached the client at once, at the end.
New: text streams as it arrives. The proxy holds from our search call. The follow-up joins the same stream. The client sees ONE response id (round 1's) and ONE merged
response.completed.Not changed: a request with
storetrue or absent, or withprevious_response_id, keeps the full buffering.Turn off: leave
ultrahigh(tool search off). There is no separate switch.Second behavior change, same PR (owner approved): a WebSocket upgrade (
GET /openai/v1/responseswithUpgrade: websocket) now gets 426 Upgrade Required.Allow: POST.Summary
sseSplicer(arespmode, likechat). No second splicer.What changed
proxy/ssepeek.go:newResponsesSSESplicer,responsesProxyToolCallName,rewriteResponses,terminateResponses.response.output_item.added.response.createdandresponse.in_progress.output_indexandsequence_numberpast what the client holds.response.completedwith one that holds every item the client saw, in order, and the summedusage.response.failed.proxy/proxy.go:statelessResponses, and the routing of a stateless Responses stream to the splicer.handBackwrites round 1's held bytes unchanged.Data dependence
None new. Nothing is stored.
docs/data-dependence.mdneeds no change.WebSocket result (Codex 0.160.0, live)
GET. It got405before this PR and now gets426(see above). Codex's source (core/src/client.rs) falls back at once only onUPGRADE_REQUIRED.supports_websockets = truebehind the proxy ends on HTTP withstore: false— the case this PR splices. Cost: about 10 seconds of retries at the start of a session.How it was tested
Box 2, fresh tar sync into an empty dir.
go test ./proxy/ -run "Responses|Splice|ClientSearch"CGO_ENABLED=1 go test -race ./proxy/...CGO_ENABLED=1 go test -race ./expand/...gofmt -l proxy,go vet ./proxy/New tests (
proxy/ssepeek_responses_test.go): text and client tool pass byte for byte; our call is held and rounds merge (one id, one completed, 2 items, summed usage, renumberedoutput_index/sequence_number); an item missing from or only in the follow-up'scompleted; opening call counts as buffered; hand-back is verbatim; cut-off stream ends withresponse.failed;statelessResponsescases; end to end through the handler forstore:false(spliced) andstoreabsent (buffered).Mutation checks (both caught, then restored):
outputwithout round 1's items: 3 tests fail.statelessResponsesgate: thestore defaultend-to-end test fails.Client behavior behind these shapes is in the #884 comment: Codex and the OpenAI SDK read
output_item.done, ignoresequence_number; the SDKresponses.streamfails ifcreatedandcompletedids differ, so one id is required.Technical notes
usageis summed over rounds only whenresponse.usageis an object.outputis round 1'soutput_item.doneitems the client saw, then the follow-up's ownoutputlist. An item only in the follow-up'scompletedis kept. One missing from round 1'scompletedis still in the merge.previous_response_id) keep buffering.🤖 Generated with Claude Code