Repository navigation
perf(octane): cache derived values at their declaration - #297
Conversation
Lowers a derived `const X = <expr containing a render-time call>` to `useMemo(() => <expr>, [deps])` so its identity is stable while its inputs are. An idiomatic `const visible = todos.filter(...)` otherwise allocates a fresh array every render, and every consumer keyed on its identity — an autoMemo region's dependency tuple, a memo() child's prop — misses unconditionally. The region cache is only as good as the stability of what it keys on. Runs after Pass A' (use()-fed chains keep their Symbol-slot treatment) and before Pass A/B, so the minted numeric-slot useMemo is lowered by the authored inline tier (`_k$N`) rather than the Symbol/warm `puTake` path. Client only — a server render evaluates each body once, so a cache is pure overhead. Also broadens the hook naming convention used by creation eligibility from `^use[A-Z]` to `(^|_)use(?:$|[A-Z])`. A prefixed custom hook (`unstable_useRouterState`, mirroring React Router) previously read as an ordinary creation, so the pass wrapped a HOOK CALL in a cache and froze its subscription — caught by the remix-router guards/parity suites. Paired benchmarks vs this branch's base (js-framework is a control: its codegen is byte-identical with and without the pass, and it still moved +-8%, which calibrates the noise floor for the run): chat-stream switchConv 3.92ms -> 1.80ms (-54%) chat-stream streamCoarse 0.56ms -> 0.30ms (-46%) chat-stream streamFine 0.94ms -> 0.66ms (-30%) chat-stream type160 1.22ms -> 1.02ms (-16%) memo-wall parent_B 0.226ms -> 0.109ms (-52%) memo-wall ctx_wall_B 0.569ms -> 0.453ms (-20%) todomvc toggleAllOff 0.24ms -> 0.12ms (-50%) todomvc toggleAllOn 0.24ms -> 0.14ms (-42%) todomvc filterCycle 0.80ms -> 0.46ms (-42%) No op regresses by the repo's own compare rule (>1.15x score AND >1.10x min, plus >0.1ms absolute for sub-1ms ops). Full suite: 1338 files / 13072 tests. NOT READY: still needs the staleness contract documented, dedicated behavioral tests (including the frozen-hook regression), a bundle-size check for the added cells, and a decision on the region/calculation contract asymmetry. Co-Authored-By: Claude Opus 5 <[email protected]>
…calculation Follows the auto-calculation WIP with the pieces it was missing. **unstable_ is enumerated, not pattern-matched.** The WIP broadened hook detection to `(?:^|_)use(?:$|[A-Z])` to catch `unstable_useRouterState`, which is looser than the convention warrants — an ordinary helper could be mistaken for a hook by spelling alone. It is now `^(?:unstable_)?use(?:$|[A-Z])`: React's own staging prefix, which bindings mirror, and nothing else. The region rule's separate `^use[A-Z]` check is folded onto the same constant so both paths agree on what a hook is. Getting this wrong in the permissive direction is not a staleness bug — a cache wrapped around a hook call freezes its state cell and any subscription it owns, which is how the WIP froze @octanejs/remix-router's pending navigation at "(idle)". **Tests.** `auto-calculation.test.ts` covers identity stability across an unrelated re-render, rebuild on a real input change, correctness of a cached reduction and imported projection, both hook-declaration shapes staying live, `let` keeping its reassignment, and a handler-only calculation. Behavioral throughout, and run under both vitest projects so the runtime hook form and the inline flat-cache lowering must agree. Validated against broken implementations: dropping the `unstable_` prefix fails 1 test (the exact bug), removing hook detection entirely fails 2, and disabling the pass fails the 2 identity tests in both projects. The restored implementation passes. **Docs.** A new "Derived values are cached at their declaration" section in docs/differences-from-react.md states the pure-render contract, what is never cached, and — deliberately — that a hoisted `const s = header.getIsSorted()` is cached while the same call inline in a template is not, with the reasoning and the `let` escape hatch. **Size.** +0.25% gzip on the codegen-size corpus (25181 → 25243 bytes). Known, pre-existing: the `codegen-size` gzip ratio guard already breaches on this branch's base (1.07x vs a 1.04x ceiling, measured with the pass disabled and again on the base commit). This change moves it to 1.08x. The guard's recorded numbers no longer match the corpus, so it needs re-recording independently of this work. Full suite: 1369 files / 13680 tests. tsgo and format:check clean. 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 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Render-read scan over-nominates names
- Fixed by adding MemberExpression/Property handlers that skip non-binding positions (static property names and object keys), and by resetting inRenderTree to false when entering nested function bodies so event-handler-only identifiers are not seeded as render reads.
Or push these changes by commenting:
@cursor push bbb1fe8a07
Preview (bbb1fe8a07)
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
@@ -10774,7 +10774,12 @@
const inner = new Set(bound);
for (const param of n.params || []) collectPatternNames(param, inner);
collectScopeDeclaredNames(n.body, inner);
- walk(n.body, inner, inRenderTree);
+ // A nested function body is not a render read: event handlers and
+ // callbacks execute lazily, not during rendering. Reset inRenderTree
+ // so identifiers inside are not seeded. If the body contains JSX
+ // (e.g. a .map() callback returning elements), nextInRenderTree
+ // re-enters render-tree mode at the JSX boundary.
+ walk(n.body, inner, false);
return;
}
if (LOOP_TYPES.has(n.type)) {
@@ -10811,6 +10816,18 @@
walk(n.empty, bound, true);
return;
}
+ // Non-computed member access — `obj.prop`: the property is a static
+ // name, not a binding reference. Only the object is a render read.
+ if (seedRenderReads && n.type === 'MemberExpression' && !n.computed) {
+ walk(n.object, bound, inRenderTree);
+ return;
+ }
+ // Non-computed object-literal key — `{ key: value }`: the key is a
+ // static name. Only the value carries binding references.
+ if (seedRenderReads && n.type === 'Property' && !n.computed) {
+ walk(n.value, bound, inRenderTree);
+ return;
+ }
if (seedRenderReads && inRenderTree && n.type === 'Identifier' && !bound.has(n.name)) {
into.add(n.name);
}You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit fe0f933. Configure here.
… render-read scan Addresses the CI failure and the Bugbot finding on #297, and corrects measurement claims that did not survive checking. **CI: examples/pulseboard, virtualized list frozen mid-scroll.** The pass cached `const virtualItems = virtualizer.getVirtualItems()` on `[virtualizer]`, whose identity is stable while its window moves with scroll — the receiver hazard #262 vetoes for regions, in another costume. Calculations are now admitted on exactly that rule (plainCalleeIsMemoizable via containsRenderCall), so a member call fails closed whether or not the author named its result. One contract, both paths; the asymmetry section added to differences-from-react.md is removed because there is no longer an asymmetry to document. The cost is real and stated: `const visible = todos.filter(...)` is no longer cached. `todos` genuinely is an immutable snapshot, but this analysis cannot yet tell that from a live object, so it fails closed on both. Recovering it needs receiver provenance and is follow-up, not a bolt-on. **Bugbot (medium): render-read scan over-nominated names.** `seedRenderReads` treated every unbound Identifier in the JSX walk as a render consumer, including non-computed MemberExpression PROPERTIES (`row.length` nominated a local named `length`) and names read inside nested function bodies (handler-only locals). Both contradicted the documented "values the render tree never reads pay nothing". The walk now stops seeding inside function values — which run at invoke time, not while the template renders — and reads only the object side of a non-computed member expression. use()-argument seeding is unaffected: it still descends into function values, and a non-computed property is an Identifier by construction so it cannot hide a use() call. **Corrected measurements.** The previous body credited this change with chat-stream and todomvc wins. Both compile BYTE-IDENTICALLY with and without the pass — verified by diffing their output — so those numbers were run-to-run variance, not results. With the narrowed rule the attributable win is memo-wall alone: parent_rerender_equal_B 0.226ms -> 0.091ms (-60%) one_change_B 0.235ms -> 0.156ms (-34%) ctx_through_wall_B 0.569ms -> 0.413ms (-27%) todomvc, chat-stream and js-framework are now all byte-identical controls; their movement (up to +-100% on sub-millisecond ops) is this machine's noise floor. Size cost drops with the narrower rule: +0.07% gzip, was +0.25%. **Tests.** The identity fixture now uses an imported projection (the admitted shape). New `LiveReceiverCalculation` covers the pulseboard regression: a state-held object with stable identity whose method answer changes must re-read on every render. Re-admitting member calls fails it. examples/pulseboard e2e: 7/7 pass locally (CI had 1 failing). Full suite: 1376 files / 13717 tests. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Pushed CI: pulseboard's virtualized list froze mid-scroll
Calculations are now admitted on that same rule, so a member call fails closed whether or not the author named its result. One contract for both paths; the asymmetry section I'd added to The cost is stated rather than hidden: Bugbot: render-read scan over-nominated namesCorrect, and it contradicted a claim in my own docs. Fixed both halves:
Verified with a probe: a local named A correction to my own numbersWhile checking the above I verified which fixtures actually change codegen. The attributable win is memo-wall alone — the only fixture here whose output changes:
TestsAdded
Full suite: 1376 files / 13717 tests. format:check, tsgo, changeset check clean. |


Follow-on to #262. That change let autoMemo see through a call in a template; this one makes the values those regions key on actually stable.
The problem
A region cache is only as good as the stability of what it keys on. memo-wall's value-position wall rebuilt 1,000 descriptors through
buildValueRows(items)on every parent re-render — that call alone was 35% of the operation's CPU profile — so the region keyed onrowscould never hit.The change
A
constwhose initializer performs a call during render is lowered touseMemo(() => <init>, [deps])over the component locals it reads, and the existing authored inline-hook-memo tier lowers that to a numeric_k$Nflat cache. Nothing new was built: it reusesisPropCreationExprfor eligibility, Pass A′'s taint/shadowing and dependency-coarsening rules, and Tier A's cell layout. Dev and server keep the runtime hook form.Placement is deliberate: after Pass A′ so
use()-fed chains keep their Symbol-slot/warm treatment; before Pass A/B so the minteduseMemois lowered by the authored tier rather than re-wrapped; client only, since a server render evaluates each body once.A calculation is admitted on exactly the callee rule that governs regions, so the two agree. A member call is not cached even when its result is named. Also never cached: hook calls (including React's
unstable_use*prefix),letdeclarations (the escape hatch), and calculations the render tree never reads.Measurements
Paired runs, one machine, baseline recorded before any edit. memo-wall is the only suite that gains anything — it is the sole fixture here whose codegen changes:
parent_rerender_equal_Bone_change_Bctx_through_wall_BThat is the
createElement-descriptors-through-a-children-hole shape every@octanejs/*binding produces.todomvc,chat-streamandjs-frameworkcompile byte-identically with and without this change — I diffed the output to confirm — so they are reported as controls only. Their run-to-run movement, up to ±100% on sub-millisecond operations, is this machine's noise floor. Treat any small number in this area with suspicion; that is exactly how the first revision's claims went wrong.Size: +0.07% gzip on the
codegen-sizecorpus (was +0.25% before the rule narrowed).Reviewer notes
CI caught a real bug: a virtualized list froze mid-scroll.
examples/pulseboarddoesconst virtualItems = virtualizer.getVirtualItems(). The virtualizer's identity is stable while its window moves with scroll, so caching on[virtualizer]froze it —header.column.getIsSorted()in another costume. Aligning the calculation rule with #262's fixed it (7/7 pulseboard e2e pass locally; CI had 1 failing) and removed the asymmetry the first revision documented. There is now one contract for both paths.What that costs.
const visible = todos.filter(...)is no longer cached.todosgenuinely is an immutable snapshot, but the analysis cannot yet distinguish that from a live receiver, so it fails closed on both — which is why TodoMVC, the case that originally motivated this work, now gains nothing. Recovering it needs receiver provenance (does the root trace to a state binding?) and deserves its own change with its own evidence.Bugbot (medium), render-read scan over-nominated names — fixed. It treated every unbound identifier in the JSX walk as a render consumer, including non-computed member properties (
row.lengthnominated a local namedlength) and names read inside nested function bodies (handler-only locals). Both contradicted the documented "values the render tree never reads pay nothing". The walk now stops seeding inside function values and reads only the object side of a non-computed member expression;use()-argument seeding is unaffected.Residual risk. Hooks are identified by naming convention — the same signal React and React Compiler use — so a hook named outside that convention would be cached and frozen. Documented.
Known, pre-existing, not fixed here. The
codegen-sizegzip ratio guard already breaches on this branch's base (1.07x against a 1.04x ceiling), confirmed both with the pass disabled and against the base commit. Its recorded numbers no longer match the corpus, so it reads as stale; re-recording a CI gate deserves its own change. That guard runs on manual dispatch and a weekly cron, so it does not gate this PR.Tests
packages/octane/tests/auto-calculation.test.ts— behavioral, run under both vitest projects so the runtime hook form and the inline flat-cache lowering must agree. Covers identity stability across an unrelated re-render, rebuild on a real input change, cached-value correctness, both hook-declaration shapes staying live,letkeeping its reassignment, a handler-only calculation, and the live-receiver regression.Validated against deliberately broken implementations:
unstable_prefixVerification
main: 1376 files / 13717 tests passexamples/pulseboarde2e: 7/7pnpm format:check,tsgo --noEmit -p packages/octane/tsconfig.json, changeset check — clean🤖 Generated with Claude Code