Repository navigation
fix(compiler): keep keyed @for rows live when they read module or global state - #1265
Merged
Merged
Conversation
…bal state forBlock PURE and DEP-PURE skip a survivor row on item identity plus the deps tuple. A module `let`/`var`, a reassigned module function, or a mutable global (`location`, `window`, `globalThis.x`) can change with neither moving, so such rows stayed stale. #1213 extended the gap to rows whose only control flow is a host-only @if (e.g. `@if (location.pathname === item.href)` never moved the active nav row). Rows whose render output reads one of those names now fail closed, as the item-memo, whole-list, and component autoMemo proofs already do. Module consts, unreassigned functions, imports, standard ECMAScript globals, and reads confined to inline onXxx handlers keep the fast path. Compiled output across all 3,047 repo .tsrx modules and the codegen-size corpus is unchanged apart from two test fixtures. Skip-probe tests that observed a survivor skip through a mutated module `let` now use a counting getter on the item instead. 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.
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Shadowed names hide mutable globals
- Replaced _moduleBoundNames (all-scopes) with _moduleTopLevelBoundNames (top-level only) in isUnwitnessedAmbientRead so sibling function parameters no longer mask global reads like location, and added a regression test confirming @for rows correctly decline PURE when a sibling shadows the name.
Or push these changes by commenting:
@cursor push 7b5812b116
Preview (7b5812b116)
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
@@ -5218,6 +5218,38 @@
['JSON', new Set(['parse', 'stringify'])],
]);
+// Top-level module-scope bindings only: declarations, function/class names,
+// and imports visible at the module's own scope. Parameters and locals of
+// nested functions are excluded — they do not shadow globals for siblings.
+function collectModuleTopLevelBoundNames(body) {
+ const names = new Set();
+ for (const statement of body) {
+ let declaration = statement;
+ if (
+ statement.type === 'ExportNamedDeclaration' ||
+ statement.type === 'ExportDefaultDeclaration'
+ ) {
+ declaration = statement.declaration;
+ if (!declaration) continue;
+ }
+ switch (declaration.type) {
+ case 'VariableDeclaration':
+ for (const d of declaration.declarations || []) collectBindings(d.id, names);
+ break;
+ case 'FunctionDeclaration':
+ if (declaration.id) names.add(declaration.id.name);
+ break;
+ case 'ClassDeclaration':
+ if (declaration.id) names.add(declaration.id.name);
+ break;
+ case 'ImportDeclaration':
+ for (const spec of declaration.specifiers || []) if (spec.local) names.add(spec.local.name);
+ break;
+ }
+ }
+ return names;
+}
+
// Every binding name the module declares anywhere. A global namespace shadowed
// by any local, parameter, or import is treated as an unknown callee.
function collectModuleBoundNames(ast) {
@@ -5635,7 +5667,7 @@
// `_$…` names are runtime helpers the compiler itself imports.
if (name.startsWith('_$')) return false;
if (ctx.mutableModuleBindings?.has(name)) return true;
- const bound = ctx._moduleBoundNames;
+ const bound = ctx._moduleTopLevelBoundNames;
return bound !== undefined && !bound.has(name) && !IMMUTABLE_AMBIENT_GLOBALS.has(name);
}
@@ -10477,6 +10509,9 @@
ast.body,
ctx.moduleFunctionDeclarations,
);
+ // Top-level module bindings for the ambient-read classifier: only names
+ // declared at the module's own scope can shadow a global for a @for body.
+ ctx._moduleTopLevelBoundNames = collectModuleTopLevelBoundNames(ast.body);
// Global namespaces are only trusted by the setup checkpoint analysis when
// no module binding shadows them (see setupCanScheduleSelfUpdate).
ctx._moduleBoundNames = collectModuleBoundNames(ast);
@@ -25120,7 +25155,7 @@
const k = path[path.length - 1];
const prefix = path.slice(0, -1);
// Prefer chaining off the nearest ALREADY-MATERIALIZED preceding sibling at
- // this level — one `.nextSibling` run across from it — over re-walking
+ // this level — one `.nextSibling` run across from it ��� over re-walking
// `.firstChild.nextSibling×k` from the parent for every sibling. A row of k
// bound cells (e.g. dbmon's `<td>`s) otherwise costs 1+2+…+k navigation steps
// (O(k²) in both code size and mount-time DOM walking); chaining makes it
diff --git a/packages/octane/tests/compiler/for-item-purity.test.ts b/packages/octane/tests/compiler/for-item-purity.test.ts
--- a/packages/octane/tests/compiler/for-item-purity.test.ts
+++ b/packages/octane/tests/compiler/for-item-purity.test.ts
@@ -213,6 +213,11 @@
'<li data-pick={pick} />',
],
['location in an @if test', '', '<li>@if (location.hash === item.href) {<b />}</li>'],
+ [
+ 'location when a sibling function shadows the name',
+ 'function match(location, href) { return location.hash === href; }',
+ '<li>@if (location.hash === item.href) {<b />}</li>',
+ ],
['a globalThis property', '', '<li>@if ((globalThis as any).flag) {<b />}</li>'],
])('declines a body reading %s', (_name, prelude, body) => {
const flags = compileList(body, prelude);You can send follow-ups to the cloud agent here.
isUnwitnessedAmbientRead treated any name bound anywhere in the module as non-global, so an unrelated parameter or local named `location` or `window` hid the real global a keyed row reads, keeping PURE/DEP-PURE. Globals are now names outside the top-level module declarations (imports, variables, functions, classes, enums) and outside the enclosing local chain the caller already checks; a missed enclosing binding fails closed. Destructured @for header fields are excluded explicitly, and TS enum reads no longer lose the fast path. Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm
marked this pull request as ready for review
September 23, 2026 08:38
A destructured header's defaults and computed keys run in the item
helper's synthesized prologue, but purity analysis only walked the
authored body. `@for (const { label = mode } of …)` with a module `let`
or global stayed PURE, and a default reading a component local
(`label = fallback`) was also PURE despite the env tuple capturing it, so
survivors kept a stale default.
The prologue is now analyzed with the body for free names and render
calls, which also binds header fields in scope and replaces the
explicit header-binding exclusion.
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: Whole-list cache misses header defaults
- Confirmed the bug: when destructured field names shadow imports and the default reads a module
let, regionStmts (built only from subStmts) missed the default's free identifier, letting listSafe stay true and the whole-list cache incorrectly skip the forBlock; fixed by including destructureInjection in regionBase so all whole-list proof checks see header defaults.
- Confirmed the bug: when destructured field names shadow imports and the default reads a module
Or push these changes by commenting:
@cursor push 4f8bdf2227
Preview (4f8bdf2227)
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
@@ -32048,7 +32048,9 @@
// then skip the forBlock call entirely while that identity and every lexical
// body/key/@empty capture are unchanged. Direct render-time calls, refs,
// mutations, effects, portals, and opaque module/global reads fail closed.
- const regionStmts = emptyStmts ? [...subStmts, ...emptyStmts] : subStmts;
+ const regionBase =
+ destructureInjection.length > 0 ? [...destructureInjection, ...subStmts] : subStmts;
+ const regionStmts = emptyStmts ? [...regionBase, ...emptyStmts] : regionBase;
const regionAst = b.block(regionStmts);
const regionFree = collectFreeIdentifiers(regionAst, bodyScope);
for (const name of collectFreeIdentifiers(keyBody, bodyScope)) regionFree.add(name);
diff --git a/packages/octane/tests/compiler/for-item-purity.test.ts b/packages/octane/tests/compiler/for-item-purity.test.ts
--- a/packages/octane/tests/compiler/for-item-purity.test.ts
+++ b/packages/octane/tests/compiler/for-item-purity.test.ts
@@ -302,6 +302,24 @@
expect(flags[0]! & (PURE | DEP_ELIGIBLE)).toBe(expected);
});
+ it('declines the whole-list cache when a destructured default reads a module let that shadows an import', () => {
+ const code = compile(
+ `
+ import { id, label } from './lib';
+ let mode = 'dark';
+ export function App(props) @{
+ <ul>@for (const { id, label = mode } of props.items; key id) {
+ <li>{label as string}</li>
+ }</ul>
+ }
+ `,
+ 'App.tsrx',
+ { hmr: false, dev: false },
+ ).code;
+ const appRegion = code.slice(code.indexOf('export const App'));
+ expect(appRegion).not.toContain('compilerMemoRegion');
+ });
+
it('keeps PURE for a destructured header whose fields the body reads', () => {
const flags = appListFlags(
compile(You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit a9d355b. Configure here.
…reads The whole-list forBlock cache walks the authored body, where destructured header fields read as unclassified free names, so any destructured header already fails its proof closed and a default or computed key cannot feed a stale list skip. Pin that for module-let and global defaults and a module-let computed key, with a plain-header control that does cache. A list proof that bound the fields without walking their defaults turns these red. Co-Authored-By: Claude Opus 5.5 <[email protected]>
6 of 7 tasks
trueadm
added a commit
that referenced
this pull request
Oct 2, 2026
…g and SSR metadata ratio guards (#1591) * fix: recover the template-call-memo, transition-hooks, signal-favoring and SSR metadata ratio guards Four ratio suites breached deterministic guards on main. Each was bisected over the suite's own output, with every old checkout on its own installed dependencies. - template-call-memo (0df8be7, #1265): a Strong `@for` row calling `console.log` lost DEP-PURE because `console` is a host global. The receiver of a statement-position `console.method()` call no longer counts as an ambient row read; its arguments still do. - ssr-final-metadata (5ead1ff, #1069): `ssrComponent` re-encoded a keyed descriptor's key that ssrChildValue's `child-key` membrane already holds. ssrChildValue now passes `identityScoped: 'key'`. - transition-hooks (5ead1ff, #1069; 8a45222, #1068): runTransition's native candidate resolver and fireEventSlot's invoke callback no longer allocate a closure per transition or delegated event. The pooled event frame's first allocation gets a one-time work-model allowance. - signal-favoring (5ead1ff, #1069): the JSX static-fragment fold matches `_$createElementFromConfig(site, C, props)` again, and bindSignalChild keeps textHoleUpdate's primitive fast path. Bump samples are calibrated to 20 ms because a TSRX bump sat under Chromium's 100 us clock floor; the dialect ceiling moves to 18 from same-runner measurements before #1069 and after this fix. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix: keep a skipped text hole's token unpublished and fit the chained-JSX budget bindSignalChild returned the new primitive as its token even when the block was already pending, so childSlot skipped the write. The repeated render then matched that token and left the previous text in place. A skipped pass now keeps the token unpublished; the new test drives a mid-render self-update through an earlier hole. invokeEventSlot is an if/else chain without the redundant bundle alias, which brings root-chained-jsx back to its raw and gzip ceilings. Removing the per-event closure still costs 2 brotli bytes, so that budget moves one 32-byte step to 25344. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf: trim bindSignalChild's primitive text fast path Fold the pending-pass check into the primitive-token flag and drop the ownsHost test: only the implicit childSlot path passes ownsHost, and that path's implicitSignal already keeps it off the fast path. Saves 36 raw and 19 gzip bytes in bundles that reach bindSignalChild. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Summary
Keyed
@forrows that read a moduleletor a mutable global no longer take the forBlock PURE / DEP-PURE survivor skip, so they re-render when that value changes.Bug: PURE and DEP-PURE skip a surviving row when its item identity (and, for DEP-PURE, the deps tuple) is unchanged. A module
let/var, a reassigned module function, or a host or application global (location,window,globalThis.flag) can change while neither moves, so the row stayed stale. #1213 extended this to rows whose only control flow is a host-only@if, which previously always re-rendered:After navigating, the active row never moved. Plain text and attribute reads such as
<li>{mode + item.id}</li>were already stale before #1213.Decision: fail closed, matching the rest of the compiler. The item-memo, whole-list, and component autoMemo proofs already refuse these names. In-component regions re-evaluate them too (verified with a probe). PURE/DEP-PURE keyed rows were the only outlier.
Changes
compile.js: a newisUnwitnessedAmbientReadclassifier flags two kinds of name:let,var, class, and reassigned functions (collectMutableModuleBindings);makeForCallwithholds PURE and DEP-PURE from any row whose render output reads one. These still keep the fast path:consts and unreassigned functions;_$…helpers;onXxx={() => …}handlers, which run after commit.docs/differences-from-react.md: the automatic-memoization paragraph now describes this. Values returned by an imported helper are still taken at their word, as before.Tests:
for-item-purity.test.tscover both fail-closed and keep-PURE cases.for.test.tsrun in dev and prod. They cover a module-letactive row in the@ifand class-ternary forms, DEP-PURE plus a modulelet, and@if (location.hash === item.href).letto detect a skipped survivor, which relied on this bug. They now use a counting getter on the item (countedRow) and assert the same skips.Performance
.tsrxmodules in the repo (production, client) with and without the gate. Only 2 changed, both test fixtures (±2–4 gzip bytes). Every benchmark and app module is byte-identical.benchmarks/codegen-sizetargets are identical, including js-framework octane-tsrx, octane-jsx and the naive variants. I ran it with its rspack CSS-modules step stubbed, because that step fails locally on both sides with an unrelated chunk assertion.Validation
pnpm format:files:checkon changed filespnpm typecheck:filespnpm test: a full local run was not clean. The machine was at load average ~60–67 from other sessions, and the run aborted with timeouts across unrelated packages. Rerunning every failing file at--maxWorkers=4, all passed exceptmotion-pristine upstream-original.test.ts, which fails identically withorigin/main's compiler. CI is the real gate here.for.test.tsandfor-item-purity.test.tson the octane and octane-prod projects (224 passed after rebase). All 16 new tests fail with the gate disabled.pnpm sync: no generated changesRisk / follow-ups
letinside their render output now re-render each parent render. That is intended, and the repo sweep found only a handful of such rows, all of them in tests.export letbinding can still go stale, because imports aren't dependency witnesses on this path. Fixing it would move those rows from PURE to DEP-PURE, a codegen change worth its own PR.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 core @for memoization proofs in the compiler; misclassification would show stale UI, though the change is fail-closed and repo codegen impact is minimal.
Overview
Fixes stale keyed
@forrows when render output depends on modulelet/var, reassigned module functions, or host/app globals (location,window, etc.) that item identity and deps tuples cannot witness.The compiler adds
isUnwitnessedAmbientRead(viacollectModuleTopLevelBindings) andmakeForCallnow setshasAmbientReadso those rows lose PURE / DEP-PURE survivor skips; reads only in inlineonXxxhandlers are ignored. Destructured@forheaders and whole-list memo get the same fail-closed treatment when defaults/keys read ambient state.docs/differences-from-react.mddocuments the rule; fixtures and tests usecountedRowand new nav/location.hashscenarios instead of relying on the old bug.Reviewed by Cursor Bugbot for commit 883825c. Bugbot is set up for automated code reviews on this repo. Configure here.