Skip to content

feat(tooldefer): our own tool search for models without defer_loading (#825) - #875

Merged
amiddavid merged 7 commits into
mainfrom
feat/provider-search-825
Nov 4, 2026
Merged

amiddavid merged 7 commits into
mainfrom
feat/provider-search-825

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Refactor in this PR (no behavior change)

  • One stream rebuild: expand.AggregateSSE now rebuilds Chat Completions streams too, next to Anthropic and Responses. The copy tooldefer.AggregateChatSSE and its fallback in serve are gone. The session recorder still translates Anthropic streams only. One small difference from the deleted copy: a stream with no Chat chunk now returns ok=false, not an empty message. serve bails on both, so the client gets the same bytes.
  • One tool-call reader: schema.OutputCalls reads a response's calls (id, name, arguments, in order) for Anthropic, Responses and Chat. expand.ResponseCalls, tooldefer.SearchCalls and the proxy's bufferedToolUseNames are now thin wrappers that classify with their own tool names. The streamed sniffer (responseToolUseNames on SSE) still reads its bounded window itself.
  • The existing expand tests pass unchanged. schema/outputcalls_test.go is one table test over the 3 formats.

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

Summary

  • Through our gateway, defer_loading saves nothing on GPT, GLM and Kimi. The full definition still reaches the model (feat(toolfilter): our own tool search for providers without defer_loading (GPT, GLM, Kimi) #825).
  • This PR builds the issue's option B: remove the tool, add it back on the first search, and keep it after that.
  • Live, gpt-5.5, 3 tools deferred: prompt tokens fell from 5,062 to 3,940 on the first request. One search added get_shipping_eta back, and the task succeeded. The next request read 3,584 cached tokens.

Step 1: native deferral on the OpenAI wire

Every probe went through our gateway on the OpenAI wire, with a unique nonce. Test setup: 1 small tool and 1 large tool of about 1,130 tokens.

Model, wire No large tool Large tool Large tool, deferred
gpt-5.5, Responses, defer_loading + {"type":"tool_search"} 67 1,195 469: native deferral works
gpt-5.5, Chat Completions 69 1,193 1,193: no saving
GLM 5.3 Flash, Responses 400: "tool_search is not supported"
GLM 5.3 Flash, Chat Completions 179 1,733 1,733 with the flag on the tool; with the flag in function, the gateway drops the tool (183) and GLM says it has no such tool
Kimi k2.5, both wires 91 1,339 1,341: no saving
  • OpenAI's docs (developers.openai.com, guide "Tool search") confirm this. Native tool_search exists on the Responses API only, for gpt-5.4 and later. It runs in a hosted mode or a client-executed mode, and it puts loaded tools at the end of the context to keep the cache.
  • defer_loading without tool_search returns 400 on gpt-5.5 Responses.
  • End to end on gpt-5.5, the hosted search loaded the tool and the model called it correctly. Turn 2 read 1,536 cached tokens.
  • This PR does not use native deferral. Option B covers every model and both wires. Native deferral for gpt-5.4+ on Responses is follow-up feat(tooldefer): native tool search for gpt-5.6+ on the Responses API #876. Its first step is a Codex run.
  • Option B never sends defer_loading. Through our gateway, GLM drops a Chat Completions tool that carries it inside function. B removes the tool instead. TestApplySearchNeverSendsDeferLoading (both wires: the first request, after an add-back, and the follow-up) and TestClientSearchInBand (every upstream body) check this.

What changed

  • tooldefer/clientsearch.go (library; it imports neither proxy nor expand):
    • ApplySearch decides the thread's set with the unchanged rule (Decide) and stores it in its own record (SearchRecord: the deferred set and the tools added back, names only). It removes those tools, adds context_guru_tools after the client's tools, and puts the names list at a fixed place:
      • Chat Completions: a system message after the leading system or developer message.
      • Responses: a developer message at input[0].
    • The bytes stay the same on every request. A tool that comes back goes at the end of tools, in load order, so the client's tools before it keep their cache.
    • View writes an OpenAI body the Anthropic way, so the rule and the history read it without change.
    • The names list never changes after an add-back.
    • A search the client received (together with a client tool call) is answered on the next request (repairSearchResults), with the same bytes each time, and its tools are added back.
    • A tool that tool_choice forces is added back.
    • A Responses turn chained on previous_response_id never makes a decision. In a thread our search already rewrote, it gets turn 1's tools, and serve answers a search in band. A chained turn that omits tools is sent as it is: live on gpt-5.5 through our LiteLLM gateway, the provider then declares no tools at all ("tools": [], no tool call), so no call to our tool can come back. Limit: the native OpenAI API might differ; feat(tooldefer): native tool search for gpt-5.6+ on the Responses API #876 can recheck it there.
    • It skips Claude models (they use feat(tooldefer): defer unused tools in a new opt-in ultrahigh preset (#485) #861's path).
  • proxy/proxy.go, the serve loop:
    • It holds the response when the request declares our search tool, and answers a search-only turn in band on a follow-up, with the loaded tools appended. It reuses the expand loop and expand.AggregateSSE.
    • A search together with a client tool call goes to the client whole.
    • Calls to the expand and adjudicate tools in the same turn are still answered in band.
  • proxy/tooldefer.go: wires applyClientSearch for the OpenAI provider, and feeds the history. A load counts as a use.
  • The 400 fallback is toolfilter: defer unused tool declarations at session start, by history (was: remove at cold moments) #485's: send the client's original once, and turn the search off for that tenant and model.
  • /stats tool_defer: an add-back that a search loaded counts in wrong_guesses (from fix(tooldefer): the follow-ups to tool deferral from #866 #874, through tooldefer.WrongGuesses in the ledger), once per tool. Two counters belong to option B only: add_backs (tools added back, each one cache miss on tools) and mixed_searches. decisions, requests and the ledger count this path too.

Data dependence

No change. Metadata only, with the same history as #485: tool names, ids and counts. One new record per thread, under the pinned cg:tdf: prefix, holds tool names only. With storage off, or with no durable place for the record, nothing is deferred. docs/data-dependence.md names the new record in the toolfilter row.

How it was tested

  • Unit tests, tooldefer/clientsearch_test.go: the view, the rewrite on both wires, byte-stable tools and list across turns, the add-back at the end of tools, the mixed call and its repair, a forced tool, the off cases (Claude, account off, no history, 400 turn-off, previous_response_id), fail open, and the Chat SSE rebuild.
  • End to end, proxy/tooldefer_search_test.go:
    • an in-band search (the client never sees our call; the tool stays with the same tools bytes; the load is a use in the history);
    • the mixed call;
    • a 400 that sends the original;
    • off in xhigh and for Claude models.
  • Race tests on the eval box, all ok:
    • go test -race ./tooldefer/... ./components/... ./schema/... ./expand/... ./apply/... ./config/...
    • go test -race ./proxy/... (480 s)
  • Mutations. Each one failed a test, and the tests passed again after the restore:
    1. The add-back not saved: fails TestAddBackKeepsTheToolAtTheEnd, TestClientSearchInBand and TestClientSearchMixedCall.
    2. No in-band answer: fails TestClientSearchInBand.
    3. A mixed call answered in band: fails TestClientSearchMixedCall.
    4. The rewrite marks a deferred tool with defer_loading instead of removing it: fails TestApplySearchNeverSendsDeferLoading.
  • Live check: a local build with --preset ultrahigh, against the plain gateway (not Context Guru), gpt-5.5, a nonce in every prompt, 3 seeded sessions, and 5 tools (3 of about 1,000 tokens each, never used):
Request Prompt tokens Cached
All tools, direct to the gateway 5,062 0
Chat, turn 1 (search + add-back + call, 2 upstream rounds) 3,940 0 (new thread)
Chat, turn 2 3,923 3,584
Chat, turns 3 and 4 3,984 / 4,015 3,584 / 3,584
Responses + stream, turn 1 (2 rounds) 4,098 0 (new thread)
Responses + stream, turn 2 4,203 3,584
  • /stats: add_backs: 1, retries_400: 0. The model answered correctly on both wires: "Order ORD-42 is arriving via DHL on 2026-11-09".
  • A second task session, after the first one loaded get_shipping_eta, deferred only 2 tools. A load counts as a use, live.
  • Spend: well under $1. The captured state was deleted after the run.
  • Not tested: a real Codex CLI session.

Open questions

  1. Buffered Chat Completions streams in deferred threads. Decided: the owner accepts the buffering for this PR. Early streaming (text at once, hold only from the first chunk of a context_guru_tools call) is follow-up feat(tooldefer): stream Chat Completions answers in deferred sessions, and hold only our search call #879. It extends proxy/ssepeek.go's sseSplicer to Chat chunks.

Technical notes

🤖 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 1 of 2 68588a72d0c4 blocking

Verdict: blocking

Findings

  1. proxy/proxy.go:2002 — after the 400 retry sets di = nil, searchOn stays true, and the loop can then dereference a nil di

    • What fails: a search thread (ultrahigh, OpenAI wire) gets a 400 or 422 to the rewritten request. The retry block sends di.orig and sets di = nil. searchOn (proxy/proxy.go:1737) was computed before and stays true. If the model's answer to the original request calls context_guru_tools (for example it repeats a call it sees in the thread's transcript), h.searchLoad(tn, di, names) at proxy/proxy.go:2278 reads di.session on a nil di (proxy/tooldefer.go:439) and panics. serve has no recover, so net/http drops the connection. The client gets a transport error, not the response — the fail-open promise is broken. The same nil di reaches tooldefer.AppendTools(wire, next, di.orig, searchNow) at proxy/proxy.go:2372 when tools were loaded. A smaller effect comes first: the retried request declares no search tool, but its SSE response is still buffered (proxy/proxy.go:2150), so the client loses its stream for nothing.
    • Proof: searchOn := di != nil && di.search && ... runs once at proxy/proxy.go:1737. The retry block at proxy/proxy.go:1983-2003 assigns di = nil and never touches searchOn. The only later di guards are if di != nil at proxy/proxy.go:1834 and 2204; the search block at proxy/proxy.go:2270-2291 is guarded by searchOn alone. The pre-forward recover at proxy/proxy.go:1295 covers the block before serve, not serve itself.
    • Fix: in the retry block, next to di = nil, also set searchOn = false (the retried body declares no search tool). Or guard the search block with di != nil.
  2. tooldefer/clientsearch_test.go:88 — the PR description names a test that does not exist, and the invariant it was to pin is untested

    • What fails: the PR says TestApplySearchNeverSendsDeferLoading checks that option B never sends defer_loading "on both wires: the first request, after an add-back, and the follow-up", and that mutation 4 failed it. grep -rn NeverSendsDeferLoading over the whole tree returns nothing. The PR also says TestClientSearchInBand checks "every upstream body" for this; that test checks tool names and the names list only, not defer_loading. So the key safety property of this PR — a tool marked defer_loading instead of removed is silently DROPPED by GLM on Chat Completions, per the PR's own measurement table — has no test. A later regression in RewriteSearch would lose tools on GLM with nothing failing.
    • Proof: repo-wide grep for NeverSendsDeferLoading in *.go: no match. proxy/tooldefer_search_test.go and tooldefer/clientsearch_test.go (the only new test files) contain no assertion on defer_loading for the search path.
    • Fix: add the test the PR describes: run ApplySearch on both wires, then assert no tool in every output body (first request, after an add-back, the follow-up, and each upstream body in the end-to-end test) carries defer_loading. Or correct the PR description if the test was dropped on purpose — but then the invariant ships untested.

Non-blocking

  • proxy/proxy.go:1992 — repairOnMissingRef and declares are Anthropic-shaped but now run on OpenAI wires. declares (proxy/tooldefer.go:529) reads a top-level name; on Chat Completions the name is at function.name, so it reports "not declared" wrongly. StubTools (tooldefer/repair.go:52) appends an Anthropic-shaped stub (input_schema, defer_loading). The path needs an OpenAI-compatible gateway whose 400 text matches the Anthropic regex in MissingRef, so it is unlikely — but the shared 400 block now runs on wires this code was not written for.
  • tooldefer/clientsearch.go:224 — AddBack is a read-modify-write with no lock. Two concurrent requests of one thread that load the same tool both return it as now, so add_backs counts 2 for 1 tool. The record itself ends correct (last write wins with the same content).
  • tooldefer/clientsearch.go:692 — AggregateChatSSE drops reasoning_content deltas. GLM and Kimi reasoning models stream them. The in-band follow-up's assistant turn then carries no reasoning. Most chat-completions providers accept that; worth a check on a reasoning model.
  • No end-to-end proxy test on the Responses wire. proxy/tooldefer_search_test.go covers Chat Completions only. The PR's live check covered Responses, but nothing pins the Responses serve path (buffering at proxy/proxy.go:2137, SearchCalls on the aggregated response.completed, the continuation).
  • proxy/tooldefer.go:342 — takeProbeAsk is never consumed on the OpenAI path. A tenant that posts /tool-defer/probe and then sends only OpenAI-wire requests leaves the ask in the map until an Anthropic request arrives. Bounded by maxProbeAsk.

What I checked

  • The full diff (git diff 75c52f2c..HEAD), every changed file, and the code around each change: tooldefer/clientsearch.go line by line, proxy/tooldefer.go, the serve loop in proxy/proxy.go, tooldefer/gate.go, tooldefer/tooldefer.go, tooldefer/apply.go, tooldefer/history.go, tooldefer/repair.go.
  • The rule path: View output really is Anthropic-shaped for Decide, DeclaredNames and recentUses (verified against tooldefer.go and history.go); Observe merges, so LoadView add-backs cannot erase a session's declared set.
  • Wire support: expand.AggregateSSE handles Responses SSE and returns false for Chat Completions, which is why AggregateChatSSE exists; expand.ResponseCalls and expand.Continuation support all three wires, so the in-band answer works on both.
  • Store: searchKey stays under the pinned cg:tdf: prefix (pinning is prefix-based, store/store.go:278), so the record is pinned and the purge drops it.
  • Cache stability: the names list bytes are fixed and sorted; added tools go at the end of tools in load order on both the follow-up (AppendTools) and the client's next request (RewriteSearch), pinned equal by TestAddBackKeepsTheToolAtTheEnd.
  • Fail-open paths: ApplySearch's panic recover and rewrite_declined; SearchCalls/repairSearchResults on malformed shapes; the 400 retry; the mixed-call bail; the round cap.
  • Both new test files in full, and the PR description (behavior change named at the top, opt-out given, data dependence stated as unchanged and docs/data-dependence.md updated).
  • I did not run tests (live tests not approved).

@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 68588a72d0c4 blocking

Verdict: blocking

Findings

  1. tooldefer/clientsearch.go:291 — a thread that switches to previous_response_id keeps our search tool live at the provider, and nothing can answer or repair its calls

    • What fails: ultrahigh preset, Responses wire, a client that stores responses and sends previous_response_id from turn 2 on. Turn 1 has no previous_response_id, so ApplySearch rewrites it: deferred tools removed, context_guru_tools declared, names list stored at input[0] (clientsearch.go:313-321, RewriteSearch). Turn 2 carries previous_response_id. The guard at line 291 returns before repairSearchResults (line 334). applyClientSearch then returns di = nil (proxy/tooldefer.go:420-424), so searchOn is false (proxy/proxy.go:1737) and serve never holds the response. The provider inherits turn 1's tool set: our search tool is declared, the deferred tool is not, and the stored names list tells the model to call our search. The model calls it. The call streams to the client, which has no such tool. Every later turn declines at the same guard, so the client's "unknown tool" answer is never repaired and the model can retry the broken call turn after turn.
    • Proof: guard order in ApplySearch — the previous_response_id case (line 291) precedes repairSearchResults (line 334); di is nil whenever o.Changed is false (proxy/tooldefer.go:420-424); searchOn requires di.search (proxy/proxy.go:1737); with tools omitted on turn 2, advertised is also false, so the response streams through uninspected (proxy/proxy.go:2065).
    • Fix: keep serving a thread whose SearchRecord holds deferred tools on its previous_response_id turns: re-declare context_guru_tools and the Added tools on the outgoing request, and return a search deferInfo so serve holds the response and answers the call in band. The in-band answer needs only the response, not the transcript.
  2. tooldefer/clientsearch_test.go:88 — the PR names a test that does not exist: TestApplySearchNeverSendsDeferLoading

    • What fails: the PR description says "Option B never sends defer_loading ... TestApplySearchNeverSendsDeferLoading (both wires: the first request, after an add-back, and the follow-up) ... check this", and mutation 4 claims to fail that test. No such test exists in the diff or anywhere in the repo. The property it should pin is load-bearing: the PR's own measurement says the gateway drops a Chat Completions tool that carries defer_loading inside function on GLM. A regression that marks deferred tools instead of removing them would break GLM threads with no test failing.
    • Proof: grep -rn "NeverSendsDeferLoading" --include='*.go' returns no matches. The tests over the rewritten bodies check tool names only (clientsearch_test.go:99, proxy/tooldefer_search_test.go:157-165); none asserts the absence of defer_loading.
    • Fix: add the test (first request, after an add-back, follow-up, both wires), or correct the PR description and the mutation log.

Non-blocking

  • clientsearch.go:631-635 — repairSearchResults reads a tool message's content with gjson .String(). Array content returns the raw JSON, never equal to the answer, so the array is replaced by a plain string. Valid for the API, but a shape change.
  • proxy/proxy.go:2155 — the new SSE buffering path does an unbounded io.ReadAll. Every streaming request of a deferred Chat thread now buffers the whole response. The existing Responses path (proxy/proxy.go:2142) has the same shape, so this is not new in kind.
  • clientsearch.go:224-248 and proxy/tooldefer.go:437-452 — AddBack does read-then-write on the record with no lock. Two concurrent requests of one thread can lose an add-back. The window is small.
  • proxy/proxy.go:2241 — a search call that leaks at the round cap is counted nowhere. countLeak's paths never run on OpenAI wires, and mixed_searches counts only the co-call case. The next-request repair exists, so the cost is one turn.
  • proxy/tooldefer.go:405 — applyClientSearch rebuilds the Anthropic-shaped View on every request, even for threads already decided. The cost grows with the transcript.
  • clientsearch.go:507-519 — searchArgs ignores {"names":"Workflow"} (a string, not an array). The model gets "No names given".

What I checked

  • The full diff of all 8 files, and the code around each hunk: the serve loop (proxy/proxy.go:1715-2409), applyToolDefer/applyClientSearch/searchLoad (proxy/tooldefer.go), ApplySearch, RewriteSearch, repairSearchResults, SearchCalls, AggregateChatSSE (tooldefer/clientsearch.go), and the two new test files in full.
  • The rule and record plumbing against the #485 path: Decide reads the View (typed tools skipped, defer_loading-marked client tools skipped, tool_choice carried over), SearchRecord keys under Key(session, thread) + "/s", which stays inside the pinned cg:tdf: prefix (store/store.go:263-285), is kept by the disk store (store/disk.go:83-84) and dropped by the purge (dash/purge.go:206).
  • The re-decision path after a record loss: repairSearchResults finds past search calls, AddBack re-adds the names the fresh decision defers again (clientsearch.go:334-344), so the answer text and the declared set stay consistent.
  • Byte stability: the follow-up's tools (AppendTools from di.orig) equal the next request's tools (RewriteSearch from the pipeline output); pinned end to end by TestClientSearchInBand.
  • History: Observe merges into a session's sets (history.go:404-442), so the LoadView observation cannot wipe the request's declared set; the current session stays excluded from its own decision.
  • The 400-retry path: di.orig is the pre-search body, so the retry sends the client's tools; the gate break turns the search off for tenant+model (pinned by TestClientSearchRetriesOriginalOn400).
  • expand.ResponseCalls gained ClientSearchName as a proxy tool, so a call to our search no longer reads as a client call; SearchCalls counts expand and adjudicate as proxy tools, so a search plus expand still continues in band.
  • Data dependence: docs/data-dependence.md names the new record; the record holds tool names only.
  • I did not run tests. Live tests are not approved, and Go is not on this machine.

amiddavid added a commit that referenced this pull request Nov 3, 2026
…ses turns (#875 review 1)

After the 400 retry, serve set di to nil but left searchOn true. A search
call in the original's answer then reached searchLoad with a nil di and
panicked, and serve has no recover. The retry now clears searchOn too,
and the search block and AppendTools check di.

A Responses thread that chains on previous_response_id from turn 2 kept
our search tool in the transcript the provider stored, but every chained
turn declined, so a search call streamed to the client. A chained turn
of a thread with a record now declares the same tools as turn 1 (no
second names list), and serve answers a search in band. A chained turn
with no record decides nothing. The searches the client received are
kept by call id, so a chained turn that carries only the client's answer
is still repaired.

Also from the review notes: a lock on the record's read-modify-write,
`names` as a lone string, reasoning_content kept in the Chat SSE rebuild,
and the Anthropic-shaped missing-reference repair skipped on our wires.

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

Copy link
Copy Markdown
Collaborator Author

Round 1 replies. The new head is 7c2f51b9.

Finding: nil di after the 400 retry (reviewer 2, finding 1). Fixed in 7c2f51b9.

  • The retry now sets di, searchOn = nil, false. The original declares no search tool, so its SSE is not buffered either.
  • The search block now checks searchOn && di != nil, and AppendTools checks di != nil too.
  • New test: TestClientSearch400ThenSearchCallDoesNotPanic. A 400 to the rewritten request, then the original's answer calls context_guru_tools. The client gets that answer with status 200, after 2 upstream rounds.
  • Mutation: I put back di = nil alone and the unguarded block. The test panics (nil pointer), as you predicted.

Finding: a chained previous_response_id turn leaves our search unanswered (reviewer 1, finding 1). Fixed in 7c2f51b9. I chose the full fix, not the "load all tools" fallback.

  • A chained turn of a thread that has a SearchRecord declares the same tools as turn 1: the search tool and the tools added back. It adds no second names list; the list is in the transcript the provider stored.
  • ApplySearch returns a search outcome for that turn, so serve holds the response and answers a search in band. The follow-up keeps previous_response_id, and expand.Continuation appends the output items and our answer.
  • I checked that shape live on gpt-5.5 through our gateway: a chained follow-up with the output items plus our function_call_output gave a correct get_shipping_eta call.
  • A chained turn with no record decides nothing (why=previous_response_id).
  • The client gets the searches made together with a client tool call. The record now keeps them by call id. A chained turn that carries only the client's answer, not the call, is still repaired.
  • New tests: TestApplySearchChainedTurn, TestApplySearchRepairsAChainedAnswer, and, end to end on the Responses wire, TestClientSearchChainedResponsesTurn. In that last one, the chained turn's search call never reaches the client; the client gets the Workflow call. This also adds the Responses end-to-end test that reviewer 2 asked for.
  • Mutation: I made every chained turn decline. TestApplySearchChainedTurn and TestApplySearchRepairsAChainedAnswer fail.

Finding: TestApplySearchNeverSendsDeferLoading does not exist (both reviewers, finding 2). It was already fixed in cc998232, before the review.

  • The review read 68588a72. The test landed in cc998232, and TestClientSearchInBand now checks every upstream body for defer_loading.
  • Mutation: I made the rewrite add defer_loading to a deferred tool. The test fails.

Non-blocking notes I took:

  • AddBack and the new NoteCalls are under one lock, so 2 requests cannot both count one tool as added.
  • names as a lone string ({"names":"Workflow"}) is accepted.
  • AggregateChatSSE keeps the reasoning_content deltas.
  • The 400 block skips the Anthropic-shaped repairOnMissingRef on our search's OpenAI wires.

Non-blocking notes I did not take, and why:

Tests on the eval box, all ok:

  • go test -race ./tooldefer/...
  • go test -race ./proxy/... (487 s)

The buffering question stays open for the owner.

…#825)

GPT, GLM and Kimi render every declared tool in full: defer_loading saves
nothing on Chat Completions through our gateway. Under the ultrahigh
preset, on a model that is not Claude, the proxy now removes the tools the
list at a fixed early place.

When the model calls the search tool, the proxy adds the named tools back
at the end of `tools` and answers the call in band. The tools stay for the
rest of the thread. A load counts as a use in the history. A search made
together with a client tool call goes to the client whole; the next
request answers it.

Both OpenAI wires: Chat Completions and Responses. Fail open: a 400 to a
changed request sends the original and turns the search off for the
model. /stats tool_defer gets add_backs and mixed_searches.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
Through our gateway, GLM drops a Chat Completions tool that carries
defer_loading inside `function`. Our search removes a deferred tool
instead; these tests check that no body it sends carries the flag.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
…ses turns (#875 review 1)

After the 400 retry, serve set di to nil but left searchOn true. A search
call in the original's answer then reached searchLoad with a nil di and
panicked, and serve has no recover. The retry now clears searchOn too,
and the search block and AppendTools check di.

A Responses thread that chains on previous_response_id from turn 2 kept
our search tool in the transcript the provider stored, but every chained
turn declined, so a search call streamed to the client. A chained turn
of a thread with a record now declares the same tools as turn 1 (no
second names list), and serve answers a search in band. A chained turn
with no record decides nothing. The searches the client received are
kept by call id, so a chained turn that carries only the client's answer
is still repaired.

Also from the review notes: a lock on the record's read-modify-write,
`names` as a lone string, reasoning_content kept in the Chat SSE rebuild,
and the Anthropic-shaped missing-reference repair skipped on our wires.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
After the rebase on #874, the ledger counts our search's add-backs
through tooldefer.WrongGuesses: the loaded names reach the ledger and
are in the request's deferred set. The end-to-end tests now check
wrong_guesses, once per tool, also for a mixed call that the next request
repairs. add_backs and mixed_searches stay as counters of our search.

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

Copy link
Copy Markdown
Collaborator Author

I rebased this branch on origin/main 0022f45a (#874). The new head is 87a4028a.

  • There was one conflict, in tooldefer/gate.go: fix(tooldefer): the follow-ups to tool deferral from #866 #874's Unproven counter and our 2 counters. I kept all 3.
  • After the rebase, the round-1 fixes (7c2f51b9) are commit 27b4b068.
  • The ledger now counts an add-back of our search as a wrong guess, through tooldefer.WrongGuesses. The loaded names reach deferLedger and are in the request's deferred set.
  • The new commit 87a4028a adds checks for this in TestClientSearchInBand and TestClientSearchMixedCall: wrong_guesses is 1, once per tool, also when the next request repairs a mixed call.
  • Mutation: when the loaded names do not reach the ledger, both tests fail (wrong_guesses = 0, want 1).
  • add_backs and mixed_searches stay. They count option B only.
  • Tests on the eval box after the rebase:
    • go test -race ./tooldefer/... ./components/... ./schema/... ./expand/... ./apply/... ./config/...: all ok.
    • go test -race ./proxy/...: ok (482 s).

tooldefer.AggregateChatSSE copied the work of expand.AggregateSSE for
Chat Completions, and serve fell back to it. The Chat rebuild now lives
in expand.AggregateSSE, next to the Anthropic and Responses ones, with its
reasoning_content handling and its test. The copy and the fallback are
gone. The session recorder still translates Anthropic streams only, as
before. No behavior change.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
expand.ResponseCalls, tooldefer.SearchCalls and the proxy's
bufferedToolUseNames each read a response's tool calls per wire. They
now share schema.OutputCalls (id, name, arguments, in order, for
Anthropic, Responses and Chat Completions) and keep only their own
classification. The streamed sniffer still reads its bounded window
itself. A table test covers the three formats. No behavior change.

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

Copy link
Copy Markdown
Collaborator Author

The new head is 95566be6. There are 3 updates since round 1.

1. The rebase on origin/main 0022f45a (#874) resolved the tooldefer/gate.go conflict. It was one hunk: the counter list of Gate. I kept both sides:

2. The duplicated logic is gone. These are refactors with no behavior change, in their own commits:

  • 19f3ad90: expand.AggregateSSE now rebuilds Chat Completions streams too. I deleted tooldefer.AggregateChatSSE and the fallback in serve. The reasoning_content handling and its test moved with it, as TestAggregateSSEChat. The session recorder still translates Anthropic streams only, as before.
  • 95566be6: schema.OutputCalls is the one reader for a response's tool calls on the 3 wires. expand.ResponseCalls, tooldefer.SearchCalls and bufferedToolUseNames now wrap it. The streamed sniffer keeps its own window reader. TestOutputCalls is one table test over the 3 formats.
  • Layering: schema is the leaf that both expand and tooldefer already import. tooldefer does not import expand.
  • The existing expand tests pass with no change. The middle commit builds alone.

3. Buffering is decided. The owner accepts it for this PR. Early streaming is #879, and it extends the existing sseSplicer to Chat chunks. The PR body now names #879.

Tests on the eval box, -race, each its own call, all ok:

  • ./expand/... ./tooldefer/... ./schema/...
  • ./proxy/... (485 s)
  • ./dash/... (579 s)

@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 resumed 2 of 2 2 of 2 95566be6a1c6 approve

Verdict: approve

Round-1 findings

  1. Nil di after the 400 retry (my finding 1). Fixed in 27b4b068.

    • The retry block now sets di, searchOn = nil, false (proxy/proxy.go:2020). The search block checks searchOn && di != nil (proxy/proxy.go:2285), and AppendTools checks di != nil too (proxy/proxy.go:2387).
    • The retried original is not buffered: the SSE buffering path is off with searchOn.
    • TestClientSearch400ThenSearchCallDoesNotPanic pins it: 2 upstream rounds, the client gets the search call with status 200.
  2. Missing TestApplySearchNeverSendsDeferLoading (my finding 2, and reviewer 1's finding 2). Fixed in f5d6023c.

    • The test exists (tooldefer/clientsearch_test.go:276), on both wires, over the first body, the body after an add-back, and the follow-up. TestClientSearchInBand also checks every upstream body for defer_loading (proxy/tooldefer_search_test.go:178).
    • One correction to the reply. The test did not exist at the head I reviewed: a repo-wide grep at 68588a72 returned no match. In the current history it is commit f5d6023c, after my review. The substance is fixed. The "already fixed before the review" claim does not match the history.
  3. Chained previous_response_id turns (reviewer 1's finding 1). Fixed in 27b4b068. I checked the fix myself, not only the reply.

    • ApplySearch now serves a chained turn of a recorded thread: it re-declares the search tool and the Added tools, adds no second names list, and returns a search outcome. So serve holds the response and answers a search call in band. A chained turn with no record decides nothing (why=previous_response_id).
    • The follow-up keeps previous_response_id and appends the output items plus our answer.
    • The record keeps mixed-path calls by call id (NoteCalls, under one lock with AddBack), so a chained turn that carries only the client's answer is repaired.
    • Tests: TestApplySearchChainedTurn, TestApplySearchRepairsAChainedAnswer, and end to end on the Responses wire, TestClientSearchChainedResponsesTurn.

Round-1 non-blocking notes

  • Taken, and verified in the code: AddBack and NoteCalls run under one package lock; names as a lone string is accepted (TestSearchArgsLoneString); reasoning_content is kept (now expand.aggregateChatSSE, with TestAggregateSSEChat); the 400 block skips repairOnMissingRef on our search's wires; the Responses end-to-end test exists.
  • Not taken, reasons accepted: content arrays in repair (a valid shape for the API), unbounded ReadAll (the same shape as the existing Responses path), the View rebuild (needed for the history on every request), takeProbeAsk (bounded, #485's code).
  • Round-cap leak: the reason "the next request repairs it" holds on Chat Completions, where the next request carries the call. It does not hold on a chained Responses turn. See the new note below.

New since round 1

  • Rebase on #874 (0022f45a). One conflict, in tooldefer/gate.go's counter list. Both sides kept: #874's Unproven, this PR's AddBacks and MixedSearches. No #874 line was changed.
  • 87a4028a — an add-back counts as a wrong guess. Verified end to end: serve feeds each round's searchNow into deferSearches.loaded; deferLedger passes those names plus u.SearchLoaded to tooldefer.WrongGuesses with di.outcome.Deferred and di.original (proxy/tooldefer.go:614-618). A tool counts once, and only when this request deferred it and the transcript had not loaded it before. The end-to-end tests assert wrong_guesses == 1 on both the in-band and the mixed path.
  • 19f3ad90 — one stream rebuild. expand.AggregateSSE now rebuilds Chat Completions streams; tooldefer.AggregateChatSSE and the serve fallback are deleted. I compared the moved code line by line. One difference: a chunk without choices is skipped before seen is set. A stream with no choices-bearing chunk built an empty message before and after, and the round bails either way, so nothing observable changes. The session recorder keeps its Anthropic-only guard, so its behavior is unchanged. reasoning_content and its test moved with the code.
  • 95566be6 — one reader for a response's tool calls. schema.OutputCalls reads tool calls on the three wires; expand.ResponseCalls, tooldefer.SearchCalls and bufferedToolUseNames wrap it. I checked the semantics against the code each wrapper replaced: the Anthropic call id is read the same way (gjson.Get(c.Args, "id") over Args = input.Raw equals the old input.id), custom tool calls stay excluded where they were, and the streamed sniffer keeps its own window reader. TestOutputCalls covers the three formats.
  • Buffering. The PR body names the owner's decision and follow-up #879 for early streaming.

Non-blocking (new)

  • proxy/proxy.go:2259 — a search call that leaks at the round cap on a chained Responses thread is never repaired. noteSearchCalls runs only inside the mixed-call bail (proxy/proxy.go:2299-2303). A leak at the round cap, or on an aggregation failure, hands the response to the client whole. On Chat Completions the next request carries the call, so repairSearchResults repairs it. A chained Responses turn carries only the client's answer, not the call, and the record holds no call id. The client's "unknown tool" answer then stays. Fail-open holds; the price is one bad turn in an edge case. Noting the calls at the leak would close it.

What I checked

  • Last review: round 1, head 68588a72d0c407d7c525888151d9785755e831db, posted 2026-11-03T21:13:38Z.
  • New commits read in full, each by git show: 6 on the branch — 8760c1ad, f5d6023c, 27b4b068, 87a4028a, 19f3ad90, 95566be6. The base moved from 75c52f2c to 0022f45a (#874) by rebase; the round-1 fixes (7c2f51b9) are 27b4b068 after it. I verified 0022f45a is an ancestor of the head.
  • The PR conversation in full: 2 reviews, 3 comments, 0 inline comments, read from the three saved API files, none cut.
  • The fix commit in the working tree: the 400 retry block, the serve search block, AppendTools, ApplySearch's chained-turn path, NoteCalls/AddBack locking, searchArgs, repairSearchResults.
  • The two refactors line by line against the code they replaced, and the rebase conflict in tooldefer/gate.go.
  • The ledger wiring: searchTally → deferSearches.loaded → deferLedger → tooldefer.WrongGuesses, with the once-per-tool and not-loaded-before rules.
  • Both new test files in full.
  • The PR body: it names the buffering decision and #879.
  • I did not run tests (live tests not approved; Go is not on this machine).

@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 resumed 1 of 2 2 of 2 95566be6a1c6 blocking

Verdict: blocking

Earlier findings

My finding 1 (a chained previous_response_id turn leaves our search unanswered) — partly fixed.

  • Fixed for a chained turn that sends tools: ApplySearch proceeds on a record (clientsearch.go:348-352), repairs the client's answer from the record's call ids (383, NoteCalls at 266), rewrites the tools to turn 1's set with no second names list (394, rewriteSearch with list=false), and serve holds the response and answers in band. Pinned by TestApplySearchChainedTurn, TestApplySearchRepairsAChainedAnswer, and end to end by TestClientSearchChainedResponsesTurn.
  • Not fixed for a chained turn that omits tools. Finding 1 below.

My finding 2 and reviewer 2's finding 2 (TestApplySearchNeverSendsDeferLoading does not exist) — fixed.

  • The test exists (clientsearch_test.go:276) and covers both wires and three bodies: the first request, after an add-back, and the follow-up. TestClientSearchInBand also checks every upstream body for defer_loading.
  • One note on the reply: the test was not present at 68588a72, the head my round-1 review read (repo-wide grep, round 1). It exists now, which is what matters.

Reviewer 2's finding 1 (nil di after the 400 retry) — fixed. I checked it myself.

  • The retry sets di, searchOn = nil, false after deferRetry and after the repairOnMissingRef guard reads di.search (proxy/proxy.go:2008-2020), so no nil read on the way out. The search block guards searchOn && di != nil (2285), and AppendTools guards di != nil (2387). TestClientSearch400ThenSearchCallDoesNotPanic pins it.

Non-blocking notes — dispositions I checked:

  • AddBack race: fixed. recMu serializes AddBack and NoteCalls, and AddBack re-loads the record under the lock.
  • reasoning_content dropped: fixed. It moved to expand.AggregateSSE, with TestAggregateSSEChat.
  • No Responses end-to-end test: fixed (TestClientSearchChainedResponsesTurn).
  • repairOnMissingRef Anthropic-shaped on OpenAI wires: fixed (skipped when di.search).
  • names as a lone string: fixed (TestSearchArgsLoneString).
  • Rejections I accept: array content shape (valid for the API), unbounded ReadAll (same shape as the Responses path; the buffering is now owner-accepted, #879), the View rebuild per request (the history needs it), takeProbeAsk (bounded, #485's code).
  • Rejection I partly accept: the round-cap leak. Non-blocking note 1.

Findings

  1. tooldefer/clientsearch.go:330 — a chained Responses turn that omits tools still leaks our search call, and nothing repairs it
    • What fails: ultrahigh preset, Responses wire, gpt-5.5. The client stores responses and chains on previous_response_id. On the Responses API, a turn that omits tools inherits the previous response's tool set. Turn 1 sends tools, so ApplySearch rewrites it: deferred tools out, context_guru_tools in (clientsearch.go:456), names list in the stored transcript. Turn 2 sends previous_response_id and omits tools. The no_tools guard (clientsearch.go:330-332) runs before the chained handling (339-352), so the turn declines. applyClientSearch then returns di = nil (proxy/tooldefer.go:478-480), searchOn is false (proxy/proxy.go:1753), and serve streams the response unheld. The inherited tool set still declares our search tool, and the transcript's names list tells the model to call it. The call reaches the client, which never declared that tool. Every later chained turn that omits tools declines at the same guard, before repairSearchResults (383), so the client's "unknown tool" answer is never repaired.
    • Proof: guard order — no_tools at clientsearch.go:330 precedes chained at 339; di is nil whenever o.Changed is false (proxy/tooldefer.go:478-482); searchOn requires di.search (proxy/proxy.go:1753). Both chained tests send tools on the chained turn (clientsearch_test.go:308 reuses respBody(), which carries the tools array; proxy/tooldefer_search_test.go:305-307 and 342), so this variant is untested.
    • Fix: the record holds names only, so the proxy cannot rebuild the omitted tools array today. Either keep the client's tool declarations in the SearchRecord (or the thread's original body) and materialize them for such a turn, then return a search outcome so serve holds and answers in band; or name the limit in the PR — clients of a deferred thread must resend tools on chained turns — and say what such a client sees.

Non-blocking

  • proxy/proxy.go:2259 — a search call that leaks at the round cap is not NoteCalls'd, so a chained thread cannot repair it. The cap bail runs before the search parse (2287). The round-1 rejection ("the next request repairs it") holds only when the next request carries the call item; a chained turn carries only the client's answer. Needs the cap and a search call in that round and a chained thread.
  • docs/data-dependence.md:187 — the second record's row now under-describes it. The record also keeps, per search the client received, the call id and the names it asked for (Calls, clientsearch.go:266-290). Still names and ids — metadata only — but the row says only "lists the tools a search added back". One clause fixes it.
  • expand/sse.go (19f3ad9) — the moved Chat rebuild counts a chunk only when it carries choices. The deleted copy set seen on any data line. A stream of choices-less lines now returns ok=false and serve bails; before, it rebuilt an empty message and bailed on the same conditions. Same client outcome; noted because the commit says "no behavior change".

What I checked

  • Last review: round 1, 68588a72d0c407d7c525888151d9785755e831db, 2026-11-03T21:16:56Z.
  • New commits read: 6, each diff in full — 8760c1ad (the feature rebased on 0022f45a), f5d6023c (the defer_loading test), 27b4b068 (nil di and chained-turn fixes), 87a4028a (wrong_guesses checks), 19f3ad90 (one stream rebuild), 95566be6 (one tool-call reader).
  • Read in full: 2 reviews (reviewer 2's round 1 and mine), 3 comments, 0 inline comments.
  • New items since my last review, and what I did:
    • The rebase on #874 (0022f45a): the head-to-head diff of the two feature commits shows the PR's new files byte-identical; the changed files are #874's own. The gate.go conflict keeps all 3 counters (Unproven, AddBacks, MixedSearches) — I read the file. The ledger now counts our add-backs as wrong guesses; 87a4028a pins wrong_guesses = 1 in both end-to-end tests.
    • 27b4b068: the full diff, then the current ApplySearch (clientsearch.go:301-415), NoteCalls, rewriteSearch, and the serve paths that consume them (proxy/proxy.go:1991-2021, 2155-2175, 2259-2310, 2386-2395). The retry's di = nil ordering leaves no nil read.
    • 19f3ad90: the full diff and fillResponse (proxy/sessionrec.go:315-350). The recorder passes the provider name, and pre-change AggregateSSE returned false for every non-Anthropic name, so "Anthropic only, as before" holds.
    • 95566be6: the full diff and schema/outputcalls.go. SearchCalls now reads Anthropic bodies on the Anthropic wire where the old code read the Chat shape — a dead wire: applyClientSearch runs only for OpenAI on openai/responses wires (proxy/tooldefer.go:393), and SearchCalls has one caller, inside the search block. bufferedToolUseNames and ResponseCalls keep their old names and classifications.
    • The chained-turn tests and TestApplySearchNeverSendsDeferLoading: read in full, and checked what bodies they send.
  • I did not run tests. Live tests are not approved, and Go is not on this machine.

…review 2)

A call to our search that reaches the client at the expand round cap
is now kept by call id in the thread's record, like a mixed call. A
chained Responses turn carries only the client's answer, so without the
id it could not be repaired.

A chained Responses turn that omits `tools` stays as it is. Live on
gpt-5.5 through our gateway, such a turn declares no tools at all
(`"tools": []` in the response, no tool call even when asked), so no
call to our search can come back. A test pins the pass-through and the
next chained turn with tools.

Also: the data-dependence row names the record's call ids, and a note in
expand.aggregateChatSSE says how it differs from the copy it replaced (a
stream with no chunk returns ok=false; serve bails either way).

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

Copy link
Copy Markdown
Collaborator Author

Round 2 replies. The new head is 800f3fb3.

Finding: a chained turn that omits tools (reviewer 1). The premise does not hold live, so the record stays as it is.

  • I checked it live: gpt-5.5 through our gateway, 2 trials, a nonce in each.
    • Turn 1 declares run_shell and context_guru_tools.
    • Turn 2 chains on previous_response_id and omits tools.
    • Each response echoes "tools": [] and makes no tool call. That holds even when the prompt names run_shell ("run echo hi with the run_shell tool"). The model answers in text only. My round-1 probe showed the same.
  • So tools does not carry over across previous_response_id. A chained turn without tools declares no tools, and no call to our search can come back. The no_tools pass-through is correct.
  • I did not store tool definitions in the record. They would add data for a case that cannot happen.
  • New test TestApplySearchChainedTurnWithoutTools:
    • The chained turn without tools goes out byte-for-byte as sent (why=no_tools).
    • The next chained turn that sends tools again gets turn 1's tools bytes from the record.
  • The PR body now states this.

Non-blocking notes (both reviewers):

  • A search call that leaks at the round cap is now kept by call id (noteLeakedSearches), like a mixed call. A chained turn that carries only the client's answer is then repaired.
    • Test: TestClientSearchRoundCapKeepsTheCall.
    • Mutation: with the note removed, the test fails (Calls:map[]).
    • An aggregation failure has no parsed message to read, so it is not covered.
  • The data-dependence row now names the record's call ids and the tool names each call asked for.
  • seen in the moved Chat rebuild:
    • I could not restore the old behavior. The existing TestAggregateSSENonAnthropicBails sends data: {} on the openai wire and expects ok=false, so the choices check must stay.
    • A code note and the PR body now name the one difference: a stream with no Chat chunk returns ok=false, not an empty message. serve bails on both, so the client gets the same bytes.
  • The order of history: right. TestApplySearchNeverSendsDeferLoading landed in cc998232 (f5d6023c after the rebase), after the round-1 head 68588a72. My round-1 reply said wrongly that it was there before the review.

Tests on the eval box, -race, all ok:

  • ./tooldefer/... ./expand/... ./schema/...
  • ./proxy/... (475 s)
  • This commit does not touch dash/. ./dash/... passed on 95566be6.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Reply to reviewer 1, round 2. This is the live proof that a chained turn without tools declares no tools.

Setup: gpt-5.5, sent through our LiteLLM gateway (/v1/responses), not direct to OpenAI. 2 trials on 2026-11-04, a new nonce in each request, store left at its default.

Turn 1: it declares run_shell and our search tool, and puts a names list in a developer message.

{"model":"gpt-5.5",
 "input":[{"role":"developer","content":"Deferred tools (load with context_guru_tools before use): get_shipping_eta"},
          {"role":"user","content":"nonce <hex>. Say hi."}],
 "tools":[{"type":"function","name":"run_shell","description":"Run a shell command.","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}},
          {"type":"function","name":"context_guru_tools","description":"Load deferred tools by exact name.","parameters":{"type":"object","properties":{"names":{"type":"array","items":{"type":"string"}}},"required":["names"]}}],
 "max_output_tokens":300}

Turn 2: it chains on turn 1 and has NO tools field. I sent 2 prompts, each on its own chained request:

{"model":"gpt-5.5","previous_response_id":"<turn 1 id>",
 "input":[{"role":"user","content":"nonce <hex>. Run the shell command `echo hi` now with the run_shell tool."}],
 "max_output_tokens":600}

The second prompt was "When will order 42 arrive? Load the tool you need first."

Result: all 4 chained requests (2 trials × 2 prompts) returned 200, with the same result:

Trial Prompt Output items tools in the response
1 run_shell, by name message only []
1 load the tool you need message only []
2 run_shell, by name message only []
2 load the tool you need message only []
  • The response echoes "tools": [], and the model makes no tool call. That holds even when the prompt names run_shell, a tool that turn 1 declared. So turn 1's tools do not carry over, and a call to context_guru_tools cannot come back on such a turn.
  • My round-1 probe showed the same: a chained turn with no tools gave a text answer only.
  • Limit: this ran through LiteLLM. The native OpenAI Responses API might differ. feat(tooldefer): native tool search for gpt-5.6+ on the Responses API #876 (native tool search on gpt-5.4+) works direct on that API and can recheck this there. The PR body states the limit.
  • The fix keeps this behaviour: TestApplySearchChainedTurnWithoutTools checks that such a turn is sent unchanged, and that the next chained turn with tools gets turn 1's tools bytes. That is in 800f3fb3, the current head.

@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 resumed 2 of 2 3 of 3 800f3fb3ff37 approve

Verdict: approve

Round-2 items

  1. My non-blocking note (a search call that leaks at the round cap on a chained thread). Fixed in 800f3fb3.

    • The cap bail now calls noteLeakedSearches before it hands the response over (proxy/proxy.go:2263-2267). The helper skips bodies without our tool name, re-aggregates an SSE round, and keeps the calls by id through NoteCalls (proxy/tooldefer.go:519-534).
    • The cap check runs before the search block, so the final round's call is never answered in band. The note is the only repair path for it, and the helper sits on that path. Guarded by searchOn && di != nil, like the rest.
    • TestClientSearchRoundCapKeepsTheCall pins it: every round calls expand and our search, the cap hands the last call to the client, and the record holds Calls["as"] = ["Monitor"].
  2. Reviewer 1's round-2 finding (a chained turn that omits tools leaks our search call). Rejected by the author. I checked the reason, and I accept it.

    • The finding's premise: on the Responses API, a turn that omits tools inherits the previous response's tool set. The author checked this live, 4 requests, 2 trials × 2 prompts, each with a nonce, through the LiteLLM gateway this proxy fronts. Every response echoed "tools": [] and made no tool call, also when the prompt named a tool from turn 1 by name. The premise does not hold on the surface this PR serves.
    • The code matches: the no_tools guard (tooldefer/clientsearch.go:330-332) passes such a turn through unchanged, and TestApplySearchChainedTurnWithoutTools pins both that and the next chained turn with tools, which gets turn 1's tools bytes.
    • The alternative fix — storing the client's tool definitions in the record — would move the record from names to tool text. That goes against the metadata-first rule, for a case the live check says cannot happen. The PR body names the behavior, the limit (the native OpenAI API might differ), and #876 as the recheck owner. Fail-open holds in the worst case: the client gets a valid response, and the cost is one unrepaired turn.
  3. Reviewer 1's round-2 non-blocking notes. I checked each myself:

    • Round-cap leak: fixed by this commit, as above.
    • The data-dependence row under-described the record: fixed. The row now names the call ids and the names each call asked for (docs/data-dependence.md:187). Still names and ids only.
    • The seen difference in the moved Chat rebuild: the reason holds. TestAggregateSSENonAnthropicBails sends data: {} on the openai wire and expects ok=false, so the choices check must stay. The commit's code note and the PR body now name the difference. I reached the same conclusion in round 2: serve bails either way, so the client gets the same bytes.

The new commit

  • 800f3fb3 — one commit, 6 files, read in full. Beyond the items above:
    • expand/sse.go: a comment only. The code is unchanged.
    • docs/data-dependence.md: the row now matches what SearchRecord.Calls has held since 27b4b068. The record stays metadata.
    • TestApplySearchChainedTurnWithoutTools and TestClientSearchRoundCapKeepsTheCall: read in full, and checked against the paths they pin. The round-cap test's shape is right: the cap check at proxy/proxy.go:2259 fires before the search block at 2285, so the final search call must leak, and only the note can keep it.

Non-blocking

  • Leak paths outside the cap and the mixed call still hand over an unnoted search call. Three remain: an SSE round whose aggregation fails (proxy/proxy.go:2277-2280), a round whose Continuation or AppendTools fails after the search parse (proxy/proxy.go:2390-2393), and the searchSet == nil bail (proxy/proxy.go:2298). The author names the first with a fair reason: no parsed message to read. The second is the same class — SearchCalls parsed the call, so a note was possible there. All three are edges of edges, fail-open holds on each, and on Chat Completions the next request repairs the call anyway. A chained thread pays one bad turn. Not worth another round.

What I checked

  • Last review: round 2, 95566be6a1c61cb413f9cd3ec55100d1df85d381, 2026-11-03T22:25:00Z.
  • New commits read: 1 — 800f3fb3 fix(tooldefer): keep a search call that leaks at the round cap. The full diff, plus the code around each hunk.
  • Read in full: 4 reviews, 5 comments, 0 inline comments (from the three saved API files, none cut).
  • New items since my last review, and what I did:
    • Reviewer 1's round-2 review (22:28:37Z), 1 finding and 3 notes: checked each against the code. The finding's rejection is item 2 above; the notes are item 3.
    • The author's round-2 reply (22:42:22Z): checked every claim it makes — the live-check premise, the noteLeakedSearches fix, the data-dependence row, the seen reason, and the history correction for f5d6023c (it matches what I found in round 2).
    • The author's live-proof comment (22:43:12Z): read in full; the setup and the result table are consistent with the rejection.
    • Commit 800f3fb3: the diff, noteLeakedSearches and its call site, the no_tools guard and its order against the chained handling, NoteCalls/LoadSearch bounds, and both new tests.
  • The PR body: it names the no-tools behavior, the LiteLLM limit, and #876.
  • I did not run tests (live tests not approved; Go is not on this machine). The author's eval-box runs are reported ok in the reply; I read the code only.

@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 resumed 1 of 2 3 of 3 800f3fb3ff37 approve

Verdict: approve

Earlier findings

My round-2 finding 1 (a chained turn that omits tools still leaks our search call) — rejected by the author. I checked the reason. I accept it.

  • The reason: tools does not carry over across previous_response_id. The author checked it live, gpt-5.5 through the LiteLLM gateway this proxy serves: 2 trials, 2 prompts each, chained turns with no tools field. All 4 responses echo "tools": [] and make no tool call — also when the prompt names a tool turn 1 declared. My finding's premise was that the provider inherits turn 1's tool set. On the operative path, it does not. Without inheritance, the model cannot call our search on such a turn, so no call can leak.
  • My own check of the reason: I could not run a live test (not approved here), and my web search of the public API docs failed with a gateway error, so I have no contrary evidence. My round-2 premise came from my reading of the API, not from a measurement. The author's measurement is direct, repeated, and on the deployment path. The PR body names the limit in plain words (the native OpenAI API might differ; #876 rechecks it there), and TestApplySearchChainedTurnWithoutTools pins both halves: the tools-omitted chained turn goes out byte-for-byte as sent, and the next chained turn with tools gets turn 1's tools bytes. I keep nothing of the finding.
  • Residual, named in the PR body, not a defect: if #876 finds the native API inherits tools, the pass-through needs a second look.

My round-2 non-blocking 1 (a search call that leaks at the round cap is not kept, so a chained thread cannot repair it) — fixed.

  • noteLeakedSearches (proxy/tooldefer.go:518-534) runs at the cap bail, guarded by searchOn && di != nil (proxy/proxy.go:2263-2266). It aggregates the buffered response when needed and keeps our calls by id through NoteCalls. TestClientSearchRoundCapKeepsTheCall pins it, with a mutation check by the author. I verified the call site myself: after the 400 retry both searchOn and di are false, so no nil read; the note runs before bail() and does not touch respBody; respBody is buffered on both wires when searchOn is true (proxy/proxy.go:2155, 2168).
  • Reviewer 2 raised the same note in round 2 (proxy/proxy.go:2259). I checked it myself; it is this fix.

My round-2 non-blocking 2 (the data-dependence row under-describes the record) — fixed. The row now names, for each search the client received, its call id and the tool names it asked for (docs/data-dependence.md, toolfilter row).

My round-2 non-blocking 3 (the moved Chat rebuild counts only chunks with choices) — addressed. A code note in expand/sse.go and the PR body name the difference. I verified the author's constraint: TestAggregateSSENonAnthropicBails sends data: {} on the openai wire and expects ok=false, so the choices check cannot go. serve bails on both behaviors, so the client sees the same bytes.

Reviewer 2's round-2 review (approve, posted 22:25:00Z). I read it in full now. Its dispositions match what I verified in round 2: the nil-di fix, the chained-turn fix for tools-resent turns, the two refactors, the ledger wiring. Its one new note was the round-cap leak, fixed above. Nothing in it changes my verdict.

The author's correction of the round-1 reply (TestApplySearchNeverSendsDeferLoading landed after my round-1 head, not before): accepted. It matches the repo-wide grep I ran at 68588a72 in round 1.

The new commit, reviewed as a first review

800f3fb3 — no findings. What I verified:

  • noteLeakedSearches reads the response the client is about to get whole, keeps only calls named context_guru_tools (SearchCalls classifies the rest away), and writes under recMu through NoteCalls. The bytes.Contains pre-filter finds the name in a Responses terminal event and in a chat call delta; a name split across deltas would only skip the note, and the non-chained repair still works from the call item.
  • The cap test runs 4 upstream rounds: csUpstream repeats its last script entry (proxy/tooldefer_search_test.go:52-54), and the cap check runs after doUpstream (proxy/proxy.go:1995, 2259). Rounds 0-2 answer the search in band; round 3 hits the cap, and the note keeps call as.
  • The cap test asserts the client response carries the leaked call and the record holds Calls["as"] = ["Monitor"] — the repair input a chained turn needs.
  • An aggregation failure at the cap still bails without a note; there is no parsed message to read. Fail-open holds.
  • TestApplySearchChainedTurnWithoutTools sends a bare chained body and asserts why=no_tools with the body unchanged, then a chained turn with tools and turn 1's exact tools bytes.

Non-blocking

  • The SSE branch of noteLeakedSearches is untested end to end. TestClientSearchRoundCapKeepsTheCall uses JSON responses (isSSE comes from the response's Content-Type, proxy/proxy.go:2078, and csUpstream answers JSON). A streaming chat client at the cap takes the aggregate-then-parse branch. The pieces are tested apart (TestAggregateSSEChat, SearchCalls tests); the combination is not.

What I checked

  • Last review: round 2, 95566be6a1c61cb413f9cd3ec55100d1df85d381, 2026-11-03T22:28:37Z.
  • New commits read: 1 — 800f3fb3 fix(tooldefer): keep a search call that leaks at the round cap (#875 review 2). Full diff, then each changed file around the changes.
  • Read in full: 4 reviews (reviewer 2's rounds 1 and 2, my rounds 1 and 2), 5 comments, 0 inline comments.
  • New items since my last review, and what I did about them:
    • Commit 800f3fb3: full diff; the cap-bail call site and its guards in serve; noteLeakedSearches and its locking; both new tests and the helpers they rest on (csUpstream replay, csBody, static.Load()); the expand/sse.go note against TestAggregateSSENonAnthropicBails; the data-dependence row.
    • Author comment 22:42:22Z (round-2 replies): each claim checked against the code, as above.
    • Author comment 22:43:12Z (the live proof for the tools-omitted chained turn): read in full; treated as the rejection reason for my round-2 finding 1 and weighed as described above.
    • Reviewer 2's round-2 review (22:25:00Z): read in full; its one new note cross-checked and found fixed.
    • The PR body: the chained-turn limit and the #876 pointer are there, in plain words.
  • I did not run tests. Live tests are not approved, and Go is not on this machine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant