Skip to content

perf(lynx): receiver diet — lazy worklet bridge, per-slice gzip gates ([lynx-perf 7]) - #15

Closed
Huxpro wants to merge 1 commit into
lynx/protocol-slimfrom
lynx/receiver-diet
Closed

Huxpro wants to merge 1 commit into
lynx/protocol-slimfrom
lynx/receiver-diet

Conversation

@Huxpro

@Huxpro Huxpro commented Aug 9, 2026

Copy link
Copy Markdown
Owner

Closes #8. Stacked on #14 ([lynx-perf 6], base lynx/protocol-slim), which stacks on #13 → #12 → #11 → #10 → #1.

Summary

  • Lazy worklet bridge: the main-thread receiver no longer imports the worklet registry or call bridges. main-renderer.ts's thread-function entry points — the modules compiled worklet output and useMainThreadRef actually import — provide a side-effect-free bridge slot (core/worklet-bridge.ts), and the receiver resolves it once per install. A production main-thread bundle that compiles no worklet features now sheds the entire registry/call-bridge machinery; worklet-addressed messages and host runWorklet dispatches arriving anyway report cleanly instead of resolving.
  • Per-slice gzip gates: benchmarks/lynx-bundle-size now emits frozen slice-budget-preview/slice-budget-ifr reference targets, and ratios.json gates preview-main, IFR-main, background, and whole-bundle gzip against them independently (1.03× headroom each).
  • The other two issue items were driven to measured verdicts rather than code: the diagnostics-string diet and the plan-materialization unification are reported with data below and deliberately not implemented.

Why

  • Issue [lynx-perf 7] Receiver diet: shrink the MT slice, spend it on FCP #8: the receiver's worklet machinery (~2k lines) was retained in every main-thread slice because main-thread.ts imported the registry statically — the rig table app uses zero worklets and paid for all of it. The registration mechanism (worklets.ts on the package sideEffects list, module-scope definition maps) makes the module un-shakable once edged, so the boundary has to be a provided slot, not an import.
  • A design constraint discovered on the way (and now documented in worklet-bridge.ts): a module-scope provide() can never be conditional under bundler sideEffects semantics — a side-effectful module is evaluated whenever any included module imports it, and a pure module containing the provide gets skipped by re-export tracing. The only reliable lazy boundary is a provide inside called functions that exist only in main-thread-only modules. That is why the wrappers live in main-renderer.ts and not in worklets.ts (which the background slice shares — putting the provide there would have dragged the main-thread registry into background bundles of worklet apps).

Changes

  • packages/lynx/src/core/worklet-bridge.ts (new): side-effect-free bridge slot — provideLynxMainThreadWorkletBridge (first provider wins) / installedLynxMainThreadWorkletBridge, bridging createRegistry, installRegistry, installCallBridge, isolateWorkletValue, isBackgroundFunctionDescriptor.
  • packages/lynx/src/main-renderer.ts: the seven thread-function re-exports become bridge-providing wrappers (registerThreadFunction, unregisterThreadFunction, bindThreadFunction, attachThreadFunction, invokeThreadFunction, runOnMainThread, runOnBackground), and useMainThreadRef provides before creating its descriptor — every entry point that can put a worklet feature in front of the receiver provides the bridge at module-evaluation/call time, which precedes the receiver's install in any statically bundled app. ensureLynxMainThreadWorkletBridge is exported for harnesses that hand-register through worklets.ts.
  • packages/lynx/src/main-thread.ts: drops all value imports from worklets.ts (type-only remain); resolves the bridge once per install; registry creation, registry/call-bridge installation, ref-owner publication, owner release, and close are all null-guarded; a call-main into a bridge-less receiver answers with a clean call-main-error ("compiled no main-thread worklets"), a host runWorklet dispatch reports and returns undefined; host hooks (runWorklet + the __FlushElementTree re-entrancy wrapper) stay installed unconditionally. The container option worklets is passed only when resolved (host-driver already models it as optional with a clean host error).
  • packages/lynx/src/first-screen.ts: runOnMainThread/runOnBackground re-export the wrappers; main-thread.ts's tail re-exports do the same. Layer identity contract updated in public-api.test.ts: the main-thread layer's runOn* pair is the one wrapper, distinct from the background layer's core implementation.
  • benchmarks/lynx-bundle-size/run.mjs: emits the two frozen slice-budget reference targets. benchmarks/baselines/ratios.json: four new guards with justifications.
  • Tests: new worklet-bridge-boundary.test.ts (see Validation); thread-calls/main-thread-events provide the bridge explicitly (they hand-register through worklets.ts, standing in for compiled output); runtime-compatibility source-graph inventory adds worklet-bridge.ts. Changeset: @octanejs/lynx patch.

Measured

Deterministic slice sizes (tasm decode + gzip -9, same instrument as the recorded baselines; baseline = #14 head e627ca59):

slice (gzip bytes) before after change
rig app main-thread 70,384 67,828 −2,556 (−3.6%)
rig app background 64,119 64,119 byte-identical
fixture preview main (receiver only) 64,266 61,893 −2,373
fixture IFR main (receiver + first screen) 68,570 65,942 −2,628
fixture IFR whole bundle 131,329 128,812 −2,517

The two issue items resolved by measurement instead of code:

  • Diagnostics-string diet: rejected. The prod main-thread slice carries 69 Octane … diagnostic strings, 10,153 raw bytes — but stripping all of them changes the slice by −234 bytes gzip (repetitive prose is nearly free under gzip, and gzip is the gate metric). The projected win was based on raw bytes. The related "self-audit" candidate — selfCheckLynxBackgroundInboundMessage on the receiver's own dispatch path — was already development-folded by [lynx-perf 5]'s validation diet; the prod slice contains zero validate/selfCheck occurrences.
  • Plan-materialization unification: assessed, not forced. main-renderer.ts's renderPlanNode is a live renderer (components, if/switch, slots, try/suspense, context) producing first-screen nodes; plan-wire.ts's expansion is a static command stamper for the wire. The genuinely shared surface is a few dozen lines of prop/text canonicalization — an expected win well under 1 KB gzip, bought with real regression risk in first-screen semantics. Not a good trade under this PR's no-behavior-change constraint; left as a named non-change.

FCP@10k (Lynx-for-Web, createView → first header text, fresh page per rep): interleaved A/B on the same host window — baseline medians 4,390/4,075/4,013 ms across three 2-rep rounds, after 4,128/4,109/4,945 ms. No resolvable delta; host noise (±900 ms between reps) dwarfs any parse effect of −2.5 KB. Reported as unchanged, not improved.

Web harness sanity (1 rep, 1k + 10k): octane completes every op with zero DNFs on this head.

Acceptance vs issue #8:

  • MT slice gzip −25% (~59 KB → ≤45 KB): not met — measured −3.6%, and this PR shows why the projection was wrong: the issue's composition analysis was made on unminified module shares, but production usedExports DCE had already dropped most of the projected mass, [lynx-perf 5/6] had already dev-folded the validation/handle machinery, and the two remaining projected levers measure at −234 B (strings) and <1 KB (unification). The realized, durable win is the worklet machinery no no-worklet app pays for again — enforced by gates and tests.
  • Whole rig-app bundle ≤80 KB: not met (128.8 KB fixture IFR); the ~102.8 KB anchor predates this stack's features and host toolchain. Both slices are now under frozen budget gates so any future growth is a red build.
  • FCP@10k in the ~800–900 ms band: not comparable — that band was recorded on the pre-migration 2.8 GHz host; this host measures ~4.1 s with ±900 ms noise. Before/after on the same host window shows no change (slope unchanged by construction: no per-row work was touched).
  • Every removal is a define or lazy boundary with a test: met (the one removal is the lazy bridge; both halves red-checked).
  • Bundle-shape gates updated with justifications, not deleted: met (four new absolute budgets added; the two existing relative gates untouched).

Validation

  • pnpm typecheck
  • scoped pnpm format:files across every changed file
  • targeted: packages/lynx/tests — 28 files / 306 tests green (includes the new suite)
  • pnpm test — full root run on this head: 1,558/1,577 files, 16,923 tests passed / 106 skipped; the 19 failing files diff empty against the perf(lynx): validation diet — dev-deep, prod-fast commit validation ([lynx-perf 5]) #13/perf(lynx): protocol slimming — derived ack handles, merged completion, empty-commit elision ([lynx-perf 6]) #14 baseline's pre-existing environmental set (Playwright-dependent browser suites, macOS-only rspeedy native demo, website SSR e2e) — zero new failures
  • node benchmarks/bench.mjs --only lynx-bundle-size --ratios → PASS (6 guards: 2 pre-existing relative + 4 new budgets)
  • node benchmarks/bench.mjs --only lynx-table --ratios --quick → PASS (14 guards; wire counters untouched)
  • Lynx-for-Web harness: zero DNFs at 1k and 10k
  • red-checked, each restored after going red: reintroducing a static worklets.ts value import in main-thread.ts → the no-worklet esbuild probe fails and both main_gzip budget gates breach (+2.3 KB); removing the runWorklet null guard and the call-main clean error → both behavioral no-bridge tests fail

New regression suite (worklet-bridge-boundary.test.ts):

  • esbuild + minify + tree-shaking probes over the real source graph: a no-worklet main-thread bundle contains none of the registry marker strings; adding registerThreadFunction usage or a useMainThreadRef import brings them back (markers chosen from code strictly behind the bridge, not from worklets.ts module scope, which every bundle still evaluates for the built-in ref-owner registrations).
  • behavioral: a receiver installed with no bridge applies ordinary commits (DOM asserted), answers call-main with the clean remote error, and reports a host-dispatched worklet instead of crashing.

Risk / follow-ups

  • The bridge slot is provided by usage, not by module presence. An app whose only worklet imports live behind a dynamic import() evaluated after installLynxMainThread would resolve no registry for that install (worklet props then fail with the existing "requires a main-thread worklet registry" host error). No supported Lynx main-thread build produces that shape — the MT slice is a single statically-evaluated script — and the failure is loud, not silent.
  • installLynxMainThread with a scripted executeMainThreadWorklet and no bridge no longer isolates the scripted result before dispatch (the host owns the shape there); real installs isolate exactly as before.
  • Double-install detection of the worklet registry now surfaces at bridge resolution inside install rather than at the old import-time call — same install call stack, same error.
  • The two measured non-changes (string diet, unification) are recorded in the issue; if a future pass wants the unification anyway, it should bring its own byte evidence.

Provenance

  • An agent produced this diff (agent-authored)

🤖 Generated with Claude Code

https://claude.ai/code/session_013br9KPN1riTSP683xEvUuU


Generated by Claude Code

…les via a lazy bridge

The main-thread receiver no longer imports the worklet registry and call
bridges. main-renderer's thread-function entry points — the modules compiled
worklet output and useMainThreadRef actually import — provide a bridge slot
the receiver resolves once per install, so a bundle that compiles no worklet
features retains none of the machinery (rig app main slice 70,384 -> 67,828
gzip). Worklet-addressed traffic arriving at a no-worklet bundle reports
cleanly. lynx-bundle-size now emits frozen per-slice gzip budgets and
ratios.json gates each slice against them.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013br9KPN1riTSP683xEvUuU
Huxpro added a commit to Huxpro/lynx-js-framework-benchmark that referenced this pull request Aug 9, 2026
…k tip

entries/octane now builds from Huxpro/octane#15 (lynx/receiver-diet 4a53620f,
octane 0.1.31, stacks lynx-perf 1→7) instead of the original wire-fix PR
branch. Full re-run supersedes every octane cell; latest.json verified in sync.

vs octane-main: select@10k 9.7x, selectStorm@10k 8.3x, update10th@10k 5.9x,
storms now 2-2.6x faster (the PR#1-era storm regression is gone), startup
~1.35x, wire select@10k 2.36MB -> 429B. Flag: BTS heap @10k rows measured
466MB vs main's 254MB — the one dimension moving the wrong way.
@Huxpro

Huxpro commented Aug 11, 2026

Copy link
Copy Markdown
Owner Author

Conclusion: close as failed by the live runtime gate. The worklet bridge reimplementation regressed selectStorm by 20.2 percent; a narrower genuinely-cold optional-worklet investigation continues in Huxpro/octane issue 44.

@Huxpro Huxpro closed this Aug 11, 2026
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.

1 participant