Skip to content

Fix ParentNode insertBefore linked-list corruption#609

Closed
TrevorSundberg wants to merge 1 commit into
Shopify:mainfrom
TrevorSundberg:codex/fix-parentnode-insertbefore-links
Closed

Fix ParentNode insertBefore linked-list corruption#609
TrevorSundberg wants to merge 1 commit into
Shopify:mainfrom
TrevorSundberg:codex/fix-parentnode-insertbefore-links

Conversation

@TrevorSundberg

Copy link
Copy Markdown

Summary

This fixes ParentNode.insertInto() in @remote-dom/polyfill so inserting a child before a non-head reference node correctly links the previous sibling to the inserted child.

The current implementation updates the inserted child and the reference node, but it does not update the previous sibling's NEXT pointer when before[PREV] is not null. That leaves the sibling list internally inconsistent: the inserted node has PREV/NEXT links, and the reference node points back to it, but traversal from the parent's first child skips the inserted node.

Affected source:
https://github.com/Shopify/remote-dom/blob/main/packages/polyfill/source/ParentNode.ts#L120-L127

Before:

child[NEXT] = before;
child[PREV] = before[PREV];
if (before[PREV] === null) this[CHILD] = child;
before[PREV] = child;

After:

child[NEXT] = before;
child[PREV] = before[PREV];
if (before[PREV] === null) this[CHILD] = child;
else before[PREV][NEXT] = child; // Link the previous sibling to the inserted child.
before[PREV] = child;

Tests passed: corepack pnpm exec vitest run packages/polyfill/source/tests/parent-node.test.ts, corepack pnpm type-check, corepack pnpm lint, and corepack pnpm exec vitest run.

Root Cause

For non-head insertions, before[PREV] is the previous sibling. That sibling must have its NEXT pointer changed to the inserted child. Without that update, the list can become inconsistent after DOM moves such as keyed reorders.

This diverges from the normal DOM insertion invariant:

previousSibling -> insertedChild -> before

Instead, the current state can become:

previousSibling -> before
insertedChild -> before
before.prev -> insertedChild

@TrevorSundberg TrevorSundberg deleted the codex/fix-parentnode-insertbefore-links branch April 29, 2026 01:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant