Skip to content

fix(signals): keep a local derived$ or query$ whose captured values are unchanged - #1635

Merged
trueadm merged 2 commits into
mainfrom
fix/local-derived-deps
Oct 3, 2026
Merged

trueadm merged 2 commits into
mainfrom
fix/local-derived-deps

Conversation

@trueadm

@trueadm trueadm commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes D2 (P2) and D5 (P3) from the 2026-10-02 review of #1476–#1611.

D2: a component-local derived$/query$ re-ran its closure on every render (since #1550).

  • RedeclarableBinding.redeclare only short-circuited when the closure was the same object, and the compiler emits a fresh closure on every render.
  • So an object result from a local derived$ changed identity on equal-prop renders. Effects with [value] deps and memoized children re-ran on every parent render.
  • Every redeclaring render also allocated a declaration stage, a staged record and its closures.
  • Repro: four renders with equal props ran the closure 4 times and the [value] effect 3 times.

How it works now:

  • The compiler lists the render values each local declaration's closures capture, using the same inference as hooks with an omitted dependency array: __derivedAt(site, compute, options, [props.v]) and __queryAt(site, select, load, options, [props.id]).
  • redeclare stores the accepted list. When every entry is Object.is-equal, it returns the committed node before opening a stage. The closure does not run and no stage is allocated.
  • Changed values, or a call compiled without a list, take the old path unchanged.

D5: custom-hook declaration paths.

  • Path segments were joined with '/', so an explicit key such as 'user/h:…' declared directly in a component shared a cell with key 'user' declared through that hook. They are now joined with NUL.
  • The path is now cached per hook-call stack instead of being rebuilt for every declaration on every render.

Changes

Compiler (signal-declarations.js, shared by the full printer and the plain-.ts surgical pass):

  • Emits the captures list for instance (i:) declarations only. Module-scope declarations never redeclare.
  • Client and server output have the same shape.
  • Method-call captures go through __methodDep, now re-exported from octane/signals.
  • A local signal$ with no key or a literal key always names the same cell, so it is left out of the list. Without this, derived$(() => count$.get() * 2) would never take the fast path.
  • A signal$ with a dynamic key stays in the list.

Shared cells:

  • Two declarations can share one cell: a duplicate explicit key, or a hook called twice from a module compiled without hook sites, which docs/signals.md documents.
  • A plain fast path let that cell switch closures, and for query$ its selection, on every render.
  • The native-read driver now numbers each render invocation, with no allocation, so the first declaration in a render keeps winning.
  • The declaration that creates a cell also counts as its render's first. Main showed the second declaration at mount and the first afterwards.
  • The server read driver numbers each body scope the same way, so SSR also presents the first declaration. On main, server rendering of a shared cell threw because the second declaration changed the cell's revision mid-render.

HMR:

  • With equal captured values, the fast path would have kept the old closure after a hot update.
  • HMR client compiles now append a per-module revision token to each list. This matches how HMR already resets hook deps.

Captures declared later in the function:

  • Reading the list at the call would throw a ReferenceError for a closure that captures a let, const or class declared after it.
  • Such declarations get no list and take the old path. This uses a new evaluatedAt option on analyzeCallbackDependencies.

Docs: docs/signals.md documents the new contract and its limits. A declaration that captures another local derived$/query$ handle, or a handle passed as a prop, still reevaluates on every render, because those handles are new objects each render.

Rebased onto #1620. The conflicts in redeclaration.ts and engine.ts were resolved by keeping both sides, and #1620's suites pass on this head.

Validation

  • pnpm format:check (scoped pnpm format:files:check on the changed files: clean)
  • pnpm typecheck (scoped pnpm typecheck:files on the changed files and the fixtures they import: clean)
  • pnpm test (not run locally; left to CI)
  • targeted tests on the rebased head:
    • octane: signal-local-selectors, hydration/signal-local-selectors, compiler/signal-declarations, hmr, suspense-parent-render-query (client + hydration).
    • octane-prod (prod and strong): the same files except compiler/signal-declarations.
    • octane-signals, -prod and -strong: signals-hook-declarations, signals-local, signals-rendering, signals-unified.
  • Each new test was seen failing against the broken implementation it guards. The checks:
    • Fast path disabled: the equal-captures and plain-hook tests fail.
    • Separator back to /: the D5 test renders direct|direct.
    • A dynamic-key signal$ wrongly treated as stable: the keyed-signal test fails.
    • Naive fast path without the invocation serial: the shared-key test fails.
    • No HMR revision token: the HMR test shows a before.
    • No guard for later-declared captures: that test throws ReferenceError.
  • pnpm sync: no generated changes.

Size, measured deterministically with esbuild + gzip (no timing benches were run):

  • Apps without signals: byte-identical.
  • The signals declare path: about +430 B minified / +184 B gzip.
  • The custom-hook path cache: +68 B gzip, only for apps with signal-aware custom hooks.
  • Compiled output: about +20 B minified per local declaration.

Risk / follow-ups

  • Captured handles: a declaration whose closure captures another local derived$/query$ handle reevaluates as before. Comparing handles by the cell they present would extend the fast path to those chains.
  • Mount behavior with shared cells: when two declarations share a cell, the creating declaration now wins at mount too. Main showed the second one at mount.
  • Pre-existing bug, not fixed here: in .tsrx, the native-read compiler memo around a declaration reads a later-declared const early. That is being handled separately.

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
Changes compiler output and core signal redeclaration/SSR identity paths; behavior is nuanced (shared keys, HMR, hook paths) though heavily tested.

Overview
Fixes local derived$ / query$ re-running on every render when props were unchanged: the compiler now emits a captures array (same inference as omitted hook deps) into lowered declarations, and RedeclarableBinding.redeclare returns the committed cell without staging or running the closure when every capture is Object.is-equal. Stable local signal$ (no key or literal key) is omitted from that list; HMR appends a per-module revision token so edited closures still apply.

Shared cells and hooks: render invocation IDs ensure the first declaration in a render wins when two sites share a key (SSR/hydration no longer flip closures mid-render). Custom-hook declaration paths use a NUL-separated, cached stack prefix so explicit keys cannot alias hook path segments and paths are not rebuilt every declaration.

Docs and broad tests cover equal-capture effects, shared keys, hook identity, keyed signal$, later const captures (no list → old path), server replay, and HMR signal edits.

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

…re unchanged

Since #1550 a component-local derived$ or query$ re-ran its closure on every
render, so an object result changed identity on equal-prop renders and every
redeclaring render allocated a declaration stage. The compiler now lists the
render values each local declaration captures, with hook dependency
inference, and RedeclarableBinding returns the committed cell without staging
or evaluating when every value is Object.is-equal. A local signal$ handle with
a static key names one cell and is not listed.

A per-invocation serial from the native-read driver keeps the first
declaration in a render winning when two declarations share a cell. HMR
compiles add a per-module revision so an edited closure still replaces the
old one. A capture declared after the call is not read eagerly.

Custom-hook declaration paths now join sites with NUL, so an authored key
that spells out a path no longer aliases it, and are cached per call stack.

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 3, 2026
@github-actions
github-actions Bot marked this pull request as draft October 3, 2026 07:34

@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: Shared-cell first-wins skips server
    • The server runtime never set signal declaration invocations, so the first-declaration-wins guard (keyed on nonzero invocation) never fired during SSR; fixed by adding setSignalDeclarationInvocation calls around server component renders in both renderComponentFramed and runFullFramedPass, giving each server render a unique nonzero invocation that matches the client's behavior.

Create PR

Or push these changes by commenting:

@cursor push e78631cfc2
Preview (e78631cfc2)
diff --git a/packages/octane/src/runtime.server.ts b/packages/octane/src/runtime.server.ts
--- a/packages/octane/src/runtime.server.ts
+++ b/packages/octane/src/runtime.server.ts
@@ -1,5 +1,6 @@
 export { trustHTML, type TrustedHTML } from './trusted-html.js';
 export { readNativeDomStyle, readNativeDomProps } from './signals/read-protocol.js';
+import { setSignalDeclarationInvocation } from './signals/read-protocol.js';
 /**
  * octane server runtime (SSR).
  *
@@ -400,6 +401,7 @@
 let NATIVE_SERVER_READS: NativeSeedReads | null = null;
 let NATIVE_SERVER_FAILURES = 0;
 let NATIVE_LOCAL_HOOK_DISPOSES: Array<() => void> | null = null;
+let SSR_INVOCATIONS = 0;
 
 /** @internal Enable invocation collection before an opted-in module renders. */
 export function enableNativeReadCollection(abi = 1): void {
@@ -5185,6 +5187,7 @@
 	SIGNAL_CONTROL_SITE = '';
 	SIGNAL_LIST_KEYS = rendererListKeys ?? null;
 	const nativeToken = NATIVE_READ_COLLECTOR === null ? -1 : beginActiveNativeReadScope(scope);
+	const outerInvocation = setSignalDeclarationInvocation(++SSR_INVOCATIONS);
 	let nativeCompleted = false;
 	try {
 		// The compiled body normally returns its HTML string, but a component that
@@ -5258,6 +5261,7 @@
 	} catch (error) {
 		throw normalizeThrownServerThenable(error);
 	} finally {
+		setSignalDeclarationInvocation(outerInvocation);
 		if (nativeToken >= 0) NATIVE_READ_COLLECTOR!.endScope(nativeToken, nativeCompleted);
 		CURRENT_SCOPE = previous.scope;
 		FRAME = previous.frame;
@@ -8965,6 +8969,7 @@
 	let signals: NativeSignalManifest | undefined;
 	let nativePassCompleted = false;
 	const nativeToken = NATIVE_READ_COLLECTOR === null ? -1 : beginActiveNativeReadScope(root);
+	const rootOuterInvocation = setSignalDeclarationInvocation(++SSR_INVOCATIONS);
 	try {
 		// Normalize the root's return the same way ssrComponent normalizes child
 		// components: a compiled component returns its HTML string, but a plain
@@ -8985,6 +8990,7 @@
 		if (!ssrIsSuspense(err)) throw err;
 		rootSuspended = true;
 	} finally {
+		setSignalDeclarationInvocation(rootOuterInvocation);
 		vtCandidates = VT_SSR_HAS_CANDIDATES;
 		rawHtml = VT_SSR_HAS_RAW_HTML;
 		try {

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

Reviewed by Cursor Bugbot for commit ae34b18. Configure here.

@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark report

  • 🔴 bundle-reachability: 1 value(s) increased

Compares 11a9da935 with 442f0bbd9 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.33 3.35 +0.6% ±5% ⚪ within noise
octane-tsrx replace 6.74 6.81 +1.0% ±15% ⚪ within noise
octane-tsrx add 3.25 3.24 −0.3% ±15% ⚪ within noise
octane-tsrx update 0.30 0.42 +40.0% ±48% ⚪ within noise
octane-tsrx select 0.12 0.15 +25.0% ±92% ⚪ within noise
octane-tsrx swap 0.28 0.31 +10.7% ±38% ⚪ within noise
octane-tsrx remove 0.24 0.28 +16.7% ±60% ⚪ within noise
octane-tsrx runlots 28.51 28.31 −0.7% ±8% ⚪ within noise
octane-tsrx select_lots 0.21 0.23 +9.5% ±52% ⚪ within noise
octane-tsrx clear 38.50 38.64 +0.4% ±10% ⚪ within noise
octane-jsx run 3.45 3.49 +1.2% ±12% ⚪ within noise
octane-jsx replace 6.27 6.39 +1.9% ±14% ⚪ within noise
octane-jsx add 2.95 3.12 +5.8% ±9% ⚪ within noise
octane-jsx update 0.46 0.50 +8.7% ±18% ⚪ within noise
octane-jsx select 0.27 0.40 +48.1% ±53% ⚪ within noise
octane-jsx swap 0.51 0.58 +13.7% ±22% ⚪ within noise
octane-jsx remove 0.44 0.51 +15.9% ±18% ⚪ within noise
octane-jsx runlots 28.23 26.99 −4.4% ±18% ⚪ within noise
octane-jsx select_lots 2.17 2.61 +20.3% ±21% ⚪ within noise
octane-jsx clear 40.51 39.71 −2.0% ±10% ⚪ within noise

Application bundle size (bytes)

No changes across 45 measured values.

Public-import reachability bundles (bytes)

target metric base head Δ
binding-radix-esbuild gzip 68,708 68,701 −7 (−0.0%) 🟢
binding-radix-esbuild brotli 59,547 59,575 +28 (+0.0%) 🔴

103 other measured values are unchanged.

…erver rendering

Only the browser's native-read driver numbered render invocations, so on the
server a second declaration naming the same cell, such as a repeated
explicit key, installed its computation mid-render. That changed the cell's
revision and server rendering threw, and the browser presented the first
declaration instead. The server read driver now numbers each body scope, and
a declaration installed outside a render stage counts as its render's first.

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

trueadm commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

The bundle-reachability flag (binding-radix-esbuild brotli +28 B, gzip −7 B) comes from minifier renaming, not new code. I reproduced both numbers locally with benchmarks/bundle-size/run-minimal.mjs against 11a9da935 and this head. The two minified bundles are the same length (213,086 B) and token-for-token identical apart from 369 swapped short identifiers (b↔k, ba↔ka, …). The only module this PR touches in that bundle is signals/read-protocol.ts, and its output stays at 428 B. Nothing to change in source.

🤖 Addressed by Claude Code

@trueadm
trueadm marked this pull request as ready for review October 3, 2026 07:50
@trueadm
trueadm merged commit 07cc1d2 into main Oct 3, 2026
51 checks passed
@trueadm
trueadm deleted the fix/local-derived-deps branch October 3, 2026 08:26
trueadm added a commit that referenced this pull request Oct 3, 2026
…ssigned variable (#1650)

* fix(signals): re-run a local declaration that captures a later or reassigned variable

#1635 compares the render values a local derived$ or query$ captures where
the declaration runs. A var declared after the declaration is still
undefined there, and a let or var assigned again holds an earlier value than
the one the lazy closure reads. Both compared equal across renders, so the
declaration kept its first render's closure after the variable changed.

Capture analysis now records every variable declaration, using a repeated
var's last one, and does not list a callback that captures a reassigned
binding. Such declarations reevaluate on every render as before.

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

* fix(signals): do not list a capture read inside its own initializer

A declaration inside the initializer of a variable its closure reads, such
as `const api = { count$: derived$(() => api.items.length), items }`, had
`[api.items]` listed. The list is read where the declaration runs, while
`api` is still in its temporal dead zone, so rendering threw. Capture
analysis now compares each binding's initialization end, the end of its
last declarator or class, so such a declaration keeps no list.

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
…es read a later binding (#1657)

* fix(signals): re-run a local declaration that captures a later or reassigned variable

#1635 compares the render values a local derived$ or query$ captures where
the declaration runs. A var declared after the declaration is still
undefined there, and a let or var assigned again holds an earlier value than
the one the lazy closure reads. Both compared equal across renders, so the
declaration kept its first render's closure after the variable changed.

Capture analysis now records every variable declaration, using a repeated
var's last one, and does not list a callback that captures a reassigned
binding. Such declarations reevaluate on every render as before.

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

* fix(signals): do not list a capture read inside its own initializer

A declaration inside the initializer of a variable its closure reads, such
as `const api = { count$: derived$(() => api.items.length), items }`, had
`[api.items]` listed. The list is read where the declaration runs, while
`api` is still in its temporal dead zone, so rendering threw. Capture
analysis now compares each binding's initialization end, the end of its
last declarator or class, so such a declaration keeps no list.

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

* fix(compiler): run a hook on every render when its omitted dependencies read a later binding

An omitted dependency array is inferred from the callback's captures and
read where the hook is called. A capture that the component initializes
after the call was read too early: a later let, const or class threw a
temporal-dead-zone ReferenceError at render, a later var was still
undefined so the hook never re-ran, and `const f = useCallback(() => f())`
read f inside its own initializer. React runs a hook with an omitted array
on every render, so inference now emits null for such a hook.

lateDependencyFinder compares only bindings of the hook's own function,
using #1650's initializationEnds, so a module let declared below a
component keeps its list. All four places that print an inferred list
emit null. Strong mode rejects an authored null list, so it reports
OCTANE_STRONG_UNTRACKED_EFFECT at the late read instead.

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

* fix(compiler): skip a null inferred list when marking stable memo dependencies

markStableMemoDependencies, added on main by #1634, walks every inferred
dependency list on the plain-module path. A hook whose omitted list reads
a later binding now infers null, so the walk threw "result.dependencies is
not iterable" while compiling such a module. A null list has no
dependencies to mark.

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

---------

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