#805·automerge

patch state does not fully rollback when an error is thrown in the patchCallback

Author: stephenCreated Nov 23, 2023Updated Aug 28, 2026
Labelsbug

Given a test that looks like:

typescript
test("rollback on automerge patch callback works", () => {
  let doc = Automerge.from({ data: 5 });

  assert.throws(() => {
    doc = Automerge.change(
      doc,
      {
        patchCallback: () => {
          throw new Error("uh oh");
        },
      },
      (doc) => (doc.data = 6)
    );
  });
  assert.equal(doc.data, 5);

  assert.throws(() => {
    doc = Automerge.change(
      doc,
      {
        patchCallback: () => {
          throw new Error("uh oh");
        },
      },
      (doc) => (doc.data = 6)
    );
  });
  assert.equal(doc.data, 5);
});

I would expect this test to pass. Instead I get:

typescript
AssertionError: expected [Function] to throw an error
 ❯ test.ts:42:10
     40|   assert.equal(doc.data, 5);
     41|
     42|   assert.throws(() => {
       |          ^
     43|     doc = Automerge.change(
     44|       doc,

The patch callback isn't called the second time around (which would trigger a throw).

Some observations:

  • The data never does become 6, so that part is working fine
  • If I change the value of the attempted write the second time to something else (i.e. 7) the patchCallback is called like normal. I suspect that means whatever is generating patches doesn't rollback its state on errors, so it thinks the value is now 6 and there is no patch to send