Skip to content

[FEAT] Global Cell matching algorithm - #78

Merged
Avni2000 merged 2 commits into
mainfrom
global-cell-matcher
Feb 12, 2026
Merged

Avni2000 merged 2 commits into
mainfrom
global-cell-matcher

Conversation

@Avni2000

@Avni2000 Avni2000 commented Feb 12, 2026 •

Copy link
Copy Markdown
Owner

Matching strategy:

  1. Hard anchors: unique ID matches, unique heading matches, then unique exact source matches.
  2. Global optimization: Hungarian assignment on remaining cells with a weighted score (content + output + contextual fingerprint).

Constants here are somewhat arbitrary, but seem to align well with other global assignment algos do

Summary by CodeRabbit

  • Refactor
    • Major improvement to notebook cell matching: anchor-first alignment plus optimal assignment for remaining cells, with a consolidated similarity model for more accurate, consistent diffs and merges and stabilized mapping/order in results.
  • Tests
    • Removed a flaky runtime drag-and-drop undo/redo test action to stabilize the test suite.

@coderabbitai

coderabbitai Bot commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The three-way cell-matching algorithm was replaced with an anchor-first strategy (ID, heading, exact source) followed by a Hungarian-assignment on remaining cells using a weighted similarity model (content, context, outputs) and stabilized position-based mapping output.

Changes

Cohort / File(s) Summary
Cell matching core
src/cellMatcher.ts
Replaced snaking/LCS approach with anchor-first + two-stage Hungarian assignment. Added hard anchors (ID, unique heading, exact source), context-token utilities, new numeric similarity scores and weights, matrix/Hungarian solver helpers, mapping construction/sorting, and adapted reordering detection.
Tests / Manifest
src/tests/undoRedoActions.test.ts, package.json
Removed (commented-out) runtime for an action that moved an unmatched cell in undoRedoActions.test.ts; package manifest adjustments reflected in package.json.

Sequence Diagram(s)

sequenceDiagram
  participant Base as BaseCells
  participant Current as CurrentCells
  participant Incoming as IncomingCells
  participant Anchors as AnchorResolver
  participant Solver as HungarianSolver
  participant Out as Mappings

  Base->>Anchors: provide base cells
  Current->>Anchors: provide current cells
  Incoming->>Anchors: provide incoming cells
  Anchors->>Anchors: apply ID/heading/source anchors
  Anchors-->>Solver: unmatched cells (base/current/incoming)
  Solver->>Solver: build cost matrix (content/context/output weights)
  Solver->>Solver: run Hungarian assignment
  Solver-->>Out: produce matched mappings
  Anchors-->>Out: include anchored matches
  Out->>Out: sortMappingsByPosition -> final ordered mappings
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 Hopping through anchors, quick and spry,

I nudge matching cells and watch them tie,
Hungarian paws find the best, not least,
Base, Current, Incoming—now a feast,
A tidy mapping, carrot-flavored and spry.

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title '[FEAT] Global Cell matching algorithm' directly corresponds to the main change: a complete redesign of the cell matching algorithm from a snaking approach to an anchor-first, Hungarian-assisted strategy.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch global-cell-matcher

No actionable comments were generated in the recent review. 🎉

🧹 Recent nitpick comments
src/tests/undoRedoActions.test.ts (2)

193-256: Remove the commented-out test block instead of leaving it disabled.

~60 lines of commented-out code adds noise and will likely never be re-enabled given the new matching algorithm guarantees no unmatched cells. If the test needs to be resurrected later, it's recoverable from Git history.


35-80: findCellMovePair is now dead code.

With Action 5 commented out, this helper has no callers. Remove it along with the commented-out block to keep the test file clean.


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

🤖 Fix all issues with AI agents
In `@src/cellMatcher.ts`:
- Around line 626-643: The current unmatched-matching step builds sub-arrays
(unmatchedCurrentCells/unmatchedIncomingCells) and calls matchCellsGlobal, which
causes scoreCellPair/getContextSignature to compute neighbor tokens from the
sliced arrays instead of the original notebook arrays; instead, implement a new
matcher (e.g., matchCellSubsets) that accepts the original currentCells and
incomingCells plus unmatchedCurrentIndices and unmatchedIncomingIndices and
constructs the cost matrix using those real indices so
scoreCellPair/getContextSignature see the true neighbors; replace the call to
matchCellsGlobal(unmatchedCurrentCells, unmatchedIncomingCells) with
matchCellSubsets(currentCells, incomingCells, unmatchedCurrentIndices,
unmatchedIncomingIndices) and ensure the new function reuses the existing
scoring logic but indexes into the original arrays.
🧹 Nitpick comments (3)
src/cellMatcher.ts (3)

275-369: Consider extracting a common anchor-matching helper.

addIdAnchors, addUniqueHeadingAnchors, and addUniqueSourceAnchors share identical match logic—only the key-extraction function differs. A single generic helper would reduce duplication:

Example consolidation
+function addUniqueAnchors(
+    baseCells: NotebookCell[],
+    otherCells: NotebookCell[],
+    toKey: (cell: NotebookCell) => string | undefined,
+    matches: Map<number, number>,
+    usedBase: Set<number>,
+    usedOther: Set<number>
+): void {
+    const baseIndex = buildUniqueValueIndex(baseCells, toKey);
+    const otherIndex = buildUniqueValueIndex(otherCells, toKey);
+    for (const [key, baseIndices] of baseIndex.entries()) {
+        if (baseIndices.length !== 1) continue;
+        const otherIndices = otherIndex.get(key);
+        if (!otherIndices || otherIndices.length !== 1) continue;
+        const baseIdx = baseIndices[0];
+        const otherIdx = otherIndices[0];
+        if (usedBase.has(baseIdx) || usedOther.has(otherIdx)) continue;
+        matches.set(baseIdx, otherIdx);
+        usedBase.add(baseIdx);
+        usedOther.add(otherIdx);
+    }
+}

Then in matchCellsGlobal:

addUniqueAnchors(baseCells, otherCells, (c) => c.id, matches, usedBase, usedOther);
addUniqueAnchors(baseCells, otherCells, getNormalizedHeadingKey, matches, usedBase, usedOther);
addUniqueAnchors(baseCells, otherCells, getExactSourceKey, matches, usedBase, usedOther);

140-151: computeCellSimilarity bypasses cheap upper-bound filters.

Unlike compareStringsApproximate, computeCellSimilarity calls sequenceMatcherRatio directly without the realQuickRatio/quickRatio early-exit guards. Since this runs for every cell pair in the cost matrix (N×M calls), adding the cheap upper-bound checks could meaningfully reduce work when many pairs are dissimilar.

Possible improvement
 function computeCellSimilarity(cell1: NotebookCell, cell2: NotebookCell): number {
     if (cell1.cell_type !== cell2.cell_type) return 0;

     const source1 = getCellSource(cell1);
     const source2 = getCellSource(cell2);

     if (source1 === source2) return 1;
     if (!source1 && !source2) return 1;
     if (!source1 || !source2) return 0;

+    // Cheap upper-bound filters before expensive matching
+    if (realQuickRatio(source1, source2) < MIN_MATCH_SCORE) return realQuickRatio(source1, source2);
+    if (quickRatio(source1, source2) < MIN_MATCH_SCORE) return quickRatio(source1, source2);
+
     return sequenceMatcherRatio(source1, source2);
 }

Note: returning the ratio instead of 0 preserves the full [0,1] score semantics while still saving the sequenceMatcherRatio cost for clearly dissimilar pairs.


506-519: Scores below threshold are assigned the same sentinel cost as type mismatches—consider distinguishing them.

Both type-mismatched pairs and below-threshold pairs receive TYPE_MISMATCH_COST (100). This works because both are rejected post-assignment (line 524), but using a distinct sentinel (e.g., LOW_SCORE_COST) would improve readability and make future cost-analysis or debugging easier. Minor point.

Comment thread src/cellMatcher.ts
Comment on lines 626 to +643
const unmatchedCurrentCells: NotebookCell[] = [];
const unmatchedCurrentIndices: number[] = [];
const unmatchedIncomingCells: NotebookCell[] = [];
const unmatchedIncomingIndices: number[] = [];

for (let currentIdx = 0; currentIdx < currentCells.length; currentIdx++) {
if (!usedcurrentIndices.has(currentIdx)) {
unmatchedCurrentCells.push(currentCells[currentIdx]);
unmatchedCurrentIndices.push(currentIdx);
}
if (usedCurrent.has(currentIdx)) continue;
unmatchedCurrentCells.push(currentCells[currentIdx]);
unmatchedCurrentIndices.push(currentIdx);
}

for (let incomingIdx = 0; incomingIdx < incomingCells.length; incomingIdx++) {
if (!usedincomingIndices.has(incomingIdx)) {
unmatchedIncomingCells.push(incomingCells[incomingIdx]);
unmatchedIncomingIndices.push(incomingIdx);
}
if (usedIncoming.has(incomingIdx)) continue;
unmatchedIncomingCells.push(incomingCells[incomingIdx]);
unmatchedIncomingIndices.push(incomingIdx);
}

// Match unmatched cells using snaking
const unmatchedMatches = matchCellsToBase(unmatchedCurrentCells, unmatchedIncomingCells);

const unmatchedMatches = matchCellsGlobal(unmatchedCurrentCells, unmatchedIncomingCells);

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

Context signatures computed over sub-arrays degrade context quality.

When matching remaining unmatched cells (line 643), the sub-arrays unmatchedCurrentCells and unmatchedIncomingCells are passed to matchCellsGlobal. Inside scoreCellPair, getContextSignature computes previous/next neighbor tokens relative to these sub-arrays—not the original notebook cell arrays. This means a cell's "neighbors" in the unmatched subset are likely unrelated to its actual neighbors in the notebook, making the context component of the score unreliable for this phase.

Since context weight is 0.2–0.3, the impact is bounded, but for edge cases where content similarity is similar across multiple candidates, the degraded context signal could lead to suboptimal pairings.

Consider passing the original currentCells/incomingCells arrays along with the real indices to preserve context fidelity:

Sketch of approach

Instead of constructing sub-arrays, pass the original cell arrays and the unmatched index lists directly to a variant of matchCellsGlobal that operates on index subsets rather than sliced arrays.

-    const unmatchedCurrentCells: NotebookCell[] = [];
-    const unmatchedCurrentIndices: number[] = [];
-    const unmatchedIncomingCells: NotebookCell[] = [];
-    const unmatchedIncomingIndices: number[] = [];
-
-    for (let currentIdx = 0; currentIdx < currentCells.length; currentIdx++) {
-        if (usedCurrent.has(currentIdx)) continue;
-        unmatchedCurrentCells.push(currentCells[currentIdx]);
-        unmatchedCurrentIndices.push(currentIdx);
-    }
-
-    for (let incomingIdx = 0; incomingIdx < incomingCells.length; incomingIdx++) {
-        if (usedIncoming.has(incomingIdx)) continue;
-        unmatchedIncomingCells.push(incomingCells[incomingIdx]);
-        unmatchedIncomingIndices.push(incomingIdx);
-    }
-
-    const unmatchedMatches = matchCellsGlobal(unmatchedCurrentCells, unmatchedIncomingCells);
+    const unmatchedCurrentIndices = collectUnmatchedIndices(currentCells.length, usedCurrent);
+    const unmatchedIncomingIndices = collectUnmatchedIndices(incomingCells.length, usedIncoming);
+
+    // Match using original arrays + index subsets to preserve context fidelity
+    const unmatchedMatches = matchCellSubsets(
+        currentCells, unmatchedCurrentIndices,
+        incomingCells, unmatchedIncomingIndices
+    );

This would require a new matchCellSubsets function that builds the cost matrix using the original arrays and real indices, so scoreCellPair sees accurate neighbor context.

🤖 Prompt for AI Agents
In `@src/cellMatcher.ts` around lines 626 - 643, The current unmatched-matching
step builds sub-arrays (unmatchedCurrentCells/unmatchedIncomingCells) and calls
matchCellsGlobal, which causes scoreCellPair/getContextSignature to compute
neighbor tokens from the sliced arrays instead of the original notebook arrays;
instead, implement a new matcher (e.g., matchCellSubsets) that accepts the
original currentCells and incomingCells plus unmatchedCurrentIndices and
unmatchedIncomingIndices and constructs the cost matrix using those real indices
so scoreCellPair/getContextSignature see the true neighbors; replace the call to
matchCellsGlobal(unmatchedCurrentCells, unmatchedIncomingCells) with
matchCellSubsets(currentCells, incomingCells, unmatchedCurrentIndices,
unmatchedIncomingIndices) and ensure the new function reuses the existing
scoring logic but indexes into the original arrays.

@Avni2000

Avni2000 commented Feb 12, 2026 •

Copy link
Copy Markdown
Owner Author

It's unlikely anyone will ever see this, but if you do, know that the number of unmatched cells dropped so hard that I will probably have to remove that feature entirely, and I already had to remove a test to match cells with playwright. Insane.

@Avni2000
Avni2000 merged commit bae54d3 into main Feb 12, 2026
4 checks passed
@Avni2000
Avni2000 deleted the global-cell-matcher branch March 1, 2026 01:39
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.

1 participant