Skip to content

Replace Levenshtein-based LCS with snaking algorithm for cell matching - #41

Merged
Avni2000 merged 6 commits into
mainfrom
copilot/replace-lcs-with-nbdime-snaking
Feb 6, 2026
Merged

Avni2000 merged 6 commits into
mainfrom
copilot/replace-lcs-with-nbdime-snaking

Conversation

Copilot AI commented Feb 4, 2026 •

Copy link
Copy Markdown
Contributor
  1. Adds Cell ID matching according to NBFormat

  2. 4 level Cell matching algo from finest/strictest -> most coarse.

    • Level 3: Cell ID match
    • Level 2: Strict (≥0.95 source ratio + strict output match)
    • Level 1: Moderate (≥0.7 source ratio + approximate output match)
    • Level 0: Approximate (≥0.7 ratio + short-string optimization)

Summary by CodeRabbit

  • New Features

    • Improved notebook merge conflict detection through enhanced cell alignment and content comparison algorithms.
  • Tests

    • Added diagnostic analysis to capture unmatched cell counts during conflict resolution testing.
  • Chores

    • Extended cell type structure to support improved conflict tracking.

Copilot AI changed the title [WIP] Replace Levenshtein distance LCS with nbdime snaking algorithm Replace Levenshtein-based LCS with nbdime snaking algorithm for cell matching Feb 4, 2026
Copilot AI requested a review from Avni2000 February 4, 2026 23:34
@Avni2000

Avni2000 commented Feb 4, 2026

Copy link
Copy Markdown
Owner

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
@Avni2000 Avni2000 changed the title Replace Levenshtein-based LCS with nbdime snaking algorithm for cell matching Replace Levenshtein-based LCS with snaking algorithm for cell matching Feb 6, 2026
@Avni2000
Avni2000 marked this pull request as ready for review February 6, 2026 00:34
@Avni2000

Avni2000 commented Feb 6, 2026

Copy link
Copy Markdown
Owner

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

@coderabbitai

coderabbitai Bot commented Feb 6, 2026

Copy link
Copy Markdown
Contributor

@Avni2000, that's excellent news about the improvements! A reduction from almost half the conflicted cells requiring manual matching to almost none is a significant achievement. I'll conduct a thorough review of the PR focusing on:

  • The snaking algorithm implementation for cell matching
  • The 4-level cell matching hierarchy (Cell ID → Strict → Moderate → Approximate)
  • Integration with NBFormat cell ID matching
  • Code quality, edge cases, and potential improvements

I'll get started on the review right away.


🧠 Learnings used
Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Applies to src/cellMatcher.ts : Implement content-based cell matching algorithm for 3-way merge

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Applies to src/conflictDetector.ts : Implement cell-level diffing—show side-by-side or inline diffs for conflicting cells, not raw JSON lines
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Feb 6, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • 🔍 Trigger a full review
📝 Walkthrough

Walkthrough

The 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

Cohort / File(s) Summary
Snakes-based Cell Matching Engine
src/cellMatcher.ts
Replaces hash/Levenshtein matching with LCS-based snakes algorithm. Introduces computeCompareGrid, computeLCSGrid, computeLCSIndices, computeSnakesFromLCS, computeSnakesMultilevel for snake computation; adds multilevel predicates (cellsMatchByIds, cellsStrictMatch, cellsModerateMatch, cellsApproximateMatch); extends compareOutput functions for stream/error/data output types; reworks matchCells to use snakes-driven mapping with edge-case handling for empty base.
Test Diagnostic Enhancement
src/tests/vscodeIntegration.test.ts
Adds pre-resolution diagnostic analysis pass that iterates conflict rows and logs counts of unmatched cells, categorized by current-only, incoming-only, and both, without altering resolution logic or outcomes.
Type Schema Extension
src/types.ts
Introduces optional id?: string field to NotebookCell interface.

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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • PR #8: Modifies sortMappingsByPosition tie-breaking logic in src/cellMatcher.ts, directly impacting the helper introduced in this PR.
  • PR #16: Refactors matching/sorting logic in src/cellMatcher.ts by re-exporting utilities from positionUtils, affecting the snakes-based matching pipeline introduced here.

Poem

🐰 Snakes align where hashes failed,
LCS grids and snakes prevailed,
Multilevel predicates dance,
Each cell finds its perfect match—
No more fuzzy, now precise! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: replacing Levenshtein-based LCS with a snaking algorithm for cell matching, which is the primary architectural shift reflected across the cellMatcher.ts file changes.
Docstring Coverage ✅ Passed Docstring coverage is 95.83% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch copilot/replace-lcs-with-nbdime-snaking

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

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

matchConfidence is always 1.0 in the no-base path, even for snaking-matched pairs.

Line 710 assigns matchConfidence: 1.0 for pairs matched by matchCellsToBase, but these could be approximate matches at level 0. Contrast this with lines 801–804 in the base-present path, which correctly use computeCellSimilarity. This makes matchConfidence unreliable 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: compareOutputApproximate ignores non-text mime-type value differences for display_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 like image/png could 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 # A and # 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 / baseToincoming and usedcurrentIndices / usedincomingIndices break 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 get matchConfidence: 0.9 regardless of actual match quality.

Line 755 hardcodes 0.9 for 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 recursive computeSnakesMultilevel creates copies at each level.

Line 490 calls A.slice(i0, i1) and B.slice(j0, j1) at every recursive level, and computeSnakes then 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 computeSnakes rather than slicing. This would avoid the per-level copy and grid reallocation.


566-577: Double cast through unknown for outputs.

Lines 567–568 use as unknown as Record<string, unknown>[] to cast CellOutput[]. This pattern appears in cellsStrictMatch, cellsModerateMatch, and the output comparison functions. Since CellOutput is a structured type (from types.ts), a targeted utility or a single assertion at the boundary would be cleaner than scattering double-casts.


595-604: cellsModerateMatch output-length check uses truthiness, not count equality.

Line 599: !!aOutputs.length !== !!bOutputs.length only checks whether outputs are empty vs. non-empty. Two cells with 1 output and 5 outputs respectively would pass this gate and then fail inside compareOutputsApproximate (which checks length !==). 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.

Comment thread src/cellMatcher.ts
Comment on lines +282 to +313
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;
}

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.

⚠️ Potential issue | 🟡 Minor

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.

@Avni2000
Avni2000 merged commit 5659de0 into main Feb 6, 2026
2 checks passed
@Avni2000
Avni2000 deleted the copilot/replace-lcs-with-nbdime-snaking branch March 1, 2026 01:39
@coderabbitai coderabbitai Bot mentioned this pull request Mar 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants