Skip to content

fix(dedupe): vacate the copy a recall row beat, instead of returning it twice - #467

Merged
abogartz merged 2 commits into
mainfrom
fix/460-recall-duplicate-slot
Nov 21, 2026
Merged

abogartz merged 2 commits into
mainfrom
fix/460-recall-duplicate-slot

Conversation

@ocsi-fixer

@ocsi-fixer ocsi-fixer Bot commented Nov 21, 2026

Copy link
Copy Markdown

The defect

memory_recall returned the same text in two of three slots and dropped a distinct match. Reproduced on main @ c48aea6 (v0.33.7) through the tool harness.

dedupeWindowGrouped stops its kept-row scan at the first collapse clash (break). A candidate can win more than one clash in the same pass, and the two classes differ. With the reporter's fixture — seed order A, B, D, B, P, Q, every row scoring 3 for the query release, so the stable sort keeps store order:

step candidate clash found action window
1 A none push A
2 B (A + staging) addition vs A push (grouping keeps both) A, B
3 D (rollbacks for documentation) substitution vs A newer wins the slot D, B
4 B again substitution vs D — break, never reaches the B behind it newer wins the slot B, B
5 P none push B, B, P

The replacement at step 4 was never re-checked against the rest of the window, so it landed beside its own exact copy. Q is the row that pays for the wasted slot.

The fix

src/recall/dedupe.ts. With grouping enabled the scan already walks every kept row; it now records every collapse clash rather than the first one. A candidate that rides takes the first collapsed slot and vacates the others it won, so the freed slot is refilled by the next distinct row. A candidate that loses to a newer kept row still does not ride, and vacates nothing.

The window becomes B, P, Q — the acceptance test in the ticket, in that order.

The rollback path is untouched. With OPENCODE_MEMORY_AMBIGUOUS=0 the scan still stops at the first clash, byte-for-byte the previous rule; the fixture returns B, P, Q there too, as it already did.

Evidence

Two tests, each pinned against a vacuous pass by asserting the pair classes (substitution for the row it meets first, identical for the copy behind it):

  • test/recall/dedupe-window.test.ts — the rule at the unit level, grouping on and off.
  • test/recall/dedupe-tool.test.ts — the same fixture through memory_recall, where the slot is the thing that matters, plus the OPENCODE_MEMORY_AMBIGUOUS=0 arm.

Both new assertions fail on main and pass here:

(fail) memory_recall additive clash > a copy that wins a clash returns once and costs no distinct row its slot
(fail) dedupeWindowGrouped > a row that wins two clashes at once leaves one copy, not two
 42 pass  2 fail

After the fix:

  • bun test test/recall/ — 175 pass, 0 fail
  • bun run test — 1621 pass, 21 skip, 0 fail
  • bun run typecheck — exit 0
  • bun run lint — exit 0 (warning count unchanged from baseline)
  • bun run lint:comments — clean

Not covered

bench/runners/dedup-live-replay.ts reads the live store and is not a CI job, so it was not run here. It measures which pairs the threshold suppresses; this change only alters which slot a won clash is written into, so the suppression set is unchanged.

Fixes #460.

…it twice

A candidate can win more than one collapse clash in a single pass: it may be
a substitution of the kept row it meets first and an exact copy of another row
already in the window. The scan stopped at the first clash, so the candidate
took that slot and left its own copy standing beside it. The window then
returned the same text twice and a distinct matching row outside never arrived.

With grouping enabled the scan now walks the whole window, and a candidate that
rides vacates every collapse slot it won besides the one it takes, so the freed
slot is refilled by the next distinct row. A candidate that loses to a newer
kept row still does not ride, and vacates nothing.

With grouping disabled the scan still stops at the first clash, so the rollback
path is byte-for-byte the previous rule.
@ocsi-fixer

ocsi-fixer Bot commented Nov 21, 2026

Copy link
Copy Markdown
Author

Branch pushed with the merge gate green: 1642 unit tests and 39 real-host e2e tests, 0 fail. The two new assertions fail on main and pass here.

@ocsi-fixer
ocsi-fixer Bot requested a review from abogartz as a code owner November 21, 2026 15:55

@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.

I reported #460 and tested the bot’s fix on Windows at a9c0b7d. The original window regression passes. I found two cases where the replacement still differs from the PR’s stated behavior.

Using the A, B, D, printer (P), and calendar (Q) rows from the new test, I called dedupeWindowGrouped with ranked input A, P, B, D, Q, limit 4, threshold 0.8, grouping enabled:

  • With timestamp seconds 4, 1, 2, 3, 5, D loses to newer A and beats older B. I got A, P, D, Q. The mixed-win rule in the PR body predicts A, P, B, Q. The scan sets outranked, but the replacement at line 321 runs before that flag is checked, so B is overwritten anyway.
  • With timestamp seconds 0, 1, 2, 3, 5, D wins both clashes. I got P, D, Q instead of D, P, Q. Each clash overwrites collapse, so D takes the last clashing slot and P moves ahead of it. That changes the top recall result.

Could the grouping-enabled path decide whether the candidate rides before changing any slot, then put a winner in the first clashing slot and remove later beaten slots? These two inputs would cover both branches alongside the original fixture.

@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.

I prepared a patch against a9c0b7d for the two cases in my review. It defers all slot changes until the candidate has won every collapse comparison, including the timestamp tie case. The winner takes the earliest matching slot and later slots are removed from right to left. Grouping disabled still stops at the first clash.

On native Windows with Bun 1.4.4, the three new regression cases failed before the patch and passed afterward. All 178 recall tests and typecheck passed. I verified the diff applies to this head. The full repository format check reported errors outside the changed files.

Applicable diff with regression tests
diff --git a/src/recall/dedupe.ts b/src/recall/dedupe.ts
index d29227b..bffc52b 100644
--- a/src/recall/dedupe.ts
+++ b/src/recall/dedupe.ts
@@ -259,7 +259,7 @@ export function dedupeWindowGrouped(
     return p;
   };
   const kept: number[] = [];
-  for (let i = 0; i < ranked.length && kept.length < limit; i++) {
+  candidates: for (let i = 0; i < ranked.length && kept.length < limit; i++) {
     if (tokensOf(i).size < MIN_CONTENT) {
       kept.push(i);
       continue;
@@ -271,19 +271,7 @@ export function dedupeWindowGrouped(
     // to its own exact copy later in it, and grouping on the first match spends
     // a slot on a duplicate while a distinct row waits outside — the exact loss
     // this pass exists to prevent. A collapse therefore outranks a group.
-    let addition = -1; // first clash that names something new
-    let collapse = -1; // a clash that is a copy or a correction
-    // Every collapse clash the candidate wins, not just the first. A row can
-    // beat two kept rows in one pass and the two classes differ: it may be a
-    // substitution of one and an exact copy of another. Taking only the first
-    // slot leaves the copy it beat standing beside it, so the window returns
-    // the same text twice and a distinct row outside never arrives.
-    const beaten: number[] = [];
-    // Collapse slots emptied because the candidate took their row's meaning.
-    const vacated = new Set<number>();
-    // A kept row the candidate loses to. One loss is enough to keep the
-    // candidate out: the newest copy is the one that rides.
-    let outranked = false;
+    const collapseSlots: number[] = [];
     for (const pos of kept.keys()) {
       const k = kept[pos]!;
       if (
@@ -299,40 +287,23 @@ export function dedupeWindowGrouped(
         groupAdditions &&
         classifyPair(tokensOf(k), tokensOf(i)) === "addition"
       ) {
-        if (addition < 0) addition = pos;
         continue;
       }
-      if (!groupAdditions) {
-        collapse = pos;
-        break;
-      }
-      collapse = pos;
-      if (ranked[k]!.ts >= ranked[i]!.ts) outranked = true;
-      else beaten.push(pos);
+      // A tie keeps the existing row. Wait until every clash is decided
+      // before replacing anything in the window.
+      if (ranked[k]!.ts >= ranked[i]!.ts) continue candidates;
+      collapseSlots.push(pos);
+      if (!groupAdditions) break;
     }
-    if (
-      collapse < 0 &&
-      addition >= 0 &&
-      groupAdditions &&
-      kept.length < limit
-    ) {
+    if (collapseSlots.length === 0) {
       kept.push(i);
-    } else if (collapse >= 0) {
-      if (ranked[i]!.ts > ranked[kept[collapse]!]!.ts) kept[collapse] = i;
-      // The slots the candidate wins against must go with the slot it takes,
-      // and only when the candidate actually rides: a vacated slot is refilled
-      // by the next distinct row, which is the whole point of the pass.
-      if (!outranked && kept[collapse] === i && beaten.length > 1) {
-        for (const pos of beaten) {
-          if (pos !== collapse) vacated.add(pos);
-        }
-      }
-    } else if (addition >= 0) {
-      if (ranked[i]!.ts > ranked[kept[addition]!]!.ts) kept[addition] = i;
-    } else kept.push(i);
-    // Removed after the branch: `collapse` and `beaten` are positions inside
-    // `kept`, and splicing mid-scan would move them.
-    for (const pos of [...vacated].sort((a, b) => b - a)) kept.splice(pos, 1);
+      continue;
+    }
+    kept[collapseSlots[0]!] = i;
+    // Preserve the first slot and remove later clashes from right to left.
+    for (let j = collapseSlots.length - 1; j > 0; j--) {
+      kept.splice(collapseSlots[j]!, 1);
+    }
   }
   const rows = kept.map((i) => ranked[i]!);
   // Families are recomputed from the window instead of accumulated during the
diff --git a/test/recall/dedupe-window.test.ts b/test/recall/dedupe-window.test.ts
index 380bcd5..efc1d72 100644
--- a/test/recall/dedupe-window.test.ts
+++ b/test/recall/dedupe-window.test.ts
@@ -336,6 +336,26 @@ describe("dedupeWindowGrouped", () => {
     expect(out.groups).toEqual([]);
   });
 
+  test.each([
+    ["older", "2026-01-01T00:00:00Z", true],
+    ["equally recent", "2026-01-01T00:00:03Z", false],
+    ["newer", "2026-01-01T00:00:04Z", false],
+  ] as const)(
+    "multi-clash preserves rank when the first row is %s",
+    (_, ts, wins) => {
+      const first = mem("release", CHECKLIST, ts);
+      const unrelated = printer("2026-01-01T00:00:01Z");
+      const staging = mem("release", WITH_STAGING, "2026-01-01T00:00:02Z");
+      const candidate = mem("release", WITH_ROLLBACKS, "2026-01-01T00:00:03Z");
+      const tail = calendar("2026-01-01T00:00:05Z");
+      const ranked = [first, unrelated, staging, candidate, tail];
+      const out = dedupeWindowGrouped(ranked, 4, DEFAULT_THRESHOLD, true);
+      expect(out.rows).toEqual(
+        wins ? [candidate, unrelated, tail] : [first, unrelated, staging, tail],
+      );
+    },
+  );
+
   test("grouping spends slots and never exceeds the limit", () => {
     const base =
       "the ingest worker retries a failed batch three times then parks it on the dead letter queue";

Two orderings of the same fixture still disagreed with the intended rule.

A candidate that wins one collapse clash and loses another wrote the slot it
won before the loss was consulted, so it displaced a row it never outranked.
The ride decision now happens first and no slot changes when the candidate
does not ride.

Each clash also overwrote the recorded collapse position, so a winner took the
LAST clashing slot rather than the first. That moved an unrelated row ahead of
the winner and changed the top recall result. The first clashing slot is now
kept, so the winner holds the rank of the row it replaced.
@ocsi-fixer

ocsi-fixer Bot commented Nov 21, 2026

Copy link
Copy Markdown
Author

Both cases reproduce and both are fixed in 75b6e30. Your reading of the mechanism was exactly right on each.

Case 1 — wins one clash, loses another. The scan set outranked but the assignment kept[collapse] = i ran before anything consulted it, so the candidate displaced the older row it beat even though a newer row elsewhere in the window had already beaten it back. The ride decision now happens before any slot is touched:

const rides = !outranked && ranked[i]!.ts > ranked[kept[collapse]!]!.ts;
if (rides) {
  kept[collapse] = i;
  for (const pos of beaten) if (pos !== collapse) vacated.add(pos);
}

Case 2 — wins both. Each clash overwrote collapse, so the winner landed in the last clashing slot and an unrelated row moved ahead of it. collapse is now assigned only when it is still -1, so the winner takes the first clashing slot and keeps the rank of the row it replaced.

Both of your inputs are now tests, with the same A, P, B, D, Q ranking at limit 4:

timestamps expected a9c0b7d 75b6e30
4, 1, 2, 3, 5 A, P, B, Q A, P, D, Q A, P, B, Q
0, 1, 2, 3, 5 D, P, Q P, D, Q D, P, Q

Both fail at a9c0b7d and pass here, so they pin the two branches rather than restating the original fixture. The original A, B, D, B, P, Q fixture and the OPENCODE_MEMORY_AMBIGUOUS=0 arm are unchanged, and the grouping-off path still stops at the first clash.

Full suite at 75b6e30: 1623 pass, 21 skip, 0 fail. Typecheck, lint and comment-lint clean.

@ocsi-fixer

ocsi-fixer Bot commented Nov 21, 2026

Copy link
Copy Markdown
Author

No behaviour change on a real store

Measured at 75b6e30 against origin/main, on a copy of the maintainer's own store. No row content was recorded anywhere: the harness compares sha256[:10] values and prints aggregates.

352 recall queries reconstructed from the store's own hit ledger, run through the shipped memory_recall handler on two identical store copies — one on origin/main, one on this branch — same order, same starting ledger state.

arm queries rows returned duplicate slots
origin/main 352 at limit 5, 352 at limit 3 1445 / 871 0 / 0
this branch 352 at limit 5, 352 at limit 3 1445 / 871 0 / 0

Windows identical: 704 / 704. No window shape differs.

The store explains why: 1685 injectable rows across 298 scopes, 0 exact duplicates, and 2 of 80,005 same-scope comparable pairs reach the 0.8 threshold. The triple this pass exists to catch — an additive pair plus one row collapsing into both — occurs 0 times.

So the fix is a no-op on the data available locally, and the regression fixtures are doing the work. That is the expected outcome for a bug that needs a duplicate row to fire, and it is worth recording so a reviewer does not read the null result as an untested change.

@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.

I re-tested 75b6e30 on Windows with Bun 1.4.4 after reporting #460 and supplying the earlier patch. Both findings from my review are resolved. I also ran 18 variations of the five-row fixture, reversing the order of the two clashing rows and giving each an older, equal, or newer timestamp relative to the candidate. A tie with either kept row preserved the window. When the candidate beat both, it took the first slot and the unrelated row kept its relative order. All 177 recall tests passed.

@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.

Verdict: approve. The fix does what it claims and I could not break it. One latent defect sits in the same lines and should get a follow-up ticket rather than block this.

What I verified independently

  • Both orderings from the review thread now produce A, P, B, Q and D, P, Q at 75b6e30.
  • vacated is not a dead write: it is consumed at src/recall/dedupe.ts:338, spliced high position to low, so indices stay valid.
  • The grouping-off path is untouched — collapse = pos; break; still stops at the first clash, so OPENCODE_MEMORY_AMBIGUOUS=0 remains a true rollback.
  • Families are recomputed from kept after the splice, so a marker cannot name a row that no longer rides. That ordering is load-bearing and is not obvious from the diff; the comment covers it.

Finding 1 — recency is decided by string comparison, not by time (medium, latent)

Three sites compare timestamps with > / >=:

if (ranked[k]!.ts >= ranked[i]!.ts) outranked = true;
const rides = !outranked && ranked[i]!.ts > ranked[kept[collapse]!]!.ts;
if (ranked[i]!.ts > ranked[kept[addition]!]!.ts) kept[addition] = i;

src/core/cmp-ts.ts exists specifically because this does not hold across serializations. Its own comment: "a legacy second-precision stamp (…:01Z) and a millisecond stamp (…:01.000Z) for the same instant order wrong as strings, which would silently mis-rank the recency tie-break."

Demonstrated against this branch — two rows, byte-identical content, Date.parse equal, limit=2:

kept stamp candidate stamp winner
00:00:01Z 00:00:01.000Z KEPT
00:00:01.000Z 00:00:01Z CANDIDATE
00:00:01.000Z 00:00:01.000Z KEPT

The third row is the correct behaviour: a tie does not ride. The second row disagrees with it for the same instant, because 'Z' (0x5A) > '.' (0x2E). Which copy survives depends on how the stamp was serialized, and the loser is the row the pass exists to protect.

Reproducer, self-contained:

const CAND = "the release build requires node python and docker installed on the runner machine";
const kept = row("2026-01-01T00:00:01.000Z", CAND);
const cand = row("2026-01-01T00:00:01Z", CAND);
const other = row("2026-01-01T00:00:00.000Z", "printer driver needs a kernel module reload before it accepts jobs");
dedupeWindowGrouped([kept, cand, other], 2, 0.8); // -> candidate, not kept

Why this is not a blocker: the maintainer's store is uniform — 2144 of 2144 row stamps use millisecond serialization — so nothing today arms it. It is armed by a legacy row, a store import, or a hand-edited line, and the failure is silent and changes the top result. This PR rewrites exactly these comparisons, so it is the natural place to spend the three-character fix:

cmpTs(ranked[i]!.ts, ranked[kept[collapse]!]!.ts) > 0

If you would rather keep the diff scoped, file it as a follow-up and I will not hold the merge.

Finding 2 — a vacated slot is not guaranteed to refill (observation, pre-existing design)

The comment says a winner's other won slots are removed "so the scan refills it". The scan is a single forward pass over ranked, so a vacated slot can only be filled by a candidate that appears later than the one that vacated it. A distinct row that was already passed and rejected earlier in the same pass is not reconsidered, so the window can come back one row short while a legitimate candidate sits behind the scanner.

That is the one-pass design, not a regression, and the alternative is a second pass on every query. Worth one sentence in the comment so the next reader does not treat refill as guaranteed.

Test gaps

  • No fixture with mixed timestamp serializations (Finding 1).
  • No fixture where a candidate rides and vacates, and a later distinct row refills the freed slot — the refill path in the comment is currently untested.

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

Copy link
Copy Markdown

🎉 This PR is included in version 0.33.8 🎉

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.

Recall can return the same text twice and drop a distinct match at the window limit

2 participants