Skip to content

fix(compiler): keep keyed @for rows live when they read module or global state - #1265

Merged
domgan-oai merged 4 commits into
mainfrom
fix/for-pure-ambient-reads
Sep 23, 2026
Merged

domgan-oai merged 4 commits into
mainfrom
fix/for-pure-ambient-reads

Conversation

@trueadm

@trueadm trueadm commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Keyed @for rows that read a module let or 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:

@for (const item of NAV; key item.href) {
	@if (location.pathname === item.href) { <li class="active">…</li> } @else { <li>…</li> }
}

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 new isUnwitnessedAmbientRead classifier flags two kinds of name:

    • mutable top-level module bindings: let, var, class, and reassigned functions (collectMutableModuleBindings);
    • unbound names outside a small set of standard ECMAScript globals.

    makeForCall withholds PURE and DEP-PURE from any row whose render output reads one. These still keep the fast path:

    • module consts and unreassigned functions;
    • imports, which are unchanged;
    • compiler _$… helpers;
    • reads confined to inline 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:

    • New compiler flag tests in for-item-purity.test.ts cover both fail-closed and keep-PURE cases.
    • New runtime tests in for.test.ts run in dev and prod. They cover a module-let active row in the @if and class-ternary forms, DEP-PURE plus a module let, and @if (location.hash === item.href).
    • feat(compiler): admit host-only conditional item bodies to forBlock PURE #1213's tests and the NaN-deps DEP-PURE test used a mutated module let to 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

  • I compiled all 3,047 .tsrx modules 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.
  • The benchmarks/codegen-size targets 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.
  • Benchmark output is unchanged, so runtime cost is unchanged by construction. Compile time adds one extra free-identifier walk, only for rows that already have a candidate name.

Validation

  • pnpm format:files:check on changed files
  • pnpm typecheck:files
  • pnpm 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 except motion-pristine upstream-original.test.ts, which fails identically with origin/main's compiler. CI is the real gate here.
  • targeted tests: for.test.ts and for-item-purity.test.ts on the octane and octane-prod projects (224 passed after rebase). All 16 new tests fail with the gate disabled.
  • pnpm sync: no generated changes

Risk / follow-ups

  • Rows reading a mutable global or module let inside 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.
  • Not fixed here: a PURE row that directly reads an imported export let binding 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

  • 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 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 @for rows when render output depends on module let/var, reassigned module functions, or host/app globals (location, window, etc.) that item identity and deps tuples cannot witness.

The compiler adds isUnwitnessedAmbientRead (via collectModuleTopLevelBindings) and makeForCall now sets hasAmbientRead so those rows lose PURE / DEP-PURE survivor skips; reads only in inline onXxx handlers are ignored. Destructured @for headers and whole-list memo get the same fail-closed treatment when defaults/keys read ambient state. docs/differences-from-react.md documents the rule; fixtures and tests use countedRow and new nav/location.hash scenarios 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.

…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]>
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent fix PR: bug fix labels Sep 23, 2026
@github-actions
github-actions Bot marked this pull request as draft September 23, 2026 08:21

@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.

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.

Create PR

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.

Comment thread packages/octane/src/compiler/compile.js Resolved
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
trueadm marked this pull request as ready for review September 23, 2026 08:38

@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.

Stale Bugbot comment from a previous run.

Comment thread packages/octane/src/compiler/compile.js Resolved
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]>

@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: 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.

Create PR

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.

Comment thread packages/octane/src/compiler/compile.js Resolved
…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]>
@domgan-oai
domgan-oai merged commit 0df8be7 into main Sep 23, 2026
30 checks passed
@domgan-oai
domgan-oai deleted the fix/for-pure-ambient-reads branch September 23, 2026 09:32
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]>
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.

2 participants