Skip to content

perf(compiler): lower conditional JSX returns to template control flow - #674

Merged
trueadm merged 3 commits into
mainfrom
perf/jsx-return-lowering
Aug 10, 2026
Merged

trueadm merged 3 commits into
mainfrom
perf/jsx-return-lowering

Conversation

@trueadm

@trueadm trueadm commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The compiler now lowers React-style conditional JSX returns — if (c) return <A/>; return <B/>;, early-exit chains, and ternary returns — to the same template control flow as @if/@else, in both dialects and both compile modes. Branch-selected output stops running through the de-opt descriptor renderer entirely. Follow-up to #670 (finding 4 of the same spa-navigation audit); a .tsrx function using plain returns had the exact same de-opt cost, so this is a dialect-neutral lowering, not .tsx special-casing.

Why

After #670, the spa-navigation .tsx twin still cost 2.4× the .tsrx twin: its recursive Node value-lowered to createScopedElement host descriptors with createScopedValue children — 4,099 createElement / 4,094 childSlot / 2,046 deoptItemBody / 1,023 hostElementBody calls per navigation that the directive dialect never makes.

Changes

  • lowerJsxReturnBranchComponents (compile.js), run in every compiler mode immediately after lowerNullishComponentExits in both the client and server entries, so SSR markers stay symmetric: restructures an admitted body into setup statements plus one directive-shaped render root, then the existing @{} pipeline compiles it — ifBlock, componentSlotVoid/Lite, autoMemo, warm plans and all.
  • Admission is deliberately conservative, and every rule exists because a full-suite failure proved it necessary:
    • named, non-async, capitalized module-level FunctionDeclarations only; use* names and lowercase helpers keep the callable value ABI;
    • every component-level return must be syntactic JSX, nullish, or a ternary of those, reachable only through if/else nesting (returns under loops/switch/try, or under an if that can also fall through, would duplicate statements across arms and re-slot hooks);
    • pairwise-distinct arm root types with at least one host root — React reconciles same-type roots at one position in place, and fragment arms key-match their children across branches (caught by the fragment-reconciliation conformance suite), while component-only arm sets (Animate ? <A/> : <B/> selectors) gain nothing and pay an SSR control range per level (caught by the visx SSR baseline);
    • no bare self-recursive arm roots — a return <Self/> chain compiles to per-level control-flow frames that overflow 1000-deep SSR trees the value path renders fine (caught by the Fizz conformance suite);
    • no hook calls in arm-bound content — a hook behind an early return keeps slot-keyed state on the component scope across branch flips; an arm scope is torn down with the arm (caught by the octane-evals conditional-note grader);
    • component arm roots must be module-level bindings (a body-local const {wrapper: MDXLayout} = … is a runtime-chosen value; caught by the mdx suite);
    • the module may reference the function only as a JSX tag, an export, or a bare memo(...)/lazy(...) argument.
  • bundler.js mirrors the decision via the exported hasLowerableJsxReturnBranches so cross-module void-output classification agrees with what each module compiled to.
  • work.mjs ceilings tightened: BOTH dialects now held at zero de-opt-renderer calls per navigation; ratios.json gains nav_teardown/nav_deep/nav_mount guards against solid (adapted from the now-superseded WIP: perf(teardown): single dom detach #615).
  • Test-harness fixes surfaced by this work: the shared server-fixture loader now preserves function-declaration hoisting for exported components (cross-referencing exports previously threw at eval); the visx committed server-HTML baseline is regenerated and gains a documented VISX_CAPTURE_SERVER_HTML regeneration path; one hydration assertion that pinned marker-comment bytes now asserts adoption by node identity plus comment-stripped content (markers are hydration's own claim-time bookkeeping).

Benchmarks (same machine as #670's numbers, node benchmarks/bench.mjs spa-navigation, medians in ms)

op jsx before #670 jsx after #670 jsx after this PR tsrx react solid
nav_deep 7.00 4.50 2.10 1.80 1.70 2.00
nav_teardown 3.70 0.90 0.60 0.60 0.80 0.60
nav_mount 3.90 4.10 1.60 1.40 1.10 1.50
nav_deep_6x 47.40 29.80 13.60 12.20 11.50 14.00

The .tsx twin now beats Solid on the full navigation. Deterministic counters: hostElementBody/deoptItemBody 1,023/2,046 → 0/0, childSlot 4,094 → 2, createElement 4,099 → 1,029, with Node's 2,046 arms on componentSlotVoid. The residual gap vs .tsrx (renderBlock 6,147 vs 5,119; createElement 1,029) is the single-return _frag wrapper ABI — the audit's finding 5, deliberately out of scope here.

Validation

  • pnpm test — 1,612 files / 17,269 tests pass (includes octane-prod, differential, conformance, all binding projects)
  • pnpm typecheck
  • pnpm format:files:check on changed files
  • targeted: new jsx-return-branches.test.ts (20 cases: recursion, early-exit chains, state retention across arm flips AND across null outputs, non-returning else paths, fragments, destructured props, memo wrapping, direct-call and use* controls, SSR adoption by node identity) — written and passing against the OLD value path first, so they pin semantics, not the implementation; spa-navigation full + quick runs with all semantic/work/ratio gates green.

Risk / follow-ups

  • Lowered components stop being directly callable as plain functions (they become void block bodies) — same contract as every @{} component; in-module direct calls are detected and reject lowering, cross-module direct calls of exported components were already unsupported in dev (HMR wrapper ABI).
  • Admission is intentionally narrow; shapes it declines (fragment arms, same-type arms, component-only selectors, hookful branches) keep exactly today's behavior. Widening any of these needs the corresponding conformance evidence first.
  • Follow-up (finding 5): give single-return .tsx components the block-body ABI instead of createElement(_frag$N, holes) — that is the remaining 1.2× renderBlock gap.

Provenance

  • An agent produced this diff (agent-authored)

🤖 Generated with Claude Code


Note

Medium Risk
Touches the core compile pipeline and client/server/hydration DOM shape for admitted components; risk is mitigated by conservative lowering rules and broad conformance/benchmark coverage, but wrong admission could change React reconciliation semantics.

Overview
Adds lowerJsxReturnBranchComponents in the Octane compiler (client and server, right after nullish-exit lowering) so React-style branch-selected JSX returns—if (c) return <A/>; return <B/>, early-exit chains, ternary returns—compile as @if/@else template control flow instead of the de-opt descriptor path when admission rules say the branches are remount-equivalent under React semantics.

Admission stays narrow: capitalized module-level components only; distinct arm root types with at least one host root; no fragment/same-type/self-recursive arms, hooks in arm-bound code, or non-JSX-only references (direct calls keep the value ABI). hasLowerableJsxReturnBranches is exported and wired in bundler.js so void-output classification matches compile-time lowering.

Benchmarks: spa-navigation README and work.mjs now expect zero hostElementBody/deoptItemBody on JSX navigation; ratios.json adds nav_teardown / nav_deep / nav_mount vs Solid. Tests: new jsx-return-branches fixture and suite; hydration checks adoption by node identity (not marker bytes); visx committed SSR HTML refreshed with a VISX_CAPTURE_SERVER_HTML regen hook.

Reviewed by Cursor Bugbot for commit 4288d22. Bugbot is set up for automated code reviews on this repo. Configure here.

if (c) return <A/>; return <B/>; (and ternary returns) now compile to the
same ifBlock arms as @if/@else in both dialects and both compile modes,
so branch-selected output stops running through the de-opt descriptor
renderer. Admission is conservative: capitalized module-level function
declarations whose component-level returns are all syntactic JSX/null
reachable through if/else only, pairwise-distinct arm root types with at
least one host root, no fragment arms, no self-recursive arm roots, no
hooks in arm-bound content, and no non-render module references. The
bundler mirrors the decision for cross-module void classification.

spa-navigation octane-jsx nav_deep 4.50 -> 2.10ms (now ahead of solid
2.00), nav_mount 4.10 -> 1.60, nav_deep_6x 29.80 -> 13.60; de-opt
counters hostElementBody/deoptItemBody 1023/2046 -> 0/0. work.mjs
ceilings tightened to hold both dialects at zero de-opt calls, and
ratios.json gains nav_teardown/nav_deep/nav_mount guards vs solid.

Co-Authored-By: Claude Fable 5 <[email protected]>
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent perf PR: performance work labels Aug 9, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Arm hook gate misses unstable hooks
    • Replaced the local isHookName predicate in containsHookCall with the shared isHookCalleeName function, which already handles unstable_/UNSTABLE_ prefixed hook names via HOOK_NAME_CONVENTION_RE.

Create PR

Or push these changes by commenting:

@cursor push 4b1180c1b9
Preview (4b1180c1b9)
diff --git a/packages/octane/src/compiler/compile.js b/packages/octane/src/compiler/compile.js
--- a/packages/octane/src/compiler/compile.js
+++ b/packages/octane/src/compiler/compile.js
@@ -23328,7 +23328,6 @@
  */
 function containsHookCall(node) {
 	const seen = new WeakSet();
-	const isHookName = (name) => name === 'use' || /^use[A-Z0-9_]/.test(name);
 	const walk = (value) => {
 		if (value == null || typeof value !== 'object') return false;
 		if (Array.isArray(value)) {
@@ -23345,12 +23344,12 @@
 			return false;
 		if (value.type === 'CallExpression') {
 			const callee = value.callee;
-			if (callee?.type === 'Identifier' && isHookName(callee.name)) return true;
+			if (callee?.type === 'Identifier' && isHookCalleeName(callee.name)) return true;
 			if (
 				callee?.type === 'MemberExpression' &&
 				callee.computed !== true &&
 				callee.property?.type === 'Identifier' &&
-				isHookName(callee.property.name)
+				isHookCalleeName(callee.property.name)
 			)
 				return true;
 		}

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit 68909d5. Configure here.

Comment thread packages/octane/src/compiler/compile.js Resolved
containsHookCall hand-rolled the use* pattern and missed unstable_use*/
UNSTABLE_use* hooks, so a component calling one behind an early return
could still lower and lose its slot state to the arm scope on a branch
flip. Use isHookCalleeName (HOOK_NAME_CONVENTION_RE) instead; regression
test pins component-scope state across flips for an unstable_use* hook.

Co-Authored-By: Claude Fable 5 <[email protected]>
@trueadm
trueadm marked this pull request as ready for review August 9, 2026 23:01
# Conflicts:
#	packages/octane/tests/_server-fixture.ts
@trueadm
trueadm merged commit 3d09348 into main Aug 10, 2026
34 checks passed
@trueadm
trueadm deleted the perf/jsx-return-lowering branch August 10, 2026 00:06
trueadm added a commit that referenced this pull request Oct 3, 2026
… samples

Two quick CI runs of the paired, ~20 ms harness and same-runner A/B runs
against the commits that set each guard decided every waiver:

- Passing, waiver removed: activity reports, ssr-workerd
  cold_spawn_to_first_byte, svg-dashboard pan_zoom, memo-wall
  parent_rerender_equal_A and octane-jsx mount, spa-navigation
  nav_teardown and nav_mount (no Octane change since #674 on one runner).
- Rebaselined: svg-dashboard icon_swap 1.2 -> 1.6, because #983's esbuild
  minification made React 15% faster while Octane stayed flat.
- Confirmed Octane regressions, waiver kept and pointed at the fix:
  js-framework-reorder rotateb (1.41x per click since #639), memo-wall
  one_change_B (1.5x) and ctx_through_wall_B (1.44x), and svg-dashboard
  tooltip_swarm (1.31x since #635).
- The rotateb note claimed React moves every survivor; it moves one. A new
  rotatef guard covers the LIS-vs-lastPlacedIndex differentiator (0.043x).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 3, 2026
The 1.2 ceiling came from a local 0.94x reading. On CI runners #674 itself
measures 1.15x and head 1.09-1.16x, so the ceiling left 3% of quick-mode
headroom; 1.35 keeps a margin while still catching per-node mount growth.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 3, 2026
…nd re-judge them (#1646)

* ci(bench): triage the weekly ratio-guard breaches so new ones show

The weekly Bench job (`bench.mjs --quick --ratios`) was red with 81 ratio
breaches, 4 suites that wrote no numbers and 4 harness gate failures, so a new
breach was invisible. Every item is now a fix or a rebaseline.

- Harness drift, fixed. Each harness had stopped producing numbers when runtime
  source it anchors on changed:
  - ssr-final-replay: a second suspended loop since 2026-09-29.
  - root-transactions/contracts: staged-DOM text and attribute journaling since
    2026-09-15.
  - signal-dom-bindings: a second native style Block allocation site since
    2026-09-23.
  - codegen-size: the server runtime's lazy streamed-signals chunk since
    2026-09-16.
  - recursive-context: counted a pure-call annotation and trailing newlines as
    output growth.
- Rebaselined, with numbers in each note: five cross-framework bundle-size
  ratios and the workerd script-size ratio. The absolute app and server-render
  budgets are now the ratchet. Lynx's no-worklet byte caps from 2026-08-17 are
  reset to measured + 32, with the background program pinned exactly.
- Fix pending, with dated waivers that expire 2026-10-24, each with an owner
  task:
  - three exact counters the revived harnesses exposed (one extra closure per
    ssrTry, 128 live text reads per 128 unchanged compiled updates, compiled
    output at 1.295x its source);
  - Lynx create ratios and the re-entrant transport gate;
  - superlinear hydrate boundary preparation;
  - Octane Three versus R3F size and frame dispatch;
  - two timing regressions near the timer floor;
  - ten quick-mode timing guards whose samples are noise-bound;
  - the scoped descriptor shape change.
- bench.mjs supports a guard `waiver` ({ reason, expires }). A waived breach
  prints and does not fail, and fails again once the date passes.
  HARNESS_FAILURE_ALLOWLIST now also covers a suite whose harness writes no
  numbers.

The budget breaches (57) clear when the budget reset lands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): pair and lengthen the timing samples behind waived ratio guards

Twelve timing guards breached in weekly quick runs without a verdict. Their
samples sat near Chromium's 100 µs clock or under two-sample noise, and each
target ran its whole block minutes after the other side of its guard.

- benchmarks/lib/paired.mjs: rotating per-round visit order and a ~20 ms
  sample calibration shared by the harnesses below.
- js-framework-reorder, memo-wall, svg-dashboard, spa-navigation: every
  target's page stays open in one browser and each sample round visits all
  targets; short ops repeat until a sample takes about 20 ms (clicks,
  hook invocations, op batches, and summed navigation legs).
- activity caught-reveal: a sample reveals several independent hidden roots
  in one window, with the small case revealing eight times as many roots so
  both cases do equal work; the cases alternate per round.
- ssr-workerd: an untimed priming spawn per target, then paired cold-spawn
  rounds; quick mode runs six rounds instead of two.
- bench.yml: a `suites` dispatch input to run selected suites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): collect garbage before every timed spa-navigation leg

The untimed return leg mounts a whole route, and its collection landed
inside the next timed teardown: nav_teardown samples ran at 17-45% rme.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): re-judge the twelve waived timing guards with paired samples

Two quick CI runs of the paired, ~20 ms harness and same-runner A/B runs
against the commits that set each guard decided every waiver:

- Passing, waiver removed: activity reports, ssr-workerd
  cold_spawn_to_first_byte, svg-dashboard pan_zoom, memo-wall
  parent_rerender_equal_A and octane-jsx mount, spa-navigation
  nav_teardown and nav_mount (no Octane change since #674 on one runner).
- Rebaselined: svg-dashboard icon_swap 1.2 -> 1.6, because #983's esbuild
  minification made React 15% faster while Octane stayed flat.
- Confirmed Octane regressions, waiver kept and pointed at the fix:
  js-framework-reorder rotateb (1.41x per click since #639), memo-wall
  one_change_B (1.5x) and ctx_through_wall_B (1.44x), and svg-dashboard
  tooltip_swarm (1.31x since #635).
- The rotateb note claimed React moves every survivor; it moves one. A new
  rotatef guard covers the LIS-vs-lastPlacedIndex differentiator (0.043x).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): rebaseline spa-navigation nav_mount to its CI baseline

The 1.2 ceiling came from a local 0.94x reading. On CI runners #674 itself
measures 1.15x and head 1.09-1.16x, so the ceiling left 3% of quick-mode
headroom; 1.35 keeps a margin while still catching per-node mount growth.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): drop the three weekly waivers that now have fix PRs

The waived guards now have owner PRs: ssr-final-replay try_closures (#1644),
root-transactions equal_reads (#1643) and codegen-size gzip compiled/source
(#1645). #1645 rebaselines the same codegen-size entry, so this branch no
longer edits it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): leave lynx-render to its owner fix

The lynx-render transport gate failure and the create_1k/create_10k ratio
breaches both trace to #885's JSON-encoded transport and now have an owner
fix. Its branch re-notes those two guards, so this branch drops their waivers
and the suite's allowlist entry instead of editing the same entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): keep harness failures unwaivable and leave descriptor shapes to their owner

Waiving a suite that throws before it writes numbers would hide any crash in
that suite, not only the known shape change, and skip all of its guards. The
scoped-descriptor-shapes defect has an owner fix in progress. That fix re-pins
the harness's expected keys, so narrowing the waiver here would edit the same
assertion. HARNESS_FAILURE_ALLOWLIST is empty again, and a thrown suite failure
always fails the job. Dated waivers remain only on individual ratio guards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): leave the Three guards to their owner fixes

three-renderer frame_1k_subscribers and the two three-bundle-size ratios have
owner PRs (#1651, #1652) that re-note and ratchet those entries, so this branch
drops their waivers instead of editing the same entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): point the four kept timing waivers at their attributed fixes

rotateb and ctx_through_wall_B clear with #1655 and #1656; one_change_B's
per-row remainder and tooltip_swarm's scoped-descriptor accessor reads each
have their own fix task.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): point parent_rerender_equal_A's note at its per-commit journal fix

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

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

agent-authored Diff or issue body substantially produced by an AI agent perf PR: performance work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant