Repository navigation
[lexical-devtools][lexical-website][lexical-y] Feature: Experimental server-side editing API (@lexical/y/headless) - #9437
Merged
Merged
Conversation
zurfyx
requested review from
acywatson,
etrepum,
fantactuka,
ivailop7 and
potatowagon
as code owners
October 22, 2026 14:14
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
lexical
@lexical/a11y
@lexical/clipboard
@lexical/code
@lexical/code-core
@lexical/code-prism
@lexical/code-shiki
@lexical/compiler
@lexical/devtools-core
@lexical/dragon
@lexical/eslint-plugin
@lexical/extension
@lexical/fast-check
@lexical/file
@lexical/hashtag
@lexical/headless
@lexical/history
@lexical/html
@lexical/internal
@lexical/link
@lexical/list
@lexical/mark
@lexical/markdown
@lexical/mdast
@lexical/offset
@lexical/overflow
@lexical/plain-text
@lexical/react
@lexical/rich-text
@lexical/selection
@lexical/table
@lexical/tailwind
@lexical/text
@lexical/utils
@lexical/y
@lexical/yjs
commit: |
potatowagon
approved these changes
Oct 22, 2026
zurfyx
force-pushed
the
zurfyx/collab-y14-block-markers
branch
from
October 23, 2026 13:02
777c5dc to
b0b85cd
Compare
zurfyx
force-pushed
the
zurfyx/collab-y-server
branch
from
October 23, 2026 13:02
bffe9c2 to
a4a139f
Compare
zurfyx
changed the base branch from
zurfyx/collab-y14-block-markers
to
zurfyx/collab-y-moves
October 23, 2026 13:02
zurfyx
added a commit
that referenced
this pull request
Oct 23, 2026
…round, with e2e specs ## Description Stacked on #9437 (the `@lexical/y` stack: #9400, #9449, #9437). Current behavior: the playground can run collaboration on `@lexical/yjs` only (collab v1 with `CollaborationPlugin`, v2 with `CollaborationPluginV2__EXPERIMENTAL`, chosen with `?isCollab=true` and `?useCollabV2=true`). The experimental `@lexical/y` binding (Yjs 14, `@y/y`) cannot be tried in the playground, and the repo's e2e suite does not cover it. New behavior (opt-in; the default playground, `pnpm run start` and collab v1/v2 are unchanged): - `?isCollab=true&useCollabY=true` runs the playground on `@lexical/y`: the editor gets `YCollabExtension` with a `@y/y` document and a `@y/websocket` provider (`4.0.0-rc.2`, the published Yjs 14 client). The playground pins `@y/y` to `14.0.0-rc.29`, the version `@lexical/y` pins, so the lockfile holds one `@y/y`. The mode lives in its own chunk (`collaborationY.tsx`, loaded with `import()`), so the default playground does not load a second Yjs. `HistoryExtension` is left out in this mode (`YCollabExtension` provides undo and conflicts with it). The toolbar's connect button connects and disconnects the provider; the binding is initialized after the provider's first sync; a document whose layout this client does not support shows a read-only notice. - `pnpm run collab:y` starts a Yjs 14 relay on `localhost:1235` (`packages/lexical-playground/scripts/collab-y-server.mjs`), and `pnpm run start:y` starts it together with the playground dev server. `pnpm run start` is unchanged (dev server and the `@lexical/yjs` collab server). The published `@y/websocket-server` still depends on the pre-`@y/y` Yjs 14 prereleases (`yjs@14.0.0-*`), whose documents are not compatible with `@y/y`, so the relay is a small in-memory y-websocket protocol server on `@y/y`, `@y/protocols` and `lib0` 1.x, with a test-only `/delay` endpoint. - Playground features the binding does not sync are handled explicitly: nested editors (image captions, sticky notes) are read only in this mode and "Add Caption" is not offered; comments are off (as in collab v2: the comment threads live in a Yjs 13 document); there are no remote cursors. Playground nodes without collab declarations use the binding's nested storage. Comments keep using MarkNode. - E2E: a new editor mode, `E2E_EDITOR_MODE=rich-text-with-collab-y` (`pnpm run test-e2e-collab-y-{chromium,firefox,webkit}`, against `pnpm run start:y`), runs `Collaboration.spec.mjs` and the new `CollabY*.spec.mjs`. `Collaboration.spec.mjs` is parameterized: where collab v1/v2 drop a peer's text on undo, collab Y asserts that the peer's text stays (undo only reverts the client's own changes), and collab Y does not restore the selection an undo step was made with, so that test places the caret explicitly. The new specs open each client in its own browser context (own keyboard), delay the relay's server-to-client messages while clients edit at the same time, and end every case by checking that all clients converge, that a client loading the document afterwards shows the same, that no typed token is lost or duplicated, and that no client logged an error or warning (the binding's development self-check reports through warnings). They cover: Enter, Backspace and Delete at line boundaries, heading/quote toggles and list create/indent/outdent while peers type; links while peers type inside and after the link; offline edits on both sides (text and structure, and a 30-lines-per-side divergence) and reconnect; undo isolation (own typing, Enter and heading undone after peer edits, undo while the peer types inside the undone text); the layout version gate (a document marked with layout 3, which this client does not read, makes open and late-joining clients read only); tables (cell typing, concurrent row and column insert stays rectangular, two rows inserted at one place); images (synced, no caption offered); and IME composition (Chromium, CDP) while a peer types, splits or joins the line. - CI: a `collab-y-linux` job (Chromium and Firefox) runs the mode the way `collab-v2-linux` runs collab v2, starting `pnpm run collab:y` instead of `pnpm run collab`. ## Test plan ### Before ``` $ pnpm run collab:y [ERR_PNPM_NO_SCRIPT] Missing script: collab:y $ pnpm run start:y [ERR_PNPM_NO_SCRIPT] Missing script: start:y $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium | grep -c CollabY 0 ``` `?useCollabY=true` is not a playground setting (it is ignored, and `?isCollab=true` runs collab v1); no playground source imports `@lexical/y`. ### After ``` $ HOST=localhost PORT=1291 node packages/lexical-playground/scripts/collab-y-server.mjs # what collab:y runs, on a free port Yjs 14 (@lexical/y) relay running on ws://localhost:1291 $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium Total: 26 tests in 4 files # Collaboration 6, CollabYNodes 6, CollabYStructure 8, CollabYSync 6 ``` Collab Y mode, development playground build (`pnpm run build-playground-dev`, served with `vite preview`), relay from `collab-y-server.mjs`, no retries: ``` $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=2 --retries=0 26 passed (1.1m) $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0 3 skipped 23 passed (1.3m) # the 3 IME specs are Chromium only $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=webkit --workers=2 --retries=0 3 skipped 23 passed (1.2m) $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=6 --retries=0 --repeat-each=3 78 passed (1.3m) # previous base revision ``` The version gate spec marks the document with layout 3. Marking it one past the root's version, as the previous revision of the spec did, writes layout 2 on a new document, which `@lexical/y` reads since block moves (#9449): ``` $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium CollabYSync -g 'version gate' # previous revision of the spec Error: expect(received).toBe(expected) // Object.is equality Expected: "readonly" Received: "active" 1 failed # this revision 1 passed (4.3s) ``` Collab v1/v2 are unchanged: ``` $ E2E_EDITOR_MODE=rich-text-with-collab npx playwright test --project=chromium --workers=2 --retries=0 Collaboration.spec 6 passed (7.3s) $ E2E_EDITOR_MODE=rich-text-with-collab-v2 npx playwright test --project=chromium --workers=6 --retries=0 Collaboration.spec 6 passed (3.8s) # previous base revision ``` Also: `pnpm run tsc` (0 errors), `pnpm run flow` (0 errors), eslint and prettier on the touched files, the tree-shaking tests (`scripts/__tests__/integration/tree-shaking.test.mjs`, 286 tests; `treeShakingSource.test.ts`, 363 tests), `npx vitest --project unit packages/lexical-playground` (33 files, 390 tests), `pnpm run build`, and `pnpm run build-playground-dev` (`@lexical/y` is only in the `collaborationY` chunk). Not exercised: the CI workflow itself (run locally only), macOS and Windows, the production playground build in a browser, and real IME input (CDP composition events only).
zurfyx
added a commit
that referenced
this pull request
Oct 23, 2026
## Description Stacked on #9438 (the `@lexical/y` stack: #9400, #9449, #9437, #9438). Depends on #9380 (`MarkStateExtension` and `collab: 'set'` NodeState). This branch carries that commit as a temporary dependency commit, to be dropped once #9380 merges. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own Y.Node, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` format per member (`splitCollabStateEntries`). Concurrent additions and removals of different members merge. Reading is unchanged: NodeState joins the member entries back into the set (#9380). Block markers, wrappers and list groups still store the set whole. - A peer that does not know the state keeps each member as its own NodeState key and writes it back unchanged, so it never collapses the members. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, so it reads the members the same way (otherwise every write of a set would be reported to the binding's `onWarn` as a `'self-check'` warning). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one set-valued state, like `MarkStateExtension`; `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit in the `@lexical/y` README and on the Yjs 14 collaboration page now says where the set is stored per member and where it is still one value (line markers, groups, inline wrappers). Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 83 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 12 / 142 / 10 113 / 144 / 113 ``` ## Test plan New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. ### Before `Schema.ts` and `SelfCheck.ts` reverted to the dependency commit: ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 Tests 17 failed | 40 passed (57) ``` ### After ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y packages/lexical-yjs packages/lexical-mark packages/lexical-react/src/__tests__/unit/Collab packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts Test Files 75 passed (75) Tests 3209 passed | 8 expected fail | 2 skipped (3219) ``` The 8 expected failures are `MarkStateCollab.test.tsx`'s pinned v2 and v1 limits from #9380 (#9381 is not in this stack). The 2 skipped tests are in `ListsInLines.test.ts` and are skipped on #9400 as well. Fuzz with comments as one set-valued state, 500 seeds plus 100 gc seeds: ``` $ FUZZ_SEEDS=500 npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/Fuzz.test.ts ✓ seeds 1..51 ... ✓ seeds 451..501, ✓ gc seeds 1..51, ✓ gc seeds 51..101 Tests 12 passed (12) ``` On the whole stack (this commit on top), the same fuzz at 2,000 + 500 gc seeds, with and without block moves, passes (116 of 116 chunks), and so does `pnpm run test-unit` (443 files). Also run: `pnpm run tsc`, `pnpm run flow` (0 errors), eslint and prettier on the touched files, `pnpm run build`, the tree-shaking tests (source 364 pass, build output 286 pass) and `pnpm run build-docs`. Not exercised: real Yjs 14 providers and browsers.
zurfyx
force-pushed
the
zurfyx/collab-y-moves
branch
from
October 23, 2026 14:50
6919907 to
c14c0a2
Compare
zurfyx
force-pushed
the
zurfyx/collab-y-server
branch
from
October 23, 2026 14:50
a4a139f to
ee1a527
Compare
zurfyx
added a commit
that referenced
this pull request
Oct 23, 2026
…round, with e2e specs ## Description Stacked on #9437 (the `@lexical/y` stack: #9400, #9449, #9437). Current behavior: the playground can run collaboration on `@lexical/yjs` only (collab v1 with `CollaborationPlugin`, v2 with `CollaborationPluginV2__EXPERIMENTAL`, chosen with `?isCollab=true` and `?useCollabV2=true`). The experimental `@lexical/y` binding (Yjs 14, `@y/y`) cannot be tried in the playground, and the repo's e2e suite does not cover it. New behavior (opt-in; the default playground, `pnpm run start` and collab v1/v2 are unchanged): - `?isCollab=true&useCollabY=true` runs the playground on `@lexical/y`: the editor gets `YCollabExtension` with a `@y/y` document and a `@y/websocket` provider (`4.0.0-rc.2`, the published Yjs 14 client). The playground pins `@y/y` to `14.0.0-rc.29`, the version `@lexical/y` pins, so the lockfile holds one `@y/y`. The mode lives in its own chunk (`collaborationY.tsx`, loaded with `import()`), so the default playground does not load a second Yjs. `HistoryExtension` is left out in this mode (`YCollabExtension` provides undo and conflicts with it). The toolbar's connect button connects and disconnects the provider; the binding is initialized after the provider's first sync; a document whose layout this client does not support shows a read-only notice. - `pnpm run collab:y` starts a Yjs 14 relay on `localhost:1235` (`packages/lexical-playground/scripts/collab-y-server.mjs`), and `pnpm run start:y` starts it together with the playground dev server. `pnpm run start` is unchanged (dev server and the `@lexical/yjs` collab server). The published `@y/websocket-server` still depends on the pre-`@y/y` Yjs 14 prereleases (`yjs@14.0.0-*`), whose documents are not compatible with `@y/y`, so the relay is a small in-memory y-websocket protocol server on `@y/y`, `@y/protocols` and `lib0` 1.x, with a test-only `/delay` endpoint. - Playground features the binding does not sync are handled explicitly: nested editors (image captions, sticky notes) are read only in this mode and "Add Caption" is not offered; comments are off (as in collab v2: the comment threads live in a Yjs 13 document); there are no remote cursors. Playground nodes without collab declarations use the binding's nested storage. Comments keep using MarkNode. - E2E: a new editor mode, `E2E_EDITOR_MODE=rich-text-with-collab-y` (`pnpm run test-e2e-collab-y-{chromium,firefox,webkit}`, against `pnpm run start:y`), runs `Collaboration.spec.mjs` and the new `CollabY*.spec.mjs`. `Collaboration.spec.mjs` is parameterized: where collab v1/v2 drop a peer's text on undo, collab Y asserts that the peer's text stays (undo only reverts the client's own changes), and collab Y does not restore the selection an undo step was made with, so that test places the caret explicitly. The new specs open each client in its own browser context (own keyboard), delay the relay's server-to-client messages while clients edit at the same time, and end every case by checking that all clients converge, that a client loading the document afterwards shows the same, that no typed token is lost or duplicated, and that no client logged an error or warning (the binding's development self-check reports through warnings). Console messages that are not about the editor are filtered by one list in the collab Y spec utilities (the other e2e specs do not read the console): failed resource loads, relay reconnects, Vite and React DevTools notices, and Firefox's "Loading failed for the <script>" for the playground's Vercel analytics scripts (`/_vercel/insights/script.js`, `/_vercel/speed-insights/script.js`), which a local or CI build does not serve (Chromium and WebKit report the same as "Failed to load resource"). They cover: Enter, Backspace and Delete at line boundaries, heading/quote toggles and list create/indent/outdent while peers type; links while peers type inside and after the link; offline edits on both sides (text and structure, and a 30-lines-per-side divergence) and reconnect; undo isolation (own typing, Enter and heading undone after peer edits, undo while the peer types inside the undone text); the layout version gate (a document marked with layout 3, which this client does not read, makes open and late-joining clients read only); tables (cell typing, concurrent row and column insert stays rectangular, two rows inserted at one place); images (synced, no caption offered); and IME composition (Chromium, CDP) while a peer types, splits or joins the line. - CI: a `collab-y-linux` job (Chromium and Firefox) runs the mode the way `collab-v2-linux` runs collab v2, starting `pnpm run collab:y` instead of `pnpm run collab`. ## Test plan ### Before ``` $ pnpm run collab:y [ERR_PNPM_NO_SCRIPT] Missing script: collab:y $ pnpm run start:y [ERR_PNPM_NO_SCRIPT] Missing script: start:y $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium | grep -c CollabY 0 ``` `?useCollabY=true` is not a playground setting (it is ignored, and `?isCollab=true` runs collab v1); no playground source imports `@lexical/y`. ### After ``` $ HOST=localhost PORT=1291 node packages/lexical-playground/scripts/collab-y-server.mjs # what collab:y runs, on a free port Yjs 14 (@lexical/y) relay running on ws://localhost:1291 $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium Total: 26 tests in 4 files # Collaboration 6, CollabYNodes 6, CollabYStructure 8, CollabYSync 6 ``` Collab Y mode, development playground build (`pnpm run build-playground-dev`, served with `vite preview`), relay from `collab-y-server.mjs`, no retries: ``` $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=2 --retries=0 26 passed (1.1m) $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0 3 skipped 23 passed (1.3m) # the 3 IME specs are Chromium only $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=webkit --workers=2 --retries=0 3 skipped 23 passed (1.2m) # previous base revision $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=6 --retries=0 --repeat-each=3 78 passed (1.3m) # previous base revision ``` Firefox without the Vercel scripts (as in CI; the build serves no `/_vercel/` files), the previous revision of the console filter, then this one: ``` $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0 # previous revision Error: console errors or warnings + "[F] console.warning: [JavaScript Warning: \"Loading failed for the <script> with source “http://localhost:4471/_vercel/speed-insights/script.js”.\" …]" 17 failed 3 skipped 6 passed (1.5m) # this revision 3 skipped 23 passed (1.3m) ``` The version gate spec marks the document with layout 3. Marking it one past the root's version, as the previous revision of the spec did, writes layout 2 on a new document, which `@lexical/y` reads since block moves (#9449): ``` $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium CollabYSync -g 'version gate' # previous revision of the spec Error: expect(received).toBe(expected) // Object.is equality Expected: "readonly" Received: "active" 1 failed # this revision 1 passed (4.3s) ``` Collab v1/v2 are unchanged: ``` $ E2E_EDITOR_MODE=rich-text-with-collab npx playwright test --project=chromium --workers=2 --retries=0 Collaboration.spec 6 passed (7.3s) $ E2E_EDITOR_MODE=rich-text-with-collab-v2 npx playwright test --project=chromium --workers=6 --retries=0 Collaboration.spec 6 passed (3.8s) # previous base revision ``` Also: `pnpm run tsc` (0 errors), `pnpm run flow` (0 errors), eslint and prettier on the touched files, the tree-shaking tests (`scripts/__tests__/integration/tree-shaking.test.mjs`, 286 tests; `treeShakingSource.test.ts`, 363 tests), `npx vitest --project unit packages/lexical-playground` (33 files, 390 tests), `pnpm run build`, and `pnpm run build-playground-dev` (`@lexical/y` is only in the `collaborationY` chunk). Not exercised: the CI workflow itself (run locally only), macOS and Windows, the production playground build in a browser, and real IME input (CDP composition events only).
zurfyx
added a commit
that referenced
this pull request
Oct 23, 2026
## Description Stacked on #9438 (the `@lexical/y` stack: #9400, #9449, #9437, #9438). Depends on #9380 (`MarkStateExtension` and `collab: 'set'` NodeState). This branch carries that commit as a temporary dependency commit, to be dropped once #9380 merges. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own Y.Node, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` format per member (`splitCollabStateEntries`). Concurrent additions and removals of different members merge. Reading is unchanged: NodeState joins the member entries back into the set (#9380). Block markers, wrappers and list groups still store the set whole. - A peer that does not know the state keeps each member as its own NodeState key and writes it back unchanged, so it never collapses the members. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, so it reads the members the same way (otherwise every write of a set would be reported to the binding's `onWarn` as a `'self-check'` warning). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one set-valued state, like `MarkStateExtension`; `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (paragraphs and list items, lists, links); the README's wire format adds the member entries (`s:<key>\u001f<member>` = `true`); the Comments and NodeState pages name `@lexical/y` among the bindings that store members separately. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 83 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 12 / 142 / 10 113 / 144 / 113 ``` ## Test plan New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. ### Before `Schema.ts` and `SelfCheck.ts` reverted to the dependency commit: ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 Tests 17 failed | 40 passed (57) ``` ### After ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y packages/lexical-yjs packages/lexical-mark packages/lexical-react/src/__tests__/unit/Collab packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts Test Files 76 passed (76) Tests 3256 passed | 8 expected fail | 2 skipped (3266) ``` The 8 expected failures are `MarkStateCollab.test.tsx`'s pinned v2 and v1 limits from #9380 (#9381 is not in this stack). The 2 skipped tests are in `ListsInLines.test.ts` and are skipped on #9400 as well. Fuzz with comments as one set-valued state, on the whole stack (this commit on top), 2,000 seeds plus 500 gc seeds, without and with block moves (25 seeds per test): ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts ✓ @lexical/y fuzz (100) ✓ @lexical/y fuzz with block moves (103) Tests 203 passed (203) ``` `pnpm run test-unit` on the whole stack: 444 files, 11,999 passed, 3 skipped. Also run: `pnpm run tsc`, `pnpm run flow` (0 errors), eslint and prettier on the touched files, `pnpm run build`, the tree-shaking tests (source 364 pass, build output 286 pass) and `pnpm run build-docs`. Not exercised: real Yjs 14 providers and browsers.
zurfyx
force-pushed
the
zurfyx/collab-y-moves
branch
from
October 23, 2026 16:08
c14c0a2 to
5fe1a90
Compare
zurfyx
force-pushed
the
zurfyx/collab-y-server
branch
from
October 23, 2026 16:08
ee1a527 to
4d81af9
Compare
zurfyx
added a commit
that referenced
this pull request
Oct 23, 2026
…round, with e2e specs ## Description Stacked on #9437 (the `@lexical/y` stack: #9400, #9449, #9437). Current behavior: the playground can run collaboration on `@lexical/yjs` only (collab v1 with `CollaborationPlugin`, v2 with `CollaborationPluginV2__EXPERIMENTAL`, chosen with `?isCollab=true` and `?useCollabV2=true`). The experimental `@lexical/y` binding (Yjs 14, `@y/y`) cannot be tried in the playground, and the repo's e2e suite does not cover it. New behavior (opt-in; the default playground, `pnpm run start` and collab v1/v2 are unchanged): - `?isCollab=true&useCollabY=true` runs the playground on `@lexical/y`: the editor gets `YCollabExtension` with a `@y/y` document and a `@y/websocket` provider (`4.0.0-rc.2`, the published Yjs 14 client). The playground pins `@y/y` to `14.0.0-rc.29`, the version `@lexical/y` pins, so the lockfile holds one `@y/y`. The mode lives in its own chunk (`collaborationY.tsx`, loaded with `import()`), so the default playground does not load a second Yjs. `HistoryExtension` is left out in this mode (`YCollabExtension` provides undo and conflicts with it). The toolbar's connect button connects and disconnects the provider; the binding is initialized after the provider's first sync; a document whose layout this client does not support shows a read-only notice. - `pnpm run collab:y` starts a Yjs 14 relay on `localhost:1235` (`packages/lexical-playground/scripts/collab-y-server.mjs`), and `pnpm run start:y` starts it together with the playground dev server. `pnpm run start` is unchanged (dev server and the `@lexical/yjs` collab server). The published `@y/websocket-server` still depends on the pre-`@y/y` Yjs 14 prereleases (`yjs@14.0.0-*`), whose documents are not compatible with `@y/y`, so the relay is a small in-memory y-websocket protocol server on `@y/y`, `@y/protocols` and `lib0` 1.x, with a test-only `/delay` endpoint. - Playground features the binding does not sync are handled explicitly: nested editors (image captions, sticky notes) are read only in this mode and "Add Caption" is not offered; comments are off (as in collab v2: the comment threads live in a Yjs 13 document); there are no remote cursors. Playground nodes without collab declarations use the binding's nested storage. Comments keep using MarkNode. - E2E: a new editor mode, `E2E_EDITOR_MODE=rich-text-with-collab-y` (`pnpm run test-e2e-collab-y-{chromium,firefox,webkit}`, against `pnpm run start:y`), runs `Collaboration.spec.mjs` and the new `CollabY*.spec.mjs`. `Collaboration.spec.mjs` is parameterized: where collab v1/v2 drop a peer's text on undo, collab Y asserts that the peer's text stays (undo only reverts the client's own changes), and collab Y does not restore the selection an undo step was made with, so that test places the caret explicitly. The new specs open each client in its own browser context (own keyboard), delay the relay's server-to-client messages while clients edit at the same time, and end every case by checking that all clients converge, that a client loading the document afterwards shows the same, that no typed token is lost or duplicated, and that no client logged an error or warning (the binding's development self-check reports through warnings). Console messages that are not about the editor are filtered by one list in the collab Y spec utilities (the other e2e specs do not read the console): failed resource loads, relay reconnects, Vite and React DevTools notices, and Firefox's "Loading failed for the <script>" for the playground's Vercel analytics scripts (`/_vercel/insights/script.js`, `/_vercel/speed-insights/script.js`), which a local or CI build does not serve (Chromium and WebKit report the same as "Failed to load resource"). They cover: Enter, Backspace and Delete at line boundaries, heading/quote toggles and list create/indent/outdent while peers type; links while peers type inside and after the link; offline edits on both sides (text and structure, and a 30-lines-per-side divergence) and reconnect; undo isolation (own typing, Enter and heading undone after peer edits, undo while the peer types inside the undone text); the layout version gate (a document marked with layout 3, which this client does not read, makes open and late-joining clients read only); tables (cell typing, concurrent row and column insert stays rectangular, two rows inserted at one place); images (synced, no caption offered); and IME composition (Chromium, CDP) while a peer types, splits or joins the line. - CI: a `collab-y-linux` job (Chromium and Firefox) runs the mode the way `collab-v2-linux` runs collab v2, starting `pnpm run collab:y` instead of `pnpm run collab`. ## Test plan ### Before ``` $ pnpm run collab:y [ERR_PNPM_NO_SCRIPT] Missing script: collab:y $ pnpm run start:y [ERR_PNPM_NO_SCRIPT] Missing script: start:y $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium | grep -c CollabY 0 ``` `?useCollabY=true` is not a playground setting (it is ignored, and `?isCollab=true` runs collab v1); no playground source imports `@lexical/y`. ### After ``` $ HOST=localhost PORT=1291 node packages/lexical-playground/scripts/collab-y-server.mjs # what collab:y runs, on a free port Yjs 14 (@lexical/y) relay running on ws://localhost:1291 $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium Total: 26 tests in 4 files # Collaboration 6, CollabYNodes 6, CollabYStructure 8, CollabYSync 6 ``` Collab Y mode, development playground build (`pnpm run build-playground-dev`, served with `vite preview`), relay from `collab-y-server.mjs`, no retries: ``` $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=2 --retries=0 26 passed (1.1m) $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0 3 skipped 23 passed (1.3m) # the 3 IME specs are Chromium only $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=webkit --workers=2 --retries=0 3 skipped 23 passed (1.2m) # previous base revision $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=6 --retries=0 --repeat-each=3 78 passed (1.3m) # previous base revision ``` Firefox without the Vercel scripts (as in CI; the build serves no `/_vercel/` files), the previous revision of the console filter, then this one: ``` $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0 # previous revision Error: console errors or warnings + "[F] console.warning: [JavaScript Warning: \"Loading failed for the <script> with source “http://localhost:4471/_vercel/speed-insights/script.js”.\" …]" 17 failed 3 skipped 6 passed (1.5m) # this revision 3 skipped 23 passed (1.3m) ``` The version gate spec marks the document with layout 3. Marking it one past the root's version, as the previous revision of the spec did, writes layout 2 on a new document, which `@lexical/y` reads since block moves (#9449): ``` $ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium CollabYSync -g 'version gate' # previous revision of the spec Error: expect(received).toBe(expected) // Object.is equality Expected: "readonly" Received: "active" 1 failed # this revision 1 passed (4.3s) ``` Collab v1/v2 are unchanged: ``` $ E2E_EDITOR_MODE=rich-text-with-collab npx playwright test --project=chromium --workers=2 --retries=0 Collaboration.spec 6 passed (7.3s) $ E2E_EDITOR_MODE=rich-text-with-collab-v2 npx playwright test --project=chromium --workers=6 --retries=0 Collaboration.spec 6 passed (3.8s) # previous base revision ``` Also: `pnpm run tsc` (0 errors), `pnpm run flow` (0 errors), eslint and prettier on the touched files, the tree-shaking tests (`scripts/__tests__/integration/tree-shaking.test.mjs`, 286 tests; `treeShakingSource.test.ts`, 363 tests), `npx vitest --project unit packages/lexical-playground` (33 files, 390 tests), `pnpm run build`, and `pnpm run build-playground-dev` (`@lexical/y` is only in the `collaborationY` chunk). Not exercised: the CI workflow itself (run locally only), macOS and Windows, the production playground build in a browser, and real IME input (CDP composition events only).
zurfyx
added a commit
that referenced
this pull request
Oct 23, 2026
## Description Stacked on #9438 (the `@lexical/y` stack: #9400, #9449, #9437, #9438). Depends on #9380 (`MarkStateExtension` and `setValue`, set-valued NodeState). This branch carries that commit as a temporary dependency commit, to be dropped once #9380 merges. Current behavior: `@lexical/y` stores each NodeState entry of a text run, line break or inline node as one `s:<key>` format holding the serialized value. A set-valued state such as `MarkStateExtension`'s `markIds` (`createState('markIds', {parse: setValue(stringValue())})`) is one array per run, so when two peers comment on the same text concurrently, one peer's comments win (last writer wins on the whole set). New behavior: - On text runs, line breaks and nodes stored as their own `Y.Node`, a set-valued state known for the node type is written as one `s:<key>\u001f<member>` = `true` format (or attribute) per member, so concurrent additions and removals of different members merge. Block markers, wrappers and list groups still store the set whole. - A state is set-valued when its schema says so, `stateConfig.schema?.meta.kind === 'set'` (what `setValue` produces). It is known for a node when it is used on it or registered for its type (as `MarkStateExtension` does for every node type when the editor is built). Splitting and joining the members is internal to `@lexical/y`; `lexical` gets no new API from this change. - Reading joins the member entries back into one array, which the state parses into its set, only when the reader knows a set-valued state with that key for the node type and no StateConfig uses the entry key itself. A peer that does not know the state keeps each member as its own NodeState key and writes it back unchanged, so it never collapses the members. A whole `s:<key>` array next to member entries (stored by an earlier `@lexical/y` build) is merged with them, and the next write stores it per member. A value state whose key contains U+001F is never read as a member, and a set-valued state whose own key contains U+001F is stored whole. - The self-check's fresh editor gets the set-valued StateConfigs registered on the binding's editor, so it reads the members the same way (otherwise every write of a set would be reported to the binding's `onWarn` as a `'self-check'` warning). - `@lexical/yjs` is unchanged (it stores a set as one value). - Tests: the harness takes a `prepare(editor)` hook (run before the binding starts; fresh readers reuse it). The fuzz now stores comments as one `setValue` state, like `MarkStateExtension`; `FUZZ_COMMENTS=keys` keeps the previous one-boolean-key-per-id model. `Size.test.ts` budgets three `MarkStateExtension` operations. - Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page says where the set is stored per member and where it is still one value (lines such as paragraphs and headings, list items, lists, links); the README's wire format adds the member entries (`s:<key>\u001f<member>` = `true`); the "Set-valued state" section of the NodeState page and the "Concurrent changes to the same ids" note of the Comments page say that `@lexical/y` stores the members separately. Limit: a peer that does not know the state exports the members it keeps as separate keys in its JSON (`"markIds\u001fc1": true`), and Lexical does not join those keys when the JSON is loaded later. Register the state on every peer, as the docs say. Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client ids), op / undo / redo: ``` one format per id whole set (before) add a comment 83 / 10 / 77 92 / 10 / 86 add an overlapping comment 83 / 10 / 77 196 / 45 / 190 remove one of two comments 12 / 142 / 10 113 / 144 / 113 ``` ## Test plan New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers (ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with concurrent comments on the same and on overlapping ranges, across a line break, resolving while a peer types, resolving one of two comments, undo while a peer types, the stored format keys, and a peer that does not know the state editing commented text. New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic `setValue(stringValue())` state, both client id orders: concurrent additions merge on a text run, an inline decorator and a block decorator, stored one key per member on each; a removal and a concurrent addition both apply; a paragraph stores the set as one `s:tags` attribute (last writer wins); a value state whose key contains U+001F is not read as a member; a set-valued state whose key contains U+001F is stored whole. ### Before `Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to the dependency commit: ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts × each id is its own format key (4 of 4 orders) AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ] × two peers mark the same range (4 of 4 orders) AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…' × two peers mark overlapping ranges (4 of 4 orders) × two peers mark overlapping ranges across a line break AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…' × keeps each id as its own format when it edits marked text × concurrent additions merge on text and stored nodes (2 of 2 orders) AssertionError: expected 'paragraph[] text[a] test_equation[a] …' to be 'paragraph[] text[a,b] test_equation[a…' × a removal and a concurrent addition both apply (2 of 2 orders) AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …' × add a comment (MarkStateExtension) AssertionError: expected 92 to be less than or equal to 90 × add an overlapping comment (MarkStateExtension) AssertionError: expected 196 to be less than or equal to 90 × remove a comment (MarkStateExtension) AssertionError: expected 113 to be less than or equal to 14 Test Files 3 failed (3) Tests 21 failed | 44 passed (65) ``` ### After ``` $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y Test Files 56 passed (56) Tests 2242 passed | 2 skipped (2244) $ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-mark Test Files 12 passed (12) Tests 781 passed | 4 expected fail (785) ``` The 2 skipped tests are in `ListsInLines.test.ts` and are skipped on #9400 as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned `@lexical/yjs` limits from #9380. Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds, without and with block moves (25 seeds per test), and the default run with one boolean key per comment: ``` $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/Fuzz.test.ts ✓ @lexical/y fuzz (100) ✓ @lexical/y fuzz with block moves (103) Tests 203 passed (203) $ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/Fuzz.test.ts Tests 29 passed (29) ``` Also run: `pnpm run tsc`, `pnpm run flow` (0 errors), eslint and prettier on the touched files, and `scripts/__tests__/unit/treeShakingSource.test.ts` (364 passed). Not exercised: real Yjs 14 providers and browsers.
zurfyx
added a commit
that referenced
this pull request
Oct 26, 2026
Stacked on #9439 (the `@lexical/y` stack: #9400, #9437, #9438, #9439). This PR is now last in the stack. > **Status: rebased, not yet reworked.** This change was moved to the end of > the stack and onto #9400's v3 design (no shared repairs, a monotone layout > record, follow-ups that only set attributes or delete). It compiles and its > own tests pass, but parts of this description still describe the earlier > design and are marked below; it gets its own fix round (performance, > remaining review findings, docs) before review. Today a block move in `@lexical/y` is a delete plus a re-insert: the binding re-creates the cheaper side, so text a collaborator types into the moved block at the same time lands in its old neighbour, and two collaborators moving the same block can duplicate it. The normalization repairs every peer runs (a block lifted out of the paragraph it was written in) are written the same way, so two peers that lift one block from different surroundings both re-create it, and text typed into it meanwhile is lost. (On #9400 v3 the author normalizes its own write instead of every peer repairing it; see "Lifted blocks" below.) A move now keeps the moved items where they are and writes a small move record where the block shows. A move changes only position, never the moved content's characters. - **Records.** A record `↷` is a child `Y.Node` of the container. It names a range of the container's own sequence by Yjs item id (`s` is the item before the range, or none; `e` is the range's last item) and has a priority `p`. Items a peer inserts later inside the range (typing, Enter) belong to it too. This ports the semantics of Yjs' unmerged range move (ContentMove: highest priority wins, loops are broken) to binding-level records. Yjs 14 has no native move. - **Ownership is computed when reading, from the document alone.** An item belongs to the active record of highest priority (then client, then clock) whose range holds it. A record placed inside its own range, directly or through other records, shows nothing. Nothing is repaired or written back. A record written again keeps its rank (`o`). A write that splits an anchor item (typing inside the last word of a range) keeps the range: anchors resolve to the item holding their id. - **Records are not boundaries.** A record shows its units before the line its item is in, so text typed concurrently at a line start stays in its line. Formats stay positional, as in Yjs. - **Joins keep their items.** Joining a line into a moved line (Backspace, Delete, a deletion across lines) writes join records (`j: 1`) at the end of the first line's text. They show the second line's text in their place, so the joined line can span ranges and the second line's characters are never copied. A second line that is not one range (a block moved away from between its parts, or it starts inside a joined range) gets one join record per piece. Two peers that make the same join write records of the same ranges; one wins and the other shows nothing, so the text appears once. - **Lines that span ranges move with their items.** A line split off a joined line, or joined across a moved range, is moved with one join record per piece but its last (written at the start of the last piece) and a block record over the last piece, instead of being re-created. - **Lifted blocks keep their node.** A block written inside a line (a table appended to a paragraph without the normalization, an older client) keeps its shared node when the normalization lifts it out (on #9400 v3, the normalization of its author) (a line written inside a line, such as a heading in a list item, is stored as lines by #9400 and needs no lift): the node is marked a unit of its container (`u: 1` on the `i:<type>` node), which splits the line around it, and the line parts get markers. (The earlier design, where every peer lifted it under a content-derived client id, is gone with #9400's shared repairs.) Lexical replacing such a block by a new one of its type (Enter at its start) keeps the shared node too. - **Records left inside a line.** A record can end up between a line's characters when the line around it changed at the same time: a peer joined the lines around it (the record is inside the joined range), or removed the line before it while another typed in that line. New units then go right after the block the record shows only when that is a line boundary, otherwise right before the next line, and when the block shows from inside that next line it is written again with a record where it shows. A moved line that such a record interrupts moves with its pieces (its text before the record too). A record is written again at its line start only when the same records stay active (moving it out of another record's range can make a record that showed nothing show its range). - **Zero cost without moves.** Every new path sits behind "this container holds a record" or "this write lifts a block". The per-keystroke cost, size, 10k-edit growth and load time of documents that never move are unchanged, and Enter and Backspace there are within 3% of #9400. - **Incremental read.** A peer that receives a move, its undo or redo, or a structural edit in a container with records re-parses only windows around the records whose ownership changed. Each window is bounded by end items its zone owns before and after the change, so a unit keeps its node only when its content provably did not change. Format edits, join records and unresolved records still read the whole container. - **Cost with many records.** Outside a transaction, a container's cached ownership is checked against the document (records deleted, anchors split or merged) once after each transaction starts and once after Yjs cleans one up, instead of on every use; inside a transaction it is still checked on every use. Which records are active, and the ownership before a change in an incremental read, come from a painted index instead of a scan of the records per position. An incremental read takes formats from one walk of the container, and the check for records left inside a line stops where the previous record's check stopped. Nothing written changes: the updates of a scripted session and of every fuzz session are byte-identical before and after. At 10,000 random moves on 1,000 blocks (every block moved, 1,000 live records), a local move goes from 347 to 34 ms, a remote read from 1,049 to 27 ms and a load from 647 to 46 ms (#9400: 5.1, 3.6 and 27 ms). What is left grows with the container's items, deleted records included. - **Records over time.** Each move leaves a tombstone of about 18 B once Yjs collects garbage (a delete and a re-insert on #9400 leaves 16.5 B). Live records stay at most one per moved range, apart from rare cases (a block moved back to where it was, a record that lost a loop, a record whose range a peer deleted, until the next local write of that container), tracked in #9455. - **Detection.** No core hook. The writer's existing key matching (same NodeKey under the same container) recognizes the moved units. The records go to the units the user moved, and a whole range that moves again reuses its record. - **Scope: moves inside one container.** This covers the root, a list (items and whole lists), a table (rows), a row (cells, so column moves), a cell's or collapsible's content, and block decorators and containers moved as units. A move into another container is still a delete plus an insert (documented). - **Undo** removes the record, so the block returns with a peer's concurrent typing. Redo writes it again. A local write that deletes a record can let another record show. The writer then reads the container again, as a peer would. - **Layout.** A new document records layout 1 (`lexical-y:1: true`). The first move record, join record or lifted block adds `lexical-y:2: true` to #9400's monotone layout record, in the same transaction as the record (so no client ever receives a record without the version), and undo never deletes it; nothing else is rewritten. Clients without moves then open it read only instead of misreading it, and the record never shrinks. `LAYOUT_VERSION` is now 2, and documents without moves stay editable by older `@lexical/y` builds. The README's wire format section documents layout 2 (records, join records, lifted blocks, the upgrade) next to the frozen layout 1. - (Removed with #9400's shared repairs: the list-merge and ragged-table repair exceptions for containers with records.) - Warnings go to the editor's `onWarn` as `LexicalWarning`s, and the code uses the binding's read-only getters. On main, the update that flips a node's `isInline()` lifts the node itself (the normalization runs on what an update writes), so the flip is written as a block of its container, not as an inline node a later repair lifts in place; this PR therefore leaves `IsInline.test.ts` as #9400 has it. **Prior art.** We studied Bob Ippolito's etrepum#65, which gives every node its own Yjs node and moves a node by writing a `{id, token}` placement into its new parent. We chose instead to port Yjs's own unmerged range-move design (`ContentMove` on the `move` branch: a record at the destination points at the moved range, the higher priority wins, loops are broken) as binding-level records. Our reasons: splits and joins stay cheap marker edits, documents pay nothing until something moves, and #65's per-node layout has known cases where a split or join racing a collaborator's typing loses or misplaces that typing (marked as expected failures in its tests). Credit to one format key per mark id, the same as the follow-up #9439. No change to `lexical`, `@lexical/yjs` or any other package. Docs: the `y.md` page's "Wire format" section, which #9400 starts with a diagram of layout 1, gains diagrams of layout 2 (a move record next to the order the editor shows, and a join record) and of the upgrade from 1 to 2, checked against a dumped document, and links the README's layout 2 specification; its limits describe moves within and across containers, joins, and layout version 2. Its limits also cover text typed into a block moved out of a container that a peer removes or moves (lost), the same block moved into two containers (shown twice), and an undo of a removal racing a move out of the removed range (shown twice), and how records and tombstones grow over time, with the Yjs advice to reload long-lived rooms on the server. The README's wire format documents layout 2, and its fuzz note lists the moves fuzz variables. `@lexical/y` is unreleased and `@experimental`. ``` $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 62 passed (62) Tests 2981 passed | 4 expected fail | 2 skipped (2987) $ FUZZ_MOVE_SEEDS=1000 FUZZ_MOVE_GC_SEEDS=200 NORMALIZE_FUZZ_SEEDS=1000 \ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{Fuzz,NormalizationConvergence,Moves,Races}.test.ts normalization fuzz: {"duplicated":[],"healed":[… 60 seeds],"seeds":1005} held paragraphs fuzz: {"duplicated":[],"healed":[228,295],"seeds":1000} Tests 3483 passed (3483) ``` Adapted to #9400 v3 in this rebase: the layout test now checks the record (`lexical-y:1` and `lexical-y:2` = `true`), that the version is written in the transaction of the first move record, and that undoing the move keeps it; the two "lifts in place" tests deliver the author's normalization with its write (receivers no longer lift); the "move a block" byte budget is 108 (was 104: the record's attribute is now part of the move's update). Also `pnpm run test-unit` compared test by test with #9439 (0 failed, 0 changed; the replay of a fixture this PR deletes no longer runs), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the tree-shaking tests (369 source, 286 built), `pnpm run build-prod` and `pnpm run build-docs` pass. The rest of this test plan is from the previous base (#9400 before its v3 rework) and is re-measured in the fix round. The new tests against the previous revision of this change (joins of lines that are not one range copied, lines that span ranges re-created, repairs written as a delete and a re-insert): ``` $ npx vitest --project unit --no-watch Moves.test NormalizationConvergence.test × move of a line split after a join ‖ typing in it (4 of 4 orders) Expected: "paragraph("zeroth") / paragraph("one") / paragraph("two") / paragraph("rXee")" Received: "paragraph("zeroth") / paragraph("Xone") / paragraph("two") / paragraph("ree")" × move of a line another zone interrupts ‖ typing in both parts (4 of 4) Expected: "paragraph("three") / paragraph("one") / paragraph("zeXrotwYo")" Received: "paragraph("XrotwYthree") / paragraph("one") / paragraph("zerotwo")" × join ‖ join of a line another zone interrupts (4 of 4) Expected: "paragraph("threezerotwo") / paragraph("one")" Received: "paragraph("threezerotwozerotwo") / paragraph("one")" × join into a moved line of a line another zone interrupts ‖ typing in it (4 of 4) × two blocks written at the end of one line by two peers, lifted by a third (12 of 12) AssertionError: expected [ 'cell', 2 ] to deeply equal [ 'cell', 1 ] × a block lifted out of the middle of a line ‖ typing next to it and in it (12 of 12) AssertionError: expected [ '¶', 'b:test_box', '¶' ] to not include 'b:test_box' × a heading lifted out of a list item ‖ typing in the heading (12 of 12) × fuzz: normalization repairs by 3 peers with partial delivery, seed 44, 47, 51, 64, 79, 93 Tests 58 failed | 839 passed (897) ``` - Randomized normalization fuzz, 2,000 seeds (3 peers, 40% of edits written without the normalization, peers typing into the same blocks, partial delivery): 490 sessions copied or lost text: 102 sessions without a nested line (101 with a copied block, 1 with a lost token) and 388 with one (a heading a peer wrote inside a list item: 387 copied, 2 lost). - `Fuzz.test.ts` / the fuzz utilities: a token a peer moves into a table, box or column counts as lost by delete wins when another peer made a removal, exactly like a token typed there. Duplicates are not excused. - Block id integration (BlockIdExtension on this change), moves fuzz, 2,000 + 500 gc seeds: 15 + 3 seeds with duplicated text (joins written as a copy, lines that span ranges moved as a delete and a re-insert). - This revision's fixes, against the previous revision of this change (a record left inside a line by concurrent edits: a unit written after the block it shows split the line, and a moved line left its text before the record behind; a heading written inside a list item stored as its own node): ``` $ npx vitest --project unit --no-watch Moves.test -t 'a record left inside a line' × a block shown from inside a joined line ‖ a new line right after it (4 of 4) + "@lexical/y self-check: line 81: text \"M0 abcNEW\" != \"NEW\"; ..." × a line typed into after a removal, shown around a record, moved (4 of 4) + "@lexical/y self-check: line 133: text \"M5 pqr\" != \"XM5 pqr\"; ..." Tests 8 failed | 234 skipped (242) $ npx vitest --project unit --no-watch NormalizationConvergence.test × a line written inside a line is stored as lines (48 of 60) × a heading written inside a list item ‖ typing in the heading (12 of 12) × fuzz: seeds 405, 435, 446, 899, 937, 1078, 1388, 1507, 1683, 1820 Tests 70 failed | 665 passed (735) ``` The normalization fuzz at 2,000 seeds copied text in 8 sessions and lost it in 2, all with a heading written inside a list item. The block id moves fuzz with undo and redo off failed 2 of 2,000 seeds (162: a self-check mismatch after a move; 741: a self-check mismatch and lost text after a new line was written next to a moved block). Enter and Backspace in a 10,000 paragraph document without moves took 71.2 and 71.5 ms against 67.0 and 66.8 ms on #9400 (3 alternating runs, +6%). - A move at 10k blocks with 100 earlier moves on #9400 without this change: #9400 writes a move as a delete and a re-insert, 78 ms end to end with 100 earlier moves at 10,000 blocks (its undo writes 131 B). - Many moves, before this revision's caching (1,000 blocks, gc on): at 10,000 random moves (1,000 live records) a local move took 347 ms, a remote read of it 1,049 ms and a load 647 ms, against 5.1, 3.6 and 27 ms on #9400; at 1,000 moves (634 live records), 24.5, 16.1 and 400 ms. ``` $ npx vitest --project unit --no-watch Moves.test Races.test Tests 341 passed (341) $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 55 passed (55) Tests 2726 passed | 4 expected fail | 2 skipped (2732) $ NORMALIZE_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch NormalizationConvergence.test Tests 4973 passed (4973) # 2,000 + 2,000 fuzz seeds, matrix 864 $ NORMALIZE_FUZZ_SEEDS=10000 npx vitest --project unit --no-watch NormalizationConvergence.test -t fuzz Tests 20000 passed # 10,000 + 10,000 fuzz seeds, on the top of the stack: # 0 copies, 0 losses; 434 + 26 sessions healed a remote # self-check mismatch by a re-read $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \ npx vitest --project unit --no-watch Fuzz.test Tests 203 passed (203) ``` Re-run on this revision (main with the final node structure, #9452, and the updated #9400): the commands above; the moves fuzz at 2,000 + 500 gc seeds through the same counting harness as before: 26 and 7 seeds with lost or duplicated text, the same seeds as on the previous base, and 1,997 of 2,000 and 498 of 500 sessions write byte-identical updates (the other 3 + 2 differ where main's normalization now runs in a local update); the block id integration (moves fuzz, 2,000 + 500 gc: duplicated text on 882 and 1993 only, as before; the BlockIdExtension fuzz, 2,000 seeds, passes); and the collab Y e2e suite in Chromium (26/26) and Firefox (23 passed, 3 Chromium-only skips). From the previous base and not re-run: the 25,000 + 5,000 gc moves fuzz, the differential, the scripted byte-identity session, the block id run with undo and redo off, the playground drag spec, and the perf and many-moves tables below. - `Moves.test.ts` (249 tests, most in 4 orders) covers: - move ‖ type (inside, start and end), move ‖ move of the same block, neighbour moves, move ‖ delete, move ‖ retype, move ‖ bold, move ‖ Enter; - every join and split ‖ move combination: join ‖ join (Backspace, Delete, both, a range across a moved line), join ‖ split, join ‖ typing, join ‖ move, split ‖ move, undo of a join, a join ‖ an undo that restores a line inside the joined range; - new: lines that span ranges moved (a line split after a join, alone, ‖ typing in it and ‖ another move), a line another zone interrupts moved ‖ typing in both parts and joined ‖ typing and ‖ the same join, and a line that ends inside a joined range moved and then typed in, a block shown from inside a joined line ‖ a new line right after it, and a line typed into after a removal, shown around a record, then moved (each checks that the result is exactly the writer's intent); - list item moves (up, between lists, ‖ indent), whole-list moves ‖ add item, table row ‖ type and column ‖ type, container ‖ type, block decorator; - undo, redo, a second move, delete of a moved block, caret mapping, the layout bump, no record for documents that never move, and reads that stay incremental. - new: cached ownership, compared with ownership built fresh from the document after every step, across undo and redo with a peer typing, records that arrive out of order, a record whose anchors arrive late, text anchors split by typing (with and without gc), anchors merged by gc, and a moved block deleted with its old neighbour under gc. Taking out the anchor check fails them. - `NormalizationConvergence.test.ts`: the 3-peer matrix (18 violations × 8 delivery schedules × 6 id orders) passes 864/864; new lift tests (a block lifted out of the middle of a line ‖ typing next to it and in it, two blocks written at the end of one line by two peers and lifted by a third, a heading written inside a list item ‖ typing in it, a block put inside such a heading and lifted from other surroundings; 6 id orders × 2 deliveries each) check the text, the stored node (`u`, no copy, no `i:heading`) and the layout bump. The randomized fuzz fails on any copied or lost token, in every session, and always runs the seeds that failed during this work. A second randomized fuzz adds edits that write plain paragraphs into quotes and list items (joined into them as lines by the normalization) and new quotes, starting from a document with a quote and a numbered list. Both pass at 2,000 and 10,000 seeds each (0 copies, 0 losses). - Fuzz with block moves (the whole stack): 2,000 + 500 gc and 25,000 + 5,000 gc seeds, 0 absolute findings (divergence, exceptions, fragments, self-check, fresh readers). The fuzz now counts a block moved into a container a peer removed as delete wins, as it already did for text typed into one. Seeds with lost or duplicated text: 26 of 2,000 (1.3%; 69 before that accounting change), 7 of 500 gc (20 before), 278 of 25,000 (1.1%; 767 before) and 52 of 5,000 gc (157 before). All of them are documented limits: two peers moving the same block when one moves it into another container (shown twice), a move into another container racing a move of its container or an undo of a removal (shown twice), text typed into a block a list conversion lifts, and joins written as a copy. `Fuzz.test.ts` at 2,000 + 500 seeds with and without moves passes, including a regression seed (a comment over a line joined with a line of two pieces, then an undo). Differential against v2, 2,000 + 500 gc: 0 absolute findings, 5 + 1 seeds worse than v2. - This revision writes exactly what the previous one wrote. Every update of a scripted two-peer session (900 steps of moves, typing, Enter, joins, removals, undo and redo, with and without gc), of the moves fuzz (2,000 + 2,000 gc and 25,000 + 5,000 gc seeds, every peer's updates hashed per seed) and of 10,000 random moves is byte-identical before and after, and the fuzz findings, the differential (the same 5 + 1 seeds) and the block id runs below are unchanged. - Block id integration (BlockIdExtension on this stack): the moves fuzz, 2,000 + 500 gc seeds, has 0 divergence, 0 self-check warnings and 0 lost text; 2 + 0 seeds show duplicated text (882, 1993): in both, two peers remove the same text and both undo the removal, and each undo restores its own copy, which Yjs does with plain `Y.Text` too (no move is involved). With undo and redo off, 2,000 + 500 seeds have no finding (162 and 741 failed before). The BlockIdExtension fuzz, 2,000 seeds, passes. - Many moves (1,000 blocks; ms: local move, remote read of it, load; mean of the last 50 moves, median of 3 loads; #9400 / before / after): | Moves, gc | Live records | Local move | Remote read | Load | | --- | --- | --- | --- | --- | | 100 random, on | 97 | 4.8 / 8.1 / 8.3 | 2.8 / 3.7 / 3.7 | 20 / 69 / 24 | | 1,000 random, on | 634 | 4.5 / 24.5 / 17.2 | 3.1 / 16.1 / 8.0 | 20 / 400 / 29 | | 10,000 random, on | 1,000 | 5.1 / 347 / 33.5 | 3.6 / 1,049 / 26.9 | 27 / 647 / 46 | | 10,000 random, off | 1,000 | 6.7 / 357 / 35.0 | 5.5 / 1,086 / 28.8 | 49 / 783 / 135 | | 10,000 back and forth, on | 1 | 5.3 / 10.0 / 10.2 | 3.0 / 8.6 / 8.7 | 22 / 28 / 26 | | 10,000 back and forth, off | 1 | 7.6 / 11.2 / 11.1 | 4.3 / 10.1 / 10.2 | 52 / 128 / 122 | A keystroke in a moved block stays at 2.2 to 4.6 ms (#9400: 2.2 to 3.0). Sizes are unchanged (235 KB after 10,000 random moves with gc, 157 KB on #9400). The remaining cost grows with the container's items, deleted records included, which Yjs keeps in the sequence. - Perf at 10,000 blocks (end to end, shared machine, #9400 → the top of the stack): Enter and Backspace in a document without moves, median of the per-round ratio over 6 alternating rounds, +0.0 to +0.5% at the top of the stack and -1.8 to +1.3% with this change alone (+6% for the previous revision); keystroke 38.7 → 38.6 ms (list item 47.9 → 46.3), load 195 → 193 ms, size, 10k-edit growth and bytes per edit identical; a move 97 → 124 ms (131 → 106 B), its undo 69 → 73 ms (131 → 11 B). - Playground (`?isCollab=true&useCollabY=true`, the stack's playground mode, a scratch spec): drag a block while the other tab types in it, a list, a list item, a table row, undo, and the same block dragged twice: Chromium 21/21 (3 repeats), Firefox 7/7, WebKit 7/7; the collab Y e2e suite passes in all three (26/26, 23/23 + 3 Chromium-only IME skips). - On this commit: `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (368 passed), `pnpm run build-prod` and the built tree-shaking test (284 passed).
zurfyx
force-pushed
the
zurfyx/collab-y-server
branch
from
October 26, 2026 08:47
6ea0dff to
208f6f4
Compare
zurfyx
force-pushed
the
zurfyx/collab-y14-block-markers
branch
from
October 26, 2026 11:27
b6f567e to
8d67a8e
Compare
zurfyx
added a commit
that referenced
this pull request
Oct 26, 2026
Stacked on #9439 (the `@lexical/y` stack: #9400, #9437, #9438, #9439). This PR is now last in the stack. > **Status: rebased, not yet reworked.** This change was moved to the end of > the stack and onto #9400's v3 design (no shared repairs, a monotone layout > record, follow-ups that only set attributes or delete). It compiles and its > own tests pass, but parts of this description still describe the earlier > design and are marked below; it gets its own fix round (performance, > remaining review findings, docs) before review. Today a block move in `@lexical/y` is a delete plus a re-insert: the binding re-creates the cheaper side, so text a collaborator types into the moved block at the same time lands in its old neighbour, and two collaborators moving the same block can duplicate it. The normalization repairs every peer runs (a block lifted out of the paragraph it was written in) are written the same way, so two peers that lift one block from different surroundings both re-create it, and text typed into it meanwhile is lost. (On #9400 v3 the author normalizes its own write instead of every peer repairing it; see "Lifted blocks" below.) A move now keeps the moved items where they are and writes a small move record where the block shows. A move changes only position, never the moved content's characters. - **Records.** A record `↷` is a child `Y.Node` of the container. It names a range of the container's own sequence by Yjs item id (`s` is the item before the range, or none; `e` is the range's last item) and has a priority `p`. Items a peer inserts later inside the range (typing, Enter) belong to it too. This ports the semantics of Yjs' unmerged range move (ContentMove: highest priority wins, loops are broken) to binding-level records. Yjs 14 has no native move. - **Ownership is computed when reading, from the document alone.** An item belongs to the active record of highest priority (then client, then clock) whose range holds it. A record placed inside its own range, directly or through other records, shows nothing. Nothing is repaired or written back. A record written again keeps its rank (`o`). A write that splits an anchor item (typing inside the last word of a range) keeps the range: anchors resolve to the item holding their id. - **Records are not boundaries.** A record shows its units before the line its item is in, so text typed concurrently at a line start stays in its line. Formats stay positional, as in Yjs. - **Joins keep their items.** Joining a line into a moved line (Backspace, Delete, a deletion across lines) writes join records (`j: 1`) at the end of the first line's text. They show the second line's text in their place, so the joined line can span ranges and the second line's characters are never copied. A second line that is not one range (a block moved away from between its parts, or it starts inside a joined range) gets one join record per piece. Two peers that make the same join write records of the same ranges; one wins and the other shows nothing, so the text appears once. - **Lines that span ranges move with their items.** A line split off a joined line, or joined across a moved range, is moved with one join record per piece but its last (written at the start of the last piece) and a block record over the last piece, instead of being re-created. - **Lifted blocks keep their node.** A block written inside a line (a table appended to a paragraph without the normalization, an older client) keeps its shared node when the normalization lifts it out (on #9400 v3, the normalization of its author) (a line written inside a line, such as a heading in a list item, is stored as lines by #9400 and needs no lift): the node is marked a unit of its container (`u: 1` on the `i:<type>` node), which splits the line around it, and the line parts get markers. (The earlier design, where every peer lifted it under a content-derived client id, is gone with #9400's shared repairs.) Lexical replacing such a block by a new one of its type (Enter at its start) keeps the shared node too. - **Records left inside a line.** A record can end up between a line's characters when the line around it changed at the same time: a peer joined the lines around it (the record is inside the joined range), or removed the line before it while another typed in that line. New units then go right after the block the record shows only when that is a line boundary, otherwise right before the next line, and when the block shows from inside that next line it is written again with a record where it shows. A moved line that such a record interrupts moves with its pieces (its text before the record too). A record is written again at its line start only when the same records stay active (moving it out of another record's range can make a record that showed nothing show its range). - **Zero cost without moves.** Every new path sits behind "this container holds a record" or "this write lifts a block". The per-keystroke cost, size, 10k-edit growth and load time of documents that never move are unchanged, and Enter and Backspace there are within 3% of #9400. - **Incremental read.** A peer that receives a move, its undo or redo, or a structural edit in a container with records re-parses only windows around the records whose ownership changed. Each window is bounded by end items its zone owns before and after the change, so a unit keeps its node only when its content provably did not change. Format edits, join records and unresolved records still read the whole container. - **Cost with many records.** Outside a transaction, a container's cached ownership is checked against the document (records deleted, anchors split or merged) once after each transaction starts and once after Yjs cleans one up, instead of on every use; inside a transaction it is still checked on every use. Which records are active, and the ownership before a change in an incremental read, come from a painted index instead of a scan of the records per position. An incremental read takes formats from one walk of the container, and the check for records left inside a line stops where the previous record's check stopped. Nothing written changes: the updates of a scripted session and of every fuzz session are byte-identical before and after. At 10,000 random moves on 1,000 blocks (every block moved, 1,000 live records), a local move goes from 347 to 34 ms, a remote read from 1,049 to 27 ms and a load from 647 to 46 ms (#9400: 5.1, 3.6 and 27 ms). What is left grows with the container's items, deleted records included. - **Records over time.** Each move leaves a tombstone of about 18 B once Yjs collects garbage (a delete and a re-insert on #9400 leaves 16.5 B). Live records stay at most one per moved range, apart from rare cases (a block moved back to where it was, a record that lost a loop, a record whose range a peer deleted, until the next local write of that container), tracked in #9455. - **Detection.** No core hook. The writer's existing key matching (same NodeKey under the same container) recognizes the moved units. The records go to the units the user moved, and a whole range that moves again reuses its record. - **Scope: moves inside one container.** This covers the root, a list (items and whole lists), a table (rows), a row (cells, so column moves), a cell's or collapsible's content, and block decorators and containers moved as units. A move into another container is still a delete plus an insert (documented). - **Undo** removes the record, so the block returns with a peer's concurrent typing. Redo writes it again. A local write that deletes a record can let another record show. The writer then reads the container again, as a peer would. - **Layout.** A new document records layout 1 (`lexical-y:1: true`). The first move record, join record or lifted block adds `lexical-y:2: true` to #9400's monotone layout record, in the same transaction as the record (so no client ever receives a record without the version), and undo never deletes it; nothing else is rewritten. Clients without moves then open it read only instead of misreading it, and the record never shrinks. `LAYOUT_VERSION` is now 2, and documents without moves stay editable by older `@lexical/y` builds. The README's wire format section documents layout 2 (records, join records, lifted blocks, the upgrade) next to the frozen layout 1. - (Removed with #9400's shared repairs: the list-merge and ragged-table repair exceptions for containers with records.) - Warnings go to the editor's `onWarn` as `LexicalWarning`s, and the code uses the binding's read-only getters. On main, the update that flips a node's `isInline()` lifts the node itself (the normalization runs on what an update writes), so the flip is written as a block of its container, not as an inline node a later repair lifts in place; this PR therefore leaves `IsInline.test.ts` as #9400 has it. **Prior art.** We studied Bob Ippolito's etrepum#65, which gives every node its own Yjs node and moves a node by writing a `{id, token}` placement into its new parent. We chose instead to port Yjs's own unmerged range-move design (`ContentMove` on the `move` branch: a record at the destination points at the moved range, the higher priority wins, loops are broken) as binding-level records. Our reasons: splits and joins stay cheap marker edits, documents pay nothing until something moves, and #65's per-node layout has known cases where a split or join racing a collaborator's typing loses or misplaces that typing (marked as expected failures in its tests). Credit to one format key per mark id, the same as the follow-up #9439. No change to `lexical`, `@lexical/yjs` or any other package. Docs: the `y.md` page's "Wire format" section, which #9400 starts with a diagram of layout 1, gains diagrams of layout 2 (a move record next to the order the editor shows, and a join record) and of the upgrade from 1 to 2, checked against a dumped document, and links the README's layout 2 specification; its limits describe moves within and across containers, joins, and layout version 2. Its limits also cover text typed into a block moved out of a container that a peer removes or moves (lost), the same block moved into two containers (shown twice), and an undo of a removal racing a move out of the removed range (shown twice), and how records and tombstones grow over time, with the Yjs advice to reload long-lived rooms on the server. The README's wire format documents layout 2, and its fuzz note lists the moves fuzz variables. `@lexical/y` is unreleased and `@experimental`. ``` $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 62 passed (62) Tests 2981 passed | 4 expected fail | 2 skipped (2987) $ FUZZ_MOVE_SEEDS=1000 FUZZ_MOVE_GC_SEEDS=200 NORMALIZE_FUZZ_SEEDS=1000 \ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{Fuzz,NormalizationConvergence,Moves,Races}.test.ts normalization fuzz: {"duplicated":[],"healed":[… 60 seeds],"seeds":1005} held paragraphs fuzz: {"duplicated":[],"healed":[228,295],"seeds":1000} Tests 3483 passed (3483) ``` Adapted to #9400 v3 in this rebase: the layout test now checks the record (`lexical-y:1` and `lexical-y:2` = `true`), that the version is written in the transaction of the first move record, and that undoing the move keeps it; the two "lifts in place" tests deliver the author's normalization with its write (receivers no longer lift); the "move a block" byte budget is 108 (was 104: the record's attribute is now part of the move's update). Also `pnpm run test-unit` compared test by test with #9439 (0 failed, 0 changed; the replay of a fixture this PR deletes no longer runs), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the tree-shaking tests (369 source, 286 built), `pnpm run build-prod` and `pnpm run build-docs` pass. The rest of this test plan is from the previous base (#9400 before its v3 rework) and is re-measured in the fix round. The new tests against the previous revision of this change (joins of lines that are not one range copied, lines that span ranges re-created, repairs written as a delete and a re-insert): ``` $ npx vitest --project unit --no-watch Moves.test NormalizationConvergence.test × move of a line split after a join ‖ typing in it (4 of 4 orders) Expected: "paragraph("zeroth") / paragraph("one") / paragraph("two") / paragraph("rXee")" Received: "paragraph("zeroth") / paragraph("Xone") / paragraph("two") / paragraph("ree")" × move of a line another zone interrupts ‖ typing in both parts (4 of 4) Expected: "paragraph("three") / paragraph("one") / paragraph("zeXrotwYo")" Received: "paragraph("XrotwYthree") / paragraph("one") / paragraph("zerotwo")" × join ‖ join of a line another zone interrupts (4 of 4) Expected: "paragraph("threezerotwo") / paragraph("one")" Received: "paragraph("threezerotwozerotwo") / paragraph("one")" × join into a moved line of a line another zone interrupts ‖ typing in it (4 of 4) × two blocks written at the end of one line by two peers, lifted by a third (12 of 12) AssertionError: expected [ 'cell', 2 ] to deeply equal [ 'cell', 1 ] × a block lifted out of the middle of a line ‖ typing next to it and in it (12 of 12) AssertionError: expected [ '¶', 'b:test_box', '¶' ] to not include 'b:test_box' × a heading lifted out of a list item ‖ typing in the heading (12 of 12) × fuzz: normalization repairs by 3 peers with partial delivery, seed 44, 47, 51, 64, 79, 93 Tests 58 failed | 839 passed (897) ``` - Randomized normalization fuzz, 2,000 seeds (3 peers, 40% of edits written without the normalization, peers typing into the same blocks, partial delivery): 490 sessions copied or lost text: 102 sessions without a nested line (101 with a copied block, 1 with a lost token) and 388 with one (a heading a peer wrote inside a list item: 387 copied, 2 lost). - `Fuzz.test.ts` / the fuzz utilities: a token a peer moves into a table, box or column counts as lost by delete wins when another peer made a removal, exactly like a token typed there. Duplicates are not excused. - Block id integration (BlockIdExtension on this change), moves fuzz, 2,000 + 500 gc seeds: 15 + 3 seeds with duplicated text (joins written as a copy, lines that span ranges moved as a delete and a re-insert). - This revision's fixes, against the previous revision of this change (a record left inside a line by concurrent edits: a unit written after the block it shows split the line, and a moved line left its text before the record behind; a heading written inside a list item stored as its own node): ``` $ npx vitest --project unit --no-watch Moves.test -t 'a record left inside a line' × a block shown from inside a joined line ‖ a new line right after it (4 of 4) + "@lexical/y self-check: line 81: text \"M0 abcNEW\" != \"NEW\"; ..." × a line typed into after a removal, shown around a record, moved (4 of 4) + "@lexical/y self-check: line 133: text \"M5 pqr\" != \"XM5 pqr\"; ..." Tests 8 failed | 234 skipped (242) $ npx vitest --project unit --no-watch NormalizationConvergence.test × a line written inside a line is stored as lines (48 of 60) × a heading written inside a list item ‖ typing in the heading (12 of 12) × fuzz: seeds 405, 435, 446, 899, 937, 1078, 1388, 1507, 1683, 1820 Tests 70 failed | 665 passed (735) ``` The normalization fuzz at 2,000 seeds copied text in 8 sessions and lost it in 2, all with a heading written inside a list item. The block id moves fuzz with undo and redo off failed 2 of 2,000 seeds (162: a self-check mismatch after a move; 741: a self-check mismatch and lost text after a new line was written next to a moved block). Enter and Backspace in a 10,000 paragraph document without moves took 71.2 and 71.5 ms against 67.0 and 66.8 ms on #9400 (3 alternating runs, +6%). - A move at 10k blocks with 100 earlier moves on #9400 without this change: #9400 writes a move as a delete and a re-insert, 78 ms end to end with 100 earlier moves at 10,000 blocks (its undo writes 131 B). - Many moves, before this revision's caching (1,000 blocks, gc on): at 10,000 random moves (1,000 live records) a local move took 347 ms, a remote read of it 1,049 ms and a load 647 ms, against 5.1, 3.6 and 27 ms on #9400; at 1,000 moves (634 live records), 24.5, 16.1 and 400 ms. ``` $ npx vitest --project unit --no-watch Moves.test Races.test Tests 341 passed (341) $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 55 passed (55) Tests 2726 passed | 4 expected fail | 2 skipped (2732) $ NORMALIZE_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch NormalizationConvergence.test Tests 4973 passed (4973) # 2,000 + 2,000 fuzz seeds, matrix 864 $ NORMALIZE_FUZZ_SEEDS=10000 npx vitest --project unit --no-watch NormalizationConvergence.test -t fuzz Tests 20000 passed # 10,000 + 10,000 fuzz seeds, on the top of the stack: # 0 copies, 0 losses; 434 + 26 sessions healed a remote # self-check mismatch by a re-read $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \ npx vitest --project unit --no-watch Fuzz.test Tests 203 passed (203) ``` Re-run on this revision (main with the final node structure, #9452, and the updated #9400): the commands above; the moves fuzz at 2,000 + 500 gc seeds through the same counting harness as before: 26 and 7 seeds with lost or duplicated text, the same seeds as on the previous base, and 1,997 of 2,000 and 498 of 500 sessions write byte-identical updates (the other 3 + 2 differ where main's normalization now runs in a local update); the block id integration (moves fuzz, 2,000 + 500 gc: duplicated text on 882 and 1993 only, as before; the BlockIdExtension fuzz, 2,000 seeds, passes); and the collab Y e2e suite in Chromium (26/26) and Firefox (23 passed, 3 Chromium-only skips). From the previous base and not re-run: the 25,000 + 5,000 gc moves fuzz, the differential, the scripted byte-identity session, the block id run with undo and redo off, the playground drag spec, and the perf and many-moves tables below. - `Moves.test.ts` (249 tests, most in 4 orders) covers: - move ‖ type (inside, start and end), move ‖ move of the same block, neighbour moves, move ‖ delete, move ‖ retype, move ‖ bold, move ‖ Enter; - every join and split ‖ move combination: join ‖ join (Backspace, Delete, both, a range across a moved line), join ‖ split, join ‖ typing, join ‖ move, split ‖ move, undo of a join, a join ‖ an undo that restores a line inside the joined range; - new: lines that span ranges moved (a line split after a join, alone, ‖ typing in it and ‖ another move), a line another zone interrupts moved ‖ typing in both parts and joined ‖ typing and ‖ the same join, and a line that ends inside a joined range moved and then typed in, a block shown from inside a joined line ‖ a new line right after it, and a line typed into after a removal, shown around a record, then moved (each checks that the result is exactly the writer's intent); - list item moves (up, between lists, ‖ indent), whole-list moves ‖ add item, table row ‖ type and column ‖ type, container ‖ type, block decorator; - undo, redo, a second move, delete of a moved block, caret mapping, the layout bump, no record for documents that never move, and reads that stay incremental. - new: cached ownership, compared with ownership built fresh from the document after every step, across undo and redo with a peer typing, records that arrive out of order, a record whose anchors arrive late, text anchors split by typing (with and without gc), anchors merged by gc, and a moved block deleted with its old neighbour under gc. Taking out the anchor check fails them. - `NormalizationConvergence.test.ts`: the 3-peer matrix (18 violations × 8 delivery schedules × 6 id orders) passes 864/864; new lift tests (a block lifted out of the middle of a line ‖ typing next to it and in it, two blocks written at the end of one line by two peers and lifted by a third, a heading written inside a list item ‖ typing in it, a block put inside such a heading and lifted from other surroundings; 6 id orders × 2 deliveries each) check the text, the stored node (`u`, no copy, no `i:heading`) and the layout bump. The randomized fuzz fails on any copied or lost token, in every session, and always runs the seeds that failed during this work. A second randomized fuzz adds edits that write plain paragraphs into quotes and list items (joined into them as lines by the normalization) and new quotes, starting from a document with a quote and a numbered list. Both pass at 2,000 and 10,000 seeds each (0 copies, 0 losses). - Fuzz with block moves (the whole stack): 2,000 + 500 gc and 25,000 + 5,000 gc seeds, 0 absolute findings (divergence, exceptions, fragments, self-check, fresh readers). The fuzz now counts a block moved into a container a peer removed as delete wins, as it already did for text typed into one. Seeds with lost or duplicated text: 26 of 2,000 (1.3%; 69 before that accounting change), 7 of 500 gc (20 before), 278 of 25,000 (1.1%; 767 before) and 52 of 5,000 gc (157 before). All of them are documented limits: two peers moving the same block when one moves it into another container (shown twice), a move into another container racing a move of its container or an undo of a removal (shown twice), text typed into a block a list conversion lifts, and joins written as a copy. `Fuzz.test.ts` at 2,000 + 500 seeds with and without moves passes, including a regression seed (a comment over a line joined with a line of two pieces, then an undo). Differential against v2, 2,000 + 500 gc: 0 absolute findings, 5 + 1 seeds worse than v2. - This revision writes exactly what the previous one wrote. Every update of a scripted two-peer session (900 steps of moves, typing, Enter, joins, removals, undo and redo, with and without gc), of the moves fuzz (2,000 + 2,000 gc and 25,000 + 5,000 gc seeds, every peer's updates hashed per seed) and of 10,000 random moves is byte-identical before and after, and the fuzz findings, the differential (the same 5 + 1 seeds) and the block id runs below are unchanged. - Block id integration (BlockIdExtension on this stack): the moves fuzz, 2,000 + 500 gc seeds, has 0 divergence, 0 self-check warnings and 0 lost text; 2 + 0 seeds show duplicated text (882, 1993): in both, two peers remove the same text and both undo the removal, and each undo restores its own copy, which Yjs does with plain `Y.Text` too (no move is involved). With undo and redo off, 2,000 + 500 seeds have no finding (162 and 741 failed before). The BlockIdExtension fuzz, 2,000 seeds, passes. - Many moves (1,000 blocks; ms: local move, remote read of it, load; mean of the last 50 moves, median of 3 loads; #9400 / before / after): | Moves, gc | Live records | Local move | Remote read | Load | | --- | --- | --- | --- | --- | | 100 random, on | 97 | 4.8 / 8.1 / 8.3 | 2.8 / 3.7 / 3.7 | 20 / 69 / 24 | | 1,000 random, on | 634 | 4.5 / 24.5 / 17.2 | 3.1 / 16.1 / 8.0 | 20 / 400 / 29 | | 10,000 random, on | 1,000 | 5.1 / 347 / 33.5 | 3.6 / 1,049 / 26.9 | 27 / 647 / 46 | | 10,000 random, off | 1,000 | 6.7 / 357 / 35.0 | 5.5 / 1,086 / 28.8 | 49 / 783 / 135 | | 10,000 back and forth, on | 1 | 5.3 / 10.0 / 10.2 | 3.0 / 8.6 / 8.7 | 22 / 28 / 26 | | 10,000 back and forth, off | 1 | 7.6 / 11.2 / 11.1 | 4.3 / 10.1 / 10.2 | 52 / 128 / 122 | A keystroke in a moved block stays at 2.2 to 4.6 ms (#9400: 2.2 to 3.0). Sizes are unchanged (235 KB after 10,000 random moves with gc, 157 KB on #9400). The remaining cost grows with the container's items, deleted records included, which Yjs keeps in the sequence. - Perf at 10,000 blocks (end to end, shared machine, #9400 → the top of the stack): Enter and Backspace in a document without moves, median of the per-round ratio over 6 alternating rounds, +0.0 to +0.5% at the top of the stack and -1.8 to +1.3% with this change alone (+6% for the previous revision); keystroke 38.7 → 38.6 ms (list item 47.9 → 46.3), load 195 → 193 ms, size, 10k-edit growth and bytes per edit identical; a move 97 → 124 ms (131 → 106 B), its undo 69 → 73 ms (131 → 11 B). - Playground (`?isCollab=true&useCollabY=true`, the stack's playground mode, a scratch spec): drag a block while the other tab types in it, a list, a list item, a table row, undo, and the same block dragged twice: Chromium 21/21 (3 repeats), Firefox 7/7, WebKit 7/7; the collab Y e2e suite passes in all three (26/26, 23/23 + 3 Chromium-only IME skips). - On this commit: `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (368 passed), `pnpm run build-prod` and the built tree-shaking test (284 passed).
zurfyx
force-pushed
the
zurfyx/collab-y-server
branch
from
October 26, 2026 11:27
208f6f4 to
34c4737
Compare
zurfyx
force-pushed
the
zurfyx/collab-y14-block-markers
branch
from
October 26, 2026 13:27
8d67a8e to
59407da
Compare
zurfyx
added a commit
that referenced
this pull request
Oct 26, 2026
Stacked on #9439 (the `@lexical/y` stack: #9400, #9437, #9438, #9439). This PR is now last in the stack. > **Status: rebased, not yet reworked.** This change was moved to the end of > the stack and onto #9400's v3 design (no shared repairs, a monotone layout > record, follow-ups that only set attributes or delete). It compiles and its > own tests pass, but parts of this description still describe the earlier > design and are marked below; it gets its own fix round (performance, > remaining review findings, docs) before review. Today a block move in `@lexical/y` is a delete plus a re-insert: the binding re-creates the cheaper side, so text a collaborator types into the moved block at the same time lands in its old neighbour, and two collaborators moving the same block can duplicate it. The normalization repairs every peer runs (a block lifted out of the paragraph it was written in) are written the same way, so two peers that lift one block from different surroundings both re-create it, and text typed into it meanwhile is lost. (On #9400 v3 the author normalizes its own write instead of every peer repairing it; see "Lifted blocks" below.) A move now keeps the moved items where they are and writes a small move record where the block shows. A move changes only position, never the moved content's characters. - **Records.** A record `↷` is a child `Y.Node` of the container. It names a range of the container's own sequence by Yjs item id (`s` is the item before the range, or none; `e` is the range's last item) and has a priority `p`. Items a peer inserts later inside the range (typing, Enter) belong to it too. This ports the semantics of Yjs' unmerged range move (ContentMove: highest priority wins, loops are broken) to binding-level records. Yjs 14 has no native move. - **Ownership is computed when reading, from the document alone.** An item belongs to the active record of highest priority (then client, then clock) whose range holds it. A record placed inside its own range, directly or through other records, shows nothing. Nothing is repaired or written back. A record written again keeps its rank (`o`). A write that splits an anchor item (typing inside the last word of a range) keeps the range: anchors resolve to the item holding their id. - **Records are not boundaries.** A record shows its units before the line its item is in, so text typed concurrently at a line start stays in its line. Formats stay positional, as in Yjs. - **Joins keep their items.** Joining a line into a moved line (Backspace, Delete, a deletion across lines) writes join records (`j: 1`) at the end of the first line's text. They show the second line's text in their place, so the joined line can span ranges and the second line's characters are never copied. A second line that is not one range (a block moved away from between its parts, or it starts inside a joined range) gets one join record per piece. Two peers that make the same join write records of the same ranges; one wins and the other shows nothing, so the text appears once. - **Lines that span ranges move with their items.** A line split off a joined line, or joined across a moved range, is moved with one join record per piece but its last (written at the start of the last piece) and a block record over the last piece, instead of being re-created. - **Lifted blocks keep their node.** A block written inside a line (a table appended to a paragraph without the normalization, an older client) keeps its shared node when the normalization lifts it out (on #9400 v3, the normalization of its author) (a line written inside a line, such as a heading in a list item, is stored as lines by #9400 and needs no lift): the node is marked a unit of its container (`u: 1` on the `i:<type>` node), which splits the line around it, and the line parts get markers. (The earlier design, where every peer lifted it under a content-derived client id, is gone with #9400's shared repairs.) Lexical replacing such a block by a new one of its type (Enter at its start) keeps the shared node too. - **Records left inside a line.** A record can end up between a line's characters when the line around it changed at the same time: a peer joined the lines around it (the record is inside the joined range), or removed the line before it while another typed in that line. New units then go right after the block the record shows only when that is a line boundary, otherwise right before the next line, and when the block shows from inside that next line it is written again with a record where it shows. A moved line that such a record interrupts moves with its pieces (its text before the record too). A record is written again at its line start only when the same records stay active (moving it out of another record's range can make a record that showed nothing show its range). - **Zero cost without moves.** Every new path sits behind "this container holds a record" or "this write lifts a block". The per-keystroke cost, size, 10k-edit growth and load time of documents that never move are unchanged, and Enter and Backspace there are within 3% of #9400. - **Incremental read.** A peer that receives a move, its undo or redo, or a structural edit in a container with records re-parses only windows around the records whose ownership changed. Each window is bounded by end items its zone owns before and after the change, so a unit keeps its node only when its content provably did not change. Format edits, join records and unresolved records still read the whole container. - **Cost with many records.** Outside a transaction, a container's cached ownership is checked against the document (records deleted, anchors split or merged) once after each transaction starts and once after Yjs cleans one up, instead of on every use; inside a transaction it is still checked on every use. Which records are active, and the ownership before a change in an incremental read, come from a painted index instead of a scan of the records per position. An incremental read takes formats from one walk of the container, and the check for records left inside a line stops where the previous record's check stopped. Nothing written changes: the updates of a scripted session and of every fuzz session are byte-identical before and after. At 10,000 random moves on 1,000 blocks (every block moved, 1,000 live records), a local move goes from 347 to 34 ms, a remote read from 1,049 to 27 ms and a load from 647 to 46 ms (#9400: 5.1, 3.6 and 27 ms). What is left grows with the container's items, deleted records included. - **Records over time.** Each move leaves a tombstone of about 18 B once Yjs collects garbage (a delete and a re-insert on #9400 leaves 16.5 B). Live records stay at most one per moved range, apart from rare cases (a block moved back to where it was, a record that lost a loop, a record whose range a peer deleted, until the next local write of that container), tracked in #9455. - **Detection.** No core hook. The writer's existing key matching (same NodeKey under the same container) recognizes the moved units. The records go to the units the user moved, and a whole range that moves again reuses its record. - **Scope: moves inside one container.** This covers the root, a list (items and whole lists), a table (rows), a row (cells, so column moves), a cell's or collapsible's content, and block decorators and containers moved as units. A move into another container is still a delete plus an insert (documented). - **Undo** removes the record, so the block returns with a peer's concurrent typing. Redo writes it again. A local write that deletes a record can let another record show. The writer then reads the container again, as a peer would. - **Layout.** A new document records layout 1 (`lexical-y:1: true`). The first move record, join record or lifted block adds `lexical-y:2: true` to #9400's monotone layout record, in the same transaction as the record (so no client ever receives a record without the version), and undo never deletes it; nothing else is rewritten. Clients without moves then open it read only instead of misreading it, and the record never shrinks. `LAYOUT_VERSION` is now 2, and documents without moves stay editable by older `@lexical/y` builds. The README's wire format section documents layout 2 (records, join records, lifted blocks, the upgrade) next to the frozen layout 1. - (Removed with #9400's shared repairs: the list-merge and ragged-table repair exceptions for containers with records.) - Warnings go to the editor's `onWarn` as `LexicalWarning`s, and the code uses the binding's read-only getters. On main, the update that flips a node's `isInline()` lifts the node itself (the normalization runs on what an update writes), so the flip is written as a block of its container, not as an inline node a later repair lifts in place; this PR therefore leaves `IsInline.test.ts` as #9400 has it. **Prior art.** We studied Bob Ippolito's etrepum#65, which gives every node its own Yjs node and moves a node by writing a `{id, token}` placement into its new parent. We chose instead to port Yjs's own unmerged range-move design (`ContentMove` on the `move` branch: a record at the destination points at the moved range, the higher priority wins, loops are broken) as binding-level records. Our reasons: splits and joins stay cheap marker edits, documents pay nothing until something moves, and #65's per-node layout has known cases where a split or join racing a collaborator's typing loses or misplaces that typing (marked as expected failures in its tests). Credit to one format key per mark id, the same as the follow-up #9439. No change to `lexical`, `@lexical/yjs` or any other package. Docs: the `y.md` page's "Wire format" section, which #9400 starts with a diagram of layout 1, gains diagrams of layout 2 (a move record next to the order the editor shows, and a join record) and of the upgrade from 1 to 2, checked against a dumped document, and links the README's layout 2 specification; its limits describe moves within and across containers, joins, and layout version 2. Its limits also cover text typed into a block moved out of a container that a peer removes or moves (lost), the same block moved into two containers (shown twice), and an undo of a removal racing a move out of the removed range (shown twice), and how records and tombstones grow over time, with the Yjs advice to reload long-lived rooms on the server. The README's wire format documents layout 2, and its fuzz note lists the moves fuzz variables. `@lexical/y` is unreleased and `@experimental`. ``` $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 62 passed (62) Tests 2981 passed | 4 expected fail | 2 skipped (2987) $ FUZZ_MOVE_SEEDS=1000 FUZZ_MOVE_GC_SEEDS=200 NORMALIZE_FUZZ_SEEDS=1000 \ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{Fuzz,NormalizationConvergence,Moves,Races}.test.ts normalization fuzz: {"duplicated":[],"healed":[… 60 seeds],"seeds":1005} held paragraphs fuzz: {"duplicated":[],"healed":[228,295],"seeds":1000} Tests 3483 passed (3483) ``` Adapted to #9400 v3 in this rebase: the layout test now checks the record (`lexical-y:1` and `lexical-y:2` = `true`), that the version is written in the transaction of the first move record, and that undoing the move keeps it; the two "lifts in place" tests deliver the author's normalization with its write (receivers no longer lift); the "move a block" byte budget is 108 (was 104: the record's attribute is now part of the move's update). Also `pnpm run test-unit` compared test by test with #9439 (0 failed, 0 changed; the replay of a fixture this PR deletes no longer runs), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the tree-shaking tests (369 source, 286 built), `pnpm run build-prod` and `pnpm run build-docs` pass. The rest of this test plan is from the previous base (#9400 before its v3 rework) and is re-measured in the fix round. The new tests against the previous revision of this change (joins of lines that are not one range copied, lines that span ranges re-created, repairs written as a delete and a re-insert): ``` $ npx vitest --project unit --no-watch Moves.test NormalizationConvergence.test × move of a line split after a join ‖ typing in it (4 of 4 orders) Expected: "paragraph("zeroth") / paragraph("one") / paragraph("two") / paragraph("rXee")" Received: "paragraph("zeroth") / paragraph("Xone") / paragraph("two") / paragraph("ree")" × move of a line another zone interrupts ‖ typing in both parts (4 of 4) Expected: "paragraph("three") / paragraph("one") / paragraph("zeXrotwYo")" Received: "paragraph("XrotwYthree") / paragraph("one") / paragraph("zerotwo")" × join ‖ join of a line another zone interrupts (4 of 4) Expected: "paragraph("threezerotwo") / paragraph("one")" Received: "paragraph("threezerotwozerotwo") / paragraph("one")" × join into a moved line of a line another zone interrupts ‖ typing in it (4 of 4) × two blocks written at the end of one line by two peers, lifted by a third (12 of 12) AssertionError: expected [ 'cell', 2 ] to deeply equal [ 'cell', 1 ] × a block lifted out of the middle of a line ‖ typing next to it and in it (12 of 12) AssertionError: expected [ '¶', 'b:test_box', '¶' ] to not include 'b:test_box' × a heading lifted out of a list item ‖ typing in the heading (12 of 12) × fuzz: normalization repairs by 3 peers with partial delivery, seed 44, 47, 51, 64, 79, 93 Tests 58 failed | 839 passed (897) ``` - Randomized normalization fuzz, 2,000 seeds (3 peers, 40% of edits written without the normalization, peers typing into the same blocks, partial delivery): 490 sessions copied or lost text: 102 sessions without a nested line (101 with a copied block, 1 with a lost token) and 388 with one (a heading a peer wrote inside a list item: 387 copied, 2 lost). - `Fuzz.test.ts` / the fuzz utilities: a token a peer moves into a table, box or column counts as lost by delete wins when another peer made a removal, exactly like a token typed there. Duplicates are not excused. - Block id integration (BlockIdExtension on this change), moves fuzz, 2,000 + 500 gc seeds: 15 + 3 seeds with duplicated text (joins written as a copy, lines that span ranges moved as a delete and a re-insert). - This revision's fixes, against the previous revision of this change (a record left inside a line by concurrent edits: a unit written after the block it shows split the line, and a moved line left its text before the record behind; a heading written inside a list item stored as its own node): ``` $ npx vitest --project unit --no-watch Moves.test -t 'a record left inside a line' × a block shown from inside a joined line ‖ a new line right after it (4 of 4) + "@lexical/y self-check: line 81: text \"M0 abcNEW\" != \"NEW\"; ..." × a line typed into after a removal, shown around a record, moved (4 of 4) + "@lexical/y self-check: line 133: text \"M5 pqr\" != \"XM5 pqr\"; ..." Tests 8 failed | 234 skipped (242) $ npx vitest --project unit --no-watch NormalizationConvergence.test × a line written inside a line is stored as lines (48 of 60) × a heading written inside a list item ‖ typing in the heading (12 of 12) × fuzz: seeds 405, 435, 446, 899, 937, 1078, 1388, 1507, 1683, 1820 Tests 70 failed | 665 passed (735) ``` The normalization fuzz at 2,000 seeds copied text in 8 sessions and lost it in 2, all with a heading written inside a list item. The block id moves fuzz with undo and redo off failed 2 of 2,000 seeds (162: a self-check mismatch after a move; 741: a self-check mismatch and lost text after a new line was written next to a moved block). Enter and Backspace in a 10,000 paragraph document without moves took 71.2 and 71.5 ms against 67.0 and 66.8 ms on #9400 (3 alternating runs, +6%). - A move at 10k blocks with 100 earlier moves on #9400 without this change: #9400 writes a move as a delete and a re-insert, 78 ms end to end with 100 earlier moves at 10,000 blocks (its undo writes 131 B). - Many moves, before this revision's caching (1,000 blocks, gc on): at 10,000 random moves (1,000 live records) a local move took 347 ms, a remote read of it 1,049 ms and a load 647 ms, against 5.1, 3.6 and 27 ms on #9400; at 1,000 moves (634 live records), 24.5, 16.1 and 400 ms. ``` $ npx vitest --project unit --no-watch Moves.test Races.test Tests 341 passed (341) $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 55 passed (55) Tests 2726 passed | 4 expected fail | 2 skipped (2732) $ NORMALIZE_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch NormalizationConvergence.test Tests 4973 passed (4973) # 2,000 + 2,000 fuzz seeds, matrix 864 $ NORMALIZE_FUZZ_SEEDS=10000 npx vitest --project unit --no-watch NormalizationConvergence.test -t fuzz Tests 20000 passed # 10,000 + 10,000 fuzz seeds, on the top of the stack: # 0 copies, 0 losses; 434 + 26 sessions healed a remote # self-check mismatch by a re-read $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \ npx vitest --project unit --no-watch Fuzz.test Tests 203 passed (203) ``` Re-run on this revision (main with the final node structure, #9452, and the updated #9400): the commands above; the moves fuzz at 2,000 + 500 gc seeds through the same counting harness as before: 26 and 7 seeds with lost or duplicated text, the same seeds as on the previous base, and 1,997 of 2,000 and 498 of 500 sessions write byte-identical updates (the other 3 + 2 differ where main's normalization now runs in a local update); the block id integration (moves fuzz, 2,000 + 500 gc: duplicated text on 882 and 1993 only, as before; the BlockIdExtension fuzz, 2,000 seeds, passes); and the collab Y e2e suite in Chromium (26/26) and Firefox (23 passed, 3 Chromium-only skips). From the previous base and not re-run: the 25,000 + 5,000 gc moves fuzz, the differential, the scripted byte-identity session, the block id run with undo and redo off, the playground drag spec, and the perf and many-moves tables below. - `Moves.test.ts` (249 tests, most in 4 orders) covers: - move ‖ type (inside, start and end), move ‖ move of the same block, neighbour moves, move ‖ delete, move ‖ retype, move ‖ bold, move ‖ Enter; - every join and split ‖ move combination: join ‖ join (Backspace, Delete, both, a range across a moved line), join ‖ split, join ‖ typing, join ‖ move, split ‖ move, undo of a join, a join ‖ an undo that restores a line inside the joined range; - new: lines that span ranges moved (a line split after a join, alone, ‖ typing in it and ‖ another move), a line another zone interrupts moved ‖ typing in both parts and joined ‖ typing and ‖ the same join, and a line that ends inside a joined range moved and then typed in, a block shown from inside a joined line ‖ a new line right after it, and a line typed into after a removal, shown around a record, then moved (each checks that the result is exactly the writer's intent); - list item moves (up, between lists, ‖ indent), whole-list moves ‖ add item, table row ‖ type and column ‖ type, container ‖ type, block decorator; - undo, redo, a second move, delete of a moved block, caret mapping, the layout bump, no record for documents that never move, and reads that stay incremental. - new: cached ownership, compared with ownership built fresh from the document after every step, across undo and redo with a peer typing, records that arrive out of order, a record whose anchors arrive late, text anchors split by typing (with and without gc), anchors merged by gc, and a moved block deleted with its old neighbour under gc. Taking out the anchor check fails them. - `NormalizationConvergence.test.ts`: the 3-peer matrix (18 violations × 8 delivery schedules × 6 id orders) passes 864/864; new lift tests (a block lifted out of the middle of a line ‖ typing next to it and in it, two blocks written at the end of one line by two peers and lifted by a third, a heading written inside a list item ‖ typing in it, a block put inside such a heading and lifted from other surroundings; 6 id orders × 2 deliveries each) check the text, the stored node (`u`, no copy, no `i:heading`) and the layout bump. The randomized fuzz fails on any copied or lost token, in every session, and always runs the seeds that failed during this work. A second randomized fuzz adds edits that write plain paragraphs into quotes and list items (joined into them as lines by the normalization) and new quotes, starting from a document with a quote and a numbered list. Both pass at 2,000 and 10,000 seeds each (0 copies, 0 losses). - Fuzz with block moves (the whole stack): 2,000 + 500 gc and 25,000 + 5,000 gc seeds, 0 absolute findings (divergence, exceptions, fragments, self-check, fresh readers). The fuzz now counts a block moved into a container a peer removed as delete wins, as it already did for text typed into one. Seeds with lost or duplicated text: 26 of 2,000 (1.3%; 69 before that accounting change), 7 of 500 gc (20 before), 278 of 25,000 (1.1%; 767 before) and 52 of 5,000 gc (157 before). All of them are documented limits: two peers moving the same block when one moves it into another container (shown twice), a move into another container racing a move of its container or an undo of a removal (shown twice), text typed into a block a list conversion lifts, and joins written as a copy. `Fuzz.test.ts` at 2,000 + 500 seeds with and without moves passes, including a regression seed (a comment over a line joined with a line of two pieces, then an undo). Differential against v2, 2,000 + 500 gc: 0 absolute findings, 5 + 1 seeds worse than v2. - This revision writes exactly what the previous one wrote. Every update of a scripted two-peer session (900 steps of moves, typing, Enter, joins, removals, undo and redo, with and without gc), of the moves fuzz (2,000 + 2,000 gc and 25,000 + 5,000 gc seeds, every peer's updates hashed per seed) and of 10,000 random moves is byte-identical before and after, and the fuzz findings, the differential (the same 5 + 1 seeds) and the block id runs below are unchanged. - Block id integration (BlockIdExtension on this stack): the moves fuzz, 2,000 + 500 gc seeds, has 0 divergence, 0 self-check warnings and 0 lost text; 2 + 0 seeds show duplicated text (882, 1993): in both, two peers remove the same text and both undo the removal, and each undo restores its own copy, which Yjs does with plain `Y.Text` too (no move is involved). With undo and redo off, 2,000 + 500 seeds have no finding (162 and 741 failed before). The BlockIdExtension fuzz, 2,000 seeds, passes. - Many moves (1,000 blocks; ms: local move, remote read of it, load; mean of the last 50 moves, median of 3 loads; #9400 / before / after): | Moves, gc | Live records | Local move | Remote read | Load | | --- | --- | --- | --- | --- | | 100 random, on | 97 | 4.8 / 8.1 / 8.3 | 2.8 / 3.7 / 3.7 | 20 / 69 / 24 | | 1,000 random, on | 634 | 4.5 / 24.5 / 17.2 | 3.1 / 16.1 / 8.0 | 20 / 400 / 29 | | 10,000 random, on | 1,000 | 5.1 / 347 / 33.5 | 3.6 / 1,049 / 26.9 | 27 / 647 / 46 | | 10,000 random, off | 1,000 | 6.7 / 357 / 35.0 | 5.5 / 1,086 / 28.8 | 49 / 783 / 135 | | 10,000 back and forth, on | 1 | 5.3 / 10.0 / 10.2 | 3.0 / 8.6 / 8.7 | 22 / 28 / 26 | | 10,000 back and forth, off | 1 | 7.6 / 11.2 / 11.1 | 4.3 / 10.1 / 10.2 | 52 / 128 / 122 | A keystroke in a moved block stays at 2.2 to 4.6 ms (#9400: 2.2 to 3.0). Sizes are unchanged (235 KB after 10,000 random moves with gc, 157 KB on #9400). The remaining cost grows with the container's items, deleted records included, which Yjs keeps in the sequence. - Perf at 10,000 blocks (end to end, shared machine, #9400 → the top of the stack): Enter and Backspace in a document without moves, median of the per-round ratio over 6 alternating rounds, +0.0 to +0.5% at the top of the stack and -1.8 to +1.3% with this change alone (+6% for the previous revision); keystroke 38.7 → 38.6 ms (list item 47.9 → 46.3), load 195 → 193 ms, size, 10k-edit growth and bytes per edit identical; a move 97 → 124 ms (131 → 106 B), its undo 69 → 73 ms (131 → 11 B). - Playground (`?isCollab=true&useCollabY=true`, the stack's playground mode, a scratch spec): drag a block while the other tab types in it, a list, a list item, a table row, undo, and the same block dragged twice: Chromium 21/21 (3 repeats), Firefox 7/7, WebKit 7/7; the collab Y e2e suite passes in all three (26/26, 23/23 + 3 Chromium-only IME skips). - On this commit: `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (368 passed), `pnpm run build-prod` and the built tree-shaking test (284 passed).
zurfyx
force-pushed
the
zurfyx/collab-y-server
branch
from
October 26, 2026 13:27
34c4737 to
3f77588
Compare
zurfyx
force-pushed
the
zurfyx/collab-y14-block-markers
branch
from
October 26, 2026 16:40
59407da to
eb0175e
Compare
zurfyx
added a commit
that referenced
this pull request
Oct 26, 2026
Stacked on #9439 (the `@lexical/y` stack: #9400, #9437, #9438, #9439). This PR is now last in the stack. > **Status: rebased, not yet reworked.** This change was moved to the end of > the stack and onto #9400's v3 design (no shared repairs, a monotone layout > record, follow-ups that only set attributes or delete). It compiles and its > own tests pass, but parts of this description still describe the earlier > design and are marked below; it gets its own fix round (performance, > remaining review findings, docs) before review. Today a block move in `@lexical/y` is a delete plus a re-insert: the binding re-creates the cheaper side, so text a collaborator types into the moved block at the same time lands in its old neighbour, and two collaborators moving the same block can duplicate it. The normalization repairs every peer runs (a block lifted out of the paragraph it was written in) are written the same way, so two peers that lift one block from different surroundings both re-create it, and text typed into it meanwhile is lost. (On #9400 v3 the author normalizes its own write instead of every peer repairing it; see "Lifted blocks" below.) A move now keeps the moved items where they are and writes a small move record where the block shows. A move changes only position, never the moved content's characters. - **Records.** A record `↷` is a child `Y.Node` of the container. It names a range of the container's own sequence by Yjs item id (`s` is the item before the range, or none; `e` is the range's last item) and has a priority `p`. Items a peer inserts later inside the range (typing, Enter) belong to it too. This ports the semantics of Yjs' unmerged range move (ContentMove: highest priority wins, loops are broken) to binding-level records. Yjs 14 has no native move. - **Ownership is computed when reading, from the document alone.** An item belongs to the active record of highest priority (then client, then clock) whose range holds it. A record placed inside its own range, directly or through other records, shows nothing. Nothing is repaired or written back. A record written again keeps its rank (`o`). A write that splits an anchor item (typing inside the last word of a range) keeps the range: anchors resolve to the item holding their id. - **Records are not boundaries.** A record shows its units before the line its item is in, so text typed concurrently at a line start stays in its line. Formats stay positional, as in Yjs. - **Joins keep their items.** Joining a line into a moved line (Backspace, Delete, a deletion across lines) writes join records (`j: 1`) at the end of the first line's text. They show the second line's text in their place, so the joined line can span ranges and the second line's characters are never copied. A second line that is not one range (a block moved away from between its parts, or it starts inside a joined range) gets one join record per piece. Two peers that make the same join write records of the same ranges; one wins and the other shows nothing, so the text appears once. - **Lines that span ranges move with their items.** A line split off a joined line, or joined across a moved range, is moved with one join record per piece but its last (written at the start of the last piece) and a block record over the last piece, instead of being re-created. - **Lifted blocks keep their node.** A block written inside a line (a table appended to a paragraph without the normalization, an older client) keeps its shared node when the normalization lifts it out (on #9400 v3, the normalization of its author) (a line written inside a line, such as a heading in a list item, is stored as lines by #9400 and needs no lift): the node is marked a unit of its container (`u: 1` on the `i:<type>` node), which splits the line around it, and the line parts get markers. (The earlier design, where every peer lifted it under a content-derived client id, is gone with #9400's shared repairs.) Lexical replacing such a block by a new one of its type (Enter at its start) keeps the shared node too. - **Records left inside a line.** A record can end up between a line's characters when the line around it changed at the same time: a peer joined the lines around it (the record is inside the joined range), or removed the line before it while another typed in that line. New units then go right after the block the record shows only when that is a line boundary, otherwise right before the next line, and when the block shows from inside that next line it is written again with a record where it shows. A moved line that such a record interrupts moves with its pieces (its text before the record too). A record is written again at its line start only when the same records stay active (moving it out of another record's range can make a record that showed nothing show its range). - **Zero cost without moves.** Every new path sits behind "this container holds a record" or "this write lifts a block". The per-keystroke cost, size, 10k-edit growth and load time of documents that never move are unchanged, and Enter and Backspace there are within 3% of #9400. - **Incremental read.** A peer that receives a move, its undo or redo, or a structural edit in a container with records re-parses only windows around the records whose ownership changed. Each window is bounded by end items its zone owns before and after the change, so a unit keeps its node only when its content provably did not change. Format edits, join records and unresolved records still read the whole container. - **Cost with many records.** Outside a transaction, a container's cached ownership is checked against the document (records deleted, anchors split or merged) once after each transaction starts and once after Yjs cleans one up, instead of on every use; inside a transaction it is still checked on every use. Which records are active, and the ownership before a change in an incremental read, come from a painted index instead of a scan of the records per position. An incremental read takes formats from one walk of the container, and the check for records left inside a line stops where the previous record's check stopped. Nothing written changes: the updates of a scripted session and of every fuzz session are byte-identical before and after. At 10,000 random moves on 1,000 blocks (every block moved, 1,000 live records), a local move goes from 347 to 34 ms, a remote read from 1,049 to 27 ms and a load from 647 to 46 ms (#9400: 5.1, 3.6 and 27 ms). What is left grows with the container's items, deleted records included. - **Records over time.** Each move leaves a tombstone of about 18 B once Yjs collects garbage (a delete and a re-insert on #9400 leaves 16.5 B). Live records stay at most one per moved range, apart from rare cases (a block moved back to where it was, a record that lost a loop, a record whose range a peer deleted, until the next local write of that container), tracked in #9455. - **Detection.** No core hook. The writer's existing key matching (same NodeKey under the same container) recognizes the moved units. The records go to the units the user moved, and a whole range that moves again reuses its record. - **Scope: moves inside one container.** This covers the root, a list (items and whole lists), a table (rows), a row (cells, so column moves), a cell's or collapsible's content, and block decorators and containers moved as units. A move into another container is still a delete plus an insert (documented). - **Undo** removes the record, so the block returns with a peer's concurrent typing. Redo writes it again. A local write that deletes a record can let another record show. The writer then reads the container again, as a peer would. - **Layout.** A new document records layout 1 (`lexical-y:1: true`). The first move record, join record or lifted block adds `lexical-y:2: true` to #9400's monotone layout record, in the same transaction as the record (so no client ever receives a record without the version), and undo never deletes it; nothing else is rewritten. Clients without moves then open it read only instead of misreading it, and the record never shrinks. `LAYOUT_VERSION` is now 2, and documents without moves stay editable by older `@lexical/y` builds. The README's wire format section documents layout 2 (records, join records, lifted blocks, the upgrade) next to the frozen layout 1. - (Removed with #9400's shared repairs: the list-merge and ragged-table repair exceptions for containers with records.) - Warnings go to the editor's `onWarn` as `LexicalWarning`s, and the code uses the binding's read-only getters. On main, the update that flips a node's `isInline()` lifts the node itself (the normalization runs on what an update writes), so the flip is written as a block of its container, not as an inline node a later repair lifts in place; this PR therefore leaves `IsInline.test.ts` as #9400 has it. **Prior art.** We studied Bob Ippolito's etrepum#65, which gives every node its own Yjs node and moves a node by writing a `{id, token}` placement into its new parent. We chose instead to port Yjs's own unmerged range-move design (`ContentMove` on the `move` branch: a record at the destination points at the moved range, the higher priority wins, loops are broken) as binding-level records. Our reasons: splits and joins stay cheap marker edits, documents pay nothing until something moves, and #65's per-node layout has known cases where a split or join racing a collaborator's typing loses or misplaces that typing (marked as expected failures in its tests). Credit to one format key per mark id, the same as the follow-up #9439. No change to `lexical`, `@lexical/yjs` or any other package. Docs: the `y.md` page's "Wire format" section, which #9400 starts with a diagram of layout 1, gains diagrams of layout 2 (a move record next to the order the editor shows, and a join record) and of the upgrade from 1 to 2, checked against a dumped document, and links the README's layout 2 specification; its limits describe moves within and across containers, joins, and layout version 2. Its limits also cover text typed into a block moved out of a container that a peer removes or moves (lost), the same block moved into two containers (shown twice), and an undo of a removal racing a move out of the removed range (shown twice), and how records and tombstones grow over time, with the Yjs advice to reload long-lived rooms on the server. The README's wire format documents layout 2, and its fuzz note lists the moves fuzz variables. `@lexical/y` is unreleased and `@experimental`. ``` $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 62 passed (62) Tests 2981 passed | 4 expected fail | 2 skipped (2987) $ FUZZ_MOVE_SEEDS=1000 FUZZ_MOVE_GC_SEEDS=200 NORMALIZE_FUZZ_SEEDS=1000 \ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{Fuzz,NormalizationConvergence,Moves,Races}.test.ts normalization fuzz: {"duplicated":[],"healed":[… 60 seeds],"seeds":1005} held paragraphs fuzz: {"duplicated":[],"healed":[228,295],"seeds":1000} Tests 3483 passed (3483) ``` Adapted to #9400 v3 in this rebase: the layout test now checks the record (`lexical-y:1` and `lexical-y:2` = `true`), that the version is written in the transaction of the first move record, and that undoing the move keeps it; the two "lifts in place" tests deliver the author's normalization with its write (receivers no longer lift); the "move a block" byte budget is 108 (was 104: the record's attribute is now part of the move's update). Also `pnpm run test-unit` compared test by test with #9439 (0 failed, 0 changed; the replay of a fixture this PR deletes no longer runs), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the tree-shaking tests (369 source, 286 built), `pnpm run build-prod` and `pnpm run build-docs` pass. The rest of this test plan is from the previous base (#9400 before its v3 rework) and is re-measured in the fix round. The new tests against the previous revision of this change (joins of lines that are not one range copied, lines that span ranges re-created, repairs written as a delete and a re-insert): ``` $ npx vitest --project unit --no-watch Moves.test NormalizationConvergence.test × move of a line split after a join ‖ typing in it (4 of 4 orders) Expected: "paragraph("zeroth") / paragraph("one") / paragraph("two") / paragraph("rXee")" Received: "paragraph("zeroth") / paragraph("Xone") / paragraph("two") / paragraph("ree")" × move of a line another zone interrupts ‖ typing in both parts (4 of 4) Expected: "paragraph("three") / paragraph("one") / paragraph("zeXrotwYo")" Received: "paragraph("XrotwYthree") / paragraph("one") / paragraph("zerotwo")" × join ‖ join of a line another zone interrupts (4 of 4) Expected: "paragraph("threezerotwo") / paragraph("one")" Received: "paragraph("threezerotwozerotwo") / paragraph("one")" × join into a moved line of a line another zone interrupts ‖ typing in it (4 of 4) × two blocks written at the end of one line by two peers, lifted by a third (12 of 12) AssertionError: expected [ 'cell', 2 ] to deeply equal [ 'cell', 1 ] × a block lifted out of the middle of a line ‖ typing next to it and in it (12 of 12) AssertionError: expected [ '¶', 'b:test_box', '¶' ] to not include 'b:test_box' × a heading lifted out of a list item ‖ typing in the heading (12 of 12) × fuzz: normalization repairs by 3 peers with partial delivery, seed 44, 47, 51, 64, 79, 93 Tests 58 failed | 839 passed (897) ``` - Randomized normalization fuzz, 2,000 seeds (3 peers, 40% of edits written without the normalization, peers typing into the same blocks, partial delivery): 490 sessions copied or lost text: 102 sessions without a nested line (101 with a copied block, 1 with a lost token) and 388 with one (a heading a peer wrote inside a list item: 387 copied, 2 lost). - `Fuzz.test.ts` / the fuzz utilities: a token a peer moves into a table, box or column counts as lost by delete wins when another peer made a removal, exactly like a token typed there. Duplicates are not excused. - Block id integration (BlockIdExtension on this change), moves fuzz, 2,000 + 500 gc seeds: 15 + 3 seeds with duplicated text (joins written as a copy, lines that span ranges moved as a delete and a re-insert). - This revision's fixes, against the previous revision of this change (a record left inside a line by concurrent edits: a unit written after the block it shows split the line, and a moved line left its text before the record behind; a heading written inside a list item stored as its own node): ``` $ npx vitest --project unit --no-watch Moves.test -t 'a record left inside a line' × a block shown from inside a joined line ‖ a new line right after it (4 of 4) + "@lexical/y self-check: line 81: text \"M0 abcNEW\" != \"NEW\"; ..." × a line typed into after a removal, shown around a record, moved (4 of 4) + "@lexical/y self-check: line 133: text \"M5 pqr\" != \"XM5 pqr\"; ..." Tests 8 failed | 234 skipped (242) $ npx vitest --project unit --no-watch NormalizationConvergence.test × a line written inside a line is stored as lines (48 of 60) × a heading written inside a list item ‖ typing in the heading (12 of 12) × fuzz: seeds 405, 435, 446, 899, 937, 1078, 1388, 1507, 1683, 1820 Tests 70 failed | 665 passed (735) ``` The normalization fuzz at 2,000 seeds copied text in 8 sessions and lost it in 2, all with a heading written inside a list item. The block id moves fuzz with undo and redo off failed 2 of 2,000 seeds (162: a self-check mismatch after a move; 741: a self-check mismatch and lost text after a new line was written next to a moved block). Enter and Backspace in a 10,000 paragraph document without moves took 71.2 and 71.5 ms against 67.0 and 66.8 ms on #9400 (3 alternating runs, +6%). - A move at 10k blocks with 100 earlier moves on #9400 without this change: #9400 writes a move as a delete and a re-insert, 78 ms end to end with 100 earlier moves at 10,000 blocks (its undo writes 131 B). - Many moves, before this revision's caching (1,000 blocks, gc on): at 10,000 random moves (1,000 live records) a local move took 347 ms, a remote read of it 1,049 ms and a load 647 ms, against 5.1, 3.6 and 27 ms on #9400; at 1,000 moves (634 live records), 24.5, 16.1 and 400 ms. ``` $ npx vitest --project unit --no-watch Moves.test Races.test Tests 341 passed (341) $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 55 passed (55) Tests 2726 passed | 4 expected fail | 2 skipped (2732) $ NORMALIZE_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch NormalizationConvergence.test Tests 4973 passed (4973) # 2,000 + 2,000 fuzz seeds, matrix 864 $ NORMALIZE_FUZZ_SEEDS=10000 npx vitest --project unit --no-watch NormalizationConvergence.test -t fuzz Tests 20000 passed # 10,000 + 10,000 fuzz seeds, on the top of the stack: # 0 copies, 0 losses; 434 + 26 sessions healed a remote # self-check mismatch by a re-read $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \ npx vitest --project unit --no-watch Fuzz.test Tests 203 passed (203) ``` Re-run on this revision (main with the final node structure, #9452, and the updated #9400): the commands above; the moves fuzz at 2,000 + 500 gc seeds through the same counting harness as before: 26 and 7 seeds with lost or duplicated text, the same seeds as on the previous base, and 1,997 of 2,000 and 498 of 500 sessions write byte-identical updates (the other 3 + 2 differ where main's normalization now runs in a local update); the block id integration (moves fuzz, 2,000 + 500 gc: duplicated text on 882 and 1993 only, as before; the BlockIdExtension fuzz, 2,000 seeds, passes); and the collab Y e2e suite in Chromium (26/26) and Firefox (23 passed, 3 Chromium-only skips). From the previous base and not re-run: the 25,000 + 5,000 gc moves fuzz, the differential, the scripted byte-identity session, the block id run with undo and redo off, the playground drag spec, and the perf and many-moves tables below. - `Moves.test.ts` (249 tests, most in 4 orders) covers: - move ‖ type (inside, start and end), move ‖ move of the same block, neighbour moves, move ‖ delete, move ‖ retype, move ‖ bold, move ‖ Enter; - every join and split ‖ move combination: join ‖ join (Backspace, Delete, both, a range across a moved line), join ‖ split, join ‖ typing, join ‖ move, split ‖ move, undo of a join, a join ‖ an undo that restores a line inside the joined range; - new: lines that span ranges moved (a line split after a join, alone, ‖ typing in it and ‖ another move), a line another zone interrupts moved ‖ typing in both parts and joined ‖ typing and ‖ the same join, and a line that ends inside a joined range moved and then typed in, a block shown from inside a joined line ‖ a new line right after it, and a line typed into after a removal, shown around a record, then moved (each checks that the result is exactly the writer's intent); - list item moves (up, between lists, ‖ indent), whole-list moves ‖ add item, table row ‖ type and column ‖ type, container ‖ type, block decorator; - undo, redo, a second move, delete of a moved block, caret mapping, the layout bump, no record for documents that never move, and reads that stay incremental. - new: cached ownership, compared with ownership built fresh from the document after every step, across undo and redo with a peer typing, records that arrive out of order, a record whose anchors arrive late, text anchors split by typing (with and without gc), anchors merged by gc, and a moved block deleted with its old neighbour under gc. Taking out the anchor check fails them. - `NormalizationConvergence.test.ts`: the 3-peer matrix (18 violations × 8 delivery schedules × 6 id orders) passes 864/864; new lift tests (a block lifted out of the middle of a line ‖ typing next to it and in it, two blocks written at the end of one line by two peers and lifted by a third, a heading written inside a list item ‖ typing in it, a block put inside such a heading and lifted from other surroundings; 6 id orders × 2 deliveries each) check the text, the stored node (`u`, no copy, no `i:heading`) and the layout bump. The randomized fuzz fails on any copied or lost token, in every session, and always runs the seeds that failed during this work. A second randomized fuzz adds edits that write plain paragraphs into quotes and list items (joined into them as lines by the normalization) and new quotes, starting from a document with a quote and a numbered list. Both pass at 2,000 and 10,000 seeds each (0 copies, 0 losses). - Fuzz with block moves (the whole stack): 2,000 + 500 gc and 25,000 + 5,000 gc seeds, 0 absolute findings (divergence, exceptions, fragments, self-check, fresh readers). The fuzz now counts a block moved into a container a peer removed as delete wins, as it already did for text typed into one. Seeds with lost or duplicated text: 26 of 2,000 (1.3%; 69 before that accounting change), 7 of 500 gc (20 before), 278 of 25,000 (1.1%; 767 before) and 52 of 5,000 gc (157 before). All of them are documented limits: two peers moving the same block when one moves it into another container (shown twice), a move into another container racing a move of its container or an undo of a removal (shown twice), text typed into a block a list conversion lifts, and joins written as a copy. `Fuzz.test.ts` at 2,000 + 500 seeds with and without moves passes, including a regression seed (a comment over a line joined with a line of two pieces, then an undo). Differential against v2, 2,000 + 500 gc: 0 absolute findings, 5 + 1 seeds worse than v2. - This revision writes exactly what the previous one wrote. Every update of a scripted two-peer session (900 steps of moves, typing, Enter, joins, removals, undo and redo, with and without gc), of the moves fuzz (2,000 + 2,000 gc and 25,000 + 5,000 gc seeds, every peer's updates hashed per seed) and of 10,000 random moves is byte-identical before and after, and the fuzz findings, the differential (the same 5 + 1 seeds) and the block id runs below are unchanged. - Block id integration (BlockIdExtension on this stack): the moves fuzz, 2,000 + 500 gc seeds, has 0 divergence, 0 self-check warnings and 0 lost text; 2 + 0 seeds show duplicated text (882, 1993): in both, two peers remove the same text and both undo the removal, and each undo restores its own copy, which Yjs does with plain `Y.Text` too (no move is involved). With undo and redo off, 2,000 + 500 seeds have no finding (162 and 741 failed before). The BlockIdExtension fuzz, 2,000 seeds, passes. - Many moves (1,000 blocks; ms: local move, remote read of it, load; mean of the last 50 moves, median of 3 loads; #9400 / before / after): | Moves, gc | Live records | Local move | Remote read | Load | | --- | --- | --- | --- | --- | | 100 random, on | 97 | 4.8 / 8.1 / 8.3 | 2.8 / 3.7 / 3.7 | 20 / 69 / 24 | | 1,000 random, on | 634 | 4.5 / 24.5 / 17.2 | 3.1 / 16.1 / 8.0 | 20 / 400 / 29 | | 10,000 random, on | 1,000 | 5.1 / 347 / 33.5 | 3.6 / 1,049 / 26.9 | 27 / 647 / 46 | | 10,000 random, off | 1,000 | 6.7 / 357 / 35.0 | 5.5 / 1,086 / 28.8 | 49 / 783 / 135 | | 10,000 back and forth, on | 1 | 5.3 / 10.0 / 10.2 | 3.0 / 8.6 / 8.7 | 22 / 28 / 26 | | 10,000 back and forth, off | 1 | 7.6 / 11.2 / 11.1 | 4.3 / 10.1 / 10.2 | 52 / 128 / 122 | A keystroke in a moved block stays at 2.2 to 4.6 ms (#9400: 2.2 to 3.0). Sizes are unchanged (235 KB after 10,000 random moves with gc, 157 KB on #9400). The remaining cost grows with the container's items, deleted records included, which Yjs keeps in the sequence. - Perf at 10,000 blocks (end to end, shared machine, #9400 → the top of the stack): Enter and Backspace in a document without moves, median of the per-round ratio over 6 alternating rounds, +0.0 to +0.5% at the top of the stack and -1.8 to +1.3% with this change alone (+6% for the previous revision); keystroke 38.7 → 38.6 ms (list item 47.9 → 46.3), load 195 → 193 ms, size, 10k-edit growth and bytes per edit identical; a move 97 → 124 ms (131 → 106 B), its undo 69 → 73 ms (131 → 11 B). - Playground (`?isCollab=true&useCollabY=true`, the stack's playground mode, a scratch spec): drag a block while the other tab types in it, a list, a list item, a table row, undo, and the same block dragged twice: Chromium 21/21 (3 repeats), Firefox 7/7, WebKit 7/7; the collab Y e2e suite passes in all three (26/26, 23/23 + 3 Chromium-only IME skips). - On this commit: `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (368 passed), `pnpm run build-prod` and the built tree-shaking test (284 passed).
zurfyx
force-pushed
the
zurfyx/collab-y-server
branch
from
October 26, 2026 16:40
3f77588 to
5a5d300
Compare
zurfyx
force-pushed
the
zurfyx/collab-y14-block-markers
branch
from
October 26, 2026 19:37
eb0175e to
48857a8
Compare
zurfyx
added a commit
that referenced
this pull request
Oct 26, 2026
Stacked on #9439 (the `@lexical/y` stack: #9400, #9437, #9438, #9439). This PR is now last in the stack. > **Status: rebased, not yet reworked.** This change was moved to the end of > the stack and onto #9400's v3 design (no shared repairs, a monotone layout > record, follow-ups that only set attributes or delete). It compiles and its > own tests pass, but parts of this description still describe the earlier > design and are marked below; it gets its own fix round (performance, > remaining review findings, docs) before review. Today a block move in `@lexical/y` is a delete plus a re-insert: the binding re-creates the cheaper side, so text a collaborator types into the moved block at the same time lands in its old neighbour, and two collaborators moving the same block can duplicate it. The normalization repairs every peer runs (a block lifted out of the paragraph it was written in) are written the same way, so two peers that lift one block from different surroundings both re-create it, and text typed into it meanwhile is lost. (On #9400 v3 the author normalizes its own write instead of every peer repairing it; see "Lifted blocks" below.) A move now keeps the moved items where they are and writes a small move record where the block shows. A move changes only position, never the moved content's characters. - **Records.** A record `↷` is a child `Y.Node` of the container. It names a range of the container's own sequence by Yjs item id (`s` is the item before the range, or none; `e` is the range's last item) and has a priority `p`. Items a peer inserts later inside the range (typing, Enter) belong to it too. This ports the semantics of Yjs' unmerged range move (ContentMove: highest priority wins, loops are broken) to binding-level records. Yjs 14 has no native move. - **Ownership is computed when reading, from the document alone.** An item belongs to the active record of highest priority (then client, then clock) whose range holds it. A record placed inside its own range, directly or through other records, shows nothing. Nothing is repaired or written back. A record written again keeps its rank (`o`). A write that splits an anchor item (typing inside the last word of a range) keeps the range: anchors resolve to the item holding their id. - **Records are not boundaries.** A record shows its units before the line its item is in, so text typed concurrently at a line start stays in its line. Formats stay positional, as in Yjs. - **Joins keep their items.** Joining a line into a moved line (Backspace, Delete, a deletion across lines) writes join records (`j: 1`) at the end of the first line's text. They show the second line's text in their place, so the joined line can span ranges and the second line's characters are never copied. A second line that is not one range (a block moved away from between its parts, or it starts inside a joined range) gets one join record per piece. Two peers that make the same join write records of the same ranges; one wins and the other shows nothing, so the text appears once. - **Lines that span ranges move with their items.** A line split off a joined line, or joined across a moved range, is moved with one join record per piece but its last (written at the start of the last piece) and a block record over the last piece, instead of being re-created. - **Lifted blocks keep their node.** A block written inside a line (a table appended to a paragraph without the normalization, an older client) keeps its shared node when the normalization lifts it out (on #9400 v3, the normalization of its author) (a line written inside a line, such as a heading in a list item, is stored as lines by #9400 and needs no lift): the node is marked a unit of its container (`u: 1` on the `i:<type>` node), which splits the line around it, and the line parts get markers. (The earlier design, where every peer lifted it under a content-derived client id, is gone with #9400's shared repairs.) Lexical replacing such a block by a new one of its type (Enter at its start) keeps the shared node too. - **Records left inside a line.** A record can end up between a line's characters when the line around it changed at the same time: a peer joined the lines around it (the record is inside the joined range), or removed the line before it while another typed in that line. New units then go right after the block the record shows only when that is a line boundary, otherwise right before the next line, and when the block shows from inside that next line it is written again with a record where it shows. A moved line that such a record interrupts moves with its pieces (its text before the record too). A record is written again at its line start only when the same records stay active (moving it out of another record's range can make a record that showed nothing show its range). - **Zero cost without moves.** Every new path sits behind "this container holds a record" or "this write lifts a block". The per-keystroke cost, size, 10k-edit growth and load time of documents that never move are unchanged, and Enter and Backspace there are within 3% of #9400. - **Incremental read.** A peer that receives a move, its undo or redo, or a structural edit in a container with records re-parses only windows around the records whose ownership changed. Each window is bounded by end items its zone owns before and after the change, so a unit keeps its node only when its content provably did not change. Format edits, join records and unresolved records still read the whole container. - **Cost with many records.** Outside a transaction, a container's cached ownership is checked against the document (records deleted, anchors split or merged) once after each transaction starts and once after Yjs cleans one up, instead of on every use; inside a transaction it is still checked on every use. Which records are active, and the ownership before a change in an incremental read, come from a painted index instead of a scan of the records per position. An incremental read takes formats from one walk of the container, and the check for records left inside a line stops where the previous record's check stopped. Nothing written changes: the updates of a scripted session and of every fuzz session are byte-identical before and after. At 10,000 random moves on 1,000 blocks (every block moved, 1,000 live records), a local move goes from 347 to 34 ms, a remote read from 1,049 to 27 ms and a load from 647 to 46 ms (#9400: 5.1, 3.6 and 27 ms). What is left grows with the container's items, deleted records included. - **Records over time.** Each move leaves a tombstone of about 18 B once Yjs collects garbage (a delete and a re-insert on #9400 leaves 16.5 B). Live records stay at most one per moved range, apart from rare cases (a block moved back to where it was, a record that lost a loop, a record whose range a peer deleted, until the next local write of that container), tracked in #9455. - **Detection.** No core hook. The writer's existing key matching (same NodeKey under the same container) recognizes the moved units. The records go to the units the user moved, and a whole range that moves again reuses its record. - **Scope: moves inside one container.** This covers the root, a list (items and whole lists), a table (rows), a row (cells, so column moves), a cell's or collapsible's content, and block decorators and containers moved as units. A move into another container is still a delete plus an insert (documented). - **Undo** removes the record, so the block returns with a peer's concurrent typing. Redo writes it again. A local write that deletes a record can let another record show. The writer then reads the container again, as a peer would. - **Layout.** A new document records layout 1 (`lexical-y:1: true`). The first move record, join record or lifted block adds `lexical-y:2: true` to #9400's monotone layout record, in the same transaction as the record (so no client ever receives a record without the version), and undo never deletes it; nothing else is rewritten. Clients without moves then open it read only instead of misreading it, and the record never shrinks. `LAYOUT_VERSION` is now 2, and documents without moves stay editable by older `@lexical/y` builds. The README's wire format section documents layout 2 (records, join records, lifted blocks, the upgrade) next to the frozen layout 1. - (Removed with #9400's shared repairs: the list-merge and ragged-table repair exceptions for containers with records.) - Warnings go to the editor's `onWarn` as `LexicalWarning`s, and the code uses the binding's read-only getters. On main, the update that flips a node's `isInline()` lifts the node itself (the normalization runs on what an update writes), so the flip is written as a block of its container, not as an inline node a later repair lifts in place; this PR therefore leaves `IsInline.test.ts` as #9400 has it. **Prior art.** We studied Bob Ippolito's etrepum#65, which gives every node its own Yjs node and moves a node by writing a `{id, token}` placement into its new parent. We chose instead to port Yjs's own unmerged range-move design (`ContentMove` on the `move` branch: a record at the destination points at the moved range, the higher priority wins, loops are broken) as binding-level records. Our reasons: splits and joins stay cheap marker edits, documents pay nothing until something moves, and #65's per-node layout has known cases where a split or join racing a collaborator's typing loses or misplaces that typing (marked as expected failures in its tests). Credit to one format key per mark id, the same as the follow-up #9439. No change to `lexical`, `@lexical/yjs` or any other package. Docs: the `y.md` page's "Wire format" section, which #9400 starts with a diagram of layout 1, gains diagrams of layout 2 (a move record next to the order the editor shows, and a join record) and of the upgrade from 1 to 2, checked against a dumped document, and links the README's layout 2 specification; its limits describe moves within and across containers, joins, and layout version 2. Its limits also cover text typed into a block moved out of a container that a peer removes or moves (lost), the same block moved into two containers (shown twice), and an undo of a removal racing a move out of the removed range (shown twice), and how records and tombstones grow over time, with the Yjs advice to reload long-lived rooms on the server. The README's wire format documents layout 2, and its fuzz note lists the moves fuzz variables. `@lexical/y` is unreleased and `@experimental`. ``` $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 62 passed (62) Tests 2981 passed | 4 expected fail | 2 skipped (2987) $ FUZZ_MOVE_SEEDS=1000 FUZZ_MOVE_GC_SEEDS=200 NORMALIZE_FUZZ_SEEDS=1000 \ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{Fuzz,NormalizationConvergence,Moves,Races}.test.ts normalization fuzz: {"duplicated":[],"healed":[… 60 seeds],"seeds":1005} held paragraphs fuzz: {"duplicated":[],"healed":[228,295],"seeds":1000} Tests 3483 passed (3483) ``` Adapted to #9400 v3 in this rebase: the layout test now checks the record (`lexical-y:1` and `lexical-y:2` = `true`), that the version is written in the transaction of the first move record, and that undoing the move keeps it; the two "lifts in place" tests deliver the author's normalization with its write (receivers no longer lift); the "move a block" byte budget is 108 (was 104: the record's attribute is now part of the move's update). Also `pnpm run test-unit` compared test by test with #9439 (0 failed, 0 changed; the replay of a fixture this PR deletes no longer runs), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the tree-shaking tests (369 source, 286 built), `pnpm run build-prod` and `pnpm run build-docs` pass. The rest of this test plan is from the previous base (#9400 before its v3 rework) and is re-measured in the fix round. The new tests against the previous revision of this change (joins of lines that are not one range copied, lines that span ranges re-created, repairs written as a delete and a re-insert): ``` $ npx vitest --project unit --no-watch Moves.test NormalizationConvergence.test × move of a line split after a join ‖ typing in it (4 of 4 orders) Expected: "paragraph("zeroth") / paragraph("one") / paragraph("two") / paragraph("rXee")" Received: "paragraph("zeroth") / paragraph("Xone") / paragraph("two") / paragraph("ree")" × move of a line another zone interrupts ‖ typing in both parts (4 of 4) Expected: "paragraph("three") / paragraph("one") / paragraph("zeXrotwYo")" Received: "paragraph("XrotwYthree") / paragraph("one") / paragraph("zerotwo")" × join ‖ join of a line another zone interrupts (4 of 4) Expected: "paragraph("threezerotwo") / paragraph("one")" Received: "paragraph("threezerotwozerotwo") / paragraph("one")" × join into a moved line of a line another zone interrupts ‖ typing in it (4 of 4) × two blocks written at the end of one line by two peers, lifted by a third (12 of 12) AssertionError: expected [ 'cell', 2 ] to deeply equal [ 'cell', 1 ] × a block lifted out of the middle of a line ‖ typing next to it and in it (12 of 12) AssertionError: expected [ '¶', 'b:test_box', '¶' ] to not include 'b:test_box' × a heading lifted out of a list item ‖ typing in the heading (12 of 12) × fuzz: normalization repairs by 3 peers with partial delivery, seed 44, 47, 51, 64, 79, 93 Tests 58 failed | 839 passed (897) ``` - Randomized normalization fuzz, 2,000 seeds (3 peers, 40% of edits written without the normalization, peers typing into the same blocks, partial delivery): 490 sessions copied or lost text: 102 sessions without a nested line (101 with a copied block, 1 with a lost token) and 388 with one (a heading a peer wrote inside a list item: 387 copied, 2 lost). - `Fuzz.test.ts` / the fuzz utilities: a token a peer moves into a table, box or column counts as lost by delete wins when another peer made a removal, exactly like a token typed there. Duplicates are not excused. - Block id integration (BlockIdExtension on this change), moves fuzz, 2,000 + 500 gc seeds: 15 + 3 seeds with duplicated text (joins written as a copy, lines that span ranges moved as a delete and a re-insert). - This revision's fixes, against the previous revision of this change (a record left inside a line by concurrent edits: a unit written after the block it shows split the line, and a moved line left its text before the record behind; a heading written inside a list item stored as its own node): ``` $ npx vitest --project unit --no-watch Moves.test -t 'a record left inside a line' × a block shown from inside a joined line ‖ a new line right after it (4 of 4) + "@lexical/y self-check: line 81: text \"M0 abcNEW\" != \"NEW\"; ..." × a line typed into after a removal, shown around a record, moved (4 of 4) + "@lexical/y self-check: line 133: text \"M5 pqr\" != \"XM5 pqr\"; ..." Tests 8 failed | 234 skipped (242) $ npx vitest --project unit --no-watch NormalizationConvergence.test × a line written inside a line is stored as lines (48 of 60) × a heading written inside a list item ‖ typing in the heading (12 of 12) × fuzz: seeds 405, 435, 446, 899, 937, 1078, 1388, 1507, 1683, 1820 Tests 70 failed | 665 passed (735) ``` The normalization fuzz at 2,000 seeds copied text in 8 sessions and lost it in 2, all with a heading written inside a list item. The block id moves fuzz with undo and redo off failed 2 of 2,000 seeds (162: a self-check mismatch after a move; 741: a self-check mismatch and lost text after a new line was written next to a moved block). Enter and Backspace in a 10,000 paragraph document without moves took 71.2 and 71.5 ms against 67.0 and 66.8 ms on #9400 (3 alternating runs, +6%). - A move at 10k blocks with 100 earlier moves on #9400 without this change: #9400 writes a move as a delete and a re-insert, 78 ms end to end with 100 earlier moves at 10,000 blocks (its undo writes 131 B). - Many moves, before this revision's caching (1,000 blocks, gc on): at 10,000 random moves (1,000 live records) a local move took 347 ms, a remote read of it 1,049 ms and a load 647 ms, against 5.1, 3.6 and 27 ms on #9400; at 1,000 moves (634 live records), 24.5, 16.1 and 400 ms. ``` $ npx vitest --project unit --no-watch Moves.test Races.test Tests 341 passed (341) $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 55 passed (55) Tests 2726 passed | 4 expected fail | 2 skipped (2732) $ NORMALIZE_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch NormalizationConvergence.test Tests 4973 passed (4973) # 2,000 + 2,000 fuzz seeds, matrix 864 $ NORMALIZE_FUZZ_SEEDS=10000 npx vitest --project unit --no-watch NormalizationConvergence.test -t fuzz Tests 20000 passed # 10,000 + 10,000 fuzz seeds, on the top of the stack: # 0 copies, 0 losses; 434 + 26 sessions healed a remote # self-check mismatch by a re-read $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \ npx vitest --project unit --no-watch Fuzz.test Tests 203 passed (203) ``` Re-run on this revision (main with the final node structure, #9452, and the updated #9400): the commands above; the moves fuzz at 2,000 + 500 gc seeds through the same counting harness as before: 26 and 7 seeds with lost or duplicated text, the same seeds as on the previous base, and 1,997 of 2,000 and 498 of 500 sessions write byte-identical updates (the other 3 + 2 differ where main's normalization now runs in a local update); the block id integration (moves fuzz, 2,000 + 500 gc: duplicated text on 882 and 1993 only, as before; the BlockIdExtension fuzz, 2,000 seeds, passes); and the collab Y e2e suite in Chromium (26/26) and Firefox (23 passed, 3 Chromium-only skips). From the previous base and not re-run: the 25,000 + 5,000 gc moves fuzz, the differential, the scripted byte-identity session, the block id run with undo and redo off, the playground drag spec, and the perf and many-moves tables below. - `Moves.test.ts` (249 tests, most in 4 orders) covers: - move ‖ type (inside, start and end), move ‖ move of the same block, neighbour moves, move ‖ delete, move ‖ retype, move ‖ bold, move ‖ Enter; - every join and split ‖ move combination: join ‖ join (Backspace, Delete, both, a range across a moved line), join ‖ split, join ‖ typing, join ‖ move, split ‖ move, undo of a join, a join ‖ an undo that restores a line inside the joined range; - new: lines that span ranges moved (a line split after a join, alone, ‖ typing in it and ‖ another move), a line another zone interrupts moved ‖ typing in both parts and joined ‖ typing and ‖ the same join, and a line that ends inside a joined range moved and then typed in, a block shown from inside a joined line ‖ a new line right after it, and a line typed into after a removal, shown around a record, then moved (each checks that the result is exactly the writer's intent); - list item moves (up, between lists, ‖ indent), whole-list moves ‖ add item, table row ‖ type and column ‖ type, container ‖ type, block decorator; - undo, redo, a second move, delete of a moved block, caret mapping, the layout bump, no record for documents that never move, and reads that stay incremental. - new: cached ownership, compared with ownership built fresh from the document after every step, across undo and redo with a peer typing, records that arrive out of order, a record whose anchors arrive late, text anchors split by typing (with and without gc), anchors merged by gc, and a moved block deleted with its old neighbour under gc. Taking out the anchor check fails them. - `NormalizationConvergence.test.ts`: the 3-peer matrix (18 violations × 8 delivery schedules × 6 id orders) passes 864/864; new lift tests (a block lifted out of the middle of a line ‖ typing next to it and in it, two blocks written at the end of one line by two peers and lifted by a third, a heading written inside a list item ‖ typing in it, a block put inside such a heading and lifted from other surroundings; 6 id orders × 2 deliveries each) check the text, the stored node (`u`, no copy, no `i:heading`) and the layout bump. The randomized fuzz fails on any copied or lost token, in every session, and always runs the seeds that failed during this work. A second randomized fuzz adds edits that write plain paragraphs into quotes and list items (joined into them as lines by the normalization) and new quotes, starting from a document with a quote and a numbered list. Both pass at 2,000 and 10,000 seeds each (0 copies, 0 losses). - Fuzz with block moves (the whole stack): 2,000 + 500 gc and 25,000 + 5,000 gc seeds, 0 absolute findings (divergence, exceptions, fragments, self-check, fresh readers). The fuzz now counts a block moved into a container a peer removed as delete wins, as it already did for text typed into one. Seeds with lost or duplicated text: 26 of 2,000 (1.3%; 69 before that accounting change), 7 of 500 gc (20 before), 278 of 25,000 (1.1%; 767 before) and 52 of 5,000 gc (157 before). All of them are documented limits: two peers moving the same block when one moves it into another container (shown twice), a move into another container racing a move of its container or an undo of a removal (shown twice), text typed into a block a list conversion lifts, and joins written as a copy. `Fuzz.test.ts` at 2,000 + 500 seeds with and without moves passes, including a regression seed (a comment over a line joined with a line of two pieces, then an undo). Differential against v2, 2,000 + 500 gc: 0 absolute findings, 5 + 1 seeds worse than v2. - This revision writes exactly what the previous one wrote. Every update of a scripted two-peer session (900 steps of moves, typing, Enter, joins, removals, undo and redo, with and without gc), of the moves fuzz (2,000 + 2,000 gc and 25,000 + 5,000 gc seeds, every peer's updates hashed per seed) and of 10,000 random moves is byte-identical before and after, and the fuzz findings, the differential (the same 5 + 1 seeds) and the block id runs below are unchanged. - Block id integration (BlockIdExtension on this stack): the moves fuzz, 2,000 + 500 gc seeds, has 0 divergence, 0 self-check warnings and 0 lost text; 2 + 0 seeds show duplicated text (882, 1993): in both, two peers remove the same text and both undo the removal, and each undo restores its own copy, which Yjs does with plain `Y.Text` too (no move is involved). With undo and redo off, 2,000 + 500 seeds have no finding (162 and 741 failed before). The BlockIdExtension fuzz, 2,000 seeds, passes. - Many moves (1,000 blocks; ms: local move, remote read of it, load; mean of the last 50 moves, median of 3 loads; #9400 / before / after): | Moves, gc | Live records | Local move | Remote read | Load | | --- | --- | --- | --- | --- | | 100 random, on | 97 | 4.8 / 8.1 / 8.3 | 2.8 / 3.7 / 3.7 | 20 / 69 / 24 | | 1,000 random, on | 634 | 4.5 / 24.5 / 17.2 | 3.1 / 16.1 / 8.0 | 20 / 400 / 29 | | 10,000 random, on | 1,000 | 5.1 / 347 / 33.5 | 3.6 / 1,049 / 26.9 | 27 / 647 / 46 | | 10,000 random, off | 1,000 | 6.7 / 357 / 35.0 | 5.5 / 1,086 / 28.8 | 49 / 783 / 135 | | 10,000 back and forth, on | 1 | 5.3 / 10.0 / 10.2 | 3.0 / 8.6 / 8.7 | 22 / 28 / 26 | | 10,000 back and forth, off | 1 | 7.6 / 11.2 / 11.1 | 4.3 / 10.1 / 10.2 | 52 / 128 / 122 | A keystroke in a moved block stays at 2.2 to 4.6 ms (#9400: 2.2 to 3.0). Sizes are unchanged (235 KB after 10,000 random moves with gc, 157 KB on #9400). The remaining cost grows with the container's items, deleted records included, which Yjs keeps in the sequence. - Perf at 10,000 blocks (end to end, shared machine, #9400 → the top of the stack): Enter and Backspace in a document without moves, median of the per-round ratio over 6 alternating rounds, +0.0 to +0.5% at the top of the stack and -1.8 to +1.3% with this change alone (+6% for the previous revision); keystroke 38.7 → 38.6 ms (list item 47.9 → 46.3), load 195 → 193 ms, size, 10k-edit growth and bytes per edit identical; a move 97 → 124 ms (131 → 106 B), its undo 69 → 73 ms (131 → 11 B). - Playground (`?isCollab=true&useCollabY=true`, the stack's playground mode, a scratch spec): drag a block while the other tab types in it, a list, a list item, a table row, undo, and the same block dragged twice: Chromium 21/21 (3 repeats), Firefox 7/7, WebKit 7/7; the collab Y e2e suite passes in all three (26/26, 23/23 + 3 Chromium-only IME skips). - On this commit: `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (368 passed), `pnpm run build-prod` and the built tree-shaking test (284 passed).
zurfyx
force-pushed
the
zurfyx/collab-y-server
branch
from
October 26, 2026 19:37
5a5d300 to
eceaf0c
Compare
zurfyx
force-pushed
the
zurfyx/collab-y-server
branch
from
October 26, 2026 22:04
eceaf0c to
abf8354
Compare
zurfyx
added a commit
that referenced
this pull request
Oct 26, 2026
Stacked on #9439 (the `@lexical/y` stack: #9400, #9437, #9438, #9439). This PR is now last in the stack. > **Status: rebased, not yet reworked.** This change was moved to the end of > the stack and onto #9400's v3 design (no shared repairs, a monotone layout > record, follow-ups that only set attributes or delete). It compiles and its > own tests pass, but parts of this description still describe the earlier > design and are marked below; it gets its own fix round (performance, > remaining review findings, docs) before review. Today a block move in `@lexical/y` is a delete plus a re-insert: the binding re-creates the cheaper side, so text a collaborator types into the moved block at the same time lands in its old neighbour, and two collaborators moving the same block can duplicate it. The normalization repairs every peer runs (a block lifted out of the paragraph it was written in) are written the same way, so two peers that lift one block from different surroundings both re-create it, and text typed into it meanwhile is lost. (On #9400 v3 the author normalizes its own write instead of every peer repairing it; see "Lifted blocks" below.) A move now keeps the moved items where they are and writes a small move record where the block shows. A move changes only position, never the moved content's characters. - **Records.** A record `↷` is a child `Y.Node` of the container. It names a range of the container's own sequence by Yjs item id (`s` is the item before the range, or none; `e` is the range's last item) and has a priority `p`. Items a peer inserts later inside the range (typing, Enter) belong to it too. This ports the semantics of Yjs' unmerged range move (ContentMove: highest priority wins, loops are broken) to binding-level records. Yjs 14 has no native move. - **Ownership is computed when reading, from the document alone.** An item belongs to the active record of highest priority (then client, then clock) whose range holds it. A record placed inside its own range, directly or through other records, shows nothing. Nothing is repaired or written back. A record written again keeps its rank (`o`). A write that splits an anchor item (typing inside the last word of a range) keeps the range: anchors resolve to the item holding their id. - **Records are not boundaries.** A record shows its units before the line its item is in, so text typed concurrently at a line start stays in its line. Formats stay positional, as in Yjs. - **Joins keep their items.** Joining a line into a moved line (Backspace, Delete, a deletion across lines) writes join records (`j: 1`) at the end of the first line's text. They show the second line's text in their place, so the joined line can span ranges and the second line's characters are never copied. A second line that is not one range (a block moved away from between its parts, or it starts inside a joined range) gets one join record per piece. Two peers that make the same join write records of the same ranges; one wins and the other shows nothing, so the text appears once. - **Lines that span ranges move with their items.** A line split off a joined line, or joined across a moved range, is moved with one join record per piece but its last (written at the start of the last piece) and a block record over the last piece, instead of being re-created. - **Lifted blocks keep their node.** A block written inside a line (a table appended to a paragraph without the normalization, an older client) keeps its shared node when the normalization lifts it out (on #9400 v3, the normalization of its author) (a line written inside a line, such as a heading in a list item, is stored as lines by #9400 and needs no lift): the node is marked a unit of its container (`u: 1` on the `i:<type>` node), which splits the line around it, and the line parts get markers. (The earlier design, where every peer lifted it under a content-derived client id, is gone with #9400's shared repairs.) Lexical replacing such a block by a new one of its type (Enter at its start) keeps the shared node too. - **Records left inside a line.** A record can end up between a line's characters when the line around it changed at the same time: a peer joined the lines around it (the record is inside the joined range), or removed the line before it while another typed in that line. New units then go right after the block the record shows only when that is a line boundary, otherwise right before the next line, and when the block shows from inside that next line it is written again with a record where it shows. A moved line that such a record interrupts moves with its pieces (its text before the record too). A record is written again at its line start only when the same records stay active (moving it out of another record's range can make a record that showed nothing show its range). - **Zero cost without moves.** Every new path sits behind "this container holds a record" or "this write lifts a block". The per-keystroke cost, size, 10k-edit growth and load time of documents that never move are unchanged, and Enter and Backspace there are within 3% of #9400. - **Incremental read.** A peer that receives a move, its undo or redo, or a structural edit in a container with records re-parses only windows around the records whose ownership changed. Each window is bounded by end items its zone owns before and after the change, so a unit keeps its node only when its content provably did not change. Format edits, join records and unresolved records still read the whole container. - **Cost with many records.** Outside a transaction, a container's cached ownership is checked against the document (records deleted, anchors split or merged) once after each transaction starts and once after Yjs cleans one up, instead of on every use; inside a transaction it is still checked on every use. Which records are active, and the ownership before a change in an incremental read, come from a painted index instead of a scan of the records per position. An incremental read takes formats from one walk of the container, and the check for records left inside a line stops where the previous record's check stopped. Nothing written changes: the updates of a scripted session and of every fuzz session are byte-identical before and after. At 10,000 random moves on 1,000 blocks (every block moved, 1,000 live records), a local move goes from 347 to 34 ms, a remote read from 1,049 to 27 ms and a load from 647 to 46 ms (#9400: 5.1, 3.6 and 27 ms). What is left grows with the container's items, deleted records included. - **Records over time.** Each move leaves a tombstone of about 18 B once Yjs collects garbage (a delete and a re-insert on #9400 leaves 16.5 B). Live records stay at most one per moved range, apart from rare cases (a block moved back to where it was, a record that lost a loop, a record whose range a peer deleted, until the next local write of that container), tracked in #9455. - **Detection.** No core hook. The writer's existing key matching (same NodeKey under the same container) recognizes the moved units. The records go to the units the user moved, and a whole range that moves again reuses its record. - **Scope: moves inside one container.** This covers the root, a list (items and whole lists), a table (rows), a row (cells, so column moves), a cell's or collapsible's content, and block decorators and containers moved as units. A move into another container is still a delete plus an insert (documented). - **Undo** removes the record, so the block returns with a peer's concurrent typing. Redo writes it again. A local write that deletes a record can let another record show. The writer then reads the container again, as a peer would. - **Layout.** A new document records layout 1 (`lexical-y:1: true`). The first move record, join record or lifted block adds `lexical-y:2: true` to #9400's monotone layout record, in the same transaction as the record (so no client ever receives a record without the version), and undo never deletes it; nothing else is rewritten. Clients without moves then open it read only instead of misreading it, and the record never shrinks. `LAYOUT_VERSION` is now 2, and documents without moves stay editable by older `@lexical/y` builds. The README's wire format section documents layout 2 (records, join records, lifted blocks, the upgrade) next to the frozen layout 1. - (Removed with #9400's shared repairs: the list-merge and ragged-table repair exceptions for containers with records.) - Warnings go to the editor's `onWarn` as `LexicalWarning`s, and the code uses the binding's read-only getters. On main, the update that flips a node's `isInline()` lifts the node itself (the normalization runs on what an update writes), so the flip is written as a block of its container, not as an inline node a later repair lifts in place; this PR therefore leaves `IsInline.test.ts` as #9400 has it. **Prior art.** We studied Bob Ippolito's etrepum#65, which gives every node its own Yjs node and moves a node by writing a `{id, token}` placement into its new parent. We chose instead to port Yjs's own unmerged range-move design (`ContentMove` on the `move` branch: a record at the destination points at the moved range, the higher priority wins, loops are broken) as binding-level records. Our reasons: splits and joins stay cheap marker edits, documents pay nothing until something moves, and #65's per-node layout has known cases where a split or join racing a collaborator's typing loses or misplaces that typing (marked as expected failures in its tests). Credit to one format key per mark id, the same as the follow-up #9439. No change to `lexical`, `@lexical/yjs` or any other package. Docs: the `y.md` page's "Wire format" section, which #9400 starts with a diagram of layout 1, gains diagrams of layout 2 (a move record next to the order the editor shows, and a join record) and of the upgrade from 1 to 2, checked against a dumped document, and links the README's layout 2 specification; its limits describe moves within and across containers, joins, and layout version 2. Its limits also cover text typed into a block moved out of a container that a peer removes or moves (lost), the same block moved into two containers (shown twice), and an undo of a removal racing a move out of the removed range (shown twice), and how records and tombstones grow over time, with the Yjs advice to reload long-lived rooms on the server. The README's wire format documents layout 2, and its fuzz note lists the moves fuzz variables. `@lexical/y` is unreleased and `@experimental`. ``` $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 62 passed (62) Tests 2981 passed | 4 expected fail | 2 skipped (2987) $ FUZZ_MOVE_SEEDS=1000 FUZZ_MOVE_GC_SEEDS=200 NORMALIZE_FUZZ_SEEDS=1000 \ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{Fuzz,NormalizationConvergence,Moves,Races}.test.ts normalization fuzz: {"duplicated":[],"healed":[… 60 seeds],"seeds":1005} held paragraphs fuzz: {"duplicated":[],"healed":[228,295],"seeds":1000} Tests 3483 passed (3483) ``` Adapted to #9400 v3 in this rebase: the layout test now checks the record (`lexical-y:1` and `lexical-y:2` = `true`), that the version is written in the transaction of the first move record, and that undoing the move keeps it; the two "lifts in place" tests deliver the author's normalization with its write (receivers no longer lift); the "move a block" byte budget is 108 (was 104: the record's attribute is now part of the move's update). Also `pnpm run test-unit` compared test by test with #9439 (0 failed, 0 changed; the replay of a fixture this PR deletes no longer runs), `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the tree-shaking tests (369 source, 286 built), `pnpm run build-prod` and `pnpm run build-docs` pass. The rest of this test plan is from the previous base (#9400 before its v3 rework) and is re-measured in the fix round. The new tests against the previous revision of this change (joins of lines that are not one range copied, lines that span ranges re-created, repairs written as a delete and a re-insert): ``` $ npx vitest --project unit --no-watch Moves.test NormalizationConvergence.test × move of a line split after a join ‖ typing in it (4 of 4 orders) Expected: "paragraph("zeroth") / paragraph("one") / paragraph("two") / paragraph("rXee")" Received: "paragraph("zeroth") / paragraph("Xone") / paragraph("two") / paragraph("ree")" × move of a line another zone interrupts ‖ typing in both parts (4 of 4) Expected: "paragraph("three") / paragraph("one") / paragraph("zeXrotwYo")" Received: "paragraph("XrotwYthree") / paragraph("one") / paragraph("zerotwo")" × join ‖ join of a line another zone interrupts (4 of 4) Expected: "paragraph("threezerotwo") / paragraph("one")" Received: "paragraph("threezerotwozerotwo") / paragraph("one")" × join into a moved line of a line another zone interrupts ‖ typing in it (4 of 4) × two blocks written at the end of one line by two peers, lifted by a third (12 of 12) AssertionError: expected [ 'cell', 2 ] to deeply equal [ 'cell', 1 ] × a block lifted out of the middle of a line ‖ typing next to it and in it (12 of 12) AssertionError: expected [ '¶', 'b:test_box', '¶' ] to not include 'b:test_box' × a heading lifted out of a list item ‖ typing in the heading (12 of 12) × fuzz: normalization repairs by 3 peers with partial delivery, seed 44, 47, 51, 64, 79, 93 Tests 58 failed | 839 passed (897) ``` - Randomized normalization fuzz, 2,000 seeds (3 peers, 40% of edits written without the normalization, peers typing into the same blocks, partial delivery): 490 sessions copied or lost text: 102 sessions without a nested line (101 with a copied block, 1 with a lost token) and 388 with one (a heading a peer wrote inside a list item: 387 copied, 2 lost). - `Fuzz.test.ts` / the fuzz utilities: a token a peer moves into a table, box or column counts as lost by delete wins when another peer made a removal, exactly like a token typed there. Duplicates are not excused. - Block id integration (BlockIdExtension on this change), moves fuzz, 2,000 + 500 gc seeds: 15 + 3 seeds with duplicated text (joins written as a copy, lines that span ranges moved as a delete and a re-insert). - This revision's fixes, against the previous revision of this change (a record left inside a line by concurrent edits: a unit written after the block it shows split the line, and a moved line left its text before the record behind; a heading written inside a list item stored as its own node): ``` $ npx vitest --project unit --no-watch Moves.test -t 'a record left inside a line' × a block shown from inside a joined line ‖ a new line right after it (4 of 4) + "@lexical/y self-check: line 81: text \"M0 abcNEW\" != \"NEW\"; ..." × a line typed into after a removal, shown around a record, moved (4 of 4) + "@lexical/y self-check: line 133: text \"M5 pqr\" != \"XM5 pqr\"; ..." Tests 8 failed | 234 skipped (242) $ npx vitest --project unit --no-watch NormalizationConvergence.test × a line written inside a line is stored as lines (48 of 60) × a heading written inside a list item ‖ typing in the heading (12 of 12) × fuzz: seeds 405, 435, 446, 899, 937, 1078, 1388, 1507, 1683, 1820 Tests 70 failed | 665 passed (735) ``` The normalization fuzz at 2,000 seeds copied text in 8 sessions and lost it in 2, all with a heading written inside a list item. The block id moves fuzz with undo and redo off failed 2 of 2,000 seeds (162: a self-check mismatch after a move; 741: a self-check mismatch and lost text after a new line was written next to a moved block). Enter and Backspace in a 10,000 paragraph document without moves took 71.2 and 71.5 ms against 67.0 and 66.8 ms on #9400 (3 alternating runs, +6%). - A move at 10k blocks with 100 earlier moves on #9400 without this change: #9400 writes a move as a delete and a re-insert, 78 ms end to end with 100 earlier moves at 10,000 blocks (its undo writes 131 B). - Many moves, before this revision's caching (1,000 blocks, gc on): at 10,000 random moves (1,000 live records) a local move took 347 ms, a remote read of it 1,049 ms and a load 647 ms, against 5.1, 3.6 and 27 ms on #9400; at 1,000 moves (634 live records), 24.5, 16.1 and 400 ms. ``` $ npx vitest --project unit --no-watch Moves.test Races.test Tests 341 passed (341) $ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs Test Files 55 passed (55) Tests 2726 passed | 4 expected fail | 2 skipped (2732) $ NORMALIZE_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch NormalizationConvergence.test Tests 4973 passed (4973) # 2,000 + 2,000 fuzz seeds, matrix 864 $ NORMALIZE_FUZZ_SEEDS=10000 npx vitest --project unit --no-watch NormalizationConvergence.test -t fuzz Tests 20000 passed # 10,000 + 10,000 fuzz seeds, on the top of the stack: # 0 copies, 0 losses; 434 + 26 sessions healed a remote # self-check mismatch by a re-read $ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \ npx vitest --project unit --no-watch Fuzz.test Tests 203 passed (203) ``` Re-run on this revision (main with the final node structure, #9452, and the updated #9400): the commands above; the moves fuzz at 2,000 + 500 gc seeds through the same counting harness as before: 26 and 7 seeds with lost or duplicated text, the same seeds as on the previous base, and 1,997 of 2,000 and 498 of 500 sessions write byte-identical updates (the other 3 + 2 differ where main's normalization now runs in a local update); the block id integration (moves fuzz, 2,000 + 500 gc: duplicated text on 882 and 1993 only, as before; the BlockIdExtension fuzz, 2,000 seeds, passes); and the collab Y e2e suite in Chromium (26/26) and Firefox (23 passed, 3 Chromium-only skips). From the previous base and not re-run: the 25,000 + 5,000 gc moves fuzz, the differential, the scripted byte-identity session, the block id run with undo and redo off, the playground drag spec, and the perf and many-moves tables below. - `Moves.test.ts` (249 tests, most in 4 orders) covers: - move ‖ type (inside, start and end), move ‖ move of the same block, neighbour moves, move ‖ delete, move ‖ retype, move ‖ bold, move ‖ Enter; - every join and split ‖ move combination: join ‖ join (Backspace, Delete, both, a range across a moved line), join ‖ split, join ‖ typing, join ‖ move, split ‖ move, undo of a join, a join ‖ an undo that restores a line inside the joined range; - new: lines that span ranges moved (a line split after a join, alone, ‖ typing in it and ‖ another move), a line another zone interrupts moved ‖ typing in both parts and joined ‖ typing and ‖ the same join, and a line that ends inside a joined range moved and then typed in, a block shown from inside a joined line ‖ a new line right after it, and a line typed into after a removal, shown around a record, then moved (each checks that the result is exactly the writer's intent); - list item moves (up, between lists, ‖ indent), whole-list moves ‖ add item, table row ‖ type and column ‖ type, container ‖ type, block decorator; - undo, redo, a second move, delete of a moved block, caret mapping, the layout bump, no record for documents that never move, and reads that stay incremental. - new: cached ownership, compared with ownership built fresh from the document after every step, across undo and redo with a peer typing, records that arrive out of order, a record whose anchors arrive late, text anchors split by typing (with and without gc), anchors merged by gc, and a moved block deleted with its old neighbour under gc. Taking out the anchor check fails them. - `NormalizationConvergence.test.ts`: the 3-peer matrix (18 violations × 8 delivery schedules × 6 id orders) passes 864/864; new lift tests (a block lifted out of the middle of a line ‖ typing next to it and in it, two blocks written at the end of one line by two peers and lifted by a third, a heading written inside a list item ‖ typing in it, a block put inside such a heading and lifted from other surroundings; 6 id orders × 2 deliveries each) check the text, the stored node (`u`, no copy, no `i:heading`) and the layout bump. The randomized fuzz fails on any copied or lost token, in every session, and always runs the seeds that failed during this work. A second randomized fuzz adds edits that write plain paragraphs into quotes and list items (joined into them as lines by the normalization) and new quotes, starting from a document with a quote and a numbered list. Both pass at 2,000 and 10,000 seeds each (0 copies, 0 losses). - Fuzz with block moves (the whole stack): 2,000 + 500 gc and 25,000 + 5,000 gc seeds, 0 absolute findings (divergence, exceptions, fragments, self-check, fresh readers). The fuzz now counts a block moved into a container a peer removed as delete wins, as it already did for text typed into one. Seeds with lost or duplicated text: 26 of 2,000 (1.3%; 69 before that accounting change), 7 of 500 gc (20 before), 278 of 25,000 (1.1%; 767 before) and 52 of 5,000 gc (157 before). All of them are documented limits: two peers moving the same block when one moves it into another container (shown twice), a move into another container racing a move of its container or an undo of a removal (shown twice), text typed into a block a list conversion lifts, and joins written as a copy. `Fuzz.test.ts` at 2,000 + 500 seeds with and without moves passes, including a regression seed (a comment over a line joined with a line of two pieces, then an undo). Differential against v2, 2,000 + 500 gc: 0 absolute findings, 5 + 1 seeds worse than v2. - This revision writes exactly what the previous one wrote. Every update of a scripted two-peer session (900 steps of moves, typing, Enter, joins, removals, undo and redo, with and without gc), of the moves fuzz (2,000 + 2,000 gc and 25,000 + 5,000 gc seeds, every peer's updates hashed per seed) and of 10,000 random moves is byte-identical before and after, and the fuzz findings, the differential (the same 5 + 1 seeds) and the block id runs below are unchanged. - Block id integration (BlockIdExtension on this stack): the moves fuzz, 2,000 + 500 gc seeds, has 0 divergence, 0 self-check warnings and 0 lost text; 2 + 0 seeds show duplicated text (882, 1993): in both, two peers remove the same text and both undo the removal, and each undo restores its own copy, which Yjs does with plain `Y.Text` too (no move is involved). With undo and redo off, 2,000 + 500 seeds have no finding (162 and 741 failed before). The BlockIdExtension fuzz, 2,000 seeds, passes. - Many moves (1,000 blocks; ms: local move, remote read of it, load; mean of the last 50 moves, median of 3 loads; #9400 / before / after): | Moves, gc | Live records | Local move | Remote read | Load | | --- | --- | --- | --- | --- | | 100 random, on | 97 | 4.8 / 8.1 / 8.3 | 2.8 / 3.7 / 3.7 | 20 / 69 / 24 | | 1,000 random, on | 634 | 4.5 / 24.5 / 17.2 | 3.1 / 16.1 / 8.0 | 20 / 400 / 29 | | 10,000 random, on | 1,000 | 5.1 / 347 / 33.5 | 3.6 / 1,049 / 26.9 | 27 / 647 / 46 | | 10,000 random, off | 1,000 | 6.7 / 357 / 35.0 | 5.5 / 1,086 / 28.8 | 49 / 783 / 135 | | 10,000 back and forth, on | 1 | 5.3 / 10.0 / 10.2 | 3.0 / 8.6 / 8.7 | 22 / 28 / 26 | | 10,000 back and forth, off | 1 | 7.6 / 11.2 / 11.1 | 4.3 / 10.1 / 10.2 | 52 / 128 / 122 | A keystroke in a moved block stays at 2.2 to 4.6 ms (#9400: 2.2 to 3.0). Sizes are unchanged (235 KB after 10,000 random moves with gc, 157 KB on #9400). The remaining cost grows with the container's items, deleted records included, which Yjs keeps in the sequence. - Perf at 10,000 blocks (end to end, shared machine, #9400 → the top of the stack): Enter and Backspace in a document without moves, median of the per-round ratio over 6 alternating rounds, +0.0 to +0.5% at the top of the stack and -1.8 to +1.3% with this change alone (+6% for the previous revision); keystroke 38.7 → 38.6 ms (list item 47.9 → 46.3), load 195 → 193 ms, size, 10k-edit growth and bytes per edit identical; a move 97 → 124 ms (131 → 106 B), its undo 69 → 73 ms (131 → 11 B). - Playground (`?isCollab=true&useCollabY=true`, the stack's playground mode, a scratch spec): drag a block while the other tab types in it, a list, a list item, a table row, undo, and the same block dragged twice: Chromium 21/21 (3 repeats), Firefox 7/7, WebKit 7/7; the collab Y e2e suite passes in all three (26/26, 23/23 + 3 Chromium-only IME skips). - On this commit: `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `pnpm run flow` (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking test (368 passed), `pnpm run build-prod` and the built tree-shaking test (284 passed).
zurfyx
force-pushed
the
zurfyx/collab-y14-block-markers
branch
from
October 26, 2026 22:04
48857a8 to
b15e04b
Compare
Merged
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #9400 (
@lexical/y, the Yjs 14 binding).Today
@lexical/ygives a server nothing beyond the main entry'sDEFAULT_ROOT_NAMEandLAYOUT_VERSION. Everything a server needs to seed,edit or read a stored document is left to each integration: bind a headless
editor to a Yjs state, wait for the layout record, run one edit, collect the
updates it writes (including the ones opening the document writes, which the
edit can build on), merge them, check their roots, and dispose of the
editor, the binding and the document without leaking listeners.
This adds a new entry,
@lexical/y/headless, with three plain functions(all
@experimental):seedYState(config, $build)writes$build's content into an empty rootthrough the binding's
initialize(): a client id derived from the content(53 bits under
'uint53', 32 under'uint32'), outside any undo history.Identical content gives identical bytes, so two seeds merge into one copy,
and so do a seed and a client's initialization of the same content in
the same configuration without
BlockIdExtension(with it, a clientnames the blocks of its initial content by position and a seed names
them with
generateId, so the two merge only when the content gives itsblocks fixed ids; content with random parts, such as drawn block ids, is
not identical either). It takes no writer (below): the client id derived
from the content is what makes identical seeds merge.
The state is garbage collected, as clients store a document, and holds
only the layout root, so it is also how a converter moves
a
@lexical/yjsdocument: seed the content an editor read from it andmerge the seed into the stored document, next to the old root. It is the
one documented way to seed or convert a document.
editYState(state, config, $edit, {writer, allowedRoots, transact, tag})runs
$editin one discrete update on the document atstate, writtenas
writer(required, see Writers below), commits theupdates it made listeners schedule (an extension giving new blocks ids;
without this they were lost when the editor was disposed), and returns
{update, state, warnings, clientID}: one merged update of everythingwritten (or
nullwhen nothing changed), the state with it applied,garbage collected as clients and Yjs servers store a document (also when
nothing changed), and the client id the edit wrote under. The update is
refused unless every root it writes to is allowed (default: the layout
root);
transact(doc)writes other shared types (an activity log) intothe same update (it only writes: an update it applies to the document is
refused,
'imported-items', as its items would be returned as theedit's). A
tagwith which the binding writes nothing(
COLLABORATION_TAG,SKIP_COLLAB_TAG) is refused before the edit runs(
'ignored-tag'), rather than returningupdate: nullas if the edithad changed nothing. Whatever
$editthrows is rethrown as it is, afterLexical has restored the previous state, and nothing is written:
transactdoes not run. That holds for any thrown value, not only anErrorof the server's own realm: Lexical passes only those to theeditor's
onErrorand drops anything else (a string, a plain object, anErrorfrom another realm such as avmcontext), which would otherwisemake a failed edit look like one that changed nothing. The helpers catch
the value inside the update themselves.
createYWriter(author)makes the writereditYStaterequires: who theserver's edits are by, and the client ids it writes under.
createYDoc(state?)returns aY.Docfor a relay or a server that loadsa stored state: Yjs's format cleanup turned off (
cleanupFormatting = false), as on the clients, withstateapplied when given.readYState(state, config, $read)returns what$readreads. Whatopening the document writes (a value an extension assigns on open) is
read but not stored, so such values can differ between reads; the docs
tell servers to store the update of a no-op
editYStateonce first.BlockIdExtensionassigns nothing on open: a block stored without an id,or with an id an earlier block stores or derives, reads the id [lexical][lexical-devtools][lexical-extension][lexical-list][lexical-website][lexical-y][lexical-yjs] Feature: @lexical/y, an experimental Yjs 14 collaboration binding #9400
derives from its Yjs identity, the same in every read, and the next edit
of that block stores it.
YHeadlessErrorwith acode:'not-initialized','read-only'(anewer layout, unknown node types, or a named slot the document cannot
store, which the binding refuses to write:
seedYStateandeditYStatethen throw instead of returning a state without it; the error's
warningsare the binding's typed warnings that say why, and its messageis short),
'foreign-roots','imported-items','ignored-tag'.configis the editor (extensions, built withbuildEditorFromExtensions,or
nodes), the root name,clientIDRange('uint32'for yrs before0.28),
onWarnandselfCheck.Writers. Opening a new
Y.Docfor each call meant every server edit wroteunder a new random client id, and a document keeps every client id that
ever wrote to it: in its state vector, which every sync sends, and in the
bookkeeping Yjs does each time it loads the document. After 3,000
one-character edits through
editYState, a document that one client wouldstore in 3,763 bytes with a 21-byte state vector was 96,364 bytes with a
26,828-byte state vector and 3,001 client ids, and the next call took 25 ms
against 1.1 ms.
editYStatenow requireswriter:createYWriter(author), created once per agent orintegration per process: it continues one client id per document it
edits, so the same 3,000 edits leave 2 client ids (the seed's and the
writer's), 3,763 bytes and a 21-byte state vector, at a flat 1 to 1.5 ms
per call;
null: a new anonymous client id for this edit alone (the previousbehaviour, now a decision the call makes).
The writer is required in the type (
writer: YWriter | nullin a requiredoptions object), so a call that does not decide does not compile, and a
caller without types (JavaScript, a cast) gets a
TypeErrorthat says whatto pass.
YWriteris branded: its phantom key is namedcreatedByCreateYWriter, so tsc's message for a writer written by handreads as the fix. In Flow it is opaque.
The writer carries an author, not a client id. Two writes under one client
id from different states give two different items the same id, and Yjs
cannot tell them apart: each peer keeps the one it received first, and the
document diverges with no error (a test shows it). A client id the caller
chooses is exactly the value that two replicas, a restart overlapping an
instance that is still draining, or an edit run on an older read would
share, with nothing to notice it. So a writer never takes a client id: it
draws its own at random, as every Yjs client does (in the config's
clientIDRange, and never one a call in progress writes under), andcontinues one only from its tip, on a state whose clock for that id is the
clock its last returned update under it reached, and never in a call made
while another call writes under it. Every write under an id then extends the one chain of
writes under it, which nothing else writes to, across documents too: each
document gets an id of its own, so two documents seeded from the same
template and edited the same way never share one. On any other state the
edit is written under a new client id. When the state holds the writer's
id short of its tip, or a call in progress writes under it, a
'@lexical/y/writer-new-client-id'warning (WRITER_NEW_CLIENT_ID_WARNING)names the fix and its
data.reasonsays why:'stale-state'(the state was read before the writer's last update there,or that update was never stored),
'busy'(a call made from inside anothercall with the writer),
'range'(the writer's id does not fit'uint32')or
'foreign-writes'(something else wrote under the writer's id; thewriter never uses it again). A state that holds none of the writer's ids
gets a new one without a warning: the writer cannot tell it from another
document. An edit that throws or is refused does not move the writer on. A
writer remembers up to 10,000 client ids (about one per document it edits);
a document whose id it forgot gets a new one on its next edit. The author
is not written into documents:
writer.authorand theresult's
clientIDfeed the app's attribution, either a registry of clientids written with
transact(wheredoc.clientIDis the edit's client id)or Yjs 14 attributions built from the update
(
createContentIdsFromUpdate,createContentMapFromContentIds). Theresult's
clientIDis the id the edit wrote under, read beforetransactruns, and the update holds only the edit's own items:
transactapplyinganother update refuses the edit (
'imported-items'). An app credits a seedby the client ids in its state vector: the content-derived one, plus the
temporary document's own when a listener writes once the content is read.
Warnings are
LexicalWarnings (fromlexical): the headless editor's ownonWarncollects every warning into the result'swarnings: LexicalWarning[]and passes each to the optionalconfig.onWarntoo(default:
console.warnoutside production). The codes are the binding's(
'@lexical/y/unsupported-layout','@lexical/y/self-check'and the others@lexical/yexports constants for) plus three of the helpers' own, exportedfrom
@lexical/y/headless(core keeps no list of codes; the entry'sYHeadlessWarningCodetype is the union of all of them):EDITOR_WARNING('@lexical/y/editor-warning'): a warning the editorreported through its
onWarnthat is not aLexicalWarning(Lexical oran extension), wrapped with the original in
data.error;FOLLOW_UPS_EXHAUSTED_WARNING('@lexical/y/follow-ups-exhausted'): theedit's listeners kept scheduling updates; after 8 follow-up updates the
rest are not committed and are not part of the result (previously this was
silent). Once the binding writes (an edit, or the read of a seed it has
written), an update that changes content
and is made after a commit in the same task, as a listener's is, commits
at once, so Lexical's own guard stops such a listener first, reported as
an
EDITOR_WARNING;WRITER_NEW_CLIENT_ID_WARNING('@lexical/y/writer-new-client-id'): awriter could not continue its client id on the state it was given, so the
edit was written under a new one (see Writers above).
The refusals' messages name their fix:
'ignored-tag'says to remove thetag from
options.tag,'foreign-roots'namesoptions.allowedRootsandsays that it replaces the default (so the layout root goes in the list too),
or, for items whose parents are in neither the update nor the state, to pass
the complete stored state,
'imported-items'says to apply other updates tothe app's own copy and use
transactonly to write,'not-initialized'names
seedYState, and'follow-ups-exhausted'says to have the listenerwrite only what is missing (a counter or a timestamp per commit never
settles).
The headless functions never throw for a warning, because a warning must
never refuse an edit, in development or production; a
config.onWarnthatthrows does not refuse it either (its error is rethrown in a microtask). The
self-check is off unless
selfCheck: true.Stored state is compacted. Clients, y-websocket and Hocuspocus persist the
encodeStateAsUpdateof a garbage-collectedY.Doc, where deleted contentkeeps only its tombstones. The headless editor's temporary document does not
garbage collect, only so that the root check can resolve the deleted items
an update refers to; returning
mergeUpdates([state, update])from it keptevery deleted character in storage forever. The root check still runs on
that uncompacted document; the returned
state(ofeditYStateandseedYState) is then encoded from a garbage-collected copy. Theupdatesent to clients is unchanged, and there is no
gcoption (no use needsuncompacted state).
The documents that load a state (the headless editor's and the one that
compacts the returned state) do not run Yjs's format cleanup
(
cleanupFormatting = false), as the binding's clients do not. Otherwisethe returned state lost format items that the clients keep (Yjs deletes the
format items around deleted text when it applies a remote update), so it
was not
statewithupdateapplied: once someone typed there, the storeddocument read differently from the clients, and a client that later synced
with it changed the formatting of what that user typed. A relay or server
that loads a stored state into a
Docof its own needs the same, and thatrule was docs only (
doc.cleanupFormatting = falseiny.md): a relay thatmissed it stored a document that read differently from the clients.
createYDoc(state)now makes such a document (compactStateuses it too),and the docs' relay sample (
y.mdServers,y-server.md) and conversionsample use it.
The headless editor configures
BlockIdExtensionthe wayYCollabExtensionconfigures it on the clients (repairTransforms: false,declared as a peer dependency), so the update that names blocks runs no
transforms on the server either.
Each call releases its editor and document before it returns. Before, a
synchronous loop of calls held every document it opened until it yielded:
Lexical keeps an editor until a commit it scheduled in a microtask runs (the
binding's start schedules one), and the editor kept the document through
the scope of its error handler and through the stack of an abort reason
created when it is disposed. Now the handlers live in a scope of their
own,
disposeclears what it releases, and the disposed editor is left withan empty paragraph. (#9400's binding makes the microtask that clears its
"committed in this task" flag outside its update listener, so that
microtask does not keep a disposed binding and its document either.) 20
synchronous reads and 20 edits of a 1,000-paragraph document went from +35
MB and +71 MB of heap to +2 and +3 MB.
The server API is plain functions only. The headless editor itself
(
openHeadlessYEditor,OpenedHeadlessYEditor) stays internal: the threefunctions cover seeding, editing and reading, and nothing public needs a
handle (
Source.test.tspins the entry's exports toseedYState,editYState,readYState,createYWriter,createYDoc,YHeadlessErrorand the threewarning codes
EDITOR_WARNING,FOLLOW_UPS_EXHAUSTED_WARNINGandWRITER_NEW_CLIENT_ID_WARNING). Exposing it later isadditive. The root check of
editYStateuses an internal helper (the rootsan update writes to); there is no
@lexical/y/serverentry.Opening a document releases everything it registered when it fails: the
editor and its extensions, the binding and the temporary document are
disposed when the state does not decode (bytes that are not a Yjs update),
the binding throws, or the document is read only here.
A
'read-only'YHeadlessErrorcarries the binding's warnings that say whyas data,
error.warnings: readonly YWarning[](#9400's typed warnings:narrow on
code, then ondata.reason), and a short message with nopackage name (
the document is read only here, orthe change was not writtenwhen the binding refused the edit's change). It used to start with@lexical/y:and embed the warnings' messages, which an app could only showor parse. The other codes' errors have no warnings (
warningsis empty).YBinding.flushPending(), which the helpers call to run the binding'spending updates at once, is
privatein its type (a type-only modifier), sothe published declarations do not offer it (
private flushPending;in thebuilt
Binding.d.ts); the helpers reach it through an internal interface.Nothing changes at run time.
The new entry imports
@lexical/yas an external sibling, so the binding isnot bundled twice. The package's
package.jsonkeeps nomainormodule(#9400 sets neither), like the other multi-entry packages:
pnpm run update-versionrewrites a package that hasmainto one export,which would drop
./headless. Flow libdefflow/LexicalYHeadless.js.flow;.flowconfigand the tsconfig paths areregenerated (
update-flowconfig,update-tsconfig).Docs: a website page, Collaboration > Server-side editing with
@lexical/y(the API, errors and warnings, and the server patterns: storewhat opening writes, edits by agents and tools, one writer per document,
converting a
@lexical/yjsdocument withseedYState), linked from the@lexical/ypage, whoseservers section covers old clients (they write other roots, so no check is
needed) and yrs compatibility. The
@lexical/ypage and the README point toseedYStatefor seeding and conversion, and the page's "Changing the layoutand migrating" section (which replaces "Upgrading from
@lexical/yjs")explains the frozen wire format, what keeps the layout and what bumps
LAYOUT_VERSION, field changes, and the steps (with a diagram and a sample)to reseed a room from Lexical JSON, an
@lexical/yroom or a@lexical/yjsroom. The page's layout text follows #9400's layout record: a room records
the versions it needs (
lexical-y:<n>: true, a record that only grows), anda newer
@lexical/yadds its version only when it first writes somethingthat needs it. The server page says that stored state is compacted like
the clients' copies and that the root check runs on the edit's own
uncompacted copy, and the code says why the temporary document does not
garbage collect. "Edits by agents and tools" applies #9400's "Edits made by
code (agents, tools)" section of the
@lexical/ypage toeditYState:edit text in place (
spliceText) rather than replacing blocks, and run theedit on the state the agent read, then merge the returned
updateinto thelatest stored state (not the returned
state). The@lexical/ypage'ssection links to it. The server page also covers the
'ignored-tag'refusal, the states returned when nothing changed (compacted too), the
format cleanup the helpers turn off (and that a server loading a stored
state into a
Docof its own should too), and that each call releases itseditor and document. Its Writers section covers
createYWriter,nulland what it costs, the reasons for a new client id with the fix for each,
attribution (a registry of client ids, or Yjs attributions built from the
update) and seeds; it also says that
allowedRootsreplaces the default,and that with
BlockIdExtensiona seed and a client's initialization ofthe same content do not merge unless the blocks have fixed ids. "One writer
per document" is now "One edit at a time per document", and the samples
pass a writer. The
@lexical/ypage's limits gain "Client ids add up".lexicaland@lexical/yjsare untouched.New tests:
Headless.test.ts(round trip; identical seeds merge; a seedholding a list item with text beside its nested list is stored normalized
(the nested list in an item of its own) and merges with a client's
initialization of the same content into one copy; no-op
edits; a throwing edit writes nothing; anything an edit throws (a string,
a plain object, an
Errorfrom another realm, anError) is rethrown asthe same value and
transactdoes not run; a state that is not a Yjsupdate releases what opening registered (an extension's registration is
released and the temporary document destroyed, for
editYState,readYStateand the internal handle); a server edit merging with twooffline peers' edits, delivered before and after the peers sync; an edit to
a line a peer is typing in, replacing a word and turning the line into a
heading, keeps the peer's text; a foreign root is refused and an allowed
one goes through;
'uint32'keeps every struct's client id in 32 bits; anewer layout is refused by every entry point with the binding's reason and
an
'unsupported-layout'warning (the document recordslexical-y:2); the stored state is garbage collected(the text an edit deleted is not in it, though it is in
mergeUpdates([state, update]), and a garbage-collected document encodesit unchanged) while the update is not; an empty state is
'not-initialized';after dispose, the editor and the document (including the ones that compact
the returned states) have exactly the listeners a bare editor and a bare
document have; with an extension that gives blocks
random ids from an update listener, an edit's update includes the new
block's id, a document stored without ids reads different ids each time
until the update of a no-op edit is stored, and then reads agree; warnings
are structured, reported, returned and do not refuse the edit, also with
NODE_ENV=production, and go toconsole.warnwithoutonWarn; a warningthat is not a
LexicalWarningis wrapped and aLexicalWarningpassedthrough; an
onWarnthat throws does not refuse the edit; a listenerthat never stops scheduling updates gives
'follow-ups-exhausted'whenseeding (once for opening, once for the content), then, once the seed is
written and read back, Lexical's own guard (an
EDITOR_WARNING); whenediting, the binding
writes, so each update the listener schedules after a commit commits at once
and Lexical's own guard stops the
listener (an
EDITOR_WARNING, "endlessly enqueueing", once for opening andonce for the edit), while the edit still goes through; whatever the
binding still has to do after an edit (an item added at a list's front) is
done before the helper returns, and nothing commits or writes after it; the
returned state keeps the format items the clients keep (a peer bolds text
another deletes; after a server edit elsewhere, the stored state with what
a peer then types reads as the clients do; both client id orders); the
state of an edit with no change is compacted too; an edit tagged
COLLABORATION_TAGorSKIP_COLLAB_TAGis refused before it runs; theheadless editor's
BlockIdExtensionhasrepairTransforms: false, as aclient's, so seeding and editing with it write without an
'unsupported-config'warning; 20 synchronous reads and 20 edits of a 1,000-paragraph documentleave less than 10 MB of heap behind; a seed of an
old editor's content merged into a document whose
@lexical/yjsroot hascontent converts it and leaves the old root as it was),
HeadlessScale.test.ts(10,000 paragraphs),HeadlessSlots.test.ts(named slots: a seed keeps them and
readYStatereads them; an edit in aslot merges with a client typing in the same slot; an edit that adds,
replaces and removes slots; block ids inside slots stored by the seed; a
slot on a line refused by
editYStateand byseedYStatewith'read-only'and the'unsupported-slots'warning), and relay round trips inYrsCompat.test.ts(seed, a peer typing, a server edit and a reconnectthrough ywasm 0.23.5 and 0.28 relays; with 53-bit server ids a 0.23 relay
makes a peer that also got the update directly show it twice; a writer
keeps its 32-bit client id over three edits through either relay).
HeadlessWriter.test.ts: a call without a writer is refused by the type(
@ts-expect-errorfor no options,{},undefined, a hand-writtenwriter and a number) and, for callers without types, at run time with the
fix in the message; 3,000 edits with a writer keep one client id, a state
as small as one client's and a flat per-call cost;
writer: nullgiveseach edit a new client id, and its update inserts under the result's
clientID; a writer continues only on a state that holds its last update,and on an older state writes under a new id with a
'stale-state'warning, every delivery order converging (a control shows the same edits
forced under one id diverging); a call made inside another call with the
same writer gets its own id (
'busy'), also when its random draw repeatsthe new id the outer call is writing under; an update applied inside
transactrefuses the edit ('imported-items') and leaves the writer as itwas; a writer that continues its id writes new segment keys (two adjacent
token nodes it adds in two edits stay apart); one writer keeps one id per
document, also for two documents seeded from the same template; an edit
that throws or is refused (foreign roots, not initialized, read only) does
not move the writer on; an id drawn and never written is reused; a
'uint32'config gets 32-bit ids ('range'); writes under a writer's idthat it did not make stop it using that id (
'foreign-writes'); a writerremembers a bounded number of ids; attribution: the update inserts under
the result's
clientIDalone, a registry entry written withtransactcredits it, and Yjs 14 attributions render the edited text as the writer's
author, built from the registry or from the update alone; a seed holds
one client id, the same for the same content, and a second one when a
listener sets a value once the content is read.
createYDoc: a relaydocument keeps the format items the clients keep where a plain
Y.Docdrops them (both client id orders), and what it stores reads as the clients
do once someone types bold text there; without a state it is empty, and a
state that does not load throws. A read-only refusal carries the binding's
typed warning (
error.warnings, narrowed oncodeanddata.reason) anda short message, also for a refused slot;
Source.test.tschecks thatYBinding's type does not offerflushPending. The Flow test rejects thesame six calls. The memory test runs edits with a writer as well (with a
30 s limit: its 60 calls on a 1,000-paragraph document take about 2 s, and
went past vitest's default 5 s when the whole suite ran at once), and the
refusal tests check that each message names its fix.
The garbage-collected state, against the previous revision of this change
(
statefrommergeUpdates([state, update])of the non-collectingdocument), with this revision's tests:
The two fixes of the previous review round (release on a failed open; any
thrown value is rethrown and nothing is written), against the revision
before it of
HeadlessEditor.ts, with this revision's tests:The fixes of the previous revision (the returned state's format items, the state
of an edit with no change, refused tags, the block id configuration,
releasing what each call opened), against the previous revision of
headless.tsandHeadlessEditor.ts, with this revision's tests:The writer and the messages of this revision, against the previous
revision of
headless.tsandHeadlessEditor.ts(and noWriter.ts),with this revision's tests:
The typed read-only error,
createYDocand the hiddenflushPendingofthis revision, against the previous revision of
headless.ts,HeadlessEditor.tsandBinding.ts(on #9400 round 37), with thisrevision's tests:
3,000 one-character edits on a 20-line seed, each on the state the last
one returned (Node 24, development build, self-check off; the last column
is the median of 21 more calls on the final state):
(The four existing YrsCompat tests also pass.) Scale, Node 24, development
build (self-check off, the default), 10,000 paragraphs vs 1,000, on this
commit, two runs on a loaded host (
disposeMsnow includes dropping theeditor's content):
Stored state, before and after the compaction (measured on the previous
base of this PR; a reviewer's re-measure on this base, 100 rewrites of one
paragraph from 316 bytes, gave 23,127 / 23,136 merged and 4,208 / 4,194
compacted; a scratch harness, not committed:
uint32ids, sources under vitest). An agent rewrites oneparagraph of a two-paragraph document 100 times through
editYState, eachtime with a different ~200-character text; the returned
stateis storedand passed to the next edit. Two runs each:
About 234 B per rewrite before (the deleted text stays) and 37 B after (its
tombstones). Extra edit time:
editYStaterewriting the middle paragraph ofdocuments of 1,000 and 10,000 paragraphs, median of the last 7 of 10 edits,
two runs each:
That is about +3 ms at 1,000 paragraphs and +20 ms (8%) at 10,000: one
applyUpdateandencodeStateAsUpdateof the state on a collectingdocument.
editMsiseditYStateend to end (open, one edit, root check, merge,dispose);
openMs/writeMs/disposeMsare the phases through an internalhandle.
Property test (a reviewer's scratch harness, not committed): 2–3 human
peers on
YCollabExtensionwith the self-check on, typing, deleting,splitting, joining, toggling headings and lists, bolding, commenting and
undoing through a relay that delays, batches, reorders and drops them
offline, while agents run
editYStateon stale stored states (0–50 stepsold) and the returned update is merged into the latest stored state; 60
steps per session, 2,000 sessions per mode. 0 sessions in which the binding
diverged, in each mode: plain, block ids, comments (
MarkStateExtension),comments with block ids, and storing the returned
statewhen the agentedited the latest state (one writer), plain and with comments. The last two
had 2 + 5 sessions whose stored state read differently from the clients
before the format cleanup fix (seeds 437, 901, 659, 1359, 1379, 1633,
1916); all 7 pass now. Each mode still has 1–3 sessions in which one
client's
Dockeeps pending structs whose dependencies it already holds (a@y/y14.0.0-rc.29 issue reproduced with Yjs alone, not the binding; theother clients and the stored state agree).
Also run, on this commit:
npx vitest --project unit packages/lexical-y packages/lexical-yjs(148 files, 4,846 tests pass, 16 expected failures, 2skipped);
pnpm run test-unitcompared test by test with #9400 (0 failed,0 changed, 83 added:
Headless.test.ts32,HeadlessWriter.test.ts16,build.test.ts15,YrsCompat.test.ts8,HeadlessSlots.test.ts6,treeShakingSource.test.ts4,HeadlessScale.test.ts1,Source.test.ts1; one #9400 test no longer runs by design: the wwwentry stub audit in
build.test.tsonly checks packages with a singleexport, and
@lexical/ynow has two; the website'sgenerated
stackblitz.test.tsaudits are left out of the comparison);pnpm run tsc,tsc-test,tsc-scripts,tsc-website,tsc-extension,pnpm run flow(0 errors),pnpm run lint,pnpm run prettier,pnpm run build-prodand the built tree-shaking test(286 passed), the source tree-shaking test (372 passed;
@lexical/y (packages/lexical-y/src/headless.ts),internal/HeadlessEditor.tsandinternal/Writer.tsretain nothing), andpnpm run build(
LexicalYHeadless.dev.jsimports@lexical/y,@y/y,lexicaland@lexical/extension/LexicalBuilderas externals), and the website buildwith TypeDoc and the broken link check (
pnpm run build-docs).Not exercised: real browsers, a real network relay (the relays are ywasm
documents in the test process), production builds' timings, and the preview
builds of this commit (pkg.pr.new publishes them when it is pushed).