Skip to content

fix(proxy): the expand tool_use that reached the client, on both sides - #103

Merged
OsherElhadad merged 12 commits into
mainfrom
fix/expand-streamed-interception
Aug 23, 2026
Merged

OsherElhadad merged 12 commits into
mainfrom
fix/expand-streamed-interception

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator

The bug

A real session received this from the model's turn:

context_guru_expand
IN  { "id": "…" }
OUT <tool_use_error>Error: No such tool available: context_guru_expand</tool_use_error>

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 model
to call it — so a call reaching a client that implements no such tool is our bug.

Root cause

peekSSE decided on the first content_block_start. A tool_use is almost never the
first 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_stream 22 against
sse_buffered 1. 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 text block 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: forward
events as they arrive, stop at the content_block_start that calls expand, run the
continuation, and write round 2's blocks into the same stream with their indices shifted past
the blocks already sent and their message_start dropped. The client keeps its stream and
never 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: 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 markers minted earlier. All of
them converge on the NEXT request, so they are closed there: every tool_result answering our
own tool gets the resolved original instead of No such tool available, is_error cleared,
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_result resolves to Unavailable(...) instead of the original, and that is a
changed 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_use block was measured, not dismissed. Both arms are derivable
from 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_use block. Every event of 39 turns timestamped, straight to the upstream, alternated
between conditions:

turn shape n deciding at the first tool_use withholds extra client wait
tool-calling 12 98.4% ± 2.1% of the streaming span (sem 0.6) +3.17 s ± 0.66 (sem 0.19)
tool-calling, thinking on 12 99.1% ± 1.7% (sem 0.49) +3.48 s ± 0.96 (sem 0.28)
prose only, no tool_use at all 12 100% ± 0.0 — the decision point becomes message_stop +4.53 s ± 0.68 (sem 0.20)
tool-calling, second model 3 99.2% ± 1.1% +3.66 s ± 1.24

The sign is not evidence — peek-far >= splice is an identity of the construction, so no
statistic 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 response
to 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 timestamped
turns 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 is
text (and one whose first block is thinking) and whose SECOND block calls expand. Red on
the parent commit at the reported symptom:

--- FAIL: …/text: the client received a raw tool_use for OUR tool — this is the reported bug
--- FAIL: …/thinking: the client received a raw tool_use for OUR tool — this is the reported bug

TestTheStreamedPrefixReachesTheClientBeforeTheExpandCall is the other half — the blocks
before 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.

  • Fixed binary: 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 block
    forwarded 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.
  • Parent binary, same prompt: sse_expand_after_stream=1, bounces=0, every response
    verdict=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>.
  • Request-side repair, live: a turn that batched expand with another tool on the fixed
    binary produced expand_call=true, the otherTools bail, and then cg.expand_repair restored=1 on the next request — the client's error replaced with content resolved from
    the 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

path reachable what the client gets now
expand after a leading block yes — this bug, 22 in production raw tool_use intercepted (splice)
otherTools (expand batched with a client tool) yes, reproduced live raw tool_use, well-formed still passed through, counted; repaired next request
round cap (maxExpandRounds) yes raw tool_use, well-formed unchanged bytes, and now counted — the cap used to skip the withholding, so the tool_use it handed the client was invisible on /stats; repaired next request
AggregateSSE fails yes (malformed / unknown dialect) withheld events verbatim unchanged, counted; repaired next request
Continuation → !ok yes (unexpected shapes) withheld events verbatim unchanged, counted; repaired next request
got == 0 no longer — #97 continues with a placeholder — —
non-Anthropic SSE, never inspected yes raw tool call still not inspected; repaired next request
bypassed request carrying older markers yes — isAgentCompaction fires on any user-role message with a compaction phrase, and a tool_result is user-role raw tool_use bypass still byte-identical. Repaired on the next non-bypassed request only while the transcript still carries the pair — for a false-positive bypass it does; for a real compaction the summary replaces the transcript, so the error is summarised away and there is nothing left to repair

sse_expand_after_stream now counts the structural fact — the client was handed our
tool_use — instead of the tool's NAME appearing in bytes going past, which the model could
also write in prose.

Review round: one blocker, and four smaller

Blocker. Once the splice withholds round 1's message_delta+message_stop, that round
holds 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_use that the request side then
answers. sseSplicer now records whether a message_stop went out, and terminate closes the
turn 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 = nil reset 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 ExpandTokens is subtracted from a unique-counted SavedUnique — a unit
mismatch 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 same
key SavedUnique dedups by, which is what puts the two operands in one unit. Guarded from both
sides, 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. TestADistinctOriginalIsStillCharged pins
the 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_use for our tool made
"" a live key and overwrote a tool_result that carried no tool_use_id. serve's doc
comment 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:

    1. startsExpandCall never matching
    2. pass forwarding the expand event anyway
    3. rewrite ignoring the index offset
    4. rewrite keeping the continuation's second message_start
    5. handBack dropping the withheld events
    6. a block-0 call no longer counted as buffered
    7. the leak counter removed from bail
    8. the request-side repair never called
    9. the repair leaving is_error set
    10. the repair matching ANY tool, not only ours
    11. an unresolvable id keeping the client's error instead of the placeholder
    12. the repair reporting nothing as restored
    13. a failed continuation round writing its 502 into the open stream
    14. a JSON continuation round losing the withheld events
    15. the round cap not terminating the loop (killed by non-termination, not an assertion — that guard is what bounds the loop, and the counter it feeds is covered separately)
    16. the retain bound never firing
    17. withheld events dropped instead of handed back past the bound
    18. the event that trips the bound forwarded twice
    19. past the bound, pass claiming the round was retained
    20. readSSEEvent not resetting the shared event buffer
    21. the rewrite pre-filter applied unconditionally
    22. the startsExpandCall pre-filter inverted
    23. terminate removed
    24. terminate forwarding the withheld content as well as the closers
    25. the repair charging the dashboard row on every turn
    26. the id-less guard removed
    27. no error event when no closer exists anywhere
    28. terminate not wired to the bail exit
    29. terminate not wired to the upstream-error exit
    30. the charge gate keyed per repair event rather than per distinct content (kills on "1 of 3
      rows 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 a bytes.Buffer that
had been replaced with a zero value, whose Bytes() is nil — a no-op edit, and it dies when
re-run with a genuinely non-nil return; and the first form of #18 did not compile (sent
declared 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.

  • Fail-open throughout: an event that cannot be renumbered goes as it came, and a repair that
    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 error event rather than a socket that stops mid-message, tested at
    each of the three spliced exits. Never a synthetic message_stop: no stop_reason in the
    enum means "truncated", and end_turn would report a broken turn as one that finished. The
    content dropped alongside the closers is the F5 limit, listed in ssepeek.go and not papered
    over.

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 appends
a 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 withheld per round — which looked tidy —
silently truncated the client on exactly that path; the reset is gone and a test holds it.

Notes for review

  • streamFrom collapses back into stream: its head parameter and the name-scanning
    counter existed only for the peek.
  • Retention, with numbers. A round is held until it ends, because Continuation needs the
    whole 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_tokens up to
    128,000 — 200,000 is refused by the model — so a full-length round is ~4.5 MB. Reaching the
    unit's MemoryMax=8G needs ~1,800 concurrent max-length streams against a measured
    concurrency 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 bound
    a process, and nothing here needs it to. It replaces what this branch deleted: ssePeekMaxBytes
    bounded 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 stop
    it. 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_tokens ceiling is the UPSTREAM's:
    this proxy never caps the field, so re-derive the bound when the upstream moves.
  • Allocation is a separate number from retention and the two must not be conflated (an
    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 httptest cost that never existed in production.
  • The repair resolves ids from the request's own transcript, the same trust boundary the
    continuation loop already uses: the tool_use it reads is the model's own call in that
    transcript, and a tool_result is only rewritten when the assistant turn it answers called
    context_guru_expand.
  • Both streaming tests now read until the wanted bytes arrive, with a deadline shorter than
    the upstream's own fallback. One Read returns one event now, and a test that just kept
    reading would be satisfied by the fallback firing on a fully buffering proxy.

Osher-Elhadad 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]>
Osher-Elhadad 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
OsherElhadad merged commit 7b20027 into main Aug 23, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Aug 23, 2026
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]>
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