Skip to content

perf(compiler): hoist capture-free hook callbacks to module scope - #337

Merged
trueadm merged 5 commits into
mainfrom
perf/hoist-capture-free-hook-callbacks
Jul 28, 2026
Merged

trueadm merged 5 commits into
mainfrom
perf/hoist-capture-free-hook-callbacks

Conversation

@trueadm

@trueadm trueadm commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Production compiles lift a capture-free function argument of a hook call to module scope, so the hook sees one identity for the module's lifetime instead of a fresh function every render.
  • Fixes free-variable analysis for a classic for (let i = 0; …) loop, whose declaration sits in the loop's init rather than its left.

Why

A function passed to a hook call site is reallocated on every render, so any hook that compares that argument sees a fresh identity and redoes work whose inputs never moved.

A store selector is the motivating case. useSelector(store, (s) => s.total) feeds a memo keyed on the selector's identity (the shape React's with-selector shim uses), and an inline arrow defeats it on every render — so an unrelated parent re-render re-runs the selection for every subscriber. React has the identical flaw, and it can't be fixed at the binding: the runtime can only skip the selector if it knows the closure's captured state is unchanged, and a fresh arrow with identical behaviour is indistinguishable from one whose capture moved. That information exists only at compile time.

Changes

  • hoistCaptureFreeHookCallbacks — a pass running after dependency inference (so materialised dep arrays are already in place). A callback is lifted only when nothing it references is declared by the enclosing top-level statement.
  • Deliberately conservative: the bound-name set over-approximates the component's declarations, so shadowing can only ever cost a lift, never produce a wrong one. Callbacks reading this/arguments, rendering JSX, or containing a hook call keep their authored position.
  • collectFreeIdentifiers now walks a binding pattern's default initialisers and computed keys. These are expressions evaluated at binding time, but only the names a pattern declared were being harvested — so (s, scale = props.factor) => … reported no reference to props and read as capture-free.
  • Excluded — hooks whose contract is stated in terms of the callback, where moving it changes observable behaviour rather than just an address: useCallback (returns the argument, owes a fresh identity when deps change), useMemo and the effect hooks (defined by how often the callback runs), useState/useReducer (once-only lazy initialiser), useEffectEvent (deliberately unstable wrapper). Custom use[A-Z] hooks and useSyncExternalStore — whose subscribe/getSnapshot are data it reads — take the lift.
  • Dev/HMR compiles keep the authored form, matching the inline hook-memo tier.
  • collectFreeIdentifiers now binds a classic for-loop's init declaration. Previously i was reported free and read as a capture of an enclosing binding the loop actually shadows, which made any callback containing a counting loop look instance-specific.

Validation

  • pnpm format:check
  • pnpm typecheck
  • pnpm test — 1428 files, 14,575 tests, 0 failures (two consecutive full runs; one intermediate run had a single deferred-hydration failure inside a vi.waitFor polling Vite's async module graph — a load timeout, passes 21/21 in isolation and green on the re-run)
  • targeted: hoist-capture-free-hook-callbacks.test.ts (codegen routing, 11 cases) + -behavior.test.ts (semantics, 3 cases), both across the octane and octane-prod projects

Every new test was watched failing first. Two caught real defects during self-review:

  • Multi-declarator statement — const A = …, B = … declares two components; a bound set built from only the first missed the second's locals and would have lifted a callback that reads them. The initial version of that test did not discriminate (both components used the param name props); renaming the second's param made it fail against the bug, and it now does.
  • useCallback identity — the first version of this pass broke returns a new function reference when deps change. That failure is what produced the exclusion list above, and is now pinned behaviorally.

Measurements

512 subscribers, 20 unrelated parent re-renders, store untouched; both arms verified to still react to a real store write.

selector calls / re-render wall clock
Authored form 512 28.7–32.6 ms
Lifted 0 9.5–11.8 ms

The call count is the durable claim — it is purely attributable to the lift. The wall-clock column compares dev and prod compiles, which differ in more than this pass, so it is not clean attribution. Holding the compile mode fixed and varying only selector identity, an expensive (2000-element) selector's re-render cost fell ~25% (62.6–64.1 ms → 46.5–47.4 ms, three runs, non-overlapping); with a cheap selector the difference stayed inside run-to-run noise. So this eliminates work at any selector cost, and converts to wall clock only when the selector does real work.

Compile-time cost: 120 real .tsrx fixtures, 5 runs, median 312.0–324.2 ms without the pass vs 316.6–321.7 ms with — fully overlapping, no measurable throughput regression.

Risk / follow-ups

  • Corrected during review: the over-approximation argument covers shadowing, but it did not cover pattern expressions, which the analysis could not see at all — that produced a genuinely unsafe lift (a callback moved to module scope while reading props from a parameter default). Found by Bugbot, reproduced, and fixed in the shared analysis in bfedb17; the gate was widened to production-only in the same commit. Both have regression tests verified failing against the pre-fix code.
  • Behaviour change to be aware of: a lifted callback is identity-stable across every instance of a component, not just across renders. For selectors that is the goal, but it is observable to code using a callback as a Map/WeakMap key or comparing it against a previously stored reference. Scoped to production compiles and hook call sites; React Compiler makes the same class of transform.
  • The collectFreeIdentifiers fix has ~20 callers (autoMemo captures, escape analysis, server-module isolation, parallel-use). It strictly reduces spurious free names, so callers become less conservative — the full suite is the gate on that.
  • No benchmark currently covers this. external-store-fanout uses raw useSyncExternalStore with no selector layer, so it would not show the win; external-store-integrations would. A selector fan-out suite plus a ratio guard is the natural follow-up, and should land before this optimization is treated as protected.
  • Capturing selectors ((s) => s.items[props.id]) still re-run. Dep-keyed memoization for those — reusing the inline hook-memo tier — is the next step.

🤖 Generated with Claude Code


Note

Medium Risk
Compiler transform changes production hook callback identity and broadens free-variable analysis used across the compiler; conservative gates and tests mitigate incorrect hoists.

Overview
Production compiles now lift capture-free function arguments on hook calls to module scope so hooks that key on callback identity (e.g. useSelector / with-selector-style memos) see a stable reference instead of a new arrow every render.

The new hoistCaptureFreeHookCallbacks pass runs after dependency inference, only when dev/HMR/profile are off. It skips callbacks that capture component bindings, use this/arguments, render JSX, or contain nested hook calls, and skips identity-owning hooks (useCallback, useMemo, effects, lazy useState/useReducer, useEffectEvent) while allowing lifts for useSyncExternalStore and custom use[A-Z] hooks.

collectFreeIdentifiers is extended to walk binding-pattern defaults/computed keys and to bind for (let i = 0; …) declarations in loop init, fixing false “capture-free” reads that could have made hoisting unsafe or declined valid lifts.

A store-selector-fanout benchmark (512 subscribers, 20 parent re-renders, store static) plus a 0.95× Octane-vs-React ratio on parent_rerenders and selectorCallsDuringRerenders metadata guard the optimization. Compiler and behavior tests cover hoist routing and semantics.

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

A function passed to a hook call site is reallocated every render, so a
hook that COMPARES it sees a fresh identity and redoes work whose inputs
never moved. A store selector is the motivating case: an inline arrow
defeats the identity-keyed memo it feeds, so an unrelated parent
re-render re-runs the selection for every subscriber.

A callback that captures nothing from the component cannot behave
differently between renders or instances, so production compiles lift it
to module scope and it keeps one identity for the module's lifetime.
Measured on 512 subscribers over 20 unrelated re-renders, selector
invocations fall from 512 per render to zero.

Hooks whose contract is stated in terms of the callback are excluded:
useCallback returns the argument and owes a fresh identity when deps
change, useMemo/effects are defined by how often it runs, useState takes
a once-only initialiser, and useEffectEvent deliberately hands back an
unstable wrapper. Custom use[A-Z] hooks and useSyncExternalStore take the
lift. Dev/HMR keeps the authored form, matching the inline hook-memo tier.

Also fixes free-variable analysis for a classic `for (let i = 0; …)`,
whose declaration sits in the loop's `init` rather than its `left`: `i`
was reported free and read as a capture of a binding the loop shadows,
which made any callback containing a counting loop look
instance-specific.

Co-Authored-By: Claude Opus 5 <[email protected]>
@vercel

vercel Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
octane-website Ready Ready Preview, Comment Jul 28, 2026 12:40pm
octane-website-mcp Ready Ready Preview, Comment Jul 28, 2026 12:40pm

Request Review

@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp July 28, 2026 11:38 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website July 28, 2026 11:38 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp July 28, 2026 11:41 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website July 28, 2026 11:42 Inactive

@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 2 potential issues.

Autofix Details

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Defaults missed as captures
    • Fixed collectFreeIdentifiers to walk function params (after collecting bindings into scope) so default initializers and computed destructuring keys are scanned for free variables, and to walk destructuring VariableDeclarator id patterns with a local scope copy containing the binding names.
  • ✅ Fixed: Hoist gate ignores dev profile
    • Moved the hoistCaptureFreeHookCallbacks call after devEnabled and profileEnabled are computed and extended its gate to !hmrEnabled && !devEnabled && !profileEnabled, matching the sibling autoMemo and inlineHookMemo tiers.

Create PR

Or push these changes by commenting:

@cursor push 391b5fe5f1
Preview (391b5fe5f1)
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
@@ -2691,6 +2691,9 @@
 			for (const p of n.params || []) collectBindings(p, newScope);
 			// `function name(){}` introduces its own name into the body scope too.
 			if (n.id) collectBindings(n.id, newScope);
+			// Walk params so default initializers and computed destructuring keys
+			// are scanned for free variables (collectBindings only extracts names).
+			for (const p of n.params || []) walk(p, newScope);
 			walk(n.body, newScope);
 			return;
 		}
@@ -2710,8 +2713,17 @@
 			return;
 		}
 
-		// VariableDeclarator's `id` is a binding, only walk the init.
+		// VariableDeclarator — the `id` pattern is a binding site, but
+		// default initializers and computed destructuring keys inside it are
+		// expressions that may reference free variables. For destructuring
+		// patterns, collect the binding names into a local scope copy first
+		// so they are not themselves reported as free.
 		if (t === 'VariableDeclarator') {
+			if (n.id && n.id.type !== 'Identifier') {
+				const patternScope = new Set(scope);
+				collectBindings(n.id, patternScope);
+				walk(n.id, patternScope);
+			}
 			walk(n.init, scope);
 			return;
 		}
@@ -5593,10 +5605,6 @@
 		);
 	}
 	const hmrEnabled = hmrDialect !== false;
-	// Runs AFTER dependency inference so materialised dep arrays are already in
-	// place: a lifted callback is module scope, which inference reads as
-	// non-reactive, and re-ordering the two would change what it infers.
-	ast = hoistCaptureFreeHookCallbacks(ast, { enabled: !hmrEnabled });
 	// Opt-in template-origin recording (`inspect: true`, client mode only): for
 	// every span baked into a hoisted template's HTML string (tag names, static
 	// attributes, static text), capture the authored source range that produced
@@ -5614,6 +5622,14 @@
 	// emits component/hook identity metadata but no hydration-warning expandos.
 	// Server compilation returns above, so profile metadata is client-only.
 	const profileEnabled = !!(options && options.profile);
+	// Runs AFTER dependency inference so materialised dep arrays are already in
+	// place: a lifted callback is module scope, which inference reads as
+	// non-reactive, and re-ordering the two would change what it infers.
+	// Production-only like the inline hook-memo and autoMemo tiers: dev/profile
+	// builds observe every entry at its authored site.
+	ast = hoistCaptureFreeHookCallbacks(ast, {
+		enabled: !hmrEnabled && !devEnabled && !profileEnabled,
+	});
 	// React-Compiler-style component-region and keyed-list caching. Always on for
 	// production client compilation — HMR can replace component contracts in
 	// place, and dev/profiling observe every entry, so those modes decline it.

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

Comment thread packages/octane/src/compiler/compile.js Resolved
Comment thread packages/octane/src/compiler/compile.js Resolved
…on prod

Addresses two review findings on the capture-free callback lift.

A binding pattern's default initialisers and computed keys are
expressions evaluated at binding time, but collectFreeIdentifiers only
harvested the NAMES a pattern declares and never walked those positions.
So `(s, scale = props.factor) => …` and `({ [props.field]: picked }) => …`
reported no reference to `props` at all and read as capture-free — the
lift then moved them to module scope where the name does not resolve.
This was an unsafe lift, not a missed one, and it invalidated the claim
that the over-approximation can only ever cost a lift. Pattern
expressions are now walked for function params, variable declarators,
and catch params, so the analysis is correct for every caller.

The lift was also gated on `!hmrEnabled` alone while its own comment,
the changeset, and the neighbouring inline hook-memo tier all describe a
production-only gate, so dev and profile builds with HMR off were still
lifting. It now uses the same `!hmrEnabled && !devEnabled &&
!profileEnabled` gate, which required moving the call below those flags.

Co-Authored-By: Claude Opus 5 <[email protected]>
@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp July 28, 2026 12:01 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website July 28, 2026 12:02 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp July 28, 2026 12:28 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website July 28, 2026 12:28 Inactive

@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 2 potential issues.

Fix All in Cursor

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Unsafe hoist on for-in assignment
    • Replaced collectBindings with walk on the non-declaration left-hand side of ForInStatement/ForOfStatement in collectFreeIdentifiers, so assignment targets are reported as free identifiers rather than being hidden as local bindings.
  • ✅ Fixed: Missed JSX for-item bindings
    • Added collection of the bare left pattern (non-VariableDeclaration) in the JSXForExpression branch of collectSubtreeBindings, so the for-item name is included in componentBound and prevents unsafe hoisting of callbacks that capture it.

Create PR

Preview
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
@@ -2774,7 +2774,10 @@ function collectFreeIdentifiers(root, initiallyBound, ignoreNodes = null) {
 			if (n.left && n.left.type === 'VariableDeclaration') {
 				for (const d of n.left.declarations || []) collectBindings(d.id, newScope);
 			} else if (n.left) {
-				collectBindings(n.left, newScope);
+				// Non-declaration left is an assignment target (e.g. `for (x of y)`),
+				// not a fresh binding. Walk it as an expression so the name surfaces
+				// as free rather than hiding an outer capture.
+				walk(n.left, newScope);
 			}
 			// A CLASSIC for carries its declaration in `init`, not `left`, and that
 			// binding is visible to the test/update/body. Without this, `i` in

@@ -2774,7 +2774,10 @@ function collectFreeIdentifiers(root, initiallyBound, ignoreNodes = null) {
 			if (n.left && n.left.type === 'VariableDeclaration') {
 				for (const d of n.left.declarations || []) collectBindings(d.id, newScope);
 			} else if (n.left) {
-				collectBindings(n.left, newScope);
+				// Non-declaration left is an assignment target (e.g. `for (x of y)`),
+				// not a fresh binding. Walk it as an expression so the name surfaces
+				// as free rather than hiding an outer capture.
+				walk(n.left, newScope);
 			}
 			// A CLASSIC for carries its declaration in `init`, not `left`, and that
 			// binding is visible to the test/update/body. Without this, `i` in
@@ -2876,6 +2879,9 @@ function collectSubtreeBindings(root, out) {
 		} else if (t === 'CatchClause') {
 			if (n.param) collectBindings(n.param, out);
 		} else if (t === 'JSXForExpression') {
+			if (n.left && n.left.type !== 'VariableDeclaration') {
+				collectBindings(n.left, out);
+			}
 			if (n.index) collectBindings(n.index, out);
 		}
 		for (const key in n) {

@@ -2876,6 +2879,9 @@ function collectSubtreeBindings(root, out) {
 		} else if (t === 'CatchClause') {
 			if (n.param) collectBindings(n.param, out);
 		} else if (t === 'JSXForExpression') {
+			if (n.left && n.left.type !== 'VariableDeclaration') {
+				collectBindings(n.left, out);
+			}
 			if (n.index) collectBindings(n.index, out);
 		}
 		for (const key in n) {

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

Reviewed by Cursor Bugbot for commit 00a9799. Configure here.

Comment thread packages/octane/src/compiler/compile.js Resolved
Comment thread packages/octane/src/compiler/compile.js Resolved
512 subscribers read one external store through a `with-selector`-shaped
selector, then the parent re-renders 20 times with the store untouched —
the workload a stable selector identity is supposed to make free. No
existing suite could see it: `external-store-fanout` uses a raw
`useSyncExternalStore` with an inline snapshot getter and has no selector
layer, and `external-store-integrations` measures Zustand/Jotai/TanStack
Query backends rather than isolating selector cost.

The suite reuses the news per-target toolchains with its own page rather
than extending the runtime-stress harness, whose shared App always renders
512 controlled form fields — those would have swamped the selection cost
and perturbed nine existing suites' baselines.

`selectorCallsDuringRerenders` is the deterministic signal, and it is read
next to `subscriberRendersDuringRerenders` and
`snapshotCallsDuringRerenders`: on a render-pass framework those stay at
512 x 20, so zero selector calls means the selection was reused, not that
the renders were skipped. Real Chromium gates every subscriber's total
after each broad write and again after the burst, plus a second write
afterwards and exact subscription teardown.

Co-authored-by: Claude Opus 5 <[email protected]>
@trueadm
trueadm merged commit 59a95d6 into main Jul 28, 2026
12 checks passed
@trueadm
trueadm deleted the perf/hoist-capture-free-hook-callbacks branch July 28, 2026 12:38
@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp July 28, 2026 12:39 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website July 28, 2026 12:40 Inactive

This branch was previously deployed

2 inactive deployments
Preview – octane-website — 1e960c5b Deployed Jul 28, 2026 by vercel[bot]
Preview – octane-website-mcp — 1e960c5b Deployed Jul 28, 2026 by vercel[bot]
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.

1 participant