Repository navigation
feat(compiler): reject uncached useSyncExternalStore snapshots in Strong mode - #1498
Conversation
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]>
Octane evaluates queued updaters and reducers while their owner renders and can call one function more than once: a transition update is evaluated when it is staged and again when the transition renders, an urgent functional update made while a transition is held is applied to the committed value and rebased onto the held value, and useOptimistic re-applies its reducer on each pending render. An updater that fetches or reads the clock therefore repeats its side effect. Add OCTANE_STRONG_IMPURE_UPDATER. useState/useLinkedState updaters, useReducer reducers, and useOptimistic reducers (inline, local, or same-module) are visited with the existing render checks: impure calls, ambient and module reads, state updates, getter and Effect Event calls, and ref reads/writes are reported under the new code, as are fetch and scheduled timer, microtask, or promise callbacks. Mutating the state an updater or reducer receives reports OCTANE_STRONG_SNAPSHOT_MUTATION. Runtime tests pin the replay. Co-Authored-By: Claude Opus 5.5 <[email protected]>
After an await, or in a timer or promise callback, setCount(count + 1) reads the render snapshot of the state it writes, so overlapping events overwrite each other's updates. Strong mode accepted this even though the updater form and the state getter read the latest value. Add OCTANE_STRONG_STALE_STATE_UPDATE. The Strong visitor now distinguishes an `event` phase (a callback body whose invocation time is unknown) from a provably `deferred` one: code after an await every path reaches, and callbacks passed to unshadowed setTimeout/setInterval/requestAnimationFrame/ requestIdleCallback/queueMicrotask or to .then/.catch/.finally. A deferred setter or dispatch whose argument reads the same state's snapshot, including through a local computed before the await, a copied alias, or a closure, is an error. Synchronous handlers stay legal. Existing diagnostics are unchanged by the phase split; fixtures that relied on stale deferred updates now use the updater form. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A state tuple whose value and getter are never read exists only to force renders for an external source (`const [, force] = useState(0)`, or useReducer((x) => x + 1, 0)). It reads that source during render and subscribes afterwards, so a change in between is never rendered, and it has no server snapshot. Add OCTANE_STRONG_WRITE_ONLY_STATE in a standalone strong-write-only-state.js built on the shared Strong hook graph, so aliases, namespace imports, and shadowing agree with the other Strong analyses. A tuple is reported when its value is elided, unused, or read only inside its own setter's arguments, its getter is absent or unused, and its setter is referenced. The message names useSyncExternalStore. Existing fixtures that used write-only tuples as scaffolding now read their value. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ong mode
useSyncExternalStore compares snapshots with Object.is. A getSnapshot that
returns a new object on every call (`() => ({ a: store.a })`) makes every read
look like a store change: development warns once, then commit-time store
checks re-render until the update-depth limit throws and the tree unmounts.
Add OCTANE_STRONG_UNCACHED_STORE_SNAPSHOT in a standalone
strong-external-store.js on the shared Strong hook graph. It reports a
getSnapshot or getServerSnapshot whose every return provably allocates: an
object or array literal, .map/.filter-style array copies, Object.keys-style
results, standard constructors, or a same-module function or local constant
that does so. Runtime tests pin the update-depth failure and the stable
replacement. The docs also note that Strong caching does not cache an inline
subscribe, which therefore resubscribes on every render.
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 2 potential issues.
Autofix Details
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Defaulted snapshot params skip binding
- Added the missing bindSnapshotPattern call in the AssignmentPattern branch of visitParameters so destructured snapshot parameters with defaults are correctly bound.
- ✅ Fixed: useLinkedState literals lack shape
- Extended initialShape to handle useLinkedState by reading its initializer from argument index 1, so .push/.set/.add on linked state now report OCTANE_STRONG_SNAPSHOT_MUTATION.
Or push these changes by commenting:
@cursor push dc321df2ee
Preview (dc321df2ee)
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
@@ -2325,6 +2325,14 @@
bindStateGetterPattern(parameter.left, value, parameterScope, bindGetter);
bindAmbientPattern(parameter.left, value, parameterScope, bindGetter);
if (value?.kind === 'prop') bindPropPattern(parameter.left, bindGetter);
+ if (value?.kind === 'snapshot' && parameter.left.type !== 'Identifier') {
+ bindSnapshotPattern(
+ parameter.left,
+ value,
+ bindGetter,
+ snapshotPatternProperty(parameterScope),
+ );
+ }
parameter = parameter.left;
} else {
visitPatternExpressions(parameter, parameterScope, phase, value?.kind === 'ref', value);
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
@@ -231,8 +231,8 @@
* proof for known mutator methods, including nested literal properties.
*/
initialShape(hook, node, scope) {
- if (hook === 'useState') {
- const initial = unwrap(node.arguments?.[0]);
+ if (hook === 'useState' || hook === 'useLinkedState') {
+ const initial = unwrap(node.arguments?.[hook === 'useLinkedState' ? 1 : 0]);
if (!FUNCTIONS.has(initial?.type)) return literalShape(initial, scope);
const body = initial.body;
if (body?.type !== 'BlockStatement') return literalShape(body, scope);You can send follow-ups to the cloud agent here.
… 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]>
…-updaters # Conflicts: # packages/octane/tests/compiler/strong-state.test.ts
Bring in the snapshot-mutation review fixes (tuple and Effect Event helper arguments, defaulted parameters, linked-state shapes). Resolve the helper follow so deferred code still follows local helpers, while an Effect Event is followed only for the state it receives. An Effect Event reads the latest committed values, so a setter inside one is not computed from a stale render snapshot even when a timer or promise calls it. OCTANE_STRONG_STALE_STATE_UPDATE no longer reports inside Effect Event bodies, and the existing fixture that relied on the updater form for this case is restored. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up. The stale-update check skipped whole Effect Event bodies, which also hid a snapshot the caller passed after an await and timer or promise callbacks created inside the event. Only state the Effect Event captures is current: its own body treats those reads (and locals derived in the body) as fresh, while parameters are checked and nested deferred callbacks use the ordinary rule. Effect Event function scopes are marked while their bodies are visited, so captured and received values are told apart by lexical scope rather than by binding identity. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
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]>
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]>
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]>
|
Bugbot Autofix prepared a fix for the issue found in the latest run.
Or push these changes by commenting: Preview (a1df5caac0)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
@@ -2222,6 +2222,7 @@
function visitStatements(statements, scope, phase) {
let executionPhase = phase;
+ let savedEffectEventDepth = -1;
for (const statement of statements ?? []) {
visit(statement, scope, executionPhase);
if (
@@ -2239,8 +2240,13 @@
statementAlwaysAwaits(statement)
) {
executionPhase = 'deferred';
+ if (effectEventDepth > 0) {
+ savedEffectEventDepth = effectEventDepth;
+ effectEventDepth = 0;
+ }
}
}
+ if (savedEffectEventDepth !== -1) effectEventDepth = savedEffectEventDepth;
return executionPhase;
}
@@ -4118,21 +4124,21 @@
// A declaration does not execute a callback. Calls and callbacks
// passed to external work are visited separately with the effect.
const enclosingEffect = currentEffect;
+ const enclosingEffectEventDepth = effectEventDepth;
currentEffect = null;
try {
// A nested callback runs at an unknown later time. Only timer and
// promise callbacks, like code after an await, are provably deferred.
+ const deferredCallback = phase !== 'module' && statePolicy.isAsynchronousCallback(node);
+ if (deferredCallback) effectEventDepth = 0;
visitFunction(
node,
scope,
- phase === 'module'
- ? 'render'
- : statePolicy.isAsynchronousCallback(node)
- ? 'deferred'
- : 'event',
+ phase === 'module' ? 'render' : deferredCallback ? 'deferred' : 'event',
);
} finally {
currentEffect = enclosingEffect;
+ effectEventDepth = enclosingEffectEventDepth;
}
return;
}
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
@@ -698,6 +698,19 @@
).toBeNull();
});
+ it.each([
+ [
+ 'an update after await inside an Effect Event',
+ `export function A({ save }) { const [n, setN] = useState(0); const run = useEffectEvent(async () => { await save(); setN(n + 1); }); useEffect(() => { run(); }); return <b>{n}</b>; }`,
+ ],
+ [
+ 'a timer callback inside an Effect Event',
+ `export function A() { const [n, setN] = useState(0); const run = useEffectEvent(() => { setTimeout(() => setN(n + 1), 100); }); useEffect(() => { run(); }); return <b>{n}</b>; }`,
+ ],
+ ])('rejects %s', (_label, body) => {
+ expect(rejected(body)).toBe(STALE_STATE_UPDATE);
+ });
+
it('checks .tsrx components and plain .ts custom hooks', () => {
const tsrx = `"use strong";
import { useState } from 'octane';You can send follow-ups to the cloud agent here. |
…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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up. The Effect Event rule treated freshness lexically: every local derived in the event body counted as current, hiding `const next = value + 1` computed from a stale argument, while a helper or IIFE called synchronously from the body was checked as if it were deferred. Track it by value instead. Functions running synchronously inside an Effect Event invocation (the event body and helpers it calls) read captured state as current. A snapshot or derived value passed in from deferred code outside such a body is tagged stale, the tag follows member reads and destructuring, and a derived local is checked through its initializer. Only stale-tagged inputs are reported inside an Effect Event; nested timer and promise callbacks still use the ordinary rule. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…store snapshots Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
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: Stale tuples skip Effect Event check
- Added state-tuple handling to staleValue so that when a state-tuple is passed from deferred code into an Effect Event, its snapshot is copied with stale: true, ensuring OCTANE_STRONG_STALE_STATE_UPDATE correctly detects deferred reads through tuple destructuring or member access.
Or push these changes by commenting:
@cursor push d58a18ff1d
Preview (d58a18ff1d)
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
@@ -3796,9 +3796,11 @@
}
function staleValue(value) {
- return (value?.kind === 'snapshot' || value?.kind === 'derived-state') && value.stale !== true
- ? { ...value, stale: true }
- : value;
+ if ((value?.kind === 'snapshot' || value?.kind === 'derived-state') && value.stale !== true)
+ return { ...value, stale: true };
+ if (value?.kind === 'state-tuple' && value.snapshot?.stale !== true)
+ return { ...value, snapshot: { ...value.snapshot, stale: true } };
+ return value;
}
function visitFresh(value, origin, phase, args) {You can send follow-ups to the cloud agent here.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up. Deferred code that passed a whole state tuple into an Effect Event left its snapshot untagged, so `pair[0]` or a destructured value inside the event read as captured and skipped OCTANE_STRONG_STALE_STATE_UPDATE. Tag the tuple's snapshot stale like a snapshot or derived argument. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A helper or Effect Event argument computed from state, like `apply(n + 1)` or a derived local passed after an await, now carries that state into the callee, so a deferred update through it reports OCTANE_STRONG_STALE_STATE_UPDATE the way `setN(n + 1)` does. Effect Events are also entered for derived arguments, not only snapshots and tuples. Two strong-mode fixtures awaited the render snapshot into an inline callback that wrote it back; they now await a constant, and the snapshot shape is pinned as rejected. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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: Defaults drop derived-state arguments
- Added 'derived-state' to the preservation check in visitParameters alongside 'prop' and 'snapshot', so derived-state bindings are no longer downgraded to 'other' when the callee parameter has a default value.
Or push these changes by commenting:
@cursor push e31beee0e4
Preview (e31beee0e4)
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
@@ -2309,7 +2309,7 @@
// A default replaces only `undefined`; otherwise the parameter is the
// state value the updater, reducer, or helper received.
value =
- value?.kind === 'prop' || value?.kind === 'snapshot'
+ value?.kind === 'prop' || value?.kind === 'snapshot' || value?.kind === 'derived-state'
? value
: value.kind === 'constant' && value.primitive === undefined
? defaultValueYou can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 7d11680. Configure here.
A default replaces only `undefined`, so a parameter with a default that receives a value computed from state, like `(value = 0) => setN(value)` called as `apply(n + 1)` after an await, keeps that state the way a received snapshot already did. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
#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]>
#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]>
Brings in #1496 (stale deferred state updates), #1498 (uncached useSyncExternalStore snapshots), and #1490. Keeps both new compiler imports in strong-mode.js. The workaround ledger records that #1498 now rejects the fresh-snapshot viewport workaround (23 → 22 compiler gaps). Prompts, references, and alternatives are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>


Summary
Adds
OCTANE_STRONG_UNCACHED_STORE_SNAPSHOT: auseSyncExternalStoregetSnapshotorgetServerSnapshotthat provably returns a new object or array on every call.What the runtime does today: snapshots are compared with
Object.is. Development logs "The getSnapshot result must be cached…" once. The commit-time store check then re-renders until the update-depth guard throws "Maximum update depth exceeded" and the tree unmounts. The runtime test pins this. The compile error reports it before the component ever runs.Changes
strong-external-store.json the shared hook graph. It reports when every return allocates:.map,.filter, and other array copies that strings lack (.sliceand.concatare excluded because strings have them);Object.keys/values/entries/fromEntries,Array.from/of,structuredClone;getSnapshotdeclaration, or a local constant.subscribe(no codegen change): Strong declaration caching does not cache(cb) => store.subscribe(cb). It is not aconstdeclaration, anduseSyncExternalStoreis not a dependency hook, so it resubscribes on every render in both compat and Strong (a runtime test pins this). Caching it would need identity and invalidation evidence first. The docs recommend definingsubscribeoutside the component.octane, minor).Validation
At this commit (the full stack):
tests/compiler/strong-*.test.tsandbundler-compiler.test.ts(1,390 passed),tests/strong-state-runtime.test.tsinoctaneandoctane-prod(36 passed), and theoctane-signals-strongproject (237 passed).Whole-stack validation, run on the top of the stack (all five families) plus the harness fix:
pnpm format:checkpnpm typecheckpnpm 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.Risk / follow-ups
store.items ?? []are not reported, because not every return allocates; they still loop at runtime when the fallback is taken.Provenance
agent-authored)🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Note
Medium Risk
Expands Strong-mode static analysis with new rejections and refined stale/mutation tracking; misclassification could block valid patterns or miss edge cases, but changes are compile-time only with broad test coverage.
Overview
Adds
OCTANE_STRONG_UNCACHED_STORE_SNAPSHOT, a compile-time check that flagsuseSyncExternalStoregetSnapshot/getServerSnapshotcallbacks whose returns are provably fresh allocations (literals, spreads,.map/.filter,Object.keys, constructors, same-module helpers/constants, etc.), becauseObject.issnapshot comparison would cause infinite re-renders at runtime. New modulestrong-external-store.jsplugs into the existing Strong hook graph; docs, changesets, compiler tests, and a runtime test pin the update-depth failure.The same diff also tightens other Strong state rules: snapshot mutation is traced through whole state tuples passed to helpers (including destructured/default parameters), Effect Events invoked with state, and
useLinkedStatereconcilers that return literals;OCTANE_STRONG_STALE_STATE_UPDATEtreats Effect Event bodies and sync helpers as reading latest committed state (while still flagging snapshots/derived values passed in from deferred code or timers inside the event).Reviewed by Cursor Bugbot for commit bdf5748. Bugbot is set up for automated code reviews on this repo. Configure here.