Skip to content

Restyle long runs of siblings in linear time - #5063

Merged
max-sixty merged 1 commit into
mainfrom
grind/sibling-selector-cost
Nov 2, 2026
Merged

max-sixty merged 1 commit into
mainfrom
grind/sibling-selector-cost

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

Pages with a long run of sibling elements now restyle in linear time. On main, a 1 MB text document spent 44 s of main-thread time drawing, almost all of it in style; with this change it spends 3.9 s. Part of #4781, whose export work (#5053) found the slow draw.

Cause

The rule in layouts.css that places what a page writes before its parts (the title column beside [data-lf-views="parts"]) has no class or tag in its subject, so the browser tests it against every element on every style pass. The browser checks a compound's conditions in the order written, and the first was :has(~ [data-lf-views="parts"]), which reads every later sibling of the element tested. On an element with thousands of later siblings, such as a row of a long text document or a line of a long lf-code block, each test read them all, so a pass over n siblings cost n². Selector statistics and ablation located it: removing these three rules cut a 300 KB listing's restyle from 1,448 ms to 406 ms.

Change

:where(main > *) now stands first in the compound, in all three copies of the rule, so an element outside main fails at once and no sibling is read. The rule's subject already sits under body > main:not(...) >, so the condition matches every element the rule matched before and no other.

What every page gains

Main-thread CPU (thread ticks from Performance.getMetrics), from navigation until the page is drawn. The host was loaded (one-minute load 5–17), so the CPU column is the reading to trust.

Page main this change
lf-text-document bound to 1 MB of text (18,000 lines) 44.1 s CPU (43.4 s style), 44 s wall 3.9 s CPU (3.3 s style), 4.9 s wall
lf-code, 22,000 lines 64.0 s CPU (62.8 s style), 64 s wall 9.0 s CPU (7.9 s style), 10 s wall
review-a-plan, median of 7 interleaved loads 141 ms CPU (35 ms style) 143 ms CPU (36 ms style)
the corpus page, median of 5 interleaved loads 24.8 s CPU (2.59 s style) 24.0 s CPU (2.37 s style)

An ordinary page has no long run of siblings, so it gains nothing measurable: the review-a-plan difference is noise, and the corpus page's style time moved by less than its script time did, which this change can't touch. Peak renderer memory is not lower: the 1 MB page peaked at 1.3 GB on main and 2.0 GB here, since the same styles are built in a shorter burst. #5061 addresses the memory.

Evidence that it changes no style

  • uv run leaf-dev stills 5a16ff03f over 15 states: the corpus (on-me, on-me-dark, on-agent), the feature gallery (gallery-tabs, gallery-theme, gallery-theme-dark), the side-list workspace (side-tab-focus, alert-queue), native-code, walkthrough, plan, triage, hub, page-about and markdown-preview-scrolled. Thirteen states were unchanged. page-about differed in pixels with no computed-style difference, as its states always do. One corpus state differed in 20 computed properties on one element, the preview of the widget builder's generated request document, which sits in main.layout-column, where the rule can't match. A second run moved that difference from on-me-dark to on-me, so it varies from load to load.
  • The rule's only target is a main with no Layout whose children include a parts holder after other content. tests/fixtures/pages/root-parts.html is that page: a header before lf-parts. Every computed property of all 452 elements, in the document and its open shadow trees, matched between main and this change (leaf-dev probe --base with reduced motion), apart from one mask-image whose URL names each arm's own revision path. The header kept position: fixed, grid-column: 1 and anchor-name: --lf-parts-title.
  • The rule lives in the lf-layouts layer every page composes, whatever its theme, and the condition it adds reads no theme value.

What I ran

  • The tests that read the parts layout: test_each_part_of_a_page_of_parts_is_laid_out_as_a_page_of_its_own, the parts, side-list, strip and workspace-part tests in widgets/test_tabs.py, test_a_page_read_from_its_top_stays_at_its_top_as_the_window_narrows and the part ring tests in controls/test_rings.py (20 passed).
  • pnpm run check (passed).
  • Timing: a Playwright script serves each page from an extracted main arm and from this tree (leaf_dev.arms.serving_source), reads Performance.getMetrics in thread ticks, and samples the renderer's RSS. The 1 MB and lf-code pages are generated fixtures of 80-character lines.

This was written by Claude Code on behalf of max-sixty

The rule that places what a page writes before its parts (layouts.css)
has no class or tag in its subject, so the browser tests it against
every element on every style pass. Its first condition was
`:has(~ [data-lf-views="parts"])`, which reads every later sibling of
the element tested. On a long run of siblings, such as the 18,000 rows
of a 1 MB text document or the lines of a long lf-code block, each pass
cost time in the square of the row count.

`:where(main > *)` now stands first in that compound, in all three
copies of the rule. An element outside `main` fails it at once, before
any sibling is read. The rule's subject already sits under
`body > main:not(...)`, so the guard changes no match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@max-sixty
max-sixty merged commit ab607c2 into main Nov 2, 2026
4 checks passed
@max-sixty
max-sixty deleted the grind/sibling-selector-cost branch November 2, 2026 07:25
max-sixty added a commit that referenced this pull request Nov 2, 2026
A long text document now draws only the runs of lines near the view.
#5063 fixed the selector that made restyling a long run of siblings
quadratic; this change takes the rest. With that fix, a text document
bound to 1 MB of text still spent 4 s of main-thread time drawing and
peaked at 2 GB in the renderer, and 4 MB spent 16 s and 6.5 GB. They now
draw in 0.4 s and 1.0 s, peaking at 310 MB and 650 MB. The work on #4781
(export performance, #5053) found the slow draw.

### Before and after

Main-thread CPU (thread ticks from `Performance.getMetrics`), wall time
to drawn, and the peak resident memory of the renderer, one run each.
The first column is `main` (b299fe0) with #5063's fix applied; the
second is this branch at its head. The host was loaded, so the CPU
column is the reading to trust.

| Page | after #5063 | this change |
| --- | --- | --- |
| 1 MB plain text | 4.0 s CPU, 5.3 s, 2.0 GB | **0.37 s, 0.7 s, 310 MB**
|
| 4 MB plain text | 15.8 s, 17 s, 6.5 GB | **0.96 s, 1.3 s, 650 MB** |
| 1 MB Python | 6.6 s, 8.1 s, 3.1 GB | **0.8 s, 2.0 s, 490 MB** |
| 4 MB Python | 26.3 s, 28 s, 8.2 GB | **2.5 s, 2.8 s, 1.2 GB** |
| 1 MB Markdown, `preview="markdown"` | 4.0 s, 5.2 s, 1.6 GB | **1.7 s,
5.5 s, 640 MB** |
| 4 MB Markdown, `preview="markdown"` | 21.5 s, 23 s, 5.6 GB | **11.5 s,
13 s, 2.1 GB** |

On the reviewer's 1 MB fixture, 12,407 lines of up to 407 characters, so
most rows wrap, read in Chromium 156 and Firefox 157 (Playwright's
builds). "Before" is this branch's previous head, 056c047, merged with
main:

| Reading | before, Chromium | before, Firefox | now, Chromium | now,
Firefox |
| --- | --- | --- | --- | --- |
| Drag to the bottom, first try | 1,580 px short | 980 px short | at the
end | at the end |
| End on the focused listing | at the end | 2,440 px short | at the end
| at the end, once the face has settled (below) |
| `t` to line 11,000 after a reload | line at 214 px, after a second
landing | line reported at 214 px, but `elementFromPoint` there found
line 11,041 and its run was still skipped | line at 214 px, one jump |
line at 214 px, one jump, the hit-test finds line 11,000 |
| End after narrowing from 718 to 460 px, last runs drawn before | 240
px short (b57ae94) | 1,700 px short (b57ae94) | at the end | at the
end |
| Wheel step, 4 MB plain / 4 MB Python, median | 110 ms / 475 ms
(review) | | 8.5 ms / 19 ms | |

### Causes

**Every row was styled several times per load.** With the selector
fixed, a load still restyled every element three times. The first pass
ran inside a layout, after `@property` registrations marked the whole
document. Marking the listing's scroller (`data-lf-scrolls`) changed an
inherited property on it. The body's `data-lf-presented` stamp ended
`transition: none` on everything in `main`. At about 17 µs per element
per pass, a 280,000-element listing took 15 s. The listing's rows now
stand in runs of 128 rows, each `content-visibility: auto`
(`lf-text-document.js`, `inRuns`). The browser styles and lays out only
the runs near the view, so each of those passes covers a few hundred
elements. The text stays in the DOM: find-in-page, selection, copy and
comment anchoring work on all of it. A lone run stays drawn, so a short
text draws as before, and a log that grows past one run keeps its rows
and a selection in them.

Each run lays out Pierre's two columns as its own grid. The run sizes
its number column to its own numbers, so a number takes the width of the
text's widest one (`--diffs-min-number-column-width-default`), and every
run's lines start at the same x.

**A row that lines added above it carried into another run was drawn
anew.** Reconciled run by run, each run was the identity boundary for
its rows. One line prepended above the last row of a run grew a
selection there to take in the row before it in Chromium, and cleared it
in Firefox; two hundred cleared it in both. The rows are now reconciled
across the whole listing (`reconcileRuns`). Which old line each new line
stands for comes from a walk over whole lines private to the widget
(`keptLines`, jsdiff's `diffArrays` capped at 1,000 edits, as the
runtime's text alignment is); a run of lines replaced by as many others
stands for them one for one, so an edited row is kept and its text
patched in place. The kept rows move into the runs the new text puts
them in with `setChildLists`, and each run then reconciles its rows with
`setRenderedChildren`, finding its kept rows in place. A run's numbers
stay with it, since they count its places. Where a rewrite runs past the
walk's cap of 1,000 edits, nothing moves and each run reconciles its own
rows, as before: walked to the end, every line of 4 MB rewritten took
285 s in review.

**Moving a node lost a selection in it.** The DOM's move algorithm runs
the live range pre-remove steps, so a selection with an end inside a
moved node is reset, `moveBefore` included, in Chromium and Firefox.
`setChildLists` now holds the page selection where an end lies inside a
node it places, and puts it back through `selectEnds` once the nodes
have landed and before the caller edits any text (`holdSelection` in
native-selection.js, which leaf.js installs into `dom-move.js` before
the boot draws anything, so the portable mover still loads off Leaf). It
installs there rather than beside `installMoveFocus` in move-focus.js:
native-selection.js reaches context.js through shadow.js, and imported
from move-focus.js, which framework.js imports first, it left `readPart`
uninitialized when a module read it. An end inside a shadow tree stays
its editor's. `lf-call-diff`, which reorders its rows with
`setChildLists`, keeps a selection on a reordered row too; without the
hold it was cleared in both engines.

**A skipped run is sized by estimate, and the estimate was a line a
row.** On wrapped text that fell thousands of pixels short. End, a drag
to the bottom and travel to a line each stopped short as the runs they
passed took their real heights. Each run's
`contain-intrinsic-block-size` now counts the lines its rows fill
(`sizeRuns`): a row's characters broken as `pre-wrap` breaks them, at
the line length read off the drawn first run. On the 1 MB wrapped
fixture and a 1 MB Python file the estimate matches the drawn height to
the pixel, in Chromium and in Firefox once its face settles. The runs
are sized again when the listing's width changes or a drawn run changes
height, as when a freshly started Firefox swaps its fallback face for
its real one. That swap comes seconds after launch: before it, Firefox's
estimate was 80 px off the drawn height on prose and 3.9% off on
highlighted Python. End pressed in those seconds still ends up to 600 px
short, since the run on screen grows when the face arrives; on main the
same window left the fourth drag to the bottom 59,400 px short.

**A run drawn at one width kept that height at another.** Chromium,
Firefox and WebKit keep a skipped run's drawn height, whether or not
`contain-intrinsic-size` says `auto`, until its style resolves with
neither `auto` nor `content-visibility: auto`; writing the size without
`auto`, for frames on end, changed nothing. css-sizing-4 says the height
goes at ResizeObserver timing once `auto` is gone, and no engine does
that, so the forgetting below rests on uniform but unspecified
behaviour: `notes/browser-support.md` records it, and the drag after
narrowing in the long-document test is its tripwire. WebKit, measured in
review: End and the drag 1,834 px short without the forgetting, at the
end with it. Narrowed after the last runs were drawn, End stopped short
(the table above). When the line length changes, each run drawn since it
last forgot a height (`contentvisibilityautostatechange`) that is
skipped now resolves its style once as `hidden` without `auto`, then
takes both back in the same task, before anything is drawn. Only such
runs go through it: the resolution cost Firefox about 60 ms on 4 MB, and
426 ms when every skipped run whose size changed went through it.
Firefox's first refit after a narrowing on 4 MB now takes 85 ms against
27 ms without forgetting; Chromium's 29 ms against 24 ms. The refit also
runs in the frame after the ResizeObserver's delivery: inside it, when
Firefox's face arrived, it resized the code the observer watches, and
Firefox reported "ResizeObserver loop completed with undelivered
notifications".

**Asking about skipped content restyled it.** `skipped()`
(`shown-box.js`) called `checkVisibility()` without
`contentVisibilityAuto`, and for content an off-screen `auto` box skips,
the browser styles that content to answer. The reading-place walk asks
it of every line, so the first scroll restyled every run. `skipped()`
now climbs with `checkVisibility({contentVisibilityAuto: true})` alone,
and `skipper()` names the box that skips an element, so the
reading-place walk asks once per run and passes over the rest of its
lines. The live view's scrollbar check (`render-checks/scrollbars.js`)
had the same problem and now passes over skipped content too, so it
can't see the end of a long document while the reader is away from it.
Runs alone made the first scroll inside a 1 MB listing take 1.3 s and
the live view's first report 1.4 s; they now take 57 ms and 25 ms.

**Travel jumps into skipped content, and draws where it lands.** A
thread or datum travel into a `content-visibility: auto` box lands at
once (`anchor-travel.js`): a glide across the runs drew each one it
passed, which took 2.4 s on a long text. The jump computed its landing
from the skipped run's estimated layout, and Firefox keeps a run skipped
until it meets the view at an update. Where the estimate is short, as
over long tokens, which Firefox also breaks after a slash, the landing
was off: on the review fixture Firefox drew lines 26 past the
destination, and in the long-document test the jump stopped 104 px short
and a second scroll followed. Travel now draws the run holding the
destination for the jump and releases it two frames later
(`drawForLanding`), so the landing no longer depends on the estimate;
`notes/browser-support.md` records the Firefox gap. A run a landing
holds drawn still counts as skippable (`skippableBox`), though its
computed style reads `visible`: read from the style alone, a second `t`
within those two frames, as a held key repeats, glided, and in Chromium
on the base64 fixture left line 1148 1,220 px out of view, and Forward
missed too.

### Remaining costs

- **The first wheel step.** It builds the page's reading of passages,
181 ms on 4 MB of plain text and 549 ms on 4 MB of Python; later steps
take 8.5 ms and 19 ms.
- **Select-all.** A selection over the whole listing draws every run:
13.7 s on 4 MB of plain text, and 34 s and 7.8 GB on 4 MB of Python
(review).
- **Markdown preview.** A 4 MB Markdown preview still takes 11.5 s. The
preview's blocks are restyled three times, as the rows were, and
grouping them into runs would change how margins collapse at each run's
edge.
- **`lf-code` and `lf-diff`.** They draw their own rows, so runs would
be a change in each. At 22,000 lines, with #5063, they take 9 s and 4.6
s.
- **Full restyles at load.** The three passes above cost every page a
full restyle per load. On ordinary pages that is tens of milliseconds.

### Calls Max may reverse

- **Travel jumps.** A thread or datum travel into a long text document's
lines, or any `content-visibility: auto` content, jumps rather than
glides.
- **Text whose lines break other than as the estimate assumes ends
short.** On CJK or base64-heavy text, End or a drag to the bottom can
stop short (Chromium on CJK about 1.7k px, Firefox End on base64 about
19.5k px), and a second press reaches the end. My call is to accept that
rather than add per-character-class break rules. In Firefox, End scrolls
smoothly and draws each run it passes; where those runs draw taller than
their estimate, the code grows during Firefox's ResizeObserver loop and
it logs "ResizeObserver loop completed with undelivered notifications".

### What I ran

- The reviewer's journeys on their fixtures (`.tmp/review/` in the
review worktree): End and the drag, travel after a reload with and
without a wheel during the landing, the Firefox hit-test, growth past
one run, and the wheel-step profile. Estimate accuracy: each run's
estimated height against its drawn height on the 1 MB wrapped and Python
fixtures, in both engines. Draw cost: a Playwright script that reads
`Performance.getMetrics` in thread ticks and samples the renderer's RSS.
-
`test_a_long_text_document_draws_the_lines_in_view_and_keeps_the_rest_whole`,
in Chromium and Firefox, on wrapped text with base64 lines in every run
but the last: a drag to the bottom after the window narrows reaches the
last line, two travels back to back into one run, the second while
frames are held so the first still holds the run drawn, take one scroll
each, and `elementFromPoint` at the second line's reported place finds
it. Sized a line a row, it fails in Firefox at the skip check after the
reload, and passes in Chromium. Without `drawForLanding`, it fails in
Firefox with an extra scroll. Without the forgetting, the drag stops 672
px short in Chromium and 32 px in Firefox. Without the `skippableBox`
fix, the second travel glides: 48 scroll steps in Chromium and 31 in
Firefox.
- End after narrowing on the 1 MB fixture (`j_end_narrow.py`), fresh and
with the last runs drawn before, in both engines: at the end in all
four.
-
`test_a_text_document_update_keeps_a_selection_it_carries_into_another_run`,
in Chromium and Firefox: a selection on the last row of a run in a
278-line text survives one line prepended, its own line edited in place,
and 200 lines prepended with its line edited again, and the numbers
count every row in order. At 1e10ee2, and without the hold, it fails
at the first insertion: Chromium's selection reads `line 127\nselected
passage\n`, Firefox's is empty. Without pairing replaced lines, it fails
at the edits.
- `tests/runtime/text-document-lines.test.mjs`, importing the widget's
`keptLines`: it shifts lines past an insertion, pairs a same-length
replacement, and gives up (null) on a full rewrite or every other line
edited of 2,000 lines, so the widget takes the per-run path. Without the
cap it fails in 0.25 s; without the pairing it fails too.
- An `lf-call-diff` check (not committed): a selection on a row a data
update reorders stays, in Chromium and Firefox; without the hold it is
cleared.
- The selection and call-diff tests that `setChildLists` reaches, in
`test_render_semantic_selection.py`, `navigation/test_commenting.py`,
`drafts/test_comment_targets.py`, `test_render_aim.py`,
`widgets/test_diffs.py` and `test_render_diff_controls.py` (68 passed, 3
failed). The three fail the same way with main's copy of every file this
branch changes:
`test_borrowed_scroll_stops_leave_code_selection_and_marks_with_their_owners[None|-1]`
(no dialog on the marked code) and
`test_a_diff_refresh_keeps_a_selection_in_unchanged_lines` (its gutter
read finds no `lines` on the diff's file entry, after the selection
check passes).
- The update cost, main-thread task time from `cmd_data_set` to the
drawn update (`Performance.getMetrics` in thread ticks), two runs each,
1e10ee2 → this head: 4 MB one line prepended 1.41 → 1.29 s; 200 more
prepended 2.08 → 2.27 s; every line rewritten 1.74 → 1.61 s; 1 MB every
tenth line edited 0.37 → 0.37 s; every line rewritten 0.44 → 0.42 s.
Main took 4.31 s and 4.68 s for the two prepends. The 4 MB load is
unchanged: 0.75 s of task time, 0.86 to 1.04 s to drawn, 554 to 572 MB,
on both.
- `uv run pytest tests/browser/widgets/test_code_and_documents.py -k
document` (18 passed); earlier, the travel tests in
`navigation/test_reading_place.py` and `test_render_anchors.py` (12
passed; 4 failed and 3 errors, the inherited bottom-clearance and
deferred-diff failures below). The text-document, scrollbar-clearance,
state-wait, parts, tabs, travel and skipped-content tests in
`test_render_pages.py`, `widgets/test_tabs.py`, `test_geometry.py`,
`navigation/test_threads.py`, `test_render_anchors.py`,
`navigation/test_reading_place.py`, `threads/test_targets.py`,
`projection/test_code_review.py`, `startup/test_projected_data.py`,
`controls/test_rings.py`, `widgets/test_workspaces_and_bounds.py` and
`test_render_gate.py` (87 passed, 5 failed, 3 errors, all inherited).
- `pnpm run test:runtime` (749 passed), `pnpm run check` (passed), `pnpm
run build:browser` (kernel rebuilt), and `uv run pre-commit run --files`
on every file this branch changes.

Inherited failures, which fail the same way with main's own files in
place of this branch's:
`test_thread_travel_keeps_its_passage_above_the_bottom_reading_clearance`,
`test_datum_travel_resolves_the_destination_after_reveal`,
`test_thread_travel_into_a_bounded_log_scrolls_the_log_and_the_page_no_more[named|anonymous]`,
and
`test_a_deferred_diff_renders_only_opened_files_and_hydrates_comment_travel`
(`lf-diff`'s `loadEntry` reads `path` of null).

Not verified: the browser's own find-in-page bar, which a headless
browser can't open; Safari on a device; Firefox on a machine other than
this Mac, where the listing's face may arrive at another time.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants