Repository navigation
fix(collapse): cut a head/tail window whenever the output is oversized — including single-line and huge-line payloads - #138
Conversation
|
Reviewed against main The character window itself is correct on the properties most likely to be wrong. Verified
9 of 12 mutations I wrote are caught. This is careful work. The problem is that the gate is in 1. Blocking — the fix is gated on LINE COUNT, not size, so the motivating shape survives above 40 lines
4 MB in, 189 bytes saved, 1.57 M tokens forwarded. And The named mitigation is void, not conditional. (Filed separately as #151, since it is Compounding this: the evidence does not establish the fix covers the measured failures. The 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 If you would rather not change the gate, the alternative is to amend the PR body: state the 2. Wanted before merge — a units mismatch declines a 55%-wide oversize band, widest in a shipped preset
One line; - 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 layoutThree of my twelve mutations survived all 8 new tests, and they are the same gap: The char path's output is frozen and replayed at depth exactly like the line path, and the PR The
(Note: the PR body's "11 mutations, 11 required failures, 0 vacuous" is about vacuity of the new Follow-ups
Two framing suggestions for the PR bodyNeither is stated, and both make the case stronger:
GeneralizationThe class is evidenced, not speculative (16 upstream 400 VerdictNeeds changes. Item 1 is the blocker and it is a scope/evidence problem rather than a defect |
|
Follow-up: a dashboard agent drove the live UI (headless Chromium, real proxy, real traffic) against First, the confirmationSame novel high-entropy 200KB single-line blob through both builds: So the PR's "nothing else catches this shape" claim holds on independent traffic, and the The inline diff also renders and wraps correctly: longest text node 4,016 chars, no page overflow, 0 1. LOW —
|
…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]>
|
Thanks — the gate/cutting distinction was the right diagnosis, and finding a second copy of the 1. Blocking — the gate is now in BYTESTaken 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
The Two things I did beyond the proposal, both small:
The histogram — it cannot be produced, and the reason is worse than inconvenienceYou were right that the "4 messages" line is a message count doing a line count's job, and right Per message that is structure only — index, role, block-type names, tool-use ids. No content, So I have taken your alternative for the evidence half and stated it plainly in the PR body One correction that came out of the same dig, in your favour and against my own body: the digest 2. The oversize band — taken as writtenbudget := min(maxTokens*collapseCharsPerToken, len(r)-1)
Your point about the gate name making a decline look legitimate on 3. Byte-exact char-window assertion — added, and two of your three survivors are caught
8 mutations, 7 caught, 1 equivalent:
On the Your note about the earlier "11 mutations / 0 vacuous" table being a claim about vacuity rather Follow-ups — all fixed except two
Dashboard follow-up
FramingBoth taken. The body now leads with 17 of 75 errored runs and says explicitly that the payoff VerificationEval box, Go 1.26.4, 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]>
4ce7c33 to
5f16ffa
Compare
|
Rebased onto The conflict was not in the collapse code. It came entirely from a two-word dashboard label edit
Verified on the rebased tree: No functional change from the review response; this is purely the rebase and the scope trim. |
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]>
Headline
17 of 75 runs errored in a live 128k-band arm. Every one of them was an upstream 400
prompt is too longon an outgoing body of 2.6–14.8 MB, and no component in the pipelinetouched those bodies.
collapseis documented as the last resort for an oversized tooloutput, 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.
collapseis tail-gated andfreezes 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_resultlands and exactly where the 400fires. 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
mainreduced it by zero, so the cut is real andvisible in
/api/componentswith nodash/changes.)The defect
collapsewas line-oriented only:Defaults are
head_lines: 20,tail_lines: 20, so any output of 40 lines or fewer wasskipped. 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
collapseentirely.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)
extractno_obvious_noise16,891 — it only strips known noise patternscmdfilterno_filter_match— only known command familiestoonnot_uniform_object_array233,501dedupsummarizekeep_last, where a FRESH oversized output sitsextract_llmover_model_context)linecapno_long_or_repeated_lines—neverTruncateexempts the line; see belowlinecapis not a partial mitigation for this shape — it is void for it. On paper its500-char per-line cap should rescue a huge line. It does not:
neverTruncateexempts any linematching
^\S+:\d+, and a one-line JSON body ({"items":[{"id":1,...) matches that byaccident. 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 PRdescribed
linecapas capping huge kept lines "unlessneverTruncateexempts them", whichimplied 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
"prompt is too long", in 3,347 requestsA 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 longand 2transport-level failures (
IncompleteRead, read timeout) that are not provider rejections. Icannot 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_resultwas 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_linesgate 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: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 errorstring, not the request). No per-message or per-block size of any kind, so the largest
tool_resultcannot even be identified, let alone measured in lines. The only size datum iswhole-request
body_bytes, which includes JSON escaping, the system prompt and 94–149 tooldefinitions, and cannot be converted to a line count of anything.
rig_seq— the field addedso a record could be joined back to the request the shim handed the proxy — is
nullin all 19records, and no raw copy of the bodies survives anywhere on the box (
proxy-i21A.logandflap-i21A.jsonlrecord 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
collapsebeing the only component contracted to catch it, plus the reproducedmechanism 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
collapsepicks its window before the depth gate: by lines when a line window actuallyshrinks 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
linecapdeclinemarker_or_kept_verbatim. Measured: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:
Bytes deliberately, not tokens.
maxTokenscomes fromresolveBudget(..., c.CtxWindow),CtxWindowcan resolve differently mid-session (model swap, refreshedmodelinfo), andrepairLostFreezere-derives at depth. A token gate could therefore classify the same contentline-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 everyfixture identically, including all four in
TestCollapseLineWindowIsByteIdentical, which iswhat 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 throughresolveBudget(somax_frac× the model window still wins),× 4 — the same chars/token ratio
internal/tokens.Countitself falls back to when theBPE codec is unavailable, so the two places in the tree that relate bytes to tokens agree;
min(maxTokens*collapseCharsPerToken, len(r)-1). chars/4overestimates 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 —
codesafesetsmax_tokens: 3000, so one-line JSONfrom 3,006 to 4,491 tokens was oversized and left entirely uncut, with no test at 3000.
marker_no_winalready protects the downside of seeding low;head_lines:tail_linesratio, so those knobs keepmeaning what they say on both paths;
3,056 tokens against a 2,000-token threshold. The fit loop is bounded at 3 passes and only
ever tightens;
max_tokens: 0cannot collapse an output to a bare markerwith no cue about what to expand.
head_lines: 0, tail_lines: 0now routes here for the samereason — 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_tokensdoes not deliver what it says:max_tokens: 100measures ~118tokens out. Two causes, both now stated in the code rather than implied away — the floor returns
before any measurement, and
gotmeasuresasm(""), an empty marker, while the shipped textcarries the ~15 tokens of
<<cg:HASH>> [full output: ...].tryMark's never-worse guardmeasures 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
linecapown it by looseningneverTruncate. Its exemptions exist because a600-char stack frame or compiler diagnostic is exactly the line a model needs whole, and the
file carries measured evidence against narrowing the pattern.
collapseis the componentwhose 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.)
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
jsoncutcomponent can be layered ahead ofcollapselater.
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
ponytailnote recording that rejection is gone, along with the residual gap itdescribed.
The counters
too_few_linesis gone, not renamed. Most of what it counted is now handled, andexporting handled work under a decline's name yields a series that falls as the component works
better — the distinction
components/component.go'sGate/Eventsplit exists for. Itspopulation is now:
char_windowevent — the character path acted;too_few_lines_and_charsgate — the only genuine decline left: no window that shrinks theoutput, i.e. no usable line window and fewer characters than the character window's floor.
Byte-identical layouts, both paths
TestCollapseLineWindowIsByteIdenticalasserts the exact expected string for fourmulti-line fixtures.
TestCollapseCharWindowIsByteIdenticalis the equivalent for the characterpath, 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 (atmax_tokens: 50the budget floors, soruneWindowreturns at pass 0 and there is nobudget-dependent arithmetic in the expectation). Each case also asserts
char_windowfired, sothe comparison cannot pass vacuously via the line path.
TestCollapseCharWindowAtExactlyTheLineWindowSizepins the boundary this PR moves from theother side: at exactly
head_lines+tail_lineslines the line window would omit zero lines, soit 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.
huge line in head: character window is not byte-identicalmaxTokens*4max_tokens 2000: 2061-token single-line output left uncut; gates map[too_few_lines_and_chars:1]>=r[:h+1]one line json: character window is not byte-identicalhuge line in tail: character window is not byte-identicalcharacter window split a multibyte runea 72000-byte output collapsed to 90 bytes — a bare marker with no cuenewCollapsenegative clampnegative line knobs must be clamped to 0, got -10/-5On the
>=survivor — review's worst one, and it survives now for a different reason thanbefore. Under the byte gate it is an equivalent mutant, not a wrong implementation: at
exactly
head_lines+tail_lineslines the mutant does take the line path and computeomitted = 0, butasm("")is then the whole content plus ~24 characters, which fails thehalving 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 outputsailing through a green suite — can no longer be expressed by that edit.
TestCollapseCharWindowAtExactlyTheLineWindowSizepins the boundary and is non-vacuous (thebyte-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: 0reached the line path and produced a bare marker with nocontent cue — 2,001 lines became 90 bytes, precisely what
collapseMinWindowCharsexists toprevent. Routed to the character window.
head_lines/tail_linespanicked on the line path (1 > -10sends even aone-liner there, then
lines[:-10]slices out of range), which also madesplitWindow'smax(...)guard unreachable for the config it looked like it defended. Clamped once innewCollapse, covering both paths;splitWindownow only handles zero.runeWindowdoc comment's claim that "an output abovemax_tokenscomes back at or underit" is softened to the truth, with both causes named.
documented in
docs/components/collapse.md;docs/components.md's "too small for eitherwindow to shrink it" now describes the gate rather than the intent.
[]runeon a 14.8 MB payload allocates ~59 MB per oversized message per turn, on top of thestrings.Splitabove it. Recorded as aponytailwith the measured rate that makes ittolerable for now (17 bodies in 3,347 requests).
char_windowrendered under a column header reading"Why declined" on a row that acted. The merged cell is deliberate (
dash/event.gofoldedevents 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.jsanddocs/dashboard.md.collapseis thefirst component to surface an event there, which is why it was never revisited.
Not fixed here, filed instead
intended and documented (gross over attempted, re-counted every turn); the presentation is
not. This PR pushes it from 115% to 158% precisely because
collapsenow catches enormousblobs, so it gets worse as the product gets better. Left out because it is a change to the
headline savings display affecting all four denominator rows, and belongs with its own
screenshot verification rather than bolted to a
components/offloadfix.linecap'sneverTruncateexempts one-line JSON. Pre-existing; the claimthat it mitigated this shape is removed from this PR rather than the exemption being loosened.
internal/tokens.Countis superlinear on a single unbroken word. 600 KB ofseparator-free CJK does not finish tokenizing inside a ten-minute
go testtimeout.Pre-existing (the size check has always tokenized full content), but note the population
change: single-line payloads used to be skipped by
too_few_lines, socollapseis now thecomponent most likely to meet such an input. It is why the UTF-8 fixture keeps ASCII
separators between the CJK runs.
dash/TestSpendSurvivesRowEvictionis red for the first 10 hours of every month.Found running the full suite for this PR; its fixture backdates 10 hours and today is the 1st,
so 3 of 10 sessions land in the previous month. Reproduced 3/3 on unmodified
main(
e88f5d8), and this PR touches nodashGo code. Distinct from the two load-dependentflakes in flaky: two load-related test flakes in the suite that gates every deploy #91.
One review item that does not apply
Review's follow-up asks to fix a vacuous
combiningcase using"éà"(which compiles toprecomposed runes in Go source). There is no
combiningcase in this suite — the rune-safetytest is
TestCollapseCharWindowKeepsValidUTF8, which uses CJK, where the multibyte property isreal 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:gofmtclean on every touched file,go build ./...clean,
mkdocs build --strictclean, fullgo test ./...green exceptdash/TestSpendSurvivesRowEviction, which fails identically on unmodifiedmain(#157).One correction to the brief
The brief quoted
collapse.gowithout the depth gate, the freeze/replay logic, or therep.Gate("non_text_blocks")/below_max_tokenscounters.origin/mainhas all of them, sothe fix had to slot into
TailOnlyCold+freeze+repairLostFreeze. The window choice isplaced before the depth gate on purpose, so a message with no usable window is not
miscounted as a cache decline.
Separately,
docs/components/collapse.mddocumentscold_cacheas defaulting tofalsewhilecoldCacheField()defaults it totrue(anddocs/components.mdsays true). Pre-existinginconsistency, unrelated, left alone.