Skip to content

[lexical-table] Bug Fix: don't throw on stale table node keys in $handleTableSelectionChangeCommand - #8674

Merged
etrepum merged 1 commit into
meta:mainfrom
etrepum:claude/sleepy-allen-23qxk1
Jun 11, 2026
Merged

etrepum merged 1 commit into
meta:mainfrom
etrepum:claude/sleepy-allen-23qxk1

Conversation

@etrepum

@etrepum etrepum commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

Description

The SELECTION_CHANGE_COMMAND handler dereferenced table node keys with $getNodeByKeyOrThrow in two places where the key can be stale, throwing invariant #63 ("Expected node with key %s to exist but it's not in the nodeMap"):

  • The shouldCheckSelectionForTable key recorded on ArrowDown (the Firefox workaround for scrollable tables) when the table is removed before the next selection change.
  • The tableObservers registry sweep, when a TableNode's destroyed mutation was missed (e.g. an update performed while the editor's root element was detached skips reconciliation), leaving a permanently poisoned registry that threw on every subsequent selection change.

The shouldCheckSelectionForTable lookup now uses $getNodeByKey and skips missing nodes, and the registry maintenance is centralized in the TableObservers class so it self-heals instead of erroring for the rest of the session:

  • TableObservers.removeObserver(tableKey) is the canonical teardown (removeListeners + registry delete) used by the mutation listener (destroyed and DOM-recreated branches)
  • TableObservers.removeAllObservers() handles plugin unregistration
  • TableObservers.$getTableNodesAndObservers() returns a snapshot of the registry for the current editor state, pruning entries whose table no longer exists so a missed destroyed mutation can't poison the registry

TableObservers is not exported from the package, so the public API is unchanged.

Closes #8670

Test plan

New unit tests

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Jun 11, 2026
@vercel

vercel Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview, Comment Jun 11, 2026 4:41am
lexical-playground Ready Ready Preview, Comment Jun 11, 2026 4:41am

Request Review

…dleTableSelectionChangeCommand

The SELECTION_CHANGE_COMMAND handler dereferenced table node keys with
$getNodeByKeyOrThrow in two places where the key can be stale, throwing
invariant #63 ("Expected node with key %s to exist but it's not in the
nodeMap"):

- The shouldCheckSelectionForTable key recorded on ArrowDown (the
  Firefox workaround for scrollable tables) when the table is removed
  before the next selection change.
- The tableObservers registry sweep, when a TableNode's destroyed
  mutation was missed (e.g. an update performed while the editor's root
  element was detached skips reconciliation), leaving a permanently
  poisoned registry that threw on every subsequent selection change.

The shouldCheckSelectionForTable lookup now uses $getNodeByKey and
skips missing nodes, and the registry maintenance is centralized in the
TableObservers class so it self-heals instead of erroring for the rest
of the session:

- TableObservers.removeObserver(tableKey) is the canonical teardown
  (removeListeners + registry delete) used by the mutation listener
  (destroyed and DOM-recreated branches)
- TableObservers.removeAllObservers() handles plugin unregistration
- TableObservers.$getTableNodesAndObservers() returns a snapshot of the
  registry for the current editor state, pruning entries whose table no
  longer exists so a missed destroyed mutation can't poison the registry

TableObservers is not exported from the package index, so the new
methods are internal and the public API is unchanged. The regression
tests drive both scenarios through the public API with an editor built
from TableExtension.

Fixes meta#8670

https://claude.ai/code/session_01V5ShLDk437pCFXFjQtRewR

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

Reviewed by Navi (Tater Thoughts Bobblehead) on behalf of @potatowagon.

LGTM ✅ — This is a well-structured defensive fix for a real edge case (stale table node keys in the observer registry).

What I checked:

  • Logic correctness: $handleTableSelectionChangeCommand now uses $getNodeByKey (nullable) instead of $getTableNodeByKeyOrThrow for the shouldCheckSelectionForTable path. This correctly handles the case where a table is removed before its pending selection-change fires — instead of throwing, it gracefully skips the stale reference. The $isTableNode guard before proceeding is the right pattern.
  • Self-healing registry ($getTableNodesAndObservers): Iterates all entries and prunes stale ones (where the node no longer exists) before returning. This prevents "poisoned registry" issues when a table is removed while the root element is detached (missing the destroyed mutation). Uses Array.from() before iteration to safely mutate during the loop — correct.
  • Encapsulation improvements: removeObserver, removeAllObservers, and $getTableNodesAndObservers are properly marked @internal and centralize cleanup logic that was previously inlined in multiple places. No new public API surface.
  • Edge cases: The two new unit tests cover both scenarios — (1) ArrowDown records a table key, table is removed, selection change fires without throwing; (2) table removed while root detached, subsequent selection changes self-heal the registry and new tables still register correctly.
  • Test coverage: 112-line test file with proper setup/teardown, uses buildEditorFromExtensions + TableExtension (modern API), discrete updates for synchronous assertions.
  • www backwards compatibility: No exports are removed or renamed. The new methods are @internal on TableObservers class. The $getTableNodeByKeyOrThrow import removal in LexicalTableSelectionHelpers.ts is local — that function is still exported from @lexical/table for external consumers. No breaking change.
  • CI: All checks green — browser tests (mac/linux/windows × chromium/firefox/webkit), unit tests (Node 22.x/24.x), e2e (plain/rich/collab/collab-v2), integration, integrity, CLA, Vercel.

Assessment: Clean defensive fix. The pattern of swapping OrThrow for nullable-with-guard is well-established in Lexical for handling stale references. The self-healing $getTableNodesAndObservers is a nice addition that prevents accumulation of leaked observers. Ready to approve.

@etrepum
etrepum added this pull request to the merge queue Jun 11, 2026
Merged via the queue into meta:main with commit eaaf18c Jun 11, 2026
48 checks passed
@etrepum etrepum mentioned this pull request Jun 25, 2026
taylorpapke pushed a commit to life-itself/ForumMagnum that referenced this pull request Sep 14, 2026
<details>
<summary>Prompts Used</summary>
In Lexical, deleting a table that's the last thing in the document, by placing the cursor after it and pressing backspace, crashes with: `Uncaught Error: Expected node with key 193 to exist but it's not in the nodeMap.` (the key number varies), after which the editor JS breaks.

> Fixed. The crash is a known upstream bug in `@lexical/table` 0.44 ([meta/lexical#8670](meta/lexical#8670)); I reproduced it in a unit test and added an app-level workaround, since the real fix only ships in lexical 0.46.
>
> **Root cause:** With scrollable tables active (our `tableHorizontalScroll: true`), pressing ArrowDown while the selection is outside a table makes `@lexical/table` record that table's node key in `shouldCheckSelectionForTable` — part of a Firefox caret-placement workaround. The key is consumed by the *next* `SELECTION_CHANGE_COMMAND`, via `$getNodeByKeyOrThrow`. Normally the ArrowDown moves the caret and the resulting selection change consumes the key immediately. But when the cursor is after a trailing table (in the sentinel paragraph our `BlockCursorNavigationPlugin` maintains there), ArrowDown can't move the caret, so no selection change happens and the key stays pending. Backspace then deletes the table, and the selection change triggered by the deletion dereferences the dead key — the "Expected node with key N to exist" throw, with the key varying because it's the deleted table's key. The throw escapes mid-selection-change handling, which is why the editor stays broken afterward.
>
> **What I did:**
>
> - `packages/lesswrong/unitTests/tableBackspaceDelete.tests.tsx` — a jsdom test mounting the real plugins (vendored `TablePlugin` with horizontal scroll, `BlockCursorNavigationPlugin`, and a variant with the Yjs `CollaborationPlugin` on a fake in-memory provider). The ArrowDown→backspace→selection-change sequence reproduced the exact error before the fix; all four scenarios pass now, and the tests also verify the table actually gets deleted and that later edits still work.
> - `packages/lesswrong/components/editor/lexicalPlugins/tables/TableDeleteCrashWorkaroundPlugin.tsx` (mounted in `Editor.tsx` next to `TablesPlugin`) — before backspace/delete/undo/redo, if an ArrowDown happened with no selection change since (the only state where the stale key can be pending), it dispatches a synthetic `SELECTION_CHANGE_COMMAND` so the pending key is consumed while the table still exists, which is a harmless no-op. It never fires during normal editing.
> - `notes/lexical-upgrade-for-table-stale-key-bug.md` — the proper fix is upgrading lexical to ≥0.46 (upstream PR [ForumMagnum#8674](meta/lexical#8674), which also fixes a second "poisoned observer registry" variant that can't be worked around from app code); the note says to delete the workaround plugin then and keep the regression test.
>
> `yarn tsc` is clean apart from pre-existing errors in your locally-modified `Layout.tsx` (`WrapperComponentThatIsNew` undefined), which predate this session. One caveat: I verified the fix via the unit-test harness, not in a live browser — worth a quick manual check that backspace-deleting a trailing table now works in the real editor.
<hr>
A post with a section heading wrapped in both <strong> and <b> winds up with two copies of that heading in the ToC. Fix, and, if the bug wasn't always there, determine when it was introduced.

> Fixed, with a regression test, and the bug is dated.
>
> **Cause.** In `packages/lesswrong/lib/tableOfContents.ts`, `extractTableOfContents` queries for `h1,h2,h3,h4,strong,b` and gets back both the outer `<strong>` and the inner `<b>`. The whole-paragraph check accepted each of them independently, because each is the sole content of its parent and its text equals the paragraph's text. So both got an anchor and a ToC entry.
>
> **Fix.** The extraction loop now records each element it accepts as a heading and skips any later candidate that is nested inside one of them. Since `querySelectorAll` returns ancestors before descendants, the outer element is the one kept, so the anchor lands on the `<strong>`. This also covers `<b><strong>`, `<strong><strong>`, and similar nestings.
>
> **Test.** Added a case to `packages/lesswrong/unitTests/tableOfContents.tests.ts` covering both nesting orders. It fails on the old code and passes with the fix. The full file passes and `yarn tsc` is clean.
>
> **When it was introduced.** The bug was not always there. The original 2018 code required a `<strong>` or `<b>` to have a `<p>` as its direct parent, which excluded the inner tag. Commit 9c62824 ("Improve tagIsWholeParagraph heuristics", 2022-07-03, merged to master in PR ForumMagnum#5159 on 2022-07-06) replaced that with a check that the tag's siblings are all the same tag type and that the enclosing paragraph's text matches, which the inner tag also satisfies. The 2024 DOM rewrite (PR merged 2024-04-03) ported the same logic faithfully, so the double entry has existed since July 2022.
>
> Nothing is committed. The two modified files are ready for review.
</details>

This branch was successfully deployed

2 active deployments
Preview – lexical — 4041fab6 Deployed Jun 11, 2026 by vercel[bot]
Preview – lexical-playground — 4041fab6 Deployed Jun 11, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: $handleTableSelectionChangeCommand throws invariant #63 on stale table node keys (poisoned tableObservers registry)

4 participants