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

Abierto Apto para principiantes
#1,355 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 4 días

@RClaudiuM ya está trabajando en esto.

Desde el 7/11/2026.

  • #1356 de @RClaudiuM — abierto

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
75/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
javascript
Área
backend

Línea de trabajo

Empieza en src/plugins/patches.ts, especialmente en generateArrayPatches_, y sigue cómo el hecho de reducir un array borrador cambia copy_ y assigned_. Añade la prueba de regresión proporcionada para reducir y volver a aumentar length, y ejecuta las pruebas relacionadas con los patches. El trabajo estará terminado cuando los patches de avance reproduzcan el resultado de la receta y los patches inversos restauren la base.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

🐛 Bug Report

With enablePatches(), if a recipe shrinks a draft array by assigning .length and then grows it back to at least its original length, no replace patch (and no inverse patch) is produced for the truncated indices. Replaying the patches on the base gives a different state than the recipe, and the inverse patches do not restore the base. The same recipe written with splice(0) produces correct patches.

Link to repro

Not applicable: no CodeSandbox account; the script below and the unit test at the end reproduce it.

To Reproduce

npm i [email protected], save as t.mjs, run node t.mjs:

import { produceWithPatches, applyPatches, enablePatches } from "immer";
enablePatches();

const base = [1];
const [result, patches, inverse] = produceWithPatches(base, d => {
  d.length = 0; // truncate index 0
  d[1] = 2;     // grow again
});

console.log(result);
console.log(patches);
console.log(inverse);
console.log(applyPatches(base, patches));
console.log(applyPatches(result, inverse));

const [r2, p2, i2] = produceWithPatches([1, 2], d => { d.length = 0; d.length = 2; });
console.log(r2, p2, i2);

Observed behavior

[ <1 empty item>, 2 ]
[ { op: 'add', path: [ 1 ], value: 2 } ]
[ { op: 'remove', path: [ 1 ] } ]
[ 1, 2 ]
[ <1 empty item> ]
[ <2 empty items> ] [] []

applyPatches(base, patches) keeps the stale 1 at index 0, and applyPatches(result, inverse) does not bring it back. The second recipe changes both elements but produces no patches at all.

Expected behavior

The same patches as for d.splice(0); d[1] = 2, which immer already gets right:

[
  { op: 'replace', path: [ 0 ], value: undefined },
  { op: 'add', path: [ 1 ], value: 2 }
] [
  { op: 'replace', path: [ 0 ], value: 1 },
  { op: 'remove', path: [ 1 ] }
]

so that applyPatches(base, patches) gives [ undefined, 2 ] and applyPatches(result, inverse) gives [ 1 ].

generateArrayPatches_ in src/plugins/patches.ts only emits a replace for an index below base.length when assigned_.get(i) is set (or allIndicesReassigned_). Assigning a smaller length truncates copy_ without marking the dropped indices as assigned, so they are skipped once the array is long again.

Unit test:

test("length shrink then grow produces replace patches", () => {
  const base = [1]
  const [result, patches, inverse] = produceWithPatches(base, d => {
    d.length = 0
    d[1] = 2
  })
  expect(applyPatches(base, patches)).toEqual(result)
  expect(applyPatches(result, inverse)).toEqual(base)
})

Environment

We only accept bug reports against the latest Immer version.

  • Immer version: 11.2.9 (also main 75a290e, built from source), Node.js v26.13.0
  • I filed this report against the latest version of Immer
  • Occurs with setUseProxies(true)
  • Occurs with setUseProxies(false) (ES5 only)

Credit: https://ucsbplse.github.io/

Lenguaje dominante
JavaScript
Estrellas
29k
Forks
905
Merge medio
3 d 16 h
PR fusionados (30 d)
22

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de immerjs/immer

Todos los issues de immerjs/immer

Issues similares

Más issues de JavaScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.