Repository navigation
Replace Levenshtein-based LCS with snaking algorithm for cell matching - #41
Conversation
…matching Co-authored-by: Avni2000 <[email protected]>
… accuracy Co-authored-by: Avni2000 <[email protected]>
|
Needs a lot more work + probably human intervention. Barely improved with one or two cells in 02_* |
- Adds ID as strictest indicator - Snakes from nbdime
|
@coderabbitai would love a review. Everything looks fantastic on the testing end, and this has brought down cost of manual matching from almost half the conflicted cells to almost none. |
|
I'll get started on the review right away. 🧠 Learnings used✅ Actions performedReview triggered.
|
|
Important Review skippedBot user detected. To trigger a single review, invoke the You can disable this status message by setting the
📝 WalkthroughWalkthroughThe cellMatcher.ts module undergoes a comprehensive algorithmic overhaul, replacing hash and Levenshtein-based cell matching with a SequenceMatcher-inspired, snakes-based approach. A new LCS-driven pipeline computes contiguous matching blocks (snakes) between cell sequences. A multilevel matching framework uses cascading predicates to drive alignment. Output comparison logic is extended to handle diverse cell output types. Changes
Sequence Diagram(s)sequenceDiagram
participant matcher as Cell Matcher
participant lcs as LCS Pipeline
participant snakes as Snake Computation
participant predicates as Multilevel Predicates
participant compare as Output Comparison
matcher->>lcs: computeCompareGrid(base, current, incoming)
lcs->>lcs: computeLCSGrid(cell sequences)
lcs->>lcs: computeLCSIndices(LCS result)
lcs->>snakes: computeSnakesFromLCS(LCS indices)
snakes->>snakes: computeSnakesMultilevel(unmatched regions)
snakes->>predicates: Apply multilevel predicates<br/>(strict → moderate → approximate)
predicates->>compare: Validate matches via<br/>compareOutputStrict/Approximate
compare->>matcher: Return refined cell mappings
matcher->>matcher: sortMappingsByPosition(mappings)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/cellMatcher.ts (1)
697-736:⚠️ Potential issue | 🟡 Minor
matchConfidenceis always1.0in the no-base path, even for snaking-matched pairs.Line 710 assigns
matchConfidence: 1.0for pairs matched bymatchCellsToBase, but these could be approximate matches at level 0. Contrast this with lines 801–804 in the base-present path, which correctly usecomputeCellSimilarity. This makesmatchConfidenceunreliable for downstream consumers.Proposed fix — use actual similarity for the no-base case
if (incomingIdx !== undefined) { mappings.push({ currentIndex: currentIdx, incomingIndex: incomingIdx, - matchConfidence: 1.0, + matchConfidence: computeCellSimilarity( + currentCells[currentIdx], + incomingCells[incomingIdx] + ), currentCell: currentCells[currentIdx], incomingCell: incomingCells[incomingIdx] });
🤖 Fix all issues with AI agents
In `@src/cellMatcher.ts`:
- Around line 282-313: compareOutputStrict currently only iterates top-level
keys from x (xKeys) against the handled set, so extra non-handled keys present
in y are ignored; make the top-level key comparison symmetric by also
constructing yKeys (e.g., new Set(Object.keys(y))) and either (a) verify xKeys
and yKeys contain the same non-handled keys (compare sizes and membership) or
(b) iterate yKeys to ensure any key not in handled also exists in x and matches
via JSON.stringify equality the same way you do for xKeys; update the block that
defines handled and the for-loop so both x and y are checked for unexpected
extra keys before proceeding to the existing data comparison.
🧹 Nitpick comments (7)
src/cellMatcher.ts (7)
254-276:compareOutputApproximateignores non-text mime-type value differences fordisplay_data/execute_result.Lines 260–262 verify both outputs share the same set of keys, but lines 263–270 only compare values for
text/*mime types. Binary keys likeimage/pngcould have completely different content and still pass. This is likely intentional (matching nbdime's approach where binary diff isn't meaningful for approximate matching), but it means two cells with identical text output but different image output will be treated as "matching."Worth a brief inline comment documenting this design choice so future readers don't mistake it for a bug.
616-633: Short-string optimization may be too aggressive for notebooks with many distinct short cells.Lines 627–629: any two cells of the same type with sources both under 10 characters are considered matching. This means
# Aand# Z(both markdown) would match at level 0, which could misalign distinct short markdown headers.Since this is the loosest fallback level and mirrors nbdime's
compare_text_approximate, it's not a blocker — but consider whether a lower threshold (e.g., 5 chars) would reduce false positives in markdown-heavy notebooks without losing the intended benefit.
740-744: Inconsistent variable naming — mix of camelCase and lowercase concatenation.
baseTocurrent/baseToincomingandusedcurrentIndices/usedincomingIndicesbreak from the camelCase convention used elsewhere (matchCellsToBase,unmatchedCurrentCells,globalCurrentIdx, etc.).Naming consistency fix
- const baseTocurrent = matchCellsToBase(baseCells, currentCells); - const baseToincoming = matchCellsToBase(baseCells, incomingCells); + const baseToCurrent = matchCellsToBase(baseCells, currentCells); + const baseToIncoming = matchCellsToBase(baseCells, incomingCells); - const usedcurrentIndices = new Set<number>(); - const usedincomingIndices = new Set<number>(); + const usedCurrentIndices = new Set<number>(); + const usedIncomingIndices = new Set<number>();Update all references accordingly (lines 748–749, 763–764, 775, 782, 818).
746-765: Base-anchored matches always getmatchConfidence: 0.9regardless of actual match quality.Line 755 hardcodes
0.9for every base-anchored mapping, even though some may be ID-exact (level 3, deserving 1.0) and others may be approximate (level 0, deserving a lower score). This flattens the signal for downstream consumers (e.g., conflict detection thresholds).Consider threading the match level or computing actual similarity here, similar to the unmatched-pair path at lines 801–804.
Proposed approach
const mapping: CellMapping = { baseIndex: baseIdx, currentIndex: currentIdx, incomingIndex: incomingIdx, - matchConfidence: 0.9, // High confidence for base-anchored matches + matchConfidence: Math.max( + currentIdx !== undefined ? computeCellSimilarity(baseCells[baseIdx], currentCells[currentIdx]) : 0, + incomingIdx !== undefined ? computeCellSimilarity(baseCells[baseIdx], incomingCells[incomingIdx]) : 0 + ), baseCell: baseCells[baseIdx],
486-496: Array slicing in recursivecomputeSnakesMultilevelcreates copies at each level.Line 490 calls
A.slice(i0, i1)andB.slice(j0, j1)at every recursive level, andcomputeSnakesthen allocates the full comparison grid and LCS grid on these slices. With 4 levels and potentially many gap regions, this can compound for large notebooks.Not a blocker for typical notebook sizes (< ~100 cells), but if performance becomes a concern, consider passing index bounds through to
computeSnakesrather than slicing. This would avoid the per-level copy and grid reallocation.
566-577: Double cast throughunknownfor outputs.Lines 567–568 use
as unknown as Record<string, unknown>[]to castCellOutput[]. This pattern appears incellsStrictMatch,cellsModerateMatch, and the output comparison functions. SinceCellOutputis a structured type (fromtypes.ts), a targeted utility or a single assertion at the boundary would be cleaner than scattering double-casts.
595-604:cellsModerateMatchoutput-length check uses truthiness, not count equality.Line 599:
!!aOutputs.length !== !!bOutputs.lengthonly checks whether outputs are empty vs. non-empty. Two cells with 1 output and 5 outputs respectively would pass this gate and then fail insidecompareOutputsApproximate(which checkslength !==). This is functionally fine — the inner function catches the mismatch — but the intention reads like a "both empty or both non-empty" gate. A brief comment would clarify.
| function compareOutputStrict(x: Record<string, unknown>, y: Record<string, unknown>): boolean { | ||
| if (!x || !y) return x === y; | ||
| if (x.output_type !== y.output_type) return false; | ||
|
|
||
| // Create 2D array | ||
| const dp: number[][] = Array(len1 + 1).fill(null).map(() => Array(len2 + 1).fill(0)); | ||
| const xKeys = new Set(Object.keys(x)); | ||
|
|
||
| // Initialize base cases | ||
| for (let i = 0; i <= len1; i++) { | ||
| dp[i][0] = i; | ||
| const handled = new Set(['output_type', 'data', 'metadata', 'execution_count']); | ||
|
|
||
| // Strict match on all keys we don't otherwise handle | ||
| for (const k of xKeys) { | ||
| if (!handled.has(k) && JSON.stringify(x[k]) !== JSON.stringify(y[k])) { | ||
| return false; | ||
| } | ||
| } | ||
| for (let j = 0; j <= len2; j++) { | ||
| dp[0][j] = j; | ||
|
|
||
| // Compare data strictly | ||
| const xData = (x.data || {}) as Record<string, unknown>; | ||
| const yData = (y.data || {}) as Record<string, unknown>; | ||
| const xDataKeys = new Set(Object.keys(xData)); | ||
| const yDataKeys = new Set(Object.keys(yData)); | ||
| if (xDataKeys.size !== yDataKeys.size) return false; | ||
| for (const k of xDataKeys) { | ||
| if (!yDataKeys.has(k)) return false; | ||
| const xVal = Array.isArray(xData[k]) ? (xData[k] as string[]).join('') : String(xData[k]); | ||
| const yVal = Array.isArray(yData[k]) ? (yData[k] as string[]).join('') : String(yData[k]); | ||
| if (!compareStringsApproximate(xVal, yVal, 0.95, 10000)) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| // Fill the matrix | ||
| for (let i = 1; i <= len1; i++) { | ||
| for (let j = 1; j <= len2; j++) { | ||
| if (str1[i - 1] === str2[j - 1]) { | ||
| dp[i][j] = dp[i - 1][j - 1]; | ||
| return true; | ||
| } |
There was a problem hiding this comment.
compareOutputStrict has an asymmetric top-level key check.
Lines 286–294 only iterate keys from x. If y has extra keys not present in x (outside the handled set), those are silently ignored and the outputs still pass the "strict" comparison.
The data sub-object check (lines 300–304) is correctly symmetric. Apply the same symmetry to the top-level keys.
Proposed fix
const xKeys = new Set(Object.keys(x));
+ const yKeys = new Set(Object.keys(y));
const handled = new Set(['output_type', 'data', 'metadata', 'execution_count']);
- // Strict match on all keys we don't otherwise handle
+ // Strict match on all keys we don't otherwise handle (check both directions)
for (const k of xKeys) {
if (!handled.has(k) && JSON.stringify(x[k]) !== JSON.stringify(y[k])) {
return false;
}
}
+ for (const k of yKeys) {
+ if (!handled.has(k) && !(k in x)) {
+ return false;
+ }
+ }🤖 Prompt for AI Agents
In `@src/cellMatcher.ts` around lines 282 - 313, compareOutputStrict currently
only iterates top-level keys from x (xKeys) against the handled set, so extra
non-handled keys present in y are ignored; make the top-level key comparison
symmetric by also constructing yKeys (e.g., new Set(Object.keys(y))) and either
(a) verify xKeys and yKeys contain the same non-handled keys (compare sizes and
membership) or (b) iterate yKeys to ensure any key not in handled also exists in
x and matches via JSON.stringify equality the same way you do for xKeys; update
the block that defines handled and the for-loop so both x and y are checked for
unexpected extra keys before proceeding to the existing data comparison.
Adds Cell ID matching according to NBFormat
4 level Cell matching algo from finest/strictest -> most coarse.
Summary by CodeRabbit
New Features
Tests
Chores