Repository navigation
[lexical] Refactor: Cache writable nodes during pending updates - #9169
Merged
Merged
Conversation
## Description
`getWritable()` currently resolves the latest node, checks `_cloneNotNeeded`, and resolves the latest node again while marking it dirty. Store writable nodes in `Map<NodeKey, LexicalNode>` so repeated writes can retrieve the mutable instance directly, and pass the already-resolved node into dirty marking.
- Populate the map for newly created nodes and writable clones; update the TypeScript and Flow field types.
- Preserve the existing cache lifetime: batched updates share one pending editor state, so live writable nodes remain cached until commit.
- Evict collected nodes from `_cloneNotNeeded` in the same loop that deletes them from the node map. The fast path must preserve the existing error when a later batched update accesses a collected node.
- Keep ordinary `getLatest()` / `$getNodeByKey()` reads unchanged, including reads of historical and separately parsed states.
- Add six lifecycle/selection tests and a fixed-size headless benchmark covering repeated writes, first writes, document replacement, and selection formatting.
**Draft because the performance tradeoff is mixed.** Repeated `getWritable()` calls improve, but first-write-heavy and some broader editing workloads regress. The map also stores an extra node reference per entry. Browser/DOM performance has not been measured. The change includes removal of a redundant lookup in dirty marking; the gains below should not all be attributed to switching Set to Map. An exploratory control retaining the Set while removing that redundant lookup captured much of the mixed-setter improvement.
## Test plan
### Before
Base: `e77523b92f67bee0bd24087350e5e18b924fd7de` from this fork's `main`. Copied only the new benchmark into a separate base worktree and ran:
```sh
NODE_ENV=production node node_modules/vitest/vitest.mjs bench --project bench getWritable --run --outputJson ../clone-map-benchmark/vitest-base.json
```
Actual output for the 1,000-paragraph document (times in milliseconds):
```text
name hz min max mean p75 p99 p995 p999 rme samples
100000 getWritable calls 33.2886 27.6034 35.5642 30.0403 30.9345 35.5642 35.5642 35.5642 ±3.58% 17
one text change 1,671.98 0.0006 4.8777 0.5981 1.0479 2.8973 3.5750 4.8777 ±7.76% 836
one setter per node 649.65 0.0041 7.7861 1.5393 2.9169 4.7630 6.7274 7.7861 ±11.22% 326
five setters per node 248.61 3.4112 8.1757 4.0224 4.0405 7.2629 8.1757 8.1757 ±3.41% 125
replace document 92.9206 9.2513 16.8162 10.7619 11.1597 16.8162 16.8162 16.8162 ±4.59% 47
select all and format 188.06 4.5670 8.7154 5.3174 5.5868 8.7154 8.7154 8.7154 ±2.85% 95
```
This is a performance experiment, so the base is not expected to fail the behavioral tests.
### After
```sh
NODE_ENV=production node node_modules/vitest/vitest.mjs bench --project bench getWritable --run --compare ../clone-map-benchmark/vitest-base.json --outputJson ../clone-map-benchmark/vitest-map.json
```
Mean wall time per operation on Node 24.19.0 / Intel Xeon Platinum 8573C. Negative changes mean less time; several differences overlap the benchmark's error margins.
| Workload | 100 paragraphs: base → PR (ms) | Change | 1,000 paragraphs: base → PR (ms) | Change |
| --- | ---: | ---: | ---: | ---: |
| 100,000 `getWritable()` calls | 26.1259 → 22.0020 | -15.8% | 30.0403 → 25.8298 | -14.0% |
| One text change | 0.0562 → 0.0529 | -5.8% | 0.5981 → 0.5816 | -2.8% |
| One setter per node | 0.1243 → 0.1382 | +11.1% | 1.5393 → 1.6081 | +4.5% |
| Five setters per node | 0.3232 → 0.2939 | -9.1% | 4.0224 → 3.8359 | -4.6% |
| Replace document | 0.9749 → 0.9910 | +1.7% | 10.7619 → 11.0026 | +2.2% |
| Select all and format | 0.4692 → 0.5048 | +7.6% | 5.3174 → 5.5549 | +4.5% |
Unit tests:
```sh
node node_modules/vitest/vitest.mjs run --project unit
```
```text
Test Files 1 failed | 318 passed (319)
Tests 5108 passed | 1 skipped (5109)
```
The failed suite could not resolve `mdast-util-to-markdown` because the isolated checkout initially lacked the example's local dependency links. Restoring those links and rerunning that suite succeeded:
```sh
node node_modules/vitest/vitest.mjs run --project unit dev-examples/mdast-editor/src/__tests__/unit/MdastCustomConstructs.test.ts
```
```text
Test Files 1 passed (1)
Tests 42 passed (42)
```
Final focused run, after adding the explicit test for reusing live nodes across batched updates:
```sh
node node_modules/vitest/vitest.mjs run --project unit packages/lexical/src/__tests__/unit/LexicalWritableNode.test.ts
```
```text
Test Files 1 passed (1)
Tests 6 passed (6)
```
Across these runs: 5,151 distinct passing tests and one skipped test. `node node_modules/typescript/bin/tsc --pretty false`, ESLint on the changed TypeScript files, Prettier checks, and `git diff --check` pass.
`node scripts/lint-flow-types.mjs` exits 1 on both the base and this PR, with the same 330 existing export warnings after normalizing checkout paths. No Flow export diagnostics were added. The full Flow type checker and real-browser suites were not run.
## Description Retain the original writable-node Set and remove the redundant getLatest lookup in dirty marking. The Map experiment adds first-write costs and an extra node reference per entry; the Set control retains the useful repeated- write improvement. Correct the benchmark's stale-reference no-ops, add a reproducible interleaved comparison runner, and cover dirtying the current parent when writing through a stale reference after moving a node. ## Test plan ### Before node scripts/bench-get-writable.mjs e77523b 700206f Actual median microseconds from the same corrected benchmark: base original Map 100 paragraphs, 100000 calls 5361.3 3583.5 100 paragraphs, first writes 133.1 141.8 1000 paragraphs, 100000 calls 12090.7 9347.8 1000 paragraphs, first writes 2132.9 2206.0 Behavioral tests are expected to pass on the base. ### After Same command, WORKTREE results in median microseconds: 100 paragraphs, 100000 calls 4335.3 100 paragraphs, first writes 133.2 1000 paragraphs, 100000 calls 9559.3 1000 paragraphs, first writes 2083.7 Large-document replacement and formatting results varied across runs; a focused 21-sample run produced median paired changes of -1.8% and +0.3%. Real-browser performance is unmeasured. node node_modules/vitest/vitest.mjs run --project unit Test Files 319 passed (319) Tests 5152 passed | 1 skipped (5153) node node_modules/typescript/bin/tsc --pretty false Exit 0 (no diagnostics). ESLint, Prettier and git diff --check pass. Full Flow and browser suites were not run.
## Description
The writable-node benchmark checks the final document, which can miss an
alternating no-op when the final cycle is odd. Extract the existing update
and verification callbacks so setup can exercise and check both halves of
the alternation. The timed update body is unchanged, and verification stays
outside it. Document the check in the benchmark README.
## Test plan
### Before
In an isolated checkout, restore the original stale-reference assignment
for the single-text-change workload while retaining the new setup check:
NODE_ENV=production node node_modules/vitest/vitest.mjs bench --project bench getWritable --run -t 'one text change'
Actual output, exit 1 before timing:
FAIL |bench| packages/lexical/src/__bench__/getWritable.bench.ts
Error: The measured edit did not change the text
### After
NODE_ENV=production node node_modules/vitest/vitest.mjs bench --project bench getWritable --run
Actual output, exit 0; all six workloads in each group completed:
BENCH Summary
|bench| one text change - packages/lexical/src/__bench__/getWritable.bench.ts > size=100 :: writable nodes
2.49x faster than one setter per node
3.55x faster than five setters per node
5.41x faster than select all and format
10.55x faster than replace document
302.12x faster than 100000 getWritable calls
|bench| one text change - packages/lexical/src/__bench__/getWritable.bench.ts > size=1000 :: writable nodes
1.94x faster than one setter per node
2.43x faster than five setters per node
4.18x faster than select all and format
6.81x faster than replace document
23.49x faster than 100000 getWritable calls
These summary ratios compare different workloads, not revisions; they are
included only as the actual successful validation output.
ESLint, Prettier and git diff --check pass. Browser suites were not run.
## Description Add JSDoc parameter and collection types to the production benchmark runner. Pin .nvmrc to the latest Node 24 release, 24.21.0. ## Test plan ### Before Full ci-check reports six tsc-scripts errors: implicit-any parameters, a null revision SHA, and an inferred never[] sample array. .nvmrc contains 24. ### After Node v24.21.0. npm run ci-check exits 0: tsc, tsc-scripts, tsc-extension, tsc-website, Flow, Prettier, and ESLint. Flow reports Found 0 errors. Ran wxt prepare for the checkout's generated extension types; pnpm_config_verify_deps_before_run=warn preserves the existing shared dependency installation without skipping any checks. Writable-node unit tests: 1 file passed, 7 tests passed. git diff --check passes.
## Description
Optimize both benchmark source bundles with the existing Rollup Terser plugin before import and timing. Verify generated development constants are literal false, pass them through compress.global_defs, and reject residual __DEV__ identifiers. Reserve those identifiers from mangling so the check cannot be fooled by renaming.
Add four optimizer regression tests and record full and focused 21-sample comparisons on Node 24.21.0. The Lexical implementation is unchanged.
## Test plan
### Before
Inspecting the production-mode esbuild bundle still found development guards:
```text
{"minifySyntax":false,"bytes":524157,"devIdentifiers":36,"typeMismatchFunctionPresent":true}
```
### After
```sh
LEXICAL_BENCH_FILTER='^$' node scripts/bench-get-writable.mjs e77523b
```
```text
"bundles":[{"bytes":179616,"eliminatedDevConstants":10},{"bytes":179600,"eliminatedDevConstants":10}]
```
Both complete optimized comparisons exit 0; all 12 workloads validate both alternating document states and post-batch results. Full and focused raw samples are committed.
```sh
pnpm_config_verify_deps_before_run=warn npm run ci-check
node node_modules/vitest/vitest.mjs run --project scripts-unit --project unit --maxWorkers=2 scripts/__tests__/unit/optimizeBenchmark.test.ts packages/lexical/src/__tests__/unit/LexicalWritableNode.test.ts
git diff --check
```
```text
ci-check: exit 0
Found 0 errors
Test Files 2 passed (2)
Tests 11 passed (11)
git diff --check: exit 0
```
Node v24.21.0. The pnpm setting preserves the existing shared dependency installation without skipping checks. The full unit/browser suites were not rerun locally for this benchmark-only change.
## Description
Install the clone in the node map before passing it to internalMarkNodeAsDirty. This keeps the supplied node current and removes the comment explaining why the previous entry was dirtied. Refresh the Terser benchmark results for this statement order.
## Test plan
### Before
```ts
// The clone is not in the node map yet; dirty the current entry.
internalMarkNodeAsDirty(latestNode);
// Update reference in node map
nodeMap.set(key, mutableNode);
```
### After
```ts
nodeMap.set(key, mutableNode);
internalMarkNodeAsDirty(mutableNode);
```
```sh
pnpm_config_verify_deps_before_run=warn npm run ci-check
node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=2 packages/lexical/src/__tests__/unit
git diff --check
```
```text
ci-check: exit 0
Found 0 errors
Test Files 61 passed (61)
Tests 1055 passed (1055)
git diff --check: exit 0
```
Node v24.21.0. Full and focused 21-sample Terser comparisons exit 0, including all document-state validations. The pnpm setting preserves the shared dependency installation without skipping checks. Full monorepo unit/browser suites were not rerun locally.
## Description Store writable nodes in _cloneNotNeeded as a Map. getWritable checks it before getLatest, so a hit avoids the main node-map lookup and passes the cached node directly to dirty marking. Misses clone the current node, install it in both maps, and then mark it dirty. Register newly created nodes in the cache, evict collected keys from both maps, and use an isolated Map while parsing editor states. Update both TypeScript and Flow declarations. Add a regression test that asserts a cached write does not look up its key in the node map, and regenerate the Terser benchmark results. ## Test plan ### Before On e77523b with the new test file copied in: node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=2 packages/lexical/src/__tests__/unit/LexicalWritableNode.test.ts ```text AssertionError: expected "get" to not be called with arguments: [ '1' ] Number of calls: 2 Test Files 1 failed (1) Tests 1 failed | 7 passed (8) ``` ### After Node 24.21.0: pnpm_config_verify_deps_before_run=warn npm run ci-check node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=2 packages/lexical/src/__tests__/unit/LexicalWritableNode.test.ts ```text Found 0 errors Test Files 1 passed (1) Tests 8 passed (8) ``` ci-check exits 0, including scripts TypeScript, Flow, lint, and formatting. The pnpm setting preserves the existing dependency installation and skips no checks. Full unit and scripts-unit suites on Node 24.19.0: node node_modules/vitest/vitest.mjs run --project unit --project scripts-unit --maxWorkers=2 ```text Test Files 329 passed (329) Tests 7873 passed | 1 skipped (7874) ``` LEXICAL_BENCH_SAMPLES=21 node scripts/bench-get-writable.mjs e77523b All 12 workloads pass their state validations; both timed bundles eliminate all 10 development constants before import. Raw samples, a focused Set control, and separate untimed operation counts are recorded in scripts/benchmarks/get-writable.node24.21.0.json. No test jobs run alongside timing. git diff --check exits 0. Browser platforms were not exercised locally.
## Description
Capture the active editor state once in getWritable. Read its selection directly, and reuse its node map for both cache-miss lookup and clone insertion instead of calling getLatest. Keep the Map cache-hit fast path and the existing missing-node invariant.
Regenerate all twelve Terser benchmark workloads and the untimed operation counts for the measured source. Every development constant is eliminated before timing.
## Test plan
### Before
The existing behavioral tests pass before this optimization, on Node 24.21.0:
node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=2 packages/lexical/src/__tests__/unit/LexicalWritableNode.test.ts
```text
Test Files 1 passed (1)
Tests 8 passed (8)
```
### After
Node 24.21.0:
pnpm_config_verify_deps_before_run=warn npm run ci-check
```text
Found 0 errors
```
ci-check exits 0, including all TypeScript targets, Flow, ESLint, and Prettier. The pnpm setting preserves the checkout's dependency installation and skips no checks.
node node_modules/vitest/vitest.mjs run --project unit --maxWorkers=2 packages/lexical/src/__tests__/unit
```text
Test Files 61 passed (61)
Tests 1056 passed (1056)
```
LEXICAL_BENCH_SAMPLES=21 node scripts/bench-get-writable.mjs e77523b
All 12 workloads pass their setup and post-batch state validations. Both bundles eliminate 10 development constants before import. The combined PR reduces repeated-write time by 23.3–25.5% against base; broader workloads range from -0.4% to +7.9%. No test jobs ran alongside timing.
node node_modules/prettier/bin/prettier.cjs --check packages/lexical/src/LexicalNode.ts
```text
Checking formatting...
All matched files use Prettier code style!
```
git diff --check exits 0. Browser platforms were not exercised locally for this change.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
## Description
Apply the repository Browserslist through Babel preset-env while preserving
native class fields and ES modules. Share Babel options with writable-node
benchmarks, bundle the transformed JavaScript without additional lowering,
and share ES2021 Terser compression with two passes. Pin Rollup's Terser to
5.51.2 for the ES2021 option types.
Regenerate all twelve workloads against the merged main revision with the
same build configuration on both sides. Preserve verification that development
constants are eliminated before timing.
## Test plan
### After
pnpm run ci-check
```text
Found 0 errors
exit 0
```
Core unit tests and focused build/optimizer tests:
```text
Test Files 64 passed (64)
Tests 1064 passed (1064)
```
pnpm run build --prod: exit 0
Published tree-shaking tests (including prepare-release setup):
```text
Test Files 1 passed (1)
Tests 266 passed (266)
```
LEXICAL_BENCH_SAMPLES=21 node scripts/bench-get-writable.mjs f627d2d
All twelve workloads completed; nine development constants eliminated from
each timed bundle. Raw samples are committed. Prettier and git diff --check
passed after regenerating results. Browser engines were not exercised locally.
etrepum
marked this pull request as ready for review
September 17, 2026 15:13
etrepum
requested review from
acywatson,
fantactuka,
ivailop7,
potatowagon and
zurfyx
as code owners
September 17, 2026 15:13
zurfyx
approved these changes
Sep 17, 2026
Merged
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Cache writable nodes in
_cloneNotNeeded: Map<NodeKey, LexicalNode>.getWritable()checks this cache before looking up the requested key in the main node map. A hit returns the cached node. A miss reads the current node directly from the active state's node map, checks the existing missing-node invariant, clones it, installs the clone in both maps, and then marks it dirty.getWritable()capturesgetActiveEditorState()once and reads the selection and node map directly from that state. The same node map supplies both the cache-miss lookup and clone insertion. The initial ephemeral check and the missing-node error are preserved.internalMarkNodeAsDirty()receives the already-current node, eliminating its redundant lookup as well.New nodes enter the cache when their keys are assigned. Batched updates retain live entries until the pending state commits; detached-node GC deletes collected keys from both maps. Parsing uses an isolated cache. Both TypeScript and Flow declarations use the Map type.
The Map stores references to nodes already owned by the pending node map. V8's Set and Map share the ordered hash-table implementation; Map adds a value slot per entry (V8 source). This trades some table storage and maintenance for fewer lookups on cache hits.
Test plan
Eight new tests cover the lookup fast path, writable-node reuse, batching/commit boundaries, collected subtrees and normalized-away nodes, historical/parsed states, selection invalidation, and moved-node parent marking.