Skip to content

fix: emit replace patches for indices dropped by shrinking length - #1356

Open
RClaudiuM wants to merge 3 commits into
immerjs:mainfrom
RClaudiuM:fix/1355-length-shrink-patches
Open

RClaudiuM wants to merge 3 commits into
immerjs:mainfrom
RClaudiuM:fix/1355-length-shrink-patches

Conversation

@RClaudiuM

Copy link
Copy Markdown

Fixes #1355

What

With enablePatches(), shrinking a draft array by assigning length and then growing it back to at least its base length produced no replace patch (and no inverse patch) for the truncated indices. So applyPatches(base, patches) kept the stale values, and the inverse patches did not restore the base. The same recipe with splice(0) was already correct.

Why

generateArrayPatches only emits a replace for an index below base_.length when assigned_ has it (or allIndicesReassigned_ is set). splice removes elements through deleteProperty, which marks each index. Assigning length goes through the set trap for "length" only, so the dropped indices were never marked.

Change

In the array set trap, when length shrinks, mark the dropped indices that exist in the base as assigned. Only indices below base_.length are marked, since those are the only ones the replace loop looks at. If the array stays short, nothing changes: the replace loop only runs up to the shorter length, and the dropped indices still get remove patches.

Tests

New cases in __tests__/patch.js (through runPatchTests, so they also check replay and reversal):

  • length = 0 then d[1] = 2 (the case from the issue)
  • length = 0 then length = 2
  • length = 1 then push(4, 5) (control, already passing)
  • length = 0 then the same values written back (control: no patches)

Before the fix, the first two fail (6 assertions). After, all pass.

Repro from the issue, run against the build:

before:
patches [{"op":"add","path":[1],"value":2}]
inverse [{"op":"remove","path":[1]}]
replay  [ 1, 2 ]
undo    [ <1 empty item> ]

after:
patches [{"op":"replace","path":[0],"value":undefined},{"op":"add","path":[1],"value":2}]
inverse [{"op":"replace","path":[0],"value":1},{"op":"remove","path":[1]}]
replay  [ undefined, 2 ]
undo    [ 1 ]

Checks run locally (Node 24): yarn test (src, build and flow), yarn coverage, yarn test:perf, prettier --check.

Assigning a smaller `length` to a draft array truncated `copy_` without
marking the dropped indices as assigned. If the array then grew back to at
least its base length, generateArrayPatches skipped those indices, so the
patches did not replay to the result and the inverse patches did not restore
the base. Mark the dropped base indices as assigned in the array set trap, as
deleting them one by one already does.

Fixes immerjs#1355

@1AbdullahButt 1AbdullahButt left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Read the trap change against src/core/proxy.ts and generateArrayPatches on main. The diagnosis is right: generateArrayPatches only emits a replace for i < base_.length when assigned_.get(String(i)) (or allIndicesReassigned_) is set. A length write only goes through the set trap for "length", so the dropped indices were never marked. The new tests (especially the "grow back to the same values → no patches" control) cover it well.

One concern is cost when patches are off. The loop runs on every shrinking length write, whether or not enablePatches() was called or the current produce collects patches. Clearing a large draft array with draft.items.length = 0 (a common idiom) used to be O(1) in the trap. It now does Math.min(oldLength, base_.length) Map#set calls, e.g. 100k writes for a 100k-element base. assigned_ is also read outside the patches plugin (finalize.ts shouldFinalize checks assigned_.size, and the nested-draft cleanup reads assigned_.get(key)), so these entries aren't free there either.

Two cheaper options:

  • Guard the loop with whether the current scope collects patches (state.scope_.patches_ / patchPlugin_), so the non-patch path is unchanged.
  • Or record the low-water mark once (e.g. state.minLength_ = Math.min(state.minLength_ ?? base_.length, +value)), and in generateArrayPatches treat i >= minLength_ as assigned. That's O(1) in the trap, and patch generation already loops over those indices.

Small things: the loop runs for every array set (with end === 0 for non-length props), so moving it inside the prop === "length" branch would make the intent clearer. The repo's perf suite (__performance_tests__) could also show whether the extra work matters.

Reviewed with help from Claude Code.

@RClaudiuM

Copy link
Copy Markdown
Author

Thanks for the review. Agreed on the first point: in c160dc5 non-length writes now return straight from objectTraps.set, so the bookkeeping only runs when length is assigned. With that change, the loop's cost is linear in the number of indices dropped by the shrink and nothing else.

@1AbdullahButt 1AbdullahButt left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Read the trap change against src/core/proxy.ts and generateArrayPatches on main. The diagnosis is right: generateArrayPatches only emits a replace for i < base_.length when assigned_.get(String(i)) (or allIndicesReassigned_) is set. A length write only goes through the set trap for "length", so the dropped indices were never marked. The new tests (especially the "grow back to the same values → no patches" control) cover it well.

One concern is cost when patches are off. The loop runs on every shrinking length write, whether or not enablePatches() was called or the current produce collects patches. Clearing a large draft array with draft.items.length = 0 (a common idiom) used to be O(1) in the trap. It now does Math.min(oldLength, base_.length) Map#set calls, e.g. 100k writes for a 100k-element base. assigned_ is also read outside the patches plugin (finalize.ts shouldFinalize checks assigned_.size, and the nested-draft cleanup reads assigned_.get(key)), so these entries aren't free there either.

Two cheaper options:

  • Guard the loop with whether the current scope collects patches (state.scope_.patches_ / patchPlugin_), so the non-patch path is unchanged.
  • Or record the low-water mark once (e.g. state.minLength_ = Math.min(state.minLength_ ?? base_.length, +value)), and in generateArrayPatches treat i >= minLength_ as assigned. That's O(1) in the trap, and patch generation already loops over those indices.

Small things: the loop runs for every array set (with end === 0 for non-length props), so moving it inside the prop === "length" branch would make the intent clearer. The repo's perf suite (__performance_tests__) could also show whether the extra work matters.

Reviewed with help from Claude Code.

Comment thread src/core/proxy.ts Outdated
die(14)
return objectTraps.set!.call(this, state[0], prop, value, state[0])
const arrayState = state[0]
if (prop !== "length")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets add a guard as suggested in the review commends to always take this branch if patch recording is disabled. Further LGTM.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the guard: the length branch now returns early unless the patches plugin is loaded, so without enablePatches() the trap is back to a single set.

I couldn't use scope_.patches_ for it: produce calls usePatchesInScope only after the recipe has run, and a createDraft draft only gets its listener in finishDraft, so during the length write it is still undefined even when patches will be recorded. Guarding on it made the #1355 tests fail again. I added a createDraft/finishDraft test for that case too.

Shrinking length only marks the dropped base indices when the patches plugin is loaded. scope_.patches_ is only set after the recipe has run (and at finishDraft for manual drafts), so it cannot be the guard.

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.

Shrinking an array with length = and growing it back loses the patches for the truncated indices

3 participants