Repository navigation
perf(compiler): hoist capture-free hook callbacks to module scope - #337
Merged
Merged
Conversation
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]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
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.
- Moved the hoistCaptureFreeHookCallbacks call after devEnabled and profileEnabled are computed and extended its gate to
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.
…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]>
7 tasks done
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
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.
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.
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]>
This was referenced Jul 28, 2026
2 of 5 tasks
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Summary
for (let i = 0; …)loop, whose declaration sits in the loop'sinitrather than itsleft.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'swith-selectorshim 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.this/arguments, rendering JSX, or containing a hook call keep their authored position.collectFreeIdentifiersnow 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 topropsand read as capture-free.useCallback(returns the argument, owes a fresh identity when deps change),useMemoand the effect hooks (defined by how often the callback runs),useState/useReducer(once-only lazy initialiser),useEffectEvent(deliberately unstable wrapper). Customuse[A-Z]hooks anduseSyncExternalStore— whosesubscribe/getSnapshotare data it reads — take the lift.collectFreeIdentifiersnow binds a classic for-loop'sinitdeclaration. Previouslyiwas 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:checkpnpm typecheckpnpm test— 1428 files, 14,575 tests, 0 failures (two consecutive full runs; one intermediate run had a singledeferred-hydrationfailure inside avi.waitForpolling Vite's async module graph — a load timeout, passes 21/21 in isolation and green on the re-run)hoist-capture-free-hook-callbacks.test.ts(codegen routing, 11 cases) +-behavior.test.ts(semantics, 3 cases), both across theoctaneandoctane-prodprojectsEvery new test was watched failing first. Two caught real defects during self-review:
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 nameprops); renaming the second's param made it fail against the bug, and it now does.useCallbackidentity — the first version of this pass brokereturns 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.
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
.tsrxfixtures, 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
propsfrom 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.Map/WeakMapkey or comparing it against a previously stored reference. Scoped to production compiles and hook call sites; React Compiler makes the same class of transform.collectFreeIdentifiersfix 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.external-store-fanoutuses rawuseSyncExternalStorewith no selector layer, so it would not show the win;external-store-integrationswould. A selector fan-out suite plus a ratio guard is the natural follow-up, and should land before this optimization is treated as protected.(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
hoistCaptureFreeHookCallbackspass runs after dependency inference, only when dev/HMR/profile are off. It skips callbacks that capture component bindings, usethis/arguments, render JSX, or contain nested hook calls, and skips identity-owning hooks (useCallback,useMemo, effects, lazyuseState/useReducer,useEffectEvent) while allowing lifts foruseSyncExternalStoreand customuse[A-Z]hooks.collectFreeIdentifiersis extended to walk binding-pattern defaults/computed keys and to bindfor (let i = 0; …)declarations in loopinit, fixing false “capture-free” reads that could have made hoisting unsafe or declined valid lifts.A
store-selector-fanoutbenchmark (512 subscribers, 20 parent re-renders, store static) plus a 0.95× Octane-vs-React ratio onparent_rerendersandselectorCallsDuringRerendersmetadata 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.