Repository navigation
perf(octane): changed-commit write path — sources plan, fused scan, journal replay - #1215
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 2 potential issues.
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Hot-path DOM expando for plan misses
- Moved the sources-plan miss counter onto the plan record so planned commits no longer assign a symbol expando on the live host.
- ✅ Fixed: Global journal suppress is re-entrant
- Journal attr suppress is now the dispatching element with save/restore, so nested writers to other hosts still snapshot and inner finally cannot unmute the outer write.
Or push these changes by commenting:
@cursor push ad613bdf85
Preview (ad613bdf85)
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
@@ -4550,16 +4550,19 @@
}
/**
- * True while a spread commit's write loop runs under a journaled transaction:
- * the element's own replay entry supersedes per-attribute snapshots, so the
- * writers below skip their getAttribute reads. Replaying writes (a rollback
- * re-running a writer) never journal either — they only append dead entries
- * to a log the rollback discards after replay.
+ * Host whose in-flight spread/planned write owns the journal window: that
+ * element's replay entry supersedes per-attribute snapshots, so its writers
+ * skip getAttribute reads. Other hosts keep snapshotting — a nested
+ * custom-element callback or flushSync can write them, and those writes are
+ * not covered by the outer undo. Nested dispatches save/restore this slot so
+ * an inner finally cannot unmute the outer write. Replaying writes never
+ * journal either — they only append dead entries to a log the rollback
+ * discards after replay.
*/
-let JOURNAL_ATTR_SUPPRESS = false;
+let JOURNAL_ATTR_SUPPRESS_EL: Element | null = null;
function journalAttr(el: Element, name: string): void {
- if (JOURNAL_ATTR_SUPPRESS || TRANSITION_JOURNAL_REPLAYING) return;
+ if (el === JOURNAL_ATTR_SUPPRESS_EL || TRANSITION_JOURNAL_REPLAYING) return;
TRANSITION_JOURNAL!.push(JOURNAL_ATTR, el, name, (STAGED_DOM?.view(el) ?? el).getAttribute(name));
journalBag();
}
@@ -23807,9 +23810,9 @@
* attachSourcesPlan's per-commit allocations — a source shape that never
* stabilizes reverts to the full path for good. ponytail: poisoned is
* permanent; a shape that stabilizes later keeps the full path (reviving it
- * would take a decay or per-shape plans).
+ * would take a decay or per-shape plans). Count lives on the plan (`misses`),
+ * not on the host.
*/
-const SOURCES_PLAN_MISSES = /* @__PURE__ */ Symbol('octane.host-prop-sources-plan-misses');
const SOURCES_PLAN_MISS_LIMIT = 3;
/**
@@ -23840,6 +23843,12 @@
readonly diffIdx: number[];
readonly diffVal: unknown[];
diffLen: number;
+ /**
+ * Consecutive failed verifications. Lives on the plan, not the host: a DOM
+ * expando on the committed write path is banned, and the plan is already
+ * the per-element planning record.
+ */
+ misses: number;
}
/**
@@ -23898,6 +23907,7 @@
resolved: Record<string, unknown>,
sources: readonly HostPropSource[],
winners: HostPropWriter[],
+ misses = 0,
): void {
let spreadIndex = -1;
let spreadKeys: readonly string[] | null = null;
@@ -23953,6 +23963,7 @@
diffIdx: new Array<number>(winners.length),
diffVal: new Array<unknown>(winners.length),
diffLen: 0,
+ misses,
} satisfies ResolvedSourcesPlan,
});
}
@@ -24101,10 +24112,11 @@
TRANSITION_JOURNAL !== null &&
!TRANSITION_JOURNAL_REPLAYING &&
activeHydration() === null;
+ const prevSuppress = JOURNAL_ATTR_SUPPRESS_EL;
if (journalReplay) {
journalUndo(() => writePlannedDiff(el, prev, next, plan, scope, true));
journalBag();
- JOURNAL_ATTR_SUPPRESS = true;
+ JOURNAL_ATTR_SUPPRESS_EL = el;
}
try {
if (!replay) stampSpreadPropFlags(el, next);
@@ -24165,7 +24177,7 @@
}
if (process.env.NODE_ENV !== 'production' && !replay) queueDevFormDiagnostic(el, scope);
} finally {
- if (journalReplay) JOURNAL_ATTR_SUPPRESS = false;
+ if (journalReplay) JOURNAL_ATTR_SUPPRESS_EL = prevSuppress;
}
}
@@ -24190,11 +24202,10 @@
const plan = (prev as Record<symbol, unknown>)[SOURCES_PLAN] as ResolvedSourcesPlan | undefined;
if (plan === undefined) return null;
if (!scanSourcesForPlan(sources, plan, prev, readStyle)) {
- const tagged = el as any;
- tagged[SOURCES_PLAN_MISSES] = ((tagged[SOURCES_PLAN_MISSES] as number | undefined) ?? 0) + 1;
+ plan.misses++;
return null;
}
- (el as any)[SOURCES_PLAN_MISSES] = 0;
+ if (plan.misses !== 0) plan.misses = 0;
const next = buildFromSourcesPlan(plan, prev);
if (
next === prev &&
@@ -24424,14 +24435,15 @@
// allocations. The plan stamps the record actually retained — on an
// unchanged commit resolvedHostPropsEqual just proved `prev` carries the
// identical keys, so the plan replays correctly against it — rather than
- // dying with a discarded `resolved`. Elements whose scans keep failing stop
- // paying the attach once SOURCES_PLAN_MISS_LIMIT trips.
- if (
- !formHost &&
- prev !== undefined &&
- (((el as any)[SOURCES_PLAN_MISSES] as number | undefined) ?? 0) < SOURCES_PLAN_MISS_LIMIT
- )
- attachSourcesPlan(el, out!, sources, winners);
+ // dying with a discarded `resolved`. Consecutive scan misses live on the
+ // previous plan; once SOURCES_PLAN_MISS_LIMIT trips, attach stops.
+ const prevPlan =
+ prev === undefined
+ ? undefined
+ : ((prev as Record<symbol, unknown>)[SOURCES_PLAN] as ResolvedSourcesPlan | undefined);
+ const planMisses = prevPlan?.misses ?? 0;
+ if (!formHost && prev !== undefined && planMisses < SOURCES_PLAN_MISS_LIMIT)
+ attachSourcesPlan(el, out!, sources, winners, planMisses);
return out;
}
@@ -25099,7 +25111,8 @@
setSpread(el, prev, value, mountScope, skipDangerouslySetInnerHTML, skipFormControls, true),
);
journalBag();
- JOURNAL_ATTR_SUPPRESS = true;
+ const prevSuppress = JOURNAL_ATTR_SUPPRESS_EL;
+ JOURNAL_ATTR_SUPPRESS_EL = el;
try {
setSpreadBody(
el,
@@ -25111,7 +25124,7 @@
false,
);
} finally {
- JOURNAL_ATTR_SUPPRESS = false;
+ JOURNAL_ATTR_SUPPRESS_EL = prevSuppress;
}
}
diff --git a/packages/octane/tests/spread-journal-nested-host.test.tsrx b/packages/octane/tests/spread-journal-nested-host.test.tsrx
new file mode 100644
--- /dev/null
+++ b/packages/octane/tests/spread-journal-nested-host.test.tsrx
@@ -1,0 +1,120 @@
+import { expect, it } from 'vitest';
+import { setClassAttr, use, useState, useTransition } from 'octane';
+import { act, mount } from './_helpers';
+
+declare module 'octane/jsx-runtime' {
+ namespace Octane {
+ namespace JSX {
+ interface IntrinsicElements {
+ 'octane-spread-journal-host': IntrinsicElements['div'];
+ }
+ }
+ }
+}
+
+// A spread commit journals one undo for that host. A custom-element callback
+// can still write a *different* host through the public attribute writers;
+// those writes are not covered by the outer undo and must snapshot themselves.
+if (customElements.get('octane-spread-journal-host') === undefined) {
+ customElements.define(
+ 'octane-spread-journal-host',
+ class extends HTMLElement {
+ static observedAttributes = ['data-mark'];
+ attributeChangedCallback(_name: string, previous: string | null, value: string | null) {
+ // Only the forward transition write. Rollback replays data-mark
+ // back to 'old' and must not re-mutate the sibling.
+ if (!this.isConnected || previous !== 'old' || value !== 'new') return;
+ const sibling = document.getElementById('probe-sibling');
+ if (sibling) setClassAttr(sibling, 'mutated');
+ }
+ },
+ );
+}
+
+interface Deferred<T> {
+ promise: Promise<T>;
+ resolve(value: T): void;
+}
+
+function deferred<T>(): Deferred<T> {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((res) => {
+ resolve = res;
+ });
+ return { promise, resolve };
+}
+
+function SuspendedValue(props: { load: (step: number) => Promise<string>; step: number }) @{
+ const value = use(props.load(props.step));
+ <span id="value">{value as string}</span>
+}
+
+function SpreadJournalNestedHost(props: { load: (step: number) => Promise<string> }) @{
+ const [step, setStep] = useState(0);
+ const [isPending, start] = useTransition();
+ <div>
+ <span id="pending">
+ {isPending ? 'pending' : 'idle'}
+ </span>
+ <button id="bump" onClick={() => start(() => setStep(1))}>{'bump'}</button>
+ <span id="probe-sibling" />
+ @try {
+ <>
+ <octane-spread-journal-host
+ id="probe-host"
+ {...(step === 0
+ ? { 'data-mark': 'old', 'data-extra': 'a' }
+ : { 'data-mark': 'new', 'data-extra': 'b' })}
+ />
+ <SuspendedValue load={props.load} step={step} />
+ </>
+ } @pending {
+ <span id="fallback">{'fallback'}</span>
+ }
+ </div>
+}
+
+it(
+ 'restores a sibling written from a spread host callback while a transition is held',
+ async () => {
+ const entries = new Map<number, Deferred<string>>();
+ const load = (step: number) => {
+ let entry = entries.get(step);
+ if (entry === undefined) {
+ entry = deferred<string>();
+ entries.set(step, entry);
+ }
+ return entry.promise;
+ };
+ load(0);
+ entries.get(0)!.resolve('zero');
+
+ const r = mount(SpreadJournalNestedHost, { load });
+ await act(() => {});
+ try {
+ expect(r.find('#probe-host').getAttribute('data-mark')).toBe('old');
+ expect(r.find('#probe-sibling').getAttribute('class')).toBe(null);
+
+ r.click('#bump');
+ expect(r.findAll('#fallback')).toHaveLength(0);
+ expect(r.find('#pending').textContent).toBe('pending');
+ expect(r.find('#probe-host').getAttribute('data-mark')).toBe('old');
+ expect(r.find('#probe-host').getAttribute('data-extra')).toBe('a');
+ // The callback wrote class="mutated" during the discarded transition.
+ // Rollback must restore the sibling; the outer spread undo only covers
+ // the host that dispatched it.
+ expect(r.find('#probe-sibling').getAttribute('class')).toBe(null);
+ expect(r.find('#value').textContent).toBe('zero');
+
+ await act(() => {
+ entries.get(1)!.resolve('one');
+ });
+ expect(r.find('#probe-host').getAttribute('data-mark')).toBe('new');
+ expect(r.find('#probe-sibling').getAttribute('class')).toBe('mutated');
+ expect(r.find('#value').textContent).toBe('one');
+ expect(r.find('#pending').textContent).toBe('idle');
+ } finally {
+ r.unmount();
+ }
+ },
+);
diff --git a/packages/octane/tests/write-path-slimming.test.ts b/packages/octane/tests/write-path-slimming.test.ts
--- a/packages/octane/tests/write-path-slimming.test.ts
+++ b/packages/octane/tests/write-path-slimming.test.ts
@@ -246,6 +246,45 @@
}
});
+ it('planned host-prop commits do not assign own properties onto the live host', () => {
+ const r = mount(WritePathSpread, {
+ tick: 'a',
+ spread: { 'data-x': '1' },
+ });
+ try {
+ const el = r.find('#wp-spread');
+ // Second commit attaches the sources plan on the resolved record.
+ r.update(WritePathSpread, {
+ tick: 'b',
+ spread: { 'data-x': '2' },
+ });
+ expect(el.getAttribute('data-x')).toBe('2');
+ const names = Object.getOwnPropertyNames(el);
+ const symbols = Object.getOwnPropertySymbols(el);
+ // Planned hit: same source shape, changed value. Planning state must
+ // stay on the resolved record, not as a DOM expando on the element.
+ r.update(WritePathSpread, {
+ tick: 'c',
+ spread: { 'data-x': '3' },
+ });
+ expect(el.getAttribute('data-x')).toBe('3');
+ expect(Object.getOwnPropertyNames(el)).toEqual(names);
+ expect(Object.getOwnPropertySymbols(el)).toEqual(symbols);
+ // Shape miss: a new key set takes the full path. Same rule — the miss
+ // count rides the plan, so the host's own-property set stays put.
+ r.update(WritePathSpread, {
+ tick: 'd',
+ spread: { 'data-y': '4' },
+ });
+ expect(el.getAttribute('data-y')).toBe('4');
+ expect(el.hasAttribute('data-x')).toBe(false);
+ expect(Object.getOwnPropertyNames(el)).toEqual(names);
+ expect(Object.getOwnPropertySymbols(el)).toEqual(symbols);
+ } finally {
+ r.unmount();
+ }
+ });
+
it('an unchanged spread record commits no writes; a changed data-* key commits', () => {
const r = mount(WritePathSpread, {
tick: 'a',You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 6d86991. Configure here.
| tagged[SOURCES_PLAN_MISSES] = ((tagged[SOURCES_PLAN_MISSES] as number | undefined) ?? 0) + 1; | ||
| return null; | ||
| } | ||
| (el as any)[SOURCES_PLAN_MISSES] = 0; |
There was a problem hiding this comment.
Hot-path DOM expando for plan misses
Medium Severity
replaySourcesPlan writes SOURCES_PLAN_MISSES onto the live host on every planned commit — increment on a miss and 0 on a hit — and setHostPropSources reads that same element slot. That is a hot-path DOM expando assign during reconcile. The miss ceiling already lives conceptually with the plan on the resolved record, so the element does not need to carry it.
Additional Locations (1)
Triggered by learned rule: Do not add expando properties to DOM elements on hot reconciliation paths
Reviewed by Cursor Bugbot for commit 6d86991. Configure here.
| ); | ||
| } finally { | ||
| JOURNAL_ATTR_SUPPRESS = false; | ||
| } |
There was a problem hiding this comment.
Global journal suppress is re-entrant
Medium Severity
JOURNAL_ATTR_SUPPRESS is a process-wide boolean. While a spread or planned write runs, every journalAttr call is dropped — including writes to other hosts — and the finally block always sets the flag back to false, so a nested setSpread or writePlannedDiff can unmute the outer write mid-loop. A synchronous callback (custom-element attributeChangedCallback, flushSync) can therefore omit snapshots the element-level undo does not cover.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 6d86991. Configure here.
|
This PR is stale, please re-create PR given the new repo agent constraints and rules. |



Summary
setHostPropSourcesnow stamps a verified source-shape plan (SOURCES_PLAN) on each committed resolved record. The next commit verifies the shape in one flat pass — same tuple length, same writer names in the same positions, at most one spread with the same key order, no merge flags, no live signal handles — and replays preclassified writers (planEntryKindarms: skip/ref/class/style/event/action/data/attr) straight to the DOM, without materializing either writerMapor re-deriving per-key routing.Object.is-matches the previous commit's (resolvedHostPropsEqual) skipssetSpread's write tail entirely; a single-spread source list can even bail before the writer Maps and resolved record are allocated (hostSourcesMatchCommitted). Dev validation and the suppress/diagnostic stamps still run viastampSpreadPropFlags, so a bailed commit leaves the identical element surface.journalSignalHostBinding) instead of cloning the whole record,JOURNAL_ATTR_SUPPRESSskips per-attributegetAttributesnapshots while a spread commit's own replay entry supersedes them, and completed renders' Effect Event payloads are retained through a failed transition's rollback — so a Suspense-retained subtree never publishes DOM without its matching impls, and a superseded binding's installed control listener and disposal flag restore exactly.CSSStyleDeclarationIDL assignment (styleIdlWritable) instead ofsetProperty— same CSS parse, no kebab conversion or CSSOM name lookup — with a priority-preservation probe keeping!importantsemantics exact.Why
Maps and re-dispatched every resolved key throughsetSpread's classification logic, even when the sources tuple and the resolved record were identical to the last commit's. Compiled spreads re-allocate their source objects every render, so identity shortcuts can never fire — the plan and the resolved-record compare are the only honest fast paths.sources/resolved/pendingControl/input/disposedfields partially mutated and could drop completed siblings' Effect Event payloads on reveal.Changes
packages/octane/src/runtime.ts:SOURCES_PLAN/SOURCES_PLAN_MISSES/SOURCES_PLAN_MISS_LIMIT,planEntryKind,attachSourcesPlan,scanSourcesForPlan,buildFromSourcesPlan,writePlannedDiff,replaySourcesPlan. Plans attach from the second commit on and retire permanently after three failed verifications (ponytail:ceiling noted in source).setHostPropSourcesend-to-end: plan replay first, then the single-spread pre-resolve bail, then the resolved-record bail; form hosts and hydration stay on the full path because their control reassertion and bookkeeping read the raw writer Map.resolvedHostPropsEqual,resolvedHostSourceKey,hostSourcesMatchCommitted;setSpreadsplit sostampSpreadPropFlagscarries the JS-only surface shared by the bail paths;commitResolvedDangerSourcesValuestail extracted so plan replay reaches innerHTML validation/write directly.journalSignalHostBinding,JOURNAL_ATTR_SUPPRESSinjournalAttr,endTransitionAttemptcompleted-render payload retention,renderBlockInner'seffectEventTargetretention loop.applyStyleProperty/styleIdlWritableIDL-write path with lazy probe andstyleIdlKeepsPriorityfallback,setStringData,removeHostProp,isAggregatedFormControlProp,addSignalHostControlWriter/syncSignalHostControl(controls passed explicitly),setDangerouslySetInnerHTMLSources,snapshotSpreadreduced to{...v},EMPTY_SIGNAL_HANDLES.packages/octane/tests/write-path-slimming.test.ts+_fixtures/write-path-slimming.tsrx(new): direct IDL style writes, leandata-*writer, and a compiled svg-edge-pulse commit asserting nosetPropertycalls for IDL names and no DOM writes on an unchanged record.packages/octane/tests/unchanged-spread-bail.test.ts+_fixtures/unchanged-spread-bail.tsrx(new): unchanged commits write nothing, getters evaluate exactly once, dropped keys still remove, controlled inputs still reassert after drift, refs swap, innerHTML isn't re-injected, custom-element and scoped-class surfaces stay identical.packages/octane/tests/single-spread-fast-path.test.ts+_fixtures/single-spread-fast-path.tsrx(new): only changed props write across identical/equal-value/reshaped commits, in-place spread mutation detected by value, ordering across multiple spreads.packages/octane/tests/signals-dom-bindings.test.ts+_fixtures/signals-dom-bindings.tsrx:SignalControlSupersederegression — a held transition binding a writable control signal is superseded by an urgent render; the suspended attempt's binding mutation rolls back and the committed control still delivers typed input..changeset/tidy-badgers-replay.md:'octane': patch.Validation
pnpm format:files:checkon touched paths — clean (format:filesmade no changes).pnpm typecheck:files—packages/octane/src/runtime.tsclean undertsgo. Scoped runs that include the test files fail insidetests/_fixtures/*.tsrx(TS7006 untypedprops, one TS2339 custom element) — the identical failure unmodified fixtures/tests produce onmain(actions.tsrx,actions.test.ts), becausepackages/octane/tsconfig.jsonexcludestests. Fixtures are byte-identical to the source branch and left as authored.vitest run packages/octane/tests/{write-path-slimming,unchanged-spread-bail,single-spread-fast-path,signals-dom-bindings}.test.ts— 172 tests pass across 9 file instances (octane,octane-prod,octane-signals-strongprojects).vitest run --project octane --project octane-prodonwrite-path-slimming+unchanged-spread-bail— 50 tests pass.pnpm syncleaves the tree clean (no generated output).pnpm format:check,pnpm typecheck,pnpm test— deferred to CI per repo convention.main@8a4a2e087(20 iters; <1 = faster) — select_toggle 3.0→1.6 ms (0.52x), style_spread_pulse 5.2→3.0 (0.57x), drag_nodes 11.3→8.6 (0.76x), label_churn 2.8→2.1 (0.76x); mount/tick/pan flat. vs react fixture: closes most of select_toggle and style_spread_pulserun-minimal.mjsscenario gz deltas vs base: deferred-hydration +346, binding-base-ui-vite +345, suspense-transition +334, root-static +314, binding-base-ui-esbuild +303, hydrate-root +223, hooks-state +70, cli-spa-starter +67, context +55, component-owned-effects +53, root-static-specialized/-local +52, binding-hooks +45; capture-only, server-hooks, server-render, binding-vanilla, behavior-root-*, binding-aria-vite unchanged.run-minimal.mjsstopped at the pre-existingbinding-aria-esbuildfailure (unrelated esbuildenumparse issue flagged on perf(runtime): beat React 19 + Compiler across the timing benchmark portfolio #1188) after capturing all listed sizes.Risk / follow-ups
(element, rawName): a matching shape reproduces the exact resolved key set, so replay can never skip a removal or misroute a writer. Shape drift, hydration, and live signal handles all fall back to the full path — a wrong plan can only cost the scan, never produce a divergent commit.Object.is-matchprevunder its resolved key, making writer ordering irrelevant; unrecognized shapes fall through to the full resolve rather than forking semantics.SOURCES_PLAN_MISS_LIMITpoisons planning permanently per element — a shape that stabilizes later keeps the full path (documented ceiling).Part of #1202. Split from #1188.
Provenance
agent-authored)Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Note
Medium Risk
Large changes to core DOM commit, transition rollback, and spread routing in
runtime.ts; incorrect plan replay or bail logic could skip writes or leave stale DOM, though shape drift and signals fall back to the full path.Overview
Host-prop commits now cache a shape-stable
sourcesplan on the resolved record and replay preclassified DOM writers on the next commit when the tuple still matches—skipping writerMapallocation and fullsetSpreadrouting. Unchanged resolved records (and a single-spread pre-resolve compare) can bail the write tail while still running dev stamps; form hosts and hydration stay on the full path.Rollback and spread journaling improve correctness on the same hot path: signal host bindings journal per-field instead of whole-record clones; spread commits use one journal replay entry with
JOURNAL_ATTR_SUPPRESSfor attributes; failed transitions retain effect-event payloads from completed renders so Suspense-retained subtrees stay consistent.Writers use verified
CSSStyleDeclarationIDL assignment for common style keys, route spreaddata-*throughsetStringData(with aligned dev warnings), and add targeted DOM-boundary tests for unchanged spreads, single-spread fast paths, style slimming, and superseded transition control bindings.Reviewed by Cursor Bugbot for commit 6d86991. Bugbot is set up for automated code reviews on this repo. Configure here.