Skip to content

perf: keep form-action and transition graphs out of event-only bundles - #946

Merged
trueadm merged 7 commits into
mainfrom
perf/pr943-bundle-growth
Sep 3, 2026
Merged

trueadm merged 7 commits into
mainfrom
perf/pr943-bundle-growth

Conversation

@trueadm

@trueadm trueadm commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Note

Low Risk
Changes are tree-shaking and compile-time emission guards with fail-closed checkpoint analysis; function form actions still depend on setFormAction installing the driver, which new tests pin.

Overview
Production bundles that only delegate events no longer pull in handleFormSubmit, startTransition, and the held-transition graph. dispatchDelegated invokes a nullable FORM_SUBMIT_DRIVER that setFormAction installs when a function $$formAction is first wired, so specialized/static roots and click-only apps shrink by several KB gzip without changing submit behavior when a real function action exists.

Compiled setup checkpoints (__s.block.pending early return) are emitted only when static analysis decides setup can schedule a render-phase self-update. Passive built-in hooks and allowlisted pure globals no longer force the checkpoint; setters, sync-factory bodies, factories/initializers passed by reference, prop/custom-hook calls, and anything unclassified still do. Module binding names guard the global allowlist against shadowing.

Adds reachability and behavior tests (production esbuild bundles, spread-mounted form actions, memo-factory mount replay) and audit doc measurements for the bundle-size follow-up.

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

Summary

  • Attributes the client bundle and compiled-output growth of fix: address React behavioral audit defects #943 per top-level declaration (Vite production tree-shaking, base 33720d8 vs main vs this branch) and removes the part that is reachability rather than fixed behavior.
  • dispatchDelegated no longer references the form-action submit handler directly. setFormAction, the only writer of $$formAction, installs a FORM_SUBMIT_DRIVER, so bundles that only delegate events (compiler-specialized roots, the CLI SPA starter) stop retaining startTransition and the whole held-transition swap graph (about 30 functions, roughly 4.1 KB gzip).
  • The compiled setup checkpoint (if (__s.block.pending && !__s.block.crossRenderUpdate) return;) is emitted only when setup can schedule a render-phase self-update. Passive built-in hooks and unshadowed standard globals cannot; setters, custom hooks, prop callbacks, sync factories that call setters, factories or initializers passed by reference (any callable-shaped argument to a sync-factory hook fails closed), and any unclassified call keep it.

Why

  • The audit doc recorded +3.3 KB gzip on the hook-memo bundles and +713 minified bytes on its compiled fixture. Measured in one environment, the static/specialized minimal scenarios had grown far more (+4.9 KB and +5.2 KB gzip): dispatchDelegated → handleFormSubmit → startTransition → ensureTransitionSwapDriver made the transition machinery reachable from any bundle with delegated events. Before fix: address React behavioral audit defects #943 that path was only reachable through setFormAction.
  • The checkpoint is not behaviorally observable (the runtime's own child-initialization guards back it; every pinned suite passes with it removed entirely), so it only needs to exist where a self-update is possible.

Measurements

Same environment for every column: Node 24.18.0, macOS ARM64, locked native parser, pnpm install --offline. Base is 33720d8 (the PR base), main is 44d50db.

node benchmarks/hook-memo/run.mjs (inline variant, gzip bytes / minified bytes):

Metric Base Main This branch
Tree-shaken bundle, gzip 55,169 58,568 58,580
Compiled fixture output, minified 7,183 7,896 7,896

node benchmarks/bundle-size/run-minimal.mjs (gzip bytes):

Scenario Base Main This branch
root-static-specialized 18,565 23,499 19,410
cli-spa-starter 31,256 36,459 32,294
root-static 46,287 49,419 49,440
hooks-state 47,553 51,346 51,350
context 48,236 52,066 52,049
hydrate-root 52,873 55,935 55,942
deferred-hydration 68,872 72,722 72,717
suspense-transition (base fixture fails its own gate) 61,092 61,084

node benchmarks/codegen-size/run.mjs (compiled corpus, minified / gzip):

Base Main This branch
Corpus minified bytes 76,534 78,983 76,553
Corpus gzip bytes 27,146 27,555 27,278

Attribution of the residual growth on root-static-specialized after this branch (about 850 gzip bytes): the urgent-transition render handling in renderBlockInner, the mount-time render-phase drain, delegated handler and submit snapshots, commit-phase error queue, Document/fragment root support, and the custom-element event checks. All are the fixed behaviors.

What was not reduced, and why

  • Hook-memo bundles and every createRoot scenario keep their growth. Their entry retains the descriptor renderer, whose spread and host-prop paths own function form actions, so they already reached the transition graph before fix: address React behavioral audit defects #943 through setFormAction → handleFormSubmit → startTransition. That chain cannot be made lazy soundly: a spread or createElement prop decides at render time. The growth there is the new transition-hook records, queued state replay, and held-update reconciliation, which are the B-series fixes themselves.
  • The hook-memo compiled fixture keeps all 12 checkpoints because every fixture component invokes an observe prop in setup, which is an unclassifiable call.
  • event-names.js stays runtime data: custom-element spread/descriptor props need the exact camel-case delegated set at render time; feature detection would diverge from React on the pinned corner cases.
  • html-tree-validation.js was already imported by the client runtime before fix: address React behavioral audit defects #943 (dev-only use, tree-shaken from production output), so it is not a contributor.
  • Every fix: address React behavioral audit defects #943 development diagnostic named in the task is already behind process.env.NODE_ENV !== 'production'; none of their strings appear in the production bundles.
  • The benchmarks/bundle-size ratio guards (node benchmarks/bench.mjs --ratios bundle-reachability) breach 66 times on main and on the pre-fix: address React behavioral audit defects #943 base: the committed budgets date from fix: stop the compiled @for path retaining the descriptor renderer #767 (2026-08-16) and that suite only runs in the weekly bench workflow. This branch improves the affected scenarios but I did not raise budgets; that needs a maintainer decision.

Changes

  • packages/octane/src/runtime.ts: FORM_SUBMIT_DRIVER, installed by setFormAction, invoked from dispatchDelegated.
  • packages/octane/src/compiler/compile.js: setupCanScheduleSelfUpdate replaces the any-call rule for the setup checkpoint; collectModuleBoundNames guards the global allowlist against shadowing; the allowlist is an explicit set of non-invoking members (Math.*, Number/Object/Array/Date inspectors, JSON.parse/stringify with their callback positions checked like hook factories), so Array.from, Object.groupBy, and any callback passed by reference keep the checkpoint.
  • Tests: form-action-bundle.test.ts (production reachability with and without a function form action, executed in JSDOM), spread-installed form action after mount in audit-events-portals.test.ts, memo-factory self-update replay plus checkpoint emission matrix in audit-hook-behavior.test.ts. Each was confirmed red with its fix reverted.
  • docs/divergence-audit-2026-09-03.md: follow-up measurements row.
  • Changeset: octane patch.

Validation

  • pnpm format:check
  • pnpm typecheck
  • pnpm test: 28,733 passed, 2 failed as 5 s timeouts (hmr.test.ts prod 'App' vite replacement, compiler/volar.test.ts spread-ref type check) during a 25-minute run under concurrent load; both files pass in isolation on this branch and on main (96/96). Locally the vitest orchestrator exhausts the default 4 GB heap on an unmodified main checkout too, so the run used NODE_OPTIONS=--max-old-space-size=12288.
  • targeted tests, both projects (octane, octane-prod): audit-hook-behavior, audit-events-portals, compiler-authored-hosts, host-update-contract, audit-list-diagnostics, audit-hook-diagnostics, universal-manual-hook-context, plain-hook-import-alias, actions, production-error-bundle, form-action-bundle
  • node benchmarks/hook-memo/run.mjs value/identity and observer controls pass

Risk / follow-ups

  • If a future path other than setFormAction starts writing $$formAction, it must also install the driver; the reachability test pins the negative case and the spread/descriptor tests pin the positive one.
  • A component whose setup reaches a setter only through a route the analysis cannot see (an unknown call) still gets the checkpoint, so the failure mode of a misclassification is an omitted optimization, never a wrong render.

Provenance

  • An agent produced this diff (agent-authored)

🤖 Generated with Claude Code

PR #943 let dispatchDelegated call the form-action submit handler directly,
which made startTransition and the held-transition swap graph reachable from
every bundle with delegated events. setFormAction, the only writer of
$$formAction, now installs that handler through FORM_SUBMIT_DRIVER. The
compiled setup checkpoint is emitted only when setup can schedule a
render-phase self-update; passive built-in hooks and unshadowed pure globals
cannot.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@trueadm
trueadm marked this pull request as ready for review September 3, 2026 20:52
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent perf PR: performance work labels Sep 3, 2026
Comment thread packages/octane/src/compiler/compile.js Resolved
trueadm and others added 2 commits September 3, 2026 22:19
A memo factory, state initializer, or reducer passed by reference can call a
setter without a visible body. Treat every argument to a sync-factory hook
that could be a function as an unclassified call so the setup checkpoint stays.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@vercel

vercel Bot commented Sep 3, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
octane-website Skipped Skipped Sep 3, 2026 9:20pm UTC

Request Review

@vercel
vercel Bot temporarily deployed to Preview – octane-website September 3, 2026 21:20 Inactive

@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: Pure namespaces invoke callbacks unsafely
    • Added SETUP_CALLBACK_NAMESPACE_METHODS set for Array.from/JSON.parse/JSON.stringify/Object.groupBy and applied walkInvokedArgument to their callback-position arguments (index 1+), so opaque references now correctly fail closed and emit the setup checkpoint.

Create PR

Or push these changes by commenting:

@cursor push 2ea0aef45b
Preview (2ea0aef45b)
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
@@ -3918,7 +3918,7 @@
 	}
 }
 
-// ─────────────────────────────────────────────────────────────────────────────
+// ───────────────────────────────────────────────��─────────────────────────────
 // Dep-keyed hook-callback memoization (production compiles).
 //
 // The companion to the capture-free lift. A callback that DOES read component
@@ -4773,6 +4773,17 @@
 	'decodeURIComponent',
 ]);
 const SETUP_PURE_GLOBAL_NAMESPACES = new Set(['Math', 'JSON', 'Number', 'Object', 'Array', 'Date']);
+// Namespace methods that synchronously invoke a callback argument. The callback
+// is always at argument index 1; earlier arguments are data. A mapper, reviver,
+// replacer, or classifier passed by reference cannot be entered, so its body is
+// opaque and must fail closed the same way sync-factory hook arguments do.
+const SETUP_CALLBACK_NAMESPACE_METHODS = new Set([
+	'Array.from',
+	'Array.fromAsync',
+	'JSON.parse',
+	'JSON.stringify',
+	'Object.groupBy',
+]);
 
 // Every binding name the module declares anywhere. A global namespace shadowed
 // by any local, parameter, or import is treated as an unknown callee.
@@ -4876,7 +4887,15 @@
 				SETUP_PURE_GLOBAL_NAMESPACES.has(callee.object.name) &&
 				isGlobal(callee.object.name)
 			) {
-				walk(n.arguments, true);
+				if (
+					callee.property?.type === 'Identifier' &&
+					SETUP_CALLBACK_NAMESPACE_METHODS.has(callee.object.name + '.' + callee.property.name)
+				) {
+					if (n.arguments[0]) walk(n.arguments[0], true);
+					for (let i = 1; i < n.arguments.length; i++) walkInvokedArgument(n.arguments[i]);
+				} else {
+					walk(n.arguments, true);
+				}
 				return;
 			}
 			found = true;

diff --git a/packages/octane/tests/audit-hook-behavior.test.ts b/packages/octane/tests/audit-hook-behavior.test.ts
--- a/packages/octane/tests/audit-hook-behavior.test.ts
+++ b/packages/octane/tests/audit-hook-behavior.test.ts
@@ -581,6 +581,14 @@
 		expect(code).not.toContain(checkpoint);
 	});
 
+	it('omits the checkpoint for callback-accepting namespace methods with inline callbacks', () => {
+		const code = compiled(`
+			const mapped = Array.from(props.items, (x: any) => x.id);
+			const data = JSON.parse(props.text, (_k: string, v: any) => v);
+		`);
+		expect(code).not.toContain(checkpoint);
+	});
+
 	it.each([
 		[
 			'a setter called in setup',
@@ -605,6 +613,22 @@
 			'a shadowed global namespace',
 			`const Math = props.math;\nconst value = Math.max(props.n, 1);`,
 		],
+		[
+			'Array.from with a mapper passed by reference',
+			`const mapped = Array.from(props.items, props.mapper);`,
+		],
+		[
+			'JSON.parse with a reviver passed by reference',
+			`const data = JSON.parse(props.text, props.reviver);`,
+		],
+		[
+			'JSON.stringify with a replacer passed by reference',
+			`const text = JSON.stringify(props.data, props.replacer);`,
+		],
+		[
+			'Object.groupBy with a classifier passed by reference',
+			`const groups = Object.groupBy(props.items, props.classify);`,
+		],
 	])('keeps the checkpoint for %s', (_, body) => {
 		expect(compiled(body)).toContain(checkpoint);
 	});

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

Reviewed by Cursor Bugbot for commit 81f7a79. Configure here.

Comment thread packages/octane/src/compiler/compile.js Resolved
trueadm and others added 2 commits September 3, 2026 22:34
…point analysis

Array.from, JSON.parse/stringify callbacks, Object.groupBy, and similar can
run user code by reference. Keep an explicit member allowlist and check the
JSON callback positions like a hook factory.

Co-Authored-By: Claude Fable 5.1 <[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 perf PR: performance work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant