Skip to content

feat(compiler): reject state mutation outside render in Strong mode - #1494

Closed
trueadm wants to merge 6 commits into
mainfrom
claude/sharp-heisenberg-c54a6a
Closed

trueadm wants to merge 6 commits into
mainfrom
claude/sharp-heisenberg-c54a6a

Conversation

@trueadm

@trueadm trueadm commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Update (2026-10-01): the original change in this PR is already in main. It landed with the squash of #1497, which carried the whole stack below it. After merging main, this PR carries only the review follow-ups: tuple and Effect Event helper arguments, defaulted parameters, and useLinkedState literal shapes, with a patch changeset (strong-mutation-helper-arguments).

Strong mode only rejected snapshot mutation while rendering. This adds OCTANE_STRONG_SNAPSHOT_MUTATION for mutations of a state value outside render: event handlers, effects, cleanup, timer/promise callbacks, and local helpers that receive the value. Render-time mutations keep OCTANE_STRONG_RENDER_SNAPSHOT_MUTATION.

"use strong";
const [items, setItems] = useState([]);
<button onClick={() => { items.push(1); setItems(items); }} />            // error
const [s, setS] = useState({ list: [] });
<button onClick={() => { s.list.push(1); setS({ ...s }); }} />           // error
useEffect(() => { s.list.push(1); });                                     // error

Why a new code instead of widening the render one: every RENDER_* code means "while rendering", and state updates already split by phase (RENDER_STATE_UPDATE / EFFECT_STATE_UPDATE). The failure and the fix also differ. Outside render, passing the same array back is an Object.is no-op, so nothing re-renders. A spread copy re-renders the owner, but identity-keyed consumers (a memo child) stay stale, and the mutation rewrites the value transitions and useOptimistic revert to. The fix is to pass a new value or keep the object in useRef.

Part of #1027. Stack (all target main; review only the top commit of each):

  1. This PR: state mutation outside render
  2. feat(compiler): require pure state updaters and reducers in Strong mode #1495: pure updaters and reducers
  3. feat(compiler): reject stale deferred state updates in Strong mode #1496: stale deferred updates
  4. feat(compiler): reject write-only state in Strong mode #1497: write-only state
  5. feat(compiler): reject uncached useSyncExternalStore snapshots in Strong mode #1498: uncached useSyncExternalStore snapshots

The benchmark harness fix is a separate PR, #1499.

Changes

  • New packages/octane/src/compiler/strong-state.js policy next to strong-mode.js, so the parallel Strong work has fewer merge conflicts. It is read-only and never annotates the AST.
  • strong-mode.js: the four snapshot-write sites and the mutator-call check report in every phase. A literal state initializer is now a structural proof for nested array properties, lazy and useReducer initial state, Map/Set created with new, and Object.assign/Reflect targets. These shapes also widen the existing render check. Destructured parameters bound to a snapshot are tracked, and local helpers called with a snapshot argument are followed.
  • Docs: new "State values, updaters, and subscriptions" section in docs/strong-compiler-checks.md, plus tsrx-basics.md and differences-from-react.md.
  • Changeset (octane, minor).

Validation

At this commit:

  • targeted tests: all tests/compiler/strong-*.test.ts and bundler-compiler.test.ts (1,283 passed), and tests/strong-state-runtime.test.ts in octane and octane-prod (8 passed). The new suite covers aliases, destructuring, member aliases, namespace imports, optional chains, shadowed Object/hooks, .tsrx, plain .ts hooks, Volar parity, unchanged client/server output, and likely agent rewrites (alias, destructure, helper, Object.assign before a spread).
  • Runtime evidence (compiled in compat mode): a mutated array passed back does not re-render; a memo child stays stale after a spread copy; after a failed Action, useOptimistic reverts to 'a,b' instead of 'a'; a mutation made in an effect never renders.

Whole-stack validation, run on the top of the stack (all five families) plus the harness fix:

  • pnpm format:check
  • pnpm typecheck
  • pnpm test: run as the 4 CI shards (vitest.ci-sharded.config.js, CI's excludes), because an unsharded local run OOMs the Vitest main process on this machine. 42,527 tests passed. Two load timeouts (website-mcp/tests/mcp-plumbing.test.ts, packages/testing-library/tests/octane-peer-minimum.test.ts) pass in isolation; no unhandled errors.
  • Before the stack was split, the existing Strong tests were rerun with the new codes filtered out: all 1,180 passed, so the analyzer changes moved no existing diagnostic.
  • Disabling each family's implementation turns that family's tests red.

Performance (whole stack): analyzer time rose ~12–13% on a dense 40-component state-heavy module, about 1% of full compile. In the official strong-compiler-checks audit, the byte-identical output controls and executed cache controls passed. Its timing ratios (Strong 0.96–1.19, compat controls 0.78–1.15) were taken under heavy external load, so they show no regression beyond noise but are not a precise measurement.

Risk / follow-ups

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
Touches Strong-mode dataflow in strong-mode.js / strong-state.js; mis-inference could add false positives or miss mutations outside render, but scope is bounded to known helper/tuple/default/useLinkedState shapes.

Overview
This PR tightens Strong mode follow-ups on OCTANE_STRONG_SNAPSHOT_MUTATION (state mutated outside render), on top of the behavior already on main.

The analyzer now flags mutations that flow through local helpers when the whole useState / hook tuple is passed in—including parameters that destructure [value, setValue]. The same applies when state is passed into an useEffectEvent invocation. Default parameter values on helpers, updaters, and reducers are wired so a snapshot binding is still tracked when the default expression is used.

For useLinkedState, a reconciler that returns a literal is treated like a lazy useState initializer: it can prove array, Map, and Set mutators on that state. Docs/changeset ship as patch strong-mutation-helper-arguments (octane patch).

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

Strong mode only rejected snapshot mutation while rendering. Mutating state in
an event handler, effect, cleanup, or deferred callback compiled cleanly, even
though passing the same array back to its setter is an Object.is no-op and
copying only the outer object leaves identity-based consumers stale and
rewrites the value transitions and useOptimistic revert to.

Add OCTANE_STRONG_SNAPSHOT_MUTATION for mutations outside render; render-time
mutations keep OCTANE_STRONG_RENDER_SNAPSHOT_MUTATION, following the existing
RENDER_/EFFECT_STATE_UPDATE split. Literal state initializers now act as a
structural proof for nested array properties, lazy and useReducer initial
state, Map/Set created with new, and Object.assign/Reflect targets. Local
helpers that receive a state value are followed. The check is read-only and
lives in a new strong-state.js policy next to strong-mode.js.

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 2 potential issues.

Autofix Details

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Helper follow skips state tuples
    • Added value?.kind === 'state-tuple' alongside 'snapshot' in the deferred-phase argument filter so that passing a full useState/useReducer tuple to a helper from an event handler correctly re-walks the helper body and catches snapshot mutations.
  • ✅ Fixed: Effect Event helpers skip snapshots
    • Added unwrapping of effect-event to its inner callback before the kind check so that useEffectEvent results receiving snapshot arguments in deferred contexts are properly re-walked for mutation detection.

Create PR

Or push these changes by commenting:

@cursor push f743029e6c
Preview (f743029e6c)
diff --git a/packages/octane/src/compiler/strong-mode.js b/packages/octane/src/compiler/strong-mode.js
--- a/packages/octane/src/compiler/strong-mode.js
+++ b/packages/octane/src/compiler/strong-mode.js
@@ -4477,10 +4477,13 @@
 					}
 				} else if (hook === null) {
 					// Any helper can write to a state value passed to it.
-					const callback = callableValue(callee, scope);
+					let callback = callableValue(callee, scope);
+					if (callback?.kind === 'effect-event') callback = callback.callback;
 					if (callback?.kind === 'callback' || callback?.kind === 'callback-choice') {
 						const args = argumentValues(node.arguments, scope);
-						if (args?.some((value) => value?.kind === 'snapshot')) {
+						if (
+							args?.some((value) => value?.kind === 'snapshot' || value?.kind === 'state-tuple')
+						) {
 							visitCallable(callback, callee, executionPhase, args);
 						}
 					}

diff --git a/packages/octane/tests/compiler/strong-state.test.ts b/packages/octane/tests/compiler/strong-state.test.ts
--- a/packages/octane/tests/compiler/strong-state.test.ts
+++ b/packages/octane/tests/compiler/strong-state.test.ts
@@ -162,6 +162,14 @@
 			'Object.assign before a spread',
 			`export function A() { const [s, setS] = useState({ list: [] }); return <b onClick={() => { Object.assign(s, { list: [...s.list, 1] }); setS({ ...s }); }}>{s.list.length}</b>; }`,
 		],
+		[
+			'a helper receiving the full state tuple',
+			`function mutate(pair) { pair[0].push(1); pair[1]([...pair[0]]); } export function A() { const tuple = useState([]); return <b onClick={() => mutate(tuple)}>{tuple[0].length}</b>; }`,
+		],
+		[
+			'a useEffectEvent receiving a snapshot parameter',
+			`export function A() { const [items, setItems] = useState([]); const handler = useEffectEvent((list) => { list.push(1); }); return <b onClick={() => handler(items)}>{items.length}</b>; }`,
+		],
 	])('rejects the rewrite through %s', (_label, body) => {
 		expect(rejected(body)).toBe(SNAPSHOT_MUTATION);
 	});

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

trueadm and others added 2 commits October 1, 2026 10:28
… in Strong mutation checks

Review follow-up. Outside render, a local helper was followed only when an
argument was a snapshot, so passing the whole state tuple, or calling an
Effect Event with the state, escaped OCTANE_STRONG_SNAPSHOT_MUTATION. A
parameter with a default also lost its snapshot binding, although a default
replaces only `undefined`. A useLinkedState reconciler that returns a literal
now supplies the same structural proof as a lazy useState initializer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The original #1494–#1497 content landed in main through the squash of #1497.
Resolve against main so this branch carries only the snapshot-mutation review
fixes: tuple and Effect Event helper arguments, defaulted parameters, and
useLinkedState literal shapes. The fix gets its own patch changeset instead of
editing the released-pending one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 1, 2026
The original updater check landed in main through the squash of #1497. This
branch now carries the #1494 follow-ups plus its own regression tests for a
destructured updater parameter with a default and a defaulted reducer state
parameter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 1, 2026
The original stale-update check landed in main through the squash of #1497,
without its Effect Event follow-ups. Resolve against main so this branch
carries the #1494/#1495 follow-ups plus the Effect Event rule: state an
Effect Event captures is current in its own body, while arguments and nested
deferred callbacks are still checked. The fix gets its own patch changeset.

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.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Tuple params skip snapshot destructure
    • Added ArrayPattern and ObjectPattern decomposition for state-tuple parameters in visitParameters, mirroring bindDeclarationValue's logic to bind index 0 as snapshot and index 1 as setter, so destructured tuple parameters are no longer left as OTHER_BINDING.

Create PR

Or push these changes by commenting:

@cursor push 72eb028689
Preview (72eb028689)
diff --git a/packages/octane/src/compiler/strong-mode.js b/packages/octane/src/compiler/strong-mode.js
--- a/packages/octane/src/compiler/strong-mode.js
+++ b/packages/octane/src/compiler/strong-mode.js
@@ -2336,6 +2336,42 @@
 			if (value?.kind === 'snapshot' && parameter.type !== 'Identifier') {
 				bindSnapshotPattern(parameter, value, bindGetter, snapshotPatternProperty(parameterScope));
 			}
+			if (value?.kind === 'state-tuple' && parameter.type !== 'Identifier') {
+				if (parameter.type === 'ArrayPattern') {
+					bindSnapshotPattern(
+						parameter.elements?.[0],
+						value.snapshot,
+						bindGetter,
+						snapshotPatternProperty(parameterScope),
+					);
+					const setterElement = parameter.elements?.[1];
+					bindGetter(
+						setterElement?.type === 'AssignmentPattern' ? setterElement.left : setterElement,
+						value.setter,
+					);
+				} else if (parameter.type === 'ObjectPattern') {
+					for (const property of parameter.properties ?? []) {
+						if (property.type !== 'Property') continue;
+						const key = property.computed
+							? staticPrimitiveValue(property.key, parameterScope)
+							: property.key?.type === 'Identifier'
+								? property.key.name
+								: property.key?.value;
+						const pv = property.value;
+						const setter = pv?.type === 'AssignmentPattern' ? pv.left : pv;
+						if ((key === 1 || key === '1') && setter?.type === 'Identifier') {
+							bindGetter(setter, value.setter);
+						} else if (key === 0 || key === '0') {
+							bindSnapshotPattern(
+								pv,
+								value.snapshot,
+								bindGetter,
+								snapshotPatternProperty(parameterScope),
+							);
+						}
+					}
+				}
+			}
 			if (parameter.type === 'Identifier' && !isReassigned(parameter)) {
 				parameterScope.bindings.set(parameter.name, value);
 			}

diff --git a/packages/octane/tests/compiler/strong-state.test.ts b/packages/octane/tests/compiler/strong-state.test.ts
--- a/packages/octane/tests/compiler/strong-state.test.ts
+++ b/packages/octane/tests/compiler/strong-state.test.ts
@@ -367,6 +367,10 @@
 			`function add(pair) { pair[0].push(1); } export function A() { const tuple = useState([]); return <b onClick={() => { add(tuple); tuple[1]([...tuple[0]]); }}>{tuple[0].length}</b>; }`,
 		],
 		[
+			'a destructured tuple parameter in a helper',
+			`function add([list]) { list.push(1); } export function A() { const tuple = useState([]); return <b onClick={() => { add(tuple); tuple[1]([...tuple[0]]); }}>{tuple[0].length}</b>; }`,
+		],
+		[
 			'an Effect Event called with the state',
 			`export function A() { const [items, setItems] = useState([]); const add = useEffectEvent((list) => { list.push(1); }); return <b onClick={() => { add(items); setItems([...items]); }}>{items.length}</b>; }`,
 		],

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

trueadm added a commit that referenced this pull request Oct 1, 2026
main now contains #1494–#1497 and the benchmark fix (#1499). Resolve against
the updated #1496 branch so this PR carries the uncached useSyncExternalStore
snapshot check on top of the open review follow-ups.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…checks

Review follow-up. A helper or Effect Event entered with a whole state tuple
left a destructured tuple parameter (`([items, setItems]) =>` or
`({ 0: items })`) unbound, so mutations through it escaped
OCTANE_STRONG_SNAPSHOT_MUTATION. Bind index 0 to the state value and index 1
to the setter, as declarations already do; a default replaces only undefined.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 1, 2026
trueadm added a commit that referenced this pull request Oct 1, 2026
Review follow-up. An Effect Event entered because it receives a state value
was visited in its caller's phase, so from deferred code its captured state
was checked as a stale render snapshot, although an Effect Event reads the
latest committed values. Visit its body as a synchronous callback: mutations
are still reported, and awaits or timers inside it remain deferred.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 1, 2026
trueadm added a commit that referenced this pull request Oct 1, 2026
Keep the value-based Effect Event model here: the followed body runs in the caller's phase with captured state treated as current and deferred arguments tagged stale.

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: Effect Event skips stale argument updates
    • Added a boundary-aware stale check that fires during Effect Event body visits with 'event' phase, using the callback's parent scope as a boundary so captures (fresh) are excluded while argument-bound parameters (stale) are checked.

Create PR

Or push these changes by commenting:

@cursor push 25acfb0083
Preview (25acfb0083)
diff --git a/packages/octane/src/compiler/strong-mode.js b/packages/octane/src/compiler/strong-mode.js
--- a/packages/octane/src/compiler/strong-mode.js
+++ b/packages/octane/src/compiler/strong-mode.js
@@ -1536,6 +1536,7 @@
 	// Updaters and reducers run while their owner renders, and deferred code
 	// reads a render snapshot that later updates may already have replaced.
 	let insidePureCallback = false;
+	let effectEventStaleScope = null;
 	const statePolicy = createStrongStatePolicy({
 		report,
 		resolve,
@@ -4473,6 +4474,8 @@
 				if (hook === null) {
 					if (executionPhase === 'deferred') {
 						statePolicy.checkStaleUpdate(callee, node.arguments, scope);
+					} else if (effectEventStaleScope !== null) {
+						statePolicy.checkStaleUpdate(callee, node.arguments, scope, effectEventStaleScope);
 					}
 					if (insidePureCallback && executionPhase === 'render') {
 						statePolicy.checkPureCall(callee, scope);
@@ -4625,7 +4628,12 @@
 							(executionPhase === 'deferred' && !effectEvent) ||
 							args?.some((value) => value?.kind === 'snapshot' || value?.kind === 'state-tuple')
 						) {
+							const prevEEScope = effectEventStaleScope;
+							if (effectEvent && executionPhase === 'deferred' && callback?.kind === 'callback') {
+								effectEventStaleScope = callback.scope;
+							}
 							visitCallable(callback, callee, effectEvent ? 'event' : executionPhase, args);
+							effectEventStaleScope = prevEEScope;
 						}
 					}
 				}

diff --git a/packages/octane/src/compiler/strong-state.js b/packages/octane/src/compiler/strong-state.js
--- a/packages/octane/src/compiler/strong-state.js
+++ b/packages/octane/src/compiler/strong-state.js
@@ -130,7 +130,16 @@
 		hookOf,
 	} = api;
 	const asynchronousCallbacks = new WeakSet();
+	let activeStaleCheckBoundary = null;
 
+	function resolvesBelowBoundary(scope, name) {
+		for (let s = scope; s; s = s.parent) {
+			if (s === activeStaleCheckBoundary) return false;
+			if (s.bindings.has(name)) return true;
+		}
+		return false;
+	}
+
 	function unshadowed(node, scope, names) {
 		const value = unwrap(node);
 		return value?.type === 'Identifier' &&
@@ -297,18 +306,24 @@
 		},
 
 		/** Report a deferred setter or dispatch computed from its own render snapshot. */
-		checkStaleUpdate(callee, args, scope) {
-			for (const setter of setterValues(callableValue(callee, scope))) {
-				for (const argument of args ?? []) {
-					const read = readsState(argument, scope, setter.state, new Set());
-					if (read === null) continue;
-					report(
-						STRONG_STALE_STATE_UPDATE,
-						read,
-						hookOf(setter.state) === 'useReducer' ? STALE_REDUCER_MESSAGE : STALE_MESSAGE,
-					);
-					break;
+		checkStaleUpdate(callee, args, scope, boundary = null) {
+			const prev = activeStaleCheckBoundary;
+			activeStaleCheckBoundary = boundary;
+			try {
+				for (const setter of setterValues(callableValue(callee, scope))) {
+					for (const argument of args ?? []) {
+						const read = readsState(argument, scope, setter.state, new Set());
+						if (read === null) continue;
+						report(
+							STRONG_STALE_STATE_UPDATE,
+							read,
+							hookOf(setter.state) === 'useReducer' ? STALE_REDUCER_MESSAGE : STALE_MESSAGE,
+						);
+						break;
+					}
 				}
+			} finally {
+				activeStaleCheckBoundary = prev;
 			}
 		},
 	};
@@ -392,9 +407,21 @@
 		if (node == null || node.type?.startsWith('TS')) return null;
 		switch (node.type) {
 			case 'Identifier':
+				if (activeStaleCheckBoundary !== null && !resolvesBelowBoundary(scope, node.name)) {
+					return null;
+				}
 				return readsBinding(resolve(scope, node.name), state, active) ? node : null;
 			case 'MemberExpression':
-				if (snapshotBinding(node, scope)?.state === state) return node;
+				if (snapshotBinding(node, scope)?.state === state) {
+					if (activeStaleCheckBoundary !== null) {
+						let root = node;
+						while (root?.type === 'MemberExpression') root = unwrap(root.object);
+						if (root?.type === 'Identifier' && !resolvesBelowBoundary(scope, root.name)) {
+							break;
+						}
+					}
+					return node;
+				}
 				return (
 					readsState(node.object, scope, state, active) ??
 					(node.computed ? readsState(node.property, scope, state, active) : null)

diff --git a/packages/octane/tests/compiler/strong-state.test.ts b/packages/octane/tests/compiler/strong-state.test.ts
--- a/packages/octane/tests/compiler/strong-state.test.ts
+++ b/packages/octane/tests/compiler/strong-state.test.ts
@@ -630,6 +630,10 @@
 			'a tuple index',
 			`export function A({ save }) { const tuple = useState(0); return <b onClick={async () => { await save(); tuple[1](tuple[0] + 1); }}>{tuple[0]}</b>; }`,
 		],
+		[
+			'an Effect Event that writes its argument back to the same state',
+			`export function A({ save }) { const [items, setItems] = useState([]); const add = useEffectEvent((list) => { setItems([...list, 1]); }); return <b onClick={async () => { await save(); add(items); }}>{items.length}</b>; }`,
+		],
 	])('rejects %s', (_label, body) => {
 		expect(rejected(body)).toBe(STALE_STATE_UPDATE);
 	});

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

Reviewed by Cursor Bugbot for commit 533950f. Configure here.

#1498 and #1496 landed on main carrying this branch's follow-ups, so the
strong-mode.js conflict resolves to main's version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@trueadm

trueadm commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: everything this PR carried landed on main through the #1498 squash merge (752028d), followed by #1496 (48b405c). After merging main, this branch has no changes left.

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.

1 participant