Skip to content

feat: fix the placement, the genericity and the accounting of the deterministic components - #89

Merged
OsherElhadad merged 15 commits into
mainfrom
feat/determinism-0821
Aug 22, 2026
Merged

OsherElhadad merged 15 commits into
mainfrom
feat/determinism-0821

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

The problem, in production numbers

From the live service (/stats, 5,752 requests / ~37h) and the dashboard DB (19,805
requests over 5 days, $3,139.97 of spend):

fact number
total savings, whole window $9.73 of $3,139.97 = 0.31% (from Σ(baseline_cost_usd − cost_usd); saved_usd was only populated for the last 2 of 6 days, which is where the $3.05/0.10% figure came from)
context frozen for cache safety on ttl_expiry turns 38.4M of 42.3M tokens = 90.8%
cost of a cache miss vs a hit 8.5x ($0.9987/req vs $0.1178)
cmdfilter filters that have EVER matched 2 of 26, no_filter_match 164,865
toon acted 0 of 5,752, not_uniform_object_array 234,437
searchfold written, tested, round-trip verified, in zero presets
format / textclean overcount_ratio 1.0 — an artifact, not a property
SSE responses buffered 1,393 of 4,172 = 33.4%

Two of those are the whole story. Placement: we freeze 90.8% of the context on the
turns where a removed token is worth ~12.5x more, to protect a prompt cache that has
already expired. Genericity: 939 lines of per-command filters have matched two
filters, while two command-agnostic rules are worth 20.3% of everything we ship.

What landed, and what it measured

Evidence is 1,795 real captured requests (19,138,824 tokens) replayed through the
proxy's /compact endpoint — deterministic, no gateway spend, byte-identical bodies on
every arm — plus real gateway runs for the things /compact cannot see. The baseline arm
is origin/main's own binary, so a delta is this branch and not a config difference.

Headline

preset arm saved tokens of before cg ms/request
codesmart (the proxy default) origin/main 262,544 1.372% 9.31
codesmart this branch 749,268 3.915% 10.66
general origin/main 5,556,801 29.034% 9.94
general this branch 5,811,290 30.364% 10.61

2.85x the savings on the default preset, for +1.35 ms/request. And on a real gateway
run (30 requests, byte-identical bodies, codesmart): billed upstream $0.8800 →
$0.8013, −8.9%
, with $0.00 of context-guru's own LLM spend.

That table contains none of item 1. /compact replays turns back to back, so
cacheIsCold never fires and Ctx.ColdCache is false throughout — the cold lift contributes
exactly zero to the 2.85x. The delta is the three deterministic additions and the arithmetic
closes: searchfold 333,764 + linecap 149,521 + textclean 12,064 − extract's 8,625 displaced =
486,724 of the 486,724 change. The cold sweep is measured separately, on a forced TTL expiry,
below. One trial per gateway arm; 8.9% is well above the harness's 0.04–0.7% spread, but a
second trial is cheap and has not been run.

1. Cold turns sweep at depth — the biggest lever

First, the −$708 number, because it is not this change

proxy/promexport.go records a measured verdict on acting when frozen_tokens reads zero:
3,092 requests whose own prefix tracker had been reset (a restart, an evicted entry) still
cache-HIT for 404,376,878 cache-read tokens, and treating that as "the cache is cold, deep
history is safe to rewrite" was worth about −$708 on sonnet-5 against +$0.62 of upside.

That is a warm cache misread as cold, and it is the opposite condition to this one.
cacheIsCold returns false when there is no previous turn on record, so a reset tracker
cannot produce a sweep — the −$708 reading declines itself. Ctx.ColdCache needs a
recorded previous turn older than the provider TTL plus a one-minute margin.

Provable rather than argued: TestColdSweepCannotFireOnTheMinus708Case walks every way the
tracker can come back empty or wrong — restart, evicted entry, corrupt timestamp, clock skew
into the future, a warm long-lived session, and idle past the TTL but inside the margin — and
asserts each reads warm and still reports its prefix frozen. TestColdCacheOffIsByteIdentical
covers the other direction: on a warm turn the setting changes nothing either way.

One defect this surfaced, now fixed: making frozen_tokens cold-aware gave 0 a second
cause, so the very reading that comment exists to warn about became ambiguous. The metric
doc now names both causes and how to separate them (the request's cache_miss_reason — a
swept turn reads ttl_expiry/cold_start, a reset tracker reads hit).

cold_cache now defaults to enabled for the three offloaders whose replacement is a
pure function of (content, config): mask, failed_run, collapse. That is the same
property repairLostFreeze requires, and it is what makes a decision taken at depth safe
to freeze and replay byte-identically on later warm turns.

This changes behaviour on live traffic. cold_cache: false restores the old gate per
component — the field is a *bool, so "unset" and "off" are distinguishable, and
TestColdCacheFalseKeepsTheTailGateOnAColdTurn holds that escape hatch open.

Not defaulted on, and why: readlifecycle derives its marker prefix from classify(),
which reads later transcript events, so the same content can yield different bytes as the
transcript grows; skeleton derives its body from the paired tool call, not from the
message alone. Neither is pure, so neither qualifies — and neither is in any preset.

Nothing loosens the cold test itself.

apply's frozen_tokens now reads the same gate the components read, cold lift included.
It called TailOnly, so a cold turn reported its whole prefix as frozen while every
offloader was free to rewrite it — which is why this lever was invisible on its own
dashboard. Reproduced end to end on a forced TTL expiry before the fix: on the
ttl_expiry turn, frozen = 13,795 of 16,616 = 83.0%, attempted = 2,821, and that one
turn cost $0.1082 against $0.0107 for a hit turn — the 8.5x, live.

The discrepancy the brief asked about, with numbers — and I did not widen the heuristic

cacheIsCold demands TTL + a 60-second margin, so a 5-minute provider TTL needs a
6-minute idle gap. The dashboard classifies ttl_expiry from cache_read == 0, which
happens from 5 minutes. Of the 742 production ttl_expiry requests, by idle gap since the
previous turn of the same session:

idle gap requests share cost share of cost
≥ 360 s — ColdCache true, sweep fires 587 79.1% $678.45 91.6%
300–360 s — provider cache gone, we still say warm 151 20.4% $59.05 8.0%
< 300 s, or no previous turn on record 4 0.5% $3.57 0.5%

So the margin costs us 20.4% of TTL misses and 8.0% of their spend, and it buys the one
protection that matters: a false cold reading rewrites content the provider is still
holding and forces a cache-write of the whole suffix at 1.25x the fresh rate, where a
missed cold turn only forgoes a saving. Reported, not widened. It is also a trap for
anyone measuring this: my first forced-expiry run used a 330-second gap, landed inside that
band, and the sweep correctly did not fire.

Proven on a real forced TTL expiry

Two gateway runs, preset: general, byte-identical bodies, a 400-second idle gap before
turn 6 so the miss is real. cache_miss_reason='ttl_expiry' confirmed in the dashboard DB,
not assumed.

The ttl_expiry turn:

origin/main this branch
tokens before 16,616 16,616
attempted 2,821 16,616
frozen for cache safety 13,795 (83.0%) 0 (0.0%)
tokens shipped 4,939 3,867
cache_write tokens 56,322 54,803
cost of that one turn $0.1081 $0.1052

And the decision is frozen, so the following warm turns keep it — turn 7 ships 4,216 tokens
instead of 5,288, and every turn after that is ~1,070 lighter. Session totals: 86,344 →
91,704 saved tokens, $0.2946 → $0.2905
.

Sizing this to production, labelled as an extrapolation. 1,519 of the 13,795 previously
frozen tokens on that turn stopped being cache-written — an 11.0% fold rate over the
frozen mass. The reports' floor estimate was 3.55%–5.27%, because it counted only the
lossless folds; this measures the whole offloader set that general runs, on one session
with a 16.6k-token prefix, where production's ttl_expiry turns average 57k. So the two
numbers are not in conflict, and neither is a forecast. What is solid and population-wide is
the denominator: 38.4M frozen tokens across 742 requests, of which 587 requests ($678.45,
91.6% of the ttl_expiry spend) clear the 360-second margin and will now be swept. The
honest next step is to watch frozen_tokens on live ttl_expiry rows after deploy rather
than to quote a dollar figure from one session.

2. Two GENERIC rules — linecap

No new per-command filters. Sixteen rtk command signatures (pytest, apt, npm, pip, go
test, cargo, tsc, eslint, mypy, ruff, docker, kubectl, make, gcc, git log, ps) were
replayed against 9,763 real messages and every one matched zero, which the live
service confirms from the other side: two filters of 26 have ever fired.

The value is in two rules that need no command signature:

  • per-line cap at 500 chars with a never-truncate allow-list — a line carrying a
    file path, a source location, a stack frame, an error, a test verdict, an exit status, a
    diff marker, a hunk header or a URL survives any cap intact. That list is what makes a
    generic cap deployable: those lines are long for the same reason the noise is. The cap
    came off a sweep (tokens / messages touched): @200 2,031,381/2,742 · @300 1,606,241/2,520
    · @500 1,105,387/1,337 · @1000 745,350/862 — 500 takes 54% of @200's tokens while
    touching half as many messages, and an untouched message is one whose bytes stay stable
    for the cache.
  • non-adjacent duplicate-line collapse with an (xN) count. Distinct from the adjacent
    collapse we already have, which measured 63 tokens of remaining value against 649,330 for
    this one. Guards: skip diff-shaped blobs entirely, never collapse lines differing only in
    a source location, never under 8 trimmed chars, never the first or last 3 lines.

Duplicates collapse before the cap so a dropped duplicate is not charged twice, and the
(xN) is rendered after the cap — appending it during the collapse put it at the end
of a line the cap then truncated, eating the annotation that makes the elision visible.

Measured on codesmart: 149,521 tokens over 629 of 1,795 requests, at 1.19 ms/request.

A regression I introduced and then fixed — placement

linecap first went in directly after cmdfilter, and on general that made it a net
loss
:

general arm saved tokens of before
linecap 7th 5,524,476 28.87%
no linecap at all 5,556,801 29.03%
linecap last (shipped) 5,811,290 30.36%

Every Offload leaves a marker and every Offload skips marker-bearing content (skipReduce,
so nothing double-reduces and no stash is orphaned). So a modest reducer ahead of a
drastic one does not merely overlap with it — it takes the candidate away. From the
per-turn gate ledger of a real 10-turn gateway session: linecap took 39,335 tokens off
messages collapse would have taken 76,554 off, and its marker then made mask, extract
and collapse decline those messages outright. Billed cost on that session went the wrong
way, $0.2935 → $0.3266. linecap now runs immediately before cachesplit in every preset,
and TestLinecapYieldsToAnEarlierOffloader pins the mechanism as a property of the
component rather than of one preset's ordering.

3. The accounting artifact — settled by measurement, then fixed

Two reports contradicted each other, and the answer decides whether the dedup-key change
creates value or destroys it. R5 §1c prices format and textclean as the pipeline's best
components — 492,666 tokens at 100% unique, $2.328 + $0.776 — on the reading that they
"rewrite in place every turn and every removal is new". R7 §6.1 says that 1.0 ratio is an
artifact of Reformats having no cache key.

R7 is right, and the mechanism is the thing R5 cites as evidence. The agent holds its own
transcript and re-sends the ORIGINAL tool output on every turn — our rewrites are wire-only,
apply never touches the client's copy. So an in-place fold meets the same unfolded bytes
again on turn 2, folds them again, and reports the same saving again. "Byte-stable across
turns", which textclean.go's own doc comment claims as a virtue, is precisely what makes
the saving re-counted rather than new. Direct evidence rather than either report's word for
it — TestInPlaceFoldReportsTheSameSavingOnEveryTurn: one ANSI-bearing tool output, ten
consecutive turns, 328 tokens of gross saving on every one of the ten, for 328 tokens of
real reduction
.

Three independent methods now agree: that mechanism test, R7's content-level count (1,582
textclean rows over 14 distinct contents = 95.29x), and my own keyed ratios below — which
matter because they are computed from the new keys and so could have been a key bug on their
own.

So this fix REDUCES reported savings, and it should. Reformats stash nothing, so every run took metrics' keyless fallback
(SavedUnique += saved) and SavedUnique was defined equal to Saved:
overcount_ratio came out 1.0 for format/textclean/toon/searchfold by
construction
, and was being read as "every token these remove is new money". The
pipeline now derives one key per rewritten message from that message's pre-fold text.

Measured effect on the same corpus — reported ratio before vs after:

component before after over-credit corrected
searchfold 1.0 (by construction) 56.54 56x
linecap — (new) 27.57 —
textclean 1.0 (by construction) 5.59 5.6x

The reports predicted 5.9–11.1x; on this corpus searchfold is far worse than that. Every
saved_tokens figure in this PR is gross; the unique column beside it is now real.

4. Preset and component hygiene

  • searchfold deployed — it was fully written, tested and round-trip verified, and in
    zero presets. It is now the largest single contributor on codesmart: 333,764
    tokens
    , acting on 1,072 of 1,795 requests.

  • toon retired from every preset. acted 0 of 5,752 in production, 0 convertible
    candidates in 11.67M measured tokens, and 0.116 ms + a TextTokens call per tool message
    to convert nothing. The component and its tests stay, so tabular traffic can enable it by
    hand — working code is not deleted, it just stops being paid for by default.

  • textclean in every preset (it was in general alone): 12,064 tokens here, and its
    denominator goes from 5,734 to 19,775 production requests.

  • R7 feat: LLM-based context components (summarize + extract code strategy) #6 — try-all-folds. Implemented, and it pays on both axes. searchfold's
    command pre-gate declined 29,737 candidate messages:

    tokens folded unique ms/request
    with the gate 234,722 5,395 1.174
    without (shipped) 333,764 5,903 0.509

    99,042 tokens of what it declined had exactly the repeated path prefix this folds — the
    pairing says which command ran, not what its output looks like. It was also the more
    expensive path: resolving a pairing json.Unmarshals a whole argument object per tool
    message. format's not_json_shaped pre-check stays — a one-byte test guarding a full
    parse is a different thing from one that reconstructs request structure.

5. cmdfilter and pipeline performance — hygiene, not user-visible value

Say this plainly before the numbers: the harness measures the whole pipeline at ~29 ms
p50 / 66 ms p95 against an upstream_ms p50 of 4.6 s — compaction is 0.6% of a request,
and this gateway's upstream_ms swings 4.0 s to 17.3 s for identical requests inside one
40-second run. So none of the millisecond work below is worth anything to a user. All the
latency value in this PR is in item 6. This is engineering hygiene on an O(transcript) term
that would have kept growing.

Five fixes, all behaviour-neutral: the unbounded match key (the 188 ms tail — Command()
falls back to Name + " " + Args for Write/Edit, and the existing newline cut cannot bound
a JSON string, so a 200 KB payload became the key every filter scanned); a per-message memo
keyed on the content hash, reusing the existing freeze/replay machinery; an RE2 union
gate so a miss costs one pass instead of 26; an allocation-free selectorKey;
schema.MessageText no longer O(n²) on multi-block messages; and min_size moved above
skipReduce, which SHA-256s the whole message.

Behaviour-neutrality is proved, not asserted: the same pipeline on both binaries over
1,795 requests gives byte-identical savings (262,544 tokens, three times running).

The speed-up is modest here. Medians over 3 repetitions:

origin/main this branch delta
cmdfilter own timer, ms/request 4.133 3.887 −6.0%
whole pipeline, ms/request 9.369 9.221 −1.6%
every other component — — +1% to +3% (the noise floor)

End-to-end /compact wall by transcript length (client-observed, so HTTP and JSON parsing
dilute it):

messages n origin/main this branch delta
< 50 1,082 11.87 ms 11.69 ms −1.5%
50–199 657 23.36 ms 22.84 ms −2.2%
200+ 56 48.09 ms 46.80 ms −2.7%
500+ 0 — — —

That table is the SECOND version. The first had +3.3% in the < 50 bucket, a real
regression: the content memo hashes the message, which partly cancelled the reason min_size
was moved above skipReduce — the messages about to be rejected as too small were hashed
anyway, just by a different caller. min_size now precedes both, and the improvement is
monotonic in transcript length, which is what a fix to an O(transcript) term should look
like.

This corpus tops out at 258 messages, so the bucket R6 measured the problem in (500+
messages, 42.95 ms) is not exercised at all.
Every mechanism fixed is linear or worse in
transcript length, so the gain should grow with it — but I did not measure that, and I am
not going to claim it. What is verified: the match key is bounded (unit test with a 200 KB
Write payload), and the union gate never changes Match's answer (equivalence test against
an ungated scan, which caught a real under-match — a gate built without (?m) rejects every
^-anchored filter as soon as the key carries a $ <command> line).

The memo's other benefit is not speed: cmdfilter's rewrite is now frozen and replayed
rather than re-derived each turn, so byte-stability inside the cached prefix stops depending
on the transform staying deterministic.

6. The SSE buffering — where all the latency value is

checkExpand := advertised && round < maxExpandRounds, where advertised means the expand
tool is on the outgoing request. Injection is marker-gated, so the documented zero-latency
fast path really does hold before the first offload — and markers are sticky, so from the
first offload onward every response in the session was read in full
.

Now a bounded peek: buffer only up to the first content_block_start, and withhold the
response only if that block is a tool_use naming the expand tool. Thinking, text, another
tool, an empty message, an error event and a stream that ends early all flush the peek and
stream the remainder. peekSSE never discards input, so head + remainder is the stream
byte-for-byte on both paths. Non-Anthropic SSE now always streams — AggregateSSE only
reconstructs the Anthropic dialect, so that path already fell through to writeRaw and was
paying full latency for an inspection that never happened. An unreadable or oversized
preamble still buffers: fail open.

Measured on the real gateway, byte-identical bodies, 30 streaming requests per arm:

origin/main this branch
responses buffered 23 of 30 (76.7%) 0 of 30
responses streamed 7 30

R5 §4d independently reached the same diagnosis and it is not a confound: the expand tool
is injected only when the transcript carries <<cg:…>> markers, markers exist only because
an offload removed something, and markers persist — so one offload turns streaming off for
the rest of the session, by construction
. The harness saw 100% of responses buffered on
preset:general.

The TTFB claim, measured properly — and I got this wrong twice before

Neither of my earlier numbers survives, so both are stated here rather than quietly
replaced.

  1. The production gap (sse_ttfb_ms_avg 7,918 ms vs sse_ttfb_ms_avg_buffered 28,998 ms)
    is not 21 s of added latency. sse_ttfb_ms_avg_buffered is time-to-last-byte by
    construction, and the buffered set is systematically later-in-session and
    longer-generating. Confounded twice over.
  2. I then measured a 256-token scripted reply straight to the gateway, got ttfb/wall =
    1.000, and concluded the gateway does not stream at all. Also wrong: a short reply
    arrives in one flush whatever the transport does. Forcing a long generation direct to the
    gateway (no proxy): first byte 8,253 ms, last byte 13,234 ms, ratio 0.62, 843 output
    tokens.
    It streams.

So here is the demonstration, built to need all three conditions at once — a marker in the
transcript (so expand.Inject fires and the old code buffers), a declared tool (same
reason), and a reply long enough that first and last byte differ. Three reps per binary:

binary reply tokens client TTFB total TTFB/total sse_buffered
origin/main 166 3,112 ms 3,112 ms 1.000 1
origin/main 256 7,887 ms 7,887 ms 1.000 2
origin/main 220 6,376 ms 6,376 ms 1.000 3
this branch 203 5,713 ms 5,713 ms 1.000 0
this branch 179 6,749 ms 6,983 ms 0.967 0
this branch 950 3,112 ms 10,221 ms 0.304 0

Buffering is gone unconditionally — sse_buffered 3/3 → 0/3. The client-visible TTFB gain
then scales with reply length, and that is the honest shape of it: nil on a ~200-token
reply
(the whole thing arrives in one gateway flush, so there was nothing to win), and
7.1 seconds earlier on a ~950-token reply (first byte at 3.1 s of a 10.2 s response).
Real agent turns are the long case — extended thinking is on for 100% of the captured
traffic and thinking tokens stream too — so the 950-token row is the representative one and
the scripted ~200-token rows are the artifact. The gateway's own ~8 s head-of-line delay
before its first byte is not ours to fix.

The limit I accepted, and measured rather than argued. A response that opens with
thinking or text and calls expand later is streamed, so the client receives the model's raw
expand tool_use instead of the proxy resolving it. That outcome already exists on two live
paths (otherTools, and got == 0 when nothing resolves), so it is inside the design's
failure envelope rather than new — and the expand loop resolved 5 calls in 5,752 production
requests
. streamFrom counts every streamed response that names the expand tool, reported
as sse_expand_after_stream (an upper bound: prose mentioning the tool counts too). If that
becomes a meaningful fraction of sse_streamed, the trade is wrong and the fix named in
ssepeek.go is to stop forwarding at the expand block and splice the continuation's
content blocks into the same stream with remapped indices.

The peek decides on the first block rather than skipping past thinking because extended
thinking is on for 100% of the captured production traffic and the thinking block holds
most of a reasoning turn's tokens — buffering through it would keep most of what is being
fixed.

Review response

Three blocking findings, all fixed; the numbers above are re-measured after them (the
tail-preserving cap keeps ~11 more chars per capped line, which costs 977 tokens on
codesmart — 0.13% of the saving, for not destroying the file reference).

  1. The peek drained non-Anthropic streams and filed them as streamed. peekSSE ran
    before the provider test and the verdict was overridden after, so the label was fixed and
    the behaviour was not — no OpenAI event carries a type sseLineVerdict recognises, so
    nothing decides and the loop runs to EOF (measured: 24,814 of 24,814 bytes consumed). The
    provider test is now first; such a stream is copied straight from resp.Body.
    TestOpenAISSEStreamsThrough asserts the client sees a chunk while the upstream is still
    blocked.

  2. Both false-cold paths closed (see item 1's section — sessionTTL for the varying-TTL
    path, an alias clock for the two-ids-one-prefix path). The alias clock lives in the store,
    not the Tracker: TurnAt runs the length through modes.Boundary, which counts a
    compaction reset, so a second key per request double-counted that metric —
    TestCompactionResetIsCounted caught it. Five stale doc sites corrected, including the one
    that argued against this change by name.

    My first version of this guard closed one direction and left its mirror open, found by
    an independent verification pass. alias != sessionID skipped the alias clock on exactly
    the header-LESS turns, so the header-bearing turns kept the provider's entry warm and
    wrote the alias record, and the header-less turn then declined to read it: four turns with
    the header on 2 and 3 gave ColdCache = [false false false TRUE] with the record 60 seconds
    old. The test that was supposed to cover this called aliasSeen directly and never reached
    the call site, so it passed throughout. TestAliasClockIsReadOnHeaderlessTurnsToo now drives
    four turns through BodyOpts and records Ctx.ColdCache as the pipeline receives it;
    reverting the one-line fix reproduces the failure. Both records are also pinned against LRU
    eviction now (store.TTLPrefix, store.SeenPrefix) — they were plain TTL+LRU, and losing
    the TTL record silently narrows a 1h session back to 5m, which re-opens path 1.

    And that fix unmasked a second one: the two guards did not compose. The clock guard was
    alias-aware and the TTL guard was single-keyed, so a prefix that recorded the 1h tier under
    one id and then arrived under the other looked up a key never written, fell back to the 5m
    tier, and could declare cold on a prefix held for an hour — path (a) reached through the door
    path (b) opens. ColdCache = [false false TRUE], and the case passed before the alias fix
    because such a turn previously had no record and declined itself.

    The TTL record is now read under both ids and widened to the longer, mirroring the clock.
    Both widenings are monotone toward warm, so composing them cannot make the cold test more
    willing to fire — the property that has to hold across the pair, not just inside each half.
    My first attempt keyed both records by the content alias alone, and every id-flip case passes
    that way; but the alias is sha256(system + firstUser), so it moves when the agent compacts
    its own context, which an explicit id survives (metaSessionKeys exists for exactly that).
    Each single-key choice fails a different part of the table:

    keying TestSessionTTLComposesAcrossBothIDs
    pair-read (shipped) passes
    sessionID only fails 3 subtests — the header-flip cases
    alias only fails 1 subtest — the compaction case

    The root cause of both misses was test placement. Three of my guard tests called the
    helpers directly and never reached the decision, so ripping the guards out of the call site
    left them passing. There are now call-site tests driving BodyOpts with a stub that records
    the Ctx.ColdCache the pipeline actually received, and each guard is verified by reverting
    it with the tests in place: TTL keying → FAILS, alias clock → FAILS.
    TestColdSweepStillFiresOnAFiveMinuteTierPrefix pins the other direction, so the guards
    cannot quietly disable the sweep instead of narrowing it.

  3. The cap destroyed the trailing reference. clipMiddle now keeps both ends, which takes
    the allow-list off the critical path — its completeness cannot be verified, and every line
    in TestNeverTruncateAllowList put its token at the head where a head cut never reaches.
    TestCapKeepsATrailingReference covers six tail-reference formats. Two ceilings recorded in
    the code rather than fixed: a token in the middle third is still lost (head-only lost it
    too), and neverTruncateRe's ^\S+:\d+ exempts any space-free line containing :<digit>
    anywhere, so a JSON log line is exempt by accident — harmless now that clipMiddle carries
    correctness, but the list should not be read as precise.

Nits taken: searchfold gets a one-pass shape gate (mayCarryPathPrefix) — its per-attempt
cost is 275 µs at 24 KB rising to 8.16 ms at 1.2 MB with no early exit, and the gate now skips
12,898 messages that cannot fold, verified against the corpus to exclude nothing foldable;
linecap's position is pinned by TestLinecapRunsLastAmongTheOffloaders; the dead lineNum
var is gone; and the "lossless trio in every preset" claim is corrected — mcp takes
format + textclean only.

Two metric side effects the review asked to be stated rather than changed:

  • cmdfilter's per-filter ledger changes meaning. With the memo, turn 2+ takes the
    reapplyFrozen branch and never reaches FilterAct, so cmdfilter_filters[*].acts and
    .saved now count FIRST removals only while the component's saved_gross still counts every
    turn. The two will diverge, and the ledger's number is now the more honest of the pair — but
    it is an undocumented semantics change inside a PR that fixes a different one.
  • MarkUnique's clear-on-overflow trips sooner. Reformats now contribute cache keys where
    they contributed none, so the 200,000-entry reset in dash/capture.go fires more often and
    post-reset repeats are re-counted as unique. Bounded, visible in overcount_ratio, and
    pre-existing policy — but it slightly warms the very ratio this PR corrects.

What I deliberately did not do

  • No per-command cmdfilter filters. R6 measured 16 rtk signatures against 9,763 real
    messages at zero matches each, and the live service says two filters of 26 have ever
    fired. The conclusion is already written down in cmdfilter_agentcmd.go from an
    independent corpus; this is its second confirmation, and the third derivation of it would
    be waste.
  • Did not widen cacheIsCold. The 60-second margin costs 20.4% of TTL misses and 8.0%
    of their spend (table above). Reported, not changed — a false cold reading is the one way
    this whole change loses money.
  • Did not default cold_cache on for readlifecycle or skeleton. Neither
    replacement is a pure function of (content, config): readlifecycle's marker prefix
    comes from classify(), which reads later transcript events, and skeleton's body comes
    from the paired tool call. Neither is in a preset, so the change would be risk with no
    reward.
  • Did not implement the SSE splice. It removes the peek's accepted limit entirely, but
    it costs index remapping, message_start suppression, recursion for multi-round expands,
    and a defined fallback for a mid-splice failure after bytes are already on the wire —
    against a loop that fires on 0.09% of requests. The counter is in place so the decision
    can be made on data. Named as the upgrade path in ssepeek.go.
  • Did not implement index-based "scan only new messages" for cmdfilter. The brief
    asked for it alongside content-hash memoization; I shipped only the memo. The requirement
    is byte identity with what the provider's prefix already holds, and an index says nothing
    about that — an earlier component in the pipeline can change what sits at a given index
    between turns. The content hash is the correct key, and it subsumes the index version.
  • Did not lower textclean.min_tokens to 16. R7 suggested it for a few thousand
    tokens; textclean's real win was docs: per-component SWE-bench results + agent preset #5 (every preset), which is measured above at 12,064
    tokens and a 3.4x denominator increase. Not worth a second behaviour change in the same
    PR.
  • Did not chase the millisecond work further. Compaction is 0.6% of a request against
    a 4.6 s upstream p50. Item 5 is hygiene on an O(transcript) term; item 6 is the latency
    work that matters. Weighted accordingly.
  • Did not re-measure the SWE-bench / Terminal-Bench arms. codesmart and codesafe
    changed shape, and TestHarnessPresetArmsMatchTheShippedPresets enforces that the study
    configs move with them — so the published numbers now describe an ancestor of the shipped
    default and need re-running. Flagged rather than silently left.

Verification

$ CGO_ENABLED=1 go test -race ./...        # 25 packages ok, 0 failures
$ go vet ./...                             # clean
$ gofmt -l .                               # empty

New tests for every behaviour change:

  • TestColdCacheLiftsDepthWhenOptedIn / TestColdDecisionStaysFrozenOnLaterWarmTurns —
    both now also run the EMPTY config, i.e. the new default; the second asserts a cold-turn
    decision is frozen and replayed byte-identically over 20 later warm turns.
  • TestColdCacheFalseKeepsTheTailGateOnAColdTurn — the escape hatch.
  • TestColdSweepCannotFireOnTheMinus708Case — six ways the prefix tracker can come back
    empty or wrong (restart, evicted entry, corrupt timestamp, clock skew, a warm long-lived
    session, inside the safety margin), each asserted to read warm and to keep reporting its
    prefix frozen. This is the test that separates this change from the recorded −$708 verdict.
  • TestInPlaceFoldReportsTheSameSavingOnEveryTurn — the dispute settler: ten turns, ten
    identical gross savings, one real reduction.
  • TestAttemptedTokensCountsTheWholePrefixOnAColdTurn — the frozen accounting.
  • TestNeverTruncateAllowList — 14 real over-length lines (source locations, Python and JVM
    frames, tracebacks, panics, test verdicts, exit codes, diff lines, hunk headers, URLs),
    each must come back byte-identical.
  • TestCapTruncatesAnUnprotectedLongLine, TestScatteredDupCollapseAnnotatesTheCount,
    TestDupCollapseSkipsDiffShapedOutput, TestDupCollapseKeepsDistinctLineNumbers,
    TestDupCollapseSkipsShortLines, TestDupCollapseProtectsTheEdges,
    TestDupCollapseRunsBeforeTheCap, TestLinecapIsAPureFunctionOfContent,
    TestLinecapSkipsMarkerBearingContent, TestLinecapYieldsToAnEarlierOffloader.
  • TestReformatGetsContentDerivedCacheKeys, TestDecliningReformatClaimsNoCacheKeys,
    TestReformatKeysAreOnePerRewrittenMessage.
  • TestUnionGateNeverChangesMatchsAnswer (11 keys × the pattern shapes in the builtins),
    TestMatchKeyBoundsTheCommandHalf,
    TestCmdfilterReplaysItsRewriteByteIdenticallyAcrossTurns (12 turns, plus the stash still
    resolving afterwards).
  • TestPeekVerdicts (11 cases: text, thinking, another tool, the expand call, pings, an
    empty message, an error event, a truncated stream, an empty body, a partial final line, a
    non-Anthropic dialect), TestPeekReturnsEveryByteItConsumed,
    TestPeekStopsAtTheDecidingEvent, TestPeekFallsBackToBufferingOnAnOversizedPreamble,
    TestMarkerBearingSSEStreamsWhenItOpensWithText, and TestExpandSSELoop extended to
    assert a response opening with the expand call is still buffered.
  • TestLosslessFoldsAreInEveryWorkingPreset, TestToonIsInNoPreset,
    TestRoutesByContentNotByCommand.

How to reproduce

Real gateway, via the shared measurement harness (--binary per branch, one
run each, byte-identical bodies):

python3 drive.py --run X --arm cs=preset:codesmart --sessions tests,greps --trials 1 \
        --binary <binary>                      # cost + the SSE buffered/streamed split
python3 drive.py --run Y --arm gen=preset:general --sessions tests --limit 10 \
        --gap-before 6 --gap-seconds 400 --binary <binary>   # a REAL ttl_expiry turn

Use 400 seconds, not 330: the provider's cache expires at 300 s but cacheIsCold
requires TTL + a 60-second margin, so a 330-second gap produces a ttl_expiry row on the
dashboard with ColdCache correctly false and no sweep. Read the cache_miss_reason
column — any surviving cache_read classifies the row as hit however long the sleep was.

Two things the harness cannot show, so they have their own throwaway probes (paths in the
review thread, not committed):

  • Token-level per-component before/after needs a corpus far larger than the scripted
    sessions. tokmeasure.py replays 1,795 captured requests through /compact per arm —
    free, deterministic, no gateway spend. Every token figure in this PR comes from it.
  • The TTFB demonstration needs a marker in the transcript, a declared tool, and a long
    reply simultaneously; Mode A's ~200-token scripted replies arrive in one flush, which is
    how I talked myself into the wrong conclusion twice. ttfbprobe.py constructs all three
    and reports client first-byte against total per binary; streamprobe.py is the
    no-proxy control that establishes the gateway streams at all.

Osher-Elhadad added 9 commits August 22, 2026 00:10
format, textclean, toon and searchfold stash nothing, so every run took the
keyless fallback in metrics (`SavedUnique += saved`) and SavedUnique was
*defined* equal to Saved. overcount_ratio came out 1.0 for all four by
construction and was being read as "every token these remove is new money".

The mechanism is the opposite: an idempotent in-place fold re-folds the SAME
message on every later turn, so its removal is re-counted per turn. Measured
token replay on the captured corpus: format 10.17x, textclean 95.29x.

The pipeline now derives one key per rewritten message from that message's
PRE-fold text, so a re-fold of re-sent content dedups exactly as an Offload's
stash keys do. Pure accounting: no component behaviour changes.

The debug line stops calling these "stashed" — a Reformat is lossless and
stashes nothing; they are dedup keys.

Signed-off-by: Osher-Elhadad <[email protected]>
Three preset defects measured on 2026-08 production traffic:

* `searchfold` was written, tested, byte-for-byte round-trip verified via its
  own inverse — and in ZERO presets. Nothing ran it. 22,014 tokens on the
  measured sample went unfolded because no pipeline named it.
* `textclean` was in `general` alone (5,734 of 19,775 requests) while 49.6% of
  corpus messages carry ANSI and it had zero false positives across 861 acting
  requests. Adding it everywhere raises its denominator ~3.4x.
* `toon` acted 0 times in 5,752 requests (not_uniform_object_array 234,437) and
  an independent sweep found 0 convertible candidates in 11.67M tokens, at
  1.53 ms and one TextTokens call per tool message. Retired from every preset.

format + textclean + searchfold now lead every preset that does deterministic
work. All three verify-then-adopt, so there is no risk argument for omitting
one. toon stays REGISTERED and tested — tabular traffic can enable it by hand;
working code is not deleted, it just stops being paid for by default.

The SWE-bench and Terminal-Bench arm configs move with the presets, which
TestHarnessPresetArmsMatchTheShippedPresets enforces: published numbers must
describe the shipped product. Those arms need re-measuring.

Signed-off-by: Osher-Elhadad <[email protected]>
The depth gate exists to protect the provider's cached prefix. On a turn whose
prompt cache has provably expired there is no prefix to protect — and production
was declining anyway. Over a 5-day window, of 742 `ttl_expiry` requests we
attempted 3.87M tokens of 42.27M and FROZE 38.40M: 90.8% of the context left
alone for the sake of a cache that was already gone. `cold_start` turns run the
same components and attempt 99.6%, so the machinery was never the problem, only
the default. Those are also the turns worth acting on: a miss costs 8.5x a hit
($0.9987/req vs $0.1178), so a token removed there is worth ~12.5x a warm one.

`cold_cache` therefore defaults to ENABLED for the three offloaders whose
replacement is a pure function of (content, config) — mask, failed_run, collapse.
That is the same property repairLostFreeze requires, and it is what makes the
decision safe to freeze at depth and replay byte-identically on later warm turns.

BEHAVIOUR CHANGE ON LIVE TRAFFIC. `cold_cache: false` restores the old gate per
component (the field is a *bool so "unset" and "off" are distinguishable), and
TestColdCacheFalseKeepsTheTailGateOnAColdTurn holds that escape hatch open.

NOT defaulted on, and why: readlifecycle derives its marker prefix from
classify(), which reads later transcript events, so the same content can yield
different bytes as the transcript grows; skeleton derives its body from the
paired tool call, not from the message alone. Neither is pure, so neither
qualifies — and neither is in any preset.

Nothing loosens the cold test itself: Ctx.ColdCache still needs a recorded
previous turn plus TTL + a one-minute margin, and still reads false for a new
session, an evicted tracker entry and the first turn after a restart. A false
cold reading is the one way this loses money.

apply's frozen_tokens now reads the same gate the components read, cold lift
included. It called TailOnly, so a cold turn reported its whole prefix as frozen
while every offloader was free to rewrite it — which is why this lever was
invisible on its own dashboard.

Signed-off-by: Osher-Elhadad <[email protected]>
… transcript

## linecap — per-line cap + scattered duplicate-line collapse

cmdfilter ships 939 lines of per-command filters and production has matched
exactly two of them (`ssh` 62 acts, `uv-sync` 60; `no_filter_match` 164,865).
Sixteen further rtk command signatures — pytest, apt, npm, pip, go test, cargo,
tsc, eslint, mypy, ruff, docker, kubectl, make, gcc, git log, ps — were replayed
against 9,763 real messages and every one matched ZERO. So this adds no command
filters. It adds the two COMMAND-AGNOSTIC rules, which is why they fire where the
signatures do not: 1.75M tokens on that corpus, 20.3% of everything shipped.

Cap at 500 chars, off the measured sweep (tokens / messages touched): @200
2,031,381/2,742 · @300 1,606,241/2,520 · @500 1,105,387/1,337 · @1000
745,350/862. 500 takes 54% of @200's tokens while touching half as many messages,
and an untouched message is one whose bytes stay stable for the provider's cache.

A never-truncate allow-list is what makes a generic cap safe: a line carrying a
file path, a source location, an error, a test verdict, an exit status, a diff
marker or a URL survives any cap intact. Those lines are long for the same reason
the noise is, and they are the ones the agent has to act on.

The duplicate collapse is the NON-adjacent case, worth 649,330 tokens; extract's
collapseObviousNoise already handles adjacent repeats and was measured at 63
tokens of remaining value. Guards: skip diff-shaped blobs entirely (identical
`+ return nil` lines are distinct edits), never collapse lines differing only in a
source location (two findings, not one repeated), never collapse under 8 trimmed
chars, never touch the first or last 3 lines. The `(xN)` keeps the elision visible
and is rendered AFTER the cap — appending it during the collapse put it at the end
of a line the cap then truncated, eating the annotation.

Duplicates collapse BEFORE the cap so a dropped duplicate is not also charged as a
capped line; the other order double-counts the same tokens.

## cmdfilter and pipeline performance — no behaviour change

Duration was linear in transcript size (3.23 ms below 50 messages, 42.95 ms at
500+) because the whole transcript was re-derived every turn, with a 188 ms tail.

* the 188 ms tail was an unbounded match key: ToolCall.Command() falls back to
  `Name + " " + Args` for Write/Edit/MultiEdit, so a 200 KB payload became the key
  every filter scanned. The existing newline cut cannot bound it — a JSON string
  never holds a literal newline. Clipped to 200 runes, which costs no reach.
* per-message memo keyed on the CONTENT hash, reusing the existing freeze/replay
  machinery. Keyed on content, not index: the requirement is byte identity with
  what the prefix already holds, and an index says nothing about that (an earlier
  component can change what sits at one).
* the registry was a linear scan of 26 regexes and it MISSES for 21 of ~43
  candidates per request — 550 full-registry evaluations. One RE2 union gate now
  short-circuits the miss; on a hit the ordered scan still picks the winner, so
  priority is unchanged. Built as (?m:...) per pattern, matching Compile: a gate
  without the flag rejects every `^`-anchored filter as soon as the key carries a
  `$ <command>` line, which is a silent under-match. Test asserts the gate never
  changes Match's answer.
* selectorKey allocated a string header per line of a 300 KB blob to keep six.
* schema.MessageText was O(n^2) on multi-block messages, and it is called for
  every tool message ahead of every size gate.
* min_size now precedes skipReduce, which SHA-256s the whole message: the ~21
  per-request messages about to be rejected as too small were being hashed first.

Verified behaviour-neutral by replay: 1,795 real captured requests through
/compact on the identical pipeline give byte-identical savings (262,544 tokens)
on both binaries.

Signed-off-by: Osher-Elhadad <[email protected]>
… stream

The largest latency item in the system, and invisible in the per-component
timings. Production over ~37h:

    sse_streamed 2,779 · sse_buffered 1,393     -> 33.4% of responses buffered
    sse_ttfb_ms_avg           7,918 ms
    sse_ttfb_ms_avg_buffered 28,998 ms          -> ~21 SECONDS of extra TTFB

against a whole-pipeline cg_added_ms_avg of 154 ms. Compaction's real latency
cost was ~140x what the component numbers say.

Cause: `checkExpand := advertised && round < maxExpandRounds`, where `advertised`
is "the expand tool is on the outgoing request". Injection is marker-gated, so the
documented zero-latency fast path does hold before the first offload — and from the
first offload onward markers are sticky, so EVERY response in the session was read
in full so the loop could look for a lone expand call.

Now the response is inspected with a bounded peek. In the Anthropic dialect the
first content_block_start arrives early and names the block type and, for a
tool_use, the tool; only a response that OPENS with a call to the expand tool has
to be withheld. Everything else — thinking, text, another tool, an empty message,
an error event, a stream that ends early — flushes the peek and streams the
remainder. peekSSE never discards input, so head + remainder is the stream
byte-for-byte on both paths.

Non-Anthropic SSE now always streams. AggregateSSE only reconstructs the Anthropic
event stream, so for any other dialect the buffered path already fell through to
writeRaw and replayed the bytes verbatim: it was paying the full latency for an
inspection that never happened.

Fail-open is preserved: an unreadable or oversized preamble buffers, which is the
old behaviour.

THE ACCEPTED LIMIT, and why it is not hidden. A response that opens with thinking
or text and calls expand LATER is streamed, so the client receives the model's raw
expand tool_use instead of the proxy resolving it. That outcome already exists on
two live paths (`otherTools`, and `got == 0`), so it is inside the design's failure
envelope rather than new. It is also measured, not asserted: streamFrom counts
every streamed response that named the expand tool, reported as
`sse_expand_after_stream` on /stats (an upper bound — prose mentioning the tool
counts too). If that number is a meaningful fraction of sse_streamed the trade is
wrong, and the fix named in ssepeek.go is to stop forwarding AT the expand block
and splice the continuation's content blocks into the same stream with remapped
indices.

The peek decides on the first block rather than skipping past thinking because
extended thinking is enabled on 100% of the captured production traffic and the
thinking block is where most of a reasoning turn's tokens are — buffering through
it would keep most of the 21 seconds, which is the thing being fixed.

Signed-off-by: Osher-Elhadad <[email protected]>
…n the command

searchfold pre-gated on which command produced each tool result — fold `rg`/`grep`/
`find` output, skip `cat`/build/test output. Replayed over 1,795 real captured
requests through /compact, that gate lost on both axes it was meant to trade
between:

                   tokens folded   unique   searchfold ms/request
      with gate          234,722    5,395                   1.174
      no gate            333,764    5,903                   0.509

It declined 29,737 candidate messages, 99,042 tokens of which had exactly the
repeated path prefix this folds: the pairing says which command RAN, not what its
output looks like, and agents pipe and redirect search output through everything.
It was also the more expensive path — resolving a pairing calls ToolCall.Command(),
which json.Unmarshals a whole argument object per tool message, whereas the fold
exits on its first line without a repeated prefix.

The fold self-verifies (adopt() keeps it only if the inverse reproduces the input
byte for byte and the result is smaller), so a misroute costs CPU, never
correctness. That is the general rule for a self-verifying fold: attempt it, keep
what round-trips. A cheap SHAPE pre-check still earns its keep where one exists —
format's not_json_shaped is a one-byte test guarding a full parse — but a pre-check
that has to reconstruct request STRUCTURE does not.

isSearchCommand and its regex go with the gate.

Signed-off-by: Osher-Elhadad <[email protected]>
Documents what the code now does, and corrects one over-claim.

* components.md: linecap gets a section with its measured sweep and its
  never-truncate allow-list; searchfold routes by content, not by command;
  toon is marked retired with the number; mask/failed_run/collapse show
  `cold_cache` defaulting true; every preset list is refreshed.
* reference/presets.md: the lossless trio, toon's retirement and linecap, with
  a note that codesmart/codesafe changed and the published SWE-bench numbers
  need re-measuring against them.
* reference/routes.md, how-to/recover-context.md, design.md: buffering is now
  chosen only when a response OPENS with an expand call, and the new
  sse_expand_after_stream counter is what keeps that trade honest.

The correction is in proxy/ssepeek.go. It read the production gap between
sse_ttfb_ms_avg (7,918 ms) and sse_ttfb_ms_avg_buffered (28,998 ms) as ~21 s
that buffering ADDED. That gap is confounded: buffering starts at the first
offload, so the buffered set is systematically later-in-session, larger-prefix,
longer-generating requests. Measured directly instead, on this box: 23 of 30 real
streaming responses buffered before the change, 0 of 30 after, on byte-identical
bodies — and NO client TTFB improvement, because the gateway this deployment
talks to does not stream either (no proxy in the path at all: ttfb/wall = 1.000
on 6 of 6 turns). The change removes context-guru's own contribution and pays off
on an upstream that streams; it does not fix that upstream.

Signed-off-by: Osher-Elhadad <[email protected]>
It was placed directly after cmdfilter, and that made it a net REGRESSION on the
one preset where it had heavier offloaders downstream of it. `general` over 1,795
real captured requests through /compact:

    linecap 7th    5,524,476 saved (28.87%)   <- worse than not shipping it
    no linecap     5,556,801 saved (29.03%)
    linecap last   5,811,621 saved (30.37%)

Mechanism, from the per-turn gate ledger of a real 10-turn gateway session: every
Offload leaves a marker, and every Offload skips marker-bearing content
(skipReduce, so nothing double-reduces and no stash is orphaned). A MODEST reducer
ahead of a DRASTIC one therefore does not merely overlap with it — it takes the
candidate away entirely. linecap took 39,335 tokens off messages `collapse` would
have taken 76,554 off, and its marker then made mask, extract and collapse decline
those messages outright (marker_or_kept_verbatim 3 and 6, below_max_tokens 6 on the
turn measured). Billed cost on that session went the wrong way: $0.2935 -> $0.3266.

So linecap now sits immediately before cachesplit in every preset, where it caps
and dedups the lines the bigger offloaders left behind. TestLinecapYieldsToAnEarlier
Offloader pins the mechanism as a property of the component rather than of one
preset's ordering.

Signed-off-by: Osher-Elhadad <[email protected]>
The memo hashes the message content, which partly cancelled the reason min_size
was moved above skipReduce in the first place: the ~21 messages per request about
to be rejected as too small were hashed anyway, just by a different caller.
Measured as a real regression on short transcripts — /compact wall was +3.3% under
50 messages.

min_size now precedes both. Behaviour-neutral in both directions: a sub-min_size
message is declined either way, and a frozen rewrite can only exist for content
that already passed the floor once, since the agent re-sends the same original
bytes and the same length gives the same verdict.

Re-measured, byte-identical savings (262,544 tokens), /compact wall by transcript
length:

    messages     n      before     after    delta
    < 50     1,082    11.87 ms  11.69 ms    -1.5%   (was +3.3%)
    50-199     657    23.36 ms  22.84 ms    -2.2%
    200+        56    48.09 ms  46.80 ms    -2.7%

cmdfilter's own timer: 4.353 -> 3.872 ms/request.

Signed-off-by: Osher-Elhadad <[email protected]>
proxy/promexport.go records a measured verdict on acting when frozen_tokens reads
zero: 3,092 requests whose OWN prefix tracker had been reset (a restart, an
evicted entry) still cache-HIT for 404,376,878 cache-read tokens, and treating
that as "the cache is cold, deep history is safe to rewrite" was worth about
-$708 on sonnet-5 against +$0.62 of upside.

The cold sweep is a different claim and the difference needs to be provable, not
argued. A reset tracker has no previous turn on record, cacheIsCold answers FALSE
for it, and the sweep cannot fire; the -$708 outcome needs a WARM cache misread as
cold. TestColdSweepCannotFireOnTheMinus708Case walks every way the tracker can
come back empty or wrong — restart, evicted entry, corrupt timestamp, clock skew
into the future, a warm long-lived session, and idle past the TTL but inside the
safety margin — and asserts each reads warm AND still reports its prefix frozen.

That metric's doc comment also needed correcting, because this branch gave
frozen_tokens == 0 a second cause. It now names both and how to tell them apart
(the request's cache_miss_reason: a swept turn reads ttl_expiry/cold_start, a
reset tracker reads hit), so the reading the comment exists to warn about stays
unambiguous.

TestInPlaceFoldReportsTheSameSavingOnEveryTurn settles the dispute the dedup-key
change turns on. The agent re-sends the ORIGINAL tool output every turn -- our
rewrites are wire-only -- so an in-place fold meets the same unfolded bytes again
and reports the same saving again: ten consecutive turns, 328 tokens of gross
each, for 328 tokens of real reduction. "Byte-stable across turns", which
textclean's own doc comment claims as a virtue, is exactly what makes the saving
re-counted rather than new.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Review — CHANGES-REQUIRED (3 blockers, all small diffs)

Verified in the PR's worktree: CGO_ENABLED=1 go test -race -count=1 ./... → 25 packages ok, 0 failures; go vet ./... clean; gofmt -l . empty. Plus three throw-away probe tests (written, run, deleted) whose numbers are quoted below.

This is the best-argued of the four branches on evidence. The −$708 separation is sound — I read promexport.go:582 rather than the commit's summary of it, and it prices misreading frozen_tokens == 0 as coldness on 3,092 requests whose tracker had been reset and which still cache-HIT for 404M cache-read tokens. That is unambiguously a warm cache misread as cold, and cacheIsCold returns false for prevAtMs <= 0 and for nowMs <= prevAtMs, so a restart, an evicted entry and a skewed clock all decline themselves. Different claim, correctly separated.

I also checked the purity property individually for each newly opted-in component and it holds: mask → prefix + headPeek(content) + Marker(sha256(content)); failed_run → fixed banner + marker; collapse → head + "... (N lines omitted) " + marker + tail with N from content and config. All pure in (content, config). readlifecycle and skeleton correctly stay off with their form defaults pinned to false, and extract_llm is untouched — no sampled output was opted in. All three call reapplyFrozen before their size/shape gates, so a cold-turn decision replays byte-identically, and TestColdDecisionStaysFrozenOnLaterWarmTurns now runs the default config too. The shared symbols (cacheIsCold, coldMargin, cacheTTL, Tracker.TurnAt, Ctx.ColdCache, Ctx.IdleMs, TailOnlyCold) are functionally untouched — modes/tracker.go isn't in the diff at all.

The accounting fix is right, and R7's reading is the correct one. I checked it from the mechanism, not from either report: apply rewrites the wire body only and never the client's copy, so the agent re-sends the original every turn, an idempotent in-place fold meets the same bytes again and re-reports the same saving — the identical mechanism behind the offloaders' 92.9x. dash/capture.go:604 (if len(keys) == 0 { return saved }) was the artifact. reformatKeys hashes pre-fold text, is namespaced away from stash keys, and can't clobber anything a component set itself since Reformat returns no keys. And §3 presents the reduction loudly, in bold, with the before/after ratios. That is the right presentation.

toon is retired but kept registered and tested; searchfold's adopt round-trip is intact. Both correct calls. Regressions are reported — the linecap placement net loss, the +3.3% short-transcript regression from the memo, two abandoned TTFB claims stated rather than quietly replaced, searchfold measured worse than the reports predicted, and the benchmark numbers flagged as describing an ancestor. DCO on all 10 commits, no AI attribution, no secrets or PII (grepped the diff and body for emails, the two account ids, session UUIDs and token shapes — zero hits), schemaVersion still 6.

The three blockers

1. The SSE peek drains the whole response on the non-Anthropic dialect, and counts it as streamed. peekSSE runs before the provider test, and sseLineVerdict recognises no OpenAI-dialect event, so no line ever decides and the loop runs to EOF or 64 KB. Measured: an 11,614-byte OpenAI-shaped stream → peek consumed 11,614 bytes (100%); a 290,000-byte one → 65,539. The client's first byte still arrives after the last upstream byte, but sseBuffered stays false, so RecordSSE files a time-to-last-byte value into sse_ttfb_ms_avg — the streamed bucket. That is the exact mislabelling the PR body correctly warns about for sse_ttfb_ms_avg_buffered, reintroduced on a new path. The comment claims these dialects "skip the peek"; they don't. One-line fix (hoist the provider test above peekSSE, pass head=nil), and TestPeekStopsAtTheDecidingEvent needs the OpenAI case — its 51-byte dialect row in TestPeekVerdicts cannot see this.

2. The shipped default contradicts its own design doc, which names two false-cold paths this PR doesn't address. Five sites still say off: docs/design.md:268 "(default off)", docs/design.md:280 an entire "Why the default is off" subsection, components/component.go:314, components/component.go:213-219 (a paragraph arguing against exactly this change, by component name), and components/offload/mask.go:102. TailOnlyCold points readers at design.md for the rationale, and design.md now argues the opposite of what ships. Worse, §"Why the default is off" names two paths that produce a true false-cold and says "neither is instrumented today": (a) a client asking ttl:"1h" on one turn and bare ephemeral on the next — cacheTTL reads the TTL from this request, so a prefix held for an hour is judged cold at six minutes; (b) a prefix touched under a different session id than the idle clock is kept under (session.Scoped falls back to a system+first-user hash) — and the provider's cache is content-keyed, not session-keyed, so activity under id B keeps the entry warm while id A's prevAt goes stale. Both are the −$708 mechanism through a different door, and both produce a populated, plausible, stale prevAt — which is the one shape TestColdSweepCannotFireOnTheMinus708Case's six rows do not cover (all six are empty/corrupt/skewed/too-recent). In fairness, the revised parallel-fan-out measurement (only 2 of 1,260 near-simultaneous cold starts plausibly share a prefix) is what makes me judge the lift probably safe rather than unsafe — but "probably, from a measurement taken for a different question" is below the standard this PR sets everywhere else, applied to the one change that can lose money by default. Asked: fix the five doc sites, and either discharge both paths with a number (how many production rows show ColdCache true and cache_read > 0 — that query is the whole test) or add that counter before defaulting on.

3. The line cap destroys the only actionable token when the file reference sits past char 500. TruncateRunes keeps the head and drops the tail, and neverTruncateRe only recognises a source location anchored at the very start of the line (^\S+:\d+) — leading whitespace defeats it. Three realistic inputs, all unprotected and truncated with the path lost: Could not resolve import '@scope/…' … at /home/u/repo/src/components/Widget.tsx:42:11 (709 chars); Cannot find module '<long path>' required from /home/u/repo/server/boot.js (631); {"level":"warn","msg":"<long>","file":"/home/u/repo/pkg/a.go","line":88} (666). Also unprotected: a bare long path with no :line; an indented path:line:col (cargo's --> src/main.rs:5:9, tsc/eslint pretty output); a Go stack frame's \t/path/file.go:412 line; an error with no literal error token. TestNeverTruncateAllowList cannot catch this class — all 14 of its lines put the actionable token at the head, where a head-preserving cut never touches it. Two fixes, either sufficient: widen the pattern (^\s*\S+:\d+ plus an unanchored path-with-line form), or cut head + ellipsis + tail instead of head-only. I prefer the second — it removes the dependency on the allow-list being complete, which is load-bearing today and cannot be verified.

The rest of the peek I checked case by case and it's sound: thinking / text / another tool / pings-first / empty message / error event / EOF mid-preamble / empty body / truncated final line all stream; a lone expand call is still buffered; sseBuffered stickiness holds across rounds; head+remainder is byte-identical; oversized preamble falls back to buffering. TestMarkerBearingSSEStreamsWhenItOpensWithText blocking the upstream before its tail is a genuinely good test. And the accepted limit — with thinking on for 100% of traffic the expand loop is effectively unreachable for streaming traffic — is disclosed, matches the pre-existing otherTools/got == 0 outcomes, fires on 5 of 5,752 requests, and is instrumented. I agree with that trade.

Nine nits (missing preset-position guard for linecap; dead lineNum var; searchfold's per-message CPU at 8.16 ms on a 1.2 MB non-foldable output; cmdfilter's per-filter ledger silently changing meaning; MarkUnique's overflow reset tripping sooner; the unreachable buildGate branch; the 2.86x headline containing none of the cold sweep; mcp lacking searchfold) are in the full review with file:line. Full review: /tmp/cg-orch/REVIEW-89.md.

Comment thread proxy/proxy.go Outdated
// Non-Anthropic dialects skip the peek and stream unconditionally: AggregateSSE
// only reconstructs the Anthropic event stream, so for anything else the
// buffered path below reaches `writeRaw` and replays the bytes verbatim. It was
// paying the full latency for an inspection that never happened.

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.

BLOCKING — the peek drains the whole response on the non-Anthropic dialect, and reports it as streamed.

peekSSE is called before the provider test, and sseLineVerdict decides only on content_block_start / message_stop / error. No OpenAI-dialect event carries a type it recognises, so no line ever decides and the loop runs to EOF or the 64 KB bound. Measured on this branch:

stream bytes peek consumed verdict
OpenAI-shaped, 200 chunks 11,614 11,614 (100%) streamable
OpenAI-shaped, 5,000 chunks 290,000 65,539 mustBuffer → forced streamable

So for any non-Anthropic SSE response under 64 KB the client's first byte still lands only after the last upstream byte — the old behaviour — but sseBuffered stays false, so the deferred RecordSSE(msSince(reqStart, sseFirstByte), false) files a time-to-last-byte value into sse_ttfb_ms_avg, the streamed bucket. That is precisely the mislabelling the PR body correctly warns about for sse_ttfb_ms_avg_buffered, reintroduced on a different path, and it will drag the streamed average for reasons no reader can see.

The comment above claims the opposite of what the code does: "Non-Anthropic dialects skip the peek and stream unconditionally." They do not skip it.

Fix is one hoist:

if provider != bschemas.Anthropic {
        sse = true
        first, u, ok := h.streamFrom(w, resp, nil, resp.Body) // no peek at all
        ...
        return
}
br := bufio.NewReader(resp.Body)
head, verdict := peekSSE(br, expand.ToolName)

No test covers it. TestPeekVerdicts' "not the Anthropic dialect at all" row is a 51-byte stream, so the drain is invisible in it, and TestPeekStopsAtTheDecidingEvent — whose own comment says "a peek that reads to EOF would be the old buffering wearing a new name" — only exercises the Anthropic dialect. Please add the OpenAI case there.

`|(?i)exit (code|status)` +
`|^[+-]{1,3}[^+-]` + // diff added/removed lines and ---/+++ headers
`|^@@ ` + // diff hunk header
`|https?://`)

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.

BLOCKING — the cap destroys the only actionable token when the file reference sits past char 500.

dsl.TruncateRunes keeps the head and drops the tail, and this pattern only recognises a source location anchored at the very start of the line (^\S+:\d+) — leading whitespace defeats it. Three realistic coding-agent inputs, all unprotected and all truncated with the path lost (measured with a probe against neverTruncate + rewrite):

line chars protected? outcome
Could not resolve import '@scope/…' … at /home/u/repo/src/components/Widget.tsx:42:11 709 no location gone
Cannot find module '<long path>' required from /home/u/repo/server/boot.js 631 no both paths gone
{"level":"warn","msg":"<long>","file":"/home/u/repo/pkg/a.go","line":88} 666 no file+line gone

Also unprotected from the same probe: a bare long absolute path with no :line suffix; an indented path:line:col reference (cargo's --> src/main.rs:5:9, tsc/eslint pretty output); a Go stack frame's file line \t/home/u/repo/pkg/thing.go:412 +0x1d … (leading tab, matched by neither ^\S+:\d+ nor ^\s*(File "|at )); and an error message with no literal error token.

TestNeverTruncateAllowList cannot catch this class — all 14 of its lines put the actionable token at the head, where a head-preserving cut never touches it.

Two fixes, either sufficient:

  • widen the pattern — ^\s*\S+:\d+ for the indent case, plus an unanchored path-with-line form so a reference anywhere in the line protects it; or
  • cut head + ellipsis + tail instead of head-only.

I prefer the second. The allow-list's completeness is load-bearing today and cannot be verified; a head+tail cut preserves both the message and the trailing location and removes that dependency entirely.

Mitigating, and why this is blocking rather than severe: the original is stashed and the marker names the expand tool, so nothing is unrecoverable — the cost is a wasted round trip on exactly the lines the agent needs to act on.

Everything else in this component I checked and found correct: no marker-only degenerate is reachable (a 20,000-char single line still yields 500 chars of content plus the marker, and the collapse always keeps first occurrences plus the first/last 3 lines); elision is visible in both rules; rendering (xN) after the cap is the right call; folds == 10 in TestDupCollapseRunsBeforeTheCap is the correct double-count guard; out/counts are appended in lockstep so they cannot desynchronise; and every positional guard from R6 §5 is present and tested.

Comment thread components/offload/linecap.go Outdated
// in a line number are never treated as the same line. `pkg/a.go:12: undefined: x` and
// `pkg/a.go:87: undefined: x` are two findings, and a count of two is not the same
// information as two locations.
var lineNum = regexp.MustCompile(`:\d+`)

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.

Nit — dead code, and its comment describes an implementation that does not exist.

lineNum is never referenced. Worse, the comment above it says it "strips the digits out of every :N:-style group so two lines that differ ONLY in a line number are never treated as the same line" — but dupKey at :285-294 does the opposite and is right to: it keeps the digits in the key, which is what makes pkg/a.go:12 and pkg/a.go:87 hash differently, and it explains that at :290. go vet does not flag unused package-level vars, so this will sit here.

Delete the var and the comment; the rule is already stated where it is implemented.

// - skeleton: its body is derived from the PAIRED tool call (path/language), not from
// the message alone.
// - extract_llm: a sampled model output, and it has its own richer `cold_cache` block.
func coldCacheDefault(v *bool) bool {

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.

BLOCKING (docs, but load-bearing) — five sites still say this default is off, and the design doc names two false-cold paths this PR does not address.

The code change is right and I would approve it on the mechanism. I checked the purity property individually for all three: mask emits prefix + headPeek(content) + Marker(sha256(content)), failed_run a fixed banner + marker, collapse head + "... (N lines omitted) " + marker + tail with N from content and config. All pure in (content, config). All three call reapplyFrozen before their size/shape gates, so a cold-turn decision replays byte-identically. The *bool is the right call and Field.Default's omitempty means Default: false serialises as absent, so the form does not lie.

1. Five places still document the old default:

  • docs/design.md:268 — "mask, failed_run and collapse therefore take a cold_cache option (default off)"
  • docs/design.md:280 — an entire subsection headed "Why the default is off."
  • components/component.go:314 (TailOnlyCold) — "The opt-in is per component and off by default."
  • components/component.go:213-219 (Ctx.ColdCache) — argues against exactly this change, by component name: "flipping TailOnly here would change what mask, failed_run and collapse do on live traffic the moment this shipped — including for deployments that asked for none of it."
  • mask.go:102, a few lines above this one — "(cold_cache, off by default)"

TailOnlyCold points readers at docs/design.md for the rationale, and that document now describes the opposite of what ships. The brief says three workstreams depend on the current meaning of these symbols — the symbols are untouched (good), but their documented meaning is now wrong, which is the same hazard by a slower route.

2. The gap that matters. docs/design.md:285-292 — the paragraph whose conclusion this PR overrides but whose content it does not address — names two paths that produce a true false-cold and says "neither is instrumented today":

  1. A client asking ttl: "1h" on one turn and a bare ephemeral mark on the next. cacheTTL(provider, body) reads the TTL out of this request, so a prefix the provider is holding for an hour is judged cold after six minutes. Live logic, and 1h grants are real on this deployment.
  2. A prefix touched under a different session id than the idle clock is kept under. session.Scoped falls back to a system + first user hash, so one provider cache entry can sit under two of our session ids — and the provider's cache is content-keyed, not session-keyed. Activity under id B keeps the entry warm while id A's prevAt goes stale; id A then reads cold at six minutes and rewrites a prefix the provider still holds.

Both are the −$708 mechanism arriving through a different door than the empty tracker, and both produce a populated, plausible, stale prevAt — which is the one shape TestColdSweepCannotFireOnTheMinus708Case does not cover. All six of its rows are variants of "the tracker came back empty, corrupt, skewed, or too recent".

In fairness, the revised parallel-fan-out measurement (only 2 of 1,260 near-simultaneous cold starts plausibly share a prefix) is what makes me judge the lift probably safe rather than unsafe. But "probably, from a measurement taken for a different question" is below the standard this PR sets for itself everywhere else, and it is being applied to the one change that can lose real money by default.

Asked: fix the five doc sites, and either discharge both paths with a number — how many production rows show ColdCache true and cache_read > 0; that query is the test — or add that counter before defaulting on. It is a handful of lines and it would settle this permanently.

Separately and for the record: the −$708 separation itself is sound. I read promexport.go:582 rather than the commit's summary of it. It prices misreading frozen_tokens == 0 as coldness on 3,092 requests whose tracker had been reset and which still cache-HIT for 404,376,878 cache-read tokens — unambiguously a warm cache misread as cold — and cacheIsCold returns false for prevAtMs <= 0 and for nowMs <= prevAtMs, so a restart, an evicted entry and a skewed clock all decline themselves.

Comment thread config/config.go
// two overlapping old-context reducers (mask is the one kept; summarize
// is its own preset — see docs/components.md redundancy notes).
"general": {"format", "toon", "textclean", "dedup", "failed_run", "cmdfilter", "mask", "extract", "extract_llm", "collapse", "cachesplit"},
"general": {"format", "textclean", "searchfold", "dedup", "failed_run", "cmdfilter", "mask", "extract", "extract_llm", "collapse", "linecap", "cachesplit"},

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.

Should-fix — nothing pins linecap's position, and the mistake it guards against has already happened once.

TestLinecapYieldsToAnEarlierOffloader proves the mechanism (linecap declines marker-bearing content), and the comment at :156-167 records the measurement. But the regression that actually occurred was a preset-ordering mistake, and nothing here stops it recurring — general with linecap 7th saved 5,524,476 tokens against 5,556,801 with no linecap at all, i.e. shipping it in the wrong slot was worse than not shipping it.

A three-line assertion alongside TestLosslessFoldsAreInEveryWorkingPreset is proportionate:

// linecap is a MODEST reducer and every Offload skips marker-bearing content, so ahead of a
// drastic one it steals the candidate outright — measured as a net loss on `general`.
for name, pipeline := range presets {
    for i, c := range pipeline {
        if c == "linecap" && (i+1 >= len(pipeline) || pipeline[i+1] != "cachesplit") {
            t.Errorf("preset %q runs linecap at %d, not immediately before cachesplit: %v", name, i, pipeline)
        }
    }
}

Also worth a line in the body: "the lossless trio in every preset" is not literally true — mcp gets format and textclean but not searchfold. The test carves mcp out with a stated reason, which is fine; the commit subject and §4 overstate it.

Comment thread components/reformat/searchfold.go Outdated
//
// This is the general rule for a self-verifying fold: attempt it, keep it if the inverse
// reproduces the input and the result is smaller. A cheap SHAPE pre-check is still worth it
// where one exists (`format`'s not_json_shaped is a one-byte test guarding a full parse);

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.

Nit — the per-message CPU is now unbounded by shape, and the comment overstates the early exit.

Dropping the command pre-gate is the right call: adopt requires inverse(out) == in and a size reduction, so a misroute costs CPU and never correctness. I verified that path is untouched. And the corpus average genuinely improves (0.509 vs 1.174 ms/request) because resolving a pairing json.Unmarshals an argument object per message.

But the fold now runs on every tool output, and it is three folds plus three inverses, each a full pass. Measured on this branch against output with no path-prefixed lines at all (a plain cat of source):

non-foldable tool output per attempt
24 KB 275 µs
240 KB 1.73 ms
1.2 MB 8.16 ms

The corpus average is fine and I accept it — but that corpus "tops out at 258 messages" and its message sizes are not the tail either. This PR's own rule applies verbatim: "a cheap SHAPE pre-check is still worth it where one exists (format's not_json_shaped is a one-byte test guarding a full parse)". One scan for any \S:\d+[:-] row would gate all three folds for a few hundred nanoseconds and keep everything the measurement gained.

Related, and the reason I measured rather than assumed: the claim in this comment that "the fold itself exits on its first line without a repeated prefix" is not what the code does. foldHitPath splits and rebuilds the whole string, and adopt only compares lengths afterwards.

// reapplyFrozen also re-Puts the stashed original for every marker in the
// replacement, so the expand loop keeps working across turns, and it declines
// content the agent has expanded (kept-verbatim).
if fk, _, ok := reapplyFrozen(c, f.Name(), m); ok {

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.

Nit — the per-filter ledger silently changes meaning here.

The memo is keyed correctly: on content, not on index or position, which is the requirement (byte identity with what the provider's prefix already holds). I also checked the near-miss — reapplyFrozen now runs before skipReduce, and contentKey strips markers, so I looked at whether a frozen cmdfilter decision for a full original could be replayed onto a message an earlier component had already collapsed (dedup/failed_run both run ahead of cmdfilter in general). It cannot: contentKey removes the marker token but keeps the surrounding text, so a truncated body hashes differently. Good.

The observability side is the loose end. On turn 2+ this branch continues, so fs.FilterAct(filt.Family(), filt.Name, stashKey, before-after) at :213 is never reached. cmdfilter_filters[*].acts and .saved therefore now count first removals only, while the component's own saved_gross still counts every turn — the two will diverge, and today they are the ledger anyone uses to decide which filter is worth keeping.

Arguably an improvement (it is closer to unique), but it is an undocumented metric-semantics change riding inside the PR that fixes a different metric-semantics problem, and this repo has now named that defect class five times. One line in the body, or move the FilterAct call so the replay path records too.

Comment thread components/pipeline.go
keys := make([]string, 0, len(changed))
for _, i := range changed {
if i < 0 || i >= len(before) {
continue

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.

Correct, and I verified the dispute independently rather than taking either report's word.

R7 is right and R5 §1c is wrong, and the mechanism is checkable from the code alone: apply rewrites the wire body only and never the client's copy of the transcript, so the agent re-sends the original unfolded tool output every turn. An idempotent in-place fold meets the same bytes again, folds them again, and reports the same saving again — the identical mechanism that gives the offloaders their 92.9x / 65.3x / 51.6x overcount ratios. "Byte-stable across turns" is what makes the saving re-counted, not what makes it new.

The artifact's source is dash/capture.go:604 (if len(keys) == 0 { return saved }), mirrored at metrics/metrics.go:321 and :404. Reformats stashed nothing, so they always took it and SavedUnique was defined equal to Saved.

Four things I checked about the fix itself, since a wrong key here would be its own bug:

  • keys hash the text before the fold, so the same output re-sent next turn maps to the same key however the fold re-renders it — that is the property that makes the dedup work at all;
  • MarkUnique already scopes by tenant + component, so the cg:fold: prefix is belt-and-braces and cannot collide with an Offload's stash keys;
  • only rep.Kind == "reformat" is overwritten, and the Reformat interface returns no keys, so nothing a component set itself is clobbered;
  • both consumers (/stats aggregator and the dashboard recorder) use the keys identically, so the two figures still agree.

And §3 presents the reduction loudly, in bold, with the before/after ratios including searchfold coming out worse than the reports predicted. That is the right presentation for a change that makes our own numbers smaller.

One knock-on worth a sentence in the body, not a change: MarkUnique's clear-on-overflow at dash/capture.go:609 (200,000 keys) now trips sooner, because Reformats contribute keys where they contributed none. After a reset, repeats are re-counted as unique — bounded and visible via overcount_ratio, and pre-existing policy, but it slightly warms the very ratio this fix is correcting.

Comment thread apply/apply.go
n := 0
for i := range norm {
if c.TailOnly(i) {
if c.TailOnlyCold(i, c.ColdCache) {

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.

Correct, and this is the "suspect the instrument before the mechanism" fix.

attemptedTokens reading TailOnly while every deterministic offloader was already free to rewrite the prefix on a cold turn is what made the biggest lever in the system invisible on its own dashboard. Reading the same gate the components read is right, and the ponytail: note about a deployment that sets cold_cache: false everywhere over-reporting attempted is the honest bound on it.

Two notes for the body rather than the code:

1. The headline table contains none of the cold sweep. "2.86x the savings on the default preset" comes from the 1,795-request /compact replay. /compact does pass the Tracker (proxy/proxy.go:603), but a replay runs turns back-to-back, so cacheIsCold never fires and Ctx.ColdCache is effectively always false — the cold lift contributes exactly zero to that table. The arithmetic bears it out (linecap 150,498 + searchfold 333,764 + textclean 12,064 ≈ the 487,701 delta). A reader can easily attribute part of the 2.86x to the change the PR itself calls the biggest lever. One sentence fixes it.

2. The ttl_expiry demonstration does not print cache_read. AttributeCache requires cache_read == 0 before it will classify a row that way, so the stated cache_miss_reason='ttl_expiry' implies it and the rule is satisfied — but since the whole point of that section is that the miss was real, printing the column alongside cache_write would settle it outright rather than by inference.

For the record on evidence I could not re-run: every token figure comes from tokmeasure.py over a corpus in /tmp/cg-det/, so none of it is checkable from the repo. The three-times-running byte-identical baseline is the right control for it. The gateway cost claim ($0.8800 → $0.8013, −8.9%) is one trial per arm — 8.9% is well above the harness's 0.04–0.7% spread so it stands, but a second trial is cheap. And the forced-TTL session's −$0.0041 deltas are inside the noise floor; the PR correctly declines to bank a dollar figure from them and says to watch live frozen_tokens instead, which is the right call.

…preserving cap

Three blocking findings from the review of #89.

## The peek drained non-Anthropic streams and filed them as streamed

peekSSE ran BEFORE the provider test and the verdict was overridden afterwards, so
the label was fixed and the behaviour was not. sseLineVerdict only decides on
content_block_start / message_stop / error and no OpenAI-shaped event carries a
type it recognises, so nothing ever decides and the loop runs to EOF or the 64 KB
bound — measured, an OpenAI-shaped 200-chunk stream was 100% consumed. The client's
first byte still arrived after the last upstream byte, and with sseBuffered false
RecordSSE filed a time-to-LAST-byte value into the STREAMED bucket, dragging that
average down invisibly. The provider test is now first and such a stream is copied
straight from resp.Body with no peek. TestOpenAISSEStreamsThrough asserts the
client sees a chunk while the upstream is still blocked;
TestOpenAIDialectPeekWouldDrainTheWholeStream pins why the guard has to exist.

## Both false-cold paths closed

docs/design.md named two ways coldness can be FABRICATED and this branch had
deleted the paragraph's conclusion without addressing its content. Both produce a
POPULATED, PLAUSIBLE, STALE prevAt — the one shape the -$708 test does not reach,
since all six of its rows are "the tracker came back empty or too recent".

* cacheTTL reads the TTL out of THIS request, so a session that asked ttl:"1h" once
  and sends a bare ephemeral mark afterwards would be judged cold at six minutes.
  sessionTTL widens it to the longest lifetime the session has ever asked for,
  monotonically, so the estimate can only move toward WARM. Unobserved today
  (0 of 1,868 captured requests carry a ttl field) and live the moment anything adds
  1h marks.
* The idle clock is per session id; the provider's cache is keyed on CONTENT. One
  conversation reaches us under two ids whenever an explicit header is present on
  some turns and absent on others, and three of thirteen production tenants send
  both id shapes. The decision now also reads the alias clock — the same id
  session.Scoped would derive with no header — and takes the LATER timestamp, so a
  touch under either id keeps both warm.

The alias clock lives in the store rather than the Tracker on purpose: TurnAt runs
the length through modes.Boundary, which counts a compaction reset, so recording a
second key per request double-counted that metric (caught by
TestCompactionResetIsCounted).

Five places still documented the old default, one of them arguing against this
change by name. component.go, mask.go and the design doc's "Why the default is off"
subsection now describe what ships, including how each fabrication path is closed.

## The line cap destroyed the only actionable token

dsl.TruncateRunes keeps the head, and real diagnostics put the reference at the END:
a tsc resolve error ending in Widget.tsx:42:11, a Cannot-find-module naming two
paths, a JSON log line whose "file"/"line" keys come last. Measured at 709, 631 and
666 chars, head-only dropped the path from all three. neverTruncateRe could not
save them either — it anchors a source location at the very start of the line, so
leading whitespace defeats it, and every line in TestNeverTruncateAllowList puts
its token at the head where a head cut never reaches.

clipMiddle now cuts the middle and keeps both ends, which takes the allow-list off
the critical path entirely: its completeness cannot be verified, and a head+tail cut
does not depend on it. The budget still binds exactly (head + marker + tail <= n),
asserted over pathological caps and multi-byte runes.

Signed-off-by: Osher-Elhadad <[email protected]>
searchfold's per-message cost is unbounded by shape now that the command pre-gate
is gone: three folds plus three inverses, each a full pass, with no early exit.
Measured on non-foldable output — 275 us at 24 KB, 1.73 ms at 240 KB, 8.16 ms at
1.2 MB. The corpus average is fine (0.502 ms/request) but its message sizes are not
the tail either.

mayCarryPathPrefix is one byte scan for a `/` or a `:<digit>`, which is a NECESSARY
condition for all three folds: every one factors out a repeated path prefix. It
skips 12,898 messages per corpus run and TestShapeGateAdmitsEveryFoldableCapture
checks against the real captures that it excludes nothing the fold would have
changed — 333,764 tokens folded, unchanged. This is the same rule the PR states for
`format`'s not_json_shaped; the doc comment claiming the fold "exits on its first
line" was simply wrong and is corrected.

Also: linecap's position in the presets is pinned (the regression that happened was
an ordering mistake, and nothing stopped it recurring); the dead lineNum var is
deleted, its rule already living in dupKey's comment; and the "lossless trio in
every preset" claim is corrected — mcp takes format + textclean only, since it
serves JSON list endpoints with no search output to fold.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Re-verification at f19cc87 — two of three blockers closed, one HALF closed

Verified against a pristine git archive of f19cc87 in /tmp/cg-r89 (md5 of apply/apply.go matches git show f19cc87:apply/apply.go), because the shared worktree was being mutated under me mid-run. CGO_ENABLED=1 go test -race -count=1 ./... → 25 packages ok, exit 0, neither #91 flake hit; go vet ./... clean; gofmt -l . empty.

1. The line cap — CLOSED, and clipMiddle is the right shape

All seven cases from my original finding now keep the tail. Measured through rewrite with max_line_chars: 500:

case in tail token result
709-char TS error ending Widget.tsx:42:11 649 Widget.tsx:42:11 kept
631-char Cannot find module, two paths 631 boot.js kept
666-char JSON log, "file"/"line" last 666 "line":88} kept
cargo --> src/main.rs:5:9 at the tail 578 src/main.rs:5:9 kept
tab-indented Go frame, thing.go:412 +0x1d 516 thing.go:412 +0x1d kept
bare long path, no :line 591 final_file_name.go kept
error with no literal error token 603 /a/b.ts kept

Every one had neverTruncate == false, which is the point: correctness no longer rests on the allow-list. Budget binds exactly (500 runes out in all seven) and I fuzzed clipMiddle at n ∈ {0,1,2,3,4,10,11,12,13,20,500} against ASCII, é and CJK — never over budget, never invalid UTF-8, including the degenerate n < 3 and n <= len(marker) branches.

Marker-only is not reachable. A 40,000-char single line → 500 chars, 1 real content line. 200 identical lines → 6 real lines (the 3+3 protected edges). 50 long duplicates → 6. The hole the sibling PR had does not exist here.

2. The OpenAI peek — CLOSED

The provider test now precedes the peek, and br stays resp.Body unwrapped for non-Anthropic. TestOpenAISSEStreamsThrough is the right proof: the upstream blocks before its tail, so the client reading first before release can only happen if nothing beyond that chunk was consumed — and it asserts SSEStreamed == 1 && SSEBuffered == 0, so the TTFB is a genuine first-byte time in the streamed bucket rather than the time-to-last-byte I found. TestOpenAIDialectPeekWouldDrainTheWholeStream characterises the old behaviour at 100% consumed (24,814 of 24,814), which is the right way to keep the guard from looking unnecessary later.

Re-ran every Anthropic case: thinking-first, text-first, non-expand tool_use, lone expand call (still buffered), pings-first, empty message, error event, EOF mid-preamble, empty body, truncated final line, oversized preamble → buffered, and TestExpandSSELoop for sticky sseBuffered across a buffered round 1 + streamed round 2. All pass under -race -count=1.

3. The two false-cold paths — one closed, one HALF closed

I read Ctx.ColdCache through the real BodyOpts path with a probe component, rather than re-deriving the predicate in a test.

Path 1 (ttl:"1h" then bare ephemeral) — CLOSED. Same id: ttl:1h at t=0, bare at +7m and +20m → all warm. Control that never asked 1h → cold at +7m, so the sweep still works. sessionTTL's monotonic max is the right shape.

Path 2 (the alias clock) — HALF closed. The half left open is the shape the code comment and docs/design.md:305-311 actually describe.

ColdCache through BodyOpts, five scenarios, one content prefix throughout:

scenario turn 1 turn 2 turn 3
control, one id, 7 min idle warm cold ✓ —
control, one id, 4 min idle warm warm ✓ —
header → NO header (warms) → header, 2 min later warm warm COLD ✗
NO header → header (warms) → NO header, 1 min later warm warm COLD ✗
header A → header B (warms) → header A, 2 min later warm cold warm ✓

Only the two-distinct-explicit-headers case is closed. Both cases involving a header-less turn read COLD on a prefix another id touched 1–2 minutes earlier — a live prefix rewritten at depth, which is the −$708 mechanism.

Root cause. apply/apply.go:464 gates the whole thing on alias != sessionID, so a header-less turn — whose sessionID is the alias — never writes cg:seen:<alias>. The other id then finds a stale record. The comment's stated reason for the skip does not hold: aliasSeen reads before it writes and runs once per request, so calling it when alias == sessionID returns the previous turn's timestamp (what the Tracker already gives), not "the timestamp just written".

TestAliasSessionClockKeepsAWarmPrefixWarm passes because it calls aliasSeen(st, alias, base+3m) directly for its turn 2. The production path does not make that call for a turn under the alias, so the test asserts a write the code never performs — it would fail without the guard, and it also passes with a guard that does not fire for the scenario it documents. docs/design.md:310 ("a touch under either id keeps both warm") overstates it, and the same section's "three of thirteen production tenants send both id shapes" is exactly the unclosed shape.

Validated fix — drop the condition, keep the comparison:

if aliasAt := aliasSeen(st, session.Scoped(o.Tenant, "", sys, firstUser), nowMs); aliasAt > prevAt {
    prevAt = aliasAt
}

Re-ran the same five scenarios against that: both broken cases turn 3 → warm, controls unchanged (7 min single-id still cold, 4 min still warm). It is also strictly better than a pure safety fix — turn 2 of cases 1/3 now correctly reads cold, recovering legitimate cold turns the per-id blindness was hiding.

I see this exact change, plus pinning cg:ttl:/cg:seen: into DefaultPinPrefixes against LRU eviction, uncommitted in the shared worktree — that closes it and also closes a residual I had (an evicted cg:ttl: key re-opens path 1). It is not in f19cc87, so this stays open against the reviewed commit.

A third false-cold, still open in both f19cc87 and that in-flight work. sessionTTL is keyed on sessionID (apply/apply.go:476), so a 1h asked for under the explicit id is invisible to the alias id. Measured: ttl:1h under cid-1 at t=0, bare under the alias at +1m, bare under the alias at +8m → COLD, on a prefix the provider may hold for an hour. Since the alias is already computed one line above, sessionTTL(st, alias, …) fixes it — the two records should share one key, because it is the content-keyed entry both are tracking.

Also confirmed

  • cacheIsCold not widened — byte-identical to origin/main; the 60 s margin stands. Controls prove it both ways (7 min cold, 4 min warm).
  • All five doc sites corrected, and correctly: component.go:212-224 now describes the default instead of arguing against it, and TailOnlyCold reframes the asymmetry as why detection is conservative rather than why the default is off. mask.go:32, mask.go:102, docs/design.md:268 and the former "Why the default is off" section all match what ships.
  • Shared symbols untouched in behaviour: modes/tracker.go has no functional diff against origin/main; components/component.go is comment-only. ColdCache, IdleMs, cacheTTL, Tracker.TurnAt, coldMargin all keep their meaning.
  • schemaVersion still 6, dash/ untouched, no new columns.
  • Both nits fixed: lineNum deleted; TestLinecapRunsLastAmongTheOffloaders pins the preset position. The mayCarryPathPrefix shape gate is a genuine necessary condition for all three folds and measures 6.3–17× faster on non-foldable output (1.27 ms vs 8.00 ms at 1.2 MB; 13 µs vs 232 µs at 24 KB). I probed it adversarially — Windows C:\src\a.go:12: admitted and folds, paths with no line numbers admitted and fold, bare filenames in one directory correctly rejected and genuinely cannot fold. No fold lost.
  • DCO on both new commits, author Osher Elhadad, no AI attribution, no PII or secrets in the new diff.

Comment thread apply/apply.go
if aliasAt := aliasSeen(st, alias, nowMs); aliasAt > prevAt {
prevAt = aliasAt
}
}

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.

STILL OPEN — alias != sessionID skips the WRITE, so half of path 2 remains.

A header-less turn has sessionID == alias, so it never records cg:seen:<alias>. The other id then reads a stale record. Measured through the real BodyOpts path, reading Ctx.ColdCache from a probe component, one content prefix throughout:

scenario turn 1 turn 2 turn 3
control, one id, 7 min idle warm cold ✓ —
control, one id, 4 min idle warm warm ✓ —
header → NO header (warms) → header, 2 min later warm warm COLD ✗
NO header → header (warms) → NO header, 1 min later warm warm COLD ✗
header A → header B (warms) → header A, 2 min later warm cold warm ✓

Only the two-distinct-explicit-headers case is closed. The two that fail are the shape this comment and docs/design.md:305-311 describe — "an explicit header present on some turns and absent on others", the one the doc says three of thirteen production tenants send.

The stated reason for the skip does not hold: aliasSeen reads before it writes and runs once per request, so calling it when alias == sessionID returns the previous turn's timestamp — the same value the Tracker gives — not "the timestamp just written".

TestAliasSessionClockKeepsAWarmPrefixWarm passes because it calls aliasSeen(st, alias, base+3m) directly for its turn 2. Production never makes that call for a turn under the alias, so the test asserts a write the code does not perform. It would fail without the guard, and it also passes with a guard that does not fire for the scenario it documents.

Validated fix — drop the condition, keep the comparison:

if aliasAt := aliasSeen(st, session.Scoped(o.Tenant, "", sys, firstUser), nowMs); aliasAt > prevAt {
    prevAt = aliasAt
}

Both failing cases turn 3 → warm; controls unchanged. Strictly better than a pure safety fix, too: turn 2 of cases 1/3 then correctly reads cold, recovering legitimate cold turns the per-id blindness was hiding. docs/design.md:310 ("a touch under either id keeps both warm") needs to follow.

I can see this change plus cg:ttl:/cg:seen: added to DefaultPinPrefixes uncommitted in the worktree — that closes it, and the pin also closes a residual I had (an evicted cg:ttl: key re-opens path 1). Flagging it against f19cc87 because it is not in the commit under review.

…th records

The alias guard closed one direction of path 2 and left its mirror open, which is
the same -$708 mechanism the other way round.

`alias != sessionID` skipped the alias clock on exactly the header-LESS turns. So
the header-bearing turns kept the provider's content-keyed entry warm AND wrote
cg:seen:<alias>, while the header-less turn — whose own tracker id no other turn
touches — declined to read it and reported COLD. Four turns over one stable prefix
with the header present on 2 and 3: ColdCache came out [false false false TRUE]
with the entry 60 seconds old.

TestAliasSessionClockKeepsAWarmPrefixWarm passed throughout because it calls
aliasSeen directly and never reaches the call site, so it could not exercise the
condition. TestAliasClockIsReadOnHeaderlessTurnsToo drives four turns through
BodyOpts and records Ctx.ColdCache as the pipeline receives it; reverting only the
one-line fix reproduces [false false false true]. It also asserts a genuine
33-minute gap still reads cold, so the guard cannot jam the sweep permanently warm.

The comment's stated reason for the skip was wrong: aliasSeen reads BEFORE it
writes and runs once per request, so reading a key it also writes yields the
previous turn's value, never this one's.

Both cold-decision records are now pinned against LRU eviction (store.TTLPrefix,
store.SeenPrefix). They were plain TTL+LRU, and losing either makes a WARM prefix
read cold: TTLPrefix narrows a session that asked for the 1h tier back to 5m —
re-opening path 1 — and SeenPrefix drops the evidence another id touched the same
entry. Both are refreshed every turn, so the sliding TTL keeps an active session's
records; the pin is only against LRU pressure from a busy proxy.

Found by an independent verification pass over a3ccd14. The design doc claimed
"a touch under either id keeps both warm", which was true only in one direction.

Signed-off-by: Osher-Elhadad <[email protected]>
Comment thread apply/apply.go Outdated
prevAt = aliasAt
}
}
coldCache = cacheIsCold(prevAt, nowMs, sessionTTL(st, sessionID, cacheTTL(provider, body)))

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.

A THIRD false-cold, open in f19cc87 and in the in-flight work too.

sessionTTL is keyed on sessionID, so a 1h tier asked for under the explicit id is invisible to the alias id — the two guards do not compose. Measured through the real path:

t=+0s    ttl:1h          id=cid-1        ColdCache=false
t=+1m    bare ephemeral  id=<no header>  ColdCache=false
t=+8m    bare ephemeral  id=<no header>  ColdCache=true   <-- provider may hold this for 1h

The alias is already computed one line above, so sessionTTL(st, alias, cacheTTL(provider, body)) fixes it. Both records track the same content-keyed provider entry, so they should share one key — keying the idle clock on content while keying the lifetime on the session id is the same mismatch that produced path 2.

For the record, path 1 in isolation is closed and I verified it separately: same id, ttl:1h at t=0 then bare ephemeral at +7m and +20m all read warm, while a control session that never asked for 1h reads cold at +7m — so the monotonic max protects without disabling the sweep.

…th call-site tests

Two residuals from the independent verification of 2a44824, the first of which my
own alias fix created.

## The alias fix unmasked a TTL-keying hole

sessionTTL was keyed by sessionID while the idle clock had moved to a
content-derived alias. Before the alias fix that was masked: the header-less turn
had prevAt == 0 and declined itself under the "no record reads warm" rule, so the
TTL comparison was never reached. With a populated alias clock it is reached, and
the 1h grant recorded under cg:ttl:<explicit-id> is invisible to that turn — which
then judges an hour-long prefix at the 5m tier. Measured through BodyOpts, both
shapes gave ColdCache [false false TRUE]; the first PASSED on f19cc87 and FAILED on
2a44824, so this was a regression, not a pre-existing gap.

Both records are now keyed by the alias. That is the actual rule rather than two
fixes that happen to agree: the provider keys its cache on CONTENT, so every fact
we keep about that cache's lifetime has to be keyed the same way or it splits
across the ids one conversation arrives under.

## Neither guard had a test that failed without it

The two tests that were supposed to cover them call sessionTTL and aliasSeen
DIRECTLY, so ripping both guards out of the call site left them passing — the same
mistake as the alias test before this, and it is what let the residual through.
The helper tests stay (they pin the helpers' contracts) and two call-site tests are
added, using a Reformat stub that records the Ctx.ColdCache the pipeline actually
received. Verified by reverting each guard in turn with the tests in place:

  TTL keyed by sessionID (the residual)  -> FAILS
  alias clock removed entirely           -> FAILS

TestColdSweepStillFiresOnAFiveMinuteTierPrefix is the other direction: a prefix
that only ever asked for the 5m tier still reads cold after a real gap, whichever
id its turns arrive under. The guards may only move the estimate toward warm, never
disable the sweep.

## Two ceilings recorded rather than fixed

A token in the MIDDLE third of an over-long line is still lost — head-only lost it
too, so it is a ceiling, not a regression. And neverTruncateRe's `^\S+:\d+` matches
any space-free line containing `:<digit>` anywhere, so a JSON log line is exempt by
accident rather than by intent; harmless now that clipMiddle carries correctness and
the allow-list is defence in depth, but the list should not be read as precise.

Signed-off-by: Osher-Elhadad <[email protected]>
The clock guard was alias-aware and the TTL guard was single-keyed, so the pair
left its intersection open: a prefix that recorded the 1h tier under one id and then
arrived under the other looked up a key never written, fell back to the 5m tier, and
could declare cold on a prefix the provider holds for an hour. Path (a) reached
through the door path (b) opens.

The TTL record is now read under BOTH the session id and the content alias and
widened to the longer, mirroring what the clock already does. Both widenings are
monotone toward WARM, so composing them cannot make the cold test more willing to
fire — which is the property that has to hold across the pair, not just inside each
half.

Both keys, not the alias alone. My previous commit keyed both records by the alias,
and every id-flip case passes that way — but the alias moves when the agent compacts
its own context, because it is sha256(system+firstUser) and compaction rewrites the
transcript head. metaSessionKeys exists precisely because an explicit id survives
that (apply.go's own comment says so) and the derived one does not. So neither id is
reliable alone.

TestSessionTTLComposesAcrossBothIDs covers every direction, and each single-key
choice fails a different subset of it:

  pair-read (shipped)  PASSES
  sessionID only       FAILS 3 subtests (the header-flip cases)
  alias only           FAILS 1 subtest  (the compaction case)

That last row is the one my own tests could not have caught before this commit, and
it is why the compaction fixture is now in the table.

Also: TestCapTruncatesAnUnprotectedLongLine's comment still described the head-only
cut it no longer tests, and a comment misdescribing its own test is the same class
as the stale doc sites the review flagged.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad
OsherElhadad merged commit 4b1779e into main Aug 22, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Aug 22, 2026
OsherElhadad pushed a commit that referenced this pull request Aug 22, 2026
#89 (deterministic components) landed on main and added its two
cold-decision key namespaces to the same const block and to
DefaultPinPrefixes, where this branch adds extract_llm's cross-session
result namespace. Both sides are additive and both records are
cache-destructive to lose.

Resolved by keeping all three prefixes: XResultPrefix (this branch)
alongside TTLPrefix and SeenPrefix (main), with every one of them in
DefaultPinPrefixes.

Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad pushed a commit that referenced this pull request Aug 22, 2026
#86 (cache keep-alive), #90 and #89 landed on main and touched the same
four files this branch does. Every conflict was two additive changes
sharing a line; none had opposed intent, and both sides survive
everywhere.

dash/schema.go — additiveColumns holds all seven new columns (this
branch's cache_ttl, sse_buffered, ttfb_ms plus main's cache_write_1h,
keepalive, keepalive_pings, keepalive_saved_usd). schemaVersion stays 6:
a bump renames the live database aside and would discard the dashboard's
whole request history to gain a column that ALTER TABLE adds in place.

dash/store.go — the requests INSERT takes the union of both column
lists, with the placeholder count and the Exec argument list widened to
match (60 columns, 60 placeholders, 60 values, in order).

dash/overview.go — the Overview query appends both sides' aggregates and
both sides' Scan targets in the same order (47 and 47): the streaming
split, breakpoint placement and coverage counters from here, the
keep-alive saving and 1h-write total from main. Filter.where()'s
`r.keepalive = 0` exclusion is untouched, so ping rows still stay out of
COUNT(*), SUM(cache_read) and the averages.

proxy/proxy.go — the per-request defer runs both: main's keeper.record
first, on the final round's body, then this branch's SSE accounting to
the aggregator and the dashboard row. Still once per client request, not
once per upstream round.

Signed-off-by: Osher-Elhadad <[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