Repository navigation
fix(signals): keep a local derived$ or query$ whose captured values are unchanged - #1635
Conversation
…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]>
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: 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.
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.
Benchmark report
Compares js-framework: 1k/10k row operations (ms, lower is better)All 20 timed operations (20 within noise)
Application bundle size (bytes)No changes across 45 measured values. Public-import reachability bundles (bytes)
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]>
|
The 🤖 Addressed by Claude Code |
…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]>
…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]>


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.redeclareonly short-circuited when the closure was the same object, and the compiler emits a fresh closure on every render.derived$changed identity on equal-prop renders. Effects with[value]deps and memoized children re-ran on every parent render.[value]effect 3 times.How it works now:
__derivedAt(site, compute, options, [props.v])and__queryAt(site, select, load, options, [props.id]).redeclarestores the accepted list. When every entry isObject.is-equal, it returns the committed node before opening a stage. The closure does not run and no stage is allocated.D5: custom-hook declaration paths.
'/', 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.Changes
Compiler (
signal-declarations.js, shared by the full printer and the plain-.tssurgical pass):i:) declarations only. Module-scope declarations never redeclare.__methodDep, now re-exported fromoctane/signals.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.signal$with a dynamic key stays in the list.Shared cells:
docs/signals.mddocuments.query$its selection, on every render.HMR:
deps.Captures declared later in the function:
ReferenceErrorfor a closure that captures alet,constorclassdeclared after it.evaluatedAtoption onanalyzeCallbackDependencies.Docs:
docs/signals.mddocuments the new contract and its limits. A declaration that captures another localderived$/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.tsandengine.tswere resolved by keeping both sides, and #1620's suites pass on this head.Validation
pnpm format:check(scopedpnpm format:files:checkon the changed files: clean)pnpm typecheck(scopedpnpm typecheck:fileson the changed files and the fixtures they import: clean)pnpm test(not run locally; left to CI)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,-prodand-strong: signals-hook-declarations, signals-local, signals-rendering, signals-unified./: the D5 test rendersdirect|direct.signal$wrongly treated as stable: the keyed-signal test fails.a before.ReferenceError.pnpm sync: no generated changes.Size, measured deterministically with esbuild + gzip (no timing benches were run):
Risk / follow-ups
derived$/query$handle reevaluates as before. Comparing handles by the cell they present would extend the fast path to those chains..tsrx, the native-read compiler memo around a declaration reads a later-declaredconstearly. That is being handled separately.Provenance
agent-authored)🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith 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, andRedeclarableBinding.redeclarereturns the committed cell without staging or running the closure when every capture isObject.is-equal. Stable localsignal$(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$, laterconstcaptures (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.