Skip to content

[lexical-y] Feature: Layout migrations and the permanent upgrade API: @lexical/y/migrate, frozen steps, @lexical/y/server, a required layoutUpgrade, and the never-drop-a-reader policy - #9766

Merged
zurfyx merged 115 commits into
mainfrom
zurfyx/y-layout-migrations
Nov 5, 2026

Conversation

@zurfyx

@zurfyx zurfyx commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Description

@lexical/y stores its encoding of Lexical inside Yjs documents that outlive the code that wrote them. This adds the migration system and freezes its public surface: after the layout 3 change that follows (#9777), layouts are only added, readers are never dropped, and every export, stored shape and exchanged shape below changes only additively (D110, D102).

Policy (DECISIONS D110, D109, D102)

  • D110, never drop a reader: after layout 3, a release adds a layout (the core reads and writes both, each document in the layout it records) and publishes a frozen step; nothing upgrades on its own. An app opts in at its authority and may raise its own floor through its server's admission. MIN_LAYOUT stays 3; no post-break reader, writer or step is removed; a step's default revision never changes its output.
  • D109, raw Yjs writes are unsupported: the encoding under the binding's root is private. A development-only RAW_YJS_WRITE_WARNING ('@lexical/y/raw-yjs-write') reports a local write to the root by an origin that is not the binding's, a Y.UndoManager or the migration's, in a transaction the binding does not write in itself (it may miss a raw write, never report the binding's own); production builds carry no check.
  • D102, the mechanism: frozen chained steps run by the one authority that stores a document, behind a generation fence; client-side migration is deferred from this release and can come back additively.

Core (@lexical/y)

  • createYCollabConfig({doc, schemaVersion, layoutUpgrade}): layoutUpgrade is required. null declares that documents below the floor open read only; createYServerLayoutUpgrade() returns a branded handle ({kind, handshake}, open to later kinds and fields) declaring that the app's server migrates, and its handshake({generation, material}) builds the session handshake. A config without it (plain JS, or configExtension directly) works as before and also reports UNSUPPORTED_CONFIG_WARNING {reason: 'missing-layout-upgrade'} when a document is below the floor.
  • MIN_LAYOUT, SEED_LAYOUT, LAYOUT_VERSION, typed number. A root below MIN_LAYOUT binds read only and reports UNSUPPORTED_LAYOUT_WARNING {reason: 'older', found, min, supported, upgrade}; readYState and editYState refuse it (headless editing declares layoutUpgrade: null, so it adds no config warning).
  • Feature requirements: a lexical-y-require:<feature> = true record the binding does not support, or a malformed one, opens the root read only (rendered, never rewritten). Other unknown lexical-y-* keys are kept and ignored.
  • The migration epoch lexical-y-epoch = {v: 1, kind, layout, client, clock, step, revision, schema?}: layout is the destination, step and revision the receipt, client and clock the transition identity. Unknown fields and kinds are tolerated; another v or a malformed known field closes writes. A migration clears the binding's undo history, and onYMigrationEpoch(doc, fn) gives apps that point for their own UndoManagers.
  • binding.quiesce() returns a YQuiescedState for a recovery handoff. Writes check the layout, epoch, requirement and schema records inside each write's own transaction (the write-time gate; its own [fix] changeset).
  • Warning and error codes are open: each code's data has a permanent {reason: 'other', detailCode, details?} fallback, and isYWarning(value, code?) narrows by code.
  • schemaVersion is documented as the version of the app's nodes (registered node classes, their fields and NodeState).

Runner (@lexical/y/migrate, imports only @y/y)

  • migrateYState(state, steps, options) returns {state, update, pending, receipt}; receipts carry v: 1. loadYMigrationSteps(from, to = MIN_LAYOUT, {loaders?}) loads the published steps from a generated manifest by default. getYLayoutInfo(doc, root?) returns a fixed status (ready, missing, invalid, unsupported) with the layout and epoch. YMigrationError has an open code.
  • Before any step runs, every root that would run one is checked: a feature requirement this release does not support refuses with 'unsupported-feature', a malformed record with 'malformed' (roots already at the target pass through unchanged).
  • A step (YLayoutMigration, execution contract v: 1) migrates one root from layout N to N + 1, one container at a time; the runner rejects an unknown execution contract before calling it, and checks everything on an observer-free copy before anything is written (units keep id, content and order; untouched keys, attributes and roots unchanged; frozen reads equal; the target's invariants; the encoded result re-read; the returned update reproduces the state).
  • The migration client id is hashed from every input and never names a client the input names, so two authorities produce the same bytes. Pending material is split out, never kept.
  • Steps are listed once in src/migrate/manifest.json; the package exports, a lazy loader table and a static server table are generated from it. The core imports none of them.

Step (@lexical/y/migrate/1to2): frozen, revision 1, goldens pinned per revision (golden/migrate-1to2-r1.json).

Server (@lexical/y/server, imports @y/y and @lexical/y/migrate)

  • prepareYRoom migrates a room on load (published steps by default). getYGeneration returns an opaque g1: token over the incarnation and every served root's transition identity.
  • checkYSession(describeYRoom(...), handshake): the handshake is {v: 1, generation, material, layouts, seed, features?}; a malformed one or an unknown v is refused; null is the legacy route. The room description carries requires and hasMigration. The five verdicts (admit, bootstrap, stale, refuse-layout, legacy) are permanent and may carry a reason.
  • createYSessionCapture(resume?) captures a legacy session (and resumes from persisted material); createYQuarantineRecord builds handoff, capture and pending records: {v: 1, updateFormat: 'yjs-v1', requires, ...}, copied from their inputs, with a yr1-sha256: hash over a canonical payload. YRecordAcknowledgement {v: 1, room, replica, sourceGeneration, record, hash} is what an acknowledgement names; a bare hash acknowledges nothing. A record with another version or update format, an unknown kind or an unsupported requirement is kept and exported as it is, never decoded: sourceView(record) checks the header before reading any bytes. Capture material is versioned ({v: 1, updateFormat: 'yjs-v1', ...}) and a capture refuses to resume any other. The pending form of createYQuarantineRecord is exclusive (material fields beside it are refused, never dropped).
  • createYDoc (Yjs only), the layout constants, and createYServerLayoutUpgrade / isYLayoutUpgradeHandle.

Docs: y.md ("Layout upgrades", the setup example, options and warnings tables, wire format, "Edits made by code"), y-server.md ("Migrating stored documents", the handshake table, records and acknowledgements), the README's wire format, and DECISIONS D102, D109, D110.

Not in this PR

Changeset

  • lexical-y-warning-api-break.md [breaking]: the warning API (open codes, generic YWarning, isYWarning(value, code), the 'other' fallback, new reasons), LAYOUT_VERSION typed number, raw Yjs writes unsupported, and the Flow changes; with Migration, Detect and Verify. It ships in the same release as layout 3's ([lexical-y] Breaking change: Pair each format run's end with its opener (layout 3) #9777), the package's one breaking release.
  • lexical-y-layout-migrations.md, lexical-y-layout-upgrade.md, lexical-y-collab-input.md [feature].
  • lexical-y-write-time-layout-gate.md [fix].
  • lexical-y-never-drop-a-reader.md [docs].
  • lexical-y-flow-layout-version.md (updated).

Test plan

Before

The new entries and their tests do not exist on main. On main, a write inside an app transaction that removes the layout record, or adds a newer or malformed one, is stored (the binding turns read only only after the transaction). A control on main, printing cause, gc, text and status:

MAINCTL missing false abcforbidden readonly
MAINCTL newer false abcforbidden readonly
MAINCTL malformed false abcforbidden readonly

MigrateHistoryGate.test.ts against the core before the write-time gate:

      Tests  64 failed | 2 passed (66)

Regression cells from the review rounds, each on the commit before its fix:

$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/MigrateRequirements.test.ts
AssertionError: expected null to be an instance of YMigrationError
      Tests  2 failed | 16 passed (18)
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/MigrateBeforeTransaction.test.ts
     × binding undo, layout first: refused, read only, not editable
     × binding redo, layout first: refused, read only, not editable
      Tests  4 failed | 28 passed (32)
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/RawYjsWriteJoined.test.ts
     × an editor edit inside doc.transact(fn, appOrigin): stored, active, no warning
     × binding.undo() and redo() inside doc.transact(fn, appOrigin): applied, no warning
Serialized Error: { code: '@lexical/y/raw-yjs-write', data: { key: null, kind: 'content', origin: 'AppOrigin', reason: 'raw-write', root: 'lexical-y', ... } }
      Tests  4 failed | 4 passed (8)
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/BufferCopies.test.ts
     × a record keeps its own bytes when the caller writes to its Buffers afterwards
     × a capture keeps its own bytes when the caller writes to its Buffers afterwards
$ pnpm run flow
Cannot assign `bindingOptionsWithExtra` to `extendedBindingOptions` because property `laterOption` is extra in
Cannot assign `configWithExtra` to `extendedConfig` because property `laterOption` is extra in
Cannot assign object literal to `literalOptions` because property `laterOption` is extra in object literal [1] but
Found 3 errors

After

On this head (main through dfe058a merged in):

$ pnpm exec vitest run --project unit packages/lexical-y packages/lexical-yjs
 Test Files  1 failed | 306 passed | 2 skipped (309)
      Tests  1 failed | 20504 passed | 393 expected fail | 131 skipped (21029)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/DisposeMemory.test.ts > 40 editors bound, edited and disposed in a synchronous loop hold no document
$ LEXICAL_Y_GC=1 FUZZ_GC=1 pnpm exec vitest run --project unit packages/lexical-y packages/lexical-yjs
 Test Files  307 passed | 2 skipped (309)
      Tests  20502 passed | 396 expected fail | 131 skipped (21029)

DisposeMemory bounds the heap growth of 40 editors bound and disposed in a loop, so it is sensitive to parallel load. Alone it passes on this head and on main alike (gc off and on, three runs each), and main fails it the same way in a loaded run:

$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/DisposeMemory.test.ts   (this head, then main dfe058a8; gc off and on, 3 runs each)
      Tests  1 passed (1)
main be882d11, LEXICAL_Y_GC=1 FUZZ_GC=1, 40 workers:
      Tests  1 failed | 19784 passed | 382 expected fail | 131 skipped (20298)
 FAIL  |unit| packages/lexical-y/src/__tests__/unit/DisposeMemory.test.ts > 40 editors bound, edited and disposed in a synchronous loop hold no document

The layout gate's attribute-read refactor (one read of the root's attributes per check) stores the same bytes: every peer's final encoded state, hashed with SHA-256, is identical before and after it over the 47 scripts in src/__tests__/fuzz/ and 600 random sessions (seeds 8,800,001 to 8,800,300, gc off and on):

(the fuzz runner patched identically in both trees to append each session's per-peer state hashes to a file; the two files diffed)
before replay rc 0 lines 47
after replay rc 0 lines 47
REPLAY-IDENTICAL
before sessions rc 0 lines 600
after sessions rc 0 lines 600
SESSIONS-IDENTICAL
$ pnpm run ci-check
Found 0 errors
$ pnpm run check-changesets
Changeset check passed: 106 pending changeset(s) valid.
$ pnpm exec vitest run --project scripts-unit
 Test Files  22 passed (22)
      Tests  3594 passed (3594)
$ pnpm run build-release

(exit 0; scripts/error-codes/codes.json not committed. The production core carries no raw-write check, only the exported warning code.)

Sizes (build-release, prod, minified / gzip -9):

file main (dfe058a) this PR
LexicalY.prod.js 273,604 / 83,386 283,263 / 86,348
LexicalYHeadless.prod.js 11,089 / 4,913 11,108 / 4,922
LexicalYServer.prod.js - 25,859 / 9,355
LexicalYMigrate.prod.js - 27,343 / 9,375
LexicalYMigrate1to2.prod.js - 970 / 634

The core's share is the write-time gate, the layout, epoch and requirement records, quiesce, and the open warning codes; the runner, the steps and the server are separate entries an app loads only where it migrates.

The generation fence, run as a fuzz on this head: real Lexical editors on @lexical/y, partial and reordered delivery, drops, duplicated messages, room expiry, legacy clients, two tabs and offline gaps, with the versioned handshake, the g1: generation, record hashes computed on both sides and scoped acknowledgements. The oracles check for no live loss against a plain merge, complete quarantine, no old-generation write in the live document, convergence, nothing dropped before its acknowledgement, and no stuck client or room.

run seeds result
gc off 1,000 999 clean; 1 threw $getTextNodeOffset: invalid offset in core Lexical's selection code (RangeSelection.isBackward), a known core error that reproduces on main, with nothing lost
gc on 1,000 1000/1000 clean
racing authorities with compare-and-set 400 400/400 clean

Controls, 100 seeds each (seeds flagged): sv 100, nofence 100, noack 100, fresh 100, ackbare (an acknowledgement by bare hash) 100, noactionable 86, noquiesce 81, inc0 48, capbase 36, race without compare-and-set 31, shared 9; nodefer and drainall 0, as on every run.

Offline edits across an upgrade (crash mid-upload, a lost acknowledgement, acknowledged then crashed before clearing, two tabs of one profile, two upgrades while offline, the fence moving during an upload, an authority restart mid-write, storage eviction, long sessions), 12 deterministic scenarios plus a fuzz: 300/300 clean; controls caught: acknowledge before the write 99, bare-hash acknowledgement 97, no deduplication 87, no eviction marker 53, clear on send 15, overwrite 4 (of 100 each).

A downstream app's suites (lint, types, unit, docs, Artifacts and its room, edit and codec fuzz suites) against main: 0 tests differ. Its 378 stored documents migrated four ways (gc off and on, the real 1to2 step and a test step rewriting every format item) read as before, headless and bound, and stay editable: 1,512 of 1,512.

The playground's collab-y e2e (chromium): 33/33 with the version gate specs expecting the raw-write warning of the newer client they simulate (the last commit).

@vercel

vercel Bot commented Nov 3, 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 Nov 5, 2026 7:21am UTC
lexical-playground Ready Ready Preview Nov 5, 2026 7:21am 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 Nov 3, 2026
@meta-code-review

meta-code-review Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

AI review status for this pull request.

Review status Updated
🟢 Reviewed (for maintainers only) Nov 5, 2026, 7:41 AM UTC

@pkg-pr-new

pkg-pr-new Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
lexical

npm i https://pkg.pr.new/lexical@9766

@lexical/a11y

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

@lexical/clipboard

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

@lexical/code

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

@lexical/code-core

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

@lexical/code-prism

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

@lexical/code-shiki

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

@lexical/compiler

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

@lexical/devtools-core

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

@lexical/dragon

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

@lexical/eslint-plugin

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

@lexical/extension

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

@lexical/fast-check

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

@lexical/file

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

@lexical/hashtag

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

@lexical/headless

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

@lexical/history

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

@lexical/html

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

@lexical/internal

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

@lexical/link

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

@lexical/list

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

@lexical/mark

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

@lexical/markdown

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

@lexical/mdast

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

@lexical/offset

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

@lexical/overflow

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

@lexical/plain-text

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

@lexical/react

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

@lexical/rich-text

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

@lexical/selection

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

@lexical/table

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

@lexical/tailwind

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

@lexical/text

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

@lexical/utils

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

@lexical/y

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

@lexical/yjs

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

commit: e089a1c

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough layout-migration work and the detailed test plan. Two things should be fixed before this lands, and a few smaller suggestions follow.

1. hasNewYEdits and quarantineRecord(input, base) throw when the replica is behind its base (packages/lexical-y/src/internal/Server.ts:793)

The deletion pass walks every live item of the base and calls view.doc.store.getItem(...) for each clock. getItem in @y/y assumes the clock exists. Suppose the base holds later clocks of a client the replica also holds, because a collaborator edited both before and after the replica's last sync. Then the lookup reads past the struct array and throws TypeError: Cannot read properties of undefined (reading 'id'), with gc off and on. That is the usual shape of a stale handoff or a legacy capture, so quarantineRecord(input, base) cannot be built for it.

Minimal repro: seed a doc, have client 500 type a, and snapshot that as the replica. Then have client 500 type b, and use that state as the base. hasNewYEdits({snapshot: replica, deltas: [], queue: [], signals: [], draft: null}, base) throws instead of returning false.

Suggested fix: bound the inner loop by view.doc.store.getClock(client), since a clock the view never received cannot have been deleted in it:

const end = view.doc.store.getClock(client);
for (const s of structs) {
  if (!(s instanceof Item) || s.deleted) {
    continue;
  }
  for (let i = 0; i < s.length && s.id.clock + i < end; i++) {
    // ...
  }
}

With that change the repro returns false and MigrateServer.test.ts still passes. Please also add a behind-base record to the quarantine tests: today every replica in MigrateServer.test.ts is built from the base's own state, and packages/lexical-y/AGENTS.md asks for tests drawn from the input space.

2. The unit job fails on the new sub-entry (scripts/__tests__/unit/build.test.ts:110)

core-tests / unit (24.x) fails "should have a source file for exported module @lexical/y/migrate/1to2". The package audit lists only top-level src/*.ts (build.test.ts:61-65), while scripts/updateVersion.mjs and scripts/shared/PackageMetadata.mjs now treat src/<entry>/<name>.ts as an export. CONTRIBUTING.md asks that the test suite pass, and teaching the audit the same sub-entry rule should fix it.

Suggestions (optional)

  • packages/lexical-y/flow/LexicalYMigrate.js.flow: YLayoutMigration is missing checkAfter(container: YNode): ReadonlyArray<string>, which the TypeScript interface and the runner's step check both require, so a Flow-typed custom step is refused as invalid-steps. AGENTS.md asks that APIs keep both their TypeScript and Flow types.
  • @lexical/y/server bundles its own copy of the runner and does not export YMigrationError. In the published packages, error instanceof YMigrationError (with the class imported from @lexical/y/migrate) is therefore false for errors from prepareYRoom, while y-server.md tells servers to act "on a YMigrationError". Re-exporting the class from @lexical/y/server and suggesting a code check, or sharing one runner between the two entries, would fix it.
  • UNSUPPORTED_EDIT_WARNING says "an earlier warning says why the binding is read only" (packages/lexical-y/src/internal/Binding.ts:4092), but with the write-time gate it now arrives before the layout warning that explains it.
  • packages/lexical-y/AGENTS.md asks that every bug fix land a regression test in src/__tests__/unit/regressions/, but the tests for the two [fix] commits live in unit/. The headless transact case in MigrateHistoryGate.test.ts also passes on any throw; asserting the 'read-only' refusal would make it a real check.
  • packages/lexical-y/DECISIONS.md: D102 replaces part of D09, but D09's row does not say so, and D102 is still OPEN while this PR ships its protocol.
  • The comment in applyUndo refers to UndoManagerOf; the class is BindingUndoManager.

continue;
}
for (let i = 0; i < s.length; i++) {
const it = view.doc.store.getItem({

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getItem assumes the clock exists in the view. When the base holds later clocks of a client the replica also holds (a collaborator edited before and after the replica's last sync), this reads past the struct array and throws TypeError: Cannot read properties of undefined (reading 'id'), so hasNewYEdits and quarantineRecord(input, base) fail on an ordinary stale record. Bounding the loop fixes it:

const end = view.doc.store.getClock(client);
// ...
for (let i = 0; i < s.length && s.id.clock + i < end; i++) {

A clock the view never received cannot have been deleted in it. Please add a behind-base record to MigrateServer.test.ts too.

): {readonly written: number, readonly deleted: number},
readBefore(container: YNode): ReadonlyArray<string>,
readAfter(container: YNode): ReadonlyArray<string>,
rewrites(key: string): boolean,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

checkAfter is missing here. The TypeScript YLayoutMigration requires it, and the runner's step check refuses a step without it (invalid-steps), so a Flow-typed custom step written to this declaration is rejected. Suggest adding checkAfter(container: YNode): ReadonlyArray<string>,.

Comment thread scripts/updateVersion.mjs
}
// Sub-entries of an entry: src/<entry>/<name>.ts is exported as
// "<package>/<entry>/<name>" (e.g. @lexical/y/migrate/2to3).
const subDir = pkg.resolve('src', basename);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The public package.json audit in scripts/__tests__/unit/build.test.ts:61-65 still lists only top-level src/*.ts, so core-tests / unit fails with "should have a source file for exported module @lexical/y/migrate/1to2". It needs the same sub-entry rule as this generator and PackageMetadata.getExportedNpmModuleEntries.

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. The runner's checks are thorough, the write-time layout gate closes a real gap, and the new entries stay out of the core bundle. On main, an editor write or an undo made inside an app transaction that removes the layout record, or adds a newer or malformed one, is stored before the binding turns read only; on this branch nothing is written, and the cause is reported before the refusal. The suggestions below are optional and non-blocking.

  1. binding.undoManager event order (packages/lexical-y/src/internal/Binding.ts, BindingUndoManager / gatedStep, L246–311). Because undo() and redo() now run Yjs's step inside an outer transaction, stack-item-popped fires before that transaction ends. A listener sees an empty changedParentTypes, canRedo() still false right after an undo, and the editor not yet updated (on main: one changed type, canRedo() true, the editor already updated). YCollabExtension still ends in the right state because it also listens to stack-item-added, but app code that reads state in stack-item-popped (a cursor restore from stackItem.meta, a toolbar reading canRedo()) will see stale values. AGENTS.md's Backwards Compatibility section asks that existing public APIs keep their behavior. You could hold the stack-item-popped emitted during a gated step and re-emit it after the outer transact returns, with that transaction's changedParentTypes, or document the new order in the changeset and y.md.
  2. migrateLocally on a nested root (Binding.ts L1893). For a root held inside another shared type, the binding returns without migrating. Because migrateLocally is set, the 'older' warning is also suppressed and nothing reaches onError, so the document stays read only with no signal to the app. Nothing reaches this while MIN_LAYOUT is 1. Consider reporting it through onError (or keeping the warning), and listing the top-level-only limit in y.md (packages/lexical-y/AGENTS.md asks that accepted limits also appear in y.md's Limits).
  3. Handshake shape (packages/lexical-y/src/internal/Server.ts L325). checkYSession destructures client.layouts and uses material as given, but the handshake arrives over the network. Consider returning refuse-layout for a malformed handshake, or adding a line to y-server.md telling servers to validate it before calling.
  4. Nits: internal/Layouts.ts L14 mentions a @lexical/y/relay entry (the entry is @lexical/y/server), and internal/constants.ts L62 says the epoch "only grows", but each migration replaces it.

On evidence: the corpus runs and the generation-fence soak in the test plan cannot be rerun from the repository, and quiesce()'s handling of an IME composition is covered only in jsdom, so a browser-mode test would be a good follow-up. The replay, the reference relay and the 2→3 step are noted as planned follow-ups, and I haven't treated them as part of this PR.

* document ran, any of which may change the layout record before anything
* is written. Refused, it writes nothing and returns null.
*/
function gatedStep(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: because this wraps Yjs's undo in an outer transact, Yjs emits stack-item-popped before that transaction ends. A listener on binding.undoManager then sees an empty changedParentTypes, canRedo() still false after an undo, and the editor not yet updated (on main: one changed type, true, updated). Holding that event during a gated step and re-emitting it after transact returns (with that transaction's changedParentTypes) would keep the existing event contract (AGENTS.md, Backwards Compatibility).

}
});
}
if (name === null) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: for a nested root this returns silently, and since migrateLocally is set, the 'older' warning is suppressed too, so the app gets neither a warning nor an onError and the document stays read only. Consider reporting it through onError here, and noting the top-level-only limit in y.md.

client.generation !== UNKNOWN_GENERATION &&
client.generation === room.generation;
// Every served root inside the client's range.
const [min, max] = client.layouts;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: the handshake comes from the client, so a malformed one (no layouts) throws here, and a non-boolean material is coerced. Consider returning {verdict: 'refuse-layout'} for a handshake that is not well formed, or telling servers in y-server.md to validate it first.

import {DEFAULT_ROOT_NAME, EPOCH_KEY, LAYOUT_PREFIX} from './constants';

// The layout record and the epoch as the migration runner and the relay
// helpers read them (see @lexical/y/migrate, @lexical/y/relay). Small on

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: there is no @lexical/y/relay entry; this reads @lexical/y/server.

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good. The migration mechanism is additive and ships behind MIN_LAYOUT = 1, so existing documents are untouched. The write-time layout gate closes a real gap: on main, an editor write inside an app transaction that removes or breaks the layout record is stored before the binding turns read only; with this change it is refused. The regression tests under src/__tests__/unit/regressions/ follow packages/lexical-y/AGENTS.md. Everything below is optional and non-blocking.

1. prepareYRoom on a room a newer client moved ahead (packages/lexical-y/src/internal/Runner.ts:554). planOf refuses any served root above max(to, LAYOUT_VERSION) with 'newer' before it checks whether that root needs a step, and prepareYRoom defaults to to MIN_LAYOUT. For a stored room recording lexical-y:3, prepareYRoom(stored, {incarnation, steps: [step1to2]}) throws YMigrationError with code 'newer', and so does the same call with steps: []. Meanwhile checkYSession on the same room admits a client reading [1, 3].

Step 3 of "The migration moment" in y-server.md says that when no served root is below MIN_LAYOUT the call returns changed: false, and that any YMigrationError should leave the room stuck. Once layout 3 ships, a server one release behind its clients that follows the guide would stop serving those rooms. Could a root with no step to run come back unchanged, keeping 'newer' for a chain that cannot start? Or could step 3 say that the authority must upgrade before its clients?

2. Reproducible fence evidence. The test plan's generation-fence fuzz, its controls, and the catalog and app corpus runs were all run outside the repository, the fence fuzz on an earlier revision. packages/lexical-y/AGENTS.md asks for tests drawn from the catalogs. Landing the fence fuzz under src/__tests__/fuzz/, or rerunning it on this head, would let others reproduce the no-loss claims.

3. quiesce() during a native composition (packages/lexical-y/src/internal/Binding.ts:1867). quiesce() ends the composition by clearing the composition key, and its tests set a synthetic composition key under jsdom. AGENTS.md reserves real input behaviour for the browser tier. A browser test that composes and then quiesces would show what happens to a native composition that is still open.

4. Malformed handoff bytes. quarantineRecord, sourceView and hasNewYEdits throw Yjs's decoder error when a snapshot is not a valid update. These bytes come from the network, so the quarantine section of y-server.md could say so and tell servers to refuse such an upload without acknowledging it. It already gives that guidance for a malformed handshake.

5. Sub-entry export convention (scripts/updateVersion.mjs:426-442). Every src/<entry>/<name>.ts of a multi-entry package now becomes a public subpath. Only packages/lexical-y/src/migrate/ matches today. A line in the Build System section of AGENTS.md, or an explicit opt-in, would stop a future helper file from being published by accident.

return {from: null, root: name, steps: []};
}
const from = record.layout;
if (from > ceiling) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: this refuses a root above max(to, LAYOUT_VERSION) before checking whether it needs a step. With prepareYRoom's default to (MIN_LAYOUT), a stored room recording lexical-y:3 throws 'newer', even with steps: [], while checkYSession admits a client reading [1, 3] to the same room. Step 3 of "The migration moment" in y-server.md says such a call returns changed: false. Returning the root unchanged when from >= to (and refusing only a chain that cannot start), or documenting server-before-client upgrades, would line the two up.

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good. The migration runner checks a lot before writing anything, the @lexical/y/server handshake table is fully tested, and the write-time gate closes a real gap on main for writes made inside an app transaction. Everything below is optional and non-blocking.

  1. README contradicts the new epoch gate. packages/lexical-y/README.md:194 says the epoch is outside the lexical-y: namespace, "so no layout gate parses it". This PR makes a malformed lexical-y-epoch open the document read only in the binding, in headless reads and edits, in the runner and in describeYRoom. The JSDoc on EPOCH_KEY and the feature changeset already say so. Suggested wording: "…outside the lexical-y: namespace; a malformed one opens the document read only, as a malformed layout record does."
  2. Assert the editor in the put-back regression. regressions/MigrateHistoryGate.test.ts:317 (record broken and restored around an editor write) checks the document, the status and the warning, but not what the editor shows. With the record restored the binding stays active, and the refused paragraph leaves the editor only through the queued re-read. packages/lexical-y/AGENTS.md asks for a regression test that pins the fix, so after the flush add an assertion that the editor's text no longer contains forbidden.
  3. Document what a skipped range costs at migration time. migrateYState cuts everything from a gap in a client's clocks onwards into pending. Yjs 14 integrates items past such a gap, so connected clients have already seen that text, and regressions/MigrateSkippedRange.test.ts shows it missing from the migrated state. It is kept in the pending record, but users see it only read only until replay ships. Step 4 of "Migrating stored documents" in packages/lexical-website/docs/collaboration/y-server.md could say so plainly.
  4. Same idea of "pristine" in describeYRoom as in the runner. src/internal/Server.ts:235 counts deleted items and deleted attributes (_start, _map.size). The runner (Runner.ts:543) and the binding look only at live content. A served root whose content and records were all deleted is unreadable to checkYSession, while the runner calls it pristine and a binding would seed it. Live length and getAttrs() would match.
  5. Flow literal types. flow/LexicalYServer.js.flow:28-30 types LAYOUT_VERSION, MIN_LAYOUT and SEED_LAYOUT as number, while flow/LexicalY.js.flow and the TypeScript of both entries use the literals. AGENTS.md asks for TypeScript and Flow types to be kept together.
  6. Evidence for later. The end-to-end generation-fence fuzz in the test plan ran on a revision before the review fixes. It would be worth re-running on the final head before the layout 3 change raises MIN_LAYOUT and starts relying on the fence. binding.quiesce() ending an IME composition is so far tested only with a synthetic composition key in jsdom. A browser-mode test would cover a real composition once an app wires quiesce() up.

Thanks for keeping each review fix in its own commit with a regression test; it made the gate changes easy to follow.

Comment thread packages/lexical-y/README.md Outdated
transaction as the layout record it adds: `layout` is that version,
`(client, clock)` the id of that record's item (the transaction's first),
`step` and `revision` the step that ran (`lexical-y/layout/<n>to<n+1>`). It
is outside the `lexical-y:` namespace, so no layout gate parses it; each

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional nit: this PR makes a malformed lexical-y-epoch open the document read only (binding, headless, runner, describeYRoom), as the EPOCH_KEY JSDoc and the changeset say. Maybe: "…outside the lexical-y: namespace; a malformed one opens the document read only, as a malformed layout record does."

await flush();
expect(text(t.root)).toBe(before);
expect(t.binding.status).toBe('active');
expect(t.warnings).toEqual(['read-only']);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: with the record put back the binding stays active, and the refused paragraph leaves the editor only through the queued re-read. An assertion that the editor's text no longer contains forbidden after the flush would pin that, too.

let pristine = true;
for (const name of [...roots].sort()) {
const root = existingRoot(doc, name);
if (root === null || (root._start === null && root._map.size === 0)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional nit: _start/_map.size count deleted items and attributes, while the runner (Runner.ts:543) and the binding look only at live content. A served root whose content and records were all deleted is unreadable here but pristine to the runner. root.length === 0 && Object.keys(root.getAttrs()).length === 0 would match them.

and the stored bytes: store nothing. On a `YMigrationError` (the class
`@lexical/y/migrate` exports, which `@lexical/y/server` uses), store
nothing, keep the room stuck (it applies nothing), and alert.
4. **Commit atomically**, compare-and-set on the version read:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: it may help to say here that pending material can include text clients already saw. Yjs 14 integrates items past a gap, and the runner cuts them (see MigrateSkippedRange.test.ts), so until replay ships that text shows only in the read-only record.

Comment on lines +28 to +30
declare export var LAYOUT_VERSION: number;
declare export var MIN_LAYOUT: number;
declare export var SEED_LAYOUT: number;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional nit: LexicalY.js.flow declares these as the literals 2, 1, 1, and the TypeScript of both entries carries the literals too. The same here would keep the Flow entries aligned.

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. The write-time gate closes a real gap. An editor write made inside an app's doc.transact (or after a beforeTransaction listener) that leaves the layout record newer, missing or malformed, or records a newer schema, was stored before this change and is refused after it. The migration entries stay out of the core bundle, and the new tests exercise both gates in both directions.

All of the following are optional and non-blocking:

  1. Warnings reference (packages/lexical-website/docs/collaboration/y.md, the Warnings table). The UNSUPPORTED_LAYOUT_WARNING row does not list the new 'older' data (found, min, supported). The UNSUPPORTED_EDIT_WARNING row still says it is reported once each time the binding goes read only, but an active binding now reports a refusal at write time every time one happens.
  2. README epoch paragraph (packages/lexical-y/README.md:194). "No layout gate parses it" no longer holds: this release opens a document whose lexical-y-epoch is malformed read only. Saying that older releases ignore the attribute and this one checks it would match the code and the changeset.
  3. Fence fuzz evidence. The generation-fence fuzz table in the description ran before the review fixes, and those fixes changed checkYSession, describeYRoom and hasNewYEdits. AGENTS.md asks the Test plan to paste the real output of what was run, so re-running it on the final head, or marking the table as pre-fix, would keep it accurate.
  4. Rollout note (y-server.md, the handshake table). Under row 2, a fence-aware client holding pre-fence material sends 'unknown' and is stale, even in an inherited room that never migrated. While replay is not shipped, its offline edits become read-only quarantine records. One sentence next to the table would help apps plan the client rollout.
  5. Sub-entry export scan (scripts/updateVersion.mjs:426-442). It publishes every src/<entry>/<name>.ts of every package. AGENTS.md keeps single-entry helpers under src/internal, so a future helper placed next to the steps would become a public subpath without anyone choosing it. Consider scoping the scan, for example with an opt-in list.
  6. Nits. The feature changeset (.changeset/lexical-y-layout-migrations.md) is one 1,200-character line, while AGENTS.md gives the format as [category] one-line summary; a short first line plus a body paragraph would read better. In packages/lexical-y/src/internal/Binding.ts, the comment at lines 355-358 is orphaned (it belongs to undoAdmits), and line 368 refers to admitsNow, which is admitsIn.

Comment thread packages/lexical-y/README.md Outdated
transaction as the layout record it adds: `layout` is that version,
`(client, clock)` the id of that record's item (the transaction's first),
`step` and `revision` the step that ran (`lexical-y/layout/<n>to<n+1>`). It
is outside the `lexical-y:` namespace, so no layout gate parses it; each

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: this release does parse the epoch. A malformed lexical-y-epoch opens the document read only (malformedLayout in Binding.ts, and the feature changeset says so too). What holds is that older releases' gates ignore it, since it is outside the lexical-y: namespace. Could this sentence say both?

/**
* How a BindingUndoManager asks its binding whether it may write, before
* the step and again inside its transaction: a fresh request, checked
* against the records as they are (see Binding.admitsNow).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Binding.admitsNow does not exist; the method is admitsIn. Also, the comment at lines 355-358 ("Each BindingUndoManager's check…") is orphaned above SchemaGrace; it belongs to undoAdmits here.

Comment thread scripts/updateVersion.mjs
}
// Sub-entries of an entry: src/<entry>/<name>.ts is exported as
// "<package>/<entry>/<name>" (e.g. @lexical/y/migrate/2to3).
const subDir = pkg.resolve('src', basename);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: this scan runs for every package, so any src/<entry>/<name>.ts becomes a public subpath. Today only @lexical/y/migrate matches, but AGENTS.md keeps single-entry helpers under src/internal, and a helper later placed next to the steps would be published without anyone choosing it. Consider an opt-in list of packages or entries.

| # | Client | Verdict |
|---|---|---|
| 1 | no handshake (a release before the fence) | `admit` as today when the room's incarnation is inherited (the room existed before the fence) and it never migrated or was replaced; otherwise `legacy`: capture it |
| 2 | material, and another (no, an unknown) generation, or a served root's layout outside `layouts` (or a served root without a layout record), or a never-seeded room whose seed contract is not `seed` | `stale`: no sync either way; the client hands off its material, then connects again. A client holding material is never refused before its material is acknowledged |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: worth a sentence that under this row, a client upgraded to a fence-aware release that holds pre-fence material ('unknown') is stale even in an inherited room that never migrated. Until replay ships, its offline edits become read-only quarantine records.

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough work here: the migration runner's checks, the frozen step with goldens, and a regression test per fix make this large change reviewable. I found one defect that I think should be fixed before merging, plus a few optional suggestions.

Must fix: D08's permitted write loses its pin and its recovery when it records the client's schema version

packages/lexical-y/src/internal/Binding.ts:4411 captures D08's permission as the schema records before the write. The admitted write then records the client's own lexical-y-schema:<n> in its finally (:5075-5079). The pin transaction (:5095) and the recovery rewrite (:5120) compare the records exactly with the captured ones (sameSchemaRecords, :3048), so they refuse. The description says this permission "carries through its own recovery and pins"; today it does not on a client's first write at a new schemaVersion.

To reproduce:

  1. Take a layout 1 document that records only lexical-y-schema:1.
  2. Bind it with schemaVersion: 2.
  3. Append a paragraph while a peer update recording lexical-y-schema:3 is applied inside the same editor.update.

Main stores the text and records k:paragraph. This branch stores the text and lexical-y-schema:2 but no k:paragraph. The README's wire format promises that "the first write of a type records its kind on the root (k:<type>)", so a later client whose class derives another kind uses the recorded one. If the same document already records schema 2, the pin is written. In the same race, a write that fails part way is no longer rewritten by the recovery: what the failed attempt wrote stays, and the edit is dropped.

A possible fix: take the records again at the end of the admitted write transaction (after recordSchema) and use those for the pin and recovery transactions, or ignore lexical-y-schema:<own version> = true in that comparison. packages/lexical-y/AGENTS.md asks every fix to land with a regression in src/__tests__/unit/regressions/. The existing D08 controls all bind schemaVersion: 1 to a document that already records it (rawDoc), so the new test should use a version the document does not record yet.

Optional suggestions (non-blocking)

  1. Warnings reference (packages/lexical-website/docs/collaboration/y.md, the Warnings table). The UNSUPPORTED_LAYOUT_WARNING row does not list the new 'older' data (found, min, supported). The UNSUPPORTED_EDIT_WARNING row still says it is reported once each time the binding goes read only, but an active binding now reports every write refused at write time.
  2. README epoch paragraph (packages/lexical-y/README.md:194). "No layout gate parses it" no longer holds: this release opens a document whose lexical-y-epoch is malformed read only.
  3. Refusal message (Binding.ts:2997). It blames the layout record even when a schema record refused the write at write time; "the layout or schema record" would match both paths.
  4. Fence fuzz evidence. The generation-fence table in the description ran before the review fixes, which changed checkYSession, describeYRoom and hasNewYEdits. AGENTS.md asks the Test plan to paste the real output of what was run, so re-run it on the final head or mark it as pre-fix.
  5. Rollout note (y-server.md, handshake row 2). A fence-aware client holding pre-fence material is stale even in an inherited room that never migrated, and with replay not shipped its offline edits become read-only records. One sentence beside the table would help apps plan the client rollout.
  6. Sub-entry export scan (scripts/updateVersion.mjs:426-442). It publishes any src/<entry>/<name>.ts of every package. AGENTS.md keeps single-entry helpers under src/internal, so an opt-in list would stop a future helper beside the steps from becoming a public subpath by accident.
  7. Nits. The feature changeset is one 1,203-character line, while CONTRIBUTING.md gives the first line as [category] one-line summary. In Binding.ts, the comment at lines 356-359 is orphaned (it belongs to undoAdmits), and line 388 refers to admitsNow, which is admitsIn. In flow/LexicalYServer.js.flow, the createYDoc comment sits above the layout constants.

} else if (this.schemaRefuses()) {
// Made before a schema record it did not see (D08): written, on
// exactly these records (see admitsIn).
grace = {records: this.schemaRecords()};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

D08's permission is captured here as the schema records before the write. The admitted write then records this client's own lexical-y-schema:<n> (:5075-5079), so the pin transaction (:5095) and the recovery rewrite (:5120) see a record the write itself added and refuse. On a client's first write at a new schemaVersion, racing a peer's newer record, the paragraph is stored without its k:paragraph pin (main records it), and a write that fails part way is not rewritten. Taking the records again at the end of the admitted write transaction, or ignoring lexical-y-schema:<own version> = true in the comparison, would carry the permission through as the description says.

Comment thread packages/lexical-y/README.md Outdated
transaction as the layout record it adds: `layout` is that version,
`(client, clock)` the id of that record's item (the transaction's first),
`step` and `revision` the step that ran (`lexical-y/layout/<n>to<n+1>`). It
is outside the `lexical-y:` namespace, so no layout gate parses it; each

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This release does parse it: a malformed lexical-y-epoch opens the document read only (malformedLayout, and the feature changeset says so). Suggest: older releases ignore it; this one opens a document whose epoch is malformed read only.

private warnRefusedAtWrite(): void {
this.warn(
UNSUPPORTED_EDIT_WARNING,
"a local change was not written: when it was written (inside an app's transaction) the document's layout record was missing, malformed or one this version does not write. It is not retried, since a retry would write outside that transaction: edit again (see binding.status)",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this message also reaches a write refused by a schema record a beforeTransaction listener made newer or malformed (:4773), so it blames the layout record for a schema refusal. "the layout or schema record" would cover both.

zurfyx added a commit that referenced this pull request Nov 4, 2026
…ate, the authority's replay of a quarantine record and the state its recovery view renders

## Description

Stacked on #9766 (layout migrations and the generation fence). That PR
keeps whatever a stale or pre-fence session sends in a quarantine record
and never merges it. The edits such a record holds were only shown read
only for users to copy from. This PR adds the two pieces y-server.md had as
planned, both to `@lexical/y/server`, Yjs only (no Lexical):

**`replayYRecovery(record, base, current, config) -> {eligible, reason, update, state, receipt, conflicts}`**

It replays a record's own changes onto the current document by Yjs identity.
The authority applies the result as a checked edit: compute on the state of
a version, apply `update` and commit `receipt.ledger` only while that
version holds, and compute again after a lost compare-and-set.

- **Eligibility:** the record's incarnation is the room's, its source
  generation is the `base` given, and every transition since was an in-place
  migration (`inPlace`). Anything else is `eligible: false`, writes nothing,
  and stays in the recovery view.
- **What is the record's own:**
  - the items of its source view outside the base's accepted ids (integrated
    in the base and present in the current document). A skipped range,
    pending material or what a migration split out is not accepted, so it
    comes back through its record;
  - the base's live items it deleted;
  - items an earlier replay of the same source inserted that it deleted
    since, through the ledger.
  - Items matching the record's legacy signals exactly (id, parent, key,
    content) are left out.
- **Inserts** are authored again at their original neighbours, under client
  ids in the same gap of the current document's clients (so they keep their
  order against concurrent inserts) and outside `reserved`. An insert whose
  container is deleted or gone, or whose neighbour is collected, is a
  conflict, as is anything anchored to it. **Deletions** delete the same
  units where they are still live.
- **Formats and attributes** apply only where the base value is proven and
  still current:
  - only a `peers: false` record proves base values. With peers, its format
    and attribute changes are conflicts, while its inserts and deletions
    still apply;
  - a value's chain may only pass through items written under the record's
    `clients`;
  - an attribute applies only when the current entry is still the one its
    write superseded.
  - Everything else is a conflict, listed with its reason ('the replica had
    peers', 'not written by the replica', 'base value unknown', 'changed
    since').
- **Per-layout format codec.** Current values are read, compared and written
  through the codec of the layout the current document's root records
  (`{read, write, same}`; layouts 1 and 2: the plain fold; `config.codecs`
  adds or overrides one). The codec writes only containers with an applied
  change. A root at a layout without a codec makes the record ineligible
  ("layout N has no replay codec"). Layout 3 registers its codec with the
  layout 3 change: until then a room at layout 3 does not replay, and its
  records stay in the recovery view.
- **Drafts:** a draft that differs is reported (`shown`), never applied.
- **Ledger:** one entry per change, keyed by source incarnation and
  generation, root, change kind, source item (and unit range or key), with
  its outcome (applied, satisfied, conflict) and result ids. Applied units
  are skipped, so a retry or two overlapping records apply each change once;
  a conflict is decided again; an entry never covers another source
  generation's ids.
- **Receipt:** every change with its status (applied, satisfied, unchanged,
  conflict, skipped, shown), the conflicts, and the new ledger entries.

**`recoveryYState(record, steps, base?, options?) -> Uint8Array`**

It returns the state a recovery view renders for a record: the record's
source view (a `pendingYRecord` record's whole stored state and its cut
bytes; `base` for a record without a snapshot), migrated on a scratch copy
to the current layout with the authority's steps.

- **Gaps:** every skipped range becomes a collected struct of the same
  length and leftover pending material is dropped. Nothing is split off, so
  items a migration cut stay visible in place.
- **Signals:** the record's legacy signals are left out, so the view does
  not render as "newer version".
- **Render only.** The result holds collected structs the record never had
  and a scratch migration. Never store it, send it into a room, merge it or
  replay it: its doc comment and y-server.md say so. An authority can serve
  it to a lazily loaded client view, so no client carries migration code.

**Also in this PR:**
- `plainRead` (the plain layout 1/2 read) and the types `YReplayChange`,
  `YReplayResult`, `YReplayConfig`, `YReplayCodec` and `YRecoveryOptions`
  are exported.
- The internal stub that threw is removed.
- The replay uses `AbstractContent#copy`, `#splice` and the `GC` export. They
  join the migration part of the Yjs contract, which only the server and
  migrate entries probe. The core entry's output is byte-identical.
- y-server.md's quarantine section describes the replay and the recovery
  view.

Limits:
- **Layout 3 sources:** a source view itself past layout 2 proves no base
  value of a format, so its format changes are conflicts. This first
  matters at a migration past layout 3.
- **Ineligible records** (a legacy capture, an unknown or unbased
  generation) are never replayed. They are for the recovery view.

## Changeset

`.changeset/lexical-y-replay-recovery.md`: `@lexical/y` patch, `[feature]`.

## Test plan

### Before

```
$ cd packages/lexical-y && node --input-type=module -e "const m = await import('@lexical/y/server'); console.log('replayYRecovery:', typeof m.replayYRecovery, '| recoveryYState:', typeof m.recoveryYState)"
replayYRecovery: undefined | recoveryYState: undefined
```

### After

```
$ cd packages/lexical-y && node --input-type=module -e "const m = await import('@lexical/y/server'); console.log('replayYRecovery:', typeof m.replayYRecovery, '| recoveryYState:', typeof m.recoveryYState)"
replayYRecovery: function | recoveryYState: function

$ for g in 0 1; do LEXICAL_Y_GC=$g REPLAY_SEEDS=60 pnpm exec vitest --run --project unit packages/lexical-y/src/__tests__/unit/Migrate*.test.ts packages/lexical-y/src/__tests__/unit/Source.test.ts packages/lexical-y/src/__tests__/unit/YjsContract.test.ts; done
 Test Files  10 passed (10)
      Tests  346 passed (346)
 Test Files  10 passed (10)
      Tests  346 passed (346)

$ for g in 0 1; do LEXICAL_Y_GC=$g REPLAY_SEEDS=60 pnpm exec vitest --run --project unit packages/lexical-y; done
 Test Files  273 passed | 2 skipped (275)
      Tests  19727 passed | 367 expected fail | 131 skipped (20225)
 Test Files  273 passed | 2 skipped (275)
      Tests  19724 passed | 370 expected fail | 131 skipped (20225)
```

**`MigrateReplay.test.ts`** (84 cells, bound editors, gc off and on, each
after the real 1to2 step and after a test-only step that rewrites every
format item):
- offline typing, and deletions (including one already made);
- formats with and without a racing current writer (different keys; the
  same key; another value: a conflict, current kept);
- an insert into a deleted line (placed as a live merge places it) and into
  a deleted container (a conflict);
- block attributes (applied; a conflict);
- typed-then-deleted text with later text anchored to it, and new blocks;
- the ledger: a second replay writes nothing, and overlapping records split
  differently apply each unit once;
- determinism, eligibility, and a draft-only record;
- a container, a line or text removed then restored by undo offline;
- random offline sessions, 60 seeds each:
  - no current writer: equal to the record merged into the base;
  - a current writer on other lines: equal to a live merge;
  - a current writer anywhere: every replayed token once, nothing of the
    current writer lost, and a missing token only with a conflict listed.

**`MigrateReplayProbes.test.ts`** (44 cells, raw Yjs shapes, gc off and on):
- attributes:
  - two replicas with identical bytes, one that saw an attribute set and
    one that saw it removed, both conflict;
  - a peer-free replica's double write is exact through its own entries;
  - a chain through a client the record does not list conflicts;
- peers, declared or by default, and a peer's deletion before the write
  (a conflict, current kept);
- the ledger: mapped deletion of a replayed insert; scope (one source
  generation never skips the same id in another); a conflict decided
  again;
- deletions: partly done in current; known only through the view's delete
  set;
- sparse bases: a skipped range is inserted, an item the base holds is
  not;
- split material back once, and an item cut for its right origin back in
  place;
- `pendingYRecord` records;
- format exactness: the base item live, or deleted;
- the signal transcript: an edit sharing the signal's id is kept;
- a container deletion (D49: as an unfenced merge);
- codecs: a root at a layout without one is ineligible; a codec given for
  it reads and writes the formats.

**`MigrateRecovery.test.ts`** (8 cells, gc off and on):
- a capture record at layout 1 whose client got its signal: the view is at
  layout 2, has no gaps, and reads as the client's own document without the
  signal;
- a pending record with a skipped range: the migrated room lacks the cut
  text, while the view shows it in place;
- a pending record read on a given base;
- a record already current: inputs untouched.

**Wrong implementations, each failing cells:**
- replay (13): no deletions; no format conflict; no container check; no
  attribute exactness; a state-vector base; inexact values taken as exact;
  an unscoped ledger; no mapped deletion; no signal match; no peers rule;
  no superseded chain; a pending record read without its base; no codec
  write (28 cells);
- recovery view: no gap filling (2 cells); no signal exclusion (2).

**Randomized end to end** (a simulated authority with clients and tabs that
type, format, undo, compose, go offline and reconnect across an in-place
1to2 migration under the fence, gc mixed). The authority replays each
handoff and pending record after the handoff as a checked edit:

| run | seeds | result |
|---|---|---|
| fence + replay | 1,200 | 1,198 clean; 2 flagged by diagnostics (below) |
| a current-generation update between compute and commit (the compare-and-set retries) | 600 | 600 clean |
| replay off | 600 | 600 clean |

Every run checked that:
- every replayed character is present once, by identity;
- nothing of the old generation is in the live document;
- nothing typed is lost at the end of the run;
- the replay deletes only what the record deleted (modulo D49 and mapped
  deletions);
- nothing extra is added;
- a racing writer's value survives.

No run lost, leaked or duplicated anything. The two seeds flagged by
diagnostics, reproduced and read item by item:
- **Unfenced-merge comparison.** An unfenced merge of the record kept two
  characters the replay did not write: an insert the replica had received
  but never integrated (it lacked the insert's dependency, which only the
  current document holds), so its record carries it as pending structs.
  The replay reads integrated items only. Nothing is lost at the end of the
  run.
- **Character-level deletion check.** The record held two copies of a
  character: one the base had deleted (another client, before the
  migration), and a later copy it deleted itself. The replay deletes that
  copy, as the record did, and an unfenced merge reads the same. The check
  counts characters, not ids.

Server entry size (production build):

| | before | after |
|---|---|---|
| `LexicalYServer.prod.js` | 18,230 B (6,639 B gzip) | 35,509 B (12,040 B gzip) |
| `LexicalYMigrate.prod.js` | 26,579 B (9,132 B gzip) | 26,640 B (9,167 B gzip): the migration contract probe's new members |
| `LexicalY.prod.js` (core) | 271,864 B | 271,864 B, byte-identical |

`tsc -p tsconfig.json`, `tsc -p tsconfig.test.json`, eslint and prettier are
clean on the changed files.
zurfyx added a commit that referenced this pull request Nov 4, 2026
…fenced: rooms migrate on load, stale clients hand off, records are listed and replayed

## Description

Stacked on the replay PR (`replayYRecovery`, `recoveryYState`), itself on
#9766. `docs/collaboration/y-server.md` describes how a server that stores
`@lexical/y` documents migrates them and keeps stale sessions apart
("Migrating stored documents"). Until now nothing in the repository ran that
recipe end to end. The playground's development relay
(`scripts/collab-y-server.mjs`, `pnpm run collab:y`) now follows it, with
`@lexical/y/server`, and the playground's collab Y client takes part:

- `scripts/collab-y-fence.mjs` (new) keeps a store per room that outlives the
  live document (in memory, as the relay persists nothing): the state, an
  incarnation (a random token, not inherited) and its seed contract, the
  generation, a version, the immutable base of every generation the room
  migrated from, the append-only quarantine records and the replay ledger.
  A migration's split material becomes a `pendingYRecord` record (the whole
  stored state and its cut bytes) and is replayed at once.
- **Migrate on load.** Loading a room runs `prepareYRoom` when a root is
  below the room's floor (`COLLAB_Y_MIN_LAYOUT`, default 1), and commits the
  state, the generation, the base and a `pending` record with a
  compare-and-set on the version read. `POST /reload` is the migration
  moment: it closes every connection (the barrier), seals the live document
  and loads it again.
- **Handshake.** A client presents `{generation, material, layouts, seed}`
  in its connection URL (`g`, `m`, `lo`, `hi`, `seed`). The relay answers
  with `checkYSession(describeYRoom(...))` in a y-websocket message of its own
  type (8, JSON) before any sync. Only `admit` and `bootstrap` sessions sync,
  and every message they send is checked against the room's current
  generation. A session without a handshake (a release before the fence) is
  captured with `captureYSession` and sent its legacy signal.
- **Handoff.** A stale client posts its quiesced material, whether it had
  peers and every client id it wrote under, to `POST /handoff`. The relay stores it as a `quarantineRecord` (once per
  hash, so a retry is acknowledged again), acknowledges the hash, and
  replays it onto the live document with `replayYRecovery` as a checked
  edit. `GET /records` lists the records: kind, source generation,
  whether they hold anything new, the replay receipt and a text preview of
  what the recovery view renders (`recoveryYState`, render only).
- **Client** (`src/collaborationY.tsx`):
  - It keeps a generation record, adopted from an `admit` or `bootstrap`
    verdict, and puts the handshake in the provider's URL before every
    connection. `?collabYMinLayout=<n>` sets the floor it presents. It
    records every client id its document writes under (the record's
    `clients`); its BroadcastChannel is off, so its records have no peers.
  - On `stale` it disconnects, calls `binding.quiesce()`, uploads the record
    until the relay acknowledges it, then reloads: the playground keeps no
    local copy, so the reloaded page bootstraps.
  - `refuse-layout` shows a notice, and a collapsible "Recovered edits" list
    shows the room's records.
- The relay runs unfenced (as before) when `@lexical/y` is not built or
  with `COLLAB_Y_FENCE=0`. CI builds the packages before the collab Y e2e
  job, so it runs fenced there.
- The collab Y version-gate spec now expects a client that loads a document
  with a layout it does not read to be refused by the relay (its
  `refuse-layout` notice) rather than to sync and turn read only. Clients
  that were already open still turn read only through the binding's gate.
- Docs: y.md and y-server.md point to the relay as the reference.

## Changeset

None: `lexical-playground` and `lexical-website` are private packages.

## Test plan

### Before

The relay applied every connection's updates to the room, whatever the
document they came from: a client that was offline while the room migrated
synced its old-generation document into the migrated one. It had no fence
to check:

```
$ pnpm run collab:y   # the relay before this change
$ E2E_PORT=4000 E2E_EDITOR_MODE=rich-text-with-collab-y pnpm exec playwright test --project=chromium --retries=0 packages/lexical-playground/__tests__/e2e/CollabYFence.spec.mjs
  ✘  1 [chromium] › ...CollabYFence.spec.mjs:55:3 › Collab Y: the fenced relay › a room migrates when it loads; edits made offline across the migration are handed off, listed and replayed (0ms)
  ✘  2 [chromium] › ...CollabYFence.spec.mjs:135:3 › Collab Y: the fenced relay › a release whose floor is above the room is refused until the room migrates (0ms)
    Error: the relay runs its fence
    Expected: true
    Received: undefined
```

### After

```
$ pnpm run build && pnpm -C packages/lexical-playground run build-dev
$ pnpm run collab:y &  pnpm -C packages/lexical-playground run preview &
$ E2E_PORT=4000 E2E_EDITOR_MODE=rich-text-with-collab-y pnpm exec playwright test --project=chromium --retries=0
  35 passed (28.3s)
$ E2E_PORT=4000 E2E_EDITOR_MODE=rich-text-with-collab-y pnpm exec playwright test --project=firefox --retries=0
  31 passed (34.6s)
$ E2E_PORT=4000 E2E_EDITOR_MODE=rich-text-with-collab-y pnpm exec playwright test --project=chromium --retries=0 --repeat-each=3 packages/lexical-playground/__tests__/e2e/CollabYFence.spec.mjs
  6 passed (10.4s)
$ E2E_PORT=4000 E2E_EDITOR_MODE=rich-text-with-collab-y pnpm exec playwright test --project=firefox --retries=0 --repeat-each=3 packages/lexical-playground/__tests__/e2e/CollabYFence.spec.mjs
  6 passed (13.9s)
$ for g in 0 1; do LEXICAL_Y_GC=$g pnpm exec vitest --run --project unit packages/lexical-playground/__tests__/unit/CollabYFence.test.ts; done
      Tests  7 passed (7)
      Tests  7 passed (7)
```

`CollabYFence.spec.mjs`:

1. Two clients open a new room, which is seeded at layout 1.
2. One goes offline and types; the other types online.
3. The relay's floor is raised to 2 and the room reloads. It migrates on
   load: layout 2, a new generation.
4. The online client reconnects stale, hands off a record that holds
   nothing new, reloads and bootstraps.
5. A client presenting floor 2 is admitted.
6. The offline client reconnects stale and hands off its record, which the
   relay replays (applied, no conflicts).
7. All three converge with every token once, a fresh client loads the
   same, and the recovery list shows both records.

A second test checks that a floor-2 client opening the room before it
migrates is refused (no sync, the notice), and is admitted after the
migration.

Each of three broken relays fails the spec (chromium):

```
never replays a handoff:        1 failed   1 passed (6.3s)
admits every handshake:         2 failed
never migrates on load:         2 failed
```

`CollabYFence.test.ts` covers:
- the handshake parsed from the URL;
- every verdict row;
- the migration on load, with its base kept, and a second load that writes
  nothing;
- a handoff stored once and replayed once on a retry;
- a client from before the fence: its capture is kept, never applied, and
  it gets its signal;
- a handoff from a generation without a base, which is kept and not
  replayed;
- a migration's split material (a skipped range in the stored state) kept
  as a pending record, replayed, its listing showing the cut text.

`tsc -p tsconfig.json`, `tsc -p tsconfig.test.json`, eslint and prettier
are clean on the changed files.

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. The layout migration runner, the frozen 1to2 step, the server fence helpers and the write-time admission check read correctly at this head; the points from earlier rounds (the headless config warning, the at-write refusal message, the hasNewYEdits cleanup and the raw-write transaction marks) are addressed; and the unit, integrity, browser and collab Y e2e jobs are green. The suggestions below are optional and non-blocking.

Optional suggestions

  1. A [breaking] bump for a package that has not been released yet. .changeset/lexical-y-warning-api-break.md:2 uses '@lexical/y': minor, as AGENTS.md ("Backwards Compatibility" and "Changesets") asks for a [breaking] entry. @lexical/y has only nightly builds so far, its introducing changeset (.changeset/lexical-y-binding.md) is still pending, and .changeset/README.md ("Format") notes that all packages release together. So this entry alone makes the next release a minor for every Lexical package, and that release's changelog would list a [breaking] change to a package it introduces. If that is not the intent, a [feature] patch entry carrying the same migration text would still tell nightly adopters what to change.
  2. The setup example in y.md. packages/lexical-website/docs/collaboration/y.md:154 declares layoutUpgrade: createYServerLayoutUpgrade() while connecting a plain @y/websocket provider that never sends the handshake and has no server running prepareYRoom. Once the floor rises, an app that copies it would report upgrade: 'server' for documents nothing migrates. layoutUpgrade: null, as the playground uses, matches that setup; alternatively, one sentence could say the handle is for apps whose server migrates and that send layoutUpgrade.handshake(...).
  3. Test plan output. The PR body summarizes test counts, sizes and fuzz results. AGENTS.md ("Commits and Pull Requests") asks the Test plan to paste the actual Before and After output; the individual commits already do, so pasting the key runs into the body would be enough.

@@ -0,0 +1,21 @@
---
'@lexical/y': minor

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, non-blocking: @lexical/y has only nightly builds so far and its introducing changeset (.changeset/lexical-y-binding.md) is still pending. Per .changeset/README.md ("Format"), all packages release together, so this minor alone makes the next release a minor for every Lexical package. If that is not intended, a [feature] patch entry with the same migration text would still guide nightly adopters.

// schema" and "Layout upgrades".
createYCollabConfig({
doc,
layoutUpgrade: createYServerLayoutUpgrade(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, non-blocking: this example connects a plain @y/websocket provider and never sends layoutUpgrade.handshake(...) or runs prepareYRoom on a server, so layoutUpgrade: null (as the playground uses) matches it. Otherwise, once the floor rises, an app copying it reports upgrade: 'server' for documents nothing migrates. A sentence saying the handle is for apps whose server migrates would also work.

… layoutUpgrade null for its plain provider

## Description

The setup example in y.md connects a plain `@y/websocket` provider, which sends no handshake and has no server running `prepareYRoom`, yet declared `layoutUpgrade: createYServerLayoutUpgrade()`. Once the floor rises, an app copying it would report `upgrade: 'server'` for documents nothing migrates. The example now declares `layoutUpgrade: null`, as the playground does, and its comment says when to pass the server handle instead.

## Test plan

### After

```
$ pnpm exec prettier --check packages/lexical-website/docs/collaboration/y.md
All matched files use Prettier code style!
```

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. Every write now checks the layout record inside its own transaction, which closes a real gap: on main, an edit made inside an app transaction that also changed the record was stored before the binding noticed. MIN_LAYOUT stays 1, so stored documents behave as before. The warning API break carries a [breaking] changeset with Migration:, Detect: and Verify:, as AGENTS.md's "Backwards Compatibility" section asks for.

A few optional, non-blocking suggestions:

  1. createYServerLayoutUpgrade({target}) has no effect (packages/lexical-y/src/internal/LayoutUpgrade.ts:97). target is validated and stored, but nothing reads it: handshake() always sends layouts: [MIN_LAYOUT, LAYOUT_VERSION], the binding reads only kind, and prepareYRoom takes its own to. The docs now promise that no export or field is ever removed, so consider documenting it as a declaration only, or leaving it out until something reads it. Adding it later is additive.
  2. README example (packages/lexical-y/README.md:73). The usage example declares createYServerLayoutUpgrade() for "any Yjs 14 provider" and sends no handshake. y.md's setup example now uses layoutUpgrade: null for that case; the README could match it.
  3. Feature requirements and older releases (packages/lexical-y/README.md:232-242, and the wire format section of packages/lexical-website/docs/collaboration/y.md). Releases before this one read only lexical-y:<n> and ignore lexical-y-require:*. The README already says this for the epoch ("older releases ignore it"). Saying the same for requirements tells a future writer to also raise the layout record, or rely on the server fence.
  4. Fence evidence. The generation-fence fuzz and its controls in the Test plan are described but not committed. Committing a seeded subset as a test would let CI rerun the evidence for a fence D102 makes permanent. AGENTS.md ("Commits and Pull Requests") also asks the Test plan's Before section to paste the failing output instead of pointing at commit messages, which a squash merge drops.
  5. Nit: repeated reads. recordedLayout (packages/lexical-y/src/internal/Binding.ts:826) calls readRequirements(root) twice, plus epochRecordOf and newestLayout, on every write-path check. Reading the root's attributes once would avoid the repeats.

The [breaking] changeset is meant to ship in the same release as layout 3 (#9777), so please make sure the two land in one release.

export function createYServerLayoutUpgrade(
options: YServerLayoutUpgradeOptions = {},
): YLayoutUpgradeHandle {
const target = options.target ?? MIN_LAYOUT;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: target is validated and stored, but nothing reads it. handshake (clientHandshake) always sends layouts: [MIN_LAYOUT, LAYOUT_VERSION], the binding reads only kind, and prepareYRoom has its own to. Since the docs now promise that no field is ever removed, consider documenting it as a declaration only, or leaving it out until something reads it. Adding it later is additive.

Comment thread packages/lexical-y/README.md Outdated
// upgraded (your server migrates them, or null: read only).
createYCollabConfig({
doc,
layoutUpgrade: createYServerLayoutUpgrade(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: this example connects to "any Yjs 14 provider" and sends no handshake. y.md's setup example now uses layoutUpgrade: null for that case, so null here would match it. Alternatively, show layoutUpgrade.handshake(...) beside a migrating server.

`true`, grow-only, the feature id an opaque string, written before (or
with) the content that needs the feature. A reader that does not support
every required feature, or finds a requirement that is not well formed
(an empty id, a value other than `true`), opens the root read only: it

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: releases before this one read only lexical-y:<n> and ignore lexical-y-require:*, so they still edit such a root. The epoch paragraph above already says "older releases ignore it". The same sentence here would tell a writer to also raise the layout record, or rely on the server fence.

*/
function recordedLayout(root: YNode): number | null {
return malformedLayout(root) !== null ? NaN : newestLayout(root);
return malformedLayout(root) !== null ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: on the write path this calls readRequirements(root) twice (once inside malformedLayout), plus epochRecordOf and newestLayout: five getAttrs() walks per check. Reading the attributes once would avoid it.

…pgrade before v1

## Description

The automated code review noted that `createYServerLayoutUpgrade` validated
and stored a `target`, but nothing read it:

- `handshake()` always sends `layouts: [MIN_LAYOUT, LAYOUT_VERSION]`;
- the binding reads only `kind`;
- `prepareYRoom` has its own `to`.

Since v1 promises that no field is ever removed, a dead permanent field
should not ship; adding a target later is additive.

- `createYServerLayoutUpgrade()` takes no options. `YServerLayoutUpgradeOptions`
  (which only held `target`) is removed from `@lexical/y` and
  `@lexical/y/server`, in TS and Flow.
- The handle (TS, and the Flow opaque type's bound) has `kind` and
  `handshake` only.
- `isYLayoutUpgradeHandle` checks the brand, a non-empty `kind` and a
  `handshake` function.
- Nothing else in the repo read `.target` on a handle: not the playground,
  not the docs, not the examples. The docs only ever show
  `createYServerLayoutUpgrade()` without arguments. The layout-upgrade
  changeset now says the factory takes no options and that the handle has
  `kind` and `handshake`.

## Test plan

### Before

`vitest --run --project unit packages/lexical-y/src/__tests__/unit/regressions/LayoutUpgrade.test.ts`
with the previous LayoutUpgrade.ts (the handle's fields are now pinned):

```
AssertionError: expected [ 'handshake', 'kind', 'target' ] to deeply equal [ 'handshake', 'kind' ]
      Tests  1 failed | 14 passed (15)
```

`tsc -p tsconfig.json --noEmit` there: 2 errors. The new
`@ts-expect-error` cells (reading `handle.target`, passing `{target}`) are
unused.

### After

- The handle's fields are `handshake` and `kind`, and it is frozen and
  branded.
- A branded object with a valid kind and handshake is a handle whatever
  `target` holds; an empty kind or a missing handshake is not.
- The TS and Flow cells expect an error for `handle.target` and for an
  options argument.

`vitest --run --project unit packages/lexical-y/src/__tests__/unit/regressions/LayoutUpgrade.test.ts packages/lexical-y/src/__tests__/unit/Source.test.ts packages/lexical-y/src/__tests__/unit/MigrateServer.test.ts`,
gc off and on:

```
      Tests  93 passed (93)
```

`tsc`: 0 errors. `node scripts/check-flow-types.mjs`: `Found 0 errors`.
The whole lexical-y and lexical-yjs unit projects: gc off 20,425 passed, 393 expected fail; gc on 20,421 passed, 396 expected fail. The gc on run also had DisposeMemory's 40-editor heap-retention cell go over its bound under the parallel run; it passes 5 of 5 alone in each gc mode on this branch's head.
…er check

## Description

The automated code review noted that `recordedLayout`, which the write path
calls in every binding-authored transaction, walked the root's attributes
five times: `malformedLayout`, `readRequirements` twice (once inside
`malformedLayout`), `epochRecordOf` and `newestLayout`. Each walk calls
`getAttrs()`, which builds the attributes afresh.

It now calls `getAttrs()` once and passes the result on:

- `Layouts.ts` gains `RootAttrs`, `epochRecordIn(attrs)` and
  `requirementsIn(attrs, supported?)`. `epochRecordOf(root)` and
  `readRequirements(root)` keep their signatures and delegate to them.
- In `Binding.ts`, `recordedLayout` reads the attributes and the
  requirements once, and hands them to `malformedIn` and `newestIn`.
  `malformedLayout(root)` keeps its signature for the evaluation path.

This is a pure refactor: same checks, same order, same results.

## Test plan

### Before

A scratch probe (not committed) counted `getAttrs()` calls on the root
during one discrete editor write on a seeded document: 32 with the previous
code.

### After

The same probe counts 12. The layout and requirement gates are unchanged.

`vitest --run --project unit packages/lexical-y/src/__tests__/unit/MigrateGate.test.ts packages/lexical-y/src/__tests__/unit/MigrateCore.test.ts packages/lexical-y/src/__tests__/unit/regressions/MigrateEpochGate.test.ts packages/lexical-y/src/__tests__/unit/regressions/MigrateRequirements.test.ts packages/lexical-y/src/__tests__/unit/regressions/MigrateHistoryGate.test.ts packages/lexical-y/src/__tests__/unit/regressions/MigrateLayoutInfo.test.ts packages/lexical-y/src/__tests__/unit/SchemaVersion.test.ts`,
gc off and on:

```
      Tests  226 passed (226)
```

`tsc`: 0 errors. `node scripts/check-flow-types.mjs`: `Found 0 errors`.
The whole lexical-y and lexical-yjs unit projects: gc off 20,425 passed, 393 expected fail; gc on 20,422 passed, 396 expected fail.
…Upgrade null; older releases ignore feature requirements

## Description

Two notes from the automated code review:

- **README usage example.** It configured "any Yjs 14 provider" with
  `createYServerLayoutUpgrade()`, which declares that a server migrates
  stored documents. A plain provider has none. Like y.md's setup example,
  it now declares `layoutUpgrade: null`, with the same note: no server
  migrates this provider's stored documents, so one below the floor opens
  read only, and an app whose server migrates passes
  `createYServerLayoutUpgrade()` and sends its handshake. The now-unused
  import is dropped.
- **Feature requirements and older releases.** Releases before this one read
  only `lexical-y:<n>` and ignore `lexical-y-require:*`, so they would still
  edit a root that requires a feature. The README's wire format and y.md
  now say so, as the epoch paragraph does for the epoch. They tell a future
  writer that adds a requirement to also raise the layout record (older
  releases then open the root read only) or to rely on its server's fence.

Docs only.

## Test plan

Docs only: prettier clean on both files. The whole lexical-y and lexical-yjs unit projects: gc off 20,425 passed, 393 expected fail; gc on 20,422 passed, 396 expected fail.

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. The runner's copy-and-check design, the server helpers and the write-time gate are carefully specified and well covered by regression tests, and the warning-type and LAYOUT_VERSION break is declared the way AGENTS.md asks for: a [breaking] changeset on a minor bump with Migration, Detect and Verify. A few optional, non-blocking suggestions:

  1. quiesce() after dispose() leaves the editor non-editable (packages/lexical-y/src/internal/Binding.ts, quiesce()'s this.setStatus('readonly')). The "Handing a replica off" section of y.md documents calling quiesce() after dispose() as writing nothing, but setStatus still calls editor.setEditable(false) on an editor dispose() already gave back. A later new YBinding(editor, ...) then records wasEditable = false in start(), so it becomes active while the editor stays read only. Skipping the status change when the binding is not started (still setting quiesced) would fix it; an editor.isEditable() assertion in the "quiesce() again, and after dispose" test of MigrateCore.test.ts, or a regression test under src/__tests__/unit/regressions/ as packages/lexical-y/AGENTS.md asks, would keep it fixed.
  2. A root holding only a well-formed lexical-y-epoch (no layout record, no content) leaves the binding pending with no warning: rootPristine() counts the epoch, so initialize() seeds nothing, and evaluate() returns quietly for an empty root with no record. Reporting UNSUPPORTED_LAYOUT_WARNING 'missing' there would match how the runner ('missing') and describeYRoom (unreadable) already treat that root.
  3. Composition at the handoff is only exercised in jsdom through $setCompositionKey. A browser-mode test, the tier AGENTS.md names for real input, would show what the editor keeps when a native composition is still running when quiesce() is called.

this.pending.has('reread') ||
this.pending.has('restore')));
this.quiesced = true;
this.setStatus('readonly');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: after dispose() this still runs setStatus('readonly'), which calls editor.setEditable(false) on an editor dispose() already gave back. A later new YBinding(editor, ...) then records wasEditable = false in start() and stays non-editable while active. Skipping the status change when !this.started (still setting quiesced) would keep the documented "after dispose() it writes nothing" behavior side-effect free.

* Whether the root is as initialization found it: no content, no layout
* record (well formed or not) and no epoch.
*/
private rootPristine(): boolean {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: because the epoch counts here, a root that holds only a well-formed lexical-y-epoch (no layout record, no content) is never seeded, and evaluate() then returns without a warning, so the binding stays pending silently. Reporting 'missing' for that root would match the runner and describeYRoom.

…able

## Description

The automated code review found that `quiesce()` after `dispose()` still
ran `setStatus('readonly')`, which calls `editor.setEditable(false)`. That
editor is one `dispose()` had already given back. A binding started later
on the same editor records `wasEditable = false` in `start()`, so it then
stays non-editable while active.

`quiesce()` now changes the status only while the binding is started. It
still marks the binding quiesced and still returns the document's state and
the draft, so its documented after-dispose behavior is unchanged.

## Test plan

### Before

New `regressions/BindingLifecycleEdges.test.ts` (dispose, quiesce, then a
second binding on the same editor) and an `editor.isEditable()` assertion
in MigrateCore's "quiesce() again, and after dispose" test, with the
previous binding:

```
     × quiesce() after dispose(): a new binding on the same editor is active and the editor editable
     × quiesce() again, and after dispose: nothing written, the same state, a YQuiescedState
AssertionError: expected false to be true // Object.is equality
```

### After

The editor stays editable after the post-dispose `quiesce()`, and the
second binding is active, editable and writes.

`vitest --run --project unit packages/lexical-y/src/__tests__/unit/regressions/BindingLifecycleEdges.test.ts packages/lexical-y/src/__tests__/unit/MigrateCore.test.ts`,
gc off and on:

```
      Tests  28 passed (28)
```

`tsc`: 0 errors. `node scripts/check-flow-types.mjs`: `Found 0 errors`.
The whole lexical-y and lexical-yjs unit projects: gc off 20,426 passed, 393 expected fail; gc on 20,423 passed, 396 expected fail. Each run also had DisposeMemory's 40-editor heap-retention cell go over its bound under the parallel run; it passes 5 of 5 alone in each gc mode on this commit.
… instead of leaving the binding pending

## Description

The automated code review found that a root holding only a well-formed
`lexical-y-epoch` (no layout record, no content) left the binding `pending`
with no warning:

- `rootPristine()` counts the epoch, so `initialize()` seeds nothing;
- `evaluate()` returned quietly for an empty root without a record while
  the binding was pending.

The runner refuses such a root as `'missing'`, and `describeYRoom` lists it
as unreadable.

`evaluate()` now treats an empty root that is not pristine (it holds a gate
record but no layout record) like content without a record: it reports
`UNSUPPORTED_LAYOUT_WARNING` `'missing'`, with a message naming the records,
and the binding is read only. Nothing is written. `YUnsupportedLayoutData`'s
doc for `'missing'` mentions records such as an epoch.

## Test plan

### Before

A new cell in `regressions/BindingLifecycleEdges.test.ts` (gc off and on)
binds a document whose root holds only a well-formed epoch, with editor
content to seed. With the previous binding:

```
     × a root holding only a well-formed epoch: missing, read only, nothing seeded
AssertionError: expected 'pending' to be 'readonly' // Object.is equality
```

### After

The binding is read only, the only layout warning is `{reason: 'missing',
supported}`, and the document's bytes are unchanged.

`vitest --run --project unit packages/lexical-y/src/__tests__/unit/regressions/BindingLifecycleEdges.test.ts packages/lexical-y/src/__tests__/unit/MigrateCore.test.ts packages/lexical-y/src/__tests__/unit/MigrateGate.test.ts packages/lexical-y/src/__tests__/unit/regressions/MigrateEpochGate.test.ts packages/lexical-y/src/__tests__/unit/regressions/MigrateRequirements.test.ts`,
gc off and on:

```
      Tests  84 passed (84)
```

`tsc`: 0 errors. `node scripts/check-flow-types.mjs`: `Found 0 errors`.
The whole lexical-y and lexical-yjs unit projects: gc off 20,429 passed, 393 expected fail; gc on 20,426 passed, 396 expected fail.
…anch

## Description

Brings in main through dfe058a, including #9788 (an edit an app's code makes in the update of a remote change's read is stored, and that update runs no node transforms). The merge applied without conflicts; DECISIONS keeps one row per number (#9784's D108, #9788's D111, this branch's D102, D109 and D110).

## Test plan

### After

(the unit, Flow and release gates on this merge are recorded in the pull request)
…ecords this client's schema version

## Description

API review round 6 found a D08 break, brought in by #9788 (main
dfe058a). `$writeReadEdits` stores an app edit made while a remote change
is read with a commit marked `userEdit: false`, so `$writeCommit` writes it
with `followUpOrigin`. That keeps it out of the undo history (D111), which
is right. But the writer and the recovery writer recorded the schema
version only when `origin === this`. So such an edit never recorded the
writer's `schemaVersion`: a schema 2 client could write while schema 1
readers stayed active.

**Fix.**

- A new internal commit flag, `recordOwnSchema?: true`, is set on the
  commit `$writeReadEdits` builds.
- The writer's and the recovery writer's finalization record the schema
  when `origin === this || commit.recordOwnSchema`. That is inside the same
  admitted transaction, after the same admission check, with the
  schema-grace handling unchanged.
- The edit keeps the follow-up origin, so it stays out of the undo history.
- Other commits are untouched (the flag is absent on them).

## Test plan

### Before

New `regressions/ReadEditSchema.test.ts`, gc off and on, adapted from the
reviewer's probe. A's editor is rebound with schema 2 and reads a change
from B, and the app's code edits during the read. With the previous
binding:

```
AssertionError: expected undefined to be true // Object.is equality
 ❯ packages/lexical-y/src/__tests__/unit/regressions/ReadEditSchema.test.ts:188:75
      Tests  4 failed (4)
```

### After

- A's updates for the read, applied over A's pre-read state, record
  `lexical-y-schema:2`.
- The undo stack stays empty.
- A schema 1 reader of the result opens it read only.
- The same holds through the recovery path: the read-time write writes,
  then throws, and the rewrite recovers. The cell checks the recovery
  warning was reported.

The writer's own finalization records the schema even when it throws, so
the recovery's record is defense in depth: the recovery cell passes with or
without that half of the change.

`vitest --run --project unit packages/lexical-y/src/__tests__/unit/regressions/ReadEditSchema.test.ts`,
gc off and on:

```
      Tests  4 passed (4)
```

`tsc`: 0 errors. `node scripts/check-flow-types.mjs`: `Found 0 errors`.
The whole lexical-y and lexical-yjs unit projects: gc off 20,490 passed,
393 expected fail; gc on 20,488 passed, 396 expected fail. The gc off run
also had DisposeMemory's 40-editor heap-retention cell go over its bound
under the parallel run; it passes 5 of 5 alone in each gc mode on this
commit. `pnpm run ci-check`: exit 0. scripts-unit: 3,594/3,594.
`pnpm run build-release`: exit 0 (LexicalY.prod.js +61 / +20 bytes
min/gzip).
…tamp for a read-time app edit

## Description

The read-time app edit's schema stamp is made by the writer's finalization, or by the recovery's when the writer fails. The existing regression's injected failure comes after the writer ran, so the writer has already stamped the schema and the recovery's own stamp is never isolated. A new regression, from the independent API review, injects the failure before anything is written, checks the schema is still absent when the recovery begins, and requires the recovery's update to carry both the edit and the schema; it also delivers only the authored updates to an active schema-1 reader, which must turn read only with the first update that shows the edit, and checks undo history stays empty and every changed local transaction is marked for the raw-write diagnostic.

## Test plan

### Before

With the recovery finalization's stamp reverted (`if (origin === this)`):

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/ReadEditSchemaRecovery.test.ts
     × the stamp comes with the edit, undo stays empty (failure before the write: true)
     × the stamp comes with the edit, undo stays empty (failure before the write: true)
AssertionError: expected undefined to be true // Object.is equality
      Tests  2 failed | 2 passed (4)
```

### After

```
$ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/regressions/ReadEditSchemaRecovery.test.ts
      Tests  4 passed (4)
```

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. The floor, the frozen steps and the server fence are each in their own entry, the core stays free of migration code, and the stored format and how existing documents read are unchanged while MIN_LAYOUT is 1. The breaking change to the warning API is declared in a [breaking] changeset with Migration:, Detect: and Verify: paragraphs, as AGENTS.md asks. The suggestions below are optional and non-blocking.

  1. A distinct reason for a write refused at write time (packages/lexical-y/src/internal/Binding.ts, warnRefusedAtWrite). On an active binding, a write refused because its transaction changed the layout or schema record is reported as UNSUPPORTED_EDIT_WARNING with {reason: 'read-only'}, the only variant YUnsupportedEditData has. The binding can stay active afterwards: MigrateHistoryGate.test.ts asserts exactly that when the app puts the record back. An app that maps 'read-only' to a read-only banner would then show it over an editable editor. This pull request freezes the reason sets, so a later distinction could only arrive as {reason: 'other'}. Would a dedicated reason (for example 'refused-at-write') be worth adding before the freeze?
  2. Release this together with the layout 3 change. .changeset/lexical-y-warning-api-break.md says the break ships with #9777 as the package's one breaking release. If a release is cut between the two merges, consumers get two breaking minors. packages/lexical-y/AGENTS.md also asks for a stack to be tested combined before merging.
  3. A browser test for quiesce() during a native composition once a provider wires the handoff (Binding.ts, the $setCompositionKey(null) call in quiesce()). The current tests set the composition key on jsdom. AGENTS.md's testing strategy puts behavior that depends on real input and selection in __tests__/browser/, which is where an open IME composition meeting a root that turns read only would show what really happens.

* listeners), or a remote update a provider applied while the editor was
* updating. Not retried: a retry would write outside that transaction.
*/
private warnRefusedAtWrite(): void {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: on an active binding this refusal reports UNSUPPORTED_EDIT_WARNING with {reason: 'read-only'}, and the binding can stay active (the 'puts it back' case in MigrateHistoryGate.test.ts), so an app that shows a read-only banner for 'read-only' would show it over an editable editor. Since this pull request freezes the reason sets, a dedicated reason (for example 'refused-at-write') is cheapest to add now.

) {
editor.update(
() => {
$setCompositionKey(null);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, for when a provider wires the handoff: this ends the composition from code only, and the tests set the composition key on jsdom. A browser test (__tests__/browser/) with a native IME composition open when quiesce() turns the root read only would show whether the composed text is committed into the draft or arrives after the handoff.

…, 'refused-at-write'

## Description

On an active binding, a local change refused because its own transaction
changed the layout or schema record was reported as `UNSUPPORTED_EDIT_WARNING`
`{reason: 'read-only'}`, the only variant `YUnsupportedEditData` had. The
binding can stay active afterwards (MigrateHistoryGate asserts exactly
that when the app puts the record back), so an app that maps `'read-only'`
to a banner would show it over an editable editor. After the API freeze, a
distinction could only arrive as `'other'`. The automated code review
raised this.

`YUnsupportedEditData` is now a union (TypeScript and Flow):

- `{reason: 'read-only'}`: refused because the binding is read only. The
  meaning is unchanged; an earlier warning says why.
- `{reason: 'refused-at-write', record: 'layout' | 'schema'}`: refused at
  write time on an active binding. `record` says which kind of record
  stopped admitting the write:
  - `'layout'`: the layout record, or the epoch or a feature requirement;
  - `'schema'`: a schema record.

  The binding may stay active.

`warnRefusedAtWrite` reports it. `admitsIn` notes which check refused, and
the message names that record. The cause-first ordering of the flushed
warnings covers both refusal reasons. So when the record stays changed,
the binding's own read-only cause (for example
`UNSUPPORTED_LAYOUT_WARNING` `'newer'`) comes first and the refusal after,
as before.

Also updated:

- y.md's warnings table;
- the write-time-gate `[fix]` changeset (one sentence);
- the `[breaking]` changeset's list of new reasons;
- MigrateHistoryGate's assertions for this path;
- WarningTypes.test's banner, which now switches over the edit reasons
  exhaustively;
- the Flow warnings test.

## Test plan

### Before

New `regressions/RefusedAtWrite.test.ts`, gc off and on, with the previous
binding:

```
     × the record changed around the write and put back: 'refused-at-write' (layout), and the binding stays active
     × a schema record a listener writes at the write's start: 'refused-at-write' (schema), after the schema warning
     × the record stays changed: the binding's own read-only warning, then 'refused-at-write'
AssertionError: expected [ [ …(3) ] ] to deeply equal [ [ …(3) ] ]
      Tests  6 failed | 2 passed (8)
```

`tsc` there reports 2 errors (the union's new member).

### After

- The layout record changed around the write and put back: the only warning
  is `refused-at-write` with `record: 'layout'`, and the binding stays
  active.
- A schema record a `beforeTransaction` listener writes at the write's
  start: `UNSUPPORTED_SCHEMA_WARNING` `'newer'`, then `refused-at-write`
  with `record: 'schema'`.
- The layout record stays changed: `UNSUPPORTED_LAYOUT_WARNING` `'newer'`
  (the binding's own read-only warning), then `refused-at-write` (layout),
  and no `'read-only'`.
- Control: an edit on a binding that is read only from the start still
  reports `'read-only'`, after its cause.

`vitest --run --project unit packages/lexical-y/src/__tests__/unit/regressions/RefusedAtWrite.test.ts packages/lexical-y/src/__tests__/unit/regressions/MigrateHistoryGate.test.ts packages/lexical-y/src/__tests__/unit/WarningTypes.test.ts packages/lexical-y/src/__tests__/unit/EditorDrift.test.ts`,
gc off and on:

```
      Tests  159 passed (159)
```

`tsc`: 0 errors. `node scripts/check-flow-types.mjs`: `Found 0 errors`.
The whole lexical-y and lexical-yjs unit projects: gc off 20,503 passed,
393 expected fail; gc on 20,498 passed, 396 expected fail. The gc on run
also had the two heap-retention cells (DisposeMemory's 40-editor loop,
Headless's synchronous loop) go over their bounds under the parallel run;
they pass 5 of 5 alone in each gc mode on this commit. `pnpm run
ci-check`: exit 0. scripts-unit: 3,594/3,594. `pnpm run build-release`:
exit 0 (LexicalY.prod.js +152 / +52 bytes min/gzip).
… its own transaction found

## Description

API review round 8 (S1). `refusedBy` was an instance field: `admitsIn` set
it, and `$writeCommit` read it after the write's transaction returned. A
nested admission in between overwrote it, so an original layout refusal was
reported as `record: 'schema'`. The nested admission comes from an app's
`afterTransaction` listener, which:

1. restores the layout record;
2. installs a refusing schema record;
3. calls the exposed undo manager;
4. restores the schema record.

The field is gone. `refusalIn(grace)` returns the refusing family (layout
checked first) or null, and `admitsIn` delegates to it. The writer and the
recovery writer keep the family in a local of their own transaction
callback, and `$runWriter` returns it as an internal `Refusal` instead of
`'refused'`. `$writeCommit` builds the warning from that result.

## Test plan

### Before

The reviewer's case, as a new cell of `regressions/RefusedAtWrite.test.ts`
(gc off and on), with the previous binding:

```
     × a nested admission in an afterTransaction listener does not change the refusal's record
AssertionError: expected [ [ …(3) ] ] to deeply equal [ [ …(3) ] ]
      Tests  2 failed | 8 passed (10)
```

(It reported `record: 'schema'`.)

### After

The one edit warning is `refused-at-write` with `record: 'layout'`, the
content is unchanged and the binding stays active.

`vitest --run --project unit packages/lexical-y/src/__tests__/unit/regressions/RefusedAtWrite.test.ts packages/lexical-y/src/__tests__/unit/regressions/MigrateHistoryGate.test.ts`,
gc off and on:

```
      Tests  124 passed (124)
```

`tsc`: 0 errors.
The whole lexical-y and lexical-yjs unit projects: gc off 20,505 passed, 393 expected fail; gc on 20,501 passed, 396 expected fail. The gc on run also had DisposeMemory's 40-editor heap-retention cell go over its bound under the parallel run; it passes 5 of 5 alone in each gc mode on this commit. `node scripts/check-flow-types.mjs`: `Found 0 errors`.
… how to migrate edit-reason handlers

## Description

API review round 8, S2 and S3.

- **S2:** the `UNSUPPORTED_EDIT_WARNING` constant's JSDoc still described
  only the read-only case ("once each time the binding goes read only"). It
  now names both reasons and how often each is reported: `'read-only'`
  once per read-only period, `'refused-at-write'` per refused write, with
  no promise about the binding's later status.
- **y.md** states the rule under the warnings table:
  - `record` names the admission family that refused;
  - its two values never grow;
  - layout is checked first when both refuse;
  - a later family arrives as `reason: 'other'` with a `detailCode`;
  - the warning promises nothing about the binding's later status (read
    `binding.status`).
- **S3, the `[breaking]` changeset:**
  - Migration handles `'refused-at-write'` separately from `'read-only'`
    (its `record`, and `binding.status` before a banner). It also says that
    `interface X extends YUnsupportedEditData` must become
    `type X = YUnsupportedEditData & {...}` or
    `Extract<YUnsupportedEditData, {reason: 'read-only'}>`.
  - Detect adds exhaustive edit-reason switches, assignments of
    `data.reason` to the literal `'read-only'`, and interfaces extending
    `YUnsupportedEditData` (TS2312).
- **S3, the `[fix]` entry's Verify:** restore the record around the
  attempted write and see `{reason: 'refused-at-write', record: 'layout'}`
  while the binding stays active.

Docs and changesets only.

## Test plan

`node scripts/changesets/check.mjs`: `Changeset check passed: 106 pending
changeset(s) valid.` `tsc`: 0 errors. Prettier clean. On this head, the whole lexical-y and lexical-yjs unit projects: gc off 20,505 passed, 393 expected fail; gc on 20,502 passed, 396 expected fail. `pnpm run ci-check`: exit 0. `pnpm run build-release`: exit 0.

@meta-code-review meta-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change looks good to me. The layout floor, the write-time admission of every binding write, the frozen 1to2 step and the server's generation fence read as correct, and the test plan carries real before/after output for each fix. Below are one optional, non-blocking fix and one release note.

Optional: quiesce()'s repeat-call draft (packages/lexical-y/src/internal/Binding.ts, lines 2009-2011)

The JSDoc says a second call returns "the same draft", and so do packages/lexical-website/docs/collaboration/y.md (the bullets under "Handing a replica off") and the YQuiescedState comment in flow/LexicalY.js.flow. That holds when the first call wrote everything.

When the first call has to refuse the editor's batched update, it returns that update as the draft with differs: true. This happens when the binding is already read only, or when the record stops admitting writes during the call (the cases regressions/MigrateQuiesceDraft.test.ts covers). The refusal then re-reads the document into the editor. A second call rebuilds the draft from the editor, so it returns the document's content without the uncommitted text, and differs: false.

An app that retries a handoff by calling quiesce() again would upload a record without the user's unwritten text, and that record would not count as actionable. The handoff in y-server.md ("retrying the same bytes") keeps the first result, so following it is fine.

To fix: keep the first call's draft and return it from later calls, or narrow the three sentences to "the same state; the draft only from the first call". Either way, add the refused case as a regression cell, as packages/lexical-y/AGENTS.md asks ("Every bug fix lands with a regression test in src/__tests__/unit/regressions/").

Release note: the description says .changeset/lexical-y-warning-api-break.md ([breaking]) should ship in the same release as layout 3 (#9777). Holding the release until both are in keeps the package to one breaking release.

The deferrals the description names are fine as follow-ups: replay and the recovery view (#9771), the fenced relay and its fuzz (#9772), the 2-to-3 step (#9777), and the known double insert on a failed write's recovery (#9775).

Comment on lines +2009 to +2011
* - Calling it again writes nothing and returns the document's state as
* it is then (the same, when nothing else wrote to it) and the same
* draft.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, non-blocking: this holds only when the first call wrote everything. If the first call refused the editor's batched update (binding already read only, or the record stopped admitting writes during the call), its draft is that update with differs: true. The refusal then re-reads the document, so a second call returns the document's content without the uncommitted text and differs: false. Keeping the first draft (say this.quiescedDraft ??= {differs, json}) and returning it from later calls would make this sentence, and the matching bullets in y.md and LexicalY.js.flow, true.

This branch was successfully deployed

2 active deployments
Preview – lexical — e089a1c2 Deployed Nov 5, 2026 by vercel[bot]
Preview – lexical-playground — e089a1c2 Deployed Nov 5, 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.

1 participant