Skip to content

perf(octane): cache derived values at their declaration - #297

Merged
trueadm merged 3 commits into
mainfrom
worktree-calc-memo-polish
Jul 27, 2026
Merged

trueadm merged 3 commits into
mainfrom
worktree-calc-memo-polish

Conversation

@trueadm

@trueadm trueadm commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

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.

Updated after CI + review. The first revision of this PR credited the change with chat-stream and TodoMVC wins. Both compile byte-identically with and without the pass, so those numbers were run-to-run variance, not results — corrected below. It also broke a virtualized list in examples/pulseboard, which forced the callee rule to be aligned with #262's. Details in the reviewer notes.

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 on rows could never hit.

The change

A const whose initializer performs a call during render is lowered to useMemo(() => <init>, [deps]) over the component locals it reads, and the existing authored inline-hook-memo tier lowers that to a numeric _k$N flat cache. Nothing new was built: it reuses isPropCreationExpr for 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 minted useMemo is 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), let declarations (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:

suite op base cand Δ
memo-wall parent_rerender_equal_B 0.226ms 0.091ms −60%
memo-wall one_change_B 0.235ms 0.156ms −34%
memo-wall ctx_through_wall_B 0.569ms 0.413ms −27%

That is the createElement-descriptors-through-a-children-hole shape every @octanejs/* binding produces.

todomvc, chat-stream and js-framework compile 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-size corpus (was +0.25% before the rule narrowed).

Reviewer notes

CI caught a real bug: a virtualized list froze mid-scroll. examples/pulseboard does const 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. todos genuinely 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.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 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-size gzip 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, let keeping its reassignment, a handler-only calculation, and the live-receiver regression.

Validated against deliberately broken implementations:

broken implementation result
re-admit member calls (the pulseboard bug) live-receiver test fails
drop the unstable_ prefix hook test fails
remove hook detection entirely 2 fail
disable the pass identity tests fail, both projects
restored implementation all pass

Verification

  • Full suite on current main: 1376 files / 13717 tests pass
  • examples/pulseboard e2e: 7/7
  • pnpm format:check, tsgo --noEmit -p packages/octane/tsconfig.json, changeset check — clean

🤖 Generated with Claude Code

trueadm and others added 2 commits July 27, 2026 00:30
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]>
@vercel

vercel Bot commented Jul 26, 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 27, 2026 12:22am
octane-website-mcp Ready Ready Preview, Comment Jul 27, 2026 12:22am

Request Review

@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp July 26, 2026 23:37 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website July 26, 2026 23:37 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 1 potential issue.

Fix All in Cursor

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.

Create PR

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.

Comment thread packages/octane/src/compiler/compile.js Resolved
… 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]>
@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp July 27, 2026 00:21 Inactive
@trueadm

trueadm commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 1517aece. CI failure and the Bugbot finding are both fixed — and checking them turned up a measurement error of my own, so the PR body has been corrected.

CI: pulseboard's virtualized list froze mid-scroll

examples/pulseboard does const virtualItems = virtualizer.getVirtualItems(). The virtualizer's identity is stable while its window moves with scroll, so caching on [virtualizer] froze the list — header.column.getIsSorted() in another costume, i.e. exactly the receiver hazard #262 vetoes for regions.

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 differences-from-react.md is gone because there is no longer an asymmetry. 7/7 pulseboard e2e pass locally.

The cost is stated rather than hidden: const visible = todos.filter(...) is no longer cached. todos genuinely is an immutable snapshot, but the analysis can't yet distinguish that from a live receiver, so it fails closed on both — which means TodoMVC, the case that motivated this work, now gains nothing from it. Recovering it needs receiver provenance and deserves its own change.

Bugbot: render-read scan over-nominated names

Correct, and it contradicted a claim in my own docs. Fixed both halves:

  • Member properties — row.length nominated a local named length. The walk now reads only the object side of a non-computed member expression. Safe for use() seeding too: a non-computed property is an Identifier by construction, so it can't hide a use() call.
  • Nested function bodies — handler-only locals were nominated. Seeding now stops at function values, which run at invoke time rather than while the template renders. use()-argument seeding still descends, since a use() inside a render prop is a real suspension point.

Verified with a probe: a local named length beside {rows.length} and a handler-only local are both left alone; a template-read control is still cached.

A correction to my own numbers

While checking the above I verified which fixtures actually change codegen. chat-stream and todomvc compile byte-identically with and without this pass. The −54% / −46% / −50% figures the first revision credited to this change were run-to-run variance.

The attributable win is memo-wall alone — the only fixture here whose output changes:

op base cand Δ
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 byte-identical controls. Their movement — up to ±100% on sub-millisecond ops — is this machine's noise floor, which is what let the bad numbers through the first time. Size cost also dropped with the narrower rule: +0.07% gzip, was +0.25%.

Tests

Added LiveReceiverCalculation for the pulseboard regression — a state-held object with stable identity whose method answer changes must be re-read every render. Re-admitting member calls fails it. The identity fixture switched to an imported projection, since that's now the admitted shape.

broken implementation result
re-admit member calls (the pulseboard bug) live-receiver test fails
drop the unstable_ prefix hook test fails
remove hook detection entirely 2 fail
disable the pass identity tests fail, both projects
restored all pass

Full suite: 1376 files / 13717 tests. format:check, tsgo, changeset check clean.

@vercel
vercel Bot temporarily deployed to Preview – octane-website July 27, 2026 00:22 Inactive
@trueadm
trueadm merged commit bd31a2d into main Jul 27, 2026
28 checks passed
@trueadm
trueadm deleted the worktree-calc-memo-polish branch July 27, 2026 00:28

This branch was previously deployed

2 inactive deployments
Preview – octane-website — 1517aece Deployed Jul 27, 2026 by vercel[bot]
Preview – octane-website-mcp — 1517aece Deployed Jul 27, 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