Repository navigation
feat(octane): $$stable — compiler-proven props-snapshot bailout for components - #1214
jonkwheeler wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 5 potential issues.
Bugbot Autofix prepared fixes for all 5 issues found in the latest run.
- ✅ Fixed: Ancestor bails strand descendant updates
- suppressedUpdate now bubbles to ancestors and is also set when drainQueue drops a child for a hidden-try retry, so a $$stable parent cannot keep the pre-abort DOM while the child cell holds the write.
- ✅ Fixed: Opaque local tags get stable stamps
- The $$stable structure walk now fails closed on identifier tags that are not same-module components, memo walls, or proven context bindings, matching the import gate.
- ✅ Fixed: Scoped child blocks skip bail proof
- Nested @{ } bodies are classified as render-position work and their free names are collected, so module reads and useFormStatus reject the parent stamp.
- ✅ Fixed: Bail-safety uses fixed-point rescans
- bailSafe transitivity now uses a reverse-edge worklist seeded with already-unsafe names instead of rescanning every candidate until a fixed point.
- ✅ Fixed: Value-position compares skip ancestor flags
- childSlot now shares markCompareInChain with componentSlot so a value-position memo or lazy compare taints ancestors before they can bail.
Or push these changes by commenting:
@cursor push ae528b67a0
Preview (ae528b67a0)
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
@@ -3974,7 +3974,7 @@
// Block scope — hoist `var`/`function` + pre-collect `let`/`const` so
// forward references work the same way they do at runtime.
- if (t === 'BlockStatement') {
+ if (t === 'BlockStatement' || t === 'JSXCodeBlock') {
const newScope = new Set(scope);
for (const stmt of n.body || []) {
if (stmt.type === 'VariableDeclaration') {
@@ -3984,6 +3984,7 @@
}
}
walk(n.body, newScope);
+ if (t === 'JSXCodeBlock') walk(n.render, newScope);
return;
}
@@ -6687,13 +6688,13 @@
if (containsDeferredRefRead(n)) found = true;
return;
}
- // An `@{ }` scoped child lowers to a nested function value invoked by the
- // hole machinery — the same deferred shape as the explicit `() => @{ }`
- // spelling — so `$$stable` classifies its internals as child-render work
- // rather than this component's render. Non-stable callsites keep walking
- // it: their region guard already skips the child with everything else.
- if (stable && t === 'JSXCodeBlock') {
- if (containsDeferredRefRead(n)) found = true;
+ // An `@{ }` scoped child is invoked by the hole machinery on every parent
+ // render. A bailed parent keeps the last hole output, so the nested body
+ // is render-position work for `$$stable` — walk it rather than treating
+ // it as a deferred callback. The explicit `() => @{ }` spelling stays
+ // deferred through the function-value arm above.
+ if (t === 'JSXCodeBlock' && containsDeferredRefRead(n)) {
+ found = true;
return;
}
if (
@@ -6882,7 +6883,25 @@
return;
}
const name = tag?.name;
+ // A component tag bound from props or another local (`const C =
+ // props.comp`) is the same opacity as an import: it is not a free
+ // name, so the admission pass never sees it, and a stamp would keep
+ // an unproven callee. Fail closed unless the identifier is a
+ // same-module component, proven context, or memo() wall.
if (
+ stable &&
+ (tag?.type === 'Identifier' || tag?.type === 'JSXIdentifier') &&
+ typeof name === 'string' &&
+ !/^[a-z]/.test(name) &&
+ !name.includes('-') &&
+ !ctx?.componentInfo?.has(name) &&
+ !ctx?.defaultMemoBindings?.has(name) &&
+ !ctx?.provenContextBindings?.has(name)
+ ) {
+ found = true;
+ return;
+ }
+ if (
name === 'Suspense' ||
name === 'ErrorBoundary' ||
name === 'ViewTransition' ||
@@ -6930,10 +6949,7 @@
if (
t === 'ArrowFunctionExpression' ||
t === 'FunctionExpression' ||
- t === 'FunctionDeclaration' ||
- // A nested `@{ }` scoped child is a deferred function value too — the
- // lowering emits it as a sibling `__tsrx$N` passed to the hole machinery.
- t === 'JSXCodeBlock'
+ t === 'FunctionDeclaration'
) {
deferred.add(n);
return;
@@ -10895,7 +10911,7 @@
info.stableBody = stableBody;
info.bailSafe = bailSafeBody;
info.stableComponentDeps = bailSafeBody ? [...new Set(stableComponentDeps)].sort() : [];
- info.stable = false; // stamped only after the bailSafe fixed point below
+ info.stable = false; // stamped only after bailSafe reverse-edge propagation
// Hookless check.
// Return-JSX functions reconcile their returned descriptor through
// renderBlock. componentSlotLite intentionally ignores return values, so
@@ -11036,23 +11052,37 @@
// `$$stable` bail-safety is transitive over same-module component edges: a
// bailed parent keeps the child's committed subtree, which is only equivalent
// to re-rendering when the child is itself bail-safe — pure modulo
- // runtime-tracked context reads. Iterate to a fixed point so declaration
- // order cannot matter and recursive components fail closed, then stamp the
- // strict bodies whose deps are all bail-safe.
- let bailSafeChanged = true;
- while (bailSafeChanged) {
- bailSafeChanged = false;
- for (const [, info] of ctx.componentInfo) {
- if (!info.bailSafe) continue;
- for (const name of info.stableComponentDeps) {
- if (ctx.componentInfo.get(name)?.bailSafe !== true) {
- info.bailSafe = false;
- bailSafeChanged = true;
- break;
- }
+ // runtime-tracked context reads. Work flows from an unsafe callee to its
+ // dependents so declaration order cannot turn an A → B → C chain into one
+ // whole-map scan per edge, and already-unsafe seeds are not re-propagated.
+ const bailSafeDependents = new Map();
+ const bailSafeQueue = [];
+ for (const [name, info] of ctx.componentInfo) {
+ if (!info.bailSafe) {
+ bailSafeQueue.push(name);
+ continue;
+ }
+ for (const dependency of info.stableComponentDeps) {
+ let dependents = bailSafeDependents.get(dependency);
+ if (dependents === undefined) {
+ bailSafeDependents.set(dependency, (dependents = []));
}
+ dependents.push(name);
+ if (ctx.componentInfo.get(dependency)?.bailSafe !== true && info.bailSafe) {
+ info.bailSafe = false;
+ bailSafeQueue.push(name);
+ }
}
}
+ for (let index = 0; index < bailSafeQueue.length; index++) {
+ const name = bailSafeQueue[index];
+ for (const dependent of bailSafeDependents.get(name) ?? []) {
+ const info = ctx.componentInfo.get(dependent);
+ if (!info?.bailSafe) continue;
+ info.bailSafe = false;
+ bailSafeQueue.push(dependent);
+ }
+ }
for (const [, info] of ctx.componentInfo) {
info.stable =
info.stableBody === true &&
diff --git a/packages/octane/src/runtime.ts b/packages/octane/src/runtime.ts
--- a/packages/octane/src/runtime.ts
+++ b/packages/octane/src/runtime.ts
@@ -2744,10 +2744,11 @@
}
/**
- * True when a transition/urgent update targeted at this block was rolled back
- * and is still waiting to re-apply. Held entries re-apply inside the state hook
- * during render, so a memo/stable bail that skips the body would strand the
- * pending value while keeping the rolled-back DOM — the bail must decline.
+ * True when a transition/urgent update targeted at this block — or a descendant
+ * that owns the state cells — was rolled back and is still waiting to re-apply.
+ * Held entries re-apply inside the child's state hook during render, so a
+ * memo/stable ancestor bail that skips the body would strand the pending value
+ * while keeping the rolled-back DOM — the bail must decline.
*/
function blockHasHeldUpdate(block: Block): boolean {
const rootHeld = block.idState.renderOwner?.transition;
@@ -2761,7 +2762,7 @@
if (entries === undefined) return false;
for (const entry of entries) {
if (
- entry.block === block &&
+ (entry.block === block || blockIsAncestorOf(block, entry.block)) &&
!entry.superseded &&
Object.is(entry.slot.value, entry.baseValue)
)
@@ -2776,6 +2777,20 @@
return false;
}
+/**
+ * A queued update dropped by an aborted transaction must be consumed by a
+ * later body re-run. The store write lives on this block, but a $$stable /
+ * memo ancestor with clean props would otherwise keep the committed subtree
+ * and never re-enter here — mark the whole ancestor chain so those bails
+ * decline. Cleared per block at the top of renderBlockInner.
+ */
+function markSuppressedUpdate(block: Block): void {
+ for (let b: Block | null = block; b !== null; b = b.parentBlock) {
+ if (b.suppressedUpdate === true) break;
+ b.suppressedUpdate = true;
+ }
+}
+
function cancelHeldTransitionUpdate(slot: TransitionActionSlot<unknown>, block: Block): boolean {
if (!urgentTransitionCellUpdate(block)) return false;
const rootHeld = block.idState.renderOwner?.transition;
@@ -3314,7 +3329,7 @@
releaseTransitionHookHolder(owner);
}
-// ─────────────────────────────────────────────────────────────────────────────
+// ───────────────────────��─────────────────────────────────────────────────────
// Transition binding journal.
//
// Rendering and mutating happen in one walk, so a transition render patches a
@@ -6786,9 +6801,10 @@
// Once one suspends, later siblings must not publish a partial screen.
const rootTransaction = block.idState.renderOwner?.transaction;
if (rootTransaction?.aborted === true) {
- // The update is deferred to the resolve pass — flag it so a memo/
- // stable/implicit bail cannot skip the body that consumes it.
- block.suppressedUpdate = true;
+ // The update is deferred to the resolve pass — flag this block and its
+ // ancestors so a memo/stable/implicit bail cannot skip the body that
+ // would re-enter the child and consume the store write.
+ markSuppressedUpdate(block);
continue;
}
const retired = rootTransaction?.retired;
@@ -6798,7 +6814,10 @@
// roots with an actual deferred deletion pay this ancestor walk.
let current: Block | null = block;
while (current !== null && !retired.has(current)) current = current.parentBlock;
- if (current !== null) continue;
+ if (current !== null) {
+ markSuppressedUpdate(block);
+ continue;
+ }
}
const crossRenderUpdate = block.crossRenderUpdate;
block.crossRenderUpdate = false;
@@ -6850,10 +6869,16 @@
// retries the render; if it no longer suspends (an external store flipped
// before the suspending promise resolved), the boundary reveals now.
if (hiddenTry !== null) {
+ // The standalone body is dropped in favor of a boundary retry. Flag
+ // this block and its ancestors: the retry (or a later equal-props
+ // parent update) must not memo/stable/implicit-bail past the child
+ // that still holds the store write.
+ markSuppressedUpdate(block);
visibilityDriver!.reveal(hiddenTry, block.pendingMode ?? 'urgent');
continue;
}
if (hiddenActivity !== null && hiddenActivity.pendingThenable !== null) {
+ markSuppressedUpdate(block);
visibilityDriver!.retryActivity(hiddenActivity, true);
continue;
}
@@ -29766,12 +29791,7 @@
// ancestor chain so those bails decline. `LAZY_BODY_CHECK` marks eagerly —
// the lazy wrapper's resolution-aware `__compare` is only installed once the
// module resolves, after ancestors may already have committed.
- if ((body as any).__compare !== undefined || (body as any)[LAZY_BODY_CHECK] !== undefined) {
- for (let b: Block | null = parentBlock; b !== null; b = b.parentBlock) {
- if (b.$$compareInChain === true) break;
- b.$$compareInChain = true;
- }
- }
+ markCompareInChain(parentBlock, body);
let state = parentScope.slots[slotKey] as CompSlot | undefined;
let hydrationCursor: Node | null = null;
if (state === undefined) {
@@ -34046,6 +34066,10 @@
componentHasKey = value.key != null;
}
if (comp !== null) {
+ // Same veto-compare taint as componentSlot: a value-position memo/lazy
+ // child must still flag ancestors, or a later $$stable/memo bail keeps
+ // this subtree without invoking `__compare`.
+ markCompareInChain(parentBlock, comp);
// A bare render-FUNCTION child (a `.tsrx` `{children}` body forwarded onto a `.ts`
// component's host element via createElement) is re-created every render, so its
// identity always differs — but it is the SAME slot child. Reconcile by SLOT like
@@ -34742,6 +34766,20 @@
}
/**
+ * Flag ancestors when a callee's compare can veto on non-prop grounds (lazy
+ * re-resolution, custom comparators). Shared by componentSlot and childSlot so
+ * a value-position `{<Wrapped />}` still taints the chain. Sticky: a stale
+ * flag only costs a missed bail.
+ */
+function markCompareInChain(parentBlock: Block | null, body: any): void {
+ if ((body as any).__compare === undefined && (body as any)[LAZY_BODY_CHECK] === undefined) return;
+ for (let b: Block | null = parentBlock; b !== null; b = b.parentBlock) {
+ if (b.$$compareInChain === true) break;
+ b.$$compareInChain = true;
+ }
+}
+
+/**
* The hazards that veto every props-equality bail (memo, $$stable, implicit):
* each names a reason the body must re-run regardless of prop equality. A new
* bail hazard belongs here so the bail paths cannot desynchronize.
diff --git a/packages/octane/tests/compiler/stable-marker.test.ts b/packages/octane/tests/compiler/stable-marker.test.ts
--- a/packages/octane/tests/compiler/stable-marker.test.ts
+++ b/packages/octane/tests/compiler/stable-marker.test.ts
@@ -135,6 +135,69 @@
expect(stableStampedNames(code).has('Stable')).toBe(false);
});
+ it('rejects a local tag aliased from props — the callee is as opaque as an import', () => {
+ const code = c(`
+ export function Stable(props) @{
+ const C = props.comp;
+ <C label={props.label} />
+ }
+ `);
+ expect(stableStampedNames(code).has('Stable')).toBe(false);
+ });
+
+ it('rejects a scoped child that reads unwitnessed module state', () => {
+ const code = c(`
+ let serial = 0;
+ export function Stable() @{
+ <div>
+ @{
+ const n = serial;
+ <span>{'' + n}</span>
+ }
+ </div>
+ }
+ `);
+ expect(stableStampedNames(code).has('Stable')).toBe(false);
+ });
+
+ it('rejects a scoped child that calls useFormStatus', () => {
+ const code = c(`
+ import { useFormStatus } from 'octane';
+ export function Stable() @{
+ <form>
+ @{
+ const status = useFormStatus();
+ <span>{status.pending ? 'busy' : 'idle'}</span>
+ }
+ </form>
+ }
+ `);
+ expect(stableStampedNames(code).has('Stable')).toBe(false);
+ });
+
+ it('does not stamp a long same-module chain whose leaf is not bail-safe', () => {
+ const code = c(`
+ export function A(props) @{
+ <section><B label={props.label} /></section>
+ }
+ function B(props) @{
+ <div><C label={props.label} /></div>
+ }
+ function C(props) @{
+ <span><D label={props.label} /></span>
+ }
+ function D(props) @{
+ const stamped = props.stamp();
+ <em>{stamped as string}</em>
+ }
+ `);
+ const stamped = stableStampedNames(code);
+ expect(stamped.has('D')).toBe(false);
+ expect(stamped.has('C')).toBe(false);
+ expect(stamped.has('B')).toBe(false);
+ expect(stamped.has('A')).toBe(false);
+ });
+
it('rejects a render-time useContext read', () => {
const code = c(`
import { createContext, useContext } from 'octane';
diff --git a/packages/octane/tests/stable-bailout.test.ts b/packages/octane/tests/stable-bailout.test.ts
--- a/packages/octane/tests/stable-bailout.test.ts
+++ b/packages/octane/tests/stable-bailout.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { lazy } from '../src/index.js';
+import { flushSync, lazy } from '../src/index.js';
import { act, flushEffects, mount } from './_helpers';
import { loadCompiledFixtureSource } from './_server-fixture.js';
@@ -195,6 +195,164 @@
root.unmount();
});
+ it('replays a child store write after a sibling suspend aborted the drain', async () => {
+ const source = `
+ import { useState } from 'octane';
+ function Child() @{
+ const [n, setN] = useState(0);
+ <div>
+ <button id="inc" onClick={() => setN(n + 1)}>{'' + n}</button>
+ </div>
+ }
+ function Stable() @{
+ <section>
+ <Child />
+ </section>
+ }
+ export function App(props) @{
+ const [tick, setTick] = useState(0);
+ @try {
+ <div>
+ {props.ready ? <span id="ok">{'ok'}</span> : props.read()}
+ <button id="tick" onClick={() => setTick(tick + 1)}>{'' + tick}</button>
+ <Stable {...{}} />
+ </div>
+ } @pending {
+ <span id="pending">{'loading'}</span>
+ }
+ }
+ `;
+ const client = compileClient(source, 'stable-suppressed-child.tsrx');
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => {
+ resolve = done;
+ });
+ let ready = true;
+ const read = () => {
+ if (!ready) throw promise;
+ return 'ok';
+ };
+ const root = mount(client.App, { ready: true, read });
+ expect(root.find('#inc').textContent).toBe('0');
+
+ // Commit the first store write so the later aborted increment is a
+ // distinct pending cell value, not a journaled first paint.
+ root.click('#inc');
+ expect(root.find('#inc').textContent).toBe('1');
+
+ ready = false;
+ flushSync(() => {
+ (root.find('#inc') as HTMLButtonElement).click();
+ root.root.render(client.App, { ready: false, read });
+ });
+ expect(root.find('#inc').textContent).toBe('1');
+
+ ready = true;
+ await act(async () => {
+ resolve();
+ await promise;
+ });
+ expect(root.find('#inc').textContent).toBe('2');
+ root.click('#tick');
+ expect(root.find('#inc').textContent).toBe('2');
+ expect(root.find('#tick').textContent).toBe('1');
+ root.unmount();
+ });
+
+ it('re-renders an opaque local-tag child that reads module state', () => {
+ const source = `
+ import { useState } from 'octane';
+ let serial = 0;
+ export function bumpSerial() {
+ serial += 1;
+ }
+ function Opaque() @{
+ <span id="n">{'' + serial}</span>
+ }
+ function Parent(props) @{
+ const C = props.comp;
+ <C />
+ }
+ export function App() @{
+ const [tick, setTick] = useState(0);
+ <section>
+ <button id="tick" onClick={() => setTick(tick + 1)}>{'' + tick}</button>
+ <Parent {...{comp: Opaque}} />
+ </section>
+ }
+ `;
+ const client = compileClient(source, 'stable-opaque-local-tag.tsrx');
+ const root = mount(client.App);
+ expect(root.find('#n').textContent).toBe('0');
+ client.bumpSerial();
+ root.click('#tick');
+ expect(root.find('#n').textContent).toBe('1');
+ root.unmount();
+ });
+
+ it('re-renders a scoped child that reads module state', () => {
+ const source = `
+ import { useState } from 'octane';
+ let serial = 0;
+ export function bumpSerial() {
+ serial += 1;
+ }
+ function Stable() @{
+ <div>
+ @{
+ const n = serial;
+ <span id="n">{'' + n}</span>
+ }
+ </div>
+ }
+ export function App() @{
+ const [tick, setTick] = useState(0);
+ <section>
+ <button id="tick" onClick={() => setTick(tick + 1)}>{'' + tick}</button>
+ <Stable />
+ </section>
+ }
+ `;
+ const client = compileClient(source, 'stable-scoped-child.tsrx');
+ const root = mount(client.App);
+ expect(root.find('#n').textContent).toBe('0');
+ client.bumpSerial();
+ root.click('#tick');
+ expect(root.find('#n').textContent).toBe('1');
+ root.unmount();
+ });
+
+ it('runs a value-position custom compare when a stable ancestor would bail', () => {
+ const source = `
+ import { memo, useState } from 'octane';
+ let extra = 0;
+ export function bumpExtra() {
+ extra += 1;
+ }
+ function Inner(props) @{
+ <span id="v">{(props.label as string) + extra}</span>
+ }
+ const Wrapped = memo(Inner, () => extra === 0);
+ function Stable() @{
+ <div>{<Wrapped label="fixed" />}</div>
+ }
+ export function App() @{
+ const [tick, setTick] = useState(0);
+ <section>
+ <button id="tick" onClick={() => setTick(tick + 1)}>{'' + tick}</button>
+ <Stable />
+ </section>
+ }
+ `;
+ const client = compileClient(source, 'stable-value-compare.tsrx');
+ const root = mount(client.App);
+ expect(root.find('#v').textContent).toBe('fixed0');
+ client.bumpExtra();
+ root.click('#tick');
+ expect(root.find('#v').textContent).toBe('fixed1');
+ root.unmount();
+ });
+
it('bails a lazy()-wrapped stable component once the module resolves', async () => {
const source = `
import { useEffect } from 'octane';You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 28f386c. Configure here.
| // suspend aborted the transaction. Its state cells still hold the update; | ||
| // only the body reads them — bailing strands the pre-abort screen forever. | ||
| return block.suppressedUpdate === true; | ||
| } |
There was a problem hiding this comment.
Ancestor bails strand descendant updates
High Severity
blockBailUnsafe only inspects the block taking the bail. suppressedUpdate and held transition entries live on the descendant that owns the state cells, so a $$stable or memo ancestor with clean props can keep the committed subtree and never re-enter that child. The pending store write then stays applied only in the hook cell while the rolled-back or pre-abort DOM remains on screen.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 28f386c. Configure here.
| return found; | ||
| } | ||
|
|
||
| // Function nodes whose bodies are DEFERRED under the `$$stable` proof — every |
There was a problem hiding this comment.
Opaque local tags get stable stamps
High Severity
The $$stable proof rejects imported callees because a block bail never runs the child's own witness, but a local tag bound from props or another expression (const C = props.comp; return <C />) is invisible: it is not a free name and the structure walk only fails member or expression tags. Those parents still receive __st, so an opaque child that reads module state, carries a custom compare, or is lazy can go stale under an equal-props parent update.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 28f386c. Configure here.
| if (stable && t === 'JSXCodeBlock') { | ||
| if (containsDeferredRefRead(n)) found = true; | ||
| return; | ||
| } |
There was a problem hiding this comment.
Scoped child blocks skip bail proof
Medium Severity
In $$stable mode both the unsafe-structure walk and collectStableDeferredFunctions treat a nested @{ } (JSXCodeBlock) as deferred child work and do not classify its body. Unlike same-module component edges, that child is never required to be bailSafe, so render-position useFormStatus, unwitnessed module state, or imported member reads inside the scoped block still let the parent be stamped. A later equal-props bail keeps the last hole output instead of re-running it.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 28f386c. Configure here.
| info.stable = | ||
| info.stableBody === true && | ||
| info.stableComponentDeps.every((name) => ctx.componentInfo.get(name)?.bailSafe === true); | ||
| } |
There was a problem hiding this comment.
Bail-safety uses fixed-point rescans
Medium Severity
$$stable bail-safety is computed with a whole-componentInfo while rescan that flips bailSafe and then rewalks every candidate until nothing changes. Graph facts in this compiler are required to use a seeded reverse-edge worklist so a long A→B→C chain is linear and declaration order cannot turn each edge into another full-module pass. The capture-propagation block immediately below already shows that worklist shape; this new loop does not.
Triggered by learned rule: Compiler graph facts: reverse-edge worklist — no per-level map rescans
Reviewed by Cursor Bugbot for commit 28f386c. Configure here.
| if (b.$$compareInChain === true) break; | ||
| b.$$compareInChain = true; | ||
| } | ||
| } |
There was a problem hiding this comment.
Value-position compares skip ancestor flags
Medium Severity
$$compareInChain is armed only inside componentSlotImpl. A memo child with __compare or a lazy body that mounts through childSlot (value-position children, provider children, descriptor holes) never flags its ancestors. A later $$stable or memo bail on that ancestor keeps the subtree without invoking the veto compare, which is the hazard this flag was added to close.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 28f386c. Configure here.
|
This PR is stale, please re-create PR given the new repo agent constraints and rules. |



Summary
When the compiler can prove a component's committed output is a pure projection of its props snapshot, it now stamps the definition with
$$stable(markStable, exported to compiled output as the compact__stABI). At render time the runtime treats the stamp as React.memo's contract without the wrapper: a shallow-equal parent update keeps the committed subtree instead of re-running the body.The proof is strict about render position. Deferred hook bodies — effects, callbacks, deps-gated factories, lazy initializers — are admitted because they run at commit/dispatch time, never inside the render a bail would skip. Sync-factory hooks (
useSyncExternalStoresnapshots, always-run memo factories) keep their arguments under render rules. A render-positionuseContext/use/useFormStatusread fails closed: the stamp promises a props-only projection. Free names are admitted only as component tags, built-in hook imports, provencreateContextidentities,memo()walls, octane's own namespace, and same-module declarations; bail-safety is transitive over same-module component edges via a fixed point, so declaration order and recursion cannot weaken it.Every props-equality bail — explicit
memo,$$stable, and the implicit bail — now declines through one shared hazard veto,blockBailUnsafe, extracted from the two existing bail paths and extended with this mechanism's new hazards:$$compareInChain— lazy re-resolution, custom comparators),blockHasHeldUpdate),suppressedUpdate).Context bookkeeping treats
$$stablelike__memo(memoInChain,$$ctxReadsstamping,refreshContextConsumerspruning), so provider commits still reach consumers inside a bailed subtree — React's lazy propagation.lazy()publishes equivalent metadata when the resolved module body is stamped.A memo-guarded callsite whose callee is context-free also keeps its lite lowering: the guard wraps the same
componentSlotLitecall instead of minting a Block per callsite, so the cache adds no mount boundaries.Why
Component bodies the compiler already proves pure were re-running on every parent render even when props were shallow-equal — work
memo()exists to skip but which required an opt-in wrapper. Stamping at the definition site gives the same bailout automatically, and routing all three bail kinds through one veto keeps their hazard sets from drifting apart.Changes
packages/octane/src/compiler/compile.js—$$stablepurity analysis (stableBody/bailSafeverdicts,collectStableDeferredFunctions, render-position free-name admission, bail-safe fixed point),__ststamp emission for initializer and hoisted-declaration forms, memo-witness chains accepting$$stable, context-free memoized-callee lite lowering.packages/octane/src/runtime.ts—markStable(bound non-enumerable$$stablegetter),blockBailUnsafeshared veto extracted fromtryMemoBail/tryImplicitBail,blockHasHeldUpdate,$$compareInChainancestor flagging incomponentSlotImpl,suppressedUpdateindrainQueue/renderBlockInner,$$stablearms in context stamping/refresh,lazymetadata.packages/octane/src/index.ts,scripts/verify-dist.mjs—markStable/__stexports + dist export assertions.stable-marker(emission shapes),stable-bailout(bail behavior incl. context-witness and held-update paths),auto-memo-lite(lite lowering, both copies),auto-memo/non-jsx-return(adjacent contract coverage),_fixtures/auto-memo-lite.tsrx..changeset/stable-component-bail.md—'octane': patch.Validation
pnpm format:check— deferred to CI;pnpm format:files:checkon all touched paths passespnpm typecheck— deferred to CI;pnpm typecheck:fileson touchedsrc/script paths passes (test-file typecheck hits a pre-existing.tsrx-resolution limitation intypecheck-files.mjs, identical on base)pnpm test— deferred to CIvitest runonstable-bailout,auto-memo,auto-memo-lite,non-jsx-return(350 tests,octane+octane-prod),compiler/stable-marker+compiler/auto-memo-lite(29 tests,octaneproject) — all greenbenchmarks/bundle-size/run.mjs+run-minimal.mjs, measured against the same harness at base8a4a2e087): js-framework octane-tsrx fw_gzip 38013 → 38051 (+38 gz); largest delta weather-app octane-tsrx fw_gzip 51897 → 52173 (+276 gz); minimal scenarios +0–270 gz — details belowmain@8a4a2e087on the honest fixture (child-1update_nodeps/tickharness overlaid for measurement only, 30 iters) — update_nodeps 0.25→0.24 ms (0.91x), all other ops 0.99–1.07x. Near-null wall-time: main's existing implicit bail already skips most row bodies (octane is 3x faster than react on update_nodeps before this change), so$$stable's skipped work is small per-row here. The mechanism's evidence is the render-count assertions instable-bailout.test.ts; suite attribution lands when the honest harness (fix(benchmarks): restore effectful-list workload honesty and enable React Compiler in spa-navigation #1205) and this PR combineFramework bytes at this HEAD vs base (gzip,
fw_*bucket unless noted):run-minimal.mjsalso hit the pre-existingbinding-aria-esbuildesbuildenumfailure — unrelated, flagged in #1188 and out of scope here.Risk / follow-ups
blockBailUnsafeveto means a missed hazard fails safe (re-runs the body) rather than stale.$$stableis never emitted under HMR (the autoMemo gate excludes it), so no rebind ordering exists for stamped declarations.Provenance
agent-authored)Part of #1202. Split from #1188.
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Note
High Risk
Changes core render bailout, context refresh, and transition/drain semantics; correctness depends on the compiler purity proof and shared hazard veto staying complete.
Overview
Adds compiler-driven
$$stable(markStable/__st): when a client component body is proven to be a props-only committed projection, the compiler stamps it so shallow-equal parent updates can bail out likememo()without a wrapper.The compiler gains strict
stableBody/bailSafeanalysis (deferred hooks admitted, render-time context/ref/import hazards rejected, transitive same-module deps via fixed point) and emits__ston eligible definitions. Memo witnesses and context-free auto-memo callsites can keepcomponentSlotLiteunder the memo guard instead of allocating context-stamping Blocks.Runtime changes unify memo, stable, and implicit bails behind
blockBailUnsafe(held transitions, aborted-transactionsuppressedUpdate,$$compareInChain, effect-event skew, unmounted retries), treat$$stablelike__memofor context propagation, and extendlazy()metadata. Public exports and dist verification addmarkStable/__st; new tests cover stamping, bailout behavior, and memo-lite lowering.Reviewed by Cursor Bugbot for commit 28f386c. Bugbot is set up for automated code reviews on this repo. Configure here.