Skip to content

Render the memory block in a canonical order so re-ranking stops busting the prompt cache (#388) - #396

Merged
abogartz merged 5 commits into
mainfrom
388-cache-stable-block
Nov 12, 2026
Merged

abogartz merged 5 commits into
mainfrom
388-cache-stable-block

Conversation

@abogartz

@abogartz abogartz commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Part of #386. Addresses #388.

What this does

The epoch's cache key is the rendered memory section joined onto the system parts, compared by bytes and never by a proxy (#162). Correct — and the problem. The block rendered in score order, and score order is a function of the live prompt. A turn that selected the same rows in a different rank order produced different bytes and re-billed the whole prefix to tell the model what it had already been told.

The block now renders canonically — guided lane first, then the lexical picks newest first — so the bytes move only when the selected set or the row content moves. selected keeps score order: the use ledger and attribution credit the ranking, and a miss has to stay diagnosable.

This is criterion 1's option 1 ("recompute only when the selected set changes identity — not order, not wording"), implemented at the render layer rather than the compare layer, so the epoch comparison stays byte-exact per #162.

Budgeting had to move with it. capToBudget trims the rendered string, which under the old order dropped the lowest-scoring row. Under a canonical order the newest row is always first, so the same call would have silently made recency decide who rides. The budget is now applied to the priority order inside selectRelevant, before the re-order. capToBudget remains in epochs.ts, but it is unreachable, not a guard: selectRelevant was handed the same budget and builds the block as the header plus non-negative whole-line increments that each stayed inside it, so a non-empty block is already inside the budget. The comment says that, and says no test can reach a different result.

What the review found, and what this push changes

finding change evidence
F1 the published bench tables were stale at 2b81069 the B/C/D arms now budget through selectRelevant(..., { budget }), the seam the epoch uses, instead of capToBudget(relevantKnowledge(...), budget) table and old/new numbers below; bench/RESULTS.md regenerated
F2 "3 fail on main" was false body corrected: 2 pass / 10 fail at both f8f42fd and ce36c65 for the 12-test file names below
F3 the canonical order was not a total order cmpTs == 0 now falls back to content, then the literal ts string two new tests, RED without the fix
F4 the CONFLICT caveat could ride with no CONFLICT row the caveat is chosen from the rows that survive the budget; the fit is measured against the widest header the selection can still produce new test, RED without the fix
F5 nits dead capToBudget comment made honest; redundant header guard removed; stale epochs.ts evidence comment corrected; a total trim keeps the pre-budget selected; 14 lint warnings removed mutation table below

F3. cmpTs returns 0 for two rows stamped with the same instant, and a stable sort then keeps the order it was handed — score order, prompt-derived. Two rows share an instant in practice: a same-millisecond pair, and a legacy second-precision stamp beside a millisecond stamp for the same instant, because ISO_TS_RE makes .000 optional so both forms load. Before: both pairs rendered differently under an inverted ranking. After: identical.

F4. The header was fixed from the pre-budget conflict count, so budgets between the header width and the header plus the CONFLICT line rendered "CONFLICT rows were code-checked against this repo's current source — follow their Action" over a block containing zero CONFLICT lines. Pre-existing, but this PR moved the budget, so it belongs here. Re-fitting the budget on the narrowed header instead of reserving the widest one oscillates — dropping the CONFLICT row shortens the header, which lets it fit again — so the fit reserves and the render chooses.

F5.4. A total trim returned selected: [], which erased the guided= evidence field and made "the budget dropped it" indistinguishable from "the selector never picked it". selected now keeps the pre-budget selection on that path; guidedRode= is the field that answers whether the row survived.

AC status, stated before review

# criterion status
1 0 prompt_reveal across a six-turn chat, store_changed still fires met for the order class, not for set churn — see below. The order class is now total, so equal-timestamp pairs are inside it
2 bytes byte-identical turn to turn unless the store changed met, asserted on the bytes
3 stability must not mean staleness, demonstrated by test met — a topic shift pulls in the row it needs and records prompt_reveal
4 the 2.1× reproduces locally, hosted provider before any dollar figure not met by this push. The post-fix live seat run was never completed and was not re-run here. No dollar figure is published
5 recall does not regress met — full suite green

Why criterion 1 cannot reach 0 on the audit workload, and should not

chain-cache.ts drives six deliberately unrelated topics. Each selects a genuinely different set, so its prompt_reveal is the model being shown different facts. Removing those means freezing the block, which criterion 3 forbids. The audit measures set churn; it cannot see order churn. Recorded as F16 in the bench notes.

The class, measured on a real seat (pre-fix)

Author-reported from the separate bench repo at the time the PR was opened. Not re-run in this push, and not reproducible from this repository alone.

bun order-pair.ts searches the harness's own seeded store for prompts that select the same set in a different ranking. Found: build,runtime selected by both "test suite on node 22.x exactly" and "test suite single file path argument, node 22.x engines", ranks inverted. Four turns, results-cache-order-on:

turn block chars invalidation
1 A 796 first
2 B 796 prompt_reveal
3 A 796 prompt_reveal
4 B 1079 prompt_reveal + store_changed

Same rows, same block length, three busts. That is the defect this PR removes.

The post-fix run did not finish. The seat degraded to 1287 s for turn 1 (it ran 5–47 s/turn an hour earlier). The agent driving this work runs on the same model over the same proxy, so the measurement is contaminated by its own traffic. Turn 1 loaded the fixed plugin and rendered the same 796 chars with only first, which is the expected shape, but three turns are missing. No dollar figure is claimed, per criterion 4's own rule.

The class, re-measured in-process at this head

Six rank-rotating prompts over a three-row store, driven through the real prompt and context hooks, so every turn shares two concepts with every row and only the rank moves. Counting distinct delivered block shapes:

tree render order per prompt distinct block shapes block bytes
f8f42fd (base) alpha>gamma>beta, beta>gamma>alpha, gamma>beta>alpha, beta>alpha>gamma, gamma>beta>alpha, gamma>alpha>beta 5 328 each
this head gamma>beta>alpha × 6 1 328

Same set, same length, five shapes on base and one here: the churn is order and nothing else.

Frequency, so nobody oversells it

Over 25 prompts against the audit's seeded store: 18 selected one row, 6 selected two, 1 selected three. Order churn needs a multi-row selection and a rank inversion. Most turns select one row, so this is a correctness fix to a stated contract (#335: "same rows, same bytes") whose token benefit is workload-dependent and small on this seat.

Bench: the table now measures the shipped code

At 2b81069 the B/C/D arms still called capToBudget(relevantKnowledge(...), budget). relevantKnowledge returns canonical bytes after this PR, so first-fit trimmed the newest-first block and recency decided who rode — the behaviour this PR removes. The runner printed B=56109 / C=55889 while the published table said 55478 / 55258, and no CI step runs the bench, so nothing caught it.

Policy Recomputes Epochs whose bytes moved Injected chars (20 turns) Avg/turn Worst section
A — naive 20 19 60996 3049.8 3404
B — block frozen on store fingerprint 4 3 55478 2773.9 2867
C — section frozen on rendered bytes 4 3 55258 2762.9 2856
D — C + riding bytes (shipped) 1 0 53500 2675.0 2675

At 2b81069 the same runner printed B = 56109 / 2805.4 / 2860 and C = 55889 / 2794.4 / 2849; A and D were already correct. Routing the arms through the selector's budget returns B and C to the published values, because the selector's first-fit runs over the same priority order the pre-PR capToBudget ran over. Recomputes and byte-change counts are unchanged in every column. The README table and its "12.3% fewer characters" claim recompute to the same values from this run ((60996 − 53500) / 60996 = 12.3%), so neither needed an edit. bench/RESULTS.md is regenerated, never hand-edited; reruns are byte-identical.

The report also told readers to run bun bench/inject-cost.ts; the runner lives at bench/runners/inject-cost.ts, so the published file no longer drifts from what regeneration produces.

Verification

bun run gate at this head: typecheck clean; lint 542 warnings and 0 format errors (main is 545, this branch was 554 before the review fixes); unit 1202 pass / 19 skip / 0 fail (1221 tests); e2e 30 pass / 0 fail against a real opencode host.

test/cache-stable-block.test.ts is 12 tests. Run against the base and against main, it gives 2 pass / 10 fail at f8f42fd and 2 pass / 10 fail at ce36c65. The earlier claim of "3 fail on main" was wrong. The two that pass without the fix are the anti-freeze guards, which are supposed to pass with the fix disabled:

  • stability is not staleness > a prompt needing a row the current block does not carry still receives it
  • stability is not staleness > a store change still busts, with store_changed taking precedence

Mutation table, run against this head's 12 tests (the PR's own 8 fail exactly where they did before, so no kill strength was lost):

mutation pass / fail killed
M1 delete the canonical sort 6 / 6 the 4 order tests plus both new tie tests
M2 budget back on the rendered string 10 / 2 "who rides is decided by priority…" and the new caveat test
M3 delete the total tiebreak (F3) 10 / 2 both new tie tests
M4 caveat fixed pre-budget (F4) 11 / 1 the new caveat test
M5 selected: [] on a total trim (F5.4) 11 / 1 the new total-trim test
M6 header guard put back (F5.2) 12 / 0 nothing — the guard is redundant, so it is removed

One pre-existing test moved: test/inject.test.ts > rare-concept overlap outranks common-word overlap asserted the rank on the first rendered line. That held only because every seeded row landed in the same millisecond and the sort was stable. It now asserts the rank on selected, which is where the ranking lives under a canonical render order, and still asserts the rare row rides.

Merge order

#379 depends on this PR. Its README sentence — "a prompt change that selects the same rows costs no cache bust" — is false on main, because main renders in score order, and is qualified in #379 as depending on #396. Merge #396 first, or land both together; #379 alone publishes a claim that its own base does not satisfy. #398 also touches README.md at the same paragraph, so whichever lands second needs a union merge there.

Also in this branch (bench repo, separate commit)

  • chain-cache.ts aborts when the plugin wrote no status file. A run whose plugin failed to load printed a full table with -1 columns.
  • chain-cache.ts retries a failed /wait instead of losing the run: a host-side TimeoutError is not evidence the turn finished.
  • CHAIN_TOPICS override, and order-pair.ts, which closes the measurement gap F16 names.

…ng stops busting the prompt cache

Part of #388.

The epoch's cache key is the rendered memory section joined onto the system parts
(src/inject/epochs.ts), compared by bytes and never by a proxy (issue #162). That is
correct, and it is the problem: the block rendered in score order, and score order is a
function of the live prompt. A new turn that selected the SAME rows in a different rank
order therefore produced different bytes and re-billed the whole prefix to tell the model
what it had already been told.

The block now renders canonically -- guided lane first, then the lexical picks newest
first -- so the bytes move only when the selected SET or the row CONTENT moves. `selected`
keeps score order: the use ledger and attribution credit the ranking, and a miss has to
stay diagnosable.

Budgeting had to move with it. capToBudget trims the rendered string, which under the old
order dropped the lowest-scoring row; under a canonical order the newest row is always
first, so the same call would silently make RECENCY decide who rides. The budget is now
applied to the priority order inside selectRelevant, before the re-order, so relevance
still decides who rides and canonical order decides how they are shown. capToBudget stays
in epochs.ts as a pass-through guard.

Not fixed here, and deliberately not claimed: a turn whose prompt selects a genuinely
different SET still busts, because it must. Criterion 3 of #388 forbids the alternative --
a block that never moves is a block frozen at session start, and the turn that needs a row
the frozen block does not carry would silently not get it.

- src/recall/relevant.ts: canonical render order; SelectOptions.budget
- src/inject/epochs.ts: pass the budget into the selection
- test/cache-stable-block.test.ts: 8 tests -- re-rank renders identically and recomputes
  nothing, canonical order asserted, a topic shift still delivers the row it needs
  (prompt_reveal fires), a store write still busts, budget keeps relevance over recency,
  and a six-turn scripted chat

Co-authored-by: OpenCode <[email protected]>
@abogartz

Copy link
Copy Markdown
Owner Author

Adversarial review — APPROVE_WITH_NITS

Reviewed head 2b81069f09238948385b61e4d9b8d28fa248c0f1 against merge-base f8f42fd. Findings come from running code, not from reading the diff.

No P1. The fix is real and removes the order-churn class. Three P2s are claim/documentation defects rather than runtime defects, but two of them publish numbers that are now wrong.

Order-churn proof

Same store (the cache audit's own cache-seed.ts), same prompts, the shipped epochs.ts call shape (budget: 1200, guidedCap: 3):

A = "test suite on node 22.x exactly"
B = "test suite single file path argument, node 22.x engines"

BASE f8f42fd                                 HEAD 2b81069
selected A = inventory>pricing>runtime>build  (identical both trees)
selected B = inventory>pricing>build>runtime
block A = 796  hash e1a3e246699c0821         block A = 796  hash e1a3e246699c0821
block B = 796  hash d2f10159c75dbb2b         block B = 796  hash e1a3e246699c0821
BYTES-EQUAL = false                          BYTES-EQUAL = true

796 matches the published audit's blockChars. Through the real plugin (prompt hook → context hook), 3 rows, 6 rank-rotating prompts:

BASE  distinct-block-shapes=3  reasons=["first","prompt_reveal" ×5]
HEAD  distinct-block-shapes=1  reasons=["first"]

Over 268 same-riding-set prompt pairs on the seeded store (15 rows × 14 prompts × 7 budgets): base churned bytes on 2 pairs, head on 0.


P2 — The body's "3 fail on main" is false; 6 of 8 fail

Repro at both f8f42fd and ce36c65:

cp <pr>/test/cache-stable-block.test.ts test/ && bun test ./test/cache-stable-block.test.ts
 2 pass / 6 fail   (both trees)

Failing: tests 1, 2, 3, 6, 7, 8. Only tests 4 and 5 pass pre-fix, and they are anti-freeze guards that pass with the fix disabled. Fix the body to "6 fail on main; 2 are anti-freeze guards that pass either way".

P2 — The PR changes deterministic bench output; published tables go stale

README.md:162-163 and bench/RESULTS.md:15-16 publish B=55478, C=55258. At head, bun run bench prints B=56109, C=55889. Base prints the README numbers.

git checkout pr-396 && bun run bench          # B 56109 / C 55889
git checkout --detach f8f42fd && bun run bench # B 55478 / C 55258

Cause: bench/runners/inject-cost.ts:298,319,360,379 still call capToBudget(relevantKnowledge(...), budget). relevantKnowledge now returns canonical bytes, so first-fit trims newest-first — exactly the "recency decides who rides" behaviour this PR removes from epochs.ts. The bench's B/C/D columns no longer model the shipped budget path. Neither bun run gate nor CI runs a bench step, so nothing catches this.

Fix: regenerate bench/RESULTS.md, update the README rows, and budget the bench's block by priority (or state the divergence in the table note).

P2 — Coupling with #379 is real and unrecorded in both directions

git diff f8f42fd pr-379 | git apply --check passes on this branch, so there is no textual conflict. But #379's README sentence at README.md:153, "a prompt change that selects the same rows costs no cache bust", is false at f8f42fd (base churns, reproduced) and becomes true only with this PR. Merging #379 alone publishes a false claim. Merging this PR alone leaves it unpublished. Neither PR says so. #379 also edits the paragraph directly under the bench table whose B/C rows this PR invalidates.

Recommend: this PR carries the table fix, and the two bodies cross-reference.


Residuals

  1. A binding budget still lets rank order move the bytes (src/recall/relevant.ts:173-180). First-fit runs in priority order, so the surviving SET depends on that order. Same selected set, same budget, different bytes:
    PROBE2: budget=444  rode1=01,03  rode2=02,03  bytes-equal=false
    budget-churn.ts on the audit's seeded store: 121 divergent budget values in [100,2400]
    default injectBudget 1200 divergent: false
    
    Not a regression — base had the same first-fit plus order churn. But claim 2's wording, "bytes move only when the selected SET or the row CONTENT moves", is false as written: the pre-budget selected set is unchanged while the riding set moves. State it, or make the survivor set order-independent.
  2. The canonical order is not a total order; cmpTs ties fall back to score order (src/recall/relevant.ts:183-189).
    TIE  two rows ts=2026-10-06T09:00:00.000Z, rank inverted -> bytes-equal=false
    TIE2 "…09:00:00Z" vs "…09:00:00.000Z" (same instant, legacy precision) -> bytes-equal=false
    
    ISO_TS_RE (src/store/model/memory.ts:138) makes .000 optional, so both forms load. appendMemory bumps collisions inside one day file, so this needs a hand-edited or foreign-day store. Fix: add a final tiebreak, e.g. on content.
  3. A repo source edit busts the cache with no store write (pre-existing, src/recall/relevant.ts:141-148,154-155). findConstant reads the working tree at render time:
    CONFLICT t1=301 t2=548 equal=false t1conflict=false t2conflict=true
    CONFLICT reasons=first,prompt_reveal   (identical at base and head)
    
    Correct behaviour, but it is a second exception to AC 2's "unless the store changed".
  4. The CONFLICT caveat can ride with no CONFLICT row (pre-existing, src/recall/relevant.ts:154-155). The header is fixed from rendered.size before the budget runs. Budgets 405–667 render "CONFLICT rows were code-checked … follow their Action" over a block containing zero CONFLICT lines. Identical range at base. This PR was the natural place to fix it: compute hasConflict from the surviving rows.

NITs

  1. capToBudget at src/inject/epochs.ts:219 is now provably dead. block.length = header.length + Σ(1+len) with non-negative line lengths, so any prefix sum ≤ total ≤ budget and capToBudget cannot drop a line. Fuzz over budgets {1,40,120,200,400,800,1200,4000} × 4 prompts × guided+lexical mixes: it never fired. Keep it if you want, but call it unreachable rather than a guard.
  2. The header guard at src/recall/relevant.ts:172 is redundant. header.length > budget implies header.length + 1 + len > budget for every line, so the loop plus !shown.length returns the same value. Mutation M4 (if (false && header.length > budget)) left all 8 tests green.
  3. Stale comment at src/inject/epochs.ts:336: "In guided but absent from guidedRode -> capToBudget dropped it." The drop now happens inside selectRelevant.
  4. A total trim now empties selected, changing evidence telemetry (src/recall/relevant.ts:172,181 return selected: []; base returned merged). With budget=100 and a guided row: selected=0 at head vs 1 at base. The guided= field disappears, so the documented diagnosis "cap dropped it" becomes indistinguishable from "the selector never picked it".
  5. Lint warnings grow 542 → 554 (+12), infos 147 → 150. bun run lint still exits 0. New: 2 × noNonNullAssertion at src/recall/relevant.ts:184-185, the rest in the new test file. The same function already avoids ! via lines[i] ?? "".

Claim-by-claim

# Claim Verdict Evidence
1 Cache key is the rendered section joined, compared by bytes; the block rendered in score order, so re-ranking re-billed verified by reading + probe epochs.ts:224 prefix=[...parts, block].join("\u0000"), :271 byte compare; churn reproduced at f8f42fd
2 Block renders canonically; bytes move only when the SET or CONTENT moves verified for the order class; false as worded churn 2→0 pairs; exceptions in residuals 1, 2, 3
3 selected keeps score order on purpose verified by probe selected rotates 10-01>10-03>10-02 / 10-02>10-03>10-01 while the block is fixed; recordHits keys on ids.join(",")
4 Budget moved to priority order; capToBudget is a pass-through guard verified by probe riding sets identical base↔head over 98 (budget, prompt) combos; the guard never fired
5 AC 1 met for the order class, not set churn verified by probe head: reasons=["first"]; base: first + 5 × prompt_reveal
6 AC 2 met, asserted on the bytes overstated residuals 1, 2, 3
7 AC 3 met — a topic shift pulls its row and records prompt_reveal verified by reading test 4 asserts ["first","prompt_reveal"]; it also passes pre-fix
8 AC 4 partially; no dollar figure verified benchmark-tests/ocsi/results-cache-order-fix.log holds turn 1 only (1287 s, block 796, first); grep -nE '\$[0-9]|USD|dollar' over the patch: none
9 AC 5 recall does not regress verified by probe 98/98 riding sets identical; 1217 unit + 30 e2e green
10 Pre-fix table 796/796/796/1079, prompt_reveal on turns 2, 3, 4 verified results-cache-order-on/audit.json matches line for line
11 25 prompts: 18 one-row, 6 two-row, 1 three-row verified by probe re-ran order-pair.ts against this tree: {"1":18,"2":6,"3":1} of 25; the named build,runtime inverted pair is present
12 8 tests, 3 fail on main, all 8 pass here; gate 1217 unit, 30 e2e, typecheck and lint clean partly false "3 fail" → 6 fail. Rest verified: bun run gate "merge gate: all green", 1217/19 skip/0 fail, 30 e2e, tsc 0, biome 0

Measured numbers

base f8f42fd head 2b81069 ce36c65 + patch
unit 1190 pass / 19 skip / 0 fail 1198 / 19 / 0 1265 / 19 / 0
e2e 30 / 0 30 / 0 —
tsc --noEmit — exit 0 exit 0
biome lint warnings 542 (+147 infos) 554 (+150 infos), exit 0 —
bun run gate — all green —
cache-stable-block.test.ts 2 pass / 6 fail 8 pass / 0 fail 8 pass
patch applies to ce36c65 — — git apply --check clean
bun run bench B / C 55478 / 55258 56109 / 55889 —

Efficacy proof (mutation → killed)

Mutant Change Tests RED
M1 delete shown.sort(...) → score-order rendering 1, 2, 3, 8
M2 const budget = undefined → trim moves back to the render string 6, 7
M3 canonical re-order first, then first-fit budget (recency rides) 6
M4 disable if (header.length > budget) none (redundant, NIT 2)

Every test meant to guard the fix dies under a mutation that defeats it. Tests 4 and 5 survive all mutants by design — they guard against freezing the block.

abogartz added a commit that referenced this pull request Nov 12, 2026
…end on (#344)

"a prompt change that selects the same rows costs no cache bust" is false on
this tree: src/recall/relevant.ts renders the lexical picks in score order, so
a prompt that keeps the same rows and re-ranks them renders different bytes and
src/inject/epochs.ts moves the epoch with reason prompt_reveal. State the
qualified claim, name the order as part of the bytes, and point at #388/#396 for
canonical render order.

The bench note gains the matching bound: its policies re-score only when the
store fingerprint moves, so the 20 prompts never re-rank one shared set and D's
0 is not evidence about that churn. No measured number changes.
…bytes

The test pinned "rare-concept overlap outranks common-word overlap" by reading
the first line of the rendered block. That only ever held because every seeded
row landed in the same millisecond and the canonical sort is stable, so the
rendered order fell back to score order. #388's follow-up makes that order
total, which removes the accident.

The ranking still exists and still decides who rides; its documented home is
`selected`, so assert it there and keep a block-level assertion that the rare
row is shown at all.
… the survivors

Two residuals the #396 review found in the canonical render order.

The order was not total. `cmpTs` returns 0 for two rows stamped with the same
instant, and a stable sort then keeps the order it was handed — score order,
which is a function of the live prompt, so an equal-timestamp pair re-billed the
prefix on a rank flip: the exact churn the PR removes, one row pair away. Two
rows share an instant in practice: a same-millisecond pair, and a legacy
second-precision stamp beside a millisecond stamp for the same instant, because
`ISO_TS_RE` makes the fractional part optional. Break the tie on content, then
on the literal ts string; both are prompt-independent.

The CONFLICT caveat claimed more than the block delivered. It was fixed from
the pre-budget conflict count, so any budget that dropped the only CONFLICT row
rendered "CONFLICT rows were code-checked against this repo's current source —
follow their Action" over a block containing zero CONFLICT lines. The caveat now
comes from the surviving rows. The budget still fits: the fit is measured against
the widest header this selection can still produce, so choosing a narrower header
afterwards cannot overflow. Re-fitting on the narrower header instead oscillates,
because dropping the CONFLICT row shortens the header and lets it fit again.

Also from the review:

- A total trim returned `selected: []`, which erased the `guided=` evidence field
  and made "the budget dropped it" indistinguishable from "the selector never
  picked it". `selected` keeps the pre-budget selection; `guidedRode=` is the
  field that answers whether the row survived.
- The header-width guard was redundant: `used` starts at the header width, so no
  line clears the test and the empty `shown` returns the same value. Removing it
  changes nothing observable (verified by mutation).
- `capToBudget` in epochs.ts is unreachable, not a guard. The comment now says so
  and says why: the block is header plus non-negative whole-line increments that
  each stayed inside the budget.
- Dropped the two `noNonNullAssertion` warnings the PR added, and the twelve in
  its test file.
The B/C/D arms still called `capToBudget(relevantKnowledge(...), budget)`. After
#388 `relevantKnowledge` returns canonical bytes, so first-fit trimmed the
newest-first block and recency decided who rode — the behaviour the PR removes
from the shipped path. The bench therefore stopped modelling the code it ships:
`bun run bench` printed B=56109 / C=55889 while the published table said
55478 / 55258, and no CI step runs the bench, so nothing caught it.

Route the arms through `selectRelevant(..., { budget })`, the same seam the epoch
uses. The numbers return to the published 60996 / 55478 / 55258 / 53500, and the
"12.3% fewer characters" claim recomputes to the same value from the new run, so
the README table needs no edit. `bench/RESULTS.md` is regenerated, not edited.

The report also said `bun bench/inject-cost.ts`; the runner lives at
`bench/runners/inject-cost.ts`, so the published file no longer drifts from what
regeneration produces.
… test

The review asked for the warnings this PR added. The import Biome wants as
`import type`, and the member order its assist enforces, were the last two, so
the file now checks clean and the branch sits at 542 warnings against main's 545.
@abogartz

Copy link
Copy Markdown
Owner Author

Review fixes pushed (2b81069 → f6f8002)

All five findings are addressed in four commits: test(inject) (move one assertion), fix(recall) (F3, F4, F5), bench (F1 plus the regenerated table), style(test) (the last two lint diagnostics).

F1 — the bench now measures the shipped budget path

I took the honest option: the bench's B/C/D arms now budget the block the same way the epoch does, through selectRelevant(..., { budget }), instead of capToBudget(relevantKnowledge(...), budget). After this PR relevantKnowledge returns canonical bytes, so first-fit over the rendered string trimmed the newest-first block and let recency decide who rode — the behaviour the PR removes. The arms now run through the same seam the shipped code runs through, so the table describes the code that ships.

Before and after, every column:

Policy before (recomputes / moved / chars / avg / worst) after
A — naive 20 / 19 / 60996 / 3049.8 / 3404 unchanged
B — block frozen on store fingerprint 4 / 3 / 56109 / 2805.4 / 2860 4 / 3 / 55478 / 2773.9 / 2867
C — section frozen on rendered bytes 4 / 3 / 55889 / 2794.4 / 2849 4 / 3 / 55258 / 2762.9 / 2856
D — C + riding bytes (shipped) 1 / 0 / 53500 / 2675.0 / 2675 unchanged

B and C return to the published values, because the selector's first-fit runs over the same priority order that the pre-PR capToBudget ran over. Recomputes and byte-change counts did not move in any column.

bench/RESULTS.md is regenerated, not hand-edited — git diff on it shows only the one new prose sentence about where the budget is applied, plus the reproduce-path correction below. Reruns are byte-identical.

README: the table rows (60996 / 55478 / 55258 / 53500 and their avg and worst columns) and the derived claim "D also injects 12.3% fewer characters than the naive policy" both recompute to the same values from this run — (60996 − 53500) / 60996 = 12.289% → 12.3%. The surrounding prose is true word-for-word; no README edit was needed.

F2 — the "3 fail on main" claim

Corrected in the PR body. The pushed 12-test file gives 2 pass / 10 fail at the merge base f8f42fd and 2 pass / 10 fail at ce36c65 (0.23.0). The two that pass without the fix are the anti-freeze guards, which are meant to pass with the fix disabled:

  • stability is not staleness > a prompt needing a row the current block does not carry still receives it
  • stability is not staleness > a store change still busts, with store_changed taking precedence

F3 — the canonical order is now total

Before (in-process, two rows at one instant, ranking inverted between the two prompts):

TIE   two rows ts=2026-10-06T09:00:00.000Z, rank inverted      -> bytes-equal = false
TIE2  "…09:00:00Z" vs "…09:00:00.000Z", same instant           -> bytes-equal = false

After: both bytes-equal = true. cmpTs == 0 now falls back to content, then to the literal ts string; both are prompt-independent. Two tests pin both shapes and are RED without the fix.

F4 — the CONFLICT caveat now describes the rows that ride

Before, at two budgets that hold the header plus a short row but not the CONFLICT line:

BUDGET 339: caveat=true  conflictLine=false
BUDGET 452: caveat=true  conflictLine=false

After: caveat=false conflictLine=false at both — the header falls back to the plain framing.

The caveat decides the header width the budget is measured against, so it cannot simply be recomputed after the trim: dropping the CONFLICT row shortens the header, which lets it fit again, which lengthens the header. The budget therefore reserves the widest header this selection can still produce, and the render picks the real header from the survivors afterwards. Reserving only matters when a conflict row exists, so a store with guided rows and no collision loses no capacity.

F5 — nits

  1. capToBudget in epochs.ts stays, and the comment now says it is unreachable rather than calling it a guard, with the arithmetic that makes it so.
  2. The redundant header guard is removed. Restoring it is mutation M6 below: 12 / 12 green, so it did nothing the loop does not.
  3. The epochs.ts evidence comment now says the budget inside selectRelevant dropped the row, not capToBudget.
  4. A total trim returns the pre-budget selected, so guided= still answers "did the selector pick it" and guidedRode= answers "did it survive". New test pins it.
  5. Lint: the branch was 554 warnings, main is 545, this head is 542 with 0 format errors. The two noNonNullAssertion in relevant.ts are gone, and test/cache-stable-block.test.ts now reports no Biome diagnostics at all.

Mutation table (this head, 12 tests)

mutation pass / fail killed
M1 delete the canonical sort 6 / 6 the 4 order tests + both new tie tests
M2 budget back on the rendered string 10 / 2 "who rides is decided by priority…" + the new caveat test
M3 delete the total tiebreak (F3) 10 / 2 both new tie tests
M4 caveat fixed pre-budget (F4) 11 / 1 the new caveat test
M5 selected: [] on a total trim (F5.4) 11 / 1 the new total-trim test
M6 header guard put back (F5.2) 12 / 0 nothing — confirms the guard was redundant

For comparison, the same M1 and M2 against the PR's original 8 tests kill 4 and 1 respectively. The same four and one still die here, so nothing was weakened; the new tests only add kills.

Order-churn proof, re-run after these changes

Six rank-rotating prompts over a three-row store through the real prompt and context hooks. Every prompt shares two concepts with every row, so the selected set is constant and only the rank moves:

tree distinct block shapes block bytes
f8f42fd 5 328 each
this head 1 328

Render order per prompt on base: alpha>gamma>beta, beta>gamma>alpha, gamma>beta>alpha, beta>alpha>gamma, gamma>beta>alpha, gamma>alpha>beta. Here: gamma>beta>alpha every time.

Gate

Typecheck clean. Lint 542 warnings, 0 format errors (main 545, branch 554 before this push). Unit 1202 pass / 19 skip / 0 fail (1221 tests). e2e 30 pass / 0 fail against a real opencode host. The pre-push hook ran the full gate and it was green.

One pre-existing test moved

test/inject.test.ts > rare-concept overlap outranks common-word overlap asserted the rank by reading the first line of the rendered block. That passed only because every seeded row landed in the same millisecond and the sort was stable, so the rendered order fell back to score order — an accident the pre-existing canonical sort was already one store-write away from losing, and which the F3 tiebreak removes outright. It now asserts the rank on selected, which is where this PR documents the ranking to live, and still asserts the rare row rides. Flagging it because it is a change to a test the review did not name.

Not fixed, with reasons

  • AC4 (post-fix live seat run, dollar figure). Not attempted. The PR body now states AC4 as not met rather than partially met, and no dollar figure is published anywhere.
  • No CI step runs the bench. The staleness in F1 survived precisely because of this. Adding a CI job that executes bench/runners/inject-cost.ts writes bench/RESULTS.md on every run, so it needs a decision about drift checks versus artifact churn that is larger than this review. The numbers are correct now; the guard rail is still missing.
  • The bench report still cites src/inject.ts. That file was split into src/inject/ by Proposal: separate responsibilities in plugin setup (src/index.ts) #168. It is regenerated prose, unrelated to the numbers, and correcting it would churn the published file again. Left alone.
  • The reproduce path inside the report said bun bench/inject-cost.ts. The runner lives at bench/runners/inject-cost.ts. I fixed the template, because otherwise every regeneration rewrites the published file away from the path that actually works. This is the only reason bench/RESULTS.md shows a second diff line beyond the budget note.

Merge order with #379

#379 must not merge before this PR. Its README claim "a prompt change that selects the same rows costs no cache bust" is false on main, where the block renders in score order, and #379 qualifies it as depending on #396. Merge #396 first, or land both together. #398 edits the same README paragraph, so whichever of #379 and #398 lands second needs a union merge there.

@ocsi-reviewer ocsi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving.

The order-churn fix is demonstrated, not asserted: the same selected set in an inverted rank produced different bytes on the base tree and identical bytes here, and over six rank-rotating prompts the base rendered several distinct block shapes where this head renders one. The follow-ups are in too — a total tiebreak so an equal-timestamp pair cannot re-introduce the churn, the CONFLICT caveat computed from the rows that survive the budget, and the bench budgeting the block the way the shipped path does so the published table is the shipped behaviour.

Full gate green, CI green. Not merged — the merge is left to a human.

@abogartz
abogartz merged commit 4c68a08 into main Nov 12, 2026
4 checks passed
abogartz-opencode-self-improvement Bot pushed a commit that referenced this pull request Nov 12, 2026
# [0.24.0](v0.23.1...v0.24.0) (2026-11-12)

### Bug Fixes

* **inject:** render the memory block in a canonical order so re-ranking stops busting the prompt cache ([2b81069](2b81069)), closes [#162](#162) [#388](#388)
* **recall:** make the canonical order total and let the caveat follow the survivors ([b2ee863](b2ee863)), closes [#396](#396)
* **status:** sum per-message receipts; session-wide means session-wide ([208a73f](208a73f)), closes [#394](#394)

### Features

* **status:** bill the plugin's own model calls and the session's completion tokens ([c046297](c046297)), closes [#387](#387) [#211](#211)
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.24.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant