Repository navigation
feat(compiler): reject stale deferred state updates in Strong mode - #1496
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]>
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: Defaults skip updater snapshot binding
- Added the missing bindSnapshotPattern call in the AssignmentPattern branch of visitParameters so destructured parameters with defaults are properly marked as snapshots, matching the existing else branch.
Or push these changes by commenting:
@cursor push 7b54734240
Preview (7b54734240)
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
@@ -2323,6 +2323,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);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]>
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]>
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]>
…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]>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
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: Tuple args skip Effect Event stale tags
- Extended staleValue to propagate stale into a state-tuple's inner snapshot so that bindTuplePattern binds a stale-tagged snapshot inside Effect Events, restoring the OCTANE_STRONG_STALE_STATE_UPDATE diagnostic.
Or push these changes by commenting:
@cursor push d293b32824
Preview (d293b32824)
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
@@ -3795,6 +3795,10 @@
}
function staleValue(value) {
+ if (value?.kind === 'state-tuple') {
+ const snapshot = staleValue(value.snapshot);
+ return snapshot !== value.snapshot ? { ...value, snapshot } : value;
+ }
return (value?.kind === 'snapshot' || value?.kind === 'derived-state') && value.stale !== true
? { ...value, stale: true }
: 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
@@ -641,6 +641,14 @@
'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>; }`,
],
+ [
+ 'a tuple passed to an Effect Event after await',
+ `export function A({ save }) { const tuple = useState(0); const apply = useEffectEvent((t) => t[1](t[0] + 1)); return <b onClick={async () => { await save(); apply(tuple); }}>{tuple[0]}</b>; }`,
+ ],
+ [
+ 'a destructured tuple passed to an Effect Event after await',
+ `export function A({ save }) { const tuple = useState(0); const apply = useEffectEvent(([n, setN]) => setN(n + 1)); return <b onClick={async () => { await save(); apply(tuple); }}>{tuple[0]}</b>; }`,
+ ],
])('rejects %s', (_label, body) => {
expect(rejected(body)).toBe(STALE_STATE_UPDATE);
});You can send follow-ups to the cloud agent here.
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]>
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]>
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]>
|
Bugbot Autofix prepared a fix for the issue found in the latest run.
Or push these changes by commenting: Preview (7435403d8f)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
@@ -2655,7 +2655,14 @@
// initializer check.
const states =
declaration.id?.type === 'Identifier' ? projectedStates(initial, scope) : null;
- if (states !== null) bind(declaration.id, { kind: 'derived-state', states, prop });
+ if (states !== null)
+ bind(declaration.id, {
+ kind: 'derived-state',
+ states,
+ prop,
+ init: initial,
+ initScope: scope,
+ });
else if (prop) bindPropPattern(declaration.id, bind);
}
}
@@ -3263,7 +3270,11 @@
// Prop-state intent belongs to the component's own initializer. A
// helper's parameter is supplied by callers, independently of spelling.
if (value?.kind === 'prop') return OTHER_BINDING;
- if (value?.kind === 'derived-state' && value.prop) return { ...value, prop: false };
+ if (value?.kind === 'derived-state') {
+ if (value.prop) return { kind: 'derived-state', states: value.states, prop: false };
+ if (value.init != null)
+ return { kind: 'derived-state', states: value.states, prop: value.prop };
+ }
return value;
});
}
@@ -4624,7 +4635,12 @@
const args = argumentValues(node.arguments, scope);
if (
(executionPhase === 'deferred' && !effectEvent) ||
- args?.some((value) => value?.kind === 'snapshot' || value?.kind === 'state-tuple')
+ args?.some(
+ (value) =>
+ value?.kind === 'snapshot' ||
+ value?.kind === 'state-tuple' ||
+ value?.kind === 'derived-state',
+ )
) {
if (effectEvent) visitEffectEventCallback(callback, callee, executionPhase, args);
else visitCallable(callback, callee, executionPhase, args);
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
@@ -322,11 +322,12 @@
};
// In an Effect Event's own body, state captured from the component is the
- // latest committed value. A parameter can still carry a stale snapshot; a
- // local derived inside the body is treated as current.
+ // latest committed value. Variables defined at or inside the Effect Event
+ // boundary are checked normally; derived locals trace through their
+ // initializers in readsState so that captured-state derivations stay fresh
+ // while parameter-derived locals are flagged.
function freshRead(scope, name) {
if (!freshCaptures) return false;
- if (resolve(scope, name)?.kind === 'derived-state') return true;
for (let current = resolveScope(scope, name); current != null; current = current.parent) {
if (current.effectEventBoundary === true) return false;
}
@@ -417,9 +418,14 @@
const node = unwrap(value);
if (node == null || node.type?.startsWith('TS')) return null;
switch (node.type) {
- case 'Identifier':
+ case 'Identifier': {
if (freshRead(scope, node.name)) return null;
- return readsBinding(resolve(scope, node.name), state, active) ? node : null;
+ const binding = resolve(scope, node.name);
+ if (freshCaptures && binding?.kind === 'derived-state' && binding.init != null) {
+ return readsState(binding.init, binding.initScope, state, active);
+ }
+ return readsBinding(binding, state, active) ? node : null;
+ }
case 'MemberExpression': {
const root = memberRoot(node);
if (You can send follow-ups to the cloud agent here. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Bugbot Autofix is ON. A cloud agent has been kicked off to fix the reported issue. You can view the agent here.
Reviewed by Cursor Bugbot for commit 13dafdb. 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_STALE_STATE_UPDATE: a setter or dispatch argument may not read the same state's render snapshot after anawait, or inside a timer or promise callback.Why: overlapping events compute from the same snapshot and overwrite each other. The runtime tests count two overlapping saves (and two overlapping timers) as
1withsetN(n + 1)and2withsetN((current) => current + 1). The message names the updater form and the state getter (the third tuple member). This mirrorsOCTANE_STRONG_RENDER_STATE_GETTER_CALL: render reads the snapshot, deferred code reads the latest value.Changes
The Strong visitor gains an
eventphase, for a callback body whose invocation time is unknown.deferrednow means provably asynchronous:awaitthat every path reaches;setTimeout,setInterval,requestAnimationFrame,requestIdleCallback, orqueueMicrotask(also throughwindow/globalThis);.then,.catch, or.finally.Every existing check treats
eventexactly as it treateddeferred, and the earlier full-suite run showed no existing diagnostic moved.The snapshot read is followed through a local computed before the
await, a copied alias, a closure such assetN(() => n + 1), named timer callbacks, and helpers called after theawait.Existing fixtures: ~45
strong-mode.test.tsfixtures usedsetCount(count + 1)after an await or in a timer or promise callback, which is genuinely stale under this rule. They now usesetCount((current) => current + 1), which preserves each test's phase-precision intent.Docs and changeset (
octane, minor).Validation
At this commit:
tests/compiler/strong-*.test.tsandbundler-compiler.test.ts(1,354 passed), andtests/strong-state-runtime.test.tsinoctaneandoctane-prod(24 passed). Likely agent rewrites are covered: hoistingconst next = n + 1before the await, copying the snapshot, an updater that ignores its argument, and an updater that adds the snapshot.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
const later = setTimeout), and subscription callbacks are not reported..then/.catch/.finallyis treated as asynchronous on any receiver, the same promise-continuation shape the existing fetch analysis uses.Provenance
agent-authored)🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Note
Medium Risk
Changes static analysis in the Strong compiler visitor; misclassification could add false positives or miss stale updates, but runtime behavior is unchanged.
Overview
Strong mode tightens snapshot-mutation and stale-deferred-update analysis while fixing Effect Event false positives.
Snapshot mutations now flag in-place writes when a whole
useStatetuple (including destructured parameters) is passed to a local helper oruseEffectEvent, when updater/reducer/helper parameters use default values that receive state, and whenuseLinkedState’s reconciler returns a literal—so array/Map/Setmutators on that state stay provable like lazyuseStateinitializers. Stale tags propagate through destructuring viachildSnapshot/bindTuplePattern.OCTANE_STRONG_STALE_STATE_UPDATEtreats Effect Events as reading latest committed state: captures in the event body and sync helpers it calls are no longer stale, but arguments passed from deferred code (afterawait, timers, promises)—includingn + 1, derived locals, forwarded tuples, and callbacks created inside the event—are still checked. Docs instrong-compiler-checks.mddescribe this split.Tests and patch changesets (
strong-mutation-helper-arguments,strong-stale-effect-events) cover the new rejections and legal timer/promise Effect Event usage.Reviewed by Cursor Bugbot for commit 27bc5eb. Bugbot is set up for automated code reviews on this repo. Configure here.