Repository navigation
fix(proxy): the expand tool_use that reached the client, on both sides - #103
Merged
Merged
Conversation
added 3 commits
August 23, 2026 16:33
A real session received
context_guru_expand
IN { "id": "..." }
OUT <tool_use_error>Error: No such tool available: context_guru_expand</tool_use_error>
which is the CLIENT's error for a tool only we implement. The proxy advertises
context_guru_expand and its own marker text tells the model to call it, so a
call reaching a client is our bug.
The SSE peek decides on the FIRST content_block_start: anything that does not
OPEN with the expand call is streamed, decided, no further peeking. A tool_use
is almost never the first block — a turn opens with thinking or with text — so
the interception condition is essentially never met on streaming traffic.
Production says the same thing: sse_expand_after_stream 22 against
sse_buffered 1.
Two tests, both red: a response whose first block is text (and one whose first
block is thinking) and whose SECOND block calls expand must not hand the client
that block, and the blocks before it must still reach the client while the model
is generating.
Signed-off-by: Osher-Elhadad <[email protected]>
…r the client's error Response side. peekSSE decided on the first content_block_start, so a response that opened with thinking or text and called expand later was streamed through and the client got a tool_use for a tool only this proxy implements. sseSplicer decides per BLOCK instead: it forwards events as they arrive, stops at the content_block_start that calls expand, runs the continuation, and writes round 2's blocks into the same stream with their indices shifted past the ones already sent and their message_start dropped. The client keeps its stream and never sees our tool. Request side. Some paths cannot be intercepted at all — the model batches expand with a tool only the client owns, the round cap, a stream that will not reconstruct, a non-Anthropic dialect, a bypassed turn carrying older markers. All of them converge on the next request, so expand.RepairToolResults answers there: every tool_result for our own tool gets the resolved original instead of `No such tool available`, is_error cleared, byte-stable so the repair does not cost the prefix cache a turn. streamFrom collapses back into stream (its head parameter and the name-scanning counter existed for the peek), and sse_expand_after_stream now counts the structural fact — the client was handed our tool_use — instead of the tool name appearing in bytes going past, which the model could also write in prose. Signed-off-by: Osher-Elhadad <[email protected]>
…assertion A rewrite of the client's own transcript must not be silent: cg.expand_repair is the only line that says the response side failed to withhold the call and the request side caught it. Debug level, and only when something was actually restored. And TestMarkerFreeSSEStreamsThrough goes back to the assertion it wanted. It was weakened to "the peek ended at the first content_block_start" because a peek has to hold the deciding event before it can decide; splicing decides per event, so the model's first delta reaches the client while the upstream is still generating, and the test says that again. Both streaming assertions now read until the wanted bytes arrive with a deadline shorter than the upstream's own fallback, because the proxy flushes per SSE event: one Read returns one event, and a test that just kept reading would be satisfied by the fallback firing on a fully buffering proxy. Signed-off-by: Osher-Elhadad <[email protected]>
added 9 commits
August 23, 2026 17:16
…an fail Once the prefix is on the wire the response is committed, and two failure paths were still writing as if it were not. An upstream error on a continuation round called http.Error, which appends a 502 body to an open event stream — a status no client can read, arriving as garbage inside the model's turn. It now hands back the events the splice withheld, the same fail-open as every other round the loop cannot finish. A continuation round that answers with JSON instead of an event stream cannot be spliced at all. withheld deliberately keeps the previous round's events so the turn terminates with a complete message instead of being cut off mid-block; a reset there looked tidy and silently truncated the client. Both are tested, and the second test's upstream counter is atomic because a hijacked connection gives the assertion no happens-before edge. Signed-off-by: Osher-Elhadad <[email protected]>
The cap short-circuited the withholding, so the terminal round streamed straight through and the tool_use the client received was invisible on /stats — the one leak the counter exists for, uncounted. Withholding and handing back is the same bytes and makes it a number, and it deletes the special case that existed only to skip it. Signed-off-by: Osher-Elhadad <[email protected]>
Two regressions in the splice, both measured rather than argued, and one corrected claim. The bound. ssePeekMaxBytes used to stop an unreadable or oversized preamble at 64 KB; removing the peek removed that, so one pathological stream — a runaway generation, an upstream that never sends message_stop — was retained in full with nothing to stop it. sseRetainMaxBytes is that bound, restored where it can now live. Past it the round is forwarded whole: anything already withheld is handed back first, nothing is dropped, the client's turn still terminates, and an expand call it contains reaches the client and is COUNTED, then repaired on the next request. 16 MiB is the first power of two above the largest legitimate round, so it never fires on real traffic. Measured: this gateway accepts max_tokens up to 128,000 (200,000 is refused by the model), and a stream runs ~35 B per output token, so a full-length response is ~4.5 MB; one token per delta would pay ~109 B per token and reach ~14 MB. The parsing. Reading events one at a time built a payload string per event, and a 2.25 MB round is ~18,750 events. Two free substring rejects — a content_block_start test before the expand check, and, when no renumbering is due, a "_start" test before the rewrite parse — take the churn from 8.0x the stream to 4.8x, against 3.2x for the whole-response buffering this replaced. The event buffer is reused across the round for the same reason. The claim. "The memory the old buffered path used, minus the latency" was true of retained bytes and false of allocation, and a reader could not tell which was meant. The comment now states both numbers separately. Signed-off-by: Osher-Elhadad <[email protected]>
Review found one blocker, and it is the same class as the reset that truncated a JSON round: `withheld = nil` was ONE instance, and `sp.pass` re-opened the same door through its return value. Once the splice withholds round 1's message_delta and message_stop, that round holds the only terminator the client will ever get. A continuation round is not obliged to carry one — it can come back empty, truncated mid-generation, or in another dialect — and the client was then left with a half-open message. That is a REGRESSION against main, where those rounds cannot arise at all: there the client gets a complete stream with the leaked tool_use, which the request-side repair then answers next turn. Trading a complete stream for an unterminated one is not a trade we get to make. sseSplicer records whether a message_stop went out and terminate() closes the turn with the withheld round's own closing events if nothing did — the closers only, never the content they were withheld alongside, so no invented bytes and no leaked tool_use. Four shapes tested: empty, truncated, OpenAI-shaped, and an error event instead of an answer. The nested case — a spliced round that calls expand again — is tested too. Also from the review: - The repair charged the dashboard row on EVERY later turn that re-sent the same stale error. ExpandTokens is subtracted from a unique-counted SavedUnique, so that drove the headline savings arbitrarily negative on a unit mismatch. The kept-verbatim mark already records the first recovery; offload.KeptVerbatim reads it, and the row is charged once. - An id-less tool_use for our tool made "" a live key, so a tool_result with no tool_use_id — someone else's block — was overwritten. Both halves of the pair must now name an id. - serve's doc comment still described marker-gated buffering and named peekSSE, which this branch deletes. Every clause of it was false. - A block generated AFTER the expand call is dropped from the client while the continuation does send it back upstream, so the two transcripts diverge. Not fixed; added to the honest-limits list, which is where it belongs. And the measurements are retained as files under docs/results/expand-splice-2026-08 rather than living only in a review thread: 39 timestamped turns for the decision point, and the SSE-bytes-per-output-token rows that set sseRetainMaxBytes. Signed-off-by: Osher-Elhadad <[email protected]>
sseRetainMaxBytes is derived from a max_tokens ceiling this proxy does not set — it only ever reads max_tokens, so the number is the upstream's and moves when the upstream does. The comment says so, with the re-derivation, because that is the input a future reader will find stale. And the numbers behind it go on disk rather than living in a review thread: per-code-path retention and churn, the attribution that found the real cost (sseEventPayload called twice per event, not the event buffer), the two instrument hazards it hit — a GC inside one arm, and the httptest recorder's own buffer growth — and the max_tokens ceilings each model enforces. The row that would flatter the fix is marked "do not quote", because it omits the per-event parsing that turned out to be the whole cost. Signed-off-by: Osher-Elhadad <[email protected]>
`mkdocs build --strict` aborts on any .md under docs/ that is absent from nav, and the measurement dump is evidence rather than a page for the site. Same shape as docs/results/extract-llm-2026-08, which stays out of nav by carrying no markdown at all: README.md -> README.txt, content unchanged. Signed-off-by: Osher-Elhadad <[email protected]>
terminate could only forward closing events that EXIST in the withheld bytes, and a round that was itself truncated has none — so four shapes still left the client mid-message. And it was wired to one of the three spliced exits: not the upstream-error exit, not bail. When the scan finds no closer anywhere, the client now gets an `error` event. Not a synthetic message_stop: the turn genuinely failed, no stop_reason in the enum means "truncated", and end_turn would report a broken turn as one that finished normally. Wired at all three exits, idempotent through sp.ended. Tested at each. Also from the delta check: - The retain bound's margin is ~3%, not headroom: framing is ~123 B per delta, so one token per delta reaches ~16.3 MB against 16 MiB. The constant does NOT move — typical full-length traffic is 4.5 MB, 3.4x under, and overshoot degrades by construction into exactly the pre-splice behaviour. The comment says that so nobody reads 3% as a cliff, and says the ceiling is the upstream's, since this proxy never caps max_tokens. - The published opus-4-7 figure did not reproduce from its own retained rows: +3.66 +/- 1.24 was wrong, it is +3.96 +/- 0.64. Every figure is now the one a reader gets by recomputing from the file, and the file says its times are rounded to 10 ms so the two cannot silently drift again. "First event at 40-55% of wall" is a median of 0.49, range 0.23-0.81. - The README claimed the ~4.5 MB typical case sets sseRetainMaxBytes. It does not; the one-token-per-delta case does. - peekSSE is gone, so the comments and the metric doc that still described it are gone with it. Signed-off-by: Osher-Elhadad <[email protected]>
…g change Two comments said reusing the event buffer took 13.3x down to 4.8x. Applying this repo's own retained rule — subtract the recorder artifact before comparing against the old path — neither half survives: 13.33 is recorder-inclusive and 4.81 is not, so the comparison handed these changes 3.73x of httptest cost that never existed in production, and the substring pre-filters did most of the work the reuse was credited with. Recorder-free throughout, one unit: per-event 9.60x -> +reuse 8.01x -> +pre-filters 4.81x, against 3.16x for the whole-response buffering this replaced. A halving, and still 1.52x more than what it replaced. The reuse stays because correct and cheap is reason enough. Also: the scratch row that must not be quoted carried 4.80 against the shipped path's 4.81, one row apart, so a reader reconciling the two had to read the note to tell which was which. The row now carries a third decimal and the shipped one says how to quote it — the label should not have to do that work. And the client-stream guarantee is scoped rather than absolute, on the third attempt at that sentence: closed whenever the withheld round carried a terminator, and an `error` event when neither round did. Signed-off-by: Osher-Elhadad <[email protected]>
…ressed F2's gate stops a stale client error being charged on every later turn. The test that came with it proves the suppression happens; nothing proved the suppression is NARROW. Keyed on the tool-call id rather than on content, the gate would stop charging every distinct original after the first — and TestTheRepairChargesTheRestoredTokensOnce would still pass, because it only ever repairs one. Three ids, two distinct originals: A and C point at the same content, B differs. Three recoveries happen and two are charged. That is the property that puts the two operands of SavedUnique - ExpandTokens in one unit, since the suppression keys on contentKey, which is what SavedUnique dedups by. Verified by mutation: keying the mark and the read on a constant instead of on content gives 1 of 3 charged and reds this test with the exact number in its failure message, while the existing test stays green. The case was verified during review but only in a throwaway probe, which is the state that rots: correct today, unguarded tomorrow. Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad
pushed a commit
to OsherElhadad/context-guru-1
that referenced
this pull request
Sep 23, 2026
…d three smaller review findings **The panel was false-green in its normal state.** `open_net_usd`, `open_turns` and `voided_net_usd` are computed per provenance group and were rendered nowhere (grep count: 0 each). A summarized session adds new content slowly by construction -- five turns after a summary on a live run had accrued 3,486 of a 20,000 target -- so "open" is where a healthy episode spends most of its life. The table therefore showed a settled total of `$0.00` in good-text green while the real committed position was negative. A review found it; an earlier commit of mine had documented that state in prose rather than fixing it, which was the wrong end of the problem. Now the Net cell renders an em-dash when nothing in the group has settled, and a new exposure line above the coverage line reports the open spans, their turns and their current net, with voided spans reported apart and never averaged in. **`?span=NaN` defeated the range guard.** Every comparison against NaN is false, so `f <= 0 || f > 8` passed it through; the span then became NaN, which compares false against everything, so no episode ever closed and the panel reported an empty measurement rather than an error. NaN and Inf are now rejected first. **A missing index made the query statistics-dependent.** Neither `idx_rc_request` nor `idx_rc_comp` covers the `(request_id, component)` pair the episode query joins on. Measured on a 50,000-request database: 0.078s with `sqlite_stat1`, ABORTED AT 11m14s without it. `janitor.go` runs `PRAGMA optimize` every five minutes so a live deployment usually has statistics, which makes the exposure the cold window after a restart plus the staleness case that comment itself warns about. The new index takes the no-statistics plan to 0.081s -- statistics-independent rather than merely fast on a warm database. A `CROSS JOIN` barrier does not help and was tried: SQLite cannot reorder a LEFT JOIN's operands, so the problem was index choice, not join order. It goes in `additiveDDL`, beside the two existing indexes on `requests`, because a version bump discards every request row to add an index that changes no row's shape. **The summarizer's reply is now treated as untrusted before being wrapped.** `summaryWrapper` concatenated the cheap model's raw output with no marker stripping and then framed it in "Use this summary as the older context ... Continue the task accordingly". Structural injection was already impossible -- the reply becomes one user-role text message, so the rossoctl#103 leaked-`tool_use` class is not reachable -- but the span being summarized is agent-read material, and our own control strings are never legitimate inside a reply because the wrapper appends the real marker itself. Both marker spellings `expand` accepts are stripped, including the JSON-escaped one that `expand.rawMarkerRe` exists for, plus the `</summary>` delimiter the summarizer's own prompt uses. Deliberately NOT attempted: detecting instructions in the reply (undecidable, and a filter that half-works invites reliance on it) or capping its length (never-worse already reverts a grown turn, and truncation would turn a long legitimate summary into a misleading one). Every new assertion was verified to fail with its fix removed. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The bug
A real session received this from the model's turn:
That is the CLIENT's error format. The tool is ours, this proxy advertises it, and this
proxy's own marker text (
[full output: call context_guru_expand]) is what tells the modelto call it — so a call reaching a client that implements no such tool is our bug.
Root cause
peekSSEdecided on the firstcontent_block_start. Atool_useis almost never thefirst block: a turn opens with thinking or with text and calls its tools after. So the
interception condition was essentially never met on streaming traffic, and production says
exactly that — over 1,687 streamed responses,
sse_expand_after_stream22 againstsse_buffered1. The loop missed ~22 calls for each one it caught.Not a thinking-block problem: about half of the captured traffic has thinking off, and a
leading
textblock does the same thing. The comment claiming "100% of captured traffic"is corrected.
Two halves, because one is not enough
Response side — splice (
sseSplicer). Decide per BLOCK instead of per response: forwardevents as they arrive, stop at the
content_block_startthat calls expand, run thecontinuation, and write round 2's blocks into the same stream with their indices shifted past
the blocks already sent and their
message_startdropped. The client keeps its stream andnever receives the one block that is ours to answer. If the loop cannot answer, the withheld
events are handed back — for a round whose blocks were not renumbered, byte-for-byte the
stream as it arrived, which is today's behaviour exactly.
Request side —
expand.RepairToolResults. Some paths cannot be intercepted at all: themodel batches expand with a tool only the client owns, the round cap, a stream that will not
reconstruct, a non-Anthropic dialect, a bypassed turn carrying markers minted earlier. All of
them converge on the NEXT request, so they are closed there: every
tool_resultanswering ourown tool gets the resolved original instead of
No such tool available,is_errorcleared,restored text marked kept-verbatim so an offloader does not compact it straight back into the
marker that caused the call. The client keeps its own copy of the error, so the same repair is
needed on every later turn, and it is idempotent and byte-stable for as long as the stash
survives — which is one process, because the store is in-memory. After a restart every
repaired
tool_resultresolves toUnavailable(...)instead of the original, and that is achanged byte mid-transcript: one full prefix write per affected session, once. Worth stating
plainly in a project whose thesis is cache economics — an unqualified byte-stability claim about
a cached prefix is exactly the sentence someone would build on.
Why splice and not "peek further"
Peeking to the first
tool_useblock was measured, not dismissed. Both arms are derivablefrom one response's event timeline, so the comparison is paired by construction with no proxy
restart inside the arm: forwarding from the first event against forwarding from the first
tool_useblock. Every event of 39 turns timestamped, straight to the upstream, alternatedbetween conditions:
message_stopThe sign is not evidence —
peek-far >= spliceis an identity of the construction, so nostatistic is claimed from it. The magnitudes are the result, and the prose-only row settles it
without any statistics at all: a turn with no tool call has its decision point at
message_stop, so the whole response is buffered. It would be paid on nearly every responseto intercept the ~1.3% that call expand. Splicing pays on that 1.3% only.
Both datasets are in the tree, under
docs/results/expand-splice-2026-08/— 39 timestampedturns and the byte-per-token rows — rather than only in this description.
That measurement also re-confirms the correction #97 made to this file: the upstream DOES
stream. The first event lands at 40-55% of wall and the deltas stream across the rest, on two
models. The claim that "the gateway does not stream, ttfb/wall 1.000 on 6 of 6" was wrong.
Failing test first
TestExpandCalledAfterALeadingBlockIsNeverGivenToTheClient— a response whose first block istext(and one whose first block isthinking) and whose SECOND block calls expand. Red onthe parent commit at the reported symptom:
TestTheStreamedPrefixReachesTheClientBeforeTheExpandCallis the other half — the blocksbefore the call must still reach the client while the upstream is generating — also red.
Real runs
A local proxy (never the service, never port 4000), an offload config that collapses a large
tool output into a marker, and real Claude Code sessions.
cg.sse_splice round=0 expand_call=true blocks_sent=1→cg.expand round=0 calls=1 resolved=1 unresolved=0→cg.sse_splice round=1 expand_call=false blocks_sent=2→upstream_rounds=2 expands=1 sse=true sse_buffered=false. One blockforwarded before the call — the bug's exact shape — then interception, then the
continuation spliced in. The session answered the canary line correctly and its client
transcript contains zero occurrences of
No such tool available.sse_expand_after_stream=1,bounces=0, every responseverdict=streamed, and the client transcript contains the reported error verbatim —{"type":"tool_use","name":"context_guru_expand",…}answered by<tool_use_error>Error: No such tool available: context_guru_expand</tool_use_error>.binary produced
expand_call=true, the otherTools bail, and thencg.expand_repair restored=1on the next request — the client's error replaced with content resolved fromthe same store. (In that run the stash happened to be a small one, so the model's own
line-500 answer was inferred rather than read; the repair firing and resolving is what the
run proves. Byte-exact substitution is asserted in
expand/repair_test.go.)The other paths, ruled in or out
tool_useotherTools(expand batched with a client tool)tool_use, well-formedmaxExpandRounds)tool_use, well-formedAggregateSSEfailsContinuation→!okgot == 0isAgentCompactionfires on any user-role message with a compaction phrase, and atool_resultis user-roletool_usesse_expand_after_streamnow counts the structural fact — the client was handed ourtool_use— instead of the tool's NAME appearing in bytes going past, which the model couldalso write in prose.
Review round: one blocker, and four smaller
Blocker. Once the splice withholds round 1's
message_delta+message_stop, that roundholds the only terminator the client will ever get, and a continuation round is not obliged to
carry one — empty, truncated mid-generation, or another dialect all leave the client with a
half-open message. That is a regression against the parent, where those rounds cannot arise
and the client gets a complete stream with the leaked
tool_usethat the request side thenanswers.
sseSplicernow records whether amessage_stopwent out, andterminatecloses theturn with the withheld round's own closing events — the closers only, so no invented bytes and
no leaked call. Four shapes tested plus the nested case (a spliced round that calls expand
again). The
withheld = nilreset fixed earlier was one instance of this class, not the class.The rest. The repair charged the dashboard row on every later turn that re-sent the same
stale error, and
ExpandTokensis subtracted from a unique-countedSavedUnique— a unitmismatch that drove the headline savings arbitrarily negative; the kept-verbatim mark already
records the first recovery, so the row is charged once. That mark keys on
contentKey, the samekey
SavedUniquededups by, which is what puts the two operands in one unit. Guarded from bothsides, because a gate on a money number can fail either way: three calls resolving two distinct
originals (two ids sharing content) charge twice — not three times, which double-counts, and
not once, which would suppress a legitimate charge.
TestADistinctOriginalIsStillChargedpinsthe second half; mutations in both directions are killed — removing the gate gives 3 of 3 rows
charged, keying it per repair event instead of per content gives 1 of 3. An id-less
tool_usefor our tool made""a live key and overwrote atool_resultthat carried notool_use_id.serve's doccomment still described marker-gated buffering and named
peekSSE, which this branch deletes.And a block generated after the expand call is dropped from the client while the continuation
does send it back upstream — not fixed, added to the honest-limits list where it belongs.
Verification
go test ./... -race -timeout 25m: 26 packages ok, 0 failures, 0 data races.Mutation-tested, 30 mutations, all killed, tree verified byte-identical after each:
startsExpandCallnever matchingpassforwarding the expand event anywayrewriteignoring the index offsetrewritekeeping the continuation's secondmessage_starthandBackdropping the withheld eventsbailis_errorsetpassclaiming the round was retainedreadSSEEventnot resetting the shared event bufferrewritepre-filter applied unconditionallystartsExpandCallpre-filter invertedterminateremovedterminateforwarding the withheld content as well as the closerserrorevent when no closer exists anywhereterminatenot wired to the bail exitterminatenot wired to the upstream-error exitrows carry expand_tokens, want 2")
Two of those indicted themselves before they indicted the code, which is why they are named
rather than folded into the count: #19 first returned
buf.Bytes()from abytes.Bufferthathad been replaced with a zero value, whose
Bytes()is nil — a no-op edit, and it dies whenre-run with a genuinely non-nil return; and the first form of #18 did not compile (
sentdeclared and not used), so it is counted only in its compiling form. An earlier version of this
description said "20" while listing more than that; the list above is now the count.
cannot be built leaves the block untouched. On the client's stream, scoped rather than
absolute, because the first two attempts at this sentence were both too strong: the message is
closed whenever the withheld round carried a terminator — tested on four continuation
shapes (empty, truncated, another dialect, error event) — and when neither round carries
one, the client gets an
errorevent rather than a socket that stops mid-message, tested ateach of the three spliced exits. Never a synthetic
message_stop: nostop_reasonin theenum means "truncated", and
end_turnwould report a broken turn as one that finished. Thecontent dropped alongside the closers is the F5 limit, listed in
ssepeek.goand not paperedover.
Two of those fail-open paths were only exposed by the splice itself and are fixed in the last
commit. Once the prefix is on the wire the response is committed, and both were still writing
as if it were not: an upstream error on a continuation round called
http.Error, which appendsa 502 body to an open event stream, and a continuation round answering with JSON cannot be
spliced at all. Both now end the turn with the events the splice withheld. The self-review
that found the second one also found that resetting
withheldper round — which looked tidy —silently truncated the client on exactly that path; the reset is gone and a test holds it.
Notes for review
streamFromcollapses back intostream: itsheadparameter and the name-scanningcounter existed only for the peek.
Continuationneeds thewhole assistant turn. ~35 SSE bytes per output token (mechanically: ~4 bytes of text plus
~105 of framing per delta of ~3.5 tokens), and this gateway accepts
max_tokensup to128,000 — 200,000 is refused by the model — so a full-length round is ~4.5 MB. Reaching the
unit's
MemoryMax=8Gneeds ~1,800 concurrent max-length streams against a measuredconcurrency of 0.55 (Little's law, 197 requests at W=16.5 s). Per-response retention equals
what the old whole-response path held; what changed is the share of responses doing it,
33.4% to ~100%, since injection stopped requiring markers (feat(config): house/housellm defaults, and stop the expand tool moving the tools array #97).
sseRetainMaxBytes(16 MiB) is not concurrency defence — a per-response cap cannot bounda process, and nothing here needs it to. It replaces what this branch deleted:
ssePeekMaxBytesbounded a single stream at 64 KB, and without it one pathological stream — a runaway
generation, an upstream that never sends
message_stop— was retained with nothing to stopit. 16 MiB is set by the WORST legitimate case, not the typical one: framing is ~123 B per
delta, so a stream emitting one token per delta pays that per TOKEN and a 128,000-token
response reaches ~16.3 MB — about 3% under the bound, not headroom. Typical full-length
traffic is ~4.5 MB, 3.4x under. That margin is deliberately not a cliff, because overshoot
degrades by construction: the round is forwarded whole, anything already withheld is handed
back first, the call is counted, and the repair answers it next request — exactly the
behaviour of every release before this one. And the
max_tokensceiling is the UPSTREAM's:this proxy never caps the field, so re-derive the bound when the upstream moves.
earlier version of this description did). Measured recorder-free throughout, so every number
is one unit: per-event 9.60x the stream, 8.01x once the event buffer is reused,
4.81x (8.54x incl_recorder) once two free substring rejects skip the parse — against
3.16x for the whole-response buffering this replaced. A halving, and the shipped path
still churns 1.52x more than what it replaced; the residual is per-line reading and is
not chased. An earlier version credited the buffer reuse with the pre-filters' share and
compared a recorder-inclusive number against a recorder-free one, which handed the change
3.73x of
httptestcost that never existed in production.continuation loop already uses: the
tool_useit reads is the model's own call in thattranscript, and a
tool_resultis only rewritten when the assistant turn it answers calledcontext_guru_expand.the upstream's own fallback. One
Readreturns one event now, and a test that just keptreading would be satisfied by the fallback firing on a fully buffering proxy.