Skip to content

fix(compiler): give each call to a module-local custom hook its own slots - #1546

Merged
trueadm merged 1 commit into
mainfrom
fix/plain-local-custom-hook-slots
Oct 2, 2026
Merged

trueadm merged 1 commit into
mainfrom
fix/plain-local-custom-hook-slots

Conversation

@trueadm

@trueadm trueadm commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

In a plain .ts/.js module, a custom hook that calls another hook declared in the same module now gives each call its own state, as a .tsrx module does.

// hooks.ts
function useCell(initial: string) { const [value] = useState(initial); return value; }
export function usePair(a: string, b: string) { return [useCell(a), useCell(b)]; }

Previously usePair('a', 'b') returned a,a on the client. The plain-module hook pass (slot-hooks.js, and plain-hook-memo.js for inline production memos) wrapped only imported custom-hook calls in withSlot. Both local calls therefore resolved their useState, useRef, useId and memo cells to one slot. The server's occurrence-indexed hook records kept them apart (a,b), so SSR→hydrate disagreed and hydration replaced the server output with mismatch diagnostics.

hook-deps.js now annotates a call to any hook-named binding the module declares (_octaneCustomHookCall). Both emitters already consume that annotation. This follows .tsrx's by-name rule while keeping the plain pass's lexical provenance:

Callee Boundary
function useX, const useX = …, hook-named parameter, const alias of one Added
Imported custom hook Unchanged (already wrapped)
Differently named helper, unbound global, optional call, useContext, type-only import None

Two guards come with the change:

  • Module-initialization calls stay unwrapped. The surgical pass appends its slot constants after the module body, so a use*() call evaluated while the module loads read them before initialization. That threw a ReferenceError for imported hooks before this change, and would now have hit local ones too.
  • Slotted custom-hook calls stay hook-shaped for the inline memo tier. After rewriting, withSlot(slot, hook, …) no longer looks like a hook call by name. isHookShapedCall now honors the copied annotation, so a useMemo factory that calls a custom hook keeps the runtime useMemo, as the inline tier's policy requires.

Existing collisions this fixes

18 of 1,868 plain package modules change output (.tsrx output is identical for all 1,268 package sources). At least two had live collisions:

  • @octanejs/mantine-hooks useFloatingWindow calls a local useRefValue four times, so every callback ref resolved to onDragEnd. A drag reported end, end, end, and enabled: false was ignored. A new test in that package covers it.
  • @octanejs/redux-toolkit buildHooks calls a local useShallowStableValue three times in one hook.

Validation

  • pnpm format:files:check on every changed file
  • pnpm format:check (repo-wide, not run)
  • pnpm typecheck (full chain not run). Ran the parts that cover this diff: tsgo -p packages/octane/tsconfig.json and both mantine-hooks configs are clean. pnpm typecheck:files reports nothing new on changed lines.
  • pnpm test (not run as one invocation). Ran octane + octane-prod in full, 36,061 tests. Every failure caused by this change was fixed. The remaining failures in behavior-root, hmr, hydration-ssr-diagnostics and volar are timeouts under machine load (load average 45–79). Their compiled output is byte-identical to main (no .tsrx test fixture changes output); hmr and hydration-ssr-diagnostics passed when run alone.
  • targeted tests:
    • New plain-hook-local-custom-hooks.test.ts: every binding kind called twice, dev and prod, surgical and inline emitters, SSR→hydrate (same nodes, no diagnostics, live updates), and module-initialization calls on client and server
    • New routing case in compiler/plain-hook-memo-codegen.test.ts
    • mantine-hooks drag/enabled test
    • All of these fail on main. Breaking each part of the fix on its own (local rule, alias rule, module-init guard, hook-shape check) fails its intended test.
    • Binding suites for apollo-client, base-ui (including the 338-file upstream-adapted suites), base-ui-utils, mantine-hooks, puck, redux, redux-toolkit, textarea-autosize, and the hosted React SSR projects all pass.
  • Performance: same plain module compiled by main and by this branch, a local 4-hook helper called once per render (pure overhead, no collision), 20,000 renders × 12 alternating rounds. The extra boundary costs +35 to +51 ns per render (2.6–3.9% of a render that does nothing else). That is the same boundary imported and .tsrx custom hooks already pay. The runtime is unchanged, so the hooks-runtime ratios are unaffected.

Updated existing tests

Five tests pinned the old "local calls are never wrapped" behavior:

  • conditional-effect-helpers.ts and activity-dom-insertion-helpers.ts relied on two local calls sharing one slot to exercise repeated enqueues through one effective slot. They now reach that state with a plain-module loop, which repeats one call site, so that runtime coverage is kept.
  • external-hook-slot, auto-hook-deps and plain-hook-import-alias drop their "not wrapped" assertions. Their real contracts are still asserted: the module's bytes are restored once slots are stripped, use() arguments are not memoized around hooks, plain-module wrapper calls get no inferred dependency arrays (as docs/differences-from-react.md documents), and shadowed or type-only imports gain no hook identity.

Risk / follow-ups

  • Every local custom-hook call in a plain module now pays one withSlot boundary, including calls that never collided.
  • Hook-named parameters and destructured values also get boundaries, matching .tsrx. Restricting this to declared functions would be a one-line change.
  • A module-scope hook-method call (export const v = store.useValue()) still hits the same TDZ through hook-methods.js. It predates this change and is filed as a separate task.
  • Signal declarations in a locally composed hook (signal$ or query$ inside a local hook called twice) still alias on main, because i: keys don't include custom-hook call sites. Separate in-progress work adds those sites to the _octaneCustomHookCall branches. With this change, local calls take those branches. Applied together locally, a locally composed signal$ hook keeps its cells per call through mount and hydration (a,b,c,d). Without this change it renders a,a,c,c.

Provenance

  • An agent produced this diff (agent-authored)

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.


Note

Medium Risk
Touches the plain-module hook transform used broadly (18 modules change output); behavior fix is correct but adds a withSlot boundary on every local custom-hook call, with compiler/runtime hydration alignment as the main concern.

Overview
Plain .ts/.js modules now give each call to a module-local custom hook its own hook slots, matching .tsrx behavior. The compiler annotates calls to hook-named bindings declared in the same module (functions, const hooks, parameters, aliases) with _octaneCustomHookCall, and the surgical slot-hooks / plain-hook-memo passes wrap those sites in withSlot—previously only imported custom hooks got that boundary, so repeated local calls shared useState, useRef, useId, and memo state on the client while SSR kept them separate, causing hydration mismatches.

Guards: hook calls at module initialization (outside any function) are not rewritten, avoiding ReferenceError from slot constants defined after the module body. isHookShapedCall treats annotated custom-hook boundaries as hook-shaped so useMemo factories that call local hooks still follow inline memo policy.

Tests: new plain-hook-local-custom-hooks.test.ts (independence, SSR→hydrate, module-scope calls); mantine-hooks drag/enabled coverage for useFloatingWindow’s local useRefValue; several compiler tests updated to expect withSlot around local hooks while still asserting wrappers don’t get inferred dependency arrays.

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

…lots

The plain `.ts`/`.js` hook pass wrapped only imported custom-hook calls in
`withSlot`. A hook calling another hook declared in the same module got no
boundary, so two calls shared their base-hook cells on the client: `useState`,
`useRef`, `useId` and memos collided. The server kept them apart by occurrence
index, so SSR rendered `a,b`, the client `a,a`, and hydration replaced the
server output.

`hook-deps.js` now annotates calls to any hook-named binding the module
declares, matching `.tsrx`'s by-name rule while keeping lexical provenance.
That covers functions, values, parameters, and `const` aliases of them.
Imports, unbound globals, optional calls, `useContext`, and differently named
helpers are unchanged. Both emitters already consume the annotation.

Two guards come with it. Calls evaluated while the module initializes stay
unwrapped: the trailing slot constants are not initialized yet, which already
threw a ReferenceError for imported hooks. The inline memo tier also treats a
slotted custom-hook call as hook-shaped, so a factory containing one keeps the
runtime `useMemo`.

This fixes collisions in existing bindings, including mantine-hooks
`useFloatingWindow` (every callback ref resolved to `onDragEnd`) and
redux-toolkit `buildHooks`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent fix PR: bug fix labels Oct 2, 2026
@trueadm
trueadm marked this pull request as ready for review October 2, 2026 08:27
@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark report

🟢 No size increases and no timing regressions outside noise.

Compares 5f354d23e with 643853711 on the same runner. Timing verdicts require a change beyond the combined margin of error (at least 5%) and one 0.1ms timer tick, with the fastest sample also moving beyond that margin. Workflow run

js-framework: 1k/10k row operations (ms, lower is better)

All 20 timed operations (20 within noise)
target operation base head Δ noise
octane-tsrx run 3.47 4.20 +21.0% ±73% ⚪ within noise
octane-tsrx replace 6.86 7.22 +5.2% ±11% ⚪ within noise
octane-tsrx add 3.54 3.57 +0.8% ±13% ⚪ within noise
octane-tsrx update 0.41 0.40 −2.4% ±71% ⚪ within noise
octane-tsrx select 0.18 0.14 −22.2% ±74% ⚪ within noise
octane-tsrx swap 0.34 0.38 +11.8% ±36% ⚪ within noise
octane-tsrx remove 0.32 0.31 −3.1% ±38% ⚪ within noise
octane-tsrx runlots 34.65 33.88 −2.2% ±17% ⚪ within noise
octane-tsrx select_lots 0.18 0.20 +11.1% ±75% ⚪ within noise
octane-tsrx clear 35.78 35.50 −0.8% ±15% ⚪ within noise
octane-jsx run 3.77 4.29 +13.8% ±32% ⚪ within noise
octane-jsx replace 7.58 7.82 +3.2% ±8% ⚪ within noise
octane-jsx add 3.33 3.50 +5.1% ±6% ⚪ within noise
octane-jsx update 0.53 0.56 +5.7% ±33% ⚪ within noise
octane-jsx select 0.39 0.38 −2.6% ±53% ⚪ within noise
octane-jsx swap 0.59 0.60 +1.7% ±25% ⚪ within noise
octane-jsx remove 0.54 0.50 −7.4% ±36% ⚪ within noise
octane-jsx runlots 31.41 33.17 +5.6% ±8% ⚪ within noise
octane-jsx select_lots 2.56 2.88 +12.5% ±27% ⚪ within noise
octane-jsx clear 33.09 37.14 +12.2% ±23% ⚪ within noise

Application bundle size (bytes)

No changes across 45 measured values.

Public-import reachability bundles (bytes)

No changes across 105 measured values.

CI job durations

  • 🟢 1 job(s) faster than every recent main run: React parity shard (4/4)

Compares the CI run for 64707dd82 (run) with the last 5 successful main push runs. A job is only slower or faster outside the whole main range, by at least 10% and 15s. Job time excludes runner setup.

job main median main range this PR Δ
wall clock (first job start to last job end) 13m 51s 12m 39s–17m 36s 12m 40s −1m 11s (−9%) ⚪ within noise
total job time 155m 53s 140m 36s–177m 43s 137m 33s −18m 20s (−12%) 🟢 faster
React parity shard (4/4) 11m 23s 10m 43s–13m 16s 10m 08s −1m 15s (−11%) 🟢 faster
All 26 timed jobs
job main median main range this PR Δ
example apps (2/3) 3m 43s 3m 38s–4m 40s 3m 53s +10s (+4%) ⚪ within noise
test (24) 3s 3s–4s 4s +1s (+33%) ⚪ within noise
classify changeset release 13s 13s–15s 13s ±0s (±0%) ⚪ within noise
typecheck 3s 3s–4s 3s ±0s (±0%) ⚪ within noise
examples 3s 3s–3s 3s ±0s (±0%) ⚪ within noise
lint 3s 3s–4s 3s ±0s (±0%) ⚪ within noise
CI provenance 3s 3s–4s 3s ±0s (±0%) ⚪ within noise
React parity checks 12s 11s–15s 11s −1s (−8%) ⚪ within noise
example apps (3/3) 3m 41s 3m 19s–4m 16s 3m 35s −6s (−3%) ⚪ within noise
Three compatibility 2m 56s 2m 38s–3m 48s 2m 49s −7s (−4%) ⚪ within noise
test shard (Node 24, 3/4) 10m 06s 9m 24s–11m 36s 9m 59s −7s (−1%) ⚪ within noise
Lynx compatibility 1m 38s 1m 32s–2m 07s 1m 29s −9s (−9%) ⚪ within noise
example apps (1/3) 3m 14s 3m 10s–4m 01s 3m 05s −9s (−5%) ⚪ within noise
heavy integration (package builds, eval corpus, runtime loaders, Astro) 5m 44s 5m 27s–6m 31s 5m 28s −16s (−5%) ⚪ within noise
React parity shard (1/4) 11m 04s 10m 51s–12m 30s 10m 42s −22s (−3%) ⚪ within noise
lint checks 8m 32s 7m 52s–10m 19s 8m 09s −23s (−4%) ⚪ within noise
validate publishable packages 4m 29s 3m 55s–5m 00s 4m 02s −27s (−10%) ⚪ within noise
test shard (Node 24, 2/4) 12m 22s 10m 38s–14m 29s 11m 52s −30s (−4%) ⚪ within noise
website integration suite 6m 21s 5m 46s–7m 00s 5m 47s −34s (−9%) ⚪ within noise
React parity shard (2/4) 10m 46s 9m 52s–11m 44s 10m 02s −44s (−7%) ⚪ within noise
test shard (Node 24, 4/4) 11m 19s 11m 03s–14m 12s 10m 24s −55s (−8%) ⚪ within noise
heavy integration (browser - chromium) 12m 43s 10m 58s–16m 52s 11m 42s −1m 01s (−8%) ⚪ within noise
React parity shard (4/4) 11m 23s 10m 43s–13m 16s 10m 08s −1m 15s (−11%) 🟢 faster
test shard (Node 24, 1/4) 12m 46s 10m 36s–13m 13s 11m 16s −1m 30s (−12%) ⚪ within noise
React parity shard (3/4) 11m 51s 10m 08s–12m 43s 10m 08s −1m 43s (−14%) ⚪ within noise
typecheck checks 8m 30s 1m 56s–11m 03s 2m 23s −6m 07s (−72%) ⚪ within noise

@trueadm
trueadm merged commit 985a81e into main Oct 2, 2026
52 checks passed
@trueadm
trueadm deleted the fix/plain-local-custom-hook-slots branch October 2, 2026 12:11
trueadm added a commit that referenced this pull request Oct 2, 2026
…nals

#1546 gave module-local custom-hook calls a withSlot boundary, but the plain
pass still walks only modules that import from `octane`. A `hooks.ts` that
imports `query$` from `octane/signals` and composes its own hooks
(`useUsers$` calling `useUser$` twice) therefore got no boundary, and both
calls shared one cell. A runtime signals import makes the module Octane's,
so its imported or declared `use*` hooks are now walked too. A module that
only declares signals is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 2, 2026
…1553)

* fix(octane): give each custom-hook call its own signal declarations

A `signal$`, `derived$` or `query$` declared inside a custom hook was keyed
only by its component instance and declaration site, so two calls of one
hook in one component aliased a single cell: `useUser$(a)`/`useUser$(b)`
rendered `X|X` and ran one loader.

Instance declarations now fold in the compiler-assigned call sites of the
enclosing custom-hook calls. Runtime hook-slot numbers follow module
evaluation order and differ between server and browser, while declaration
keys are wire identity for seeds, streamed results and early values, so
each signal-aware custom-hook call gets a position-hashed `h:` site
registered on its slot Symbol (tsrx, plain-module surgical and inline-memo
paths). Sites are emitted only for DOM targets, in modules with a runtime
signals import or for `$` hooks.

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

* fix(compiler): key aliased `$` hook calls the same way in every module kind

A `.tsrx` module checked only the local callee for a trailing `$`, while
plain modules checked only the imported name. `import { useUser$ as
useUser }` in a component module without a signals import therefore still
shared one cell across calls. All three emitters now register a call site
when either the local or the imported hook name ends in `$`; the `.tsrx`
path reads the exported name from the authored imports that its server
and client compiles share.

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

* test(octane): re-select only the changed call of a repeated query$ hook

Pins the combination with #1550: each custom-hook call owns its own query,
so a new captured argument re-selects that call's query and leaves the
other call's result in place.

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

* fix(compiler): bound hook calls in plain modules that import only signals

#1546 gave module-local custom-hook calls a withSlot boundary, but the plain
pass still walks only modules that import from `octane`. A `hooks.ts` that
imports `query$` from `octane/signals` and composes its own hooks
(`useUsers$` calling `useUser$` twice) therefore got no boundary, and both
calls shared one cell. A runtime signals import makes the module Octane's,
so its imported or declared `use*` hooks are now walked too. A module that
only declares signals is unchanged.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 2, 2026
…#1572)

* fix(compiler): leave hook methods called during module init unslotted

The plain .ts/.js hook pass wrapped every `obj.useX()` call in
`withSlot(_h$N, () => obj.useX())`, but declares its slot constants after
the module body to keep authored line numbers. A hook method evaluated
while the module initializes, e.g. `export const initial =
store.useValue()`, therefore threw `ReferenceError: Cannot access '_h$0'
before initialization`.

Such a call runs outside every render and needs no boundary. The scope
analysis now stamps `_octaneModuleInitCall` on a hook-method call with no
enclosing function (plain pass only; the full compiler declares its slots
before the body) and `hookMethodName` skips it, so the surgical and inline
emitters and optional-chain lowering all leave it authored. Static fields,
static blocks, computed keys and decorators of a module-level class run at
module init too. An instance field initializer runs with each
construction, possibly during render, so it gets an `initializer` scope
that keeps its boundary, as a constructor body does.

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

* chore(changeset): note instance-field boundaries for local custom hooks

The merge with #1546 shares the instance-field `initializer` scope with
its withinFunction, so a module-declared custom hook called from an
instance field also keeps its own slot.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 2, 2026
…FEs (#1574)

* fix(compiler): leave hook methods called during module init unslotted

The plain .ts/.js hook pass wrapped every `obj.useX()` call in
`withSlot(_h$N, () => obj.useX())`, but declares its slot constants after
the module body to keep authored line numbers. A hook method evaluated
while the module initializes, e.g. `export const initial =
store.useValue()`, therefore threw `ReferenceError: Cannot access '_h$0'
before initialization`.

Such a call runs outside every render and needs no boundary. The scope
analysis now stamps `_octaneModuleInitCall` on a hook-method call with no
enclosing function (plain pass only; the full compiler declares its slots
before the body) and `hookMethodName` skips it, so the surgical and inline
emitters and optional-chain lowering all leave it authored. Static fields,
static blocks, computed keys and decorators of a module-level class run at
module init too. An instance field initializer runs with each
construction, possibly during render, so it gets an `initializer` scope
that keeps its boundary, as a constructor body does.

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

* chore(changeset): note instance-field boundaries for local custom hooks

The merge with #1546 shares the instance-field `initializer` scope with
its withinFunction, so a module-declared custom hook called from an
instance field also keeps its own slot.

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

* fix(compiler): treat functions invoked in place at module init as module init

A module-scope IIFE runs during module initialization, but its body is a
function scope, so its hook-method and custom-hook calls still got a
withSlot(_h$N, ...) boundary and the module threw a TDZ ReferenceError on
load.

A call whose callee is an arrow or function expression (directly, through
TypeScript or paren wrappers, or via .call/.apply) now marks that
function's scope invokedInPlace, and withinFunction walks through it. An
IIFE inside a component or hook still has that function above it and keeps
its boundary. Generator bodies run on .next(), possibly during a render,
so they do not count.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 3, 2026
…owering (#1634)

Production builds of plain .ts/.js hook modules grew with #1546 (a withSlot
boundary per local custom-hook call) and #1577 (the inline memo tier admitted
~99% of modules). This trims both without changing behavior:

- hook-deps.js omits a module-declared hook's call boundary when the hook
  reads no slot (it calls nothing but useContext and other such hooks), or
  when it is the hook's only use, made directly by another local hook that is
  used only by name, outside any cycle of such calls. Signal-reading modules
  and `$` hooks keep every boundary.
- memoSlot receives the hook name only for an authored slot, which a manual
  hook may leave undefined; a compiler-appended slot always resolves.
- A plain-module memo dependency that is a never-reassigned local binding is
  read in place instead of through a temporary. Imports stay copied: they
  are live bindings the factory can change.
- The inline tier's admission and print move into createPlainProgramPrinter,
  and a corpus test reprints every Octane module in packages/*/src through it,
  comparing TypeScript syntax trees and requiring TypeScript and esbuild to
  parse the output, so an esrap gap fails CI instead of shipping to
  production only.

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 fix PR: bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant