Repository navigation
Conversation
…ng history The per-output form of removing the merged design's `trim` verdict (cc1aa9f), on the same evidence: trim was chosen zero times in 21 probe opportunities, metrics were identical without it, and in production it was accepted ONCE against EIGHT rejected as invented. It was the only verdict that asked the model to transport text, which is what a model is worst at. The per-output strategies divide the same way, and nothing had drawn the line: code, deterministic produce a PROGRAM (or a deterministic projection) executed against the real text — nothing is transported, so nothing can be invented single, rlm hand the content back THROUGH the model — the transporting shape A sweep now allows only the first group. Restricted there specifically, for two reasons that compound. `strategy: auto` orders `rlm` AHEAD of `code` once a body is large, and large bodies are precisely what a sweep works on — so on a sweep the transporting mode is not a corner case, it is the default pick. And a sweep rewrites content DEEP IN HISTORY that the model has already reasoned about, so an invention there contradicts the transcript rather than degrading one recent tool result. The exclusion is COUNTED (`sweep_strategy_narrowed`), which is the half of the trim change that is easy to lose: there, a model answering `trim` degraded to `keep` AND WAS COUNTED, because an unjudged output is otherwise indistinguishable from silence. Here, "the operator asked for rlm and got code" must not read as "the operator asked for code". `auto` is excluded by absence rather than by filtering. It is a strategy ORDER, and extract.intersectAllowed narrows the order it produces, so an `auto` configuration still resolves — to code, then deterministic — instead of being emptied and failing open to no compaction. Three tests. Two pin the classification against the engine's own list of accepted strategies, so a strategy added later cannot silently default to "does not transport" and go uncounted. The third runs ONE `strategy: rlm` config over two turns that differ only in whether the prompt cache is cold, so it asserts the sweep condition rather than something general about rlm. Verified by removing the narrowing: the cold arm fails with gates=map[], the warm arm still passes. Full suite: 27 packages, 0 failures, gofmt clean. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Closing — superseded before merge, and by a better shape. This restricted the sweep's strategies to
So once trim is gone the operation is binary — keep verbatim or drop entirely — with no column stripping and no elision markers. That removes the transporting operation rather than just the transporting strategies, which is the point of the trim measurement (accepted once against eight rejected as invented). Two things follow, and both are why this PR should not land as a half-step:
Replaced by a per-output spent-ness adjudicator, in a new PR. Nothing here is lost that is worth keeping: the strategy classification and its tests are subsumed, since an adjudicator never selects a compaction strategy at all. |
… over the model's cached transcript (#118) * docs(proposals): the cold sweep should adjudicate, not compact Specification only; no behaviour change. Committed ahead of the implementation because the reasoning is the expensive part and it is currently spread across a closed PR, a commit message on another branch, and a conversation. The argument: extract_llm does one thing in two situations that want different things. On a warm turn it trims a recent tool output, and rewriting is right there. On a cold sweep it does the same to outputs deep in history, where the operation is wrong -- that content is either still load-bearing, in which case rewriting corrupts what the model has already reasoned about, or it is spent, in which case it should be removed rather than made smaller. feat/coref-compaction reached this conclusion for the merged design and removed the `trim` verdict (cc1aa9f): chosen zero times in 21 probe opportunities, metrics identical without it, accepted once in production against eight rejected as invented, and the only verdict that asked the model to transport text. What remained is binary -- keep verbatim, or drop with a shape descriptor left in place -- with an obligation named and quoted verbatim, and unsure defaulting to keep. Applying that contract per-output removes the transporting OPERATION rather than just the transporting strategies, which is the strongest form of the rule the measurement supports. It also settles two things that were being carried as open questions: `rewrite` becomes moot on the sweep rather than differently-defaulted, since nothing is rewritten; and the extract_llm/extract_llm_sweep split stops being config hygiene, because strategy, rewrite, aggressiveness and max_chars all cease to apply to a component that selects no compaction strategy. Records the config surface field by field, six safety invariants each stated as a test that must fail when its subject is reverted, the counters and which two must be alertable, three open questions that need measurement rather than argument, and an execution order whose first slice is verifiable without any component wiring. Supersedes #117, which restricted the sweep's strategies to the non-transporting ones. That stopped the model RETURNING content but left `code` rewriting it, so it was a half-step toward this and is closed rather than merged. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * feat(extract): the cold-sweep adjudication contract, and the four rules that make a verdict actionable The cold sweep and the warm tail want different operations. On a warm turn a rewrite is right: the output is recent and a smaller version of it is more useful than none of it. On a cold sweep the same operation runs against deep history, which is either still load-bearing -- in which case rewriting corrupts content the model has already reasoned about -- or spent, in which case the answer is removal, not a smaller version of something nobody will read. This is the contract for the second case, ported from the merged design's internal/extract/bulk.go WITHOUT its batching. The contract is general; the batch is not. The verdict is binary because cc1aa9f measured the alternative. trim was chosen ZERO times in 21 probe opportunities, keep/drop scored identically to keep/drop/trim on every metric, and in production it was accepted ONCE against EIGHT rejected as invented. It was the only verdict that asked the model to transport text. Removing it removes the transporting OPERATION rather than the transporting STRATEGIES: after this there is no reply field that can carry output content at all. The criterion is a required output field rather than an instruction because arms carrying an identical criterion differed ONLY in whether the model had to name and quote the obligation, and the arm that had to emit it halved the false-drop rate, 4/4 to 2/4. Stating the criterion alone measured inert. Two sections of bulk.go's prompt are deliberately absent. READING THE EVIDENCE taught the model to interpret a co-reference index's counters, and no such index exists on this path. JUDGE THEM AGAINST EACH OTHER describes comparative ranking, which a per-output call structurally cannot do -- and that is a recorded risk, not an oversight: the merged experiment measured comparative judgement as the difference between 6% and 58% live-kept. The safety machinery is what carries this design, and every failure it detects resolves toward keep. Four guards, each verified to FAIL when its subject is reverted: * a drop that names an outstanding obligation is refused, not performed. Removing the refusal (keeping its counter) gives: --- FAIL: TestDropNamingAnObligationIsRefused (0.00s) adjudicate_test.go:38: needed_by="a": dropped an output the model itself said is still needed adjudicate_test.go:38: needed_by="b": dropped an output the model itself said is still needed adjudicate_test.go:38: needed_by="c": dropped an output the model itself said is still needed adjudicate_test.go:38: needed_by="A": dropped an output the model itself said is still needed adjudicate_test.go:38: needed_by=" b ": dropped an output the model itself said is still needed adjudicate_test.go:38: needed_by="in-progress-step": dropped an output the model itself said is still needed * unsure defaults to keep. Making an unparseable reply and an unusable verdict drop instead gives: --- FAIL: TestUnsureDefaultsToKeep (0.00s) adjudicate_test.go:81: empty reply: dropped on an unusable verdict; unsure must default to keep adjudicate_test.go:81: prose, no object: dropped on an unusable verdict; unsure must default to keep adjudicate_test.go:81: truncated object: dropped on an unusable verdict; unsure must default to keep adjudicate_test.go:81: not json inside braces: dropped on an unusable verdict; unsure must default to keep adjudicate_test.go:81: verdict absent: dropped on an unusable verdict; unsure must default to keep adjudicate_test.go:81: verdict empty: dropped on an unusable verdict; unsure must default to keep adjudicate_test.go:81: verdict is trim: dropped on an unusable verdict; unsure must default to keep adjudicate_test.go:81: verdict is prose: dropped on an unusable verdict; unsure must default to keep * a fabricated obligation quote is counted. It argues for KEEPING so it is not dangerous, but on this design it is the only remaining signal that the model is inventing, since nothing else it returns is content. Removing the containment check gives: --- FAIL: TestFabricatedObligationQuoteIsCounted (0.00s) adjudicate_test.go:106: a quote absent from the transcript was not counted as fabricated * an unanswered criterion field is tolerated and counted. Requiring it would collapse yield against a model that omits it; ignoring it would hide that the forcing function never ran. Removing the counter gives: --- FAIL: TestUnansweredCriterionIsToleratedAndCounted (0.00s) adjudicate_test.go:138: an unanswered criterion was not counted; the forcing function's absence would be invisible Every test asserts a PRECONDITION before its subject -- that the reply parsed, and that the verdict reached the branch under test. Without those, a parse regression turns each into a vacuous pass: Judge would return the zero Adjudication, Drop would be false, and "the refusal worked" would be indistinguishable from "the reply was never read". The quote check retries once whitespace-insensitively. A model that re-wrapped a long line copied faithfully and is not inventing, and this counter is meant to be alertable -- a routine re-wrap firing it would train the operator to ignore the signal that matters. No component wiring in this commit; the contract and its parser are verifiable alone. Suite: 27 packages, 0 failures. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * feat(offload): the sweep's drop path -- a shape residue that transports nothing, and a drop that stays recoverable Two properties carry the drop, and each is now a test. THE RESIDUE TRANSPORTS NOTHING. It is computed from the output's SHAPE -- content class, line count, record count, token count -- by this code, and contains no byte of the output. That is stricter than the merged design's residue, which fell back to a 96-character head peek for anything that was not a JSON array or object, i.e. for most real tool output. A head peek is our code copying rather than the model copying, so it is not the failure cc1aa9f was about, but it is still unverified content in the request -- and the point of an adjudicator over a compactor is that no content moves at all. It also does not help where it looks like it should: for a record set the first rows say nothing about whether the field you want is in there, which is the argument the merged design already accepted for structured content and then declined to apply to the rest. The record count is there because a line count alone cannot answer "how much was here": a multi-megabyte JSON API result is routinely a SINGLE line, which is the same shape that makes collapse skip such payloads, and "1 line" is a useless thing to tell an agent about 200 records. Only a top-level array that parses gets a count; a partial payload gets the line count rather than a guess, because the descriptor's whole value is that every number in it is true. THE DROP IS REVERSIBLE, AND THE MODEL IS NOT TOLD SO. It goes through tryMark/commitMark, so the never-worse check is MARKER-INCLUSIVE -- the descriptor is small but the marker plus its recovery hint is not free, and the pipeline's aggregate guard is per-request rather than per-message. Note the asymmetry with the prompt, which never mentions recoverability: measured, reassuring the model that removals stay recoverable produced 91% removal at 6% live-kept. The operator gets the safety net; the model does not get to hear about it. Guards, each verified to FAIL when its subject is reverted: * a dropped output stays recoverable. Removing the commitMark stash gives: --- FAIL: TestDroppedOutputStaysRecoverable (0.03s) extract_sweep_drop_test.go:56: the marker did not resolve — the drop would be unrecoverable --- FAIL: TestDroppedOutputWithoutAPersistingStoreLeavesNoDanglingMarker (0.00s) extract_sweep_drop_test.go:84: an unrecoverable drop must set Irreversible or the pipeline will revert it and omitting the marker token from the assembled text gives: --- FAIL: TestDroppedOutputStaysRecoverable (0.02s) extract_sweep_drop_test.go:52: expected exactly one resolvable marker, got 0 in "[context-guru removed a spent tool output — tool output, 7 lines, 109 tokens]" * the descriptor transports nothing. Restoring the merged design's head peek gives, on the first of four fixtures: --- FAIL: TestSweepDescriptorTransportsNothing (0.00s) extract_sweep_drop_test.go:117: descriptor transports content from the output: "KUBERNETES_NAMESPACE=quarantine-zebra" appears in "[context-guru removed a spent tool output — tool output, 7 lines, 109 tokens; began: KUBERNETES_NAMESPACE=quarantine-zebra\ndeployment/ingress-flamingo READY 3/3 RESTARTS 0\ndeplo]" extract_sweep_drop_test.go:117: descriptor transports content from the output: "deployment/ingress-flamingo" appears in ... [27 further leaks across the remaining fixtures] and removing the record count gives: --- FAIL: TestSweepDescriptorCountsRecordsOnASingleLineArray (0.00s) extract_sweep_drop_test.go:138: a 200-record single-line array must report its record count, got "[context-guru removed a spent tool output — json_blob, 1 lines, 802 tokens]" The recoverability test asserts a PRECONDITION that the drop actually happened before it asserts recovery: "recoverable" is trivially true of content that was never removed, so a helper that returned early would otherwise pass. The descriptor test asserts the shape facts are present alongside the no-leak check, because a descriptor that came back empty would pass the leak assertion while telling the agent nothing. No component wiring yet -- the splice is a package helper the sweep component will call. Suite: 27 packages, 0 failures. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * feat(offload): extract_llm_sweep -- the cold sweep adjudicates one output at a time The component the previous two commits were building toward. On a turn whose prompt cache has expired it asks a cheap model, ONE OUTPUT PER CALL, whether each candidate is still needed, and either keeps it VERBATIM or removes it behind a shape descriptor and a recoverable marker. Not a batch, deliberately. A shared reply can be truncated mid-array, quote fidelity degraded with batch size when measured (4 of 37 quotes non-verbatim at batch 16 against 0 of 16 at batch 10), and a batch-truncation counter has to exist to compensate. A per-output call has none of those. The cost of the choice is that comparative judgement is unavailable, which is recorded in internal/extract/adjudicate.go rather than glossed: the merged experiment measured comparative ranking as the difference between 6% and 58% live-kept, so the prior on per-output YIELD is negative and it is the safety machinery that carries this design. Reused rather than forked, as specified: the model client, pricing, the economic gate, the session result cache, the marker/stash machinery and the report/gate plumbing are all extract_llm's. Only the decision is new. The config surface is the split the proposal specifies. min_tokens, min_idle_seconds and max_calls are the sweep's own; model, marker_mode, context, context_messages, model_max_input_tokens and economic_gate are shared. strategy, rewrite, aggressiveness and max_chars are REFUSED with a named reason rather than silently ignored -- an adjudicator selects no strategy and produces no rewritten text, so a silently accepted `rewrite: false` would read as "verified deletion-only is on" when nothing is being rewritten. Detected on a separate probe struct, because a field on the config struct would have to be declared to the settings form and would put a knob on the page whose only behaviour is to fail. Three things the proposal did not cover, decided here: * A DROP MUST BE REPLAYED ON EVERY LATER TURN. The decision is frozen in the shared session-scoped result cache and re-applied at any depth on warm turns, because otherwise the next warm turn re-sends the removed output verbatim -- the saving evaporates AND the prefix the provider is caching stops being byte-stable, which costs more than the sweep saved. This is safe in the sense TailOnlyCold's doc requires: the DECISION came from a model, but the REPLACEMENT is sweepDescriptor(content), a pure function of the content, so a replay cannot emit different bytes than the turn that decided it. Session-scoped only, never global -- a drop is a judgement about THIS transcript's obligations. * The sweep carries its OWN ratioTracker. extract_llm's is calibrated on partial rewrites and this path is all-or-nothing, so pooling them would price each on the other's history. The gate's break-even for a drop is still the unmeasured number the proposal names as open question 3; rather than invent a prior, the existing exploration budget learns it. * The refusal is counted INSTEAD of a keep, not alongside it. Both leave the output verbatim, but folding "the model tried to remove something it had just said was needed" into the keep total is what would make the alertable counter invisible. A REAL DEFECT FOUND WHILE VERIFYING THE CAP TEST. The gates were first raised from inside the per-call goroutines. components.Report is copied by value across this codebase so its Gates map carries no lock, and Go turns that into `fatal error: concurrent map writes` rather than a wrong count -- it killed the test binary. Each call now accumulates its own gate names into its own slot and the serial phase raises them, the same discipline the ModelCall records use. Guards, each verified to FAIL when its subject is reverted: * a drop naming an outstanding obligation is refused end to end. Letting the component perform it gives: --- FAIL: TestSweepRefusesADropThatNamesAnObligation (0.08s) extract_sweep_test.go:157: the contradictory drop was PERFORMED (gates: map[below_output_floor:1 sweep_adjudicated:1 sweep_drop_refused_obligation:1 sweep_dropped:1]) * the cold condition governs. Dropping the ColdCache check gives: --- FAIL: TestSweepDoesNothingOnAWarmTurn (0.05s) extract_sweep_test.go:179: a warm turn must say why it did nothing (gates: map[below_output_floor:1 cached_prefix:1]) --- FAIL: TestSweepMinIdleRaisesTheBar/warm,_however_long_idle (0.00s) extract_sweep_test.go:202: sweeping=true, want false * a drop survives into later warm turns. Not freezing the decision gives: --- FAIL: TestSweepReplaysItsDropOnTheNextWarmTurn (0.08s) extract_sweep_test.go:236: the warm turn did not replay the frozen drop (gates: map[not_a_cold_sweep:1]) * the cap binds. Disabling it gives: --- FAIL: TestSweepCapBinds (0.07s) extract_sweep_test.go:265: max_calls: 2 allowed 5 calls (gates: map[sweep_adjudicated:5 sweep_dropped:5]) * the compaction-only keys are refused with a REASON. Removing the probe leaves the generic yaml message, which says the key is unknown rather than why it cannot apply: --- FAIL: TestSweepRejectsCompactionOnlyKeys/strategy (0.00s) extract_sweep_test.go:326: error does not say why the key cannot apply: yaml: unmarshal errors: line 1: field strategy not found in type offload.extractSweepConfig * every candidate is accounted for under concurrency. Raising the gates from the goroutines again gives, under -race: WARNING: DATA RACE Read at 0x00c000b92150 by goroutine 31: github.com/rossoctl/context-guru/components.(*Report).Gate() components/component.go:510 github.com/rossoctl/context-guru/components/offload.(*ExtractSweep).Offload.func1() components/offload/extract_sweep.go:418 Every test asserts a PRECONDITION that the component acted -- the call count, and the gate for the branch under test -- before asserting the outcome. A component that never ran leaves the transcript in exactly the state a correct keep does, so without those the drop, keep and refusal tests would all pass on a component that had stopped working. extract_llm keeps its per_output and cold_cache surface for now; removing it is the next commit, so this one is additive and the suite is green either way. Suite: 27 packages, 0 failures. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * test(sweep): pin the adjudicator's counter contract at both ends The six counters the proposal names are what an operator's dashboard query and alert rule are written against, so a rename breaks monitoring silently rather than loudly -- the harness and the alert keep running and report zeros, which is the same failure mode statsGoldenTopLevel exists to prevent for the /stats payload. Two of the six must be ALERTABLE, and each names a distinct misbehaviour rather than a volume: * sweep_drop_refused_obligation -- the model tried to remove an output it had, in the same reply, just said was still needed. The removal does not happen; that is the invariant. But a non-zero rate means the contract is not holding and the only thing between the workload and silent context loss is our refusal. * sweep_quote_fabricated -- the model cited transcript text that is not in the transcript. It argues for KEEPING so it is not dangerous, but on this design it is the ONLY remaining signal that the model is inventing, because nothing else it returns is content. If the verdicts are to be trusted at all, this is the number that says whether they can be. They reach an operator through the existing generic cg_component_gate_declines_total{component, gate} series rather than through a bespoke metric each, so no new export surface is added. Pinned at BOTH ends, with the literal strings written out twice on purpose: * components/offload drives the real component through five outcomes -- spent, still needed, a drop contradicting an obligation, an invented quote, an unanswered criterion -- and asserts it raises those exact names. * proxy asserts the same names survive to /stats under the component's own object AND to the Prometheus gate series, with distinct per-counter values so a mixed-up mapping shows up. A single shared list would have been less duplication and a worse test: a rename that edited it would leave every test passing while breaking every deployed alert rule. Verified to FAIL when its subject is reverted. Renaming the two alertable counters in the component only: --- FAIL: TestSweepRaisesTheContractedCounterNames/a_drop_contradicting_an_obligation (0.00s) extract_sweep_test.go:378: the component did not raise "sweep_drop_refused_obligation"; got map[below_output_floor:1 sweep_adjudicated:1 sweep_refused:1] --- FAIL: TestSweepRaisesTheContractedCounterNames/an_invented_obligation (0.00s) extract_sweep_test.go:378: the component did not raise "sweep_quote_fabricated"; got map[below_output_floor:1 sweep_adjudicated:1 sweep_fabricated:1 sweep_kept:1] and dropping the gate histogram from the /stats rollup (metrics.addGates): --- FAIL: TestSweepCountersReachStatsAndMetrics (0.00s) sweep_counters_test.go:73: the component's gate histogram did not reach /stats, so the counter names cannot be checked Both tests assert a PRECONDITION first -- that an adjudication was counted, and that the gate histogram arrived at all. Without them a component that never called the model, or a rollup that dropped `gates` entirely, would be indistinguishable from six renamed counters. Suite: 27 packages, 0 failures. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * fix(extract_llm): stop raising gates from the per-call goroutines (#119) extract_llm raised two gates from inside its concurrent phase -- deduped_inflight_extraction and reply_truncated. components.Report is copied by value throughout this codebase and its Gates map therefore carries no lock; the file says so itself, six lines above, at the declaration of the per-slot ModelCall records that exist for exactly this reason. The gates never got the same treatment. THE SEVERITY IS WHY THIS IS ITS OWN COMMIT. An unsynchronised map write is not a wrong counter and not a recoverable panic. The runtime aborts with `fatal error: concurrent map writes`, which in a proxy kills the PROCESS -- every in-flight request of every session -- rather than letting one component fail open the way the rest of this file is careful to. Found while building extract_llm_sweep, whose first draft made the same mistake and whose cap test died on it. The reachable path is the single-flight follower. extractInflight collapses byte-identical content into one call and releases every waiter at the same instant, so N identical candidates in one request give N-1 simultaneous raises. Four identical tool outputs is enough. Fixed with the pattern already proved in the sweep component: each call appends its own gate names to its own slot, and the existing serial phase raises them. The gates are raised unconditionally there, before the `calls[k].Component != ""` guard, because a single-flight follower returns BEFORE filling its ModelCall slot -- and its gate is precisely the one that says so, so gating the raise on a filled record would drop it. The broader question -- give Report.Gate a lock once so no component can reproduce this -- stays open on #119. This commit fixes the one live occurrence in the file it was already being edited in. Verified to FAIL when reverted. Raising the gates from the goroutines again gives, under -race: WARNING: DATA RACE Read at 0x00c00015e158 by goroutine 28: github.com/rossoctl/context-guru/components.(*Report).Gate() components/component.go:507 github.com/rossoctl/context-guru/components/offload.(*ExtractLLM).Offload.func2() components/offload/extract_llm.go:1356 Previous write at 0x00c00015e158 by goroutine 27: github.com/rossoctl/context-guru/components.(*Report).Gate() components/component.go:508 github.com/rossoctl/context-guru/components/offload.(*ExtractLLM).Offload.func2() components/offload/extract_llm.go:1356 and, WITHOUT -race, the quiet form -- a lost increment -- on 3 of 20 runs: --- FAIL: TestConcurrentCallsDoNotRaceOnTheGateHistogram (0.00s) extract_llm_gaterace_test.go:69: deduped_inflight_extraction = 2, want 3: a follower's gate was lost, which is the quiet form of the same unsynchronised write (gates: map[deduped_inflight_extraction:2]) That second form is why the test asserts an exact count rather than only relying on -race, which the suite does not run by default. The test asserts a PRECONDITION that a follower actually ran -- only a follower can raise deduped_inflight_extraction -- because if the candidates never reached the concurrent phase no two raises were ever simultaneous and the test would prove nothing. Suite: 27 packages, 0 failures. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * feat(sweep)!: adjudicate a BATCH, not one output per call The per-output shape this component shipped with was the one the experiments REFUTED, and the proposal doc's argument for it was inverted. Corrected here, in the code and in the doc. WHAT THE EVIDENCE ACTUALLY SAYS. docs/results/coref-selection-experiment.md, ten arms over 8,105 recorded decisions: shown ONE output, a model scored 6% live-kept on haiku and 14% on sonnet, both inside the drop-everything null model's error bar -- shown a single output, a model simply drops it. Shown ~15 together it reached 58% at the LOWEST cost per output, because the overhead amortises and, more importantly, because comparative judgement beats absolute judgement: ranking a dozen candidates against each other is a question a model can answer, "is this one output expendable" is not. `4ca1f13` was cited by the proposal as evidence that per-output "is a shape that has already run". It says the opposite. It found a live arm at 1.02 verdicts per call and filed that as the bug: "that is the per-output design refuted at 6% live-kept, not the bulk shape that measured 58%, so iteration 014 measured something other than what it claimed". It also added the assertion whose absence let it through -- the prompt must offer more than one output, because "asserting a single call was not enough, since one call carrying one item is exactly the refuted design". `cc1aa9f` gives the direction of the failure, and it is the one a SWEEP cannot tolerate: "at batch 3-6 the model dropped a genuinely-spent output only 2 times in 4, at batch 10 it dropped it 4 in 4 and cleared 100% of genuinely-spent candidates. Small batches do not make it wrong, they make it UNWILLING TO ACT, which is what a 94.6% keep rate looks like from inside." A sweep exists because the entire transcript is re-billing at the write rate; a timid adjudicator is an expensive no-op exactly where the money is. NEITHER OBJECTION TO BATCHING SURVIVES. Both were already solved on feat/coref-compaction: * truncated shared replies -- `659e7a6` traced 24 of 34 unparseable replies to a 2048-token output budget. Fixed here by a new optional components.Budgeter interface (same shape as Remodeler: same endpoint, same credential, larger reply budget), which the sweep uses to ask for extract.AdjudicationReplyTokens = 16000. Not a raise of cheapmodel.DefaultMaxTokens, because the budget a caller needs is a property of what it ASKS FOR: a one-output compaction reply and a twelve-verdict array are different lengths. Output bills as generated rather than as budgeted, so the ceiling costs nothing until used. A client without the knob still works and is counted (sweep_reply_budget_not_raised) rather than silently returning to truncation. * quote fidelity decaying with batch size -- measured, and the cap is set below the observed ceiling: 4 of 37 quotes non-verbatim at batch 16 against 0 of 16 at batch 10, so MaxAdjudicationItems is 12, the conservative end. And the transport principle never distinguished the shapes at all: post-trim, no verdict carries content either way. That argument rules out rewriting; it says nothing about how many verdicts travel in one reply. STARVATION, which is the failure that made this component's predecessor lie about its own shape. `4ca1f13`'s other finding is that the arm's real defect was an upstream per-candidate filter -- prefix_still_referenced removed 149,681 candidates, leaving about one per request. There is no coref index on main, but the ECONOMIC GATE was the same mechanism, so it now runs ONCE for the batch rather than per candidate. That is also the correct arithmetic: it compares an expected saving against one CALL's cost, and a call now covers up to twelve candidates, so charging each of them a whole call priced the batch at ~12x its real cost. The old candidate-level max_calls truncation is gone for the same reason -- max_calls: 4 leaving four candidates is a batch of four, the size at which the model was measured unwilling to act. It now bounds BATCH calls. Every safety guarantee is unchanged, because all of them are per-VERDICT properties: the refusal of a drop naming an obligation, unsure-defaults-to-keep, fabricated-quote counting with the whitespace-insensitive retry, the shape descriptor that transports nothing, reversibility, and the drop-replay-on-warm-turns freeze. The #119 gate discipline matters more, not less: batches still fan out, so each call accumulates its own gate names and the serial phase raises them. New counters, all in the reviewed surface: sweep_offered (via a new Report.GateN, because a per-candidate loop cannot express "this many were SHOWN" -- the distinction that cost three iterations when 2.80 verdicts/call was read as the batch size), sweep_batch_truncated, sweep_batch_of_one, sweep_kept_whole_batch, sweep_verdict_unknown_label, sweep_verdict_duplicate_label, sweep_verdict_missing, sweep_reply_budget_not_raised. docs/proposals/sweep-adjudicator.md carries the correction rather than the wrong reasoning. Guards, each verified to FAIL when its subject is reverted: * the batch is offered as a batch. Chunking at 1 instead of MaxAdjudicationItems gives: --- FAIL: TestSweepOffersTheWholeBatchInOneCall (0.13s) extract_sweep_test.go:265: 12 candidates took 4 calls; the measured shape is ONE call over the batch --- FAIL: TestSweepAccountsForEveryCandidateUnderConcurrency (0.38s) extract_sweep_test.go:470: expected 5 concurrent batch calls, got 60 (gates: map[sweep_adjudicated:60 sweep_batch_of_one:60 ...]) * the economic gate does not thin the batch. Putting it back per candidate reproduces the starvation exactly -- twelve candidates become a batch of two: --- FAIL: TestSweepEconomicGateDoesNotThinTheBatch (0.14s) extract_sweep_test.go:542: sweep_offered = 2, want 12: the gate thinned the batch one candidate at a time, which is how a bulk arm silently becomes the refuted per-output shape (gates: map[economic_gate:10 sweep_adjudicated:2 sweep_dropped:2 sweep_offered:2 ...]) * the reply budget is raised. Skipping the Budgeter call gives: --- FAIL: TestSweepRaisesTheReplyBudget (0.08s) extract_sweep_test.go:422: the sweep asked for a 0-token reply budget, want 16000 --- FAIL: TestSweepCountsAClientThatCannotRaiseItsBudget (0.00s) extract_sweep_test.go:443: a client without a budget knob was not counted (gates: map[... sweep_kept_whole_batch:1 ...]) * a deliberate keep-all is not a failure. Folding the empty array back in gives: --- FAIL: TestSweepCountsADeliberateKeepAllSeparatelyFromAFailure (0.10s) extract_sweep_test.go:352: a deliberate keep-all was not counted as one (gates: map[... sweep_verdict_missing:1]) * truncation is not a format failure. Making ReplyWasTruncated return false gives: --- FAIL: TestTruncationIsDistinguishedFromAFormatFailure (0.00s) adjudicate_test.go:140: a reply that opened the array and never closed it must read as truncated --- FAIL: TestSweepCountsADeliberateKeepAllSeparatelyFromAFailure (0.09s) extract_sweep_test.go:369: a cut-off array was not counted as truncation (gates: map[... sweep_unparseable:1]) * a verdict for an unoffered label is never acted on. Removing the check does not merely act on the wrong content, it CRASHES -- a model-supplied label indexes the candidate slice directly: panic: runtime error: index out of range [99] with length 1 github.com/rossoctl/context-guru/components/offload.(*ExtractSweep).adjudicateBatch(...) components/offload/extract_sweep.go:695 * bounded coverage is visible. Dropping the truncation counter gives: --- FAIL: TestSweepBatchesPastTheItemCapAndCountsWhatItTruncated (0.30s) extract_sweep_test.go:326: sweep_batch_truncated = 0, want 6 — bounded coverage must be visible * a batch of one is counted. Removing the counter gives: --- FAIL: TestSweepCountsABatchOfOne (0.09s) extract_sweep_test.go:301: a batch of one was not counted; a starved batch would be invisible (gates: map[... sweep_kept:1 sweep_offered:1 ...]) * the contract asks for comparative judgement. Removing the paragraph gives: --- FAIL: TestContractAsksForComparativeJudgementAndNoTransport (0.00s) adjudicate_test.go:246: prompt does not carry "JUDGE THEM AGAINST EACH OTHER" The economic-gate tests run with the gate ON, which the rest of the file turns off. Without them the whole gated path was untested and the per-candidate reversion passed the suite -- found by running that reversion and watching nothing fail. BREAKING: `max_calls` now bounds batch calls rather than per-output calls. Suite: 27 packages, 0 failures. Also verified race-clean under -race. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * refactor(extract_llm)!: remove the cold-sweep surface, which is its own component now Finishes the split. extract_llm is unconditionally the warm/tail compactor: `per_output` and the whole `cold_cache` block are gone, along with every `sweeping` branch they governed -- the cadence and pressure exemptions, the sweep's own floor, the tail-gate lift, the request-trigger carve-out, the separate cap arm, the one-writer-then-readers call ordering, and the AUTO file-read exception. Roughly twenty conditionals that each existed to make one component behave as two. BREAKING, deliberately: there is one deployment and it is migrated by hand. But a removed key must say where it went, so `per_output` and `cold_cache` are REFUSED with an error naming the replacement rather than falling through to KnownFields' "field not found" -- which reads as a typo rather than a relocation. `cold_cache: {enabled: true}` silently accepted would read as "the sweep is on" while nothing swept, and that is the most expensive available misreading of this config: the sweep exists for the turns measured at 4% of requests and 31% of spend. MODEL ESCALATION MOVED RATHER THAN DYING. It was already guarded on `sweeping`, so removing the sweep would have left it unreachable -- and it protects exactly the case that matters more now: a batch's fixed prompt cost is larger than a single output's, so a small adjudication model's window is easier to exceed, and when fitsModelContext declines every candidate the sweep silently does nothing on the largest, most expensive transcripts. It now lives in extract_llm_sweep, with its pricing and call-model re-derivation intact and a sweep_escalated_to_agent_model counter. MIGRATED, not just compiled: * the `housellm` preset -- the live deployment's configuration -- gains extract_llm_sweep after extract_llm, carrying cold_cache.min_tokens 1000 as its own min_tokens. Its comment keeps the measurements that justify the floor and now says plainly that they describe the value of sweeping this workload, not the yield of the adjudicator that now does it. * config/form.go loses its ONE per-component coupling. applyExtractLLMCoupling existed only because the constructor refused `per_output: false` with the sweep off, so the form had to translate two switches into pipeline membership; the sweep is a component now and follows the ordinary rule. The recommended prefill serves two blocks. * dash/ui/app.js loses XLLM_SWITCHES and the checkbox handler that flipped one switch back on -- a checkbox meaning two different things is what the split removed. * proxy/control_test.go, proxy/optionsfields_test.go, config/form_test.go, components/all/xglobal_test.go, apply/sweep_variants_test.go and the docs. TWO TESTS WERE POINTED AT THE WRONG COMPONENT AND WOULD HAVE KEPT PASSING. TestHousellmColdSweepActuallyFires read extract_llm's preset block; left alone it would have asserted that a component which no longer sweeps still sweeps -- the same "configured into a no-op while looking enabled" failure it was written to catch, one level up. It now reads the extract_llm_sweep block, answers with a verdict array instead of a Starlark program, and also asserts sweep_dropped, because a call that adjudicates and removes nothing is the same no-op from the operator's side. The options-fields guard asserted that a nested key is served as one dotted field using cold_cache.min_tokens; it now uses trigger.min_request_tokens and additionally checks that the sweep's own fields reach the page at all and that the compaction knobs do NOT -- a field for a key the constructor rejects is a control whose only behaviour is to fail the save. extract_cold_test.go is reduced to what is not about the sweep component: the pricing of a cold turn, which extract_llm still sees, and the refusal of the moved keys. Everything else it covered -- depth, the floor, the cap, min_idle_seconds, the context mode, not draining the hot path's budget -- is tested against extract_llm_sweep, where it is exercised through the shape that was measured good rather than through a compaction pass pointed at deep history. Verified to FAIL when reverted. Removing the movedToSweep probe leaves the generic yaml message: --- FAIL: TestKeysThatMovedToTheSweepAreRefusedByName/per_output (0.00s) extract_cold_test.go:68: error does not name the component the key moved to: yaml: unmarshal errors: line 1: field per_output not found in type offload.extractLLMConfig extract_cold_test.go:71: error does not say what per_output becomes (want mention of "warm/tail pass"): yaml: unmarshal errors: line 1: field per_output not found in type offload.extractLLMConfig --- FAIL: TestKeysThatMovedToTheSweepAreRefusedByName/cold_cache (0.00s) extract_cold_test.go:68: error does not name the component the key moved to: yaml: unmarshal errors: line 1: field cold_cache not found in type offload.extractLLMConfig which is exactly the reading this guard exists to prevent: the key looks misspelled rather than moved. Also adds docs/components/extract_llm_sweep.md, including the three questions the design records rather than answers. Suite: 27 packages, 0 failures. gofmt clean. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * fix(sweep): the batches never shared their prompt prefix -- split it, and order the calls only where the write is earnable Found in review. The sweep launched every batch concurrently under one semaphore with no cache coordination, so each sent the same contract and conversation context as fresh input and none could read another's write. Three separate things were wrong, and the first one made the other two unreachable. THERE WAS NO BREAKPOINT AT ALL. The component called Model.Complete, which routes to CompleteSystem(ctx, "", prompt) and thence to CompleteBlocks(ctx, nil, prompt) -- no system field, so systemBlocks placed no cache_control mark and there was nothing for a sibling batch to read. Not a missed optimisation: a request field that was never sent. The prompt is now SPLIT. The contract is a system block, invariant across every request and tenant. The goal is a second system block when there is more than one batch to share it, and stays in the user half otherwise -- with one batch there is nothing to read the entry and a write costs 1.25x fresh, so marking it would be a 25% loss. THE CANDIDATES ARE NEVER IN THE PREFIX: they differ per batch, so an entry containing them could never be read, which is strictly worse than no breakpoint. Routed through extract.AskAdjudication so completeSplit stays unexported and the decision about which half is cacheable lives next to the contract it splits. THE CALLS NOW EARN THE WRITE BEFORE READING IT. cheapmodel.claimCacheWrite deliberately withholds the breakpoint from concurrent siblings -- an entry only ever written is worse than none -- so with every batch in flight at once, sharing could not happen even in principle. The first batch runs alone, then the rest concurrently, the same mechanism extract_llm uses. It could not reuse extCfg.CacheContext/serialFirst directly, because the adjudication path builds no extract.Cfg; the mechanism is mirrored explicitly instead. AND IT IS CONDITIONAL, WHICH IS THE PART THE MEASUREMENT DECIDED. A cache_control below the provider's minimum cacheable prefix is silently ignored -- no error, cache_creation_input_tokens: 0 -- and the minimum is 4,096 provider tokens on haiku-class against 1,024 on sonnet-class. MEASURED with internal/tokens: adjudication contract 504 o200k contract + two-message `recent` context ~537 o200k haiku-class floor 3,413 o200k (needs ~2,900 tokens of conversation) sonnet-class floor 853 o200k (needs ~349, which a real context supplies) unnameable gateway alias haiku-class, minCacheablePrefix's own default So SHARING IS REACHABLE ON SONNET-CLASS AND PROVABLY CANNOT WORK ON HAIKU-CLASS at `context: recent` -- and housellm pins claude-haiku-4-5. Serializing the first batch costs a whole gateway queue round (~2-4 s p50, tail 12-16 s), so paying it for a write the provider will refuse is strictly a loss. The component reads its own prefix size through extract.AdjudicationPrefixTokens, asks cheapmodel.CacheablePrefix, and serializes only when the answer is yes. On haiku it stays fully concurrent -- which is what it already did, but now for a reason that is checked rather than by accident. The asymmetry is recorded rather than resolved silently. `context: full` would clear haiku's floor and is NOT adopted: that is proposal open question 2, unmeasured, and chasing a cache is the wrong reason to change what the model is shown. Both outcomes are counted instead: sweep_prefix_uncacheable when the floor cannot be cleared, and sweep_prefix_cache_read_ZERO when a sibling read nothing despite the ordering -- that second failure is indistinguishable from a working one except on the bill, which is why it needs a counter and not a comment. max_calls DEFAULT STANDS, and now on stated arithmetic rather than an assumption I made and you endorsed. Three extra batches duplicate ~1,600 input tokens: a fraction of a cent on haiku, and about 4% of ONE batch's own body (twelve candidates bounded at 4,000 chars). The prefix is not where this component's money is, by construction -- the transcript is deliberately not in it. That is the difference from extract_llm's `context: full` sweep, where the prefix WAS the transcript at ~138,000 tokens and duplicating it across five calls was the entire defect. The comment on MaxCalls now says this in place of the bare extrapolation. Guards, each verified to FAIL when its subject is reverted: * the contract is sent as a cacheable system prefix. Reverting to Model.Complete gives: --- FAIL: TestSweepSerializesTheFirstBatchWhenThePrefixIsCacheable (0.47s) extract_sweep_cache_test.go:127: only 0 system block(s): the goal did not join the cacheable prefix, so siblings have nothing to read --- FAIL: TestSweepDoesNotCacheTheGoalForASingleBatch (0.00s) extract_sweep_cache_test.go:178: a single-batch sweep sent 0 system blocks; the goal must stay in the user half so no 1.25x write is paid for an entry nothing reads * the candidates stay out of the prefix. Moving them into it gives: --- FAIL: TestAdjudicationSendsTheContractAsACacheableSystemPrefix (0.00s) adjudicate_cache_test.go:62: output 0 is inside the cacheable prefix; no sibling batch could ever read it adjudicate_cache_test.go:66: output 0 is not in the user half, so the model was never shown it * the first batch is serialized where the write is earnable. Removing the ordering gives: --- FAIL: TestSweepSerializesTheFirstBatchWhenThePrefixIsCacheable (0.46s) extract_sweep_cache_test.go:131: 3 calls had started when the first returned: the first batch did not run alone, so claimCacheWrite suppressed its breakpoint and no sibling can read a write * and NOT serialized where it is not. Serializing unconditionally gives: --- FAIL: TestSweepStaysConcurrentAndCountsItWhenThePrefixCannotBeCached (0.51s) extract_sweep_cache_test.go:157: the first batch was serialized on a model that cannot cache the prefix: the queue round bought nothing (started at first return = 1) * the uncacheable outcome is visible. Removing the counter gives: --- FAIL: TestSweepStaysConcurrentAndCountsItWhenThePrefixCannotBeCached (0.40s) extract_sweep_cache_test.go:153: haiku-class cannot cache this prefix and the component did not record it (gates: map[sweep_adjudicated:36 sweep_kept:36 sweep_offered:36 sweep_prefix_cache_read_ZERO:2 ...]) * a sibling that read nothing is counted. Removing that counter gives: --- FAIL: TestSweepCountsASiblingThatReadNothingFromCache (0.39s) extract_sweep_cache_test.go:208: sweep_prefix_cache_read_ZERO = 0, want 2: a sibling paying fresh for the shared prefix would be invisible * a single batch pays for no cache write. Forcing cacheContext on gives: --- FAIL: TestSweepDoesNotCacheTheGoalForASingleBatch (0.06s) extract_sweep_cache_test.go:178: a single-batch sweep sent 2 system blocks; the goal must stay in the user half so no 1.25x write is paid for an entry nothing reads The ordering test asserts three PRECONDITIONS before its subject -- that there were sibling batches at all, that the prefix was judged cacheable, and that the split really produced two system blocks -- because each of those failing would make "the first batch ran alone" true for the wrong reason. The prefix-size test is written so that a contract which grows past a floor it currently says it does not clear FAILS there, since that would be a real change in this component's economics and this is where it should be noticed. Suite: 27 packages, 0 failures. gofmt clean. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * feat(prefixask): port prefix asks to main -- ask the request's model over its cached transcript Groundwork for the sweep redesign, landed on its own because it is verifiable on its own and because the sweep rewrite that consumes it is a separate change. A component that must decide whether a tool output is still needed cannot answer that from the output alone: need is relevance MINUS whatever has already been captured elsewhere in the transcript, and that second term lives in the later turns. Sending those turns fresh costs ~10x a cache read, and on a cheap model the required verbatim quoting degraded to 20.8% at bulk batch sizes against 0 of 59 on the request model. So the judgement wants the agent's OWN model AND the whole transcript, and only a cache read makes that affordable. Ported from a9d666f on feat/coref-compaction rather than reimplemented: * components: PrefixUsage and PrefixAsker, plus Ctx.PrefixAsk. Usage is RETURNED and not merely recorded, because a caller whose whole justification is the cache read has to be able to gate on whether the read happened -- which a metrics counter cannot support. * cheapmodel: Anthropic.CompletePrefixed, which appends the ask as a trailing user message and touches nothing else except `stream`, since every byte before the appended message is prefix. * proxy: a bounded per-session stash of the body actually forwarded, and the asker built from it. * apply: Opts.PrefixAsk through to the Ctx. THREE FACTS FROM THE ORIGINAL MEASUREMENT that are easy to lose and are now each a test: appending to a byte-identical prefix reads the whole prefix and writes nothing (19,595 read / 0 created); `tool_choice` is NOT in the cache key so forcing it to none is free AND necessary, or the prefix's tools make the model answer with a tool_use; `tools` ARE in the key, so stripping them reads a different, smaller entry. The route also rejects assistant prefill, which the appended user message satisfies by construction. THE PREFIX IS THE PREVIOUS TURN'S SENT BODY, not the incoming one. The upstream cache was populated by what context-guru emitted, i.e. the compacted form; the incoming body is uncompacted and diverges at the first thing any component removed, making everything past that point a fresh charge. Consequence, stated in the doc comment rather than left to be rediscovered: the ask sees the transcript as of the previous turn, so the newest tool output is invisible to it -- acceptable here, because tail content has had no turns in which to be superseded and would be kept anyway. Three deliberate differences from the branch this comes from: * ON BY DEFAULT, no CONTEXT_GURU_PREFIX_ASK gate. It was off there because "a feature whose benefit is a cache hit should not be on by default in a host that cannot verify the hit". We CAN verify it -- that is what returning PrefixUsage is for -- so there is nothing for the operator to opt in to. The other reason it was off, that it holds request bodies in memory, is a bound to state rather than a reason to disable: prefixask.go now documents what happens at each cap (an oversized body is not stashed; past the session or byte cap the whole stash is dropped), and the worst case is a declined sweep, never a wrong answer. * KEYED BY THE SCOPED SESSION ID. serve already receives tr.Session, which is exactly what a component reads as Ctx.Session. Keying the stash by the raw header instead would make every Ask miss while the mechanism looked switched on -- the failure mode the original's own comment warns about. * Ctx.CacheTTLMs carries the cache lifetime the cold decision already derives (5 minutes for a bare ephemeral mark, an hour for an explicit ttl, widened to the longest this prefix ever asked for). Added here because the sweep's trigger has to reason about where in the cache's LIFETIME a turn falls, not merely whether the entry is gone -- and re-deriving it in the component would be a second read of one fact, which is how the cold decision and the dashboard came to disagree once already. CompletePrefixed also documents what the cached region IS here, because it is not what the rest of that file deals with: systemBlocks places our own breakpoint and is bound by the provider's minimum cacheable prefix (4,096 tokens on haiku-class), while this places none at all -- the marks are the agent's own and the region is the transcript, which clears any floor by orders of magnitude. The model-family asymmetry that governs systemBlocks does not apply. Guards, each verified to FAIL when its subject is reverted: * tool_choice forced to none: --- FAIL: TestCompletePrefixedAppendsWithoutDisturbingThePrefix (0.00s) prefixask_test.go:127: tool_choice is not forced to none, so the model will answer with a tool_use: map[] * tools left exactly as the prefix had them: prefixask_test.go:117: tools were not preserved exactly; they are part of the cache key: [] * the ask appended as a USER message: prefixask_test.go:105: the ask was appended as role "assistant"; this route rejects assistant prefill * usage returned so the caller can gate on it: prefixask_test.go:82: CacheRead = 0, want the provider's figure — the caller gates on it --- FAIL: TestAskUsesTheStashedBodyForThatSession (0.00s) prefixask_test.go:179: CacheRead = 0; the caller cannot gate on a figure that does not arrive * a missing prefix is an ERROR, not an empty answer: --- FAIL: TestAskWithoutAStashedBodyReportsNoPrefix (0.00s) prefixask_test.go:157: a missing prefix was not reported as an error prefixask_test.go:190: session 2 got session 1's prefix (err=<nil>) * Anthropic-only: --- FAIL: TestPrefixAskerIsAnthropicOnlyAndNeedsTheIncomingClient (0.00s) prefixask_test.go:219: an OpenAI route got an asker; its cache semantics are not the measured ones * the per-body cap binds: --- FAIL: TestAnOversizedBodyIsNotStashed (0.00s) prefixask_test.go:200: a 1500001-byte body was stashed past the 1500000 cap No component consumes any of this yet, so behaviour is unchanged: the asker is built and handed to the pipeline, and nothing asks. Suite: 27 packages, 0 failures. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * feat(sweep)!: ask the request's model over its cached transcript, and drop the batching Supersedes the batching. The sweep no longer copies candidate content into any prompt: it asks the REQUEST's own model, over the transcript already in that model's prompt cache, and ships an INVENTORY of candidates rather than their content. One call for all of them. WHY. Three measurements, from a9d666f: * appending a trailing user message to a byte-identical prefix read 19,595 tokens from cache and created 0, on the live route. * verbatim quoting -- the only remaining signal that the model is inventing -- degraded to 20.8% on the cheap model at bulk batch sizes, against 0 of 59 on the request model. Since a fabricated quote is the only check left on this design, that alone settles which model is asked. * need is relevance MINUS what has already been captured elsewhere, and that second term lives in the later turns, which a prompt carrying only the candidate cannot show. REMOVED, because they existed only to bound copied content: the batch assembler, the 12-item cap, per-batch concurrency, max_calls, sweep_batch_of_one and batch-truncation counting. Also the sibling-ordering machinery from 316ead4 -- CacheablePrefix-conditional serialization, AdjudicationPrefixTokens and sweep_prefix_uncacheable -- since with one call there are no siblings to order and no floor to clear. The haiku/sonnet minimum-prefix asymmetry is moot: the cached region is now the whole transcript, which clears any minimum by orders of magnitude, and CompletePrefixed's comment records that explicitly. THE TRIGGER IS PRE-EXPIRY, NOT COLD, and that resolves a real contradiction rather than tuning one. The ask needs a WARM cache to read; the removal wants a COLD one so there is no live prefix to invalidate. Both are cheap in the window where the entry still exists but has little life left, so the sweep fires when 0 < remaining <= pre_expiry_seconds. The TTL is DERIVED, never assumed: Ctx.CacheTTLMs is the same figure apply's cold decision uses, read out of the request (5 minutes for a bare ephemeral mark, an hour for an explicit ttl, widened to the longest this prefix ever asked for). Unknown does not fire. THE WINDOW'S WIDTH IS THE ONE UNMEASURED NUMBER, and it is flagged as such in the code, the component doc and the proposal. One minute is apply.coldMargin, the only figure here with a stated purpose for clock uncertainty around cache expiry. Wider fires more often and invalidates more remaining TTL; narrower fires rarely. Nothing measures either side, so it is configurable and deliberately narrow rather than tuned. THE CACHE READ IS VERIFIED AND ALWAYS COUNTED; the miss then FALLS BACK by default. sweep_prefix_cache_read_ZERO fires whenever the read did not happen -- that part is not optional, because a silent miss looks identical to a working call except on the bill. By default the sweep then asks again with a bounded sample of each output, which is what a9d666f chose: treating "no prefix" as "no verdicts" would disable the component on every session's FIRST turn and read as a model that declined to act. `block_fallback: true` declines instead, for an operator who would rather forgo the yield than pay for it. The fallback still asks the REQUEST's model, because the measurement that chose that model is about faithful quoting rather than caching, and that reason survives the loss of the cache read. THE MODEL IS NOT A FREE CHOICE HERE, and the asymmetry with extract_llm is spelled out where a reader will hit it. extract_llm may compact with any model because its prompt CARRIES the output; this component's prompt carries an inventory and the outputs are read from the prompt cache of the model being asked. Only the request's model has that cache, so `model.source: config` is incoherent rather than merely suboptimal -- the ask would read nothing and pay fresh for the entire transcript. A `model` block is refused with an error saying exactly that, not accepted and silently corrected. KEPT, all of it: the obligation refusal, unsure-defaults-to-keep, fabricated-quote counting with the whitespace-insensitive retry, the zero-transport descriptor with its record count, reversibility, decision freezing and replay, integer labels, the unoffered-label guard, and the per-slot gate accumulation from #119. The reply budget is now cheapmodel.PrefixAskMaxTokens and matters MORE than at batch 12, since one reply carries a verdict for every candidate. Guards, each verified to FAIL when its subject is reverted: * the fallback is the default. Declining instead gives: --- FAIL: TestSweepFallsBackWhenTheCacheReadDidNotHappen (0.05s) extract_sweep_test.go:232: the default did not fall back, so the component stops working on a first turn (gates: map[below_output_floor:1 sweep_inventory_of_one:1 sweep_prefix_cache_read_ZERO:1]) * block_fallback refuses it. Ignoring the switch gives: --- FAIL: TestBlockFallbackDeclinesInsteadOfPaying (0.05s) extract_sweep_test.go:269: block_fallback did not refuse the fallback (gates: map[... sweep_fallback_used:1 ... sweep_prefix_cache_read_ZERO:1]) --- FAIL: TestSweepFallsBackWithNoAsker (0.00s) extract_sweep_test.go:311: block_fallback did not refuse the no-asker fallback (gates: map[... sweep_fallback_used:1 ...]) * the missed read is counted in BOTH modes. Removing the counter gives: --- FAIL: TestSweepFallsBackWhenTheCacheReadDidNotHappen (0.05s) extract_sweep_test.go:228: a zero cache read was not counted; the mechanism's failure would be invisible --- FAIL: TestBlockFallbackDeclinesInsteadOfPaying (0.00s) extract_sweep_test.go:266: strict mode did not count the missed read (gates: map[below_output_floor:1 sweep_fallback_blocked:1 sweep_inventory_of_one:1]) * a model block is refused with its reason. Letting it through leaves the generic yaml message: --- FAIL: TestSweepRefusesAModelBlockAndSaysWhy (0.00s) extract_sweep_test.go:329: the error does not mention "source: config", so the constraint reads as an oversight: yaml: unmarshal errors: line 1: field model not found in type offload.extractSweepConfig * the pre-expiry window governs. Reverting to the cold gate gives: --- FAIL: TestSweepFiresOnlyInThePreExpiryWindow/inside_the_window (0.00s) extract_sweep_test.go:293: sweeping = false, want true (idle=240000ms ttl=300000ms cold=false) --- FAIL: TestSweepFiresOnlyInThePreExpiryWindow/apply_already_called_it_cold (0.00s) extract_sweep_test.go:293: sweeping = true, want false (idle=240000ms ttl=300000ms cold=true) * the inventory ships no output content. Putting the body back in the ask gives: --- FAIL: TestSweepSendsTheInventoryAndNotTheOutputs (0.05s) extract_sweep_test.go:603: the whole output body was copied into the ask, defeating the mechanism extract_sweep_test.go:607: the ask is 38031 chars; it should be the contract plus one line per candidate * the unoffered-label guard prevents a crash on model input, not merely a wrong action. Removing it gives: panic: runtime error: index out of range [99] with length 1 offload.(*ExtractSweep).adjudicate(...) components/offload/extract_sweep.go:502 * a nil asker is handled rather than dereferenced: panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x18] ALSO FIXES A CORRUPTED FILE I COMMITTED IN 5d02669. config/form_test.go lost its first 60 bytes to a bad base64 round-trip, so the config package did not compile on the pushed branch even though the suite passed on the eval box -- I validated remotely and committed from a stale local copy. The header is reconstructed and every changed file's sha256 is now checked against the box before committing. docs/proposals/sweep-adjudicator.md carries its second correction and now describes the code rather than preceding it; docs/components/extract_llm_sweep.md is rewritten for the new mechanism. Suite: 27 packages, 0 failures. gofmt clean. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> * feat(sweep): ship the tool_use id as a locating anchor, and guard the coref seam Two changes, both about what the next person needs rather than about behaviour today. THE tool_use ID IS BACK IN THE INVENTORY, as a LOCATING field. Dropping it went one step past the evidence: a9d666f establishes that the ANSWER key must be an integer -- asked to answer with opaque ids the model regularised them, `toolu_01..07` for `toolu_probe_00..07`, against 0 bad labels in 40+ trials with integers -- and says nothing about whether an id may appear in the prompt. The echo risk was always about what the model RETURNS, not what it reads. The cost of absence was the one EXACT anchor there is. The id is also in the transcript the model reads from cache, so shipping it makes an inventory line and a tool result identifiable to each other; without it head-plus-size is the only matching signal, which is shaky on a transcript carrying a dozen near-identical `Read` results. The two aids now have separated roles in the code and in the contract: the label is what the model answers with, the id and the head are what it locates with, and the prompt says so outright ("ANSWER BY LABEL ... do not put it in your reply"). The unoffered-label guard's comment now records what it CANNOT catch: a label that is in range but wrong removes the wrong content and looks valid from there, and nothing downstream can detect it either. That is the failure the id exists to PREVENT rather than to detect, which is the only defence available against a plausible-but-wrong label. THE COREF SEAM IS LEFT CLEAN AND TRIPWIRED, because PR #80 rebases onto this branch and brings the index's evidence signals and index-driven candidate selection with it. * AdjudicationItem.Evidence renders into the inventory line when non-empty and is omitted entirely when not, so the index can arrive without reshaping the contract -- and the contract is the part with measurements attached. Nothing populates it on main, and the prompt deliberately says nothing about how to read one: teaching the model to interpret counters the prompt never carries would be teaching it to read a field that does not exist. * sweep_inventory_thinned, AT the candidate-gathering site rather than only in the doc. 4ca1f13's real defect was a per-candidate PRE-FILTER sitting exactly there: prefix_still_referenced removed 149,681 candidates and left about one per request, silently turning a bulk arm into the p…
Ports the reasoning behind removing the merged design's
trimverdict (cc1aa9f, onfeat/coref-compaction) to the per-output path thatmainactually ships, and applies it whereit matters most: the cold-cache sweep.
The principle, transferred
cc1aa9fremovedtrimbecause it was the only verdict that asked the model to transporttext, on this evidence: chosen zero times in 21 probe opportunities, metrics identical without
it, and in production accepted once against eight rejected as invented.
There is no
trimverdict onmain— it belongs to the merged contract, where one call disposesof many outputs and needs a word per output. But the same division exists in the per-output
strategies, and nothing had drawn the line:
codedeterministicsinglerlmA sweep now allows only the first group.
Why the sweep specifically
Two reasons that compound:
strategy: autoordersrlmahead ofcodeonce a body is large, and large bodies areprecisely what a sweep works on. So on a sweep the transporting mode is not a corner case, it is
the default pick.
invention there contradicts the transcript, rather than degrading one recent tool result.
Two details taken from the original rather than invented
The narrowing is counted (
sweep_strategy_narrowed). This is the half of the trim changethat is easy to lose: there, a model answering
trimdegraded tokeepand was counted,because an unjudged output is otherwise indistinguishable from silence. Here, "the operator asked
for
rlmand gotcode" must not read as "the operator asked forcode".autois excluded by absence, not by filtering. It is a strategy order, andextract.intersectAllowednarrows the order it produces — so anautoconfiguration stillresolves, to
codethendeterministic, instead of being emptied and failing open to nocompaction at all.
Verification
Three tests. Two pin the classification against
extract.Modes, the engine's own list of acceptedstrategies, so a strategy added later cannot silently default to "does not transport" and have its
narrowing go uncounted. The third runs one
strategy: rlmconfig over two turns that differonly in whether the prompt cache is cold, so it asserts the sweep condition rather than
something general about
rlm.Verified by removing the narrowing: the cold arm fails with
gates=map[], the warm arm stillpasses. Full suite: 27 packages, 0 failures,
gofmtclean. No benchmarks run.Intentionally not in this PR
Splitting
extract_llmintoextract_llm+extract_llm_sweep. Agreed as the better designand scoped, but it is a config-surface migration and belongs in its own PR. The sweep already
diverges from the tail path in nine places — its own floor (
cold_cache.min_tokensreplacesmin_tokens), its own call cap, cadence gate exempted, pressure trigger exempted, request triggerexempted, cached-prefix tail gate bypassed,
skip_file_readsauto-mode inverted, model escalationon prompt overflow, and serialised cache-write ordering. That is two components sharing one config
struct, and
per_output: falseplus the "leaves the component with nothing to do" error is theseam showing.
When that lands, a transporting
strategyunderextract_llm_sweepshould become a config-timeerror rather than a runtime narrowing — strictly better feedback. The narrowing here then
becomes defence-in-depth, following the precedent set in
2d6902d, which keptdropOrphanedToolResults"as a defensive net rather than the primary mechanism."Whether the sweep's
rewriteshould default tofalse(verified deletion-only containmentrather than the
derivationRatiobackstop). It is the adjacent question — proof strength ratherthan text transport — and it would reduce sweep savings by an amount only measurement can
establish, so it is deliberately unchanged here.