Skip to content

Fix revertChangeset for index-based arrays - #412

Open
aarondpn wants to merge 1 commit into
ltwlf:v4from
aarondpn:fix/revert-index-array-ordering
Open

Fix revertChangeset for index-based arrays#412
aarondpn wants to merge 1 commit into
ltwlf:v4from
aarondpn:fix/revert-index-array-ordering

Conversation

@aarondpn

@aarondpn aarondpn commented Jul 27, 2026

Copy link
Copy Markdown

Problem

revertChangeset corrupts index-based arrays when a changeset contains more than one ADD:

revertChangeset(['a', 'b', 'c'], diff(['a'], ['a', 'b', 'c']))
// => ['a', 'c']   expected ['a']

revertArrayChange iterated $index subchanges in their original ascending order. Reverting an ADD splices the element out, so undoing index 1 first shifts 'c' down into that slot and the subsequent splice(2, 1) becomes a no-op.

applyChangeset already sorts $index REMOVEs descending; the revert path never got the mirrored treatment. This is the revert-side counterpart to #407, which fixed the apply side on master.

revertArrayChange processed $index subchanges in their original ascending
order. Reverting an ADD splices the element out, so an earlier splice shifts
the remaining elements and later indices land on the wrong slot:
revertChangeset(['a','b','c'], diff(['a'], ['a','b','c'])) returned ['a','c'].
ADDs are now undone from the highest index down, mirroring the ordering
applyArrayChange already uses for REMOVE operations.

Two further defects in the same path surfaced while verifying the fix:

- revertLeafChange called addKeyValue without embeddedKey, so reverting a
  REMOVE appended the value instead of splicing it back at its index. This
  affected every type change, since treatTypeChangeAsReplace defaults to true
  and encodes those as a REMOVE/ADD pair at the same index.
- The leaf/branch guard tested subchange.value != null, routing null-valued
  subchanges down the branch path where they were silently dropped. It now
  keys off the presence of nested changes, matching applyArrayChange.

Verified by exhaustive round-trip over all arrays of length 0-4 built from
four distinct types (116281 pairs, both directions): no apply or revert
failures. Existing snapshots are unchanged.
@sonarqubecloud

Copy link
Copy Markdown

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