Skip to content

feat(dedup): keep an additive clash instead of collapsing it - #450

Merged
abogartz merged 5 commits into
mainfrom
feat/dedup-addition-groups
Nov 19, 2026
Merged

abogartz merged 5 commits into
mainfrom
feat/dedup-addition-groups

Conversation

@abogartz

@abogartz abogartz commented Nov 19, 2026 •

Copy link
Copy Markdown
Owner

What changes

A near-duplicate clash is two different situations that happen to share a score. Either one row corrected the other, or the two rows name two things that both hold. The pass treats both as copies.

src/recall/dedupe.ts now classifies a clash by its leftover token sets before deciding:

leftovers meaning behavior
none on either side one row typed twice collapse to the newer (unchanged)
one side wholly contained the shorter row names something the longer one does not restate keep both, report the pair
a leftover on each side read as the same statement about a changed world collapse to the newer (unchanged)

Only the middle row is decidable from containment, and only that one changes behavior. The third row
is an interpretation, and its absence of containment is not evidence of a correction: two instructions
naming two scripts that both exist — bun run bench:recall and bun run bench:write — leave a
leftover on each side, score 0.882, and the older is dropped. That predates this PR and this PR does
not fix it; docs/adr/0002-window-dedup.md records it as the rule's remaining limitation.

The threshold is untouched. The default stays 0.8, and the recency rule from §17 is unchanged.

Why

Two rows in the maintainer's store, both active and injectable:

BabylonDocs build command: run "npm run build" from the repo root (package.json).
BabylonDocs build:example-images command: run "npm run build:example-images" from the repo root (package.json).

They score 0.82 because build:example-images tokenises to contain build. Every shipped guard passes on them — both above MIN_CONTENT, same polarity, identical dropped chunks — so the pass deletes the plain build command and a session asking how to build is told only about the example-images target.

Raising the threshold was measured and rejected: the pair worth releasing scores 0.8235 and the changed-fact pair pinned in test/dedupe-tool.test.ts scores 0.8333, so any separating constant is a window one hundredth wide fitted to two observations. The difference between these two cases is not in the amount of overlap. It is visible in the shape of what is left over.

Measured on the live store

Replayed over 1,330 active rows in 241 scopes at window 5, comparing grouping off against grouping on:

rows suppressed — grouping OFF 817   ON 816
slots used      — grouping OFF 513   ON 514  (+1)
groups reported — 1

One suppression reversed, one extra slot of 514, and it is the pair above. Nothing else in the store is
classified as additive.

Re-run after the collapse-outranks-group fix (the store grew in between, so both numbers move
together): 515 slots with grouping off, 516 with it on, 1 group, and no window holds a
byte-identical pair
— the invariant that finding was about, checked across every scope.

Guards stay load-bearing

classifyPair compares token sets only, so late 0 and late 1 classify as a copy — words() drops chunks of length ≤ 2, and that is where single-digit facts hide. The short-chunk guard, not the classifier, keeps them apart, and a test pins both halves of that so a later change cannot mistake the classifier for a replacement.

The marker

A kept group with no explanation swaps one wrong deletion for an unexplained duplicate, so memory_recall appends one line per family, modelled on conflictLine() in src/recall/conflicts.ts: the rows, the tokens each one carries that none of the others do, and an Action.

A family is a connected component over the additive relation, not a pair. Twenty nested same-scope rows make every pair additive, and a pair-per-marker renderer emitted 10 lines and 2,050 characters at limit 5, and 103 lines and 22,771 characters at limit 20 — all repeating the same Action. Components give 1 line and 204 characters, and 1 line and 262. No cap is needed: each side lists what that member has that none of the others have, so a nested chain prints one side (every row but the largest is contained in the union of the rest), and the six-token cap still applies per side. Line length grows with vocabulary, not with family size. Unlike CONFLICT the verdict is deliberately open — the distinction that decided it is visible in the token sets, not in the prose, so the reader picks.

Rendered from the live store, this is what a session now sees:

- [2026-10-18] pattern/BabylonDocs: BabylonDocs build:example-images command: run "npm run build:example-images" from the repo root (package.json).
- [2026-10-18] pattern/BabylonDocs: BabylonDocs build command: run "npm run build" from the repo root (package.json).
AMBIGUOUS (BabylonDocs): rows 4 and 5 share shape but neither restates the other — only in 4: example-images, example, images. Action: neither supersedes the other. Pick by what you are actually doing; if both apply, use both.

The plain build command is back in the window, and the reason the two coexist is on the page.

Two guards on the render. The token list is capped at 6 with the withheld count printed, so a pair that reaches the threshold while differing widely cannot dump its vocabulary into a result. And the scope is store text, so it is flattened like every other rendered field — one row is one line, and a stored newline cannot forge a section here either. A test pins both.

The tool path is a plain result string, so unlike the CONFLICT path this touches no prompt-cache key and no byte budget.

Tests

Twenty new cases:

  • classifyPair — each class, empty-set edge, and the digit trap above.
  • The build pair returns both rows and one group. Its Jaccard is asserted >= DEFAULT_THRESHOLD so a tokenizer change cannot silently make the test vacuous.
  • The regression that matters: the runbook friday/monday pair still collapses to the newer row, and the stale row is absent. Grouping must not re-admit a corrected fact.
  • Exact copies still collapse; the flag-off path is the plain slice with no groups; ordering follows the ranking, never the grouping.
  • A cap test: five additive rows at limit: 3 never exceed three.
  • A collapse outranks a group. With plain build, example-images, a byte-identical copy of
    example-images and a distinct prerequisite at limit: 3, the copy must take the example-images slot
    and the prerequisite must ride. Grouping on the first clash kept both copies and dropped the
    prerequisite — the loss this pass exists to prevent, reintroduced by the grouping rule.
  • Groups are recomputed from the final window, so a marker can never name a row that was replaced in
    its slot. Through the handler: three distinct rows and exactly one AMBIGUOUS line.
  • A group carries the Memory objects, not window positions — a later clash overwrites a slot, and a group keyed on that slot would re-point at whatever landed there.
  • ambiguousLine — wording, position numbering, the token cap and withheld count, the both-sides case, and the newline contract.
  • Grouping off preserves the first-match rule. The reviewer's A/B/C fixture — A
    additive with C, substituting against B — must return C then B with grouping off and
    A then C with it on.
  • A nested chain is one family. Twenty mutually additive rows yield one group of
    five at limit: 5, not ten pairs, and the handler prints one Action: line.
  • Through the real handler: both commands return with the marker; OPENCODE_MEMORY_AMBIGUOUS=0 collapses them and prints no marker; a corrected fact returns one row and no marker, so a stale row cannot come back wearing one.

bun test ./test/ 1528 pass / 21 skip / 0 fail, bun run test:e2e 35 pass, bun run typecheck clean, comment-lint clean over 100 added lines.

Rollback

OPENCODE_MEMORY_AMBIGUOUS=0 restores the collapse for every class and emits no marker, and restores the original scan: it stops at the first clash, so which row wins the timestamp comparison is unchanged from before this PR. That mattered — walking the whole window to prefer a collapse initially ran with grouping off too, and the pair chosen decides which row survives. Verified differentially against origin/main's dedupeWindow over 1,200 randomized window and limit combinations: 23 divergences before the fix, 0 after. Independent of OPENCODE_MEMORY_DEDUP: that flag turns the whole pass off; this one only chooses what a clash does when the pass is on.

Not in this PR

Nothing is left half-wired. Two follow-ups this exposes rather than settles: the addition class rests on one live example plus the reasoning, so a second store is the real prerequisite for trusting it (see #449), and the write-gate gap that let a cross-type duplicate through in the first place is a separate defect named in bench/dedup-live-results.md.

Context: #448 (the defect), #449 (the design discussion and the POC that produced this rule).

A near-duplicate clash is two different situations that share a score. Either
one row corrected the other, or the two rows name two things that both hold.
The pass treats both as copies, so a scope holding two commands loses one: the
live pair `npm run build` and `npm run build:example-images` reaches 0.82
because the longer identifier tokenises to contain the shorter one, and the
plain build command disappears from the returned window.

Classify the clash by its leftover token sets. Nothing left over either way is
a copy; one side wholly contained names something the partner does not restate,
so both rows are kept and reported as a group; a leftover on each side is the
same statement about a changed world, and the newer row still takes the slot.

No threshold change. On the maintainer's store this reverses exactly one
suppression and spends one extra slot of 514. The recency rule and every
existing guard are unchanged, and the short-chunk guard stays load-bearing:
"late 0" and "late 1" classify as a copy on tokens alone.

OPENCODE_MEMORY_AMBIGUOUS=0 restores the collapse for every class.
A kept group was computed and not explained, which swapped one wrong deletion
for an unexplained duplicate. `memory_recall` now appends one line per group,
modelled on conflictLine: both rows, the tokens only one of them carries, and
an Action. Unlike CONFLICT the verdict is deliberately open, because the
distinction that decided it is visible in the token sets and not in the prose.

The token list is capped so a pair that reaches the threshold while differing
widely cannot dump its vocabulary into the result, and the withheld count is
printed. The scope is store text and is flattened like every other rendered
field, so a stored newline cannot forge a section here either.

Rendered from the live store:

  pattern/BabylonDocs: BabylonDocs build:example-images command: run ...
  pattern/BabylonDocs: BabylonDocs build command: run "npm run build" ...
  AMBIGUOUS (BabylonDocs): rows 4 and 5 share shape but neither restates the
  other - only in 4: example-images, example, images. Action: neither
  supersedes the other. Pick by what you are actually doing; if both apply,
  use both.

bun test ./test/ 1528 pass / 21 skip / 0 fail, test:e2e 35 pass.

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

An exact duplicate can now take the last recall slot. At 8321e82 I seeded four same-scope rows in this order: the plain build command from the PR, the example-images command, a byte-identical copy of the example-images command with a later timestamp, and a distinct build prerequisite. Querying the real memory_recall handler for BabylonDocs build command with limit 3 returned plain / examples / examples, plus two AMBIGUOUS lines. All four matched the query. The prerequisite fell out of the window.

In dedupeWindowGrouped, the second copy matches the plain command as an addition, then the loop breaks before reaching its exact match. Could the scan check the rest of the kept rows for a copy before allocating another slot? The regression expectation here is plain / newest examples / prerequisite, with one marker.

A separate limit on the interpretation of “substitution”: I seeded otherwise identical instructions naming this repository’s bun run bench:recall and bun run bench:write. The score was 0.882, the class was substitution, and the handler returned only the newer write command. These scripts run different benchmarks and both exist. This behavior predates the PR. Qualifying the table’s “changed world” description would distinguish that remaining limitation from the build/example-images case this PR fixes.

Two defects in the grouping rule, both from review.

An exact copy could take the last slot. The clash scan stopped at the first
match, so with plain build, example-images, a byte-identical copy of
example-images and a distinct prerequisite, the copy clashed with the plain
command as an addition and was kept beside it. Two identical rows rode and the
prerequisite fell out - the loss this pass exists to prevent, reintroduced by
the grouping rule. The scan now walks every kept row and prefers a collapse:
an additive clash is only kept when nothing in the window is a copy or a
correction of the incoming row.

Groups are recomputed from the final window instead of accumulated during the
pass. A collapse replaces a row in place, so a group recorded earlier named a
row that no longer rode, and recall dropped its marker because the row was not
in the result - the pair stayed unexplained. Recomputing costs a handful of
comparisons over cached token sets and makes the marker describe what the
reader is actually shown.

Also qualifies `substitution`: only `addition` is decidable from containment.
Two instructions naming two scripts that both exist (bun run bench:recall and
bun run bench:write) leave a leftover on each side, score 0.882, and the older
is dropped. That predates this rule and is now stated as a limitation rather
than described as a changed world.

Replayed over the live store: +1 slot, 1 group, and no window holds a
byte-identical pair. bun test ./test/ 1530 pass / 21 skip / 0 fail.
The code comment points at this ADR for the limitation, so the ADR has to
state it. Only `addition` is decidable from containment. Two instructions
naming two scripts that both exist leave a leftover on each side, score
0.882, and the older is dropped -- review found this with
bun run bench:recall and bun run bench:write. Recorded as the rule's
remaining limitation rather than described as a changed world.
@abogartz

Copy link
Copy Markdown
Owner Author

Both confirmed. Fixed at 4588937, with the limitation written down at cac5dca. The first one is a correctness regression the grouping rule introduced, and your fixture found a second defect behind it.

1. The exact copy took the last slot. Reproduced at 8321e82 with your four rows:

kept: [ build command, build:example-images command, build:example-images command ]
distinct rows kept: 2 of 3

The cause is exactly what you named — break on the first clash. Fixed by walking every kept row and letting a collapse outrank a group: the scan records the first additive clash but keeps looking, and if anything later in the window is a copy or a correction of the incoming row, that wins. An additive clash is only kept when nothing in the window is a collapse. Your regression expectation now holds, at both layers — dedupeWindowGrouped returns plain / newest copy / prerequisite, and the memory_recall handler returns three distinct rows with one marker.

2. Your fixture exposed a second bug once the first was fixed. With the copy collapsing correctly, the AMBIGUOUS line disappeared from the handler output. Groups were accumulated during the pass, so the group still named the original example-images row — which had just been replaced in its slot by the copy — and the handler drops a marker whose rows are not in the result. The pair was left unexplained, which is the whole point of the marker. Groups are now recomputed from the final window: a handful of comparisons over cached token sets, and the marker can only ever describe rows the reader is actually shown. The window-level test pins that, including the group identity:

expect(out.rows).toEqual([BUILD, copy, prereq]);
// The group names the rows that actually ride, not the pair the pass first saw.
expect(out.groups).toEqual([[BUILD, copy]]);

3. The substitution reading. Agreed, and the qualifier is in both places a reader would look. classifyPair's doc comment now says only addition is decidable from containment, and that its absence is not evidence of a correction, with your case named: bun run bench:recall and bun run bench:write leave a leftover on each side, score 0.882, and the older is dropped. docs/adr/0002-window-dedup.md gained a section saying the same, because the comment points there — a pointer at a document that does not say the thing is worse than no pointer. It states plainly that the split does not fix this and why it cannot: the pass has no way to learn from a row's text that both scripts are real. That is also the argument for the marker existing — where the classifier can see two readings are possible, it says so instead of choosing.

Live-store replay after the fix: +1 slot (515 → 516), 1 group, and no window holds a byte-identical pair — the invariant your finding is really about, checked across every scope rather than asserted.

bun test ./test/ 1530 pass / 21 skip / 0 fail, comment-lint clean over 126 added lines, merge gate green on push.

Worth saying what these two have in common: both were the grouping rule breaking the rule's own purpose. The pass exists so distinct rows keep slots, and my first version spent a slot on a duplicate and then failed to explain the pair that cost it. Neither showed up in the 20 tests I wrote, because every one of them had one additive pair and one distinct row — the failure needs a duplicate of a grouped row, which only appears if you think to seed one.

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The duplicate-slot regression is covered at both the window and handler layers now. All 42 focused tests passed at cac5dca, including the replacement copy retaining its marker. I found two effects of the revised clash scan:

  1. The rollback flag can change which facts survive. I compared the pre-PR deduper with OPENCODE_MEMORY_AMBIGUOUS=0 at this head, same ranking and increasing timestamps. A contains “alpha bravo charlie delta echo foxtrot golf hotel”, B replaces “alpha” with “india” and appends “juliet kilo”, and C is A plus “juliet kilo”. At limit 5 and threshold 0.8, the pre-PR result is C/B. The flag-off result is A/C: the scan skips the earlier additive match with A and gives the later substitution match with B priority even when grouping is disabled. Could flag-off preserve the original first-match rule?
  2. The final-window pass emits a marker for every overlapping pair. With 20 same-scope synthetic rows (80 common tokens, each row adding one more), the grouped-window function and marker renderer produced 190 marker lines totaling 45,257 characters for 20 facts. At the default limit of 5 it produced 10 markers. The six-token cap limits each line, but all repeat the same Action. One representative link per additional row, or a per-window marker cap with an omitted count, would bound the explanation while retaining the facts.

…e marker

Two effects of the revised clash scan, both from review.

Rollback changed which facts survived. Walking the whole window and preferring
a collapse ran even with grouping disabled, so an additive clash seen early
took priority over a substitution seen later -- and the pair chosen decides
which row wins on timestamp. A rollback flag that alters results is not a
rollback. With grouping off the scan now stops at the first clash, exactly as
before the feature. Verified differentially against origin/main's dedupeWindow
over 1,200 randomised window/limit combinations: 23 divergences before this
commit, 0 after.

Markers scaled with pairs, not with explanations. Twenty nested same-scope rows
made every pair additive, so the final-window pass emitted one line per pair:
measured on that fixture through the real handler, 10 lines and 2,050 marker
characters at limit 5, and 103 lines and 22,771 characters at limit 20 -- all
repeating the same Action. Groups are now connected components over the
additive relation, so a chain is one family and one line: 1 line and 204
characters at limit 5, 1 line and 262 at limit 20. Each side lists what that
member has that none of the others have, so a nested chain prints one side --
every row but the largest is contained in the union of the rest -- and the line
grows with vocabulary rather than size.

The component walk works in positions within `kept`, not row indices, and the
single map that crosses back is called out: getting it wrong names a row that a
later collapse replaced, which is the bug the recomputation exists to avoid.

Live store unchanged: +1 slot, 1 family, no window holds a byte-identical pair.
bun test ./test/ 1534 pass / 21 skip / 0 fail, test:e2e 35 pass.

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified both fixes at fe21276. I reran the three-row rollback fixture against the pre-grouping implementation: both kept C/B in the same order with grouping off. With grouping on, the nested five-row and twenty-row fixtures each retained all requested rows and returned one family for the renderer. The previous twenty-row result produced 190 marker lines. All 46 focused window, marker, and recall-handler tests passed, including the duplicate-copy case.

That resolves my change requests. The ADR also records the remaining limitation for parallel benchmark commands. My verification used disposable fixtures; I did not repeat the private-store measurement.

@abogartz

Copy link
Copy Markdown
Owner Author

Both confirmed and fixed at fe21276. The first one is the more serious: a rollback flag that changes results is not a rollback.

1. Flag-off no longer touches the scan. With groupAdditions false the scan stops at the first clash and lets recency decide, exactly as before the feature — an additive clash is only tracked as a candidate when grouping is on. Your A/B/C is in the suite: grouping off returns C then B, grouping on returns A then C, and the test says why the difference is allowed only in one direction.

I did not take that on assertion. I extracted dedupeWindow from origin/main and ran it against flag-off over 1,200 randomized window/limit combinations — random subsets of a shared vocabulary, each row either a strict superset (additive), a substitution, or a subset, with increasing timestamps:

  • at the head you reviewed: 23 divergences
  • after this commit: 0

That harness was throwaway; the divergence class it found is now pinned by the test. Worth saying the mechanism out loud: walking the whole window looked like a strictly local change to the grouping path, but the pair chosen decides which row wins the timestamp comparison, so it silently reached into the collapsed path too.

2. Markers now scale with families, not pairs. groups is connected components over the additive relation instead of every additive pair, and the renderer emits one line per component. Measured on your construction — 20 nested same-scope rows, through the real memory_recall handler:

limit before after
5 10 lines, 2,050 marker chars 1 line, 204 chars
20 103 lines, 22,771 marker chars 1 line, 262 chars

I chose components over a per-window cap because a cap throws information away and a component does not: the reader learns that rows 1–5 belong together, and every member is still named. Two properties keep the line bounded without one. Each side lists what that member has that none of the others have, so a nested chain prints one side — every row but the largest is contained in the union of the rest — and the existing six-token cap still applies per side. Line length grows with the family's vocabulary, not its size.

A bug the rewrite nearly shipped with, caught by the test from the last round: the component walk works in positions within kept, and my first version mapped those straight into ranked, so the family named a row a later collapse had already replaced — the exact defect the recomputation exists to prevent, reintroduced two lines from the comment explaining it. The map that crosses back is now the only one, and the comment says so.

Live store unchanged: +1 slot, 1 family, no window holds a byte-identical pair. bun test ./test/ 1534 pass / 21 skip / 0 fail, test:e2e 35 pass, comment-lint clean over 167 added lines, merge gate green on push.

@abogartz
abogartz merged commit ef45f6f into main Nov 19, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.33.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.

2 participants