Skip to content

fix: resolve cloned Set member origins when applying patches - #1399

Open
amstedy wants to merge 1 commit into
immerjs:mainfrom
amstedy:fix/apply-patches-set-remove-cloned-value
Open

amstedy wants to merge 1 commit into
immerjs:mainfrom
amstedy:fix/apply-patches-set-remove-cloned-value

Conversation

@amstedy

@amstedy amstedy commented Dec 1, 2026

Copy link
Copy Markdown

Fixes #1367 (Case 2C).

Summary

When applyPatches adds a draftable object to a Set (either via op: "add" or op: "replace" with a Set), deepClonePatchValue clones the entry to preserve patch isolation (#411). A subsequent op: "remove" patch referencing the original object (in combined patches or across separate applyPatches / undo calls) failed because Set.prototype.delete compares by reference and could not match the cloned member.

This change:

  • Tracks the root origin of cloned Set members in a WeakMap (cloneOrigins) paired with a WeakSet (originsWithClones) scoped inside enablePatches(), keeping O(1) fast paths and zero overhead for non-Set values and uncloned objects.
  • Resolves cloned/origin/draft references on Set remove and deduplicates repeated add patches via a lazy per-applyPatches_ origin index so bulk removals remain O(N).
  • Skips unnecessary deepClonePatchValue(patch.value) work on op: "remove".

Verification

  • Added __tests__/patch-set-replay.js covering combined patches (Case 2C), sequential undo, repeated in-place mutations, duplicate add idempotency, structurally equal distinct references, Draft proxy patch values, Map object keys, and linear scaling under both autoFreeze: false and autoFreeze: true.
  • Verified with vitest, production tsup build (vitest.config.build.ts with mangleProps), tsc, flow, and prettier.

This branch has not been deployed

No deployments
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.

Testing Immer patch replay against an independent model: possible bugs and questions

1 participant