Skip to content

Find shadow stages from the node a change names, not from every stage - #7446

Merged
max-sixty merged 6 commits into
mainfrom
agent-a0dfe261172ee6407
Nov 27, 2026
Merged

max-sixty merged 6 commits into
mainfrom
agent-a0dfe261172ee6407

Conversation

@max-sixty

@max-sixty max-sixty commented Nov 27, 2026 •

Copy link
Copy Markdown
Owner

Leaf's runtime found the shadow roots ("stages") it needed by scanning every live stage on the page, so its cost per change grew with how many stages the page holds. #7417, now on main, gives every lf-option a stage of its own, which exposed it: on leaf-dev bench asks at 256 questions (1,024 options), main takes 15.5 s of main-thread CPU to load, against 1.1 s before #7417, and a keystroke takes 14.5 ms and a wheel step 13.6 ms against a 12 ms budget. With this change, load is 1.73 s, a keystroke 6.2 ms and a wheel step 5.1 ms. On main's own prose and document pages it measures no change.

  • matching (dom/arrivals) walks down from each added node, through every open root and stage under it, instead of climbing from every stage's host. The walk, treesUnder (lib/shadow-tree), keeps a list rather than recursing, so no depth of nesting overflows the stack; reach's sweep, the page reading's forgetting of parts and the render checks' openRoots now use it too.
  • shadowRootsIn (dom/shadow), asked of anything smaller than the document, finds the declared roots among that root's own elements rather than filtering every stage.
  • The selection capture asks the platform once with no roots, then again with only the declared roots its ends came back beside, instead of handing it every root on every key, wheel step and press. The press check hands it only the selected range's own tree. pageShadowRoots loses its last callers and goes.

One case answers differently from main: a stage inside a closed shadow root that is not itself a stage, which a page's script or a package would have to build. No walk from above can enter a closed root, so moving that root's host no longer re-offers what the stage holds. adoptShadowStage would enroll such a root, but widget-api.js doesn't export it, so dom/arrivals states the limit instead. Scoped queries also list stages in tree order rather than enrollment order; no caller reads that order. And author markup and code that shadow a DOM property reach the walks as they reach every reader of author elements: a form control named childNodes hides a selection's end in a stage beside it, and a shadowRoot getter that throws runs wherever a walk reads it.

A script that builds a deep nest in the document one element at a time costs more than on main: 256 nested elements appended one by one in one task deliver in 19.6 ms against 4.7 ms, since each record's walk reads every descendant's root where main ran a native query; both grow with the square of the depth. What remains of #7417's load cost is linear, mostly inserting each stage's styles. Found while reviewing the Effect UI work, for which Max asked; Codex reviewed each round. The walks read a host's root as shadowRoot answers and keep only a root whose host is that element, so a closed stage a widget hands out is read as before, and a form's control of that name or a root forwarded from a child is not taken for one.

Tests: pnpm run test:runtime (1,218 pass), pnpm run test:worker, pnpm run check:browser, and 199 focused browser tests. New tests cover an owner in a stage inside another stage, in a stage behind an open root that is no stage, in a form with a control named shadowRoot, and 10,000 nested stages, a closed stage its host hands out, hosts whose shadowRoot answers false or a child's root, as well as a query under a host made in another window and a press on words in a host that stands first in a table.

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

Three runtime readings found the shadow stages they needed by scanning every
live stage on the page, so their cost grew with the stages the page holds
rather than with what changed. #7417, which gives each lf-option a stage of
its own, made that visible: on `leaf-dev bench asks` at 256 sections (1,024
stages) load took 16 s of main-thread CPU, 87% of it in arrivals.js
`matching`.

- `matching` (arrivals.js) found the stages inside each node a mutation
  record names by climbing from every live stage's host (`liveStages()` with
  `under`), so a batch cost (nodes named) x (stages). It now walks the named
  node's tree for hosts (`hostStages`) and recurses into each stage it finds,
  so stages nested in another stage's tree are still found.
- `shadowRootsIn` (shadow.js) filtered every live stage for each root it was
  asked about, which the page reading's watch, `queryAllUnder` and reach's
  sweep ask of each changed node. It now finds the hosts in `root`'s tree
  whose tags declare `shadow` (`declaredElements`) and keeps those whose
  root is declared. This reverses #3266's move to the stage registry for this
  question. `elementById`, whose misses #3266 measured, keeps its cost in
  stages: it asks each stage for the id and keeps the element where that
  stage is a root declared in `root`'s tree (`declaredIn`), the same test
  `shadowRootsIn` applies.
- The selection capture (`pageRange`) and the press check (`onSelectedWords`,
  through the new `pageCaretAt`) handed the platform every declared root on
  the page through `pageShadowRoots` on every key, wheel step and press. They
  now ask the platform once with no roots, take the declared root of the host
  each end comes back beside, and ask again with only those. The answer is
  the same: an end in a root the platform isn't handed comes back at its
  host's edge in Chromium, Firefox and WebKit. `pageShadowRoots` has no
  callers left and is removed.

Tests: a runtime test of an owner in a stage inside another stage, which
fails without the recursion. reach.test.mjs now declares an `lf-` tag through
`adoptRegistry`, since `shadowRootsIn` reads `shadow` through the
vocabulary's doors, which name only `lf-` tags. annotation-inventory adopts a
layer generation: a reading of the page now reads the vocabulary, and the
vocabulary keeps nothing until a generation stands, which every served page
has.

`leaf-dev bench asks options --input click --input key --input tab --input
scroll --sizes 64,256 --rounds 2`, #7417 (4f50787) without and with this
commit cherry-picked, load average 13-17 on 18 cores, CPU ms:

  asks          64 before  64 after  256 before  256 after
  load             1410.8     621.7     15938.5     1856.5   (exp 1.91 -> 1.15)
  click              23.0      18.3        53.3       31.5
  key                 6.3       5.0        11.1        6.1
  tab                19.6      15.6        40.2       25.4
  scroll              5.5       3.7        14.1        5.9

  options       64 before  64 after  256 before  256 after
  load              266.8     257.2       744.1      439.7   (exp 1.89 -> 1.08)
  click              16.5      15.3        29.5       26.3
  key                 4.4       4.5         6.0        5.1
  tab                12.2      12.0        28.1       26.9
  scroll              2.2       1.8         4.1        2.8

After the fix, `--profile` on asks lists no load function growing faster
than exponent 1.5 and no key or scroll function from these paths. On main's
own pages, `bench prose document` with revision, key, tab, scroll and click
at 64 and 256 reads the same CPU on both arms, and the prose revision at 256
paints in 278.5 ms on both (three rounds).
…rces

#7433 moved arrivals, native-selection, shadow, widget-elements and
readings/passages to TypeScript. This branch's changes to their compiled
.js now live in each .ts, and node build/typescript.mjs regenerated the
.js. The port is a move: treesFrom is typed Element | ShadowRoot,
shadowRootsIn and declaredIn take Document | DocumentFragment | Element,
and the code is otherwise as before.
leaf-agent
leaf-agent previously approved these changes Nov 27, 2026
An independent review of 8e5045b found five regressions against its
parent. Each now has a test that fails on 8e5045b and passes here.

- A stage behind an open root that is no stage was out of `matching`'s
  walk, which entered only stages, so moving its outer host delivered no
  arrival or departure. The walk now passes through every open root and
  every stage, and takes matches only from the named node's tree and the
  stages. Runtime test: an owner in such a stage connects and disconnects
  with the outer host.
- The walk called itself once per nested tree, so a record naming thousands
  of nested stages threw RangeError and lost the batch. One iterative
  walk, `treesUnder` in lib/shadow-tree.ts, now serves `matching`, reach's
  sweep, the page reading's forgetting of parts (passages.ts) and the
  render checks' `openRoots`, each naming the trees it enters. Runtime
  test: a record naming 10,000 nested stages is read through.
- `shadowRootsIn` read `shadow` through the vocabulary's doors, which list
  only `lf-` tags, so it disagreed with `declaredRoot` and `elementById`
  for any other declared tag, and reach.test.mjs had been changed to hide
  it. It now asks `declaredRoot` of each element of `root`'s tree, or, for
  the document, of each stage, as before 8e5045b: the anchor reading
  asks the document on every wheel step and Tab, where a query of the page
  cost a page of plain prose its whole size. reach.test.mjs and
  annotation-inventory.test.mjs are back as they were on main.
- Through `declaredElements`, a host made in another window, as a live
  sample's frame makes one, was no `instanceof Element` here, so a query
  under the host missed its own root. `shadowRootsIn` tests the node's
  kind instead. Browser test: a query under such a host reaches its
  declared root.
- The press check asked the platform for the caret with no roots and read
  the host off the answer, but Chromium and WebKit place a point over a
  host that stands first in a table before the table, so a press on words
  selected there pressed the control around them. It now hands over the
  selected range's own tree, the only one whose characters can be in it,
  and `pageCaretAt` goes. Browser test: a press on such words doesn't
  press the `role=button` around the table.

`shadowRootsIn` has no caller outside shadow.ts left and is no longer
exported.

Not covered: a stage behind a closed root that is no stage. No walk from
above can enter that root, so moving its host re-offers nothing the stage
holds; the stage is heard only by records of its own. Covering it would
take either a record of closed roots (wrapping `attachShadow`, which still
misses declarative closed roots) or the per-record climb from every stage
that this branch removed.
leaf-agent
leaf-agent previously approved these changes Nov 27, 2026
…ermost nodes

A second review of 6372e42 found two more defects against the merge base
and one cost the branch could also remove.

A. A form answers `shadowRoot` with its controls of that name, so a form
   holding inputs named `shadowRoot` handed a RadioNodeList to `treesUnder`,
   whose `querySelectorAll` threw and lost the batch. `openRoot`
   (lib/shadow-tree.ts) now reads the platform's own `shadowRoot` getter,
   which answers for an element of any window, and `seenRoot` (arrivals.ts)
   and `declaredRoot` (shadow.ts) read through it. Runtime test: an owner
   inside such a form connects when the form arrives. happy-dom has no named
   properties on a form, so the test gives the form the browser's answer as
   its own; it fails on 6372e42.

B. `partScopes` (readings/passages.ts) filtered every live stage for each
   part, so the page reading cost parts x stages. It now finds a part's
   declared trees from the part down (`treesUnder(root, declaredRoot)`), and
   the declared trees under what any of their slots shows, which is what
   `readingUnder(stage.host, root)` admitted through a slot. It no longer
   admits a declared stage inside a root that is not a declared stage, whose
   words the page reading's walk never enters. Runtime test: a part reads
   the declared tree of a host one of its slots shows; it passes on
   6372e42 and fails without the slot step.

C. A batch that names nested additions, as a script appending elements one
   inside the last, walked each record's node, so every later addition was
   walked again: 992 elements visited for 32 nested elements and 4,032 for
   64 on 6372e42. `read` now walks an added node only when none of its
   composed ancestors is among the batch's added nodes, and likewise a
   removed node among the removed ones. Runtime test: each of the nested
   elements' owners connects, and doubling the chain about doubles the
   elements visited (62 then 126).

D. Queries under an element now list the declared roots in tree order, where
   the merge base listed them in enrollment order; queries of the document
   keep enrollment order. No caller depends on the order: `queryAllUnder`'s
   scoped callers filter, map, test with `some` or collect into a set
   (projection data, a control's label barriers, the ids a change names),
   `pageQueryAll`'s one `find` asks the document, and the `arriveBatch`
   owners (reach, code-copy) treat each element alone. No change.

E. `matching`'s comment and the arrivals.ts header now say that a closed root
   is entered only once it is a stage, as `adoptShadowStage` makes one. That
   function is Leaf's own; `widget-api.js` exports only `shadowStage`, which
   builds an open stage, so a stage inside a page script's or a package's own
   closed root is heard only by records of its own.

`leaf-dev bench asks document --input click --input key --input tab
--input scroll --sizes 256 --rounds 2 --base` (base c21e060, main with
#7417), CPU ms at 256, load average 8-22 during the run:

  asks       load 16968 -> 1933, click 64.4 -> 35.4, key 11.1 -> 6.1,
             tab 39.4 -> 23.6, scroll 13.1 -> 5.0
  document   load 550 -> 588, click 20.8 -> 21.4, key 7.9 -> 7.3,
             tab 18.4 -> 16.9, scroll 7.8 -> 7.1

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The outermost filter added in d545118 drops a stage's own records when the host of a closed root the stage stands in arrives in the same batch. The climb in outermost crosses every shadow boundary, closed ones included, since ShadowRoot.host answers for a closed root. So the stage's record is skipped as "found by the host's walk", but matching on that host can't enter the closed root (seenRoot gives it neither an open root nor an enrolled stage). This breaks the case the new arrivals.ts header promises ("a stage inside a page script's or a package's own closed root is heard only by records of its own"). shadowStage enrolls the stage and then fills it in the same task, so a page script's element with a closed root, holding a shadow widget that stages as it connects, hits this when the element is appended.

Here is a repro in Chromium through the serve fixture. Owners in the stage never connect at d545118, and they connect at 6372e42:

const host = document.createElement('div');
const closed = host.attachShadow({ mode: 'closed' });
const inner = closed.appendChild(document.createElement('div'));
const stage = inner.attachShadow({ mode: 'open' });
watchArrivalsIn(stage);
const owner = document.createElement('span');
watchOwner(owner, { connect: () => log.push('connect') });
document.body.append(host);
stage.append(owner);   // log stays [] at d545118

happy-dom delivers each target's records in a separate callback, so a runtime test can't show this. It needs a browser test. The fix is to stop the climb at a root the walk doesn't enter (suggestions inline, plus a rebuild of arrivals.js). With that change applied to the built file, the probe passes in Chromium and tests/runtime/arrivals.test.mjs passes 20/20, including the nested-chain visit count.

Comment thread browser/runtime/dom/arrivals.ts Resolved
Comment thread browser/runtime/dom/arrivals.ts Resolved
Codex's review of d545118 found five cases where it answered differently
from the merge base, all in two changes that fixed no regression:

- The walk of each batch's outermost nodes lost a departure when a watched
  element moved into an unenrolled open root under a host the same batch
  removed, and a form control named `parentNode` cycled its ancestry, which
  skipped arrivals and could loop. It also added ancestor reads on every
  addition, on pages with no stages too. The merge base walked overlapping
  records again as well, so `read` goes back to walking every node a record
  names.
- The slot-aware `partScopes` lost a heading shown through a slot that
  forwards another slot, threw on an SVG `slot`, and threw on an assigned
  form with a control named `querySelectorAll`. It measured no change on
  `asks`, so `partScopes` goes back to filtering the live stages.

`openRoot` keeps reading the platform's own `shadowRoot` getter, now looked
up at its first call: the Worker's tests import lib/shadow-tree.js where no
`Element` is defined, which failed CI on d545118.

Tests: `pnpm run test:runtime`, `pnpm run test:worker`,
`pnpm run check:browser`, and the host-from-another-window browser test.
leaf-agent
leaf-agent previously approved these changes Nov 27, 2026
Codex's review of 37ac6cd found that the platform's own getter, which
`openRoot` read so that a `<form>` with a control named `shadowRoot` gave
no control as a root, also missed a closed stage a widget hands out as its
`shadowRoot`. `shadowStage` builds the stage in that root, and the merge
base read its words and ids there; the branch read the host as opaque.

`openRoot` now reads `host.shadowRoot` as the page's own code does and
keeps the answer only when it is a root whose host is that element. That
reads the handed-out stage, and reads a form's control, a lazy widget's
`false` and a wrapper forwarding its child's root as no root, without a
throw and for a host of any window; and it needs no lookup the Worker's
tests would trip on.

Two classes stay as they are on the merge base, since every walk now reads
each element's root and a defense for each shape would grow without end:
a form control named after a DOM property shadows it on its form (one
named `childNodes` hides a selection's end in a stage beside it), and an
author getter that throws or has side effects runs where Leaf reads it.

Tests: `pnpm run test:runtime`, `pnpm run test:worker`,
`pnpm run check:browser`.
@max-sixty
max-sixty merged commit e2ce3aa into main Nov 27, 2026
6 checks passed
@max-sixty
max-sixty deleted the agent-a0dfe261172ee6407 branch November 27, 2026 23:14
max-sixty added a commit that referenced this pull request Nov 27, 2026
`browser/AGENTS.md` gains "Renderers", which names both renderers (a
bundled widget is a `LeafElement` or a `defineWidget` component, and the
chrome draws with Lit) and the rule Max picked ("Port by the rule
above") on the Effect UI direction review page on 27 November 2026.
Under it, a port deletes the Lit view it replaces, and a service it adds
calls the same owner as its `widget-api.js` function. It names what it
made easier and benches a page full of its widget, base beside head,
within root `AGENTS.md`'s "Responsiveness" budgets. A widget that
decorates the author's children tries a light-DOM part first. The chrome
moves only once `@effect/ui` ships a release whose mount and component
APIs aren't experimental. A widget that can't meet the rule is the point
to stop and raise it. The section replaces the two statements that
prescribed Lit alone, `packages/AGENTS.md` points ports to it, and two
comments that contradicted it change: `lf-options.js` no longer calls
its shadow roots the shape of every decorating widget, and
`build/vendor.mjs` no longer says the chrome draws with Effect UI. The
bench item comes from #7417, which ported `lf-options` without one and
made a page of 1,024 options take 15.5 s to load (#7446 fixed the scan
behind that).

A temporary A/B scored it: headless Opus plans for porting `lf-tabs` and
for moving the Page Map dialog, three runs per arm per task, base text
beside this branch, judged by Opus and corrected by reading the quotes.
Base passed 3/3 on deleting the Lit view, 0/3 on naming what the port
made easier, 3/3 on benching base beside head, 0/3 on trying a light-DOM
part first, and 0/3 on holding the chrome back. Head passed 3/3 on every
one. Every base `lf-tabs` plan took shadow roots, citing the old
`lf-options` header line, and every base Page Map plan went ahead and
rewrote the Lit rule. Every head `lf-tabs` plan found that
`defineWidget` appends its light box after the authored children, where
a tab strip can't stand. Root `AGENTS.md` already sends both arms to
`leaf-dev bench`. The runs cost $23.86.

> _This was written by Claude Code on behalf of max-sixty_
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