From 9fd3254a8dece45b5895598fa2446f8a21dd7cd2 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Dec 2026 22:16:39 -0500 Subject: [PATCH] fix: Collaborative persist can overwrite a concurrent API update (#14898) * fix: Collaborative persist can overwrite a concurrent API update Merge the stored state into the snapshot under the row lock before deriving content, so an API update that committed after the snapshot is kept. * chore: Clarify collaborative updater comments --- .../documentCollaborativeUpdater.test.ts | 57 ++++++++++++++++ .../commands/documentCollaborativeUpdater.ts | 66 ++++++++++--------- 2 files changed, 92 insertions(+), 31 deletions(-) diff --git a/server/commands/documentCollaborativeUpdater.test.ts b/server/commands/documentCollaborativeUpdater.test.ts index 2fbd37f258..dd506eb7ed 100644 --- a/server/commands/documentCollaborativeUpdater.test.ts +++ b/server/commands/documentCollaborativeUpdater.test.ts @@ -5,6 +5,7 @@ import { schema } from "@server/editor"; import { createContext } from "@server/context"; import { Document, Event, Revision } from "@server/models"; import { sequelize } from "@server/storage/database"; +import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import { buildDocument, buildUser } from "@server/test/factories"; import documentCollaborativeUpdater from "./documentCollaborativeUpdater"; @@ -128,6 +129,62 @@ describe("documentCollaborativeUpdater", () => { expect(document.updatedAt).toEqual(updatedAt); }); + it("keeps an API update that committed after the snapshot", async () => { + const user = await buildUser(); + const paragraph = (text: string) => ({ + type: "paragraph", + content: [{ type: "text", text }], + }); + const initial = buildYDoc([paragraph("A"), paragraph("B")]); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + }); + await document.update({ + state: Buffer.from(Y.encodeStateAsUpdate(initial)), + }); + + // The collaboration server takes a snapshot and an editor types in A. + const snapshot = new Y.Doc(); + Y.applyUpdate(snapshot, Y.encodeStateAsUpdate(initial)); + const fragment = snapshot.getXmlFragment("default"); + const first = fragment.get(0) as Y.XmlElement; + (first.get(0) as Y.XmlText).insert(1, " typed"); + + // An API update to B commits before the snapshot is persisted. + DocumentHelper.applyToState( + document, + Node.fromJSON(schema, { + type: "doc", + content: [paragraph("A"), paragraph("B changed")], + }) + ); + await document.save(); + + await documentCollaborativeUpdater({ + documentId: document.id, + stateGeneration: 0, + ydoc: snapshot, + collaborators: { ids: [user.id] }, + isLastConnection: true, + clientVersion: null, + }); + + await document.reload(); + const texts = document.content?.content?.map( + (node) => node.content?.[0]?.text + ); + expect(texts).toEqual(["A typed", "B changed"]); + + const { state } = await Document.unscoped().findByPk(document.id, { + attributes: ["state"], + rejectOnEmpty: true, + }); + const stored = new Y.Doc(); + Y.applyUpdate(stored, state!); + expect(stored.getXmlFragment("default").toString()).toContain("B changed"); + }); + it.each(["single", "multiple"])( "uses the last collaborator for attribution with %s collaborators", async (scenario) => { diff --git a/server/commands/documentCollaborativeUpdater.ts b/server/commands/documentCollaborativeUpdater.ts index be12262da3..c4e31487f0 100644 --- a/server/commands/documentCollaborativeUpdater.ts +++ b/server/commands/documentCollaborativeUpdater.ts @@ -26,7 +26,7 @@ interface Props { documentId: string; /** The generation of the collaborative state that the snapshot belongs to. */ stateGeneration: number; - /** Current collaborative state. */ + /** Current collaborative state, the stored state is merged into it. */ ydoc: Y.Doc; /** The collaborators and sequence associated with this snapshot. */ collaborators: CollaboratorSnapshot; @@ -59,35 +59,6 @@ export default async function documentCollaborativeUpdater({ isLastConnection, clientVersion, }: Props): Promise { - const state = Y.encodeStateAsUpdate(ydoc); - - // Round-trip through the schema so the stored JSON is canonical. The raw - // y-prosemirror output includes empty `attrs: {}` on every mark, and outputs - // properties in a different order - resulting in spurious "edits". The JSON - // round-trip additionally drops undefined-valued attrs, which are absent - // from previously stored content but present on `Node.toJSON` output. - const content = JSON.parse( - JSON.stringify( - Node.fromJSON(schema, yDocToProsemirrorJSON(ydoc, "default")).toJSON() - ) - ) as ProsemirrorData; - - // extract collaborators from doc user data - const pud = new Y.PermanentUserData(ydoc); - const pudIds = Array.from(pud.clients.values()); - - // State over the maximum length can not be saved. Edit history can make the - // state much larger than the content, so replace it with new state built - // from the content. Large state under the maximum is replaced when the - // document is idle, see documentStateFlattener. - let flattenedState: Buffer | undefined; - if (state.length > DocumentValidation.maxStateLength) { - const flattened = ProsemirrorHelper.flatten(content); - if (flattened.length <= DocumentValidation.maxStateLength) { - flattenedState = flattened; - } - } - return sequelize.transaction(async (transaction) => { // Persistence is not bound to an HTTP request, so it must not inherit the // request statement timeout of the collaboration process. @@ -97,7 +68,7 @@ export default async function documentCollaborativeUpdater({ ); // Only the columns read below are selected, the deprecated markdown text - // and collaborative state can each be megabytes and are not needed here. + // can be megabytes and is not needed here. const document = await Document.unscoped().findOne({ attributes: [ "id", @@ -109,6 +80,7 @@ export default async function documentCollaborativeUpdater({ "editorVersion", "lastModifiedById", "revisionCount", + "state", "stateGeneration", "teamId", ], @@ -133,6 +105,38 @@ export default async function documentCollaborativeUpdater({ return { reset: true }; } + // Merge in the stored state, which can have API updates made after ydoc + // was copied from the collaboration room. + if (document.state) { + Y.applyUpdate(ydoc, document.state); + } + + const state = Y.encodeStateAsUpdate(ydoc); + + // Round-trip through the schema so the stored JSON is canonical. The raw + // y-prosemirror output includes empty `attrs: {}` on every mark, and outputs + // properties in a different order - resulting in spurious "edits". The JSON + // round-trip additionally drops undefined-valued attrs, which are absent + // from previously stored content but present on `Node.toJSON` output. + const content = JSON.parse( + JSON.stringify( + Node.fromJSON(schema, yDocToProsemirrorJSON(ydoc, "default")).toJSON() + ) + ) as ProsemirrorData; + + // extract collaborators from doc user data + const pud = new Y.PermanentUserData(ydoc); + const pudIds = Array.from(pud.clients.values()); + + // Rebuild state that is over the maximum length from the content. + let flattenedState: Buffer | undefined; + if (state.length > DocumentValidation.maxStateLength) { + const flattened = ProsemirrorHelper.flatten(content); + if (flattened.length <= DocumentValidation.maxStateLength) { + flattenedState = flattened; + } + } + const isUnchanged = isEqual(document.content, content); const isDeleted = !!document.deletedAt; const lastModifiedById = isDeleted