Skip to content

perf(lynx): describe the first tree after the frame it describes - #273

Merged
Huxpro merged 3 commits into
new-lynxfrom
perf/lynx-capture-after-paint
Sep 2, 2026
Merged

Huxpro merged 3 commits into
new-lynxfrom
perf/lynx-capture-after-paint

Conversation

@Huxpro

@Huxpro Huxpro commented Sep 2, 2026

Copy link
Copy Markdown
Owner

Summary

Per #247's owner directive (issuecomment-5505266187): move capture out of the FCP window.

A synchronous first screen runs render → publish → capture → announce with nothing between the entry's call and the browser's next frame, so all four are inside the paint window. Only the first two produce the frame. capture validates the painted tree and builds the description the background clones when it adopts, and nothing on the paint path reads either.

An engine-lifecycle receiver now publishes the frame and takes capture and announce in the next task.

The order does not move, only the timing

Both arms run one shared captureFirstScreen body. That is the point of the shape rather than a convenience: there is no second sequence that could answer differently, so "the boundary moves in time, not in order" is a property of the code instead of a claim about it.

announce still waits for capture, and it needs no new gate to do so — canAnnounceReady() already withholds the reply while the screen is open. So a correlated ready request landing in the gap waits and is answered by the capture that was already scheduled: never a partial tree, never a second one built to answer it. That is the #231/#233 fence reused rather than rebuilt, which is why the wire-budget tests are untouched.

Every other reader brings capture forward instead of finding nothing:

reader why it cannot wait
a tap on the painted tree the token index it resolves through is built by capture; without this the delivery resolves no first-tree target, falls through to the live-root path, and is discarded as an event with no accepted root — the paint would be tappable and the tap lost
firstScreenSnapshot() null has meant "no synchronous first screen was painted" since the accessor existed and must not also start meaning "painted, not yet described"
an inbound commit adoption reads firstTree to choose between adopting the painted tree and painting a fresh one
unmount, receiver close cleanup disposes a captured journal or retires a declined source; an uncaptured screen is neither, and its container would outlive the receiver

handleAdoptionReady deliberately has no such fence. It was in the first draft; the break matrix showed it dead, and reading it back confirmed why — awaitingAdoption is armed at exactly one site, a commit whose prepared batch adopted the first tree, which already required a captured journal. The comment now says so instead of the code guarding a state the receiver cannot be in.

Two paths decline, and neither approximates

  • An immediate-mode root.render() returns the capture verdict to its caller: null for a tree the background cannot adopt, a throw for one that cannot be captured. Deferring there would answer before the answer exists, so that arm keeps capture in front of the paint. This is the synchronous adopter the directive names — and it is what Lynx for Web uses (main-thread-entry.js defines immediate on web, engine on native). Native, the target engine, is the engine arm.
  • A receiver with no macrotask rung captures inline. A microtask drains before the host can paint, so scheduling capture on one would move the work without taking it out of the window — the deferral in name and today's cost in fact. Promise.resolve().then is therefore deliberately not a fallback here, even though this same file schedules a deferred flush on exactly that: that one only has to outlast a dispatch, this one has to outlast a frame.

A third decline was found by review rather than by design: a scheduler that throws would leave the screen painted, announced to nobody, and described by nothing. It now falls back to the inline order.

New option scheduleFirstScreenCapture chooses the rung — defaults to the ambient setTimeout, takes a host's own "the frame is on screen" callback, and takes null to decline outright. The device round can substitute a better rung without redesigning anything.

Why

captureLynxFirstTree + the three snapshotFirstTree* helpers + describe's per-host map total 1148 ms over 7 screens ≈ 164 ms/screen at 10,000 rows — comparable to publish itself and larger than everything left inside it (source: the profile in #247's publish report; method: per-frame self time from a CPU profile, not ablation and not interleaved A/B).

There is deliberately no web-lane number in this PR. The web harness runs immediate, which declines the deferral, so the lane cannot see this cut at all — quoting a wall-clock delta from it would be quoting noise. Forcing the web entry to engine to make it measurable would change when the page paints in the first place, which is not the same experiment.

What the diff claims instead is structural and is asserted in the suite rather than in a scratch instrument: capture reads one native ID per described host, and the flush is the frame publication, so moves capture in time without moving it in order counts one against the other and pins that zero native IDs are read between the flush and the end of the task that painted, and that the announcement does not go out until the walk has finished.

Changes

  • packages/lynx/src/main-thread.ts
    • captureFirstScreen(source) — the capture and announce phases extracted as one body, returning whether a tree was captured.
    • captureFirstScreenAfterPaint(source) — the same body one task later, with the fault discipline the deferred arm needs: the render call that would have received a fault returned when the paint published, so it settles the screen the way the synchronous catch does and reports rather than rethrows.
    • ensureFirstScreenCaptured() — takes the pending capture before running it, so the announcement's synchronous reentry finds nothing left and cannot run the walk twice.
    • resolveFirstScreenCaptureScheduler + the scheduleFirstScreenCapture option and its validation.
    • renderFirstScreenNow takes deferCapture; the released arm passes false, the engine-lifecycle arm passes true.
  • packages/lynx/tests/first-screen.test.ts — a first-tree capture after the paint suite, 14 tests.
  • .changeset/lynx-capture-after-paint.md

Does this change the sequence?

No. render → publish → capture → announce is unchanged, and the two phases that moved run from the same body in the same order as before. Consumers of the captured tree see byte-identical inputs: adoption, hydration handover, teardown, incrementalCompact, and the announcement-run machinery are all downstream of a firstTree that is built by the same walk from the same source at the same accepted version. The ABI and the wire are untouched. The three deferred publish items from #247's report are not folded in.

Validation

  • pnpm format:check — repo-wide, clean
  • pnpm typecheck — exit 0, clean, repo-wide
  • pnpm test — reported in a follow-up comment on this PR
  • targeted tests: --project lynx, 49 files / 780 tests, all pass
  • pnpm sync — no generated changes

Deliberate breaks

A test only counts once it has been seen to fail. Each row is one break to the source, the whole lynx project run, then restored.

break red
the engine arm never defers 10
the released (immediate) arm defers 22
scheduleFirstScreenCapture: null still defers 1
firstScreenState = 'painted' at publish (announce opens early) 1
drop the tap fence 1
drop the firstScreenSnapshot() fence 2
drop the commit fence 1
drop the unmount fence 1
drop the close fence 1
ensureFirstScreenCaptured clears after running 1
a post-paint fault rethrows out of the scheduler 1
a throwing scheduler strands the capture 1
drop the adoption-ready fence 0 — which is why it is not in the diff

Three of these were 0 red on the first pass (unmount, close, reentry). Rather than delete the guards or wave them through, each got the test that was missing: unmount-in-the-gap, close-in-the-gap, and an announcement that reenters the receiver. The fourth 0 was genuinely dead and the guard came out.

Risk / follow-ups

  • Native is the arm that collects this, and it is the arm with no lane here. The FCP verdict belongs to the device round, per the directive.
  • The default rung is the ambient setTimeout. If LepusNG offers something that lands closer to "the frame is on screen", scheduleFirstScreenCapture takes it with no other change; if it offers no macrotask at all, the receiver declines and behaves exactly as it does today.
  • A tap in the gap pays the capture cost synchronously. That is the same cost today's order charges every first screen, and the alternative is losing the tap.

Provenance

  • An agent produced this diff (agent-authored)

🤖 Generated with Claude Code

https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy


Generated by Claude Code

A synchronous first screen runs `render` -> `publish` -> `capture` ->
`announce` with nothing between the entry's call and the browser's next
frame, so all four are inside the paint window. Only the first two produce
the frame. `capture` validates the painted tree and builds the description
the background clones when it adopts, and nothing on the paint path reads
either: at 10,000 rows it is about 164 ms per screen, comparable to
`publish` itself and larger than anything left inside it.

An engine-lifecycle receiver now publishes the frame and takes `capture`
and `announce` in the next task. The order does not move, only the timing:
both arms run one shared `captureFirstScreen` body, so there is no second
sequence that could answer differently, and `announce` still waits because
`canAnnounceReady()` already withholds the reply while the screen is
unpainted. A correlated ready request landing in the gap therefore waits
and is answered by the capture that was already scheduled -- never a
partial tree, never a second one built to answer it.

Every other reader brings capture forward rather than finding nothing: a
tap resolving its first-tree target, `firstScreenSnapshot()`, an inbound
commit, unmount, and receiver close. `handleAdoptionReady` deliberately
has no such fence, because `awaitingAdoption` is armed at one site that
already required a captured journal.

Two paths decline rather than approximate. An immediate-mode
`root.render()` returns the capture verdict to its caller, so it keeps
capture in front of the paint; that is the arm Lynx for Web uses. And a
receiver with no macrotask rung captures inline, because a microtask
drains before the host can paint and would move the work without taking
it out of the window. `scheduleFirstScreenCapture` chooses the rung,
defaults to the ambient `setTimeout`, and takes `null` to decline.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy
Huxpro and others added 2 commits September 2, 2026 09:48
…renders

During the deferred-capture gap the receiver still reads
firstScreenState === 'open' with a published paint, and two entry
points treated that state as "nothing was rendered yet":

- markFirstScreenSyncReady settled the painted screen as 'skipped' and
  announced readiness with no first tree, so the background would paint
  the page again over the one on the glass — while the still-armed
  timer later captured the stale source and flipped the state back.
- a second root.render() passed the one-shot guard that used to throw
  deterministically, appending a second tree onto the painted page.

Both now take the same fence every other gap reader takes:
ensureFirstScreenCaptured() before reading the state. In
markFirstScreenSyncReady the fence runs before firstScreenSyncReady
flips, so the capture's own announce attempt stays withheld and the
mark's announcement is the one that goes out, carrying the tree.

Two red-verified tests: a sync-ready mark in the gap must answer a
correlated ready request with firstTree, and a render in the gap must
take the one-shot refusal.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YHfFsy9CLaRovTFH8pTGyY
@Huxpro
Huxpro marked this pull request as ready for review September 2, 2026 11:02
@Huxpro
Huxpro merged commit b230f8a into new-lynx Sep 2, 2026
18 of 19 checks passed

Huxpro commented Sep 2, 2026

Copy link
Copy Markdown
Owner Author

pnpm test — the full suite promised in the body

Ran on 6fdb524a0, the branch head at the time. The merged head is 371942ccd, one commit further; there is a note on that at the end.

Test Files  4 failed | 2449 passed (2453)
     Tests  3 failed | 26870 passed | 3 skipped (26876)
  Duration  3252 s

Four red files, none of them in packages/lynx. This diff touches three files: packages/lynx/src/main-thread.ts, packages/lynx/tests/first-screen.test.ts, and .changeset/lynx-capture-after-paint.md.

Three are pre-existing, and the base run says so

I ran the four owning projects at the live base a1852691c, detached, with this diff absent:

Test Files  3 failed | 17 passed (20)
     Tests  3 failed | 148 passed (151)

Same three files, same tests, same lines as on the head:

file and line failure on the base with the diff absent
packages/octane/tests/browser/suspense-hydration/suspense-hydration.test.ts:256 restores focused input and its selected text after a keyed DOM reorder — expected [ +0, +0 ] to deeply equal [ 2, 9 ] red, identically
packages/drei/tests/browser/upstream-e2e.browser.test.ts:208 page.waitForFunction: Timeout 30000ms exceeded red, identically
packages/rspeedy-plugin-octane/tests/native-demo.test.ts:566 escalates cleanup for a detached descendant after its leader exits — stopProcessTree resolved false; the suite is macOS Lynx Explorer native demo red, identically

The same four projects at 1202d917e gave the same three (3 failed | 146 passed). The base counts 151 tests to that head's 149 because the base advance added tests to packages/rspeedy-plugin-octane/tests/plugin.test.ts — not because anything skipped.

The fourth is a hook that ran out of time before a test body did

packages/octane/tests/react-hosted/web3-island.test.ts failed at the suite level rather than on an assertion:

Error: Hook timed out in 10000ms.
 ❯ packages/octane/tests/react-hosted/web3-island.test.ts:78:1

Line 78 is the beforeAll that builds the rainbowkit hydration fixture through executeHydrationFixture. The log has it mid-Vite-build — 502 modules transformed, rendering chunks, computing gzip size — when the 10 s hook deadline expired, and Vitest recorded 2 tests | 2 skipped: no test body ran.

Alone on the same head:

Test Files  1 passed (1)
     Tests  2 passed (2)
  Duration  20.6 s

That is the one re-run I take, and only because the hook died during fixture build with nothing executed. It is a contention timeout, not a result.

monaco-editor-browser earns the same note pointing the other way: it was red in an earlier full run on 1202d917e and green in all three runs since — the head projects, the base projects, and this suite. Same class.

On the head that actually merged

371942ccd closes two gap readers this diff missed — markFirstScreenSyncReady settling a painted screen as skipped and announcing with no first tree, and a second root.render() slipping the one-shot guard. Both are real, and both are fixed there. Re-verified on that head:

  • --project lynx — 50 files / 823 tests, all pass
  • the deliberate-break matrix — 12/12 still red, with the engine arm never defers rising 10 → 12 as it picks up the two tests that commit added.

The body's targeted tests line reads 49 files / 780 tests, which was 1202d917e, before origin/new-lynx (#269–#272) was merged in. It is 50 / 821 on 6fdb524a0 and 50 / 823 on 371942ccd.


Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants