Skip to content

feat(compiler): admit host-only conditional item bodies to forBlock PURE - #1213

Merged
domgan-oai merged 1 commit into
mainfrom
feat/forblock-pure-host-conditionals
Sep 21, 2026
Merged

domgan-oai merged 1 commit into
mainfrom
feat/forblock-pure-host-conditionals

Conversation

@jonkwheeler

@jonkwheeler jonkwheeler commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Extends the keyed @for item-body shape check (hasOnlyHostConditionalItemBodies) so a body whose only nested structure is host-only conditional content — an @if over host output, including a narrowly proven nested keyed @for — is admitted to the forBlock PURE fast path.
  • Adds functionBodyContainsComponent so the admission fails closed: a component tag hidden behind a function boundary (e.g. a memoizable call's t => <Tag /> callback argument) still disqualifies the body, since the shape walk deliberately skips function internals.
  • Two existing gates keep the identity-only skip honest: containsAutoMemoUnsafeStructure rejects render-time hazards like an assignment in the @if test, and containsImportedMemberRead rejects live imported member reads (@if (mod.flag)) whose value can mutate while the import's identity stays fixed.

Why

  • The forBlock PURE bit lets updateSurvivor skip a surviving row's body entirely when the item identity is unchanged. Until now any nested component-shaped structure — including a plain host-only @if, which the shape classifier counts as hasNestedComp — disqualified the body.
  • A host-only conditional renders nothing opaque of its own: with no parent captures the body is a pure function of the item, so identical-identity survivors have nothing inside the conditional that could move.
  • Effect: conditional rows common in real lists (badges, flags, optional spans) now skip re-render on sibling updates and keyed reorders, instead of re-running every survivor body.

Changes

  • packages/octane/src/compiler/compile.js: hasOnlyHostConditionalItemBodies consults functionBodyContainsComponent at function boundaries; new functionBodyContainsComponent helper; makeForCall computes hostConditionalPure (hasNestedComp && hasOnlyHostConditionalItemBodies && !containsAutoMemoUnsafeStructure && !containsImportedMemberRead) and folds it into the hostPure admission.
  • packages/octane/tests/compiler/for-item-purity.test.ts (new): pins the emitted forBlock flags bit — admission for host-only @if and a proven nested keyed @for; fail-closed cases for component arms, function-boundary-hidden components, parent captures, assignment-in-test, imported member reads, @try, @switch, portals, and index-binding/keyless nested @for.
  • packages/octane/tests/for.test.ts + packages/octane/tests/_fixtures/for.tsrx: PureConditionalList end-to-end coverage — identical-identity survivors skip re-reading a mutated module binding on sibling change and on keyed reorder while DOM moves correctly.

Validation

  • pnpm format:files:check on touched paths — clean.
  • pnpm typecheck:files on touched paths — clean.
  • targeted tests: vitest run packages/octane/tests/compiler/for-item-purity.test.ts packages/octane/tests/for.test.ts — 196 tests pass across the octane and octane-prod projects (compiler test runs under octane only, per config).
  • pnpm sync leaves the tree clean (no generated output).
  • pnpm format:check, pnpm typecheck, pnpm test — deferred to CI per repo convention.
  • svg-dashboard delta at this branch's HEAD: octane-tsrx geomean 0.866x vs main@8a4a2e087 (20 iters, same harness; <1 = faster) — drag_nodes 10.1→4.3 ms (0.42x), label_churn 2.5→1.5 (0.59x), style_spread_pulse 4.9→3.5 (0.72x), topology_churn 2.7→2.4 (0.89x); mount/tick/pan flat. vs react fixture: 1.02x geomean (select_toggle, style_spread_pulse remain write-path ops owned by the changed-commit-write-path child)
  • Framework bytes at HEAD (octane fw gz): app/tsrx 38013, jsx 66787, todomvc 42426, chat-stream 41865, weather-app 51897 — compiler-only change; runtime bytes unchanged vs base expected. run-minimal.mjs captured all listed scenario sizes before stopping at the pre-existing binding-aria-esbuild failure (known unrelated esbuild issue flagged on perf(runtime): beat React 19 + Compiler across the timing benchmark portfolio #1188).

Risk / follow-ups

  • Fail-closed design: any shape the prover cannot clear keeps the ordinary (non-PURE) survivor path, so a mis-admission would have to come from the prover's host-only contract itself, not from an unguarded call site.
  • Nested @for admission is narrow — keyed, no index binding — because the identity skip has no index witness; index-bound and keyless nested loops stay out.

Part of #1202. Split from #1188.

Provenance

  • An agent produced this diff (agent-authored)

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 proofs for keyed-list survivor skipping; mis-admission could leave stale DOM, though the design fails closed and is heavily tested.

Overview
Extends keyed @for PURE admission so item bodies whose only extra structure is host-only @if content (optional spans, flags, etc.) can skip re-render when the item identity is unchanged—previously any nested “component-shaped” control flow blocked the fast path.

The compiler now treats hostConditionalPure as an alternate to a flat host body: hasOnlyHostConditionalItemBodies plus existing safety checks (containsAutoMemoUnsafeStructure, containsImportedMemberRead), and functionBodyContainsComponent so components hidden in callback arguments (e.g. t => <Tag />) still fail closed. Parent captures, component arms, live imports, and broader control flow stay on the ordinary survivor path.

New for-item-purity tests assert the emitted forBlock flags bit; PureConditionalList fixture and runtime tests confirm unchanged-identity rows skip body work on sibling updates and keyed reorders while DOM moves correctly.

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

@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent feat PR: new feature or capability labels Sep 21, 2026

@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: Imported member gate misses TS wrappers
    • containsImportedMemberRead now unwraps TS/paren receivers so wrapped imported members fail closed and cannot take the identity-only skip.

Create PR

Or push these changes by commenting:

@cursor push 6a22de103b
Preview (6a22de103b)
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
@@ -6504,7 +6504,8 @@
 
 // A JSX member chain bottoms out at a JSXIdentifier, so the base test below
 // never matches one. Do not reintroduce a JSX-awareness flag: it cannot change
-// the answer.
+// the answer. Unwrap TS/paren wrappers on the receiver so `mod!.flag` and
+// `(mod as T).flag` still count as live imported member reads.
 function containsImportedMemberRead(root, importedNames) {
 	let found = false;
 	const seen = new WeakSet();
@@ -6517,9 +6518,9 @@
 		if (typeof n !== 'object' || seen.has(n)) return;
 		seen.add(n);
 		if (n.type === 'MemberExpression' || n.type === 'JSXMemberExpression') {
-			let object = n;
+			let object = unwrapTsExpr(n.object);
 			while (object?.type === 'MemberExpression' || object?.type === 'JSXMemberExpression') {
-				object = object.object;
+				object = unwrapTsExpr(object.object);
 			}
 			if (object?.type === 'Identifier' && importedNames.has(object.name)) {
 				found = true;

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
@@ -169,6 +169,45 @@
 		expect(flags[0]! & PURE).toBe(0);
 	});
 
+	it.each<[string, string, string]>([
+		['a non-null assertion', "import { flags } from './flags';", 'flags!.enabled'],
+		[
+			'a type assertion',
+			"import { flags } from './flags';",
+			'(flags as { enabled: boolean }).enabled',
+		],
+		[
+			'a satisfies assertion',
+			"import { flags } from './flags';",
+			'(flags satisfies { enabled: boolean }).enabled',
+		],
+		[
+			'a type assertion before a further member',
+			"import { flags } from './flags';",
+			'(flags as { nested: { enabled: boolean } }).nested.enabled',
+		],
+		['a namespace non-null assertion', "import * as flags from './flags';", 'flags!.enabled'],
+	])('declines when the imported member read uses %s', (_name, prelude, test) => {
+		// TS wrappers must not hide a live import: the identity-only skip still
+		// cannot witness `flags.enabled` flipping while `flags` stays fixed.
+		const flags = appListFlags(
+			compile(
+				`
+				${prelude}
+				export function App(props) @{
+					<ul>@for (const item of props.items; key item.id) {
+						<li>@if (${test}) {<span class="x" />}</li>
+					}</ul>
+				}
+			`,
+				'App.tsrx',
+				{ hmr: false, dev: false },
+			).code,
+		);
+		expect(flags).toHaveLength(1);
+		expect(flags[0]! & PURE).toBe(0);
+	});
+
 	it.each<[string, string, string?]>([
 		[
 			'@try',

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

Reviewed by Cursor Bugbot for commit 0c15b59. Configure here.

Comment thread packages/octane/src/compiler/compile.js Resolved
@jonkwheeler

Copy link
Copy Markdown
Contributor Author

Suggested review order for the #1188 split (tracking: #1202):

  1. fix(benchmarks): restore effectful-list workload honesty and enable React Compiler in spa-navigation #1205 — fixtures/harness honesty; everything downstream is measured against the baselines it fixes
  2. ci(benchmarks): recommit bundle budgets to measured main reality #1207 — budgets + guards re-measured on main; gives the perf PRs headroom to land green
  3. feat(compiler): admit host-only conditional item bodies to forBlock PURE #1213 — forBlock PURE, compiler-only; smallest and most contained
  4. feat(octane): $$stable — compiler-proven props-snapshot bailout for components #1214 — $$stable, compiler+runtime; introduces blockBailUnsafe (the shared hazard veto)
  5. perf(octane): signal-instance identity + dormant-owner fast paths #1216 — signal identity + dormant paths; moderate runtime diff
  6. perf(octane): changed-commit write path — sources plan, fused scan, journal replay #1215 — write path; largest diff, easiest once feat(octane): $$stable — compiler-proven props-snapshot bailout for components #1214 and perf(octane): signal-instance identity + dormant-owner fast paths #1216's machinery is familiar

Wave 2 (#1213–#1216) is any-order for merging — this sequence front-loads the concepts later diffs build on.

@domgan-oai
domgan-oai merged commit 620769b into main Sep 21, 2026
53 checks passed
@domgan-oai
domgan-oai deleted the feat/forblock-pure-host-conditionals branch September 21, 2026 20:08
domgan-oai pushed a commit that referenced this pull request Sep 23, 2026
…bal state (#1265)

* fix(compiler): keep keyed @for rows live when they read module or global 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]>

* fix(compiler): classify ambient globals by top-level module bindings

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]>

* fix(compiler): analyze destructured @for header defaults as row reads

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]>

* test(compiler): pin the whole-list cache off for destructured header 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]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot mentioned this pull request Sep 23, 2026
trueadm pushed a commit that referenced this pull request Nov 2, 2026
…2310)

containsImportedMemberRead walked a member chain's receivers with
`object.object` and stopped at the first node that was not a member
expression. A receiver wrapped in `!`, `as`, or `satisfies` ended the walk
before the imported identifier, so a read like `flags!.enabled` looked free
of live imports. In production builds a keyed @for row reading one could
take the identity-only survivor skip, and the whole list could be cached on
`[props.items, flags]`, so the row kept a stale @if branch after the member
changed. The walk now unwraps each receiver with unwrapValueExpression.

Reported by Cursor Bugbot on #1213:
#1213 (comment)

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 feat PR: new feature or capability

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants