Skip to content

[lexical-devtools][lexical-website][lexical-y] Feature: Experimental server-side editing API (@lexical/y/headless) - #9437

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

zurfyx merged 1 commit into
mainfrom
zurfyx/collab-y-server

Conversation

@zurfyx

@zurfyx zurfyx commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Stacked on #9400 (@lexical/y, the Yjs 14 binding).

Today @lexical/y gives a server nothing beyond the main entry's
DEFAULT_ROOT_NAME and LAYOUT_VERSION. Everything a server needs to seed,
edit or read a stored document is left to each integration: bind a headless
editor to a Yjs state, wait for the layout record, run one edit, collect the
updates it writes (including the ones opening the document writes, which the
edit can build on), merge them, check their roots, and dispose of the
editor, the binding and the document without leaking listeners.

This adds a new entry, @lexical/y/headless, with three plain functions
(all @experimental):

  • seedYState(config, $build) writes $build's content into an empty root
    through the binding's initialize(): a client id derived from the content
    (53 bits under 'uint53', 32 under 'uint32'), outside any undo history.
    Identical content gives identical bytes, so two seeds merge into one copy,
    and so do a seed and a client's initialization of the same content in
    the same configuration without BlockIdExtension (with it, a client
    names the blocks of its initial content by position and a seed names
    them with generateId, so the two merge only when the content gives its
    blocks fixed ids; content with random parts, such as drawn block ids, is
    not identical either). It takes no writer (below): the client id derived
    from the content is what makes identical seeds merge.
    The state is garbage collected, as clients store a document, and holds
    only the layout root, so it is also how a converter moves
    a @lexical/yjs document: seed the content an editor read from it and
    merge the seed into the stored document, next to the old root. It is the
    one documented way to seed or convert a document.
  • editYState(state, config, $edit, {writer, allowedRoots, transact, tag})
    runs $edit in one discrete update on the document at state, written
    as writer (required, see Writers below), commits the
    updates it made listeners schedule (an extension giving new blocks ids;
    without this they were lost when the editor was disposed), and returns
    {update, state, warnings, clientID}: one merged update of everything
    written (or null when nothing changed), the state with it applied,
    garbage collected as clients and Yjs servers store a document (also when
    nothing changed), and the client id the edit wrote under. The update is
    refused unless every root it writes to is allowed (default: the layout
    root); transact(doc) writes other shared types (an activity log) into
    the same update (it only writes: an update it applies to the document is
    refused, 'imported-items', as its items would be returned as the
    edit's). A tag with which the binding writes nothing
    (COLLABORATION_TAG, SKIP_COLLAB_TAG) is refused before the edit runs
    ('ignored-tag'), rather than returning update: null as if the edit
    had changed nothing. Whatever $edit throws is rethrown as it is, after
    Lexical has restored the previous state, and nothing is written:
    transact does not run. That holds for any thrown value, not only an
    Error of the server's own realm: Lexical passes only those to the
    editor's onError and drops anything else (a string, a plain object, an
    Error from another realm such as a vm context), which would otherwise
    make a failed edit look like one that changed nothing. The helpers catch
    the value inside the update themselves.
  • createYWriter(author) makes the writer editYState requires: who the
    server's edits are by, and the client ids it writes under.
  • createYDoc(state?) returns a Y.Doc for a relay or a server that loads
    a stored state: Yjs's format cleanup turned off (cleanupFormatting = false), as on the clients, with state applied when given.
  • readYState(state, config, $read) returns what $read reads. What
    opening the document writes (a value an extension assigns on open) is
    read but not stored, so such values can differ between reads; the docs
    tell servers to store the update of a no-op editYState once first.
    BlockIdExtension assigns nothing on open: a block stored without an id,
    or with an id an earlier block stores or derives, reads the id [lexical][lexical-devtools][lexical-extension][lexical-list][lexical-website][lexical-y][lexical-yjs] Feature: @lexical/y, an experimental Yjs 14 collaboration binding #9400
    derives from its Yjs identity, the same in every read, and the next edit
    of that block stores it.
  • YHeadlessError with a code: 'not-initialized', 'read-only' (a
    newer layout, unknown node types, or a named slot the document cannot
    store, which the binding refuses to write: seedYState and editYState
    then throw instead of returning a state without it; the error's
    warnings are the binding's typed warnings that say why, and its message
    is short), 'foreign-roots', 'imported-items', 'ignored-tag'.

config is the editor (extensions, built with buildEditorFromExtensions,
or nodes), the root name, clientIDRange ('uint32' for yrs before
0.28), onWarn and selfCheck.

Writers. Opening a new Y.Doc for each call meant every server edit wrote
under a new random client id, and a document keeps every client id that
ever wrote to it: in its state vector, which every sync sends, and in the
bookkeeping Yjs does each time it loads the document. After 3,000
one-character edits through editYState, a document that one client would
store in 3,763 bytes with a 21-byte state vector was 96,364 bytes with a
26,828-byte state vector and 3,001 client ids, and the next call took 25 ms
against 1.1 ms. editYState now requires writer:

  • a writer from createYWriter(author), created once per agent or
    integration per process: it continues one client id per document it
    edits, so the same 3,000 edits leave 2 client ids (the seed's and the
    writer's), 3,763 bytes and a 21-byte state vector, at a flat 1 to 1.5 ms
    per call;
  • null: a new anonymous client id for this edit alone (the previous
    behaviour, now a decision the call makes).

The writer is required in the type (writer: YWriter | null in a required
options object), so a call that does not decide does not compile, and a
caller without types (JavaScript, a cast) gets a TypeError that says what
to pass. YWriter is branded: its phantom key is named
createdByCreateYWriter, so tsc's message for a writer written by hand
reads as the fix. In Flow it is opaque.

The writer carries an author, not a client id. Two writes under one client
id from different states give two different items the same id, and Yjs
cannot tell them apart: each peer keeps the one it received first, and the
document diverges with no error (a test shows it). A client id the caller
chooses is exactly the value that two replicas, a restart overlapping an
instance that is still draining, or an edit run on an older read would
share, with nothing to notice it. So a writer never takes a client id: it
draws its own at random, as every Yjs client does (in the config's
clientIDRange, and never one a call in progress writes under), and
continues one only from its tip, on a state whose clock for that id is the
clock its last returned update under it reached, and never in a call made
while another call writes under it. Every write under an id then extends the one chain of
writes under it, which nothing else writes to, across documents too: each
document gets an id of its own, so two documents seeded from the same
template and edited the same way never share one. On any other state the
edit is written under a new client id. When the state holds the writer's
id short of its tip, or a call in progress writes under it, a
'@lexical/y/writer-new-client-id' warning (WRITER_NEW_CLIENT_ID_WARNING)
names the fix and its data.reason says why:
'stale-state' (the state was read before the writer's last update there,
or that update was never stored), 'busy' (a call made from inside another
call with the writer), 'range' (the writer's id does not fit 'uint32')
or 'foreign-writes' (something else wrote under the writer's id; the
writer never uses it again). A state that holds none of the writer's ids
gets a new one without a warning: the writer cannot tell it from another
document. An edit that throws or is refused does not move the writer on. A
writer remembers up to 10,000 client ids (about one per document it edits);
a document whose id it forgot gets a new one on its next edit. The author
is not written into documents: writer.author and the
result's clientID feed the app's attribution, either a registry of client
ids written with transact (where doc.clientID is the edit's client id)
or Yjs 14 attributions built from the update
(createContentIdsFromUpdate, createContentMapFromContentIds). The
result's clientID is the id the edit wrote under, read before transact
runs, and the update holds only the edit's own items: transact applying
another update refuses the edit ('imported-items'). An app credits a seed
by the client ids in its state vector: the content-derived one, plus the
temporary document's own when a listener writes once the content is read.

Warnings are LexicalWarnings (from lexical): the headless editor's own
onWarn collects every warning into the result's warnings: LexicalWarning[] and passes each to the optional config.onWarn too
(default: console.warn outside production). The codes are the binding's
('@lexical/y/unsupported-layout', '@lexical/y/self-check' and the others
@lexical/y exports constants for) plus three of the helpers' own, exported
from @lexical/y/headless (core keeps no list of codes; the entry's
YHeadlessWarningCode type is the union of all of them):

  • EDITOR_WARNING ('@lexical/y/editor-warning'): a warning the editor
    reported through its onWarn that is not a LexicalWarning (Lexical or
    an extension), wrapped with the original in data.error;
  • FOLLOW_UPS_EXHAUSTED_WARNING ('@lexical/y/follow-ups-exhausted'): the
    edit's listeners kept scheduling updates; after 8 follow-up updates the
    rest are not committed and are not part of the result (previously this was
    silent). Once the binding writes (an edit, or the read of a seed it has
    written), an update that changes content
    and is made after a commit in the same task, as a listener's is, commits
    at once, so Lexical's own guard stops such a listener first, reported as
    an EDITOR_WARNING;
  • WRITER_NEW_CLIENT_ID_WARNING ('@lexical/y/writer-new-client-id'): a
    writer could not continue its client id on the state it was given, so the
    edit was written under a new one (see Writers above).

The refusals' messages name their fix: 'ignored-tag' says to remove the
tag from options.tag, 'foreign-roots' names options.allowedRoots and
says that it replaces the default (so the layout root goes in the list too),
or, for items whose parents are in neither the update nor the state, to pass
the complete stored state, 'imported-items' says to apply other updates to
the app's own copy and use transact only to write, 'not-initialized'
names seedYState, and 'follow-ups-exhausted' says to have the listener
write only what is missing (a counter or a timestamp per commit never
settles).

The headless functions never throw for a warning, because a warning must
never refuse an edit, in development or production; a config.onWarn that
throws does not refuse it either (its error is rethrown in a microtask). The
self-check is off unless selfCheck: true.

Stored state is compacted. Clients, y-websocket and Hocuspocus persist the
encodeStateAsUpdate of a garbage-collected Y.Doc, where deleted content
keeps only its tombstones. The headless editor's temporary document does not
garbage collect, only so that the root check can resolve the deleted items
an update refers to; returning mergeUpdates([state, update]) from it kept
every deleted character in storage forever. The root check still runs on
that uncompacted document; the returned state (of editYState and
seedYState) is then encoded from a garbage-collected copy. The update
sent to clients is unchanged, and there is no gc option (no use needs
uncompacted state).

The documents that load a state (the headless editor's and the one that
compacts the returned state) do not run Yjs's format cleanup
(cleanupFormatting = false), as the binding's clients do not. Otherwise
the returned state lost format items that the clients keep (Yjs deletes the
format items around deleted text when it applies a remote update), so it
was not state with update applied: once someone typed there, the stored
document read differently from the clients, and a client that later synced
with it changed the formatting of what that user typed. A relay or server
that loads a stored state into a Doc of its own needs the same, and that
rule was docs only (doc.cleanupFormatting = false in y.md): a relay that
missed it stored a document that read differently from the clients.
createYDoc(state) now makes such a document (compactState uses it too),
and the docs' relay sample (y.md Servers, y-server.md) and conversion
sample use it.

The headless editor configures BlockIdExtension the way
YCollabExtension configures it on the clients (repairTransforms: false,
declared as a peer dependency), so the update that names blocks runs no
transforms on the server either.

Each call releases its editor and document before it returns. Before, a
synchronous loop of calls held every document it opened until it yielded:
Lexical keeps an editor until a commit it scheduled in a microtask runs (the
binding's start schedules one), and the editor kept the document through
the scope of its error handler and through the stack of an abort reason
created when it is disposed. Now the handlers live in a scope of their
own, dispose clears what it releases, and the disposed editor is left with
an empty paragraph. (#9400's binding makes the microtask that clears its
"committed in this task" flag outside its update listener, so that
microtask does not keep a disposed binding and its document either.) 20
synchronous reads and 20 edits of a 1,000-paragraph document went from +35
MB and +71 MB of heap to +2 and +3 MB.

The server API is plain functions only. The headless editor itself
(openHeadlessYEditor, OpenedHeadlessYEditor) stays internal: the three
functions cover seeding, editing and reading, and nothing public needs a
handle (Source.test.ts pins the entry's exports to seedYState,
editYState, readYState, createYWriter, createYDoc, YHeadlessError and the three
warning codes EDITOR_WARNING, FOLLOW_UPS_EXHAUSTED_WARNING and
WRITER_NEW_CLIENT_ID_WARNING). Exposing it later is
additive. The root check of editYState uses an internal helper (the roots
an update writes to); there is no @lexical/y/server entry.

Opening a document releases everything it registered when it fails: the
editor and its extensions, the binding and the temporary document are
disposed when the state does not decode (bytes that are not a Yjs update),
the binding throws, or the document is read only here.

A 'read-only' YHeadlessError carries the binding's warnings that say why
as data, error.warnings: readonly YWarning[] (#9400's typed warnings:
narrow on code, then on data.reason), and a short message with no
package name (the document is read only here, or the change was not written when the binding refused the edit's change). It used to start with
@lexical/y: and embed the warnings' messages, which an app could only show
or parse. The other codes' errors have no warnings (warnings is empty).

YBinding.flushPending(), which the helpers call to run the binding's
pending updates at once, is private in its type (a type-only modifier), so
the published declarations do not offer it (private flushPending; in the
built Binding.d.ts); the helpers reach it through an internal interface.
Nothing changes at run time.

The new entry imports @lexical/y as an external sibling, so the binding is
not bundled twice. The package's package.json keeps no main or module
(#9400 sets neither), like the other multi-entry packages:
pnpm run update-version rewrites a package that has main to one export,
which would drop ./headless. Flow libdef
flow/LexicalYHeadless.js.flow; .flowconfig and the tsconfig paths are
regenerated (update-flowconfig, update-tsconfig).

Docs: a website page, Collaboration > Server-side editing with
@lexical/y (the API, errors and warnings, and the server patterns: store
what opening writes, edits by agents and tools, one writer per document,
converting a @lexical/yjs document with seedYState), linked from the @lexical/y page, whose
servers section covers old clients (they write other roots, so no check is
needed) and yrs compatibility. The @lexical/y page and the README point to
seedYState for seeding and conversion, and the page's "Changing the layout
and migrating" section (which replaces "Upgrading from @lexical/yjs")
explains the frozen wire format, what keeps the layout and what bumps
LAYOUT_VERSION, field changes, and the steps (with a diagram and a sample)
to reseed a room from Lexical JSON, an @lexical/y room or a @lexical/yjs
room. The page's layout text follows #9400's layout record: a room records
the versions it needs (lexical-y:<n>: true, a record that only grows), and
a newer @lexical/y adds its version only when it first writes something
that needs it. The server page says that stored state is compacted like
the clients' copies and that the root check runs on the edit's own
uncompacted copy, and the code says why the temporary document does not
garbage collect. "Edits by agents and tools" applies #9400's "Edits made by
code (agents, tools)" section of the @lexical/y page to editYState:
edit text in place (spliceText) rather than replacing blocks, and run the
edit on the state the agent read, then merge the returned update into the
latest stored state (not the returned state). The @lexical/y page's
section links to it. The server page also covers the 'ignored-tag'
refusal, the states returned when nothing changed (compacted too), the
format cleanup the helpers turn off (and that a server loading a stored
state into a Doc of its own should too), and that each call releases its
editor and document. Its Writers section covers createYWriter, null
and what it costs, the reasons for a new client id with the fix for each,
attribution (a registry of client ids, or Yjs attributions built from the
update) and seeds; it also says that allowedRoots replaces the default,
and that with BlockIdExtension a seed and a client's initialization of
the same content do not merge unless the blocks have fixed ids. "One writer
per document" is now "One edit at a time per document", and the samples
pass a writer. The @lexical/y page's limits gain "Client ids add up".

lexical and @lexical/yjs are untouched.

New tests: Headless.test.ts (round trip; identical seeds merge; a seed
holding a list item with text beside its nested list is stored normalized
(the nested list in an item of its own) and merges with a client's
initialization of the same content into one copy; no-op
edits; a throwing edit writes nothing; anything an edit throws (a string,
a plain object, an Error from another realm, an Error) is rethrown as
the same value and transact does not run; a state that is not a Yjs
update releases what opening registered (an extension's registration is
released and the temporary document destroyed, for editYState,
readYState and the internal handle); a server edit merging with two
offline peers' edits, delivered before and after the peers sync; an edit to
a line a peer is typing in, replacing a word and turning the line into a
heading, keeps the peer's text; a foreign root is refused and an allowed
one goes through; 'uint32' keeps every struct's client id in 32 bits; a
newer layout is refused by every entry point with the binding's reason and
an 'unsupported-layout' warning (the document records lexical-y:2); the stored state is garbage collected
(the text an edit deleted is not in it, though it is in
mergeUpdates([state, update]), and a garbage-collected document encodes
it unchanged) while the update is not; an empty state is 'not-initialized';
after dispose, the editor and the document (including the ones that compact
the returned states) have exactly the listeners a bare editor and a bare
document have; with an extension that gives blocks
random ids from an update listener, an edit's update includes the new
block's id, a document stored without ids reads different ids each time
until the update of a no-op edit is stored, and then reads agree; warnings
are structured, reported, returned and do not refuse the edit, also with
NODE_ENV=production, and go to console.warn without onWarn; a warning
that is not a LexicalWarning is wrapped and a LexicalWarning passed
through; an onWarn that throws does not refuse the edit; a listener
that never stops scheduling updates gives 'follow-ups-exhausted' when
seeding (once for opening, once for the content), then, once the seed is
written and read back, Lexical's own guard (an EDITOR_WARNING); when
editing, the binding
writes, so each update the listener schedules after a commit commits at once
and Lexical's own guard stops the
listener (an EDITOR_WARNING, "endlessly enqueueing", once for opening and
once for the edit), while the edit still goes through; whatever the
binding still has to do after an edit (an item added at a list's front) is
done before the helper returns, and nothing commits or writes after it; the
returned state keeps the format items the clients keep (a peer bolds text
another deletes; after a server edit elsewhere, the stored state with what
a peer then types reads as the clients do; both client id orders); the
state of an edit with no change is compacted too; an edit tagged
COLLABORATION_TAG or SKIP_COLLAB_TAG is refused before it runs; the
headless editor's BlockIdExtension has repairTransforms: false, as a
client's, so seeding and editing with it write without an
'unsupported-config' warning; 20 synchronous reads and 20 edits of a 1,000-paragraph document
leave less than 10 MB of heap behind; a seed of an
old editor's content merged into a document whose @lexical/yjs root has
content converts it and leaves the old root as it was),
HeadlessScale.test.ts (10,000 paragraphs), HeadlessSlots.test.ts
(named slots: a seed keeps them and readYState reads them; an edit in a
slot merges with a client typing in the same slot; an edit that adds,
replaces and removes slots; block ids inside slots stored by the seed; a
slot on a line refused by editYState and by seedYState with
'read-only' and the 'unsupported-slots' warning), and relay round trips in
YrsCompat.test.ts (seed, a peer typing, a server edit and a reconnect
through ywasm 0.23.5 and 0.28 relays; with 53-bit server ids a 0.23 relay
makes a peer that also got the update directly show it twice; a writer
keeps its 32-bit client id over three edits through either relay).
HeadlessWriter.test.ts: a call without a writer is refused by the type
(@ts-expect-error for no options, {}, undefined, a hand-written
writer and a number) and, for callers without types, at run time with the
fix in the message; 3,000 edits with a writer keep one client id, a state
as small as one client's and a flat per-call cost; writer: null gives
each edit a new client id, and its update inserts under the result's
clientID; a writer continues only on a state that holds its last update,
and on an older state writes under a new id with a 'stale-state'
warning, every delivery order converging (a control shows the same edits
forced under one id diverging); a call made inside another call with the
same writer gets its own id ('busy'), also when its random draw repeats
the new id the outer call is writing under; an update applied inside
transact refuses the edit ('imported-items') and leaves the writer as it
was; a writer that continues its id writes new segment keys (two adjacent
token nodes it adds in two edits stay apart); one writer keeps one id per
document, also for two documents seeded from the same template; an edit
that throws or is refused (foreign roots, not initialized, read only) does
not move the writer on; an id drawn and never written is reused; a
'uint32' config gets 32-bit ids ('range'); writes under a writer's id
that it did not make stop it using that id ('foreign-writes'); a writer
remembers a bounded number of ids; attribution: the update inserts under
the result's clientID alone, a registry entry written with transact
credits it, and Yjs 14 attributions render the edited text as the writer's
author, built from the registry or from the update alone; a seed holds
one client id, the same for the same content, and a second one when a
listener sets a value once the content is read. createYDoc: a relay
document keeps the format items the clients keep where a plain Y.Doc
drops them (both client id orders), and what it stores reads as the clients
do once someone types bold text there; without a state it is empty, and a
state that does not load throws. A read-only refusal carries the binding's
typed warning (error.warnings, narrowed on code and data.reason) and
a short message, also for a refused slot; Source.test.ts checks that
YBinding's type does not offer flushPending. The Flow test rejects the
same six calls. The memory test runs edits with a writer as well (with a
30 s limit: its 60 calls on a 1,000-paragraph document take about 2 s, and
went past vitest's default 5 s when the whole suite ran at once), and the
refusal tests check that each message names its fix.

$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Headless.test.ts packages/lexical-y/src/__tests__/unit/HeadlessScale.test.ts packages/lexical-y/src/__tests__/unit/YrsCompat.test.ts
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/Headless.test.ts
Error: Cannot find module '../../headless' imported from .../packages/lexical-y/src/__tests__/unit/Headless.test.ts
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/HeadlessScale.test.ts
Error: Cannot find module '../../headless' imported from .../packages/lexical-y/src/__tests__/unit/HeadlessScale.test.ts
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/YrsCompat.test.ts
Error: Cannot find module '../../headless' imported from .../packages/lexical-y/src/__tests__/unit/YrsCompat.test.ts
 Test Files  3 failed (3)
      Tests  no tests

The garbage-collected state, against the previous revision of this change
(state from mergeUpdates([state, update]) of the non-collecting
document), with this revision's tests:

$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Headless.test.ts
 × the stored state is garbage collected; the update is not
   AssertionError: expected true to be false     # the deleted text is in the stored state
 × dispose leaves no listeners on the editor or the document
   AssertionError: expected 5 to be 7            # no compacting documents yet
      Tests  2 failed | 17 passed (19)

The two fixes of the previous review round (release on a failed open; any
thrown value is rethrown and nothing is written), against the revision
before it of
HeadlessEditor.ts, with this revision's tests:

$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Headless.test.ts -t 'rethrown|releases'
 ✓ an error thrown by the edit is rethrown and nothing is returned
 × anything the edit throws is rethrown, and nothing is written
   AssertionError: expected null to be 'a string'   # a thrown string was swallowed; the edit returned
 × a state that fails to open releases what opening registered
   AssertionError: expected +0 to be 3               # no temporary document destroyed
      Tests  2 failed | 1 passed | 18 skipped (21)

The fixes of the previous revision (the returned state's format items, the state
of an edit with no change, refused tags, the block id configuration,
releasing what each call opened), against the previous revision of
headless.ts and HeadlessEditor.ts, with this revision's tests:

$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Headless.test.ts
 × the state an edit with no change returns is compacted too
   AssertionError: expected Uint8Array[ … ] to deeply equal Uint8Array[ … ]   # the input state, uncompacted
 × the returned state keeps the format items the clients keep (2 of 2 orders)
   AssertionError: expected [] to deeply equal [ 'f:bold=true', 'f:bold=null' ]
 × an edit tagged as remote or skipped is refused
   Error: expected a YHeadlessError                # update: null, as if nothing changed
 × block ids are configured as on the clients
   AssertionError: expected true to be false       # repairTransforms
 × a synchronous loop of calls holds no document it opened
   AssertionError: expected 70661088 to be less than 10000000
      Tests  6 failed | 22 passed (28)

The writer and the messages of this revision, against the previous
revision of headless.ts and HeadlessEditor.ts (and no Writer.ts),
with this revision's tests:

$ pnpm run tsc-test
packages/lexical-y/src/__tests__/unit/HeadlessWriter.test.ts(29,3): error TS2305: Module '"../../headless"' has no exported member 'createYWriter'.
packages/lexical-y/src/__tests__/unit/HeadlessWriter.test.ts(37,28): error TS2307: Cannot find module '../../internal/Writer' or its corresponding type declarations.
packages/lexical-y/src/__tests__/unit/HeadlessWriter.test.ts(120,7): error TS2578: Unused '@ts-expect-error' directive.   # a call without options compiled
packages/lexical-y/src/__tests__/unit/HeadlessWriter.test.ts(124,7): error TS2578: Unused '@ts-expect-error' directive.   # and one with {} too
packages/lexical-y/src/__tests__/unit/HeadlessWriter.test.ts(176,22): error TS2339: Property 'clientID' does not exist on type 'EditYStateResult'.
...                                                 # 138 more of these kinds: no `writer` option, no `clientID`
$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/HeadlessWriter.test.ts packages/lexical-y/src/__tests__/unit/Headless.test.ts
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/HeadlessWriter.test.ts
Error: Cannot find module '../../internal/Writer' imported from .../HeadlessWriter.test.ts
 × an edit tagged as remote or skipped is refused
   AssertionError: expected '@lexical/y: the binding does not writ…' to match /; remove it from options\.tag /
 × a synchronous loop of calls holds no document it opened
   TypeError: createYWriter is not a function
 × an update to a root that is not allowed is refused
   AssertionError: expected '@lexical/y: the update writes outside…' to be '@lexical/y: the update writes outside…'
 × an empty state is not initialized
   AssertionError: expected '@lexical/y: the state has no layout r…' to contain 'with seedYState(config, $build)'
 × listeners that never stop scheduling updates are reported
   AssertionError: expected '@lexical/y: listeners kept scheduling…' to contain 'have it write only what is missing, v…'
 Test Files  2 failed (2)
      Tests  5 failed | 24 passed (29)

The typed read-only error, createYDoc and the hidden flushPending of
this revision, against the previous revision of headless.ts,
HeadlessEditor.ts and Binding.ts (on #9400 round 37), with this
revision's tests:

$ pnpm run tsc-test
packages/lexical-y/src/__tests__/unit/Headless.test.ts(51,3): error TS2305: Module '"../../headless"' has no exported member 'createYDoc'.
packages/lexical-y/src/__tests__/unit/Headless.test.ts(844,15): error TS2339: Property 'warnings' does not exist on type 'YHeadlessError'.
packages/lexical-y/src/__tests__/unit/Headless.test.ts(844,28): error TS7006: Parameter 'warning' implicitly has an 'any' type.
packages/lexical-y/src/__tests__/unit/Headless.test.ts(856,31): error TS2339: Property 'warnings' does not exist on type 'YHeadlessError'.
packages/lexical-y/src/__tests__/unit/Headless.test.ts(1115,20): error TS2339: Property 'warnings' does not exist on type 'YHeadlessError'.
packages/lexical-y/src/__tests__/unit/HeadlessSlots.test.ts(209,38): error TS2339: Property 'warnings' does not exist on type 'YHeadlessError'.
packages/lexical-y/src/__tests__/unit/Source.test.ts(96,9): error TS2322: Type 'false' is not assignable to type 'true'.
$ npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Headless.test.ts packages/lexical-y/src/__tests__/unit/HeadlessSlots.test.ts packages/lexical-y/src/__tests__/unit/Source.test.ts
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/Headless.test.ts > @lexical/y/headless > createYDoc gives a relay the format items the clients keep (1,2)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/Headless.test.ts > @lexical/y/headless > createYDoc gives a relay the format items the clients keep (2,1)
TypeError: createYDoc is not a function
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/Headless.test.ts > @lexical/y/headless > createYDoc without a state is an empty document; a state that does not load throws
TypeError: createYDoc is not a function
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/Headless.test.ts > @lexical/y/headless > a document with a newer layout is read only and refused
AssertionError: expected '@lexical/y: the document is read only…' to be 'the document is read only here' // Object.is equality
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/Headless.test.ts > @lexical/y/headless > warnings are reported and never refuse an edit
AssertionError: expected undefined to deeply equal [ …(1) ]
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/HeadlessSlots.test.ts > named slots, headless > an edit with a slot on a line is refused (read-only), with the warning
AssertionError: expected '@lexical/y: the change was not writte…' to be 'the change was not written' // Object.is equality
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/Source.test.ts > public entries
AssertionError: expected [ 'EDITOR_WARNING', …(7) ] to deeply equal [ 'EDITOR_WARNING', …(8) ]
 Test Files  3 failed (3)
      Tests  7 failed | 34 passed (41)
$ npx vitest --project unit --no-watch --reporter=verbose packages/lexical-y/src/__tests__/unit/Headless.test.ts packages/lexical-y/src/__tests__/unit/HeadlessWriter.test.ts packages/lexical-y/src/__tests__/unit/HeadlessScale.test.ts packages/lexical-y/src/__tests__/unit/YrsCompat.test.ts
 ✓ Headless.test.ts > seed, edit and read round trip
 ✓ Headless.test.ts > the stored state is garbage collected; the update is not
 ✓ Headless.test.ts > identical seeds give the same bytes and merge into one copy
 ✓ Headless.test.ts > a seed is normalized, and merges with a client's seed of the same content into one copy
 ✓ Headless.test.ts > an edit with no change returns no update
 ✓ Headless.test.ts > the state an edit with no change returns is compacted too
 ✓ Headless.test.ts > the returned state keeps the format items the clients keep (1,2)
 ✓ Headless.test.ts > the returned state keeps the format items the clients keep (2,1)
 ✓ Headless.test.ts > createYDoc gives a relay the format items the clients keep (1,2)
 ✓ Headless.test.ts > createYDoc gives a relay the format items the clients keep (2,1)
 ✓ Headless.test.ts > createYDoc without a state is an empty document; a state that does not load throws
 ✓ Headless.test.ts > an edit tagged as remote or skipped is refused
 ✓ Headless.test.ts > block ids are configured as on the clients
 ✓ Headless.test.ts > a synchronous loop of calls holds no document it opened
 ✓ Headless.test.ts > an error thrown by the edit is rethrown and nothing is returned
 ✓ Headless.test.ts > anything the edit throws is rethrown, and nothing is written
 ✓ Headless.test.ts > a state that fails to open releases what opening registered
 ✓ Headless.test.ts > a server edit merges with concurrent peer edits (server first)
 ✓ Headless.test.ts > a server edit merges with concurrent peer edits (peers first)
 ✓ Headless.test.ts > an edit to a block a peer is typing in keeps their text
 ✓ Headless.test.ts > an update to a root that is not allowed is refused
 ✓ Headless.test.ts > clientIDRange 'uint32' keeps every client id in 32 bits
 ✓ Headless.test.ts > a document with a newer layout is read only and refused
 ✓ Headless.test.ts > an empty state is not initialized
 ✓ Headless.test.ts > dispose leaves no listeners on the editor or the document
 ✓ Headless.test.ts > updates scheduled by an edit are part of its update
 ✓ Headless.test.ts > values assigned on open are stored by a no-op edit, not by a read
 ✓ Headless.test.ts > warnings are reported and never refuse an edit
 ✓ Headless.test.ts > the binding's own updates are part of the edit, not left for later
 ✓ Headless.test.ts > listeners that never stop scheduling updates are reported
 ✓ Headless.test.ts > a seed merged next to an older layout converts the document
 ✓ Headless.test.ts > extensions define the editor
 ✓ HeadlessWriter.test.ts > every call decides who it writes as
 ✓ HeadlessWriter.test.ts > 3,000 edits with a writer keep one client id: the state stays small and each call costs the same
 ✓ HeadlessWriter.test.ts > writer: null keeps a new anonymous client id per edit
 ✓ HeadlessWriter.test.ts > a writer continues its client id only on a state that holds its last update
 ✓ HeadlessWriter.test.ts > a call made inside another call with the same writer gets its own client id
 ✓ HeadlessWriter.test.ts > a call made inside another call never draws the client id the outer call is writing under
 ✓ HeadlessWriter.test.ts > an update applied inside transact refuses the edit: its items would be credited to the writer
 ✓ HeadlessWriter.test.ts > a writer that continues its client id writes new segment keys: adjacent token nodes stay apart
 ✓ HeadlessWriter.test.ts > one writer keeps one client id per document
 ✓ HeadlessWriter.test.ts > an edit that throws, or is refused, does not move the writer on
 ✓ HeadlessWriter.test.ts > a client id the writer drew and wrote nothing under is used for the next document
 ✓ HeadlessWriter.test.ts > a writer used with clientIDRange uint32 writes under 32-bit client ids
 ✓ HeadlessWriter.test.ts > writes under a writer client id that the writer did not make stop it using that id
 ✓ HeadlessWriter.test.ts > a writer remembers a bounded number of client ids
 ✓ HeadlessWriter.test.ts > attribution: the update is the writer client id alone, and Yjs attributions credit its author
 ✓ HeadlessWriter.test.ts > a seed is credited by the client ids in its state vector: one, unless a listener writes once the content is read
 ✓ YrsCompat.test.ts > @lexical/y with yrs relays > yrs 0.23 duplicates the content of a 53-bit client on reconnect
 ✓ YrsCompat.test.ts > @lexical/y with yrs relays > yrs 0.23 with clientIDRange uint32: no duplication
 ✓ YrsCompat.test.ts > @lexical/y with yrs relays > yrs 0.28 handles 53-bit client ids
 ✓ YrsCompat.test.ts > @lexical/y with yrs relays > uint32 range survives Yjs drawing a new client id
 ✓ YrsCompat.test.ts > @lexical/y/headless with yrs relays > ywasm 0.23 relay round trip, 32-bit ids
 ✓ YrsCompat.test.ts > @lexical/y/headless with yrs relays > ywasm 0.23 relay round trip, 32-bit ids, update also sent directly
 ✓ YrsCompat.test.ts > @lexical/y/headless with yrs relays > ywasm 0.28 relay round trip, 32-bit ids
 ✓ YrsCompat.test.ts > @lexical/y/headless with yrs relays > ywasm 0.28 relay round trip, 32-bit ids, update also sent directly
 ✓ YrsCompat.test.ts > @lexical/y/headless with yrs relays > a writer continues its 32-bit client id on a ywasm 0.23 relay's state
 ✓ YrsCompat.test.ts > @lexical/y/headless with yrs relays > a writer continues its 32-bit client id on a ywasm 0.28 relay's state
 ✓ YrsCompat.test.ts > @lexical/y/headless with yrs relays > ywasm 0.28 relay round trip, 53-bit ids
 ✓ YrsCompat.test.ts > @lexical/y/headless with yrs relays > ywasm 0.23 relay with 53-bit server ids duplicates a direct update
 ✓ HeadlessScale.test.ts > @lexical/y/headless at scale > open, edit and dispose a 10,000-block document
 Test Files  4 passed (4)
      Tests  61 passed (61)

3,000 one-character edits on a 20-line seed, each on the state the last
one returned (Node 24, development build, self-check off; the last column
is the median of 21 more calls on the final state):

                     state     state vector   client ids   3,000 edits   next call
writer               3,763 B   21 B           2            3.6 s         1.1 ms
writer: null        96,364 B   26,828 B       3,001        38.3 s        25.1 ms
one client (a tab)   3,763 B   21 B           2

(The four existing YrsCompat tests also pass.) Scale, Node 24, development
build (self-check off, the default), 10,000 paragraphs vs 1,000, on this
commit, two runs on a loaded host (disposeMs now includes dropping the
editor's content):

{"big":{"blocks":10000,"disposeMs":6,"editMs":305,"openMs":176,"readMs":194,"seedMs":540,"stateBytes":578013,"updateBytes":71,"writeMs":75},
 "small":{"blocks":1000,"disposeMs":1,"editMs":37,"openMs":18,"readMs":20,"seedMs":62,"stateBytes":56012,"updateBytes":71,"writeMs":8}}
{"big":{"blocks":10000,"disposeMs":6,"editMs":349,"openMs":179,"readMs":189,"seedMs":618,"stateBytes":578013,"updateBytes":71,"writeMs":78},
 "small":{"blocks":1000,"disposeMs":1,"editMs":41,"openMs":18,"readMs":23,"seedMs":71,"stateBytes":56012,"updateBytes":71,"writeMs":7}}

Stored state, before and after the compaction (measured on the previous
base of this PR; a reviewer's re-measure on this base, 100 rewrites of one
paragraph from 316 bytes, gave 23,127 / 23,136 merged and 4,208 / 4,194
compacted; a scratch harness, not committed: uint32 ids, sources under vitest). An agent rewrites one
paragraph of a two-paragraph document 100 times through editYState, each
time with a different ~200-character text; the returned state is stored
and passed to the next edit. Two runs each:

stored bytes after   0     25      50      75      100 rewrites
before (merged)      172   6,011   11,860  17,708  23,555
                     172   6,002   11,846  17,710  23,559
after (compacted)    172   1,249   2,164   3,074   3,889
                     172   1,239   2,153   3,059   3,874

About 234 B per rewrite before (the deleted text stays) and 37 B after (its
tombstones). Extra edit time: editYState rewriting the middle paragraph of
documents of 1,000 and 10,000 paragraphs, median of the last 7 of 10 edits,
two runs each:

                1,000 paragraphs    10,000 paragraphs
before          25.8 / 29.4 ms      260.9 / 260.7 ms
after           30.1 / 30.6 ms      281.4 / 280.1 ms

That is about +3 ms at 1,000 paragraphs and +20 ms (8%) at 10,000: one
applyUpdate and encodeStateAsUpdate of the state on a collecting
document.

editMs is editYState end to end (open, one edit, root check, merge,
dispose); openMs/writeMs/disposeMs are the phases through an internal
handle.

Property test (a reviewer's scratch harness, not committed): 2–3 human
peers on YCollabExtension with the self-check on, typing, deleting,
splitting, joining, toggling headings and lists, bolding, commenting and
undoing through a relay that delays, batches, reorders and drops them
offline, while agents run editYState on stale stored states (0–50 steps
old) and the returned update is merged into the latest stored state; 60
steps per session, 2,000 sessions per mode. 0 sessions in which the binding
diverged, in each mode: plain, block ids, comments (MarkStateExtension),
comments with block ids, and storing the returned state when the agent
edited the latest state (one writer), plain and with comments. The last two
had 2 + 5 sessions whose stored state read differently from the clients
before the format cleanup fix (seeds 437, 901, 659, 1359, 1379, 1633,
1916); all 7 pass now. Each mode still has 1–3 sessions in which one
client's Doc keeps pending structs whose dependencies it already holds (a
@y/y 14.0.0-rc.29 issue reproduced with Yjs alone, not the binding; the
other clients and the stored state agree).

Also run, on this commit: npx vitest --project unit packages/lexical-y packages/lexical-yjs (148 files, 4,846 tests pass, 16 expected failures, 2
skipped); pnpm run test-unit compared test by test with #9400 (0 failed,
0 changed, 83 added: Headless.test.ts 32, HeadlessWriter.test.ts 16,
build.test.ts 15, YrsCompat.test.ts 8, HeadlessSlots.test.ts 6,
treeShakingSource.test.ts 4, HeadlessScale.test.ts 1, Source.test.ts 1; one #9400 test no longer runs by design: the www
entry stub audit in build.test.ts only checks packages with a single
export, and @lexical/y now has two; the website's
generated stackblitz.test.ts audits are left out of the comparison); pnpm run tsc, tsc-test, tsc-scripts,
tsc-website, tsc-extension, pnpm run flow (0 errors), pnpm run lint,
pnpm run prettier, pnpm run build-prod and the built tree-shaking test
(286 passed), the source tree-shaking test (372 passed;
@lexical/y (packages/lexical-y/src/headless.ts),
internal/HeadlessEditor.ts and internal/Writer.ts retain nothing), and pnpm run build
(LexicalYHeadless.dev.js imports @lexical/y, @y/y, lexical and
@lexical/extension/LexicalBuilder as externals), and the website build
with TypeDoc and the broken link check (pnpm run build-docs).

Not exercised: real browsers, a real network relay (the relays are ywasm
documents in the test process), production builds' timings, and the preview
builds of this commit (pkg.pr.new publishes them when it is pushed).

@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:08pm UTC
lexical-playground Ready Ready Preview Oct 28, 2026 7:08pm 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@9437

@lexical/a11y

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

@lexical/clipboard

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

@lexical/code

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

@lexical/code-core

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

@lexical/code-prism

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

@lexical/code-shiki

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

@lexical/compiler

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

@lexical/devtools-core

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

@lexical/dragon

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

@lexical/eslint-plugin

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

@lexical/extension

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

@lexical/fast-check

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

@lexical/file

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

@lexical/hashtag

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

@lexical/headless

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

@lexical/history

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

@lexical/html

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

@lexical/internal

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

@lexical/link

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

@lexical/list

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

@lexical/mark

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

@lexical/markdown

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

@lexical/mdast

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

@lexical/offset

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

@lexical/overflow

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

@lexical/plain-text

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

@lexical/react

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

@lexical/rich-text

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

@lexical/selection

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

@lexical/table

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

@lexical/tailwind

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

@lexical/text

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

@lexical/utils

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

@lexical/y

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

@lexical/yjs

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

commit: bac67b8

@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-server branch from bffe9c2 to a4a139f Compare October 23, 2026 13:02
@zurfyx
zurfyx changed the base branch from zurfyx/collab-y14-block-markers to zurfyx/collab-y-moves October 23, 2026 13:02
zurfyx added a commit that referenced this pull request Oct 23, 2026
…round, with e2e specs

## Description

Stacked on #9437 (the `@lexical/y` stack: #9400, #9449, #9437).

Current behavior: the playground can run collaboration on `@lexical/yjs` only
(collab v1 with `CollaborationPlugin`, v2 with
`CollaborationPluginV2__EXPERIMENTAL`, chosen with `?isCollab=true` and
`?useCollabV2=true`). The experimental `@lexical/y` binding (Yjs 14, `@y/y`)
cannot be tried in the playground, and the repo's e2e suite does not cover it.

New behavior (opt-in; the default playground, `pnpm run start` and collab
v1/v2 are unchanged):

- `?isCollab=true&useCollabY=true` runs the playground on `@lexical/y`: the
  editor gets `YCollabExtension` with a `@y/y` document and a `@y/websocket`
  provider (`4.0.0-rc.2`, the published Yjs 14 client). The playground pins
  `@y/y` to `14.0.0-rc.29`, the version `@lexical/y` pins, so the lockfile
  holds one `@y/y`. The mode lives in its own chunk (`collaborationY.tsx`,
  loaded with `import()`), so the default playground does not load a second
  Yjs. `HistoryExtension` is left out in this mode (`YCollabExtension`
  provides undo and conflicts with it). The toolbar's connect button connects
  and disconnects the provider; the binding is initialized after the
  provider's first sync; a document whose layout this client does not support
  shows a read-only notice.
- `pnpm run collab:y` starts a Yjs 14 relay on `localhost:1235`
  (`packages/lexical-playground/scripts/collab-y-server.mjs`), and
  `pnpm run start:y` starts it together with the playground dev server.
  `pnpm run start` is unchanged (dev server and the `@lexical/yjs` collab
  server). The published `@y/websocket-server` still depends on the
  pre-`@y/y` Yjs 14 prereleases (`yjs@14.0.0-*`), whose documents are not
  compatible with `@y/y`, so the relay is a small in-memory y-websocket
  protocol server on `@y/y`, `@y/protocols` and `lib0` 1.x, with a test-only
  `/delay` endpoint.
- Playground features the binding does not sync are handled explicitly:
  nested editors (image captions, sticky notes) are read only in this mode
  and "Add Caption" is not offered; comments are off (as in collab v2: the
  comment threads live in a Yjs 13 document); there are no remote cursors.
  Playground nodes without collab declarations use the binding's nested
  storage. Comments keep using MarkNode.
- E2E: a new editor mode, `E2E_EDITOR_MODE=rich-text-with-collab-y`
  (`pnpm run test-e2e-collab-y-{chromium,firefox,webkit}`, against
  `pnpm run start:y`), runs `Collaboration.spec.mjs` and the new
  `CollabY*.spec.mjs`. `Collaboration.spec.mjs` is parameterized: where
  collab v1/v2 drop a peer's text on undo, collab Y asserts that the peer's
  text stays (undo only reverts the client's own changes), and collab Y does
  not restore the selection an undo step was made with, so that test places
  the caret explicitly. The new specs open each client in its own browser
  context (own keyboard), delay the relay's server-to-client messages while
  clients edit at the same time, and end every case by checking that all
  clients converge, that a client loading the document afterwards shows the
  same, that no typed token is lost or duplicated, and that no client logged
  an error or warning (the binding's development self-check reports through
  warnings). They cover: Enter, Backspace and Delete at line boundaries,
  heading/quote toggles and list create/indent/outdent while peers type;
  links while peers type inside and after the link; offline edits on both
  sides (text and structure, and a 30-lines-per-side divergence) and
  reconnect; undo isolation (own typing, Enter and heading undone after peer
  edits, undo while the peer types inside the undone text); the layout
  version gate (a document marked with layout 3, which this client does not
  read, makes open and late-joining clients read only); tables (cell typing,
  concurrent row and column insert stays rectangular, two rows inserted at
  one place); images (synced, no caption offered); and IME composition
  (Chromium, CDP) while a peer types, splits or joins the line.
- CI: a `collab-y-linux` job (Chromium and Firefox) runs the mode the way
  `collab-v2-linux` runs collab v2, starting `pnpm run collab:y` instead of
  `pnpm run collab`.

## Test plan

### Before

```
$ pnpm run collab:y
[ERR_PNPM_NO_SCRIPT] Missing script: collab:y

$ pnpm run start:y
[ERR_PNPM_NO_SCRIPT] Missing script: start:y

$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium | grep -c CollabY
0
```

`?useCollabY=true` is not a playground setting (it is ignored, and
`?isCollab=true` runs collab v1); no playground source imports `@lexical/y`.

### After

```
$ HOST=localhost PORT=1291 node packages/lexical-playground/scripts/collab-y-server.mjs   # what collab:y runs, on a free port
Yjs 14 (@lexical/y) relay running on ws://localhost:1291

$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium
Total: 26 tests in 4 files       # Collaboration 6, CollabYNodes 6, CollabYStructure 8, CollabYSync 6
```

Collab Y mode, development playground build (`pnpm run build-playground-dev`,
served with `vite preview`), relay from `collab-y-server.mjs`, no retries:

```
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=2 --retries=0
  26 passed (1.1m)
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0
  3 skipped  23 passed (1.3m)           # the 3 IME specs are Chromium only
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=webkit --workers=2 --retries=0
  3 skipped  23 passed (1.2m)
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=6 --retries=0 --repeat-each=3
  78 passed (1.3m)                      # previous base revision
```

The version gate spec marks the document with layout 3. Marking it one past
the root's version, as the previous revision of the spec did, writes layout
2 on a new document, which `@lexical/y` reads since block moves (#9449):

```
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium CollabYSync -g 'version gate'
# previous revision of the spec
    Error: expect(received).toBe(expected) // Object.is equality
    Expected: "readonly"
    Received: "active"
  1 failed
# this revision
  1 passed (4.3s)
```

Collab v1/v2 are unchanged:

```
$ E2E_EDITOR_MODE=rich-text-with-collab npx playwright test --project=chromium --workers=2 --retries=0 Collaboration.spec
  6 passed (7.3s)
$ E2E_EDITOR_MODE=rich-text-with-collab-v2 npx playwright test --project=chromium --workers=6 --retries=0 Collaboration.spec
  6 passed (3.8s)                       # previous base revision
```

Also: `pnpm run tsc` (0 errors), `pnpm run flow` (0 errors), eslint and prettier on the touched files,
the tree-shaking tests (`scripts/__tests__/integration/tree-shaking.test.mjs`,
286 tests; `treeShakingSource.test.ts`, 363 tests),
`npx vitest --project unit packages/lexical-playground` (33 files, 390 tests),
`pnpm run build`, and
`pnpm run build-playground-dev` (`@lexical/y` is only in the `collaborationY`
chunk).

Not exercised: the CI workflow itself (run locally only), macOS and
Windows, the production playground build in a browser, and real IME input
(CDP composition events only).
zurfyx added a commit that referenced this pull request Oct 23, 2026
## Description

Stacked on #9438 (the `@lexical/y` stack: #9400, #9449, #9437, #9438).
Depends on #9380 (`MarkStateExtension` and `collab: 'set'` NodeState). This
branch carries that commit as a temporary dependency commit, to be dropped
once #9380 merges.

Current behavior: `@lexical/y` stores each NodeState entry of a text run,
line break or inline node as one `s:<key>` format holding the serialized
value. A set-valued state such as `MarkStateExtension`'s `markIds` is one
array per run, so when two peers comment on the same text concurrently, one
peer's comments win (last writer wins on the whole set).

New behavior:

- On text runs, line breaks and nodes stored as their own Y.Node, a
  set-valued state known for the node type is written as one
  `s:<key>\u001f<member>` format per member (`splitCollabStateEntries`).
  Concurrent additions and removals of different members merge. Reading is
  unchanged: NodeState joins the member entries back into the set (#9380).
  Block markers, wrappers and list groups still store the set whole.
- A peer that does not know the state keeps each member as its own NodeState
  key and writes it back unchanged, so it never collapses the members.
- The self-check's fresh editor gets the set-valued StateConfigs registered
  on the binding's editor, so it reads the members the same way (otherwise
  every write of a set would be reported to the binding's `onWarn` as a
  `'self-check'` warning).
- Tests: the harness takes a `prepare(editor)` hook (run before the binding
  starts; fresh readers reuse it). The fuzz now stores comments as one
  set-valued state, like `MarkStateExtension`; `FUZZ_COMMENTS=keys` keeps
  the previous one-boolean-key-per-id model. `Size.test.ts` budgets three
  `MarkStateExtension` operations.
- Docs: the "Set-valued NodeState" limit in the `@lexical/y` README and on
  the Yjs 14 collaboration page now says where the set is stored per member
  and where it is still one value (line markers, groups, inline wrappers).

Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client
ids), op / undo / redo:

```
                                   one format per id   whole set (before)
add a comment                      83 / 10 / 77        92 / 10 / 86
add an overlapping comment         83 / 10 / 77        196 / 45 / 190
remove one of two comments         12 / 142 / 10       113 / 144 / 113
```

## Test plan

New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers
(ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with
concurrent comments on the same and on overlapping ranges, across a line
break, resolving while a peer types, resolving one of two comments, undo
while a peer types, the stored format keys, and a peer that does not know
the state editing commented text.

### Before

`Schema.ts` and `SelfCheck.ts` reverted to the dependency commit:

```
$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts
 × each id is its own format key (4 of 4 orders)
   AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ]
 × two peers mark the same range (4 of 4 orders)
   AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…'
 × two peers mark overlapping ranges (4 of 4 orders)
 × two peers mark overlapping ranges across a line break
   AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…'
 × keeps each id as its own format when it edits marked text
 × add a comment (MarkStateExtension)
   AssertionError: expected 92 to be less than or equal to 90
 × add an overlapping comment (MarkStateExtension)
   AssertionError: expected 196 to be less than or equal to 90
 × remove a comment (MarkStateExtension)
   AssertionError: expected 113 to be less than or equal to 14
      Tests  17 failed | 40 passed (57)
```

### After

```
$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y packages/lexical-yjs packages/lexical-mark packages/lexical-react/src/__tests__/unit/Collab packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts
 Test Files  75 passed (75)
      Tests  3209 passed | 8 expected fail | 2 skipped (3219)
```

The 8 expected failures are `MarkStateCollab.test.tsx`'s pinned v2 and v1
limits from #9380 (#9381 is not in this stack). The 2 skipped tests are in
`ListsInLines.test.ts` and are skipped on #9400 as well.

Fuzz with comments as one set-valued state, 500 seeds plus 100 gc seeds:

```
$ FUZZ_SEEDS=500 npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/Fuzz.test.ts
 ✓ seeds 1..51 ... ✓ seeds 451..501, ✓ gc seeds 1..51, ✓ gc seeds 51..101
      Tests  12 passed (12)
```

On the whole stack (this commit on top), the same fuzz at 2,000 + 500 gc
seeds, with and without block moves, passes (116 of 116 chunks), and so
does `pnpm run test-unit` (443 files).

Also run: `pnpm run tsc`, `pnpm run flow` (0 errors), eslint and prettier
on the touched files, `pnpm run build`, the tree-shaking tests (source 364
pass, build output 286 pass) and `pnpm run build-docs`.

Not exercised: real Yjs 14 providers and browsers.
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-moves branch from 6919907 to c14c0a2 Compare October 23, 2026 14:50
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-server branch from a4a139f to ee1a527 Compare October 23, 2026 14:50
zurfyx added a commit that referenced this pull request Oct 23, 2026
…round, with e2e specs

## Description

Stacked on #9437 (the `@lexical/y` stack: #9400, #9449, #9437).

Current behavior: the playground can run collaboration on `@lexical/yjs` only
(collab v1 with `CollaborationPlugin`, v2 with
`CollaborationPluginV2__EXPERIMENTAL`, chosen with `?isCollab=true` and
`?useCollabV2=true`). The experimental `@lexical/y` binding (Yjs 14, `@y/y`)
cannot be tried in the playground, and the repo's e2e suite does not cover it.

New behavior (opt-in; the default playground, `pnpm run start` and collab
v1/v2 are unchanged):

- `?isCollab=true&useCollabY=true` runs the playground on `@lexical/y`: the
  editor gets `YCollabExtension` with a `@y/y` document and a `@y/websocket`
  provider (`4.0.0-rc.2`, the published Yjs 14 client). The playground pins
  `@y/y` to `14.0.0-rc.29`, the version `@lexical/y` pins, so the lockfile
  holds one `@y/y`. The mode lives in its own chunk (`collaborationY.tsx`,
  loaded with `import()`), so the default playground does not load a second
  Yjs. `HistoryExtension` is left out in this mode (`YCollabExtension`
  provides undo and conflicts with it). The toolbar's connect button connects
  and disconnects the provider; the binding is initialized after the
  provider's first sync; a document whose layout this client does not support
  shows a read-only notice.
- `pnpm run collab:y` starts a Yjs 14 relay on `localhost:1235`
  (`packages/lexical-playground/scripts/collab-y-server.mjs`), and
  `pnpm run start:y` starts it together with the playground dev server.
  `pnpm run start` is unchanged (dev server and the `@lexical/yjs` collab
  server). The published `@y/websocket-server` still depends on the
  pre-`@y/y` Yjs 14 prereleases (`yjs@14.0.0-*`), whose documents are not
  compatible with `@y/y`, so the relay is a small in-memory y-websocket
  protocol server on `@y/y`, `@y/protocols` and `lib0` 1.x, with a test-only
  `/delay` endpoint.
- Playground features the binding does not sync are handled explicitly:
  nested editors (image captions, sticky notes) are read only in this mode
  and "Add Caption" is not offered; comments are off (as in collab v2: the
  comment threads live in a Yjs 13 document); there are no remote cursors.
  Playground nodes without collab declarations use the binding's nested
  storage. Comments keep using MarkNode.
- E2E: a new editor mode, `E2E_EDITOR_MODE=rich-text-with-collab-y`
  (`pnpm run test-e2e-collab-y-{chromium,firefox,webkit}`, against
  `pnpm run start:y`), runs `Collaboration.spec.mjs` and the new
  `CollabY*.spec.mjs`. `Collaboration.spec.mjs` is parameterized: where
  collab v1/v2 drop a peer's text on undo, collab Y asserts that the peer's
  text stays (undo only reverts the client's own changes), and collab Y does
  not restore the selection an undo step was made with, so that test places
  the caret explicitly. The new specs open each client in its own browser
  context (own keyboard), delay the relay's server-to-client messages while
  clients edit at the same time, and end every case by checking that all
  clients converge, that a client loading the document afterwards shows the
  same, that no typed token is lost or duplicated, and that no client logged
  an error or warning (the binding's development self-check reports through
  warnings). Console messages that are not about the editor are filtered by
  one list in the collab Y spec utilities (the other e2e specs do not read
  the console): failed resource loads, relay reconnects, Vite and React
  DevTools notices, and Firefox's "Loading failed for the <script>" for the
  playground's Vercel analytics scripts (`/_vercel/insights/script.js`,
  `/_vercel/speed-insights/script.js`), which a local or CI build does not
  serve (Chromium and WebKit report the same as "Failed to load resource").
  They cover: Enter, Backspace and Delete at line boundaries,
  heading/quote toggles and list create/indent/outdent while peers type;
  links while peers type inside and after the link; offline edits on both
  sides (text and structure, and a 30-lines-per-side divergence) and
  reconnect; undo isolation (own typing, Enter and heading undone after peer
  edits, undo while the peer types inside the undone text); the layout
  version gate (a document marked with layout 3, which this client does not
  read, makes open and late-joining clients read only); tables (cell typing,
  concurrent row and column insert stays rectangular, two rows inserted at
  one place); images (synced, no caption offered); and IME composition
  (Chromium, CDP) while a peer types, splits or joins the line.
- CI: a `collab-y-linux` job (Chromium and Firefox) runs the mode the way
  `collab-v2-linux` runs collab v2, starting `pnpm run collab:y` instead of
  `pnpm run collab`.

## Test plan

### Before

```
$ pnpm run collab:y
[ERR_PNPM_NO_SCRIPT] Missing script: collab:y

$ pnpm run start:y
[ERR_PNPM_NO_SCRIPT] Missing script: start:y

$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium | grep -c CollabY
0
```

`?useCollabY=true` is not a playground setting (it is ignored, and
`?isCollab=true` runs collab v1); no playground source imports `@lexical/y`.

### After

```
$ HOST=localhost PORT=1291 node packages/lexical-playground/scripts/collab-y-server.mjs   # what collab:y runs, on a free port
Yjs 14 (@lexical/y) relay running on ws://localhost:1291

$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium
Total: 26 tests in 4 files       # Collaboration 6, CollabYNodes 6, CollabYStructure 8, CollabYSync 6
```

Collab Y mode, development playground build (`pnpm run build-playground-dev`,
served with `vite preview`), relay from `collab-y-server.mjs`, no retries:

```
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=2 --retries=0
  26 passed (1.1m)
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0
  3 skipped  23 passed (1.3m)           # the 3 IME specs are Chromium only
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=webkit --workers=2 --retries=0
  3 skipped  23 passed (1.2m)           # previous base revision
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=6 --retries=0 --repeat-each=3
  78 passed (1.3m)                      # previous base revision
```

Firefox without the Vercel scripts (as in CI; the build serves no
`/_vercel/` files), the previous revision of the console filter, then this
one:

```
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0
# previous revision
    Error: console errors or warnings
    + "[F] console.warning: [JavaScript Warning: \"Loading failed for the <script> with source “http://localhost:4471/_vercel/speed-insights/script.js”.\" …]"
  17 failed  3 skipped  6 passed (1.5m)
# this revision
  3 skipped  23 passed (1.3m)
```

The version gate spec marks the document with layout 3. Marking it one past
the root's version, as the previous revision of the spec did, writes layout
2 on a new document, which `@lexical/y` reads since block moves (#9449):

```
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium CollabYSync -g 'version gate'
# previous revision of the spec
    Error: expect(received).toBe(expected) // Object.is equality
    Expected: "readonly"
    Received: "active"
  1 failed
# this revision
  1 passed (4.3s)
```

Collab v1/v2 are unchanged:

```
$ E2E_EDITOR_MODE=rich-text-with-collab npx playwright test --project=chromium --workers=2 --retries=0 Collaboration.spec
  6 passed (7.3s)
$ E2E_EDITOR_MODE=rich-text-with-collab-v2 npx playwright test --project=chromium --workers=6 --retries=0 Collaboration.spec
  6 passed (3.8s)                       # previous base revision
```

Also: `pnpm run tsc` (0 errors), `pnpm run flow` (0 errors), eslint and prettier on the touched files,
the tree-shaking tests (`scripts/__tests__/integration/tree-shaking.test.mjs`,
286 tests; `treeShakingSource.test.ts`, 363 tests),
`npx vitest --project unit packages/lexical-playground` (33 files, 390 tests),
`pnpm run build`, and
`pnpm run build-playground-dev` (`@lexical/y` is only in the `collaborationY`
chunk).

Not exercised: the CI workflow itself (run locally only), macOS and
Windows, the production playground build in a browser, and real IME input
(CDP composition events only).
zurfyx added a commit that referenced this pull request Oct 23, 2026
## Description

Stacked on #9438 (the `@lexical/y` stack: #9400, #9449, #9437, #9438).
Depends on #9380 (`MarkStateExtension` and `collab: 'set'` NodeState). This
branch carries that commit as a temporary dependency commit, to be dropped
once #9380 merges.

Current behavior: `@lexical/y` stores each NodeState entry of a text run,
line break or inline node as one `s:<key>` format holding the serialized
value. A set-valued state such as `MarkStateExtension`'s `markIds` is one
array per run, so when two peers comment on the same text concurrently, one
peer's comments win (last writer wins on the whole set).

New behavior:

- On text runs, line breaks and nodes stored as their own Y.Node, a
  set-valued state known for the node type is written as one
  `s:<key>\u001f<member>` format per member (`splitCollabStateEntries`).
  Concurrent additions and removals of different members merge. Reading is
  unchanged: NodeState joins the member entries back into the set (#9380).
  Block markers, wrappers and list groups still store the set whole.
- A peer that does not know the state keeps each member as its own NodeState
  key and writes it back unchanged, so it never collapses the members.
- The self-check's fresh editor gets the set-valued StateConfigs registered
  on the binding's editor, so it reads the members the same way (otherwise
  every write of a set would be reported to the binding's `onWarn` as a
  `'self-check'` warning).
- Tests: the harness takes a `prepare(editor)` hook (run before the binding
  starts; fresh readers reuse it). The fuzz now stores comments as one
  set-valued state, like `MarkStateExtension`; `FUZZ_COMMENTS=keys` keeps
  the previous one-boolean-key-per-id model. `Size.test.ts` budgets three
  `MarkStateExtension` operations.
- Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page
  says where the set is stored per member and where it is still one value
  (paragraphs and list items, lists, links); the README's wire format adds
  the member entries (`s:<key>\u001f<member>` = `true`); the Comments and
  NodeState pages name `@lexical/y` among the bindings that store members
  separately.

Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client
ids), op / undo / redo:

```
                                   one format per id   whole set (before)
add a comment                      83 / 10 / 77        92 / 10 / 86
add an overlapping comment         83 / 10 / 77        196 / 45 / 190
remove one of two comments         12 / 142 / 10       113 / 144 / 113
```

## Test plan

New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers
(ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with
concurrent comments on the same and on overlapping ranges, across a line
break, resolving while a peer types, resolving one of two comments, undo
while a peer types, the stored format keys, and a peer that does not know
the state editing commented text.

### Before

`Schema.ts` and `SelfCheck.ts` reverted to the dependency commit:

```
$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts
 × each id is its own format key (4 of 4 orders)
   AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ]
 × two peers mark the same range (4 of 4 orders)
   AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…'
 × two peers mark overlapping ranges (4 of 4 orders)
 × two peers mark overlapping ranges across a line break
   AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…'
 × keeps each id as its own format when it edits marked text
 × add a comment (MarkStateExtension)
   AssertionError: expected 92 to be less than or equal to 90
 × add an overlapping comment (MarkStateExtension)
   AssertionError: expected 196 to be less than or equal to 90
 × remove a comment (MarkStateExtension)
   AssertionError: expected 113 to be less than or equal to 14
      Tests  17 failed | 40 passed (57)
```

### After

```
$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y packages/lexical-yjs packages/lexical-mark packages/lexical-react/src/__tests__/unit/Collab packages/lexical/src/__tests__/unit/LexicalNodeState.test.ts
 Test Files  76 passed (76)
      Tests  3256 passed | 8 expected fail | 2 skipped (3266)
```

The 8 expected failures are `MarkStateCollab.test.tsx`'s pinned v2 and v1
limits from #9380 (#9381 is not in this stack). The 2 skipped tests are in
`ListsInLines.test.ts` and are skipped on #9400 as well.

Fuzz with comments as one set-valued state, on the whole stack (this commit
on top), 2,000 seeds plus 500 gc seeds, without and with block moves (25
seeds per test):

```
$ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \
    npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/Fuzz.test.ts
 ✓ @lexical/y fuzz (100)
 ✓ @lexical/y fuzz with block moves (103)
      Tests  203 passed (203)
```

`pnpm run test-unit` on the whole stack: 444 files, 11,999 passed, 3
skipped.

Also run: `pnpm run tsc`, `pnpm run flow` (0 errors), eslint and prettier
on the touched files, `pnpm run build`, the tree-shaking tests (source 364
pass, build output 286 pass) and `pnpm run build-docs`.

Not exercised: real Yjs 14 providers and browsers.
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-moves branch from c14c0a2 to 5fe1a90 Compare October 23, 2026 16:08
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-server branch from ee1a527 to 4d81af9 Compare October 23, 2026 16:08
zurfyx added a commit that referenced this pull request Oct 23, 2026
…round, with e2e specs

## Description

Stacked on #9437 (the `@lexical/y` stack: #9400, #9449, #9437).

Current behavior: the playground can run collaboration on `@lexical/yjs` only
(collab v1 with `CollaborationPlugin`, v2 with
`CollaborationPluginV2__EXPERIMENTAL`, chosen with `?isCollab=true` and
`?useCollabV2=true`). The experimental `@lexical/y` binding (Yjs 14, `@y/y`)
cannot be tried in the playground, and the repo's e2e suite does not cover it.

New behavior (opt-in; the default playground, `pnpm run start` and collab
v1/v2 are unchanged):

- `?isCollab=true&useCollabY=true` runs the playground on `@lexical/y`: the
  editor gets `YCollabExtension` with a `@y/y` document and a `@y/websocket`
  provider (`4.0.0-rc.2`, the published Yjs 14 client). The playground pins
  `@y/y` to `14.0.0-rc.29`, the version `@lexical/y` pins, so the lockfile
  holds one `@y/y`. The mode lives in its own chunk (`collaborationY.tsx`,
  loaded with `import()`), so the default playground does not load a second
  Yjs. `HistoryExtension` is left out in this mode (`YCollabExtension`
  provides undo and conflicts with it). The toolbar's connect button connects
  and disconnects the provider; the binding is initialized after the
  provider's first sync; a document whose layout this client does not support
  shows a read-only notice.
- `pnpm run collab:y` starts a Yjs 14 relay on `localhost:1235`
  (`packages/lexical-playground/scripts/collab-y-server.mjs`), and
  `pnpm run start:y` starts it together with the playground dev server.
  `pnpm run start` is unchanged (dev server and the `@lexical/yjs` collab
  server). The published `@y/websocket-server` still depends on the
  pre-`@y/y` Yjs 14 prereleases (`yjs@14.0.0-*`), whose documents are not
  compatible with `@y/y`, so the relay is a small in-memory y-websocket
  protocol server on `@y/y`, `@y/protocols` and `lib0` 1.x, with a test-only
  `/delay` endpoint.
- Playground features the binding does not sync are handled explicitly:
  nested editors (image captions, sticky notes) are read only in this mode
  and "Add Caption" is not offered; comments are off (as in collab v2: the
  comment threads live in a Yjs 13 document); there are no remote cursors.
  Playground nodes without collab declarations use the binding's nested
  storage. Comments keep using MarkNode.
- E2E: a new editor mode, `E2E_EDITOR_MODE=rich-text-with-collab-y`
  (`pnpm run test-e2e-collab-y-{chromium,firefox,webkit}`, against
  `pnpm run start:y`), runs `Collaboration.spec.mjs` and the new
  `CollabY*.spec.mjs`. `Collaboration.spec.mjs` is parameterized: where
  collab v1/v2 drop a peer's text on undo, collab Y asserts that the peer's
  text stays (undo only reverts the client's own changes), and collab Y does
  not restore the selection an undo step was made with, so that test places
  the caret explicitly. The new specs open each client in its own browser
  context (own keyboard), delay the relay's server-to-client messages while
  clients edit at the same time, and end every case by checking that all
  clients converge, that a client loading the document afterwards shows the
  same, that no typed token is lost or duplicated, and that no client logged
  an error or warning (the binding's development self-check reports through
  warnings). Console messages that are not about the editor are filtered by
  one list in the collab Y spec utilities (the other e2e specs do not read
  the console): failed resource loads, relay reconnects, Vite and React
  DevTools notices, and Firefox's "Loading failed for the <script>" for the
  playground's Vercel analytics scripts (`/_vercel/insights/script.js`,
  `/_vercel/speed-insights/script.js`), which a local or CI build does not
  serve (Chromium and WebKit report the same as "Failed to load resource").
  They cover: Enter, Backspace and Delete at line boundaries,
  heading/quote toggles and list create/indent/outdent while peers type;
  links while peers type inside and after the link; offline edits on both
  sides (text and structure, and a 30-lines-per-side divergence) and
  reconnect; undo isolation (own typing, Enter and heading undone after peer
  edits, undo while the peer types inside the undone text); the layout
  version gate (a document marked with layout 3, which this client does not
  read, makes open and late-joining clients read only); tables (cell typing,
  concurrent row and column insert stays rectangular, two rows inserted at
  one place); images (synced, no caption offered); and IME composition
  (Chromium, CDP) while a peer types, splits or joins the line.
- CI: a `collab-y-linux` job (Chromium and Firefox) runs the mode the way
  `collab-v2-linux` runs collab v2, starting `pnpm run collab:y` instead of
  `pnpm run collab`.

## Test plan

### Before

```
$ pnpm run collab:y
[ERR_PNPM_NO_SCRIPT] Missing script: collab:y

$ pnpm run start:y
[ERR_PNPM_NO_SCRIPT] Missing script: start:y

$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium | grep -c CollabY
0
```

`?useCollabY=true` is not a playground setting (it is ignored, and
`?isCollab=true` runs collab v1); no playground source imports `@lexical/y`.

### After

```
$ HOST=localhost PORT=1291 node packages/lexical-playground/scripts/collab-y-server.mjs   # what collab:y runs, on a free port
Yjs 14 (@lexical/y) relay running on ws://localhost:1291

$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --list --project=chromium
Total: 26 tests in 4 files       # Collaboration 6, CollabYNodes 6, CollabYStructure 8, CollabYSync 6
```

Collab Y mode, development playground build (`pnpm run build-playground-dev`,
served with `vite preview`), relay from `collab-y-server.mjs`, no retries:

```
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=2 --retries=0
  26 passed (1.1m)
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0
  3 skipped  23 passed (1.3m)           # the 3 IME specs are Chromium only
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=webkit --workers=2 --retries=0
  3 skipped  23 passed (1.2m)           # previous base revision
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium --workers=6 --retries=0 --repeat-each=3
  78 passed (1.3m)                      # previous base revision
```

Firefox without the Vercel scripts (as in CI; the build serves no
`/_vercel/` files), the previous revision of the console filter, then this
one:

```
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=firefox --workers=2 --retries=0
# previous revision
    Error: console errors or warnings
    + "[F] console.warning: [JavaScript Warning: \"Loading failed for the <script> with source “http://localhost:4471/_vercel/speed-insights/script.js”.\" …]"
  17 failed  3 skipped  6 passed (1.5m)
# this revision
  3 skipped  23 passed (1.3m)
```

The version gate spec marks the document with layout 3. Marking it one past
the root's version, as the previous revision of the spec did, writes layout
2 on a new document, which `@lexical/y` reads since block moves (#9449):

```
$ E2E_EDITOR_MODE=rich-text-with-collab-y npx playwright test --project=chromium CollabYSync -g 'version gate'
# previous revision of the spec
    Error: expect(received).toBe(expected) // Object.is equality
    Expected: "readonly"
    Received: "active"
  1 failed
# this revision
  1 passed (4.3s)
```

Collab v1/v2 are unchanged:

```
$ E2E_EDITOR_MODE=rich-text-with-collab npx playwright test --project=chromium --workers=2 --retries=0 Collaboration.spec
  6 passed (7.3s)
$ E2E_EDITOR_MODE=rich-text-with-collab-v2 npx playwright test --project=chromium --workers=6 --retries=0 Collaboration.spec
  6 passed (3.8s)                       # previous base revision
```

Also: `pnpm run tsc` (0 errors), `pnpm run flow` (0 errors), eslint and prettier on the touched files,
the tree-shaking tests (`scripts/__tests__/integration/tree-shaking.test.mjs`,
286 tests; `treeShakingSource.test.ts`, 363 tests),
`npx vitest --project unit packages/lexical-playground` (33 files, 390 tests),
`pnpm run build`, and
`pnpm run build-playground-dev` (`@lexical/y` is only in the `collaborationY`
chunk).

Not exercised: the CI workflow itself (run locally only), macOS and
Windows, the production playground build in a browser, and real IME input
(CDP composition events only).
zurfyx added a commit that referenced this pull request Oct 23, 2026
## Description

Stacked on #9438 (the `@lexical/y` stack: #9400, #9449, #9437, #9438).
Depends on #9380 (`MarkStateExtension` and `setValue`, set-valued
NodeState). This branch carries that commit as a temporary dependency
commit, to be dropped once #9380 merges.

Current behavior: `@lexical/y` stores each NodeState entry of a text run,
line break or inline node as one `s:<key>` format holding the serialized
value. A set-valued state such as `MarkStateExtension`'s `markIds`
(`createState('markIds', {parse: setValue(stringValue())})`) is one array per
run, so when two peers comment on the same text concurrently, one peer's
comments win (last writer wins on the whole set).

New behavior:

- On text runs, line breaks and nodes stored as their own `Y.Node`, a
  set-valued state known for the node type is written as one
  `s:<key>\u001f<member>` = `true` format (or attribute) per member, so
  concurrent additions and removals of different members merge. Block
  markers, wrappers and list groups still store the set whole.
- A state is set-valued when its schema says so,
  `stateConfig.schema?.meta.kind === 'set'` (what `setValue` produces). It is
  known for a node when it is used on it or registered for its type (as
  `MarkStateExtension` does for every node type when the editor is built).
  Splitting and joining the members is internal to `@lexical/y`; `lexical`
  gets no new API from this change.
- Reading joins the member entries back into one array, which the state
  parses into its set, only when the reader knows a set-valued state with
  that key for the node type and no StateConfig uses the entry key itself.
  A peer that does not know the state keeps each member as its own NodeState
  key and writes it back unchanged, so it never collapses the members. A
  whole `s:<key>` array next to member entries (stored by an earlier
  `@lexical/y` build) is merged with them, and the next write stores it per
  member. A value state whose key contains U+001F is never read as a member,
  and a set-valued state whose own key contains U+001F is stored whole.
- The self-check's fresh editor gets the set-valued StateConfigs registered
  on the binding's editor, so it reads the members the same way (otherwise
  every write of a set would be reported to the binding's `onWarn` as a
  `'self-check'` warning).
- `@lexical/yjs` is unchanged (it stores a set as one value).
- Tests: the harness takes a `prepare(editor)` hook (run before the binding
  starts; fresh readers reuse it). The fuzz now stores comments as one
  `setValue` state, like `MarkStateExtension`; `FUZZ_COMMENTS=keys` keeps the
  previous one-boolean-key-per-id model. `Size.test.ts` budgets three
  `MarkStateExtension` operations.
- Docs: the "Set-valued NodeState" limit on the Yjs 14 collaboration page
  says where the set is stored per member and where it is still one value
  (lines such as paragraphs and headings, list items, lists, links); the
  README's wire format adds the member entries (`s:<key>\u001f<member>` =
  `true`); the "Set-valued state" section of the NodeState page and the
  "Concurrent changes to the same ids" note of the Comments page say that
  `@lexical/y` stores the members separately.

Limit: a peer that does not know the state exports the members it keeps as
separate keys in its JSON (`"markIds\u001fc1": true`), and Lexical does not
join those keys when the JSON is loaded later. Register the state on every
peer, as the docs say.

Bytes the editing client emits (`@y/y` 14.0.0-rc.29, gc off, pinned client
ids), op / undo / redo:

```
                                   one format per id   whole set (before)
add a comment                      83 / 10 / 77        92 / 10 / 86
add an overlapping comment         83 / 10 / 77        196 / 45 / 190
remove one of two comments         12 / 142 / 10       113 / 144 / 113
```

## Test plan

New `packages/lexical-y/src/__tests__/unit/MarkState.test.ts`: two peers
(ids 1,2 and 2,1, causal and per-sender delivery) and three peers, with
concurrent comments on the same and on overlapping ranges, across a line
break, resolving while a peer types, resolving one of two comments, undo
while a peer types, the stored format keys, and a peer that does not know
the state editing commented text.

New `packages/lexical-y/src/__tests__/unit/SetState.test.ts`: a generic
`setValue(stringValue())` state, both client id orders: concurrent additions
merge on a text run, an inline decorator and a block decorator, stored one
key per member on each; a removal and a concurrent addition both apply; a
paragraph stores the set as one `s:tags` attribute (last writer wins); a
value state whose key contains U+001F is not read as a member; a set-valued
state whose key contains U+001F is stored whole.

### Before

`Read.ts`, `Schema.ts` and `SelfCheck.ts` reverted to the dependency commit:

```
$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/MarkState.test.ts packages/lexical-y/src/__tests__/unit/SetState.test.ts packages/lexical-y/src/__tests__/unit/Size.test.ts
 × each id is its own format key (4 of 4 orders)
   AssertionError: expected [ 's:markIds' ] to deeply equal [ 's:markIds\u001fc1', …(1) ]
 × two peers mark the same range (4 of 4 orders)
   AssertionError: expected 'paragraph("Revenue " "grew 4%"[c2] " …' to be 'paragraph("Revenue " "grew 4%"[c1,c2]…'
 × two peers mark overlapping ranges (4 of 4 orders)
 × two peers mark overlapping ranges across a line break
   AssertionError: expected 'paragraph("a"[c2] "b"[c1] linebreak[c…' to be 'paragraph("a"[c2] "b"[c1,c2] linebrea…'
 × keeps each id as its own format when it edits marked text
 × concurrent additions merge on text and stored nodes (2 of 2 orders)
   AssertionError: expected 'paragraph[] text[a] test_equation[a] …' to be 'paragraph[] text[a,b] test_equation[a…'
 × a removal and a concurrent addition both apply (2 of 2 orders)
   AssertionError: expected 'paragraph[] text[a,c] test_equation[a…' to be 'paragraph[] text[c] test_equation[c] …'
 × add a comment (MarkStateExtension)
   AssertionError: expected 92 to be less than or equal to 90
 × add an overlapping comment (MarkStateExtension)
   AssertionError: expected 196 to be less than or equal to 90
 × remove a comment (MarkStateExtension)
   AssertionError: expected 113 to be less than or equal to 14
 Test Files  3 failed (3)
      Tests  21 failed | 44 passed (65)
```

### After

```
$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y
 Test Files  56 passed (56)
      Tests  2242 passed | 2 skipped (2244)

$ npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-mark
 Test Files  12 passed (12)
      Tests  781 passed | 4 expected fail (785)
```

The 2 skipped tests are in `ListsInLines.test.ts` and are skipped on #9400
as well. The 4 expected failures are `MarkStateCollab.test.tsx`'s pinned
`@lexical/yjs` limits from #9380.

Fuzz with comments as one set-valued state, 2,000 seeds plus 500 gc seeds,
without and with block moves (25 seeds per test), and the default run with
one boolean key per comment:

```
$ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \
    npx vitest --project unit --no-watch --maxWorkers=1 packages/lexical-y/src/__tests__/unit/Fuzz.test.ts
 ✓ @lexical/y fuzz (100)
 ✓ @lexical/y fuzz with block moves (103)
      Tests  203 passed (203)

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

Also run: `pnpm run tsc`, `pnpm run flow` (0 errors), eslint and prettier
on the touched files, and `scripts/__tests__/unit/treeShakingSource.test.ts`
(364 passed).

Not exercised: real Yjs 14 providers and browsers.
zurfyx added a commit that referenced this pull request Oct 26, 2026
Stacked on #9439 (the `@lexical/y` stack: #9400, #9437, #9438, #9439). This
PR is now last in the stack.

> **Status: rebased, not yet reworked.** This change was moved to the end of
> the stack and onto #9400's v3 design (no shared repairs, a monotone layout
> record, follow-ups that only set attributes or delete). It compiles and its
> own tests pass, but parts of this description still describe the earlier
> design and are marked below; it gets its own fix round (performance,
> remaining review findings, docs) before review.

Today a block move in `@lexical/y` is a delete plus a re-insert: the binding
re-creates the cheaper side, so text a collaborator types into the moved
block at the same time lands in its old neighbour, and two collaborators
moving the same block can duplicate it. The normalization repairs every peer
runs (a block lifted out of the paragraph it was written in) are written the
same way, so two peers that lift one block from different surroundings both
re-create it, and text typed into it meanwhile is lost. (On #9400 v3 the
author normalizes its own write instead of every peer repairing it; see
"Lifted blocks" below.)

A move now keeps the moved items where they are and writes a small move
record where the block shows. A move changes only position, never the moved
content's characters.

- **Records.** A record `↷` is a child `Y.Node` of the container. It names a
  range of the container's own sequence by Yjs item id (`s` is the item
  before the range, or none; `e` is the range's last item) and has a priority
  `p`. Items a peer inserts later inside the range (typing, Enter) belong to
  it too. This ports the semantics of Yjs' unmerged range move (ContentMove:
  highest priority wins, loops are broken) to binding-level records. Yjs 14
  has no native move.
- **Ownership is computed when reading, from the document alone.** An item
  belongs to the active record of highest priority (then client, then clock)
  whose range holds it. A record placed inside its own range, directly or
  through other records, shows nothing. Nothing is repaired or written back.
  A record written again keeps its rank (`o`). A write that splits an anchor
  item (typing inside the last word of a range) keeps the range: anchors
  resolve to the item holding their id.
- **Records are not boundaries.** A record shows its units before the line
  its item is in, so text typed concurrently at a line start stays in its
  line. Formats stay positional, as in Yjs.
- **Joins keep their items.** Joining a line into a moved line (Backspace,
  Delete, a deletion across lines) writes join records (`j: 1`) at the end
  of the first line's text. They show the second line's text in their place,
  so the joined line can span ranges and the second line's characters are
  never copied. A second line that is not one range (a block moved away
  from between its parts, or it starts inside a joined range) gets one join
  record per piece. Two peers that make the same join write records of the
  same ranges; one wins and the other shows nothing, so the text appears
  once.
- **Lines that span ranges move with their items.** A line split off a
  joined line, or joined across a moved range, is moved with one join record
  per piece but its last (written at the start of the last piece) and a
  block record over the last piece, instead of being re-created.
- **Lifted blocks keep their node.** A block written inside a line (a
  table appended to a paragraph without the normalization, an older client)
  keeps its shared node when the normalization lifts it out (on #9400 v3,
  the normalization of its author) (a line written
  inside a line, such as a heading in a list item, is stored as lines by
  #9400 and needs no lift): the node is
  marked a unit of its container (`u: 1` on the `i:<type>` node), which
  splits the line around it, and the line parts get markers. (The earlier
  design, where every peer lifted it under a content-derived client id, is
  gone with #9400's shared repairs.) Lexical replacing such a block by a new one of its type (Enter at
  its start) keeps the shared node too.
- **Records left inside a line.** A record can end up between a line's
  characters when the line around it changed at the same time: a peer
  joined the lines around it (the record is inside the joined range), or
  removed the line before it while another typed in that line. New units
  then go right after the block the record shows only when that is a line
  boundary, otherwise right before the next line, and when the block shows
  from inside that next line it is written again with a record where it
  shows. A moved line that such a record interrupts moves with its pieces
  (its text before the record too). A record is written again at its line
  start only when the same records stay active (moving it out of another
  record's range can make a record that showed nothing show its range).
- **Zero cost without moves.** Every new path sits behind "this container
  holds a record" or "this write lifts a block". The per-keystroke cost,
  size, 10k-edit growth and load time of documents that never move are
  unchanged, and Enter and Backspace there are within 3% of #9400.
- **Incremental read.** A peer that receives a move, its undo or redo, or a
  structural edit in a container with records re-parses only windows around
  the records whose ownership changed. Each window is bounded by end items
  its zone owns before and after the change, so a unit keeps its node only
  when its content provably did not change. Format edits, join records and
  unresolved records still read the whole container.
- **Cost with many records.** Outside a transaction, a container's cached
  ownership is checked against the document (records deleted, anchors
  split or merged) once after each transaction starts and once after Yjs
  cleans one up, instead of on every use; inside a transaction it is still
  checked on every use. Which records are active, and the ownership before a change in an
  incremental read, come from a painted index instead of a scan of the
  records per position. An incremental read takes formats from one walk of
  the container, and the check for records left inside a line stops where
  the previous record's check stopped. Nothing written changes: the updates
  of a scripted session and of every fuzz session are byte-identical before
  and after. At 10,000 random moves on 1,000 blocks (every block moved,
  1,000 live records), a local move goes from 347 to 34 ms, a remote read
  from 1,049 to 27 ms and a load from 647 to 46 ms (#9400: 5.1, 3.6 and
  27 ms). What is left grows with the container's items, deleted records
  included.
- **Records over time.** Each move leaves a tombstone of about 18 B once
  Yjs collects garbage (a delete and a re-insert on #9400 leaves 16.5 B).
  Live records stay at most one per moved range, apart from rare cases (a
  block moved back to where it was, a record that lost a loop, a record
  whose range a peer deleted, until the next local write of that
  container), tracked in #9455.
- **Detection.** No core hook. The writer's existing key matching (same
  NodeKey under the same container) recognizes the moved units. The records
  go to the units the user moved, and a whole range that moves again reuses
  its record.
- **Scope: moves inside one container.** This covers the root, a list (items
  and whole lists), a table (rows), a row (cells, so column moves), a cell's
  or collapsible's content, and block decorators and containers moved as
  units. A move into another container is still a delete plus an insert
  (documented).
- **Undo** removes the record, so the block returns with a peer's concurrent
  typing. Redo writes it again. A local write that deletes a record can let
  another record show. The writer then reads the container again, as a peer
  would.
- **Layout.** A new document records layout 1 (`lexical-y:1: true`). The
  first move record, join record or lifted block adds `lexical-y:2: true` to
  #9400's monotone layout record, in the same transaction as the record (so
  no client ever receives a record without the version), and undo never
  deletes it; nothing else is rewritten. Clients without moves then open it
  read only instead of misreading it, and the record never shrinks. `LAYOUT_VERSION` is
  now 2, and documents without moves stay editable by older `@lexical/y`
  builds. The README's wire format section documents layout 2 (records, join
  records, lifted blocks, the upgrade) next to the frozen layout 1.
- (Removed with #9400's shared repairs: the list-merge and ragged-table
  repair exceptions for containers with records.)
- Warnings go to the editor's `onWarn` as `LexicalWarning`s, and the code
  uses the binding's read-only getters.

On main, the update that flips a node's `isInline()` lifts the node itself
(the normalization runs on what an update writes), so the flip is written as
a block of its container, not as an inline node a later repair lifts in
place; this PR therefore leaves `IsInline.test.ts` as #9400 has it.

**Prior art.** We studied Bob Ippolito's etrepum#65, which gives
every node its own Yjs node and moves a node by writing a `{id, token}`
placement into its new parent. We chose instead to port Yjs's own unmerged
range-move design (`ContentMove` on the `move` branch: a record at the
destination points at the moved range, the higher priority wins, loops are
broken) as binding-level records. Our reasons: splits and joins stay cheap
marker edits, documents pay nothing until something moves, and #65's
per-node layout has known cases where a split or join racing a collaborator's typing loses or
misplaces that typing (marked as expected failures in its tests). Credit to
one format key per mark id, the same as the follow-up #9439.

No change to `lexical`, `@lexical/yjs` or any other package. Docs: the
`y.md` page's "Wire format" section, which #9400 starts with a diagram of
layout 1, gains diagrams of layout 2 (a move record next to the order the
editor shows, and a join record) and of the upgrade from 1 to 2, checked
against a dumped document, and links the README's layout 2 specification; its limits
describe moves within and across containers, joins, and layout version 2.
Its limits also cover text typed into a block moved out of a container that
a peer removes or moves (lost), the same block moved into two containers
(shown twice), and an undo of a removal racing a move out of the removed
range (shown twice), and how records and tombstones grow over time, with
the Yjs advice to reload long-lived rooms on the server. The README's wire
format documents layout 2, and its
fuzz note lists the moves fuzz variables. `@lexical/y` is unreleased and
`@experimental`.

```
$ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs
 Test Files  62 passed (62)
      Tests  2981 passed | 4 expected fail | 2 skipped (2987)

$ FUZZ_MOVE_SEEDS=1000 FUZZ_MOVE_GC_SEEDS=200 NORMALIZE_FUZZ_SEEDS=1000 \
    npx vitest --project unit --no-watch packages/lexical-y/src/__tests__/unit/{Fuzz,NormalizationConvergence,Moves,Races}.test.ts
normalization fuzz: {"duplicated":[],"healed":[… 60 seeds],"seeds":1005}
held paragraphs fuzz: {"duplicated":[],"healed":[228,295],"seeds":1000}
      Tests  3483 passed (3483)
```

Adapted to #9400 v3 in this rebase: the layout test now checks the record
(`lexical-y:1` and `lexical-y:2` = `true`), that the version is written in
the transaction of the first move record, and that undoing the move keeps
it; the two "lifts in place" tests deliver the author's normalization with
its write (receivers no longer lift); the "move a block" byte budget is
108 (was 104: the record's attribute is now part of the move's update). Also
`pnpm run test-unit` compared test by test with #9439 (0 failed, 0 changed;
the replay of a fixture this PR deletes no longer runs), `pnpm run tsc`,
`tsc-test`, `tsc-scripts`, `tsc-website`, `tsc-extension`, `pnpm run flow`
(0 errors), `pnpm run lint`, `pnpm run prettier`, the tree-shaking tests (369
source, 286 built), `pnpm run build-prod` and `pnpm run build-docs` pass.

The rest of this test plan is from the previous base (#9400 before its v3
rework) and is re-measured in the fix round.

The new tests against the previous revision of this change (joins of lines
that are not one range copied, lines that span ranges re-created, repairs
written as a delete and a re-insert):

```
$ npx vitest --project unit --no-watch Moves.test NormalizationConvergence.test
 × move of a line split after a join ‖ typing in it (4 of 4 orders)
   Expected: "paragraph("zeroth") / paragraph("one") / paragraph("two") / paragraph("rXee")"
   Received: "paragraph("zeroth") / paragraph("Xone") / paragraph("two") / paragraph("ree")"
 × move of a line another zone interrupts ‖ typing in both parts (4 of 4)
   Expected: "paragraph("three") / paragraph("one") / paragraph("zeXrotwYo")"
   Received: "paragraph("XrotwYthree") / paragraph("one") / paragraph("zerotwo")"
 × join ‖ join of a line another zone interrupts (4 of 4)
   Expected: "paragraph("threezerotwo") / paragraph("one")"
   Received: "paragraph("threezerotwozerotwo") / paragraph("one")"
 × join into a moved line of a line another zone interrupts ‖ typing in it (4 of 4)
 × two blocks written at the end of one line by two peers, lifted by a third (12 of 12)
   AssertionError: expected [ 'cell', 2 ] to deeply equal [ 'cell', 1 ]
 × a block lifted out of the middle of a line ‖ typing next to it and in it (12 of 12)
   AssertionError: expected [ '¶', 'b:test_box', '¶' ] to not include 'b:test_box'
 × a heading lifted out of a list item ‖ typing in the heading (12 of 12)
 × fuzz: normalization repairs by 3 peers with partial delivery, seed 44, 47, 51, 64, 79, 93
      Tests  58 failed | 839 passed (897)
```

- Randomized normalization fuzz, 2,000 seeds (3 peers, 40% of edits written
  without the normalization, peers typing into the same blocks, partial
  delivery): 490 sessions copied or lost text: 102 sessions
  without a nested line (101 with a copied block, 1 with a lost token) and
  388 with one (a heading a peer wrote inside a list item: 387 copied, 2
  lost).
- `Fuzz.test.ts` / the fuzz utilities: a token a peer moves into a table,
  box or column counts as lost by delete wins when another peer made a
  removal, exactly like a token typed there. Duplicates are not excused.
- Block id integration (BlockIdExtension on this change), moves fuzz, 2,000
  + 500 gc seeds: 15 + 3 seeds with
  duplicated text (joins written as a copy, lines that span ranges moved as
  a delete and a re-insert).
- This revision's fixes, against the previous revision of this change (a
  record left inside a line by concurrent edits: a unit written after the
  block it shows split the line, and a moved line left its text before the
  record behind; a heading written inside a list item stored as its own
  node):

  ```
  $ npx vitest --project unit --no-watch Moves.test -t 'a record left inside a line'
   × a block shown from inside a joined line ‖ a new line right after it (4 of 4)
     + "@lexical/y self-check: line 81: text \"M0 abcNEW\" != \"NEW\"; ..."
   × a line typed into after a removal, shown around a record, moved (4 of 4)
     + "@lexical/y self-check: line 133: text \"M5 pqr\" != \"XM5 pqr\"; ..."
        Tests  8 failed | 234 skipped (242)
  $ npx vitest --project unit --no-watch NormalizationConvergence.test
   × a line written inside a line is stored as lines (48 of 60)
   × a heading written inside a list item ‖ typing in the heading (12 of 12)
   × fuzz: seeds 405, 435, 446, 899, 937, 1078, 1388, 1507, 1683, 1820
        Tests  70 failed | 665 passed (735)
  ```

  The normalization fuzz at 2,000 seeds copied text in 8 sessions and lost
  it in 2, all with a heading written inside a list item. The block id
  moves fuzz with undo and redo off failed 2 of 2,000 seeds (162: a
  self-check mismatch after a move; 741: a self-check mismatch and lost
  text after a new line was written next to a moved block). Enter and
  Backspace in a 10,000 paragraph document without moves took 71.2 and
  71.5 ms against 67.0 and 66.8 ms on #9400 (3 alternating runs, +6%).
- A move at 10k blocks with 100 earlier moves on #9400 without this change:
  #9400 writes a move as a
  delete and a re-insert, 78 ms end to end with 100 earlier moves at 10,000
  blocks (its undo writes 131 B).

- Many moves, before this revision's caching (1,000 blocks, gc on): at
  10,000 random moves (1,000 live records) a local move took 347 ms, a
  remote read of it 1,049 ms and a load 647 ms, against 5.1, 3.6 and 27 ms
  on #9400; at 1,000 moves (634 live records), 24.5, 16.1 and 400 ms.

```
$ npx vitest --project unit --no-watch Moves.test Races.test
      Tests  341 passed (341)
$ npx vitest --project unit --no-watch packages/lexical-y packages/lexical-yjs
 Test Files  55 passed (55)
      Tests  2726 passed | 4 expected fail | 2 skipped (2732)
$ NORMALIZE_FUZZ_SEEDS=2000 npx vitest --project unit --no-watch NormalizationConvergence.test
      Tests  4973 passed (4973)     # 2,000 + 2,000 fuzz seeds, matrix 864
$ NORMALIZE_FUZZ_SEEDS=10000 npx vitest --project unit --no-watch NormalizationConvergence.test -t fuzz
      Tests  20000 passed           # 10,000 + 10,000 fuzz seeds, on the top of the stack:
                                    # 0 copies, 0 losses; 434 + 26 sessions healed a remote
                                    # self-check mismatch by a re-read
$ FUZZ_SEEDS=2000 FUZZ_GC_SEEDS=500 FUZZ_MOVE_SEEDS=2000 FUZZ_MOVE_GC_SEEDS=500 \
    npx vitest --project unit --no-watch Fuzz.test
      Tests  203 passed (203)
```

Re-run on this revision (main with the final node structure, #9452, and the
updated #9400): the commands above; the moves fuzz at 2,000 + 500 gc seeds
through the same counting harness as before: 26 and 7 seeds with lost or
duplicated text, the same seeds as on the previous base, and 1,997 of 2,000
and 498 of 500 sessions write byte-identical updates (the other 3 + 2 differ
where main's normalization now runs in a local update); the block id
integration (moves fuzz, 2,000 + 500 gc: duplicated text on 882 and 1993
only, as before; the BlockIdExtension fuzz, 2,000 seeds, passes); and the
collab Y e2e suite in Chromium (26/26) and Firefox (23 passed, 3
Chromium-only skips). From the previous base and not re-run: the 25,000 +
5,000 gc moves fuzz, the differential, the scripted byte-identity session,
the block id run with undo and redo off, the playground drag spec, and the
perf and many-moves tables below.

- `Moves.test.ts` (249 tests, most in 4 orders) covers:
  - move ‖ type (inside, start and end), move ‖ move of the same block,
    neighbour moves, move ‖ delete, move ‖ retype, move ‖ bold, move ‖
    Enter;
  - every join and split ‖ move combination: join ‖ join (Backspace,
    Delete, both, a range across a moved line), join ‖ split, join ‖
    typing, join ‖ move, split ‖ move, undo of a join, a join ‖ an undo
    that restores a line inside the joined range;
  - new: lines that span ranges moved (a line split after a join, alone, ‖
    typing in it and ‖ another move), a line another zone interrupts moved
    ‖ typing in both parts and joined ‖ typing and ‖ the same join, and a
    line that ends inside a joined range moved and then typed in, a block
    shown from inside a joined line ‖ a new line right after it, and a line
    typed into after a removal, shown around a record, then moved (each
    checks that the result is exactly the writer's intent);
  - list item moves (up, between lists, ‖ indent), whole-list moves ‖ add
    item, table row ‖ type and column ‖ type, container ‖ type, block
    decorator;
  - undo, redo, a second move, delete of a moved block, caret mapping, the
    layout bump, no record for documents that never move, and reads that
    stay incremental.
  - new: cached ownership, compared with ownership built fresh from the
    document after every step, across undo and redo with a peer typing,
    records that arrive out of order, a record whose anchors arrive late,
    text anchors split by typing (with and without gc), anchors merged by
    gc, and a moved block deleted with its old neighbour under gc. Taking
    out the anchor check fails them.
- `NormalizationConvergence.test.ts`: the 3-peer matrix (18 violations × 8
  delivery schedules × 6 id orders) passes 864/864; new lift tests (a block
  lifted out of the middle of a line ‖ typing next to it and in it, two
  blocks written at the end of one line by two peers and lifted by a
  third, a heading written inside a list item ‖ typing in it, a block put
  inside such a heading and lifted from other surroundings; 6 id orders ×
  2 deliveries each) check the text, the stored node (`u`, no copy, no
  `i:heading`) and the layout bump. The randomized fuzz fails on any
  copied or lost token, in every session, and always runs the seeds that
  failed during this work. A second randomized fuzz adds edits that write
  plain paragraphs into quotes and list items (joined into them as lines by
  the normalization) and new quotes, starting from a document with a quote
  and a numbered list. Both pass at 2,000 and 10,000 seeds each (0 copies,
  0 losses).
- Fuzz with block moves (the whole stack): 2,000 + 500 gc and 25,000 + 5,000
  gc seeds, 0 absolute findings (divergence, exceptions, fragments,
  self-check, fresh readers). The fuzz now counts a block moved into a
  container a peer removed as delete wins, as it already did for text typed
  into one. Seeds with lost or duplicated text: 26 of 2,000 (1.3%; 69 before
  that accounting change), 7 of 500 gc (20 before), 278 of 25,000 (1.1%; 767
  before) and 52 of 5,000 gc (157 before). All of them are documented
  limits: two peers moving the same block when one moves it into another
  container (shown twice), a move into another container racing a move of
  its container or an undo of a removal (shown twice), text typed into a
  block a list conversion lifts, and joins written as a copy. `Fuzz.test.ts`
  at 2,000 + 500 seeds with and without moves passes, including a regression seed (a comment over a line joined with a line of
  two pieces, then an undo).
  Differential
  against v2, 2,000 + 500 gc: 0 absolute findings, 5 + 1 seeds worse than
  v2.
- This revision writes exactly what the previous one wrote. Every update
  of a scripted two-peer session (900 steps of moves, typing, Enter,
  joins, removals, undo and redo, with and without gc), of the moves fuzz
  (2,000 + 2,000 gc and 25,000 + 5,000 gc seeds, every peer's updates
  hashed per seed) and of 10,000 random moves is byte-identical before and
  after, and the fuzz findings, the differential (the same 5 + 1 seeds)
  and the block id runs below are unchanged.
- Block id integration (BlockIdExtension on this stack): the moves fuzz,
  2,000 + 500 gc seeds, has 0 divergence, 0 self-check warnings and 0 lost
  text; 2 + 0 seeds show duplicated text (882, 1993): in both, two peers
  remove the same text and both undo the removal, and each undo restores
  its own copy, which Yjs does with plain `Y.Text` too (no move is
  involved). With undo and redo off, 2,000 + 500 seeds have no finding
  (162 and 741 failed before). The BlockIdExtension fuzz, 2,000 seeds,
  passes.
- Many moves (1,000 blocks; ms: local move, remote read of it, load; mean
  of the last 50 moves, median of 3 loads; #9400 / before / after):

  | Moves, gc | Live records | Local move | Remote read | Load |
  | --- | --- | --- | --- | --- |
  | 100 random, on | 97 | 4.8 / 8.1 / 8.3 | 2.8 / 3.7 / 3.7 | 20 / 69 / 24 |
  | 1,000 random, on | 634 | 4.5 / 24.5 / 17.2 | 3.1 / 16.1 / 8.0 | 20 / 400 / 29 |
  | 10,000 random, on | 1,000 | 5.1 / 347 / 33.5 | 3.6 / 1,049 / 26.9 | 27 / 647 / 46 |
  | 10,000 random, off | 1,000 | 6.7 / 357 / 35.0 | 5.5 / 1,086 / 28.8 | 49 / 783 / 135 |
  | 10,000 back and forth, on | 1 | 5.3 / 10.0 / 10.2 | 3.0 / 8.6 / 8.7 | 22 / 28 / 26 |
  | 10,000 back and forth, off | 1 | 7.6 / 11.2 / 11.1 | 4.3 / 10.1 / 10.2 | 52 / 128 / 122 |

  A keystroke in a moved block stays at 2.2 to 4.6 ms (#9400: 2.2 to 3.0).
  Sizes are unchanged (235 KB after 10,000 random moves with gc, 157 KB on
  #9400). The remaining cost grows with the container's items, deleted
  records included, which Yjs keeps in the sequence.
- Perf at 10,000 blocks (end to end, shared machine, #9400 → the top of
  the stack): Enter and Backspace in a document without moves, median of
  the per-round ratio over 6 alternating rounds, +0.0 to +0.5% at the top
  of the stack and -1.8 to +1.3% with this change alone (+6% for the
  previous revision); keystroke 38.7 → 38.6 ms (list item 47.9 → 46.3),
  load 195 → 193 ms, size, 10k-edit growth and bytes per edit identical; a
  move 97 → 124 ms (131 → 106 B), its undo 69 → 73 ms (131 → 11 B).
- Playground (`?isCollab=true&useCollabY=true`, the stack's playground
  mode, a scratch spec): drag a block while the other tab types in it, a
  list, a list item, a table row, undo, and the same block dragged twice:
  Chromium 21/21 (3 repeats), Firefox 7/7, WebKit 7/7; the collab Y e2e
  suite passes in all three (26/26, 23/23 + 3 Chromium-only IME skips).
- On this commit: `pnpm run tsc`, `tsc-test`, `tsc-scripts`, `pnpm run flow`
  (0 errors), `pnpm run lint`, `pnpm run prettier`, the source tree-shaking
  test (368 passed), `pnpm run build-prod` and the built tree-shaking test
  (284 passed).
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-server branch from 6ea0dff to 208f6f4 Compare October 26, 2026 08:47
@zurfyx
zurfyx force-pushed the zurfyx/collab-y14-block-markers branch from b6f567e to 8d67a8e Compare October 26, 2026 11:27
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-server branch from 208f6f4 to 34c4737 Compare October 26, 2026 11:27
@zurfyx
zurfyx force-pushed the zurfyx/collab-y14-block-markers branch from 8d67a8e to 59407da Compare October 26, 2026 13:27
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-server branch from 34c4737 to 3f77588 Compare October 26, 2026 13:27
@zurfyx
zurfyx force-pushed the zurfyx/collab-y14-block-markers branch from 59407da to eb0175e 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-server branch from 3f77588 to 5a5d300 Compare October 26, 2026 16:40
@zurfyx
zurfyx force-pushed the zurfyx/collab-y14-block-markers branch from eb0175e to 48857a8 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-server branch from 5a5d300 to eceaf0c Compare October 26, 2026 19:37
@zurfyx
zurfyx force-pushed the zurfyx/collab-y-server branch from eceaf0c to abf8354 Compare October 26, 2026 22:04
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-y14-block-markers branch from 48857a8 to b15e04b Compare October 26, 2026 22:04
@potatowagon potatowagon mentioned this pull request Dec 2, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — 50ca48be Deployed Oct 28, 2026 by vercel[bot]
Preview – lexical-playground — 50ca48be 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