Skip to content

[lexical-website][lexical-y] Feature: Store set-valued NodeState one format per member - #9439

Merged
zurfyx merged 1 commit into
mainfrom
zurfyx/collab-y-mark-set
Oct 28, 2026
Merged

zurfyx merged 1 commit into
mainfrom
zurfyx/collab-y-mark-set

Conversation

@zurfyx

@zurfyx zurfyx commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Stacked on #9438 (the @lexical/y stack: #9400, #9437, #9438).
Builds on #9380 (MarkStateExtension and arraySetValue, set-valued
NodeState), which is on main.

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: arraySetValue(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 arraySetValue
    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 under the set's
    key, unless a StateConfig uses the entry key itself or the set's key is a
    StateConfig that does not hold a set. For a set-valued state the reader
    knows, the state's own parse turns the array into its canonical value (a
    frozen array, sorted and without duplicates, the same value a local
    $setState or a JSON load gives). For one it does not know yet, the
    sorted array is kept as an unknown NodeState value, which the writer
    stores one entry per member again, as it does any string array under
    that key on a node of that type (the reader notes the key per node type,
    so a JSON copy of the node's state is stored the same way): an unchanged
    set writes nothing, and a changed one writes only the members it adds or
    removes, never the whole set. So such a peer never collapses the
    members; and since Lexical parses an unknown value when a state is first
    used, a client that starts using the state after it read the document (the
    usual way: createState, then $getState/$setState, with nothing
    registered) reads the set, and its writes keep the members. The state
    needs no registration. 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 set-valued state whose own key contains U+001F is stored whole.
    A set whose key is the empty string is stored and read like any other
    (s:\u001f<member>).
  • Reserved names. A member entry's name is the set's key, U+001F and the
    member, so another state named that way ('tags\u001fx' next to a set
    'tags') would be stored under the same attribute as member x of tags.
    The binding refuses such a StateConfig, whether or not it holds a value,
    whenever it writes that state or the set on a node for which both are
    known (used on it or registered for its type): an invariant
    (devInvariant) in development, a warning in production, and the set is
    then stored whole, as one value, so no reader drops a member. Only
    StateConfigs are refused: an entry no StateConfig knows is a set's member
    or another client's data, and is written back as it is. A reader keeps
    an entry as an ordinary key whenever it knows a state of the entry's own
    name, so a document written by a client that does not know the set (and
    so does not refuse) still reads correctly.
  • Every member round-trips. Yjs stores format and attribute names as
    UTF-8, which turns a lone surrogate into U+FFFD, so two members that
    differ only there would be read back as one. A member that holds a lone
    surrogate, or that starts with U+001F, is stored escaped:
    s:<key>\u001f\u001f followed by the member's JSON, with every
    surrogate code unit written as a \uXXXX escape (ASCII). Every other
    member is stored as itself.
  • Layout 2. Member entries are a stored shape older clients misread
    (they see s:markIds\u001fc1 as some other NodeState, and no comment),
    so they are layout 2, as the package README's layout rules require:
    LAYOUT_VERSION is 2; a new document still records lexical-y:1, and
    the transaction that writes a document's first member entry also records
    lexical-y:2 (undo keeps it). From then on, clients that only read
    layout 1 ([lexical][lexical-devtools][lexical-extension][lexical-list][lexical-website][lexical-y][lexical-yjs] Feature: @lexical/y, an experimental Yjs 14 collaboration binding #9400 to [lexical-playground] Feature: Collab Y (@lexical/y) mode in the playground, with e2e specs #9438 builds) open the document read only, with the
    @lexical/y/unsupported-layout warning, instead of editing it without
    its comments; documents that never hold a member entry stay at layout 1
    and older clients keep editing them. The planned move records ([lexical-y][lexical-website] Feature: Real block moves (move records) #9449)
    become layout 3. A client that is active and reads the version a peer
    just recorded does not read the whole document again when the record
    arrives (it changes nothing it reads or writes). The version is recorded
    in a finally inside each transaction that writes content (an edit's,
    the initial write's and the rewrite that recovers from a failed write),
    so a write that throws part way, which Yjs still commits and sends,
    carries it too; once a document records it, a transaction's inserts are
    not scanned for member entries.
  • One format family per set. The write cursor bounds the format items
    a delete leaves, and keeps a format's items at the boundaries a concurrent
    writer relies on, per format family ([lexical][lexical-devtools][lexical-extension][lexical-list][lexical-website][lexical-y][lexical-yjs] Feature: @lexical/y, an experimental Yjs 14 collaboration binding #9400's formatFamily). Here a set's
    member entries (s:<key>\u001f<member>, escaped members included) and a
    whole array an earlier build stored under s:<key> are one family, the
    set's key, so they follow the rules the whole set follows: the run a
    delete leaves keeps a bounded number of member items per set, not per
    member (a comment added to each of 60 words typed and deleted again at one
    place leaves at most 4 live items, not 2 per comment); and removing a
    member from a range that holds another member's boundary writes the
    removed member's value again there, so text a peer types before that
    boundary does not bring the member back. Removing a comment whose range
    holds another comment's start costs 51 bytes (redo 48) instead of 10.
  • Known limit: a removed member leaves an item. Removing a member from
    text that stores its set per member (resolving a comment with
    $removeMarkID) leaves one small live format item after that text (about
    30 bytes with a short comment id), which the binding cannot safely clean
    up: a collaborator writing inside that text at the same time may still
    rely on it ([lexical][lexical-devtools][lexical-extension][lexical-list][lexical-website][lexical-y][lexical-yjs] Feature: @lexical/y, an experimental Yjs 14 collaboration binding #9400's write cursor keeps the item after a format change's
    range for that writer, for any key; a set stored whole reuses it for the
    next comment there, a member's key is not written again). So the
    document grows with every member removed, not only with its content.
    Removing the same member again at the same place adds nothing, and adding
    a member and undoing it leaves nothing. The docs now recommend resolving
    a comment without removing its id: keep the id in the text, mark the
    thread resolved in the app's own store, and leave resolved ids out when
    rendering (see the MarkStateExtension option for that). Unresolving is
    then free and the document does not change. Removing the id stays
    documented as the alternative, with this cost
    (Resolving comments).
  • A reader that compares a node with what is stored does not refuse a
    state named like a member entry (refusals are for writes), so a document
    holding one, stored by a client that knows only that state, still reads
    in full on clients that know both.
  • The self-check's fresh editor gets the set-valued StateConfigs registered
    on the binding's editor, and every StateConfig whose key contains U+001F,
    so it reads the members and those ordinary keys the same way (otherwise
    every write of a set would be reported to the editor's onWarn as a
    '@lexical/y/self-check' warning, and so would an ordinary state whose
    name looks like a member entry).
  • @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
    arraySetValue state, like MarkStateExtension, and registers it for
    text the way MarkStateExtension does (in the node type's shared state
    config, with no editor update, so that the peers' identical seed is still
    a load for BlockIdExtension and gets the same ids on every peer);
    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), that
    the state needs no registration, and not to name another state with a set's key and U+001F, and the old
    "NodeState sets" limit (one value per text run) is removed, and the limit
    says that storing members is layout 2 and what older clients then do; the
    layout section says LAYOUT_VERSION is 2 and when a room records it; the
    README's wire format gets a layout 2 section (the member entries
    s:<key>\u001f<member> = true, their escaping, the empty key, the
    reserved names, and the lazy upgrade), and its layout record rule says
    "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page
    says that @lexical/y stores the ids separately, and where. The
    Comments and Annotations page gets a "Resolving comments" section: keep
    a resolved comment's id in the text and its thread's state in the app's
    store (unresolving is then free, and the document does not change), or
    remove the id with $removeMarkID and add it again to unresolve, which
    under @lexical/y leaves one live item per removal; the Yjs 14 page's
    limits get a "Removed set members" item that says the same and links
    that section. The core
    NodeState page is not changed: it only says that meta.kind === 'set'
    marks a set whose members are independent.

A peer that does not know the state exports the joined set in its JSON
("markIds": ["c1"]), which a later JSON load parses as the set.

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                      109 / 10 / 77       92 / 10 / 86
add an overlapping comment         83 / 10 / 77        196 / 45 / 190
remove one of two comments         51 / 116 / 48       113 / 144 / 113

The first comment in a document also records layout 2 (26 bytes, once per
document); without that record it is 83 / 10 / 77.

What each way of resolving a comment leaves, 200 comments on the same
words, through MarkStateExtension and YCollabExtension as an app builds
them, two clients with pinned client ids (a scratch probe, not committed;
live format items, and bytes a GC'd copy of the document grows by per
comment):

$removeMarkID (resolved by the author or the other client)   200 items, 49 B per comment (81 B with UUID ids)
the id kept in the text, resolved in the app's store          400 items (2 per comment, its range), 65 B
one comment resolved and reopened 200 times                   1 item
a comment added, then undone                                  0 items

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. Mark ids on the wire: ten ids on one text
run, among them lone high and low surrogates ('\ud800', '\ud801',
'\udc00', 'x\udbff'), a valid pair and ids starting with U+001F: every
peer and a fresh reader read them back exactly, every stored name is
well-formed, and a peer that removes '\ud800' removes only that one. A
JSON copy of a commented text node (node.updateFromJSON(JSON.parse( JSON.stringify(node.exportJSON()))) through the headless API, with
MarkStateExtension or a nodes-only config): an unchanged copy writes
nothing; a copy made while a human resolves A and adds B keeps B only
(with and without a text edit, both merge orders); a copy that adds C to a
JSON still holding A, while a human resolves A, gives C.

New packages/lexical-y/src/__tests__/unit/SetState.test.ts: a generic
arraySetValue(stringValue()) state, both client id orders: concurrent
additions (each peer adds the member the other sorts after) merge on a text
run, an inline decorator and a block decorator, stored one key per member
on each, and every peer reads back the canonical frozen array (['a', 'b']); a removal and a concurrent addition both apply; a
paragraph stores the set as one s:tags attribute (last writer wins); a
state named like a member entry of a known set ('tags\u001fx') is refused
and nothing is written, also when it is only registered and never set (the
set's write is refused); a boolean state of that name stored by a client
that does not know the set is read as itself by clients that know both, and
the whole-container self-check after a structural edit reports nothing; a
set-valued state whose key contains U+001F is stored whole (written as
['b', 'a', 'a'], read back as the frozen ['a', 'b']); a set whose key is
the empty string, with members '', 'x' and 'a\u001fb', on a text run,
a line break, an inline and a block decorator, reads back as
['', 'a\u001fb', 'x'] on every peer and on a fresh reader; members holding
lone surrogates, a valid pair and one starting with U+001F on a text run,
a line break, an inline and a block decorator read back exactly on every
peer and a fresh reader. The layout record: a set stored whole on a
paragraph leaves the document at layout 1; the update that writes the
first member entry also records lexical-y:2, which every peer then has
and undo keeps; through the headless API a seed and a text edit without
members stay at layout 1, the edit that adds a member records layout 2 in
its update, and a seed with a member records both; a write that throws
part way (the edit and the rewrite that recovers from it each write
everything, then throw), with NODE_ENV development and production, and an
initial write into a root inside another shared type that throws part way,
both send lexical-y:2 in the first update, with the member entry. A set
used without registration, both client id orders: a client that starts using the
set after it read the document reads the members, types in the tagged
text, adds a member and removes one, and every peer, the stored keys and a
fresh reader agree, with no error or warning; concurrent changes merge when
one client learned the set late; a client that never uses the set edits
the text and keeps its members, and its JSON equals the others'; the
headless API seeds such a state, reads it, adds a member and edits the text
without touching it.

Read.ts, Schema.ts and SelfCheck.ts reverted to #9438:

$ npx vitest --project unit --no-watch 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[b] test_equation[b] …' 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
 × a state named like a member entry of a set is refused
   AssertionError: expected [Function] to throw an error
 × a state named like a member entry is refused even without a value
 × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders)
 × concurrent changes merge when one client learned the set late (2 of 2 orders)
 × a client that never uses the set keeps its members (2 of 2 orders)
 Test Files  3 failed (3)
      Tests  29 failed | 46 passed (75)

This revision's fixes (members that are not well-formed UTF-16, a JSON
copy of an unknown set, and layout 2), with this revision's tests and the
previous revision of Binding.ts, Read.ts, Schema.ts and
constants.ts:

$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts
 × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader
   AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } }   # peers read '\ufffd'
 × an unchanged copy writes nothing (nodes only)
   AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null
 × an unchanged copy writes nothing (nodes only, seeded nodes only)
 × a copy does not bring back a comment a human resolved at the same time (nodes only)
 × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere)
   AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ]
 × a changed copy writes only the members it adds or removes
   AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ]
 × are read back exactly on text, a line break and stored nodes
 × the first member entry records layout 2 in its own update, and undo keeps it
   AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ]
 × the headless API records layout 2 with the first member entry only
      Tests  9 failed | 137 passed (146)

The same, on this revision (two more tests, below): Tests 148 passed (148).

#9400's regressions/Formats.test.ts with the previous revision of
Schema.ts (every key a family of its own) and of Size.test.ts's budget:

$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1)
      Tests  5 failed | 94 passed | 4 expected fail (103)

The same, on this revision: Tests 99 passed | 4 expected fail (103).

A write that throws part way, with the previous revision of Binding.ts
(which recorded the version after the write, so not when it threw):

$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way'
 × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production
 × an initial write that throws part way still sends layout 2 with the member entries it wrote
   AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ]
      Tests  2 failed | 21 skipped (23)

A layout 2 document opened by the previous commit (#9438, layout 1 only),
written here with one comment and read there with MarkStateExtension:
status: "readonly", warning '@lexical/y/unsupported-layout' (data:
{reason: 'newer', found: 2, supported: 1}; message layout 2 is newer than 1 since #9400's typed warnings) (before this revision: active, no
warning, and no comment shown).

$ npx vitest --project unit --no-watch packages/lexical-y/
 Test Files  136 passed | 2 skipped (138)
      Tests  4674 passed | 12 expected fail | 2 skipped (4688)

$ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx
 Test Files  5 passed (5)
      Tests  141 passed | 4 expected fail (145)

The 2 skipped tests (IncidentReplay.test.ts and TabLeakReplay.test.ts)
and the 12 expected failures (pinned limits in regressions/) are #9400's
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
(25 seeds per test), and the default run with one boolean key per comment:

$ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts
      Tests  100 passed (100)

$ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts
      Tests  16 passed (16)

Property test with comments (a reviewer's scratch harness, not committed:
2–3 human peers with MarkStateExtension and the self-check on, typing,
structure, bold, comments added and resolved, undo, through a delaying and
reordering relay, while agents edit stale stored states with
editYState, 60 steps per session), 2,000 sessions each: comments,
comments with block ids, and storing the returned state when the agent
edited the latest state. 0 sessions in which the binding diverged; the
last mode had 5 sessions whose stored state read differently before
which one client's Doc keeps pending structs it could apply (a @y/y
14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its
comments mode with the self-check off (2,000 sessions) and on (500
sessions) gives the same result in every session as #9438. A first
version of the layout 2 record made every peer read the whole document
again when the record arrived, which changed the result of 3 of those
2,000 sessions (text shown twice); the binding now skips that read when it
already reads the recorded version, and the 3 sessions are as on #9438.

Collab Y e2e on this commit (the development build as CI makes it, with
the binding's self-check on, collab-y-server.mjs relay, 2 workers, no
retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs
are Chromium only).

On this commit: pnpm run test-unit compared test by test with #9438 (0
failed, 0 changed, 68 added: MarkState.test.ts 41, SetState.test.ts 23,
Size.test.ts 3, and Lifecycle.test.ts's version gate test renamed from
"(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's
base eb0a28499 (0 failed, 0 missing, 0 changed, 4,882 added: 4,875 on the
previous revision, plus #9400's 3 new WarningTypes.test.ts tests and
#9437's 4 new tests (createYDoc, and that YBinding hides flushPending); the
website's generated stackblitz.test.ts audits are left out of both
comparisons), pnpm run tsc, tsc-test,
tsc-scripts, tsc-website, tsc-extension, pnpm run flow (0 errors),
pnpm run lint, pnpm run prettier, the source tree-shaking test
(372 passed), pnpm run build-prod and the built tree-shaking
test (286 passed), and the website build with TypeDoc and the
broken link check (pnpm run build-docs) all pass.

Not exercised: WebKit, and real Yjs 14 providers other than the playground
relay.

@vercel

vercel Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
lexical Ready Ready Preview Oct 28, 2026 7:44pm UTC
lexical-playground Ready Ready Preview Oct 28, 2026 7:44pm UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Oct 22, 2026
@pkg-pr-new

pkg-pr-new Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
lexical

npm i https://pkg.pr.new/facebook/lexical@9439

@lexical/a11y

npm i https://pkg.pr.new/facebook/lexical/@lexical/a11y@9439

@lexical/clipboard

npm i https://pkg.pr.new/facebook/lexical/@lexical/clipboard@9439

@lexical/code

npm i https://pkg.pr.new/facebook/lexical/@lexical/code@9439

@lexical/code-core

npm i https://pkg.pr.new/facebook/lexical/@lexical/code-core@9439

@lexical/code-prism

npm i https://pkg.pr.new/facebook/lexical/@lexical/code-prism@9439

@lexical/code-shiki

npm i https://pkg.pr.new/facebook/lexical/@lexical/code-shiki@9439

@lexical/compiler

npm i https://pkg.pr.new/facebook/lexical/@lexical/compiler@9439

@lexical/devtools-core

npm i https://pkg.pr.new/facebook/lexical/@lexical/devtools-core@9439

@lexical/dragon

npm i https://pkg.pr.new/facebook/lexical/@lexical/dragon@9439

@lexical/eslint-plugin

npm i https://pkg.pr.new/facebook/lexical/@lexical/eslint-plugin@9439

@lexical/extension

npm i https://pkg.pr.new/facebook/lexical/@lexical/extension@9439

@lexical/fast-check

npm i https://pkg.pr.new/facebook/lexical/@lexical/fast-check@9439

@lexical/file

npm i https://pkg.pr.new/facebook/lexical/@lexical/file@9439

@lexical/hashtag

npm i https://pkg.pr.new/facebook/lexical/@lexical/hashtag@9439

@lexical/headless

npm i https://pkg.pr.new/facebook/lexical/@lexical/headless@9439

@lexical/history

npm i https://pkg.pr.new/facebook/lexical/@lexical/history@9439

@lexical/html

npm i https://pkg.pr.new/facebook/lexical/@lexical/html@9439

@lexical/internal

npm i https://pkg.pr.new/facebook/lexical/@lexical/internal@9439

@lexical/link

npm i https://pkg.pr.new/facebook/lexical/@lexical/link@9439

@lexical/list

npm i https://pkg.pr.new/facebook/lexical/@lexical/list@9439

@lexical/mark

npm i https://pkg.pr.new/facebook/lexical/@lexical/mark@9439

@lexical/markdown

npm i https://pkg.pr.new/facebook/lexical/@lexical/markdown@9439

@lexical/mdast

npm i https://pkg.pr.new/facebook/lexical/@lexical/mdast@9439

@lexical/offset

npm i https://pkg.pr.new/facebook/lexical/@lexical/offset@9439

@lexical/overflow

npm i https://pkg.pr.new/facebook/lexical/@lexical/overflow@9439

@lexical/plain-text

npm i https://pkg.pr.new/facebook/lexical/@lexical/plain-text@9439

@lexical/react

npm i https://pkg.pr.new/facebook/lexical/@lexical/react@9439

@lexical/rich-text

npm i https://pkg.pr.new/facebook/lexical/@lexical/rich-text@9439

@lexical/selection

npm i https://pkg.pr.new/facebook/lexical/@lexical/selection@9439

@lexical/table

npm i https://pkg.pr.new/facebook/lexical/@lexical/table@9439

@lexical/tailwind

npm i https://pkg.pr.new/facebook/lexical/@lexical/tailwind@9439

@lexical/text

npm i https://pkg.pr.new/facebook/lexical/@lexical/text@9439

@lexical/utils

npm i https://pkg.pr.new/facebook/lexical/@lexical/utils@9439

@lexical/y

npm i https://pkg.pr.new/facebook/lexical/@lexical/y@9439

@lexical/yjs

npm i https://pkg.pr.new/facebook/lexical/@lexical/yjs@9439

commit: bec8e9d

@zurfyx
zurfyx force-pushed the zurfyx/collab-y14-block-markers branch from 777c5dc to b0b85cd Compare October 23, 2026 13:02
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-mark-set branch from 3f520c9 to a852345 Compare October 23, 2026 13:03
@zurfyx
zurfyx changed the base branch from zurfyx/collab-y14-block-markers to zurfyx/collab-y-playground October 23, 2026 13:03
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-playground branch from 4245212 to 8eeaf3e Compare October 23, 2026 14:51
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-mark-set branch from a852345 to cfd6922 Compare October 23, 2026 14:51
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-playground branch from 8eeaf3e to 739ffea Compare October 23, 2026 16:08
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-mark-set branch from cfd6922 to 4f04dcd Compare October 23, 2026 16:08
zurfyx added a commit that referenced this pull request Oct 23, 2026
## Description

Stacked on #9400 (`@lexical/y`).

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.

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.
- **Repairs lift blocks in place.** A block a peer wrote 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 (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. Peers that lift
  it at once write the same attribute and markers under a content-derived
  client id (one copy), and peers holding different surroundings keep the one
  block. 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.
- **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 is layout 1. The first move record, join
  record or lifted block upgrades it in place to layout 2: one root
  attribute, in a transaction undo never reverts, and nothing else is
  rewritten. Clients without moves then open it read only instead of
  misreading it, and the number never goes back down. `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.
- **Repairs** skip list merges in containers with records, and skip
  ragged-table repair when moved rows have row spans.
- Warnings go to the editor's `onWarn` as `LexicalWarning`s, and the code
  uses the binding's read-only getters.

**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
#65 for exploring real moves in Lexical; its v3 independently converged on
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 has a new "Wire format" section with diagrams of layout 1 (a
container's sequence and the root's layout number and storage kinds), layout
2 (a move record next to the order the editor shows, and a join record) and
the upgrade from 1 to 2, checked against a dumped document; 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). The README's wire format documents layout 2, and its
fuzz note lists the moves fuzz variables. `@lexical/y` is unreleased and
`@experimental`.

## Test plan

### Before

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 IsInline.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)
 × an instance whose isInline() flips is written again in its new form (2)
 × fuzz: normalization repairs by 3 peers with partial delivery, seed 44, 47, 51, 64, 79, 93
      Tests  60 failed | 847 passed (907)
```

- 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).

### After

```
$ npx vitest --project unit --no-watch Moves.test Races.test
      Tests  334 passed (334)
$ npx vitest --project unit --no-watch packages/lexical-y
 Test Files  52 passed (52)
      Tests  2628 passed | 2 skipped (2630)
$ NORMALIZE_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch NormalizationConvergence.test
      Tests  4972 passed (4972)     # 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
```

- `Moves.test.ts` (242 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.
- `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.
- 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.
- 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).
- `tsc`, `tsc-test`, `flow`, `eslint`, `prettier`, tree-shaking and `build`
  pass.
…format per member

Stacked on #9438 (the `@lexical/y` stack: #9400, #9437, #9438).
Builds on #9380 (`MarkStateExtension` and `arraySetValue`, set-valued
NodeState), which is on main.

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: arraySetValue(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 `arraySetValue`
  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 under the set's
  key, unless a StateConfig uses the entry key itself or the set's key is a
  StateConfig that does not hold a set. For a set-valued state the reader
  knows, the state's own parse turns the array into its canonical value (a
  frozen array, sorted and without duplicates, the same value a local
  `$setState` or a JSON load gives). For one it does not know yet, the
  sorted array is kept as an unknown NodeState value, which the writer
  stores one entry per member again, as it does any string array under
  that key on a node of that type (the reader notes the key per node type,
  so a JSON copy of the node's state is stored the same way): an unchanged
  set writes nothing, and a changed one writes only the members it adds or
  removes, never the whole set. So such a peer never collapses the
  members; and since Lexical parses an unknown value when a state is first
  used, a client that starts using the state after it read the document (the
  usual way: `createState`, then `$getState`/`$setState`, with nothing
  registered) reads the set, and its writes keep the members. The state
  needs no registration. 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 set-valued state whose own key contains U+001F is stored whole.
  A set whose key is the empty string is stored and read like any other
  (`s:\u001f<member>`).
- **Reserved names.** A member entry's name is the set's key, U+001F and the
  member, so another state named that way (`'tags\u001fx'` next to a set
  `'tags'`) would be stored under the same attribute as member `x` of `tags`.
  The binding refuses such a StateConfig, whether or not it holds a value,
  whenever it writes that state or the set on a node for which both are
  known (used on it or registered for its type): an invariant
  (`devInvariant`) in development, a warning in production, and the set is
  then stored whole, as one value, so no reader drops a member. Only
  StateConfigs are refused: an entry no StateConfig knows is a set's member
  or another client's data, and is written back as it is. A reader keeps
  an entry as an ordinary key whenever it knows a state of the entry's own
  name, so a document written by a client that does not know the set (and
  so does not refuse) still reads correctly.
- **Every member round-trips.** Yjs stores format and attribute names as
  UTF-8, which turns a lone surrogate into U+FFFD, so two members that
  differ only there would be read back as one. A member that holds a lone
  surrogate, or that starts with U+001F, is stored escaped:
  `s:<key>\u001f\u001f` followed by the member's JSON, with every
  surrogate code unit written as a `\uXXXX` escape (ASCII). Every other
  member is stored as itself.
- **Layout 2.** Member entries are a stored shape older clients misread
  (they see `s:markIds\u001fc1` as some other NodeState, and no comment),
  so they are layout 2, as the package README's layout rules require:
  `LAYOUT_VERSION` is 2; a new document still records `lexical-y:1`, and
  the transaction that writes a document's first member entry also records
  `lexical-y:2` (undo keeps it). From then on, clients that only read
  layout 1 (#9400 to #9438 builds) open the document read only, with the
  `@lexical/y/unsupported-layout` warning, instead of editing it without
  its comments; documents that never hold a member entry stay at layout 1
  and older clients keep editing them. The planned move records (#9449)
  become layout 3. A client that is active and reads the version a peer
  just recorded does not read the whole document again when the record
  arrives (it changes nothing it reads or writes). The version is recorded
  in a `finally` inside each transaction that writes content (an edit's,
  the initial write's and the rewrite that recovers from a failed write),
  so a write that throws part way, which Yjs still commits and sends,
  carries it too; once a document records it, a transaction's inserts are
  not scanned for member entries.
- **One format family per set.** The write cursor bounds the format items
  a delete leaves, and keeps a format's items at the boundaries a concurrent
  writer relies on, per format family (#9400's `formatFamily`). Here a set's
  member entries (`s:<key>\u001f<member>`, escaped members included) and a
  whole array an earlier build stored under `s:<key>` are one family, the
  set's key, so they follow the rules the whole set follows: the run a
  delete leaves keeps a bounded number of member items per set, not per
  member (a comment added to each of 60 words typed and deleted again at one
  place leaves at most 4 live items, not 2 per comment); and removing a
  member from a range that holds another member's boundary writes the
  removed member's value again there, so text a peer types before that
  boundary does not bring the member back. Removing a comment whose range
  holds another comment's start costs 51 bytes (redo 48) instead of 10.
- **Known limit: a removed member leaves an item.** Removing a member from
  text that stores its set per member (resolving a comment with
  `$removeMarkID`) leaves one small live format item after that text (about
  30 bytes with a short comment id), which the binding cannot safely clean
  up: a collaborator writing inside that text at the same time may still
  rely on it (#9400's write cursor keeps the item after a format change's
  range for that writer, for any key; a set stored whole reuses it for the
  next comment there, a member's key is not written again). So the
  document grows with every member removed, not only with its content.
  Removing the same member again at the same place adds nothing, and adding
  a member and undoing it leaves nothing. The docs now recommend resolving
  a comment without removing its id: keep the id in the text, mark the
  thread resolved in the app's own store, and leave resolved ids out when
  rendering (see the `MarkStateExtension` option for that). Unresolving is
  then free and the document does not change. Removing the id stays
  documented as the alternative, with this cost
  ([Resolving comments](https://lexical.dev/docs/collaboration/comments#resolving-comments)).
- A reader that compares a node with what is stored does not refuse a
  state named like a member entry (refusals are for writes), so a document
  holding one, stored by a client that knows only that state, still reads
  in full on clients that know both.
- The self-check's fresh editor gets the set-valued StateConfigs registered
  on the binding's editor, and every StateConfig whose key contains U+001F,
  so it reads the members and those ordinary keys the same way (otherwise
  every write of a set would be reported to the editor's `onWarn` as a
  `'@lexical/y/self-check'` warning, and so would an ordinary state whose
  name looks like a member entry).
- `@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
  `arraySetValue` state, like `MarkStateExtension`, and registers it for
  text the way `MarkStateExtension` does (in the node type's shared state
  config, with no editor update, so that the peers' identical seed is still
  a load for `BlockIdExtension` and gets the same ids on every peer);
  `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), that
  the state needs no registration, and not to name another state with a set's key and U+001F, and the old
  "NodeState sets" limit (one value per text run) is removed, and the limit
  says that storing members is layout 2 and what older clients then do; the
  layout section says `LAYOUT_VERSION` is 2 and when a room records it; the
  README's wire format gets a layout 2 section (the member entries
  `s:<key>\u001f<member>` = `true`, their escaping, the empty key, the
  reserved names, and the lazy upgrade), and its layout record rule says
  "in the same transaction as" the content that needs a version; the Collaboration section of the Comments and Annotations page
  says that `@lexical/y` stores the ids separately, and where. The
  Comments and Annotations page gets a "Resolving comments" section: keep
  a resolved comment's id in the text and its thread's state in the app's
  store (unresolving is then free, and the document does not change), or
  remove the id with `$removeMarkID` and add it again to unresolve, which
  under `@lexical/y` leaves one live item per removal; the Yjs 14 page's
  limits get a "Removed set members" item that says the same and links
  that section. The core
  NodeState page is not changed: it only says that `meta.kind === 'set'`
  marks a set whose members are independent.

A peer that does not know the state exports the joined set in its JSON
(`"markIds": ["c1"]`), which a later JSON load parses as the set.

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                      109 / 10 / 77       92 / 10 / 86
add an overlapping comment         83 / 10 / 77        196 / 45 / 190
remove one of two comments         51 / 116 / 48       113 / 144 / 113
```

The first comment in a document also records layout 2 (26 bytes, once per
document); without that record it is 83 / 10 / 77.

What each way of resolving a comment leaves, 200 comments on the same
words, through `MarkStateExtension` and `YCollabExtension` as an app builds
them, two clients with pinned client ids (a scratch probe, not committed;
live format items, and bytes a GC'd copy of the document grows by per
comment):

```
$removeMarkID (resolved by the author or the other client)   200 items, 49 B per comment (81 B with UUID ids)
the id kept in the text, resolved in the app's store          400 items (2 per comment, its range), 65 B
one comment resolved and reopened 200 times                   1 item
a comment added, then undone                                  0 items
```

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. Mark ids on the wire: ten ids on one text
run, among them lone high and low surrogates (`'\ud800'`, `'\ud801'`,
`'\udc00'`, `'x\udbff'`), a valid pair and ids starting with U+001F: every
peer and a fresh reader read them back exactly, every stored name is
well-formed, and a peer that removes `'\ud800'` removes only that one. A
JSON copy of a commented text node (`node.updateFromJSON(JSON.parse(
JSON.stringify(node.exportJSON())))` through the headless API, with
`MarkStateExtension` or a nodes-only config): an unchanged copy writes
nothing; a copy made while a human resolves A and adds B keeps B only
(with and without a text edit, both merge orders); a copy that adds C to a
JSON still holding A, while a human resolves A, gives C.

New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic
`arraySetValue(stringValue())` state, both client id orders: concurrent
additions (each peer adds the member the other sorts after) merge on a text
run, an inline decorator and a block decorator, stored one key per member
on each, and every peer reads back the canonical frozen array (`['a',
'b']`); a removal and a concurrent addition both apply; a
paragraph stores the set as one `s:tags` attribute (last writer wins); a
state named like a member entry of a known set (`'tags\u001fx'`) is refused
and nothing is written, also when it is only registered and never set (the
set's write is refused); a boolean state of that name stored by a client
that does not know the set is read as itself by clients that know both, and
the whole-container self-check after a structural edit reports nothing; a
set-valued state whose key contains U+001F is stored whole (written as
`['b', 'a', 'a']`, read back as the frozen `['a', 'b']`); a set whose key is
the empty string, with members `''`, `'x'` and `'a\u001fb'`, on a text run,
a line break, an inline and a block decorator, reads back as
`['', 'a\u001fb', 'x']` on every peer and on a fresh reader; members holding
lone surrogates, a valid pair and one starting with U+001F on a text run,
a line break, an inline and a block decorator read back exactly on every
peer and a fresh reader. The layout record: a set stored whole on a
paragraph leaves the document at layout 1; the update that writes the
first member entry also records `lexical-y:2`, which every peer then has
and undo keeps; through the headless API a seed and a text edit without
members stay at layout 1, the edit that adds a member records layout 2 in
its update, and a seed with a member records both; a write that throws
part way (the edit and the rewrite that recovers from it each write
everything, then throw), with `NODE_ENV` development and production, and an
initial write into a root inside another shared type that throws part way,
both send `lexical-y:2` in the first update, with the member entry. A set
used without registration, both client id orders: a client that starts using the
set after it read the document reads the members, types in the tagged
text, adds a member and removes one, and every peer, the stored keys and a
fresh reader agree, with no error or warning; concurrent changes merge when
one client learned the set late; a client that never uses the set edits
the text and keeps its members, and its JSON equals the others'; the
headless API seeds such a state, reads it, adds a member and edits the text
without touching it.

`Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to #9438:

```
$ npx vitest --project unit --no-watch 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[b] test_equation[b] …' 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
 × a state named like a member entry of a set is refused
   AssertionError: expected [Function] to throw an error
 × a state named like a member entry is refused even without a value
 × a client that starts using the set after it read the document reads the members, and its writes keep them (2 of 2 orders)
 × concurrent changes merge when one client learned the set late (2 of 2 orders)
 × a client that never uses the set keeps its members (2 of 2 orders)
 Test Files  3 failed (3)
      Tests  29 failed | 46 passed (75)
```

This revision's fixes (members that are not well-formed UTF-16, a JSON
copy of an unknown set, and layout 2), with this revision's tests and the
previous revision of `Binding.ts`, `Read.ts`, `Schema.ts` and
`constants.ts`:

```
$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{SetState,MarkState,Lifecycle,Storage,Size}.test.ts
 × ids that are not well-formed UTF-16 keep every code unit on every peer and a fresh reader
   AssertionError: expected { root: { …(6) } } to deeply equal { root: { …(6) } }   # peers read '\ufffd'
 × an unchanged copy writes nothing (nodes only)
   AssertionError: expected Uint8Array[ 1, 2, 177, 151, 159, …(-109) ] to be null
 × an unchanged copy writes nothing (nodes only, seeded nodes only)
 × a copy does not bring back a comment a human resolved at the same time (nodes only)
 × a copy does not bring back a comment a human resolved at the same time (nodes only everywhere)
   AssertionError: expected [ 'A', 'B' ] to deeply equal [ 'B' ]
 × a changed copy writes only the members it adds or removes
   AssertionError: expected [ 'A', 'C' ] to deeply equal [ 'C' ]
 × are read back exactly on text, a line break and stored nodes
 × the first member entry records layout 2 in its own update, and undo keeps it
   AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ]
 × the headless API records layout 2 with the first member entry only
      Tests  9 failed | 137 passed (146)
```

The same, on this revision (two more tests, below): `Tests  148 passed (148)`.

#9400's `regressions/Formats.test.ts` with the previous revision of
`Schema.ts` (every key a family of its own) and of `Size.test.ts`'s budget:

```
$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > F24A-1: words typed and deleted again at one place > leave a bounded number of format items (comments)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 1,2,3)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b " (ids 3,2,1)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 1,2,3)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/regressions/Formats.test.ts > R24B-F1: a comment resolved ‖ plain text typed before a character it covers > C3 over "b c" (ids 3,2,1)
      Tests  5 failed | 94 passed | 4 expected fail (103)
```

The same, on this revision: `Tests  99 passed | 4 expected fail (103)`.

A write that throws part way, with the previous revision of `Binding.ts`
(which recorded the version after the write, so not when it threw):

```
$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/SetState.test.ts -t 'throws part way'
 × a write that throws part way still sends layout 2 with the member entries it wrote, in development and production
 × an initial write that throws part way still sends layout 2 with the member entries it wrote
   AssertionError: expected [ 'lexical-y:1' ] to deeply equal [ 'lexical-y:1', 'lexical-y:2' ]
      Tests  2 failed | 21 skipped (23)
```

A layout 2 document opened by the previous commit (#9438, layout 1 only),
written here with one comment and read there with `MarkStateExtension`:
`status: "readonly"`, warning `'@lexical/y/unsupported-layout'` (`data`:
`{reason: 'newer', found: 2, supported: 1}`; message `layout 2 is newer
than 1` since #9400's typed warnings) (before this revision: `active`, no
warning, and no comment shown).

```
$ npx vitest --project unit --no-watch packages/lexical-y/
 Test Files  136 passed | 2 skipped (138)
      Tests  4674 passed | 12 expected fail | 2 skipped (4688)

$ npx vitest --project unit --no-watch packages/lexical-mark/ packages/lexical-yjs/src/__tests__/unit/MarkStateCollab.test.tsx
 Test Files  5 passed (5)
      Tests  141 passed | 4 expected fail (145)
```

The 2 skipped tests (`IncidentReplay.test.ts` and `TabLeakReplay.test.ts`)
and the 12 expected failures (pinned limits in `regressions/`) are #9400's
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
(25 seeds per test), and the default run with one boolean key per comment:

```
$ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts
      Tests  100 passed (100)

$ FUZZ_COMMENTS=keys npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts
      Tests  16 passed (16)
```

Property test with comments (a reviewer's scratch harness, not committed:
2–3 human peers with `MarkStateExtension` and the self-check on, typing,
structure, bold, comments added and resolved, undo, through a delaying and
reordering relay, while agents edit stale stored states with
`editYState`, 60 steps per session), 2,000 sessions each: comments,
comments with block ids, and storing the returned `state` when the agent
edited the latest state. 0 sessions in which the binding diverged; the
last mode had 5 sessions whose stored state read differently before
which one client's `Doc` keeps pending structs it could apply (a `@y/y`
14.0.0-rc.29 issue reproduced with Yjs alone). On this revision, its
comments mode with the self-check off (2,000 sessions) and on (500
sessions) gives the same result in every session as #9438. A first
version of the layout 2 record made every peer read the whole document
again when the record arrived, which changed the result of 3 of those
2,000 sessions (text shown twice); the binding now skips that read when it
already reads the recorded version, and the 3 sessions are as on #9438.

Collab Y e2e on this commit (the development build as CI makes it, with
the binding's self-check on, `collab-y-server.mjs` relay, 2 workers, no
retries): Chromium 31 passed; Firefox 28 passed, 3 skipped (the IME specs
are Chromium only).

On this commit: `pnpm run test-unit` compared test by test with #9438 (0
failed, 0 changed, 68 added: `MarkState.test.ts` 41, `SetState.test.ts` 23,
`Size.test.ts` 3, and `Lifecycle.test.ts`'s version gate test renamed from
"(3 ‖ 2)" to "(n+2 ‖ n+1)", the one missing name), and with the stack's
base `eb0a28499` (0 failed, 0 missing, 0 changed, 4,882 added: 4,875 on the
previous revision, plus #9400's 3 new `WarningTypes.test.ts` tests and
#9437's 4 new tests (`createYDoc`, and that `YBinding` hides `flushPending`); the
website's generated `stackblitz.test.ts` audits are left out of both
comparisons), `pnpm run tsc`, `tsc-test`,
`tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow` (0 errors),
`pnpm run lint`, `pnpm run prettier`, the source tree-shaking test
(372 passed), `pnpm run build-prod` and the built tree-shaking
test (286 passed), and the website build with TypeDoc and the
broken link check (`pnpm run build-docs`) all pass.

Not exercised: WebKit, and real Yjs 14 providers other than the playground
relay.
zurfyx added a commit that referenced this pull request Oct 26, 2026
…al-y][lexical-yjs] Feature: @lexical/y, an experimental Yjs 14 collaboration binding

## Description

A new experimental package, `@lexical/y`: a collaboration binding for
Lexical on Yjs 14 (`@y/y`). `@lexical/yjs` (Yjs 13) is unchanged: Yjs 14 is a
different npm package with a different API, so a Yjs 14 binding cannot
replace it in place, and an application uses one or the other.

Try it: [jot.rovira.sh](https://jot.rovira.sh), a full-page note anyone
with the link can edit at the same time, built on `@lexical/y` (source:
[zurfyx/jot](https://github.com/zurfyx/jot)).

Current behavior: the only binding, `@lexical/yjs`, stores one shared
element per Lexical node. Splitting, joining, retyping or re-indenting a
paragraph, and linking or unlinking text, are written as a delete and a
re-insert, so a collaborator's concurrent typing there can be lost or
misplaced (see Before), and every Enter or heading change rewrites
elements (see the bytes table).

New behavior: `@lexical/y` stores a paragraph, heading, quote or list item
as its characters followed by a marker, a list as the items it groups and a
link as a format over its characters. The storage is derived from general
facts the node classes declare in `$config` (`inline`, `children`,
`mergeAdjacent`, `derived`), with one fixed rule, first match wins: a block
with `children: 'inline'` is a line; an inline element with `mergeAdjacent`
is a format; a block listing line classes as `children`, with
`mergeAdjacent`, is a group (a line holding its own group, a list item
holding a list, is the only nesting); anything else is nested. The first
three also need the class's data to be fully in its schema and NodeState.
These edits then keep the characters and merge with concurrent typing.

Built on the `$config` keys, their declarations on Lexical's nodes and the
opt-in `NodeStructureExtension` (#9452, on main); the binding registers that
normalization, so each client writes its own edits in the normalized form
the declarations describe, and shows a remote change as it is stored (a
remote change never makes a reader write). There are no collab-specific keys
in core and no binding-level storage overrides.

Also new here: `describeStorage(editor, binding?)` (the kind per type), and a
per-document pin: the first write of a type records its kind and identity
fields on the root (`k:<type>`, outside the undo history); a later client
whose class derives another kind uses the recorded kind when it can store
the class that way, and opens read only otherwise. List identity is the
declared `mergeAdjacent.by` fields only (`listType`), so NodeState such as a
block id never splits a list.

Entries (all `@experimental`):
- `@lexical/y`: `YBinding` (its `editor`, `doc`, `root`, `status`, `pins`
  and `undoManager` are read-only getters), `YCollabExtension` (binding,
  collaborative undo, `status` signal; conflicts with the history
  extensions), `describeStorage`, `DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`, and
  the types `YBindingOptions`, `YBindingStatus`, `YCursor`, `YCollabConfig`,
  `ClientIDRange`, `StorageKind`, and the warning code constants below with
  their union type `YWarningCode`. No React, no DOM requirement.
- `lexical`: `LexicalWarning` (`extends Error`, `readonly code: string`,
  `readonly data?`), a generic class with no codes of its own, and the
  update tag `DEFER_COMPOSITION_MERGE_TAG` (see Core).
- `@lexical/extension`: one new `BlockIdExtension` option,
  `repairTransforms` (default `true`, behaviour unchanged; see Block ids).
- The www entry stub `packages/lexical-y/LexicalY.js`, as every other
  single-entry package has.
- No server entry: old clients write other roots (see "Old clients"), so a
  server needs no API of its own; the two constants a server may want
  (`DEFAULT_ROOT_NAME`, `LAYOUT_VERSION`) come from the main entry.
- Seeding a document on a server is `seedYState` in `@lexical/y/headless`
  (#9437, stacked on this); the internal one-off writer is not exported.

Warnings: `lexical` exports `LexicalWarning` (`extends Error`, `readonly
code`, `readonly data?`), which packages pass to the editor's existing
`onWarn` (its `(error: Error) => void` signature is unchanged) for warn-level
conditions with a stable, package-namespaced code (`code` is a `string`;
core knows no codes). Documented under "Errors and warnings" in Defining
Extensions, with neutral example codes. `@lexical/y` has no `onWarn` option
of its own: every
warning goes to the editor's `onWarn` as a `LexicalWarning`, with an exported
constant per code: `UNSUPPORTED_LAYOUT_WARNING`
(`'@lexical/y/unsupported-layout'`), `UNKNOWN_NODE_TYPES_WARNING` and
`STORAGE_MISMATCH_WARNING` (each makes the binding read only),
`SELF_CHECK_WARNING`, `RECOVERED_READ_WARNING`, `RECOVERED_WRITE_WARNING`,
`NESTED_FALLBACK_WARNING` (a class stored nested, for example a link subclass
that overrides `shouldMergeAdjacentLink`) and `UNSYNCED_VALUE_WARNING`, each
with documented `data`, and their union, the `YWarningCode` type. Codes are
public API: never renamed or reused, only added, so a `switch` over them
needs a `default`. A warning is delivered once a change has been applied
in full, never from inside a Yjs observer or transaction, and a handler that
throws does not affect syncing (its error is rethrown in a microtask). The
class and value warnings (`NESTED_FALLBACK_WARNING`,
`UNSYNCED_VALUE_WARNING`) are found once per process and reported once per
binding (a class's only to editors that register it), so a second editor
gets them too. `YBindingOptions.onStatus` is called the same way: once the
binding's work is done and Yjs is idle, never inside a Yjs observer.
Without an `onWarn`, Lexical's default applies (it throws in development,
outside Yjs, and `console.warn`s in production).

Docs: a new page, Collaboration > Yjs 14 (`@lexical/y`): when to use it
rather than `@lexical/yjs`, install, setup with `YCollabExtension` and a
provider, the options, warnings (the codes, their `data`, delivery and the
default handler), how content is stored (diagrams of a paragraph and a
heading, a nested list, a link and a table next to the sequence that stores
them), the wire format (a diagram of layout 1: a container's sequence of
characters, `¶` markers with their attributes, format ranges and nested
nodes, and the root's layout record and storage pins, with the stored names
checked against a dumped document and a link to the README's
specification), what changes when collaboration is on (why, a before/after diagram per
rule: a block split around, a heading in a link, paragraphs in a quote
becoming one quote with line breaks, a horizontal rule splitting a numbered
list with its numbering continued, adjacent equal links; and what it means for an
app), edits made by code (agents and tools: edit text in place, apply an
edit to the state it was computed from and merge), servers (old clients,
yrs before 0.28), limits, and upgrading from
`@lexical/yjs` (no in-place migration yet). `LexicalWarning` is documented
under "Errors and warnings" in Defining Extensions. The package README is
short (install, a minimal example, links to the pages and the API reference,
how to run the long fuzz and replay a seed) and holds the frozen wire
format. `DEFER_COMPOSITION_MERGE_TAG` is listed under
Updates > Common Update Tags. A session of 10,000 edits
takes about 217 KB, against 2.8 MB with the default `@lexical/yjs` layout
(see Performance).

`@y/y` is a peer and dev dependency pinned exactly to 14.0.0-rc.29 (npm's
`latest` tag points at an older release candidate). rc.29 is past the
repository's 7-day minimum release age; the lockfile resolves `@y/[email protected]`
(integrity `sha512-A4W9Bnrf…`) and nothing else. The cursor equivalence test
passes on it.

Core (`lexical`): two generic pieces, and nothing about collaboration
(no collaboration vocabulary, API or behaviour; `@lexical/y` keeps its own
codes and checks):
- `LexicalWarning` (above).
- A new update tag, `DEFER_COMPOSITION_MERGE_TAG` (`'defer-composition-merge'`,
  exported from `lexical` next to the other tags, documented in Updates >
  Common Update Tags). While an IME composition is active, an update carrying
  it does not merge text into or out of the composed text node: a merge
  rewrites the composed DOM text node, and the browser's composition range
  would take in the merged text. Once such a merge was held back, later steps
  of the same composition hold it back too (a private `_compositionMergeHeld`
  key, cleared whenever the composition key changes); the nodes merge when
  the composition ends. It is for any update that changes text next to a
  composition without user input (changes applied from another source);
  `@lexical/y` adds it to the updates that apply a remote change. Without it
  normalization ignores the composition, so every other update, including
  one tagged `COLLABORATION_TAG` or `SKIP_COLLAB_TAG`, merges exactly as
  before: `LexicalNormalizationComposition.test.ts` runs 112 scenarios (7
  operations next to the composed node × 8 tags, including
  `COLLABORATION_TAG`, × with and without `skipTransforms`) composing and not
  composing and requires identical JSON and node identities, and
  `SyncCompositionUnchanged.test.ts` (`@lexical/yjs`) drives v1 and v2
  bindings (8 scenarios × 2 client id orders each) with a composition in
  progress and compares every step with traces recorded on main. A hold
  keyed on `COLLABORATION_TAG`, as an earlier revision of this PR had, fails
  2 of them (v1). Checked that `@lexical/y` still needs it: without the tag,
  6 of the 21 tests in its main composition block fail (a peer joins the
  lines while composing).

Block ids: `@lexical/y` works with `BlockIdExtension` (#9421, on main),
which gives every new block an id stored as NodeState:
- The update that names the blocks a remote change brings (positional ids,
  the same on every client that has the same document) is made by every
  client that reads the change: a follow-up of the commit, which may set
  attributes or delete, never insert (see Write path). `BlockIdExtension`
  gains an option, `repairTransforms` (default `true`, unchanged): with
  `false`, the follow-up sets the ids without running transforms and changes
  nothing else. `YCollabExtension` sets it through a peer dependency
  (`declarePeerDependency('@lexical/extension/BlockId',
  {repairTransforms: false})`), so an app that adds both extensions gets it.
  With `true` (an editor that uses `YBinding` directly without setting it,
  or an app that sets it, which overrides `YCollabExtension`), the naming
  update also runs the editor's transforms over what the remote change
  brought: the binding writes only the attributes and deletions they make
  and reads the rest again (tagging that read as the naming update, so that
  the extension does not make it again), and attributes the transforms
  derive can disagree between clients. The docs say to set it to `false`:
  forced to `true` in `YExtension.ts`, 1 of the 15 `BlockIds.test.ts` tests
  fails (the test of the setting itself), and with `BlockIdExtension`
  editors `NormalizationConvergence.test.ts` fails 51 of its 1,131 cases,
  with or without the self-check: the 48 runs of adjacent equal lists
  written inside a list item without the normalization, and 3 of its 100
  randomized sessions, which end with clients showing different content.
  The BlockId Fuzz (2,000 + 500 seeds) and Races pass.
  No other `BlockIdExtension` behaviour changes, and its existing tests are
  unchanged.
- A line that concurrent edits leave without its marker (text typed into a
  paragraph a peer removed, read as a paragraph) has no stored id. Its
  positional id would cover the whole document, so clients holding
  different concurrent edits derived different ids, and with follow-ups
  limited to attributes they could not converge. The reader derives it
  instead, from Yjs identity: `y`, the client of the line's first character's
  item, `_` and that item's clock (base 36), set as the block's NodeState
  when `BlockIdExtension` is registered and the line is a block it names.
  Every client and a fresh reader derive the same id from the same
  document, whatever order they saw changes in; the edit that next changes
  the line stores it with the marker it writes, so the id does not change.
  No storage, no follow-up write; part of layout 1 (unreleased). A read
  that recovers by rebuilding the editor keeps it.
- Initial content: two clients that initialize a new document with the same
  content write the same bytes with `BlockIdExtension` too (both id orders,
  with and without text, with a different `generateId` per client): the
  extension names a document's first content positionally, so the ids are
  the same before the content is hashed (see Data model).

Changes in this revision (each with a regression test):
- Only a client's own edits are written, and what made a commit decides
  it, not its tags alone. Lexical commits the updates queued during one
  listener phase together, with their tags merged, so an app's update
  queued from a listener (the character limit's wrapping, an app's own
  edit) could share a commit with the binding's list refresh and was not
  written: its author showed it, the document never got it, and later
  writes failed. The binding's own updates (the refresh, showing what a
  composition held back, reading containers again, the author's
  normalization) no longer run from its listener: they wait until the
  editor is idle, so each commits alone (what a composition held back shows
  then, or when the next remote change is read, also once another
  composition has started), and the normalization, queued from the listener
  so that it runs before a remote change can be read, does nothing when
  another update is committed with it. An update queued in the same phase
  as `BlockIdExtension`'s naming update is still committed with it (see
  Known limits).
- While the binding writes, an update that changes content commits at once,
  as with `discrete: true`. One queued from a listener waited for a
  microtask, and a remote change the provider applied in that task was
  integrated first, so the update was written at positions computed without
  it (a failed write, or text in another place).
- A change the binding does not write is read again. Follow-ups may set
  attributes or delete (deletes were refused too); what else they change is
  not written, nothing of that container is, and it is read again, so the
  editor shows the document (it kept the change, and differed from every
  other client). A remote change that arrives first is read after those
  containers are read in full, and the author's normalization waits for
  that read. With `repairTransforms: true`, `BlockIdExtension`'s naming
  update no longer stalls the binding (see Block ids).
- A transform registered while a document is open (a plugin that mounts
  once the editor is editable, such as the playground's table cell
  resizer) makes Lexical run it over the whole document in an update of its
  own: that update is a follow-up, so a client that loads a ragged table
  shows it as stored instead of padding it on its own screen.
- A line without a marker that an update did not change is left without
  one: two clients making structural edits in its container at once each
  gave it a marker (an extra empty paragraph everywhere).
- A new editor bound to a document an editor of the same client wrote, and
  a read that recovers, no longer reuse segment keys (a token typed later
  merged into an earlier one on every other client).
- A saved EditorState set again is written whole: descendants that changed
  under ancestors that kept their objects were not written.
- `BlockIdExtension`'s naming update stays out of the undo history.
- An unknown line type inside a list stored as a node makes the binding read
  only, as everywhere else (it read as a list item and a local edit could
  overwrite it); read recovery keeps the derived ids of lines without a
  marker; a layout record removed from an active empty root makes the
  binding read only.
- `internal/UpdateRoots.ts`, used only by tests, moves to the test
  utilities; nine unused exports are removed.

Data model:
- Shared root `doc.get('lexical-y')`, a new root name, with a layout record:
  one root attribute per layout version the document needs (`lexical-y:1:
  true`). A reader gates on the highest version present; the record only
  grows (no client deletes one), and a writer records a version in the same
  transaction as, and before, the first content that needs it, so two
  clients upgrading at once (3 ‖ 2) leave every reader at 3 (a single
  last-writer-wins number could come out as 2). Any change to how a stored
  shape is read is a new version. The editor stays read only until the record
  has been read. A newer version, a malformed record, content without one,
  or a record removed from a document the binding was writing keeps it read
  only; going read only clears the undo history.
- `initialize()` (after the provider's first sync) marks only an empty root.
  An `editor.update()` still pending when it runs is committed first and is
  part of the initial content (it was written afterwards as an ordinary,
  undoable edit, so two clients seeding the same content that way showed it
  twice).
  It refuses (read only, `'unsupported-layout'`) when an older layout's root
  (`root`, `root-v2`) has content; a binding with `convert: true` writes the
  layout root next to it. Into a pristine root (one that never held an item
  or an attribute, deleted ones included), the initial content is written
  with a client id hashed from the layout version, the target shared type
  (its top-level name or item id) and the exact items written (encoded from
  a scratch document), so two clients initializing the same content into
  the same new root at once write it once, while different roots or content
  never share an id; outside the undo history. It is the binding's first
  write, so its segment keys (token-mode text) are that id and a counter
  from 0 on every client. A root that held anything is initialized under
  the client's own id: around retained items two clients' copies could
  differ under one derived id (the scratch document does not hold them),
  and Yjs never reconciles two items with one id. Content-derived ids
  are 53-bit hashes (cyrb53) under `clientIDRange: 'uint53'` and 32-bit under
  `'uint32'`, so they live in the same range as the clients' own ids; every
  client of a document must use the same range. The real client id is back
  before the transaction's observers and update handlers run, so a provider
  that relays synchronously from an update handler never sees (or makes the
  binding write follow-ups under) a derived id.
- The wire format is frozen as layout 1 in the README (root and attributes,
  markers, run terminators, `b:`/`i:` prefixes, `c`, `t`, `p:`, `s:`, `g`,
  `g:`, `l`, `o`, `@`, `f:`, `k`, `w:`, `#`, `k:<type>` pins, value
  encoding, the layout record, the derived id of a line without a marker). Layout 2 (#9449, stacked on this) adds move records.
- Every container (the root and every node stored as its own Y.Node) holds
  one sequence of text, child nodes and line markers (Yjs 14 Y.Node children
  are unified, so no XmlText per container is needed).
- A line (a block class declaring `children: 'inline'`, schema-complete) is
  its inline content followed
  by a marker: a child `Y.Node` named `¶` whose map attributes hold the
  line's type (left out for a paragraph), schema fields (minus derived),
  NodeState, and for a group item the group type, key fields and level. Not
  a character with formats (such as U+2029) and not an embed:
  * map attributes merge per key (last writer wins), so a concurrent heading
    change and indent both apply, without format start/end items in the
    sequence;
  * the marker's identity (its item) never changes when its attributes do,
    where an immutable embed would have to be replaced (and could be
    duplicated by concurrent replacements);
  * block attributes never mix with inline formats, and text may contain
    any character.
- Groups (lists) are rebuilt from consecutive items; local groups are kept
  in the same canonical shape by a transform (adjacent equal groups and
  wrapper items merged, empty groups removed); derived fields (list
  numbering) are recomputed by a refresh update on every client. Only the
  declared `mergeAdjacent.by` fields identify a group (`listType` for a list);
  its other synced fields and NodeState do not split it. A nested item's marker
  also records its outer groups and their wrapper items' fields (`o`), so an
  indented first item keeps its outer list's type and the wrappers' fields
  sync.
- Storage follows the class, never the instance: a line class stays a line
  even with a block child (the child is stored as a node inside its
  content, for example in a shadow-root quote, unless the normalization
  lifts it out; see Normalization). `isInline()` still decides
  where a node sits: a format applies to inline instances, a line to block
  ones. A node whose
  `isInline()` changes (a class computing it from a field) is written again
  in its new form: a format becomes an `i:` node inside the line, and back.
  Undeclared or invalid blocks are `b:<type>` child nodes with the
  class's own (compact) JSON as attributes; inline elements that are not
  formats and inline decorators are `i:<type>` children.
- A container records what it holds (`c`: blocks or inline content) when it
  is created, from its declared `children` or its children, and never
  changes it:
  leftover inline content of a block container reads as a paragraph on every
  reader; inline content directly in a block container is always ended by a
  `¦` terminator.
- Inline elements stored as formats (declared inline, with `mergeAdjacent`)
  are one format key each
  (`w:link`, whose value holds the wrapper's fields); text formats are one
  key per format (`f:bold`), plus type, JSON fields, NodeState and, for text
  nodes Lexical would not merge, a segment key (`k`). Formats apply to any
  child, so a link can span a line break or an inline decorator; a line
  break's NodeState is a format of its `\n`. Two adjacent equal links keep an
  instance key (`#`) so they stay two links on every peer.
- NodeState equal to its default is not stored (setting it back deletes
  the key). Element `textFormat`/`textStyle` are always stored.
- Schema completeness (own `$config()`, no hand-written `exportJSON`,
  `updateFromJSON` or `afterCloneFrom` below the declaring class) is
  required for lines, groups and inline formats; anything else is a node.
- Editor instances (nested caption editors) are not synchronized; JSON
  snapshots of them are (members that JSON would drop are dropped).
- A class with a hand-written serialization is a node; an edit to one of its
  own fields alone is written (the whole node's JSON is compared) and read
  through `updateFromJSON`, then `importJSON` for fields it does not know.
- Unknown types fail closed: a client that meets a node, line, text or
  group type it does not register (a line inside a list stored as a node
  included) goes read only with a warning, so it never hides and later
  deletes content it cannot show.

Write path:
- Anchored edits: Y.Node#insert/delete/format walk the type from its start
  on every call in rc.29, so the binding edits the sequence from the item it
  knows (the previous line's marker) with a port of Yjs' text position
  algorithm. A test runs random operations through it and through
  Y.Node#applyDelta and requires identical documents (byte for byte).
- A keystroke (one text node of a line changed, same formats, every other
  child unchanged including inside links) diffs only that node's old and
  new text, anchored at the caret, and writes at its offset: cost in the line's
  items, not its length (0.4 ms in a 200,000-character paragraph).
-  Identity-anchored structure: units matched by node key (a weighted
  longest increasing subsequence: as many blocks as possible stay in place,
  a list counting as one block; between equal counts a block node, whose
  rewrite copies its subtree, outweighs lines). A line whose content did not
  change (node identity against the previous state, inline elements
  included) is never diffed; removed or moved units are deleted exactly;
  only split, join and type-change segments are diffed, as one sequence of
  the segment's items with the caret as the diff anchor: text that moved to
  another line keeps its items (no re-insert of a moved tail, so text a peer
  deleted is not resurrected). Each character keeps its old item only if it
  comes from the same Lexical text node as before (text nodes merged by a
  join or an unlink are attributed using the caret at the join, else by
  common prefix and suffix, among the nodes removed from the content being
  rewritten; text merged from elsewhere is new), so text that moved between
  nodes or lines is written as new text, never built from equal old
  characters. Diffs never split a surrogate pair. A Lexical node replaced in
  place by a new one keeps its shared node and content: a different type is
  recorded in the node's `t` attribute (a paragraph held by a list item
  turned into a heading keeps a peer's concurrent typing). Enter inserts a
  marker, Backspace deletes one, a type, indent or list type change only
  sets marker attributes.
- Structure is read from node links (the root is always marked dirty);
  attributes are written only for changed keys; inserted content carries its
  formats (no reformat after insert); format passes walk runs, not
  characters.
- Follow-ups: updates every client makes after a commit (the refresh of a
  group's derived fields, `BlockIdExtension`'s naming update, the update
  Lexical makes to run a transform registered while the document is open
  over all of it) are written through one check: they may set attributes
  or delete, never insert a marker, materialize a line without one, or
  insert content. What else they change is not written, and the binding
  reads those containers again, so the editor keeps showing the document (a
  development warning names the change). The re-read of a naming update's
  change is tagged as that update, so that `BlockIdExtension` does not make
  it again on what was read; content a follow-up changes every time it runs
  (a list's own transforms in each refresh) is read again three times in a
  row, then once more without the refresh. What made
  a commit decides whether it is one: the binding's own updates commit
  alone (they run when the editor is idle), and the transform's update
  commits alone and dirties every node of a type that just gained a
  transform. An update another listener queues in the same listener phase
  as the naming update is committed with it and counts as part of it.
- While the binding writes, every local update that changes content commits
  at once (as `discrete: true` does) instead of in a microtask, so a remote
  change the provider applies in the same task never finds one waiting.
- An update of the client's own that ran no transforms is normalized by the
  client right after it (see Normalization), in the same undo step.
- Self-check (off by default; `selfCheck` and `selfCheckSample`, also options
  of `YCollabExtension`; skipped while such a normalization is pending):
  every line a write touched is read back from Yjs (text, formats, line
  break NodeState, marker), and every container a structural write touched,
  or where a group item's marker changed, is read whole into a fresh editor
  and compared with the editor's JSON (node types, list structure, wrapper
  fields, NodeState); mismatches go to the editor's `onWarn` as a
  `'@lexical/y/self-check'` warning. The whole
  container read runs every time for containers of up to 256 units and is
  sampled in proportion above that (Enter in a 2,000-block document went
  from about 50 to about 12 ms in development). Lexical's tests turn it on
  through their helpers and fail on a warning.

Read path: a local update still pending (one without transforms, which
does not commit at once) is committed before a remote transaction is read,
and a container that still shows a follow-up's change the binding did not
write is read in full first; changed items are bucketed by container once
per transaction; an inserted or deleted format item re-derives the start formats
of the following units (past block nodes too) until they agree again; each
changed item is located by walking to the next end item; text edits update
lines in place; structural changes re-parse only the touched units (groups
next to them are regrouped without re-reading untouched lines); formats that
span a marker propagate only while the value at the next unit's start
changes (re-reading the next unit as a region when it cannot be updated in
place); an inline element that cannot be empty is not shown when peers
deleted all its content; NodeState keys are read in sorted order. The local
selection is captured as relative positions before each remote transaction
(a caret anchored to the character on its left, a range to its edge
characters) and restored in the same update (an end item a peer deleted is
skipped when a position is resolved). While the local editor is composing
(IME), remote inserts into the composing line are applied to Yjs but not to
that line's nodes (the browser composes into their DOM); readers and writers
of that line skip those ids, and the line is read again when the composition
ends (a read that only moves the composed line, regrouping its list, keeps
what is hidden hidden; if the composing client removes the line, what was
hidden in it is read where it is stored). Deletions, formats and structure in
the composing line are read at
once, keeping the composed text node (its key and text): text a peer joins
into the line goes into nodes of its own, and a composing line joined into
the next keeps its node for the merged line. Remote reads skip Lexical's
transforms, so every list whose children a read changed, or whose items
gained or lost a nested list, is refreshed afterwards by running the list
class's own transforms with its siblings hidden (list numbering is computed
the same way on every peer, and a transform never merges two lists on one
peer only; in an editor that is not focused that refresh does not set the
DOM selection (SKIP_DOM_SELECTION_TAG), which would move the focus into it,
while a focused editor sets it as usual, so a refresh that reshapes the DOM
under the caret keeps the caret). After a remote change that refresh writes
a group's stored fields (`g:<field>`, `o`) to its items' markers only for
groups whose fields the change or the refresh changed (a list's text
format), and otherwise only fills in a marker that lacks them: a marker can
hold the fields as another client wrote them while a reader takes the
group's from its first item, and two clients that did not hold the same
items yet (so each took another first item) rewrote each other's marker
without end. A list whose own fields a remote change changes (its start)
is refreshed too (its items kept the old numbering on the reader); groups are told apart by their first declared key field
only (a list by its type, as Lexical merges lists), and a region read back
empty regroups its neighbours. Groups and wrapper items carry their
textFormat and textStyle (Lexical serializes them only while an element has
no text), and each wrapper reads the fields its own group recorded. A list
stored as a node inside a line (Lexical keeps blocks pasted into a list item
inside it) reads text left without a marker as one of its items; an element
that cannot be empty is shown only while its content is not, on every
reader, and a line of another type in it (a quote) reads as one of its items,
as `ListNode.splice` converts a block put into a list; two such lists of one
type that end up next to each other (added by two peers at once) stay two
lists until a local edit merges them. When the local tree joins
two wrapper items, the nested lists they hold are joined too, as a reader
builds them. A link's own textFormat is stored with its value. The character
diff of a line places a change at the caret only while the text after the
caret is unchanged (after a join the caret is before the new text). A marker
attribute a peer removed resets the field even when exportJSON hides it
(`checked` outside a check list). A NodeState value read before its key's
config was known is replaced by the known value when the node is written (a
reset comment is removed on every peer).

Recovery: a stored node a write deletes without giving it a new shared node
loses its mapping (no later write goes into a deleted node, where Yjs drops
what is inserted; this was the "cursor advanced past the end" exception on
paste). A write that throws part way is followed by a rewrite of every
container in a fresh transaction; a remote read that throws is followed by a
rebuild of the editor from the shared content (what every fresh reader
shows) in a fresh update; both are reported through `onWarn`. When the
self-check finds the editor different from the shared content after a
remote change (the shared content is right, the editor is not), those
containers are read again. (After a local write the editor is the intent,
so a mismatch there is only reported.)
A text diff with a run of equal characters places the change at the caret
(a space typed next to a space), and never splits a surrogate pair.
Normalization: the binding registers `NodeStructureExtension`'s
normalization, and `YCollabExtension` depends on the extension, so editors
without `@lexical/y` are unaffected. A local edit is normalized by Lexical
as it is made, so what a client writes is normalized. Content the
normalization would change can still reach a peer:
- written without it (an update with `skipTransforms`, `setEditorState`
  with a state the editor did not build, an older client): its author
  normalizes it right after, as part of the same edit (above); the update
  that normalizes marks what the first one changed dirty, with the elements
  holding it, and calls `INTERNAL_$normalizeNodeStructure` on them. Readers
  show the update as written until the normalization arrives;
- produced by concurrent edits (text typed into a paragraph a peer
  removed from a table cell, a row insert ‖ a column insert, two lists
  added to one list item): every client shows it as stored, and the next
  local edit that touches it normalizes it, as that client's edit.
No client normalizes another client's content on its own, so no two
clients write the same repair. A line written inside a line (a heading a
client wrote inside a list item without the normalization) is stored as the
lines the normalization leaves: the holder's inline content split around it,
each part a line with the holder's marker, and the held line with its own
marker, so readers never see the nested shape and the author's
normalization only changes markers. The shape changes collaboration brings
are listed on the docs page ("What changes when you turn on collaboration",
with before/after diagrams): paragraphs in a quote or list item become lines
of one quote or item, other blocks inside inline content are lifted (split
around, link re-wrapped), a horizontal rule in a numbered list splits the
list and continues the numbering, inline content in a block holder is
wrapped in a paragraph, adjacent equal links and lists merge (also without
`LinkExtension`), and shadow roots, `OverflowNode` (stored nested inside its
line, never split around) and undeclared classes are left alone. A class
whose merge is decided by an overridable method keeps that method as the
authority: a `LinkNode` subclass that overrides `shouldMergeAdjacentLink`
is stored as a nested node, not as a format.

Storage reads only `getDeclaredNodeStructure` from `lexical` (its `derived`
set tells which fields are not stored), plus which nodes it treats as
inline content.

Lists: `@lexical/list`'s paths (JSON and HTML paste, `insertNodes`,
markdown import and shortcuts, indent and outdent, list commands and
deletions; 26 checked) never put a list directly in a list item's line
(`listitem[text, list]`): they nest lists in wrapper items, which are stored
as levels. Only direct API calls and writers outside the binding make that
shape; two such lists stay two lists until a local edit merges them (as
y-prosemirror and TipTap do), so the shared list merge is gone rather than
replaced by lifting.

Containers opt out of Yjs' remote formatting cleanup, which rescans every
type with formats after a remote format change (O(document) here): the
binding marks its containers as having no formats before Yjs decides. The
document's `cleanupFormatting` flag and the app's other types are untouched.

Servers on yrs before 0.28 read client ids as 32-bit numbers, while Yjs 14
draws 53-bit ones. With Yjs 14's default ids:
- a ywasm 0.23.5 relay stores an author's content under a truncated id, and
  the author receives its own content back as another client's on reconnect,
  duplicating it;
- a real yrs 0.23 server rejects the reconnect ("the awareness update is
  malformed"), and edits made offline are lost.
yrs/ywasm 0.28.0 is fine. Opt-in compatibility: `clientIDRange: 'uint32'`
(binding and extension) keeps the document's client id, and the ids the
binding derives from content, in 32 bits, including when Yjs draws a new
one. The default, `'uint53'`, leaves Yjs 14's ids unchanged. The binding
does not own the awareness, which takes the document's client id when it is
created; the docs tell apps to give the document a 32-bit id before
creating the awareness and provider. With 32-bit ids, a yrs 0.23 server
converges, including offline edits, reconnects and late joiners.

Old clients: the new root name and the layout version gate stay (a newer
layout opens read only). Clients of the Yjs 13 bindings never read or write
this root, so they cannot change a `@lexical/y` document's content and
servers need no check of their own.

Undo: Yjs 14 UndoManager on the root, tracking only this binding's writes;
`undo()` and `redo()` do nothing while the binding is not active (they
wrote into a document the client had gone read only on), and going read
only clears the history, so the `UndoManager` itself writes nothing. A
container the undone change inserted that holds another client's content is
kept whole (its fields and own content too), unless the undo also restores
a container of the same type (the change was a move: keeping the copy
would duplicate it).
Cursors: `getCursor()` / `$resolveCursor()` (relative positions on items;
no provider wiring or rendering).

`@y/y` internals used (all in rc.29; a bump must re-run the cursor
equivalence test): `new Item(...)`, `item.integrate`, `getItemCleanStart`,
`createID`, `Item.left/right/origin/rightOrigin/parent/content/deleted/
countable/length`, `YNode._start`, `_item`, `_map`,
`_searchMarker`, `_hasFormatting`, the `beforeObserverCalls` event,
`doc.store.getItem/getClock/clients`, `findIndexSS`, `iterateStructsByIdSet`,
`Transaction.insertSet/deleteSet` (and, in the tests only, `decodeUpdate`
and `findRootTypeKey`).

Supported: split, join, partial joins, heading/quote/paragraph, list type,
indent/outdent, Enter in list items, checked state, alignment and NodeState
of lines, links and other inline formats (incl. property changes and spans
across line breaks), text formats, comments as NodeState, tables and any
nested containers (collapsible-like container > title + content, cell >
collapsible, box > box), block and inline decorators, inline elements
(MarkNode) with nested content, undo/redo, cursors, local selection across
remote edits.

Known limits:
- A move is a delete and a reinsert: text a peer types into a moved line
  lands in its old neighbour. The cheaper side is rewritten: a long move
  rewrites the moved block, not every block it passed; in a swap the smaller
  block is re-created (a collapsible dragged past a box keeps a peer's
  typing inside it); between equal blocks the moved one (Lexical's record of
  explicit moves, `_recordNodeMoves`). A block a peer moves into a container
  that another peer removes at the same time is removed with it (delete
  wins). When a peer removes a range and undoes the removal while another
  moves a block out of that range, the undo restores the block next to the
  moved copy, so it shows twice (Yjs undo restores deleted items as new
  ones).
- Lexical restructures written as moves lose a peer's concurrent typing in
  the moved paragraph, and two peers making the same restructure at once
  both write it, so its content shows twice: a list created from a paragraph
  inside a container that is not a shadow root (a box), indenting, unlisting
  or pasting list items that hold blocks, a normalization (a merge, a lift)
  two clients make from different states. Two peers pulling the same text
  across a container edge (range deletes from a list item into a
  collapsible title) both copy it.
- Shapes concurrent edits leave are shown as stored until a local edit
  touches them: a table whose rows end up with different lengths (row insert
  ‖ column insert) until the next table command, which pads it; two clients
  running a table command on it at once both pad it, and the table gets an
  extra empty column. Two lists in one list item's line (only direct API
  calls and outside writers make the shape) stay two lists until an edit in
  the second merges them, written as a move.
- Content written without Lexical's normalization is shown as written on
  other clients until its author's normalization arrives (right after the
  write); an author that goes offline in between leaves it unnormalized until
  someone edits there. A Lexical command used on such a shape meanwhile can
  fail: Shift+Enter in a list item that holds only a block decorator throws
  in core's `insertNodes`.
- A list type change racing a new item in that list (Enter in it) splits the
  list: the new item keeps the old type, in a list of its own between the two
  halves (`@lexical/yjs` keeps one list).
- A list held by a paragraph (written without the normalization) is stored
  as a node inside the line until the normalization lifts it out: a
  Backspace or range delete that removes it meanwhile takes what a peer
  types into it at the same time (delete wins).
- An update applied with `skipTransforms` waits for its commit like any
  other Lexical update: a remote change the provider applies in the same
  task before it commits is integrated first, and the update is written
  after it.
- Properties a class keeps outside its `$config()` schema and NodeState are
  not synced; such classes are stored as nodes with a warning naming the
  properties (Lexical itself drops them when it clones the node).
- MarkNode is an element with its own content: wrapping a range moves the
  text into it, and concurrent typing in that range stays outside. Store
  comments as NodeState instead (MarkStateExtension).
- Set-valued NodeState (a state declared with `arraySetValue(...)`, which
  MarkStateExtension uses for its mark ids) is stored as one value per text
  run in this PR, not one entry per member: two peers changing the set of
  the same text at once (two comments on the same words) keep one writer's
  set (converged, no error). Per-member storage is #9439, stacked on this PR,
  to land before the first release that publishes `@lexical/y`.
- A split racing a type change gives the first half the splitter's type;
  text typed into a line a peer removed joins the next line.
- Text typed into the last block of a container while a peer removes that
  block is kept as a line without a marker (shown as a paragraph). Other
  edits in the container leave it so; two clients typing into it at once
  each give it a marker, which splits it in two (one part can be empty).
- Slots are not synchronized; a link's fields merge as a whole (last
  writer wins).
- Yjs format semantics: bold ‖ bold on adjacent ranges of one line can leave
  part unformatted (the same on Yjs 13).
- A join ‖ removal of the joined line also joins the next line (nothing
  deleted comes back); unwrapping a container is a removal and a
  reinsertion of its lines, so text a peer types inside it at the same time
  is lost, as is text typed inside a container a peer removed (delete
  wins).
- Two clients initializing with different content at once both keep their
  content (converged). Content with random values counts as different, and
  so does initializing a root that held content before (written under each
  client's own id): seed new documents in one place (on the server), or
  give the initial blocks fixed ids.
- Undo never deletes a container another client has put content in (it is
  kept whole).
- With `BlockIdExtension`, a block that reaches clients without an id
  (written by a client without the extension) is named by each client from
  the document it has (positional ids); clients holding different
  concurrent edits give it different ids, which converge on one. An update
  another listener queues in the same listener phase as that naming update
  is committed with it and counts as part of it: what it inserts is not
  written, and the editor reads it back as stored.
- A node whose `isInline()` changes is written again in its new form: text a
  peer types inside it at the same time lands next to it (as with a move).
- Several edits to one line in a single update are written as one replace
  (a peer's caret inside it moves to the edge).
- Structural edits in a large list cost time proportional to the list on
  both sides (regrouping and renumbering).
- Relies on the @y/y internals listed above.
- Version gate: the highest `lexical-y:<n>` the root records must be at most
  `LAYOUT_VERSION`, and every `lexical-y:` attribute an integer from 1 set to
  `true`; anything else is read only.
- With Yjs 14's default 53-bit client ids, servers on yrs before 0.28
  duplicate content or lose offline edits on reconnect; use the opt-in
  32-bit range for them, and create the awareness from that document.

Known open issues (from randomized runs; see Test plan):
- An update made between a follow-up whose change was not written and the
  read that undoes it in the editor (an app's update queued from a listener
  in the same task) is written against the editor that still shows that
  change. With `skipTransforms` writes, block ids and such an app listener,
  106 of 500 randomized sessions rewrote the document after "cursor
  advanced past the end", and 1 ended with a client different from a fresh
  reader. Without `skipTransforms` writes, none.
- Block moves: with moves in the randomized scripts, @lexical/y loses or
  duplicates more than v2 on 6 of 1,000 seeds (the same 6 as on the previous revision; 0 of 200 with gc), all in the move limits
  above.
- Self-check: with the self-check on, a remote change can leave the editor
  briefly different from the shared content (two adjacent equal lists the
  incremental reader has not regrouped yet); the binding then reads those
  containers again and reports a `'@lexical/y/self-check'` warning
  (none of the 2,000 randomized normalization sessions in Test plan, with
  or without block ids; 4 of 2,000 property sessions with block ids, see Test plan). With it off (the default), sessions end
  with every client equal to a fresh reader.
- NodeState keys of a node keep the order of the author's local history in
  its own editor (values equal; other clients read them sorted).
- Not a binding issue: `$toggleLink(null)` on a range that ends at the edge
  of a link's text throws in `$splitLinkAtSelection` (empty
  `extractedChildren`), in any editor on main; the fuzz no longer generates
  it.

## Test plan

### Before

The tests this revision adds or changes, run on the previous revision
(the new files copied in). Each file's failing tests:

```
$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/<file>
ListenerUpdates.test.ts         Tests  10 failed | 1 passed (11)
 × an update an app's listener queues after a list change is written
   (block ids: false) / (block ids: true)
 × an update an app's listener queues when a composition ends is written,
   with the remote text held back until then
 × an overflow wrapping queued from a listener after a list change is written
 × an update an app's listener queues is written when a remote change to its
   line is applied in the same task
 × with repairTransforms: true, a block written inside a paragraph without the
   normalization is shown once (block ids on the author / on the receiver only)
 × with repairTransforms: true, a link written directly in the root without the
   normalization is wrapped once
 × a remote change read while the editor still shows a change the binding did
   not write is read on the document
 × a transform registered while the document is open does not insert: the
   editor reads the document again
BindingState.test.ts            Tests  7 failed | 1 passed (8)
 × a new editor bound to a document an editor of the same client wrote keeps
   its text nodes apart
 × a saved EditorState restored with setEditorState is written whole (from
   another editor) / (from the same editor)
 × a read that recovers keeps the ids lines without a marker derive
 × a read that recovers keeps the text nodes it writes next apart from those it read
 × a line of a type the editor does not register makes the binding read only
   (inside a list stored as a node)
 × removing the layout record while the root is empty makes the binding read only
ShownAsStored.test.ts           Tests  1 failed | 5 passed (6)
 × a transform registered after the document was read does not change what
   was read, and an edit made right after it is written
BlockIds.test.ts                Tests  1 failed | 14 passed (15)
 × the update that names the blocks a remote change brings stays out of the
   client's undo history
ConcurrentShapes.test.ts        Tests  2 failed | 11 passed (13)
 × list type ‖ list type / Enter ‖ Enter in its container leaves it a line
   without a marker
Composition.test.ts             Tests  61 passed (61)
```

The one test of `ListenerUpdates.test.ts` that passes there (a transform
registered while the document is open removes a paragraph, and the removal
is written) pins the rule that a follow-up may delete: the previous revision
wrote that update as an edit. The new `Composition.test.ts` case (a
composition that starts before the last one showed what it held back) pins
a case of this revision's own waiting: the previous revision showed held-back
text in the same commit chain, so it passes there.

Randomized runs that found the problems this revision fixes (and, in the
playground, a client that loaded a document holding a ragged table padded it
on its own screen, writing nothing):

```
# the app-listener harness below, 500 sessions, no block ids, previous revision
a write failed and the document was rewritten: 409 sessions; diverged: 57
  (an app's update committed together with the binding's list refresh was refused)
# the same, during this revision, before local updates committed at once
"cursor advanced past the end" out of the session: 17 of 500;
with skipTransforms and the self-check on, local self-check warnings: 117 of 300
  (an update queued from a listener, written after a remote change applied in the same task)
```

### After

```
$ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs packages/lexical-extension
 Test Files  82 passed | 1 skipped (83)
      Tests  2940 passed | 4 expected fail | 3 skipped (2947)
```

Long runs (the table plugin registered in the fuzz):

```
# STORAGE_PROP_SEEDS=1000 STORAGE_FUZZ_SEEDS=500 SHAPE_FUZZ_SEEDS=600 NORMALIZE_FUZZ_SEEDS=2000
#   DerivedStorage, ConcurrentShapesFuzz, NormalizationConvergence, Races
 Test Files  4 passed (4)
      Tests  4605 passed (4605)
normalization fuzz: {"duplicated":[],"healed":[],"seeds":2000}
# FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500: Fuzz
      Tests  100 passed (100)
# LEXICAL_Y_BLOCK_ID=1, the same seeds: Fuzz, Races, NormalizationConvergence
 Test Files  3 passed (3)
      Tests  3194 passed (3194)
normalization fuzz: {"duplicated":[],"healed":[],"seeds":2000}
```

Differential (`FUZZ_DIFF=1`, the same scripts on this binding and on
`@lexical/yjs`'s v2 layout):

```
# FUZZ_NO_MOVE=1, 2,000 seeds; with FUZZ_GC=1, 500 seeds
absolute failures 0, worse than v2 0 (both)
# with moves, 1,000 seeds; with FUZZ_GC=1, 200 seeds
worse than v2: seeds 272, 295, 394, 410 (dup), 524, 752 (loss); with gc: 0
```

Randomized property run (2-4 `YCollabExtension` editors,
`MarkStateExtension` in half the sessions, gc in 20%, partial delivery,
ordinary edits plus `skipTransforms` writes, `registerTablePlugin`; every
session checks convergence, a fresh reader, Lexical's normalization as an
oracle, block id uniqueness, the tokens typed and a runaway guard), 2,000
sessions per lane, self-check off (the default), this revision against the
previous one:

```
                                   block ids on    block ids off   no skipTransforms
                                   new    prev     new    prev     new    prev
diverged                           0      0        0      0        0      0
fresh-reader mismatch              0      0        0      0        0      0
duplicate / missing block ids      0 / 0  0 / 0    n/a    n/a      n/a    n/a
runaway growth, errors             0      0        0      0        0      0
an op threw                        2      2        2      2        0      0
token shown twice                  115    116      92     95       1      1
token lost: a concurrent removal   571    574      568    570      577    576
token lost: unexplained            10     10       9      9        4      4
token lost: the author's outdent   23     23       24     24       2      2
ragged table at the end            251    249      250    250      294    295
table with an all-empty column     543    543      537    536      576    576
left unnormalized (shown as stored) 28    30       30     31       1      1
```

With the self-check on (block ids on): 4 sessions with a self-check
warning, against 11 (a line holding lines inside a table cell, compared
before its author's normalization ran, was reported). "An op threw" is a
line break inserted into a list item holding only a block decorator, which
another client shows until the author's normalization arrives (see Known
limits). "Lost: a concurrent removal" is delete wins; "lost: unexplained"
and "lost: the author's outdent" (a token the author's own outdent removes
from its editor, before any sync) are the same on both revisions. "Ragged"
and "left unnormalized" are the shapes concurrent edits leave, shown as
stored by design. A table with an all-empty column counts inserted empty
columns too.

A second randomized harness drives the editors as an app does, with an
update listener that queues an edit of its own after 30% of the local
commits (as the character limit and other plugins do), and checks the same
properties (a payload check across peers and relays included):

```
                                   no block ids   block ids      block ids,       mixed, skipTransforms,
                                                                 skipTransforms   self-check on
sessions                           500            500            500              300
                                   new   prev     new   prev     new   prev       new   prev
a write failed, document rewritten 0     409      0     392      106   396        37    271
error reaching onError             0     409      0     391      3     382        0     260
diverged / fresh-reader mismatch   0/0   57/57    0/0   72/72    1/1   100/100    0/0   2/2
exception out of the session       0     32       0     51       0     72         0     12
follow-up change refused (dev)     0     443      0     431      399   420        126   283
self-check warning, local/remote   off   off      off   off      off   off        2/0   282/231
token shown twice                  0     2        1     2        27    18         14    16
ragged table at the end            215   195      220   183      237   206        126   117
left unnormalized                  1     1        2     3        14    7          5     7
```

The lanes without `skipTransforms` are clean. With `skipTransforms` writes
and block ids, an app update Lexical commits together with
`BlockIdExtension`'s naming update counts as part of that update (see
Known limits): its inserts are not written and the editor reads them back.
The rewrites ("cursor advanced past the end") come from an update made
before that read, which is written against the editor that still shows
the refused change; the binding rewrites the document and every client
converges, except 1 session of 500. This is open.

Every scenario the reviews of the previous revision reported is one of the
tests listed under Before.

On this commit: tsc (the project, the tests and the scripts), flow (0
errors), eslint and prettier pass; `build-prod`, `build-types` and the
website build (with its link check) succeed, and the tree-shaking audit of
the built packages passes (284 of 284); core (`lexical` and
`lexical-extension`, `src` and `flow`) adds no collaboration vocabulary
compared with main (`14aea377a`). `pnpm run test-unit` on a clean checkout: 12,540 tests (12,536
passed, 4 skipped; the website build adds 36 audits of its generated pages,
12,576 with them), against 10,072 (10,070 passed, 2 skipped) on main;
comparing the two reports, no test of main fails, is missing or changed.

Performance was not measured again on this revision: the figures above (a
keystroke in a 200,000-character paragraph, the size of a 10,000-edit
session) are the previous revision's. This revision commits local updates
at once while the binding writes, and makes the binding's own updates wait
for a microtask; both are open for measurement.

Not exercised in this revision: real browsers (the playground end-to-end
run that found the ragged-table load divergence was not re-run here), a real
yrs server process, other Yjs 14 providers than `@y/websocket`, and mobile
browsers.
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-playground branch from 739ffea to 96e653b Compare October 26, 2026 04:23
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-mark-set branch from 4f04dcd to 16c6136 Compare October 26, 2026 04:23
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-mark-set branch from d9c1545 to ed6b7ed Compare October 26, 2026 16:40
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-playground branch from b97d7f3 to 692222c Compare October 26, 2026 16:40
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
zurfyx force-pushed the zurfyx/collab-y-mark-set branch from ed6b7ed to 419777f Compare October 26, 2026 19:37
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-playground branch from 692222c to 3e748b5 Compare October 26, 2026 19:37
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
zurfyx force-pushed the zurfyx/collab-y-playground branch from 3e748b5 to f54babd Compare October 26, 2026 22:04
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-mark-set branch from 419777f to 62f1300 Compare October 26, 2026 22:04
zurfyx added a commit that referenced this pull request Oct 27, 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
zurfyx force-pushed the zurfyx/collab-y-mark-set branch from 62f1300 to b3867b0 Compare October 27, 2026 01:53
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-playground branch from f54babd to 019b614 Compare October 27, 2026 01:53
zurfyx added a commit that referenced this pull request Oct 27, 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).

This branch was successfully deployed

2 active deployments
Preview – lexical — 8c1bf4bb Deployed Oct 28, 2026 by vercel[bot]
Preview – lexical-playground — 8c1bf4bb Deployed Oct 28, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants