Skip to content

fix(collapse): cut a head/tail window whenever the output is oversized — including single-line and huge-line payloads - #138

Merged
OsherElhadad merged 2 commits into
mainfrom
fix/collapse-single-line
Sep 1, 2026
Merged

OsherElhadad merged 2 commits into
mainfrom
fix/collapse-single-line

Conversation

@amiddavid

@amiddavid amiddavid commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Headline

17 of 75 runs errored in a live 128k-band arm. Every one of them was an upstream 400
prompt is too long on an outgoing body of 2.6–14.8 MB, and no component in the pipeline
touched those bodies. collapse is documented as the last resort for an oversized tool
output, so when it declines, nothing caps the output — and it declined this entire shape by
construction.

The payoff here is avoided hard failures, not a savings line, and a reader primed by the
four-denominator convention should not go looking for one.
collapse is tail-gated and
freezes its decision, so a new cut happens only on the turn the output arrives — the cold
tail. That is exactly where a multi-megabyte tool_result lands and exactly where the 400
fires. A savings series aggregated over turns will barely move; what moves is the error
count. (Independently, a dashboard agent driving the live UI measured 113,975 → 1,824 bytes
on a novel 200 KB single-line blob where main reduced it by zero, so the cut is real and
visible in /api/components with no dash/ changes.)

The defect

collapse was line-oriented only:

lines := strings.Split(content, "\n")
if len(lines) <= cl.headLines+cl.tailLines {
    rep.Gate("too_few_lines") // few long lines; head/tail wouldn't help
    continue
}

Defaults are head_lines: 20, tail_lines: 20, so any output of 40 lines or fewer was
skipped
. For the single largest shape of tool output in practice the reasoning is inverted: a
database or HTTP API result serialised as JSON is very often ONE line, so a single-line
multi-megabyte payload fell through collapse entirely.

Review then found the same defect one level up: the fix's own gate was still in line-count
units, so an output with more than 40 lines took the line path however big those lines were.
Both are fixed here; see The gate is in bytes below.

Nothing else caught it (measured, live 128k-band arm)

component acted why not
extract 0 no_obvious_noise 16,891 — it only strips known noise patterns
cmdfilter 0 no_filter_match — only known command families
toon 21 not_uniform_object_array 233,501
dedup 774 exact duplicates only
summarize 2,349 the only real compactor — and it protects keep_last, where a FRESH oversized output sits
extract_llm — declines by design: an output exceeding the compaction model's context is left verbatim (over_model_context)
linecap 0 no_long_or_repeated_lines — neverTruncate exempts the line; see below

linecap is not a partial mitigation for this shape — it is void for it. On paper its
500-char per-line cap should rescue a huge line. It does not: neverTruncate exempts any line
matching ^\S+:\d+, and a one-line JSON body ({"items":[{"id":1,...) matches that by
accident
. Measured directly by the reviewer: in=2097191B out=2097191B acted=False gates=map[no_long_or_repeated_lines:1] neverTruncate(line)=true. Earlier revisions of this PR
described linecap as capping huge kept lines "unless neverTruncate exempts them", which
implied a conditional mitigation; for the exact payload shape this PR exists to handle the
exemption always fires. That claim has been removed from the code comment, the commit message
and this body. Filed as #151.

Consequence

  • 17 of 75 benchmark runs errored in that arm
  • 17 upstream 400s, all "prompt is too long", in 3,347 requests
  • outgoing bodies of 2.6 MB to 14.8 MB

A note on those counts, because an earlier version of this body said 16. The capture digest for
the arm (capfail-i21A.jsonl) holds 19 records: 17 × 400 prompt is too long and 2
transport-level failures (IncompleteRead, read timeout) that are not provider rejections. I
cannot reconstruct the filter that produced 16, so the number the record actually supports is
17, and that is what this body now uses.

Correction: the evidence does NOT show the fix would have prevented those failures

Earlier revisions argued: "a digest of one failing 14.8 MB body held only 4 messages, so a
single tool_result was multiple megabytes."
Review is right that this is a message count,
not a line count, and that nothing in it establishes those bodies had ≤ 40 lines — i.e.
nothing established the old too_few_lines gate was what let any of them through.

The line-count histogram asked for cannot be produced, and not because the data is
inconvenient to reach — it was never recorded.
I went back to the experiment record on the
box that still holds it (/tmp/cg-loca/capfail-i21A.jsonl, read-only). The digest schema is:

status, body_bytes, rig_seq, n_messages, system_present, error,
digest[] = { i, role, types[], tool_use[], tool_result[] }

Per message it records structure only — index, role, block-type names, tool-use ids. No
content, not even a truncated head (the writer's data[:600] truncation applies to the error
string, not the request). No per-message or per-block size of any kind, so the largest
tool_result cannot even be identified, let alone measured in lines. The only size datum is
whole-request body_bytes, which includes JSON escaping, the system prompt and 94–149 tool
definitions, and cannot be converted to a line count of anything. rig_seq — the field added
so a record could be joined back to the request the shim handed the proxy — is null in all 19
records, and no raw copy of the bodies survives anywhere on the box (proxy-i21A.log and
flap-i21A.jsonl record bytes, never lines). Verified against the writer,
/tmp/cg-loca/capture_hop.py.

So: the question "did those 17 failing bodies have ≤ 40 lines" cannot be answered from this
experiment record, in either direction.
What the record establishes is the class — 17
oversize-prompt 400s on 2.6–14.8 MB bodies with 4–57 messages — not that this specific gate was
the one that let them through. The case for the change therefore rests on the class being
real and on collapse being the only component contracted to catch it, plus the reproduced
mechanism in tests and the reviewer's live measurements — not on a demonstrated one-to-one with
those 17. Answering it properly needs a new capture that records newline counts per block;
that is worth doing before the next arm and is not something this PR can retrofit.

The design

collapse picks its window before the depth gate: by lines when a line window actually
shrinks the output, by runes when it does not. Runes rather than bytes, because the result
is spliced back into the request body verbatim and a split multibyte rune would emit invalid
UTF-8 upstream.

The gate is in BYTES, not lines, and not tokens

Having more lines than the window says nothing about their size. With a line-count gate, an
output with a multi-megabyte line inside the kept head or tail survived untouched — and worse
than being declined
, because dropping the small filler lines in the middle counts as acting,
which stamps a marker, which then makes linecap decline marker_or_kept_verbatim. Measured:

huge line in head: in=4195111B  after collapse=4194922B (events=map[])
                   after linecap=4194922B (gates=map[marker_or_kept_verbatim:1])  tokens=1570220

4 MB in, 189 bytes saved, 1.57 M tokens forwarded. The line window is now taken only when
it at least halves the output; anything else falls through to the character window:

if cl.headLines+cl.tailLines > 0 && len(lines) > cl.headLines+cl.tailLines {
    asm := /* the existing line closure, unchanged */
    if len(asm(""))*2 <= len(content) {
        return asm, false, true // the line window really cut it: byte-identical, as before
    }
    // it kept most of the bytes (a giant kept line) -> fall through to the rune window
}

Bytes deliberately, not tokens. maxTokens comes from resolveBudget(..., c.CtxWindow),
CtxWindow can resolve differently mid-session (model swap, refreshed modelinfo), and
repairLostFreeze re-derives at depth. A token gate could therefore classify the same content
line-window on one turn and character-window on the next and emit different bytes — trading
a savings bug for a cache bug, in a component whose collapsed form is frozen and replayed
inside the cached prefix. The byte form depends only on the content and
head_lines/tail_lines, so it is replay-safe unconditionally. Both forms classify every
fixture identically, including all four in TestCollapseLineWindowIsByteIdentical, which is
what preserves byte-identity for everything the line window handles today.

Where the character budget comes from — no new knob

It is the component's own token threshold expressed in characters:

  • max_tokens, resolved through resolveBudget (so max_frac × the model window still wins),
    × 4 — the same chars/token ratio internal/tokens.Count itself falls back to when the
    BPE codec is unavailable, so the two places in the tree that relate bytes to tokens agree;
  • never seeded above the content: min(maxTokens*collapseCharsPerToken, len(r)-1). chars/4
    overestimates on dense JSON (~2.5 chars/token), and the bail-out was tested against that
    un-measured seed, so content genuinely oversized in tokens was still shorter in runes
    than its char budget and was declined outright as too_few_lines_and_chars. That hole was 55%
    wide, and widest in a shipped preset — codesafe sets max_tokens: 3000, so one-line JSON
    from 3,006 to 4,491 tokens was oversized and left entirely uncut, with no test at 3000.
    marker_no_win already protects the downside of seeding low;
  • split between head and tail in the head_lines:tail_lines ratio, so those knobs keep
    meaning what they say on both paths;
  • then measured and tightened. On the 3 MB JSON fixture, unmeasured chars/4 lands at
    3,056 tokens against a 2,000-token threshold. The fit loop is bounded at 3 passes and only
    ever tightens;
  • floored at 200 characters, so a max_tokens: 0 cannot collapse an output to a bare marker
    with no cue about what to expand. head_lines: 0, tail_lines: 0 now routes here for the same
    reason — it used to reach the line path (1 > 0+0) and emit a bare 90-byte marker.

The 200-char floor and the 3-pass bound are now documented (they were not), because they
mean a very small max_tokens does not deliver what it says: max_tokens: 100 measures ~118
tokens out. Two causes, both now stated in the code rather than implied away — the floor returns
before any measurement, and got measures asm(""), an empty marker, while the shipped text
carries the ~15 tokens of <<cg:HASH>> [full output: ...]. tryMark's never-worse guard
measures the real marker and declines rather than growing a message, which is what makes the
residue harmless.

Legality is inherited, not re-implemented. The character path goes through exactly the same
shared helpers as the line path — tryMark/commitMark (reversible stash + <<cg:HASH>>
marker, and the marker-inclusive never-worse guard), skipReduce (idempotence), freeze
(replay at depth). The only new code is the window arithmetic.

What I rejected

  • Making linecap own it by loosening neverTruncate. Its exemptions exist because a
    600-char stack frame or compiler diagnostic is exactly the line a model needs whole, and the
    file carries measured evidence against narrowing the pattern. collapse is the component
    whose stated contract is "the last resort for anything still oversized" — a hole in the last
    resort belongs to the last resort. (fix(linecap): neverTruncateRe's ^\S+:\d+ exempts one-line JSON, so the cap never fires on it #151/linecap: neverTruncate's ^\S+:\d+ exempts single-line JSON by accident (analysed, deliberately not fixed) #140.)
  • A structure-aware JSON cut (parse, keep the first N array elements). Strictly better
    output when it applies, but it is a new component's worth of work with a parse cost on every
    megabyte-scale payload, it fails on truncated/non-JSON bodies, and it is not what a
    content-agnostic fallback is for. A jsoncut component can be layered ahead of collapse
    later.
  • A token-based fall-through gate. Rejected on cache-safety grounds; see above.
  • Grapheme-safety. With decomposed content the kept tail can begin with an orphaned
    combining mark. Cosmetic, and the output stays valid UTF-8, which is the property that matters
    for splicing into a request body. Not worth a segmentation dependency here.

Earlier revisions rejected "applying the character window as a second stage after the line
window"
on byte-identity grounds. That was the wrong call and review was right to block it: the
byte gate gets the same coverage without changing the bytes for anything the line window
already cut, because the halving test is passed by every shape it handles today by orders of
magnitude. The ponytail note recording that rejection is gone, along with the residual gap it
described.

The counters

too_few_lines is gone, not renamed. Most of what it counted is now handled, and
exporting handled work under a decline's name yields a series that falls as the component works
better — the distinction components/component.go's Gate/Event split exists for. Its
population is now:

  • char_window event — the character path acted;
  • too_few_lines_and_chars gate — the only genuine decline left: no window that shrinks the
    output, i.e. no usable line window and fewer characters than the character window's floor.

Byte-identical layouts, both paths

TestCollapseLineWindowIsByteIdentical asserts the exact expected string for four
multi-line fixtures. TestCollapseCharWindowIsByteIdentical is the equivalent for the character
path, which review correctly identified as missing: its output is frozen and replayed at depth
in exactly the same way, so a changed layout re-anchors every cached position after it in every
live session mid-flight. Four fixtures (one-line JSON, multibyte, huge line in the kept head,
huge line in the kept tail), expectation written out as a literal format string rather than
captured from window(), with the head/tail split pinned to 100/100 by construction (at
max_tokens: 50 the budget floors, so runeWindow returns at pass 0 and there is no
budget-dependent arithmetic in the expectation). Each case also asserts char_window fired, so
the comparison cannot pass vacuously via the line path.

TestCollapseCharWindowAtExactlyTheLineWindowSize pins the boundary this PR moves from the
other side: at exactly head_lines+tail_lines lines the line window would omit zero lines, so
it must not be taken.

Mutation results

Standing rule: for each new test, revert the code it covers and confirm the test FAILS.
Review's separate point is taken — vacuity of an assertion is weaker than catching a plausible
wrong implementation — so this round is stated as mutation results, with the mutants review
found surviving.

8 mutations, 7 caught, 1 equivalent.

mutation outcome failure
remove the byte gate (revert to the line-COUNT gate) CAUGHT huge line in head: character window is not byte-identical
revert the budget clamp to maxTokens*4 CAUGHT max_tokens 2000: 2061-token single-line output left uncut; gates map[too_few_lines_and_chars:1]
flip the too-few-lines gate to >= EQUIVALENT see below
off-by-one head slice r[:h+1] CAUGHT one line json: character window is not byte-identical
off-by-one omitted count CAUGHT huge line in tail: character window is not byte-identical
byte slicing instead of rune slicing CAUGHT character window split a multibyte rune
remove the zero-line-window routing CAUGHT a 72000-byte output collapsed to 90 bytes — a bare marker with no cue
revert the newCollapse negative clamp CAUGHT negative line knobs must be clamped to 0, got -10/-5

On the >= survivor — review's worst one, and it survives now for a different reason than
before. Under the byte gate it is an equivalent mutant, not a wrong implementation: at
exactly head_lines+tail_lines lines the mutant does take the line path and compute
omitted = 0, but asm("") is then the whole content plus ~24 characters, which fails the
halving test and falls through to the character window anyway. The behaviour the mutation used
to produce — whole content plus a marker, marker_no_win, a 40-line multi-megabyte output
sailing through a green suite — can no longer be expressed by that edit.
TestCollapseCharWindowAtExactlyTheLineWindowSize pins the boundary and is non-vacuous (the
byte-gate mutation fails it), but no test can distinguish equivalent code, and killing the
behaviour is a stronger outcome than catching the mutant. The other two survivors are caught.

The earlier round's 11 vacuity checks stand as reported; nothing in them is retracted.

Follow-ups fixed here

  • head_lines: 0, tail_lines: 0 reached the line path and produced a bare marker with no
    content cue — 2,001 lines became 90 bytes, precisely what collapseMinWindowChars exists to
    prevent. Routed to the character window.
  • Negative head_lines/tail_lines panicked on the line path (1 > -10 sends even a
    one-liner there, then lines[:-10] slices out of range), which also made splitWindow's
    max(...) guard unreachable for the config it looked like it defended. Clamped once in
    newCollapse, covering both paths; splitWindow now only handles zero.
  • The runeWindow doc comment's claim that "an output above max_tokens comes back at or under
    it" is softened to the truth, with both causes named.
  • The 200-char floor, the 3-pass bound, the seed clamp and the negative-knob clamp are
    documented in docs/components/collapse.md; docs/components.md's "too small for either
    window to shrink it" now describes the gate rather than the intent.
  • []rune on a 14.8 MB payload allocates ~59 MB per oversized message per turn, on top of the
    strings.Split above it. Recorded as a ponytail with the measured rate that makes it
    tolerable for now (17 bodies in 3,347 requests).
  • Dashboard, from the follow-up review: char_window rendered under a column header reading
    "Why declined" on a row that acted. The merged cell is deliberate (dash/event.go folded
    events in to fix an empty-cell bug) and is left merged; the header is now "Why / what
    happened"
    in dash/ui/index.html, dash/ui/app.js and docs/dashboard.md. collapse is the
    first component to surface an event there, which is why it was never revisited.

Not fixed here, filed instead

One review item that does not apply

Review's follow-up asks to fix a vacuous combining case using "éà" (which compiles to
precomposed runes in Go source). There is no combining case in this suite — the rune-safety
test is TestCollapseCharWindowKeepsValidUTF8, which uses CJK, where the multibyte property is
real and the byte-slicing mutation is caught. Nothing to fix; flagging it rather than silently
skipping it in case the note came from a different branch.

Build and test

Eval box, Go 1.26.4, CGO_ENABLED=1: gofmt clean on every touched file, go build ./...
clean, mkdocs build --strict clean, full go test ./... green except
dash/TestSpendSurvivesRowEviction, which fails identically on unmodified main (#157).

One correction to the brief

The brief quoted collapse.go without the depth gate, the freeze/replay logic, or the
rep.Gate("non_text_blocks") / below_max_tokens counters. origin/main has all of them, so
the fix had to slot into TailOnlyCold + freeze + repairLostFreeze. The window choice is
placed before the depth gate on purpose, so a message with no usable window is not
miscounted as a cache decline.

Separately, docs/components/collapse.md documents cold_cache as defaulting to false while
coldCacheField() defaults it to true (and docs/components.md says true). Pre-existing
inconsistency, unrelated, left alone.

@OsherElhadad

Copy link
Copy Markdown
Collaborator

Reviewed against main e88f5d8 in a clean worktree, including a live proxy under
--preset codesafe. go build ./... clean, go test ./... → 27 packages ok / zero FAIL,
mkdocs build --strict clean. Docs are accurate against the code — every claim in
docs/components/collapse.md checked against collapse.go (too_few_lines_and_chars:197,
char_window:142, collapseCharsPerToken=4:162, rune-based :214, tightening-only :238),
and retiring the old gate name rather than reusing it was the right instinct.

The character window itself is correct on the properties most likely to be wrong. Verified
live, not read:

  • Slices runes, not bytes (r := []rune(content)). Emoji, CJK, 4-byte and mixed content all
    stay valid UTF-8, including a 6-offset sweep walking the cut through every byte of a 3-byte
    rune. Mutating it to byte slicing is caught by the new suite.
  • Reversible. GET /expand?id= byte-matched both fixtures (204891/204891, 180000/180000),
    and cross-session access correctly 404s.
  • Deterministic. Byte-identical across 3 turns in one session and 2 fresh sessions (same md5).
  • Never-worse holds in tokens. tryMark refuses before any side effect; 201–380 B inputs are
    correctly declined marker_no_win, so the smallest input actually shrunk is ~400 B.
  • Skip-if-already-marked is honoured structurally — skipReduce at :108 precedes
    window(), so one call site covers both paths.

9 of 12 mutations I wrote are caught. This is careful work. The problem is that the gate is in
the wrong units.

1. Blocking — the fix is gated on LINE COUNT, not size, so the motivating shape survives above 40 lines

collapse.go:183 takes the line path whenever there are more than head_lines+tail_lines
lines, regardless of how big those lines are. A multi-megabyte line inside the kept head or tail
window survives untouched — and because collapse still "acts" (it drops the small filler lines
in the middle) it stamps a marker, which then makes linecap decline:

huge line in head: in=4195111B  after collapse=4194922B (events=map[])
                   after linecap=4194922B (gates=map[marker_or_kept_verbatim:1])  tokens=1570220
huge line in tail: in=4195110B  after collapse=4194921B (events=map[])

4 MB in, 189 bytes saved, 1.57 M tokens forwarded. events is empty, so the char window never
engaged.

And linecap could not have rescued it even without the marker. The commit's ponytail note says
"linecap, which runs after, caps those lines unless neverTruncate exempts them" — but the commit
also correctly observes that ^\S+:\d+ matches {"items":[{"id":1,... by accident, so for the
exact payload shape this PR exists to handle, neverTruncate always exempts it:

linecap alone: in=2097191B out=2097191B acted=False gates=map[no_long_or_repeated_lines:1] neverTruncate(line)=true

The named mitigation is void, not conditional. (Filed separately as #151, since it is
pre-existing.)

Compounding this: the evidence does not establish the fix covers the measured failures. The
commit cites "A digest of one failing 14.8 MB body held only 4 messages, so a single tool_result
was multiple megabytes"
— that is a message count, not a line count. Nothing in the PR
shows the 16 failing bodies had ≤40 lines, so nothing shows this change would have prevented any
of them. A line-count histogram of those 16 bodies converts this from plausible to demonstrated,
and it looks like data you already have.

Fix — move the gate to size. Use the byte-based form, not a token-based one:

if len(lines) > cl.headLines+cl.tailLines {
    asm := /* existing line closure, unchanged */
    if len(asm(""))*2 <= len(content) {
        return asm, false, true   // line window really cut it: byte-identical, as today
    }
    // line window kept most of the bytes (a giant kept line) -> fall through to runeWindow
}

A token-based gate reading maxTokens would not be replay-safe: maxTokens comes from
resolveBudget(..., c.CtxWindow), CtxWindow can change mid-session, and repairLostFreeze
(:126) re-derives at depth — which collapse.go:119-125 already warns about. Under max_frac
that could flip line→char for the same content and emit different bytes, trading a savings bug for
a cache bug. The byte form depends only on content plus head_lines/tail_lines, so it is
unconditionally replay-safe. Both forms classify all six cases identically, including the four
fixtures from TestCollapseLineWindowIsByteIdentical, which is what preserves byte-identity for
everything the line window handles today.

If you would rather not change the gate, the alternative is to amend the PR body: state the
residual hole plainly, drop the linecap claim, and show the histogram.

2. Wanted before merge — a units mismatch declines a 55%-wide oversize band, widest in a shipped preset

collapse.go:215 seeds budget := maxTokens * collapseCharsPerToken (×4) and :221 tests the
bail-out against that un-measured seed, before the fit loop runs. Dense JSON tokenizes at
~2.5 chars/token, so content genuinely oversized in tokens is still shorter in runes than a
4-chars/token budget and is declined outright:

runes=6015 tokens=2304 oversized=true acted=false gates=map[too_few_lines_and_chars:1]
runes=7958 tokens=3033 oversized=true acted=false gates=map[too_few_lines_and_chars:1]
runes=8180 tokens=3114 oversized=true acted=true  events=map[char_window:1]

max_tokens=2000: one-line JSON from 2007 to 3033 tokens is OVERSIZED and still UNCUT
max_tokens=3000: one-line JSON from 3006 to 4491 tokens is OVERSIZED and still UNCUT

codesafe sets collapse.max_tokens: 3000, so the shipped deterministic preset has the wider
3006–4491-token hole
, and no test covers 3000. Since collapse is the last resort, a decline
means nothing caps the output — and the gate name makes it look on /stats like a legitimately
unhandleable payload when a 200-char window would have cut it 96%.

One line; marker_no_win already protects the downside:

-	budget := maxTokens * collapseCharsPerToken
+	// Never seed above the content: chars/4 overestimates on dense JSON, and bailing out on
+	// the un-measured seed declines content the fit loop would have cut.
+	budget := min(maxTokens*collapseCharsPerToken, len(r)-1)

3. Wanted before merge — no byte-exact assertion on the char-window layout

Three of my twelve mutations survived all 8 new tests, and they are the same gap:

MUT flip too-few-lines gate to >=:   *** SURVIVED ***
MUT off-by-one head slice (r[:h+1]): *** SURVIVED ***
MUT off-by-one omitted count:        *** SURVIVED ***

The char path's output is frozen and replayed at depth exactly like the line path, and the PR
argues at :177-180 why that matters — a changed layout "re-anchors every cached position after
it in every live session mid-flight"
. The line path got
TestCollapseLineWindowIsByteIdentical on that basis; the char path got no equivalent.

The > → >= survivor is the worst: at exactly 40 lines the mutant takes the line path, computes
omitted = 0, emits the whole content plus a marker, fails tryMark and declines
marker_no_win. A 40-line multi-MB output would silently sail through — the precise boundary this
PR moves — with a green suite.

TestCollapseCharWindowIsByteIdentical mirroring the line-path test's construction (spell the
expected string out rather than capture it), plus one len(lines) == headLines+tailLines case
asserting char_window fires, pins all three.

(Note: the PR body's "11 mutations, 11 required failures, 0 vacuous" is about vacuity of the new
assertions — a weaker and different property than catching a plausible wrong implementation. Both
can be true; I am not disputing that table.)

Follow-ups

  • collapse.go:210-212 claims "an output above max_tokens comes back at or under it". False for
    small budgets: max_tokens=100 → 118 tokens out. Two causes — the 200-char floor returns at
    :229 before any measurement, and got := TextTokens(asm("")) measures an empty marker
    while the shipped text carries ~15 tokens of <<cg:HASH>> [full output: ...]. Only the
    incidental 10% margin absorbs that. Soften the comment or measure asm(token).
  • head_lines: 0, tail_lines: 0 → a 64 KB output becomes 87 bytes, a bare marker with no content
    cue, which is exactly what collapseMinWindowChars exists to prevent — reached via the line
    path (1 > 0+0), which the new floor does not guard.
  • Negative head_lines/tail_lines panic on the line path (1 > -10 sends even a one-liner
    there), so splitWindow's new max(cl.headLines, 0) at :251 is unreachable for the config it
    appears to defend. Pre-existing and fail-open contains it, but clamping once in newCollapse
    covers both paths and makes the new guard mean what it reads as.
  • docs/components.md:284 — "too small for either window to shrink it" describes intent, not the
    gate (see item 2). The 200-char floor and 3-pass bound are also undocumented, so max_tokens: 50
    silently yields a window the user did not ask for.
  • Rune-safe but not grapheme-safe: with decomposed content the kept tail can start with an orphaned
    combining mark. Cosmetic (still valid UTF-8). Related: the new test's combining case is
    vacuous — Go source "éà" compiles to precomposed single runes; use "é" to cover it.
  • collapse.go:214 — []rune on a 14.8 MB payload allocates ~59 MB per oversized message per
    turn, on top of the strings.Split at :182. Worth a ponytail: note given the PR's own
    motivating sizes.

Two framing suggestions for the PR body

Neither is stated, and both make the case stronger:

  1. Say plainly that the payoff is avoided hard failures, not a savings line. collapse is
    tail-gated and freezes its decision, so a new char-window cut only happens on the turn the
    output arrives — the cold tail, which is exactly where a multi-MB tool_result lands and where
    the 400 fires. A reader primed by the four-denominator convention will look for a savings
    number and read its absence as a weak result.
  2. Lead with 17 of 75 errored runs. That is the honest headline and it is stronger than any
    token count.

Generalization

The class is evidenced, not speculative (16 upstream 400 prompt is too long in 3,347 requests,
bodies 2.6–14.8 MB). It generalizes cleanly across agents and dialects because it is
content-shaped rather than agent-shaped — confirmed by driving the OpenAI dialect
(role:"tool") through /compact and watching the char window fire (char_window: 2). No sibling
component shares the too-few-lines hole (mask/failed_run are whole-message, smartcrush works
on []json.RawMessage, extract has no window, the DSL's truncate_lines_at is rune-safe), so
collapse is the right file — the fix is just bolted to the cutting mechanism rather than to the
gate that causes the problem.

Verdict

Needs changes. Item 1 is the blocker and it is a scope/evidence problem rather than a defect
in the code that was written; items 2 and 3 are each ~1 line and ~1 test. The character window is
correct where it counts.

@OsherElhadad

Copy link
Copy Markdown
Collaborator

Follow-up: a dashboard agent drove the live UI (headless Chromium, real proxy, real traffic) against
this branch and main. This PR is a real measured win, and it surfaces in the dashboard with zero
dash/ changes
— but two rendering details are worth a line each.

First, the confirmation

Same novel high-entropy 200KB single-line blob through both builds:

main       before=113975  after=113975  saved_unique=0        (nothing acted — linecap's neverTruncate didn't catch it either)
integrated before=113975  after=1824    saved_unique=112151

So the PR's "nothing else catches this shape" claim holds on independent traffic, and the
linecap-cannot-help half of my earlier finding 1 is confirmed from the other direction. The
component table picked it up automatically — runs 2 acted 2 100.0% unique 170k gross 170k overcount 1.0× 24ms — and the new char_window event reached both /api/components and the request drawer
with no dashboard code changes at all. That is a good sign about the event/gate split you chose.

The inline diff also renders and wraps correctly: longest text node 4,016 chars, no page overflow, 0
JS console errors, all four view modes, and the …(196831 characters omitted) marker present. I went
looking for a silent-truncation bug and there isn't one — before is honestly capped with
…[+196009 bytes].

1. LOW — char_window renders under a column header that says "Why declined", on a row that acted

dash/ui/index.html:481 and dash/ui/app.js:3297 (el('th',{text:'Why declined'})).

Your data model is right: /api/components keeps events:{char_window:1} separate from gates:{},
and the commit message is explicit about why — "Counted as an EVENT, not a gate… exporting 'handled'
under the old decline name would make the series fall as the component works better."
The UI then
renders both into one cell under a decline-only header:

request drawer, row 8:  collapse  offload  112k  112k  15ms  [acted]   char_window 1
                                                                        ^ column header: "WHY DECLINED"

dash/event.go:417 records that events were folded into the gates cell to fix an empty-cell bug — so
the merge is deliberate and correct; the header was just never revisited. Fix is one string in two
files: "Why / what happened". Do not un-merge the cell.

Not your PR's defect, but your PR is what makes it visible, so it seems worth raising here rather
than in isolation.

2. MEDIUM (pre-existing, and this PR makes it worse) — the first savings bar now reads 158%

main       pct=115.42  available=True
integrated pct=158.17  available=True

Rendered as a bar labelled 158.17% with subtitle 409k ÷ 259k tokens, in a track that is 100% by
construction — so the bar is pinned full while the number contradicts it, as the first figure on
the page.

The arithmetic is intended (docs/dashboard.md:80: gross-over-attempted, because attempted_tokens
is re-counted every turn). The presentation is not: a >100% figure under a heading "Savings
percentage" reads as a bug to anyone who has not read that paragraph. Your PR pushes it from 115% to
158%
precisely because collapse now catches enormous blobs — it gets worse as the product gets
better.

It is a ratio, not a share. Render 1.58× with the track at min(1, …), or drop the track and show
the bare figure with its divisor. Don't touch the arithmetic. Raising it here because this PR is what
moves it past the point where a reader can charitably ignore it.

Neither item changes my verdict — the blocking items remain the line-count gate (finding 1), the
max_tokens × 4 seed (finding 2), and the missing byte-exact char-window assertion (finding 3).

amiddavid added a commit that referenced this pull request Sep 1, 2026
…rsize band

Review of #138 found the character window itself correct on the properties most likely
to be wrong (rune-safe across a 6-offset sweep through a 3-byte rune, byte-exact expand
recovery, deterministic across sessions, never-worse in tokens) but the GATE in the wrong
units. Three fixes, all in that gate.

1. The window was chosen on the LINE COUNT, so an output with more than
   head_lines+tail_lines lines took the line path however big those lines were. A
   multi-megabyte line inside the kept head or tail survived untouched - and worse than
   being declined, because dropping the small filler lines in the middle counts as acting
   and stamps a marker, which then makes linecap decline marker_or_kept_verbatim.
   Measured by the reviewer: 4,195,111 B in, 4,194,922 B out, 189 bytes saved, 1.57 M
   tokens forwarded, events empty. The line window is now taken only when it at least
   HALVES the output; anything else falls through to the character window.

   The test is in bytes, not tokens, deliberately. maxTokens comes from
   resolveBudget(..., c.CtxWindow), CtxWindow can resolve differently mid-session, and
   repairLostFreeze re-derives at depth - so a token gate could classify the same content
   line-window on one turn and character-window on the next and emit different bytes,
   trading a savings bug for a cache bug. Bytes depend only on the content and
   head_lines/tail_lines, so the classification is replay-safe. Both forms classify every
   fixture identically, which is what keeps the line path byte-identical.

   The ponytail note this replaces was doubly wrong: it named the shape as out of scope
   when it is the same defect, and it named linecap as the mitigation when linecap's
   neverTruncate exempts `^\S+:\d+` and one-line JSON matches that by accident (#151),
   so the mitigation was void rather than conditional.

2. runeWindow seeded budget at maxTokens*4 and tested the bail-out against that
   UN-measured seed, before the fit loop ran. chars/4 overestimates on dense JSON
   (~2.5 chars/token), so content genuinely oversized in TOKENS was still shorter in
   runes than its char budget and was declined outright as too_few_lines_and_chars. At
   max_tokens 3000 - what the shipped codesafe preset sets - one-line JSON from 3,006 to
   4,491 tokens was oversized and left entirely uncut, and no test covered 3000. Seeding
   at min(maxTokens*collapseCharsPerToken, len(r)-1) closes it; marker_no_win already
   protects the downside of seeding low.

3. The character path had no byte-exact layout assertion, so three of the reviewer's
   twelve mutations survived all eight new tests. Its output is frozen and replayed at
   depth exactly like the line path's, which is why the line path got
   TestCollapseLineWindowIsByteIdentical; TestCollapseCharWindowIsByteIdentical is the
   equivalent, with the expectation written out as a literal format string rather than
   captured from window(), over four fixtures including both huge-kept-line shapes.

Follow-ups from the same review, fixed here:

- head_lines: 0, tail_lines: 0 reached the LINE path (`1 > 0+0`) and produced a bare
  marker with no content cue - 2,001 lines of payload became 90 bytes, which is exactly
  what collapseMinWindowChars exists to prevent. With no line window configured, the
  character window (even split, floored) is the only sensible reading of "cap this".
- Negative head_lines/tail_lines panicked on the line path (`1 > -10` sends even a
  one-liner there, then lines[:-10] slices out of range), which also made splitWindow's
  own max(...) guard unreachable for the config it looked like it defended. Clamped once
  in newCollapse, which covers both paths; splitWindow now only has to handle zero.
- The runeWindow doc claimed "an output above max_tokens comes back at or under it". It
  does not for small budgets: the 200-char floor returns before any measurement, and
  `got` measures asm("") - an EMPTY marker - while the shipped text carries the ~15
  tokens of the marker and its hint. Softened to say so, and to name tryMark's never-worse
  guard as what makes the residue harmless.
- The 200-char floor and the 3-pass bound were undocumented, so max_tokens: 50 silently
  yielded a window the user did not ask for. Both documented, with the seed clamp and the
  negative-knob clamp, in docs/components/collapse.md.
- []rune on a 14.8 MB payload allocates ~59 MB per oversized message per turn, on top of
  the strings.Split above it. Recorded as a ponytail note with the measured rate that
  makes it tolerable for now (16 bodies in 3,347 requests).

Declined, with reasons: the reviewer's "combining" follow-up does not apply - there is no
`combining` case in the new suite to fix (TestCollapseCharWindowKeepsValidUTF8 uses CJK,
where the rune property is real). Grapheme-safety is left alone: an orphaned combining
mark is cosmetic and the output stays valid UTF-8, which is the property that matters for
splicing into a request body.

Each new test was verified by reverting the code it covers on the eval box (Go 1.26.4,
CGO_ENABLED=1). 8 mutations, 7 caught:

  M1 remove the byte gate (revert to the line-COUNT gate)  CAUGHT
     collapse_charwindow_test.go:320: huge line in head: character window is not
     byte-identical
  M2 revert the budget clamp to maxTokens*4                CAUGHT
     :439: max_tokens 2000: 2061-token single-line output left uncut; gates
     map[too_few_lines_and_chars:1]
  M3 flip the too-few-lines gate to >=                     EQUIVALENT (see below)
  M4 off-by-one head slice r[:h+1]                         CAUGHT
     :320: one line json: character window is not byte-identical
  M5 off-by-one omitted count                              CAUGHT
     :320: huge line in tail: character window is not byte-identical
  M6 byte slicing instead of runes                         CAUGHT
     :219: character window split a multibyte rune
  M7 remove the zero-line-window routing                   CAUGHT
     :467: a 72000-byte output collapsed to 90 bytes - a bare marker with no cue
  M8 revert the newCollapse negative clamp                 CAUGHT
     :484: negative line knobs must be clamped to 0, got -10/-5

M3 is the reviewer's worst survivor, and it survives now because the byte gate makes it an
EQUIVALENT mutant rather than a wrong implementation: at exactly head_lines+tail_lines
lines the mutant does take the line path and compute omitted = 0, but asm("") is then the
whole content plus ~24 characters, which fails the halving test and falls through to the
character window anyway. The behaviour the mutation used to produce - whole content plus a
marker, marker_no_win, a 40-line multi-megabyte output sailing through - can no longer be
expressed by that edit. TestCollapseCharWindowAtExactlyTheLineWindowSize pins the boundary
from the other side and is non-vacuous (M1 fails it), but no test can distinguish
equivalent code, and that is a stronger outcome than catching the mutant.

go build ./... clean, gofmt clean, mkdocs build --strict clean, go test ./... green except
dash/TestSpendSurvivesRowEviction, which fails identically on unmodified main (e88f5d8):
its fixture backdates 10 hours and today is the 1st, so 3 of 10 sessions land in the
previous month. Filed as #157. The dashboard's 158% savings bar is #158.

Assisted-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid amiddavid changed the title fix(collapse): cut a character window when there are too few lines to cut fix(collapse): cut a head/tail window whenever the output is oversized — including single-line and huge-line payloads Sep 1, 2026
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Thanks — the gate/cutting distinction was the right diagnosis, and finding a second copy of the
same units mistake one level up from the one I fixed is the review I needed. All three blocking
items are addressed in 4ce7c33, plus every follow-up except two I filed instead. Details, the
mutation results, and the histogram outcome below.

1. Blocking — the gate is now in BYTES

Taken as proposed, in the byte form and for the reason you gave:

if cl.headLines+cl.tailLines > 0 && len(lines) > cl.headLines+cl.tailLines {
    asm := /* the existing line closure, unchanged */
    if len(asm(""))*2 <= len(content) {
        return asm, false, true // the line window really cut it: byte-identical, as before
    }
    // it kept most of the bytes (a giant kept line) -> fall through to the rune window
}

The cache argument against a token gate is decisive and I have written it into the code rather
than just the PR, so the next person to reach for maxTokens here sees why not: resolveBudget

  • a mid-session CtxWindow change + repairLostFreeze re-deriving at depth means a token gate
    could classify the same content differently on a later turn and emit different bytes. Trading a
    savings bug for a cache bug is a bad trade and the byte form costs nothing to get right.

The ponytail note that declared this shape out of scope is gone, and so is its linecap
claim. You are right that it was void rather than conditional — neverTruncate(line)=true on
exactly the payload shape the component exists for. Removed from the code comment, the commit
message and the PR body, with #151 referenced where the mechanism is described.

Two things I did beyond the proposal, both small:

  • I gated the line branch on headLines+tailLines > 0 as well, which folds in the
    head_lines: 0, tail_lines: 0 follow-up: that config used to reach the line path via
    1 > 0+0 and emit a bare 90-byte marker.
  • TestCollapseCutsAHugeLineInsideTheLineWindow reproduces both of your fixtures (huge line in
    head, huge line in tail) and asserts the output at least halves, stays under max_tokens,
    fires char_window, and is still byte-recoverable from the stash.

The histogram — it cannot be produced, and the reason is worse than inconvenience

You were right that the "4 messages" line is a message count doing a line count's job, and right
that it looked like data I already had. It is not. I went back to capfail-i21A.jsonl on the old
box (read-only; nothing touched). The digest schema is:

status, body_bytes, rig_seq, n_messages, system_present, error,
digest[] = { i, role, types[], tool_use[], tool_result[] }

Per message that is structure only — index, role, block-type names, tool-use ids. No content,
not even a truncated head (capture_hop.py's data[:600] truncation applies to the error
string, not the request body, which is discarded after len(raw)). No per-message or per-block
size of any kind, so the largest tool_result cannot even be identified, let alone counted in
lines. The only size datum is whole-request body_bytes, which includes JSON escaping, the
system prompt and 94–149 tool definitions. rig_seq — the field that exists precisely so a
record can be joined back to the request the shim handed the proxy — is null in all records,
and no raw copy survives (proxy-i21A.log and flap-i21A.jsonl record bytes, never lines).

So I have taken your alternative for the evidence half and stated it plainly in the PR body
rather than leaving the inference standing: the question cannot be answered from this
experiment record, in either direction.
The case rests on the class being real and collapse
being the only component contracted to catch it, plus the reproduced mechanism in tests and your
live measurements — not on a demonstrated one-to-one with those failures.

One correction that came out of the same dig, in your favour and against my own body: the digest
holds 19 records — 17 × 400 prompt is too long plus 2 transport-level failures
(IncompleteRead, read timeout) that are not provider rejections. Both of us have been writing
16. I cannot reconstruct that filter, so the PR now says 17 and names the 2 non-400s. And the
capture needs a newline count per block before the next arm; that is a rig change, not something
this PR can retrofit.

2. The oversize band — taken as written

budget := min(maxTokens*collapseCharsPerToken, len(r)-1)

TestCollapseCutsDenseJSONInTheOversizeBand covers max_tokens 2000 and 3000, sizing each
fixture into the band programmatically and asserting the preconditions (over the threshold in
tokens, under it in chars/4 runes) so it cannot pass vacuously if the band ever moves. Reverting
the clamp fails it with 2061-token single-line output left uncut; gates map[too_few_lines_and_chars:1].

Your point about the gate name making a decline look legitimate on /stats is the part that
stuck with me — that is the failure mode where nobody ever finds out.

3. Byte-exact char-window assertion — added, and two of your three survivors are caught

TestCollapseCharWindowIsByteIdentical, mirroring the line-path test: expectation spelled out as
a literal format string, not captured from window(), over four fixtures (one-line JSON,
multibyte, huge line in the kept head, huge line in the kept tail). The head/tail split is
pinned to 100/100 by construction — at max_tokens: 50 the budget floors at
collapseMinWindowChars, so runeWindow returns at pass 0 and there is no budget-dependent
arithmetic hiding in the expectation. Every case also asserts char_window fired, so the
comparison cannot pass vacuously through the line path.

8 mutations, 7 caught, 1 equivalent:

mutation outcome failure
remove the byte gate (revert to the line-COUNT gate) CAUGHT huge line in head: character window is not byte-identical
revert the budget clamp to maxTokens*4 CAUGHT max_tokens 2000: 2061-token single-line output left uncut
flip the too-few-lines gate to >= EQUIVALENT see below
off-by-one head slice r[:h+1] CAUGHT one line json: character window is not byte-identical
off-by-one omitted count CAUGHT huge line in tail: character window is not byte-identical
byte slicing instead of rune slicing CAUGHT character window split a multibyte rune
remove the zero-line-window routing CAUGHT a 72000-byte output collapsed to 90 bytes — a bare marker with no cue
revert the newCollapse negative clamp CAUGHT negative line knobs must be clamped to 0, got -10/-5

On the >= mutant — your worst survivor — it still survives, and I want to be precise about
why rather than claim a kill.
Under the byte gate it is an equivalent mutant, not a wrong
implementation. At exactly head_lines+tail_lines lines the mutant does take the line path and
compute omitted = 0, but asm("") is then the whole content plus ~24 characters, which fails
the halving test and falls through to the character window anyway. I verified this rather than
argued it: with the mutation applied, TestCollapseCharWindowAtExactlyTheLineWindowSize passes
because char_window fires — the exact behaviour you described (whole content plus a marker,
marker_no_win, a 40-line multi-megabyte output through a green suite) can no longer be
expressed by that edit. The boundary test is there and is non-vacuous (the byte-gate mutation
fails it), but no test distinguishes equivalent code. I think killing the behaviour is the
stronger outcome; if you would rather have a test that also kills the edit, say so and I will
add a direct window() unit assertion on byChars at the boundary — it will be green under both
versions, so it would be a documentation test, not a mutation kill.

Your note about the earlier "11 mutations / 0 vacuous" table being a claim about vacuity rather
than about catching plausible wrong implementations is fair and I have restated this round as
mutation results.

Follow-ups — all fixed except two

  • :210-212 comment false for small budgets. Softened, with both causes named in the code
    (the floor returns before measurement; got measures asm(""), an empty marker, while the
    shipped text carries ~15 tokens) and tryMark's guard named as what makes the residue
    harmless. I chose the comment over measuring asm(token) because window() does not yet know
    the hash — measuring a same-length placeholder is doable but changes the emitted bytes of a
    path that is now frozen and replayed, for a residue the never-worse guard already contains.
    Happy to revisit if you disagree.
  • head_lines: 0, tail_lines: 0 → bare marker. Fixed, routed to the character window.
  • Negative knobs panic / unreachable max(...). Clamped once in newCollapse, as you
    suggested — it covers both paths, and splitWindow now only has to handle zero, so its guard
    means what it reads as.
  • Undocumented 200-char floor and 3-pass bound. Documented, with the seed clamp and the
    negative clamp, and docs/components.md's "too small for either window to shrink it" now
    describes the gate.
  • []rune on 14.8 MB. Recorded as a ponytail with the rate that makes it tolerable
    (17 bodies in 3,347 requests) and the note that streaming is the obvious fix if that rises.
  • Grapheme-safety. Declined, as cosmetic-and-still-valid-UTF-8. Recorded in the PR's rejected
    list rather than left silent.
  • The combining case. This one I cannot action: there is no combining case in the suite.
    The rune-safety test is TestCollapseCharWindowKeepsValidUTF8, which uses CJK — the multibyte
    property is real there and the byte-slicing mutation is caught. Possible the note came from a
    different branch; flagging rather than skipping it.

Dashboard follow-up

  • Header. Fixed as you specified — one string in dash/ui/index.html and dash/ui/app.js,
    now "Why / what happened", plus the paragraph in docs/dashboard.md that described the
    column as gate counts only. Cell left merged; dash/event.go's reason for merging is sound and
    collapse being the first component to surface an event there is why the header was never
    revisited.
  • The 158% bar. Filed as dash: the first savings bar renders 158% in a 100%-wide track — a ratio presented as a share #158 rather than fixed here, with your measurements, the
    renderDenominators max: 100 mechanism, and three fix options (1.58× with the track at
    min(1, …) recommended, and do not touch the arithmetic stated explicitly). It changes the
    headline savings display and affects all four denominator rows, so it wants its own screenshot
    verification rather than riding along on a components/offload fix. You are right that this PR
    is what pushes it past charitable-ignoring, and I have said so in the issue.

Framing

Both taken. The body now leads with 17 of 75 errored runs and says explicitly that the payoff
is avoided hard failures rather than a savings line, with the tail-gate/freeze reasoning for why
no savings series will show it — plus your dashboard agent's 113,975 → 1,824 measurement as the
independent confirmation that the cut is real when it fires.

Verification

Eval box, Go 1.26.4, CGO_ENABLED=1: gofmt clean, go build ./... clean,
mkdocs build --strict clean, full go test ./... green except
dash/TestSpendSurvivesRowEviction — which fails 3/3 on unmodified main (e88f5d8) too. Its
fixture backdates 10 hours and today is the 1st, so 3 of its 10 sessions land in the previous
month and MonthToDateUSD correctly returns 7 instead of 10. Filed as #157 with fix options;
distinct from the two load-dependent flakes in #91, and it would have been red for you a few
hours earlier in the day. This PR touches no dash Go code.

Not merging — back to you.

… cut

collapse is the pipeline's last-resort catch-all for an oversized tool output, so
when it declines, nothing caps the output. It was line-oriented only, and declined
anything with head_lines+tail_lines lines or fewer (40 by default, gate
too_few_lines) on the reasoning that "head/tail wouldn't help". For the single
largest shape of tool output in practice that reasoning is inverted: a database or
HTTP API result serialised as JSON is very often ONE line, so a multi-megabyte
payload fell through collapse entirely.

Nothing else caught it. Measured on a live 128k-band arm: extract acted 0 times
(no_obvious_noise 16,891 - it only strips known noise patterns), cmdfilter 0
(no_filter_match, known command families only), toon 21
(not_uniform_object_array 233,501), dedup 774 (exact duplicates only), extract_llm
declines by design once the output exceeds the compaction model's own window
(over_model_context), and summarize protects keep_last, which is exactly where a
FRESH oversized output sits. linecap's per-line cap does not rescue this shape
either: its neverTruncate allow-list exempts any line matching `^\S+:\d+`, which
`{"items":[{"id":1,...` matches by accident.

The consequence was measured, not hypothetical: 16 upstream 400s in 3,347 requests,
all "prompt is too long", on outgoing bodies of 2.6 MB to 14.8 MB, and 17 of 75
benchmark runs errored in that arm. A digest of one failing 14.8 MB body held only
4 messages, so a single tool_result was multiple megabytes.

collapse now picks its window before the depth gate: by LINES when there are enough
of them, by RUNES when there are not. Runes rather than bytes so a multibyte
character is never split into invalid UTF-8 in text that is spliced back into the
request body verbatim.

The character budget adds no knob. It is the component's own token threshold
expressed in characters: max_tokens (resolved through resolveBudget, so max_frac
still wins) times 4 - the same chars/token ratio internal/tokens.Count itself falls
back to when the BPE codec is unavailable - split between head and tail in the
head_lines:tail_lines ratio, so those knobs keep meaning what they say on both
paths. chars/4 is only the starting estimate: dense JSON tokenizes closer to
2.5 chars/token, so a flat window would overshoot the very budget it enforces. On
the 3 MB JSON fixture in the new test, unmeasured chars/4 lands at 3,056 tokens
against a 2,000-token threshold. The assembled window is therefore MEASURED against
max_tokens and the budget scaled down when it overshoots, bounded at 3 passes, with
a 200-character floor so a max_tokens of 0 cannot collapse an output to a bare
marker with no cue about what to expand.

Every property that makes this a legal Offload is preserved by going through the
same shared helpers as the line path: tryMark/commitMark for the reversible stash
plus <<cg:HASH>> marker and the marker-inclusive never-worse guard, skipReduce for
idempotence, and freeze so later turns replay the same bytes at depth.

too_few_lines is GONE rather than renamed. Most of what it counted is now handled,
and exporting handled work under a decline's name produces a series that falls as
the component works better - the distinction components/component.go's Gate/Event
split exists for. Its population is now the char_window EVENT when the character
path acts, and the too_few_lines_and_chars GATE for the only genuine decline left:
too few lines for a line window and too few characters for a character one.

Behaviour for multi-line output is unchanged by construction - the line branch
still assembles the identical format string - and
TestCollapseLineWindowIsByteIdentical asserts the exact expected bytes for four
multi-line fixtures rather than capturing them from the implementation, because a
collapsed form is frozen and replayed at depth: a changed layout would re-anchor
every cached position after it in live sessions mid-flight.

Every new assertion was vacuity-checked by reverting the code it covers: 11
mutations, 11 required failures, 0 vacuous. See the PR body for the table.

Incidental finding, NOT fixed here: internal/tokens.Count is superlinear in the
length of a single unbroken word, and a separator-free CJK blob is exactly that -
600 KB of it did not finish tokenizing inside a ten-minute go test timeout. That is
pre-existing (collapse's own size test tokenizes the whole content, as it always
did), but it is why the UTF-8 fixture here keeps ASCII separators between the CJK
runs, and it is worth its own investigation.

ponytail: an output with MORE than head_lines+tail_lines lines still takes the line
window and can stay multi-megabyte if the kept lines are themselves huge. linecap
runs after collapse and caps those lines unless neverTruncate exempts them. Left
out of scope deliberately so the line path stays byte-identical; the character
window is the natural second stage if that shape shows up in production.

Assisted-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
…rsize band

Review of #138 found the character window itself correct on the properties most likely
to be wrong (rune-safe across a 6-offset sweep through a 3-byte rune, byte-exact expand
recovery, deterministic across sessions, never-worse in tokens) but the GATE in the wrong
units. Three fixes, all in that gate.

1. The window was chosen on the LINE COUNT, so an output with more than
   head_lines+tail_lines lines took the line path however big those lines were. A
   multi-megabyte line inside the kept head or tail survived untouched - and worse than
   being declined, because dropping the small filler lines in the middle counts as acting
   and stamps a marker, which then makes linecap decline marker_or_kept_verbatim.
   Measured by the reviewer: 4,195,111 B in, 4,194,922 B out, 189 bytes saved, 1.57 M
   tokens forwarded, events empty. The line window is now taken only when it at least
   HALVES the output; anything else falls through to the character window.

   The test is in bytes, not tokens, deliberately. maxTokens comes from
   resolveBudget(..., c.CtxWindow), CtxWindow can resolve differently mid-session, and
   repairLostFreeze re-derives at depth - so a token gate could classify the same content
   line-window on one turn and character-window on the next and emit different bytes,
   trading a savings bug for a cache bug. Bytes depend only on the content and
   head_lines/tail_lines, so the classification is replay-safe. Both forms classify every
   fixture identically, which is what keeps the line path byte-identical.

   The ponytail note this replaces was doubly wrong: it named the shape as out of scope
   when it is the same defect, and it named linecap as the mitigation when linecap's
   neverTruncate exempts `^\S+:\d+` and one-line JSON matches that by accident (#151),
   so the mitigation was void rather than conditional.

2. runeWindow seeded budget at maxTokens*4 and tested the bail-out against that
   UN-measured seed, before the fit loop ran. chars/4 overestimates on dense JSON
   (~2.5 chars/token), so content genuinely oversized in TOKENS was still shorter in
   runes than its char budget and was declined outright as too_few_lines_and_chars. At
   max_tokens 3000 - what the shipped codesafe preset sets - one-line JSON from 3,006 to
   4,491 tokens was oversized and left entirely uncut, and no test covered 3000. Seeding
   at min(maxTokens*collapseCharsPerToken, len(r)-1) closes it; marker_no_win already
   protects the downside of seeding low.

3. The character path had no byte-exact layout assertion, so three of the reviewer's
   twelve mutations survived all eight new tests. Its output is frozen and replayed at
   depth exactly like the line path's, which is why the line path got
   TestCollapseLineWindowIsByteIdentical; TestCollapseCharWindowIsByteIdentical is the
   equivalent, with the expectation written out as a literal format string rather than
   captured from window(), over four fixtures including both huge-kept-line shapes.

Follow-ups from the same review, fixed here:

- head_lines: 0, tail_lines: 0 reached the LINE path (`1 > 0+0`) and produced a bare
  marker with no content cue - 2,001 lines of payload became 90 bytes, which is exactly
  what collapseMinWindowChars exists to prevent. With no line window configured, the
  character window (even split, floored) is the only sensible reading of "cap this".
- Negative head_lines/tail_lines panicked on the line path (`1 > -10` sends even a
  one-liner there, then lines[:-10] slices out of range), which also made splitWindow's
  own max(...) guard unreachable for the config it looked like it defended. Clamped once
  in newCollapse, which covers both paths; splitWindow now only has to handle zero.
- The runeWindow doc claimed "an output above max_tokens comes back at or under it". It
  does not for small budgets: the 200-char floor returns before any measurement, and
  `got` measures asm("") - an EMPTY marker - while the shipped text carries the ~15
  tokens of the marker and its hint. Softened to say so, and to name tryMark's never-worse
  guard as what makes the residue harmless.
- The 200-char floor and the 3-pass bound were undocumented, so max_tokens: 50 silently
  yielded a window the user did not ask for. Both documented, with the seed clamp and the
  negative-knob clamp, in docs/components/collapse.md.
- []rune on a 14.8 MB payload allocates ~59 MB per oversized message per turn, on top of
  the strings.Split above it. Recorded as a ponytail note with the measured rate that
  makes it tolerable for now (16 bodies in 3,347 requests).

Declined, with reasons: the reviewer's "combining" follow-up does not apply - there is no
`combining` case in the new suite to fix (TestCollapseCharWindowKeepsValidUTF8 uses CJK,
where the rune property is real). Grapheme-safety is left alone: an orphaned combining
mark is cosmetic and the output stays valid UTF-8, which is the property that matters for
splicing into a request body.

Each new test was verified by reverting the code it covers on the eval box (Go 1.26.4,
CGO_ENABLED=1). 8 mutations, 7 caught:

  M1 remove the byte gate (revert to the line-COUNT gate)  CAUGHT
     collapse_charwindow_test.go:320: huge line in head: character window is not
     byte-identical
  M2 revert the budget clamp to maxTokens*4                CAUGHT
     :439: max_tokens 2000: 2061-token single-line output left uncut; gates
     map[too_few_lines_and_chars:1]
  M3 flip the too-few-lines gate to >=                     EQUIVALENT (see below)
  M4 off-by-one head slice r[:h+1]                         CAUGHT
     :320: one line json: character window is not byte-identical
  M5 off-by-one omitted count                              CAUGHT
     :320: huge line in tail: character window is not byte-identical
  M6 byte slicing instead of runes                         CAUGHT
     :219: character window split a multibyte rune
  M7 remove the zero-line-window routing                   CAUGHT
     :467: a 72000-byte output collapsed to 90 bytes - a bare marker with no cue
  M8 revert the newCollapse negative clamp                 CAUGHT
     :484: negative line knobs must be clamped to 0, got -10/-5

M3 is the reviewer's worst survivor, and it survives now because the byte gate makes it an
EQUIVALENT mutant rather than a wrong implementation: at exactly head_lines+tail_lines
lines the mutant does take the line path and compute omitted = 0, but asm("") is then the
whole content plus ~24 characters, which fails the halving test and falls through to the
character window anyway. The behaviour the mutation used to produce - whole content plus a
marker, marker_no_win, a 40-line multi-megabyte output sailing through - can no longer be
expressed by that edit. TestCollapseCharWindowAtExactlyTheLineWindowSize pins the boundary
from the other side and is non-vacuous (M1 fails it), but no test can distinguish
equivalent code, and that is a stronger outcome than catching the mutant.

go build ./... clean, gofmt clean, mkdocs build --strict clean, go test ./... green except
dash/TestSpendSurvivesRowEviction, which fails identically on unmodified main (e88f5d8):
its fixture backdates 10 hours and today is the 1st, so 3 of 10 sessions land in the
previous month. Filed as #157. The dashboard's 158% savings bar is #158.

Assisted-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid
amiddavid force-pushed the fix/collapse-single-line branch from 4ce7c33 to 5f16ffa Compare September 1, 2026 09:51
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (3f272cd) — force-pushed 4ce7c33 → 5f16ffa, so review anchors on the old SHA are stale.

The conflict was not in the collapse code. It came entirely from a two-word dashboard label edit
this PR had picked up as a follow-up ("Why declined" → "Why / what happened" in dash/ui/app.js
and dash/ui/index.html). Two findings while resolving it:

  • main already made that change, and went further: for the table this PR touched it removed
    the column altogether (Errors | Verdict) rather than renaming it. So the edit was redundant, and
    it is dropped — no dash/ files remain in this PR. Changed files: 7 → 5.
  • The docs/dashboard.md half is kept, because it is not redundant. main's UI now says
    Why / what happened while main's own docs still say "Why declined" — the UI change left the
    documentation stale. This PR's doc edit corrects that, and additionally explains the thing that
    made the rename necessary in the first place: the column now carries events, not only declines,
    and collapse's char_window is the first one to appear there on a row that acted.

Verified on the rebased tree: gofmt clean, go build ./... clean, Collapse tests pass, full
go test ./... green — including dash/TestSpendSurvivesRowEviction, which is genuinely fixed on
current main (see #157: every earlier report of it, mine included, was reproduced against a tree
predating 1f1ac2b).

No functional change from the review response; this is purely the rebase and the scope trim.

@OsherElhadad
OsherElhadad merged commit d33661c into main Sep 1, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Sep 1, 2026
OsherElhadad pushed a commit to OsherElhadad/context-guru-1 that referenced this pull request Sep 23, 2026
The branch this replaces carried 97 commits against a merge base main has since
moved 295 files past. Three of its general fixes landed separately (rossoctl#136 schema
shape validation, rossoctl#137 the adjudicate verdict tool, rossoctl#138 collapse's byte gate),
and main absorbed the prefix-ask infrastructure independently as
extract_llm_sweep. What is left is the part that was only ever about
co-reference, re-cut onto main rather than rebased: internal/coref (the index),
the coref component, and prefix_econ (the shared cache-write price).

The pre-recut history is preserved on origin at archive/coref-compaction-pre-recut
(f31b451) -- the experiment record and the refuted arms are evidence, not clutter,
and a force-push must not be the only copy of them.

Two things main required that the branch predated:

RegisterFields for coref. main added a test asserting every registered component
declares exactly its configurable YAML keys, and its motivating story is this
branch's own: an account whose extract_llm ran 251 times and acted zero times
because the two keys that decided it were not on the settings page. coref had a
constructor and no descriptors, so it was that bug waiting to happen. Each hint
carries the measurement behind the default rather than restating the field name --
including the two thresholds (closed_dist, open_reps) that are explicitly NOT
measured yet, which is why cut_closed ships off.

MarkKeptVerbatim lost its session argument. The branch had made keep-verbatim
marks session-scoped; main's are global, so a mark written by one session exempts
the same bytes in every other session sharing the store -- preferentially on
content that recurs across sessions, which is exactly the content most worth
cutting. That is a real lost-savings leak, but fixing it is a store key-format
change in state.go affecting every offloader plus a read-both-shapes migration
for marks already on disk, so it is filed separately rather than smuggled in
here. The two tests that prove the leak are SKIPPED with their bodies preserved
commented, not adapted: an adapted body would compile, read as a real test, and
assert nothing, because both sessions would share one global mark.

Signed-off-by: David Amid <[email protected]>
Assisted-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants