Repository navigation
fix(dedupe): vacate the copy a recall row beat, instead of returning it twice - #467
Conversation
…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.
|
Branch pushed with the merge gate green: 1642 unit tests and 39 real-host e2e tests, 0 fail. The two new assertions fail on |
WhollyMindless
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
|
Both cases reproduce and both are fixed in Case 1 — wins one clash, loses another. The scan set 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 Both of your inputs are now tests, with the same
Both fail at Full suite at |
No behaviour change on a real storeMeasured at 352 recall queries reconstructed from the store's own hit ledger, run through the shipped
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
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, QandD, P, Qat75b6e30. vacatedis not a dead write: it is consumed atsrc/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, soOPENCODE_MEMORY_AMBIGUOUS=0remains a true rollback. - Families are recomputed from
keptafter 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 keptWhy 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) > 0If 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.
|
🎉 This PR is included in version 0.33.8 🎉 The release is available on: Your semantic-release bot 📦🚀 |
The defect
memory_recallreturned the same text in two of three slots and dropped a distinct match. Reproduced onmain@c48aea6(v0.33.7) through the tool harness.dedupeWindowGroupedstops 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 orderA, B, D, B, P, Q, every row scoring 3 for the queryrelease, so the stable sort keeps store order:AAB(A+staging)additionvsAA, BD(rollbacksfordocumentation)substitutionvsAD, BBagainsubstitutionvsD— break, never reaches theBbehind itB, BPB, B, PThe replacement at step 4 was never re-checked against the rest of the window, so it landed beside its own exact copy.
Qis 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=0the scan still stops at the first clash, byte-for-byte the previous rule; the fixture returnsB, P, Qthere too, as it already did.Evidence
Two tests, each pinned against a vacuous pass by asserting the pair classes (
substitutionfor the row it meets first,identicalfor 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 throughmemory_recall, where the slot is the thing that matters, plus theOPENCODE_MEMORY_AMBIGUOUS=0arm.Both new assertions fail on
mainand pass here:After the fix:
bun test test/recall/— 175 pass, 0 failbun run test— 1621 pass, 21 skip, 0 failbun run typecheck— exit 0bun run lint— exit 0 (warning count unchanged from baseline)bun run lint:comments— cleanNot covered
bench/runners/dedup-live-replay.tsreads 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.