Repository navigation
fix(octane): skip retired hosts when removal dispatches focusout - #1548
Conversation
Teardown disposes a Block before it detaches the Block's DOM, and Chromium dispatches focusout synchronously while it removes a focused host. Delegated dispatch then started handlers on hosts whose component had unmounted: a signal write reported ScopeDisposedError (production error 151) and plain onBlur handlers ran for unmounted components. setEventHandler records the rendering Block on each event host, a disposed Block records the event-route epoch at which its hosts leave dispatch (staged for a ViewTransition deletion), and a phase snapshot skips hosts that retired before the native delivery began. Live ancestors, other roots, snapshotted handlers, and in-flight deliveries keep their existing behavior. Closes #1472 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Benchmark report
Compares js-framework: 1k/10k row operations (ms, lower is better)All 20 timed operations (20 within noise)
Application bundle size (bytes)
7 other measured values are unchanged. Public-import reachability bundles (bytes)
35 other measured values are unchanged. CI job durations
Compares the CI run for
All 26 timed jobs
|
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: List clear retires hosts after detach
- Added a retireEventOwner pre-pass loop before the DOM removal in batchClearItems so synchronous focusout during detach sees every row as retired, matching the ordering in unmountBlockInner and deferRootOwnedListClear.
Or push these changes by commenting:
@cursor push 63293cf0b6
Preview (63293cf0b6)
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
@@ -44260,6 +44260,12 @@
return;
}
const p = domNode(state.start).parentNode!;
+ // Retire event owners before the DOM detach so that synchronous focusout
+ // (or any other removal-triggered event) sees every row as retired.
+ // Mirrors unmountBlockInner and the deferred owned-clear commit path.
+ for (let b: Block | null = state.head; b !== null; b = b.nextSibling) {
+ retireEventOwner(b);
+ }
if (domNode(state.start).previousSibling === null && getNextSibling(state.end) === null) {
// forBlock owns the parent — nuke everything in one DOM op, then re-add markers.
(STAGED_DOM?.view(p as Element) ?? (p as Element)).textContent = '';You can send follow-ups to the cloud agent here.
Stamp a disposed Block's retirement inline where Blocks are disposed instead of calling a helper per Block: the ViewTransition effect-cleanup gate allows no extra call per removed row. A staged deletion now retires its Blocks through one deferred-layout-driver action per capture, so the batching code ships only with ViewTransition. The snapshot check is inlined and the Block field is renamed `retired`, keeping root-chained-jsx within its committed byte budget. batchClearItems' immediate path now disposes the items before it clears their DOM, matching every other deletion: cleanups observe attached hosts, and removing a focused row finds its hosts already retired. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Move the $$eventOwner prototype seed into delegateEvents so handler-free bundles skip it, and read the owner's retirement through optional chaining. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Branch on the staged capture by truthiness and shorten the driver method to `retireHosts`. root-chained-jsx still needs 75 gzip / 115 brotli bytes over current main for the Block field, the inline disposal stamp, and the dispatch check, which exceeds the 60-byte gzip headroom main had left. Raise only its gzip and brotli ceilings by one 32-byte step (28416 / 25280); raw stays within 85728 and every other budget is unchanged. 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: Missing disposal check after list teardown
- Wrapped the unmount loop and DOM manipulation in batchClearItems in a single teardown bracket (TEARDOWN_DEPTH++/try/finally) so that dispatchTeardownErrors is deferred until both phases complete and the markers are consistent, matching the pattern used by resetScopeChildren and unmountBlock.
Or push these changes by commenting:
@cursor push 7c69a60f9c
Preview (7c69a60f9c)
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
@@ -44806,41 +44806,57 @@
// nextSibling) rather than the Map's iterator: zero allocation and a
// monomorphic pointer chase. Callers reset head/tail only AFTER this returns,
// so the chain still covers exactly the old items here.
- for (let b: Block | null = state.head; b !== null; b = b.nextSibling) {
- if (b.cleanups !== null || b.children !== null || b._slots !== null) {
- unmountBlock(b, false);
+ //
+ // The bracket spans the unmount walk AND the DOM removal so that a cleanup
+ // error is deferred until the markers are consistent: without it each
+ // unmountBlock installs its own bracket at TEARDOWN_DEPTH 0, and the dispatch
+ // between items can activate a boundary that disposes the list while the DOM
+ // clear still needs state.start.
+ const firstItem = state.head;
+ if (firstItem !== null && TEARDOWN_DEPTH === 0) {
+ TEARDOWN_HANDLER = findTryHandler(firstItem.parentBlock) ?? rendererRegionTryHandler(firstItem);
+ TEARDOWN_BLOCK = firstItem;
+ }
+ if (firstItem !== null) TEARDOWN_DEPTH++;
+ try {
+ for (let b: Block | null = firstItem; b !== null; b = b.nextSibling) {
+ if (b.cleanups !== null || b.children !== null || b._slots !== null) {
+ unmountBlock(b, false);
+ } else {
+ // Pure-host de-opt item (deoptItemBody with no component descendants):
+ // nothing to unmount scope-wise, but its subtree may carry stamped refs
+ // that must not keep pointing at the batch-removed DOM. Guarded so the
+ // common template-row clear stays a single null check; `deoptRefs`
+ // additionally skips the subtree scan for ref-free items.
+ if (b.deoptNode !== null && b.deoptRefs) detachDeoptTreeRefs(b.deoptNode, null);
+ b.disposed = true;
+ if (STAGED_COMMIT_CAPTURE) DEFERRED_LAYOUT_DRIVER!.retireHosts(b);
+ else b.retired = ++eventRootEpoch;
+ }
+ }
+ const p = domNode(state.start).parentNode!;
+ if (domNode(state.start).previousSibling === null && getNextSibling(state.end) === null) {
+ // forBlock owns the parent — nuke everything in one DOM op, then re-add markers.
+ (STAGED_DOM?.view(p as Element) ?? (p as Element)).textContent = '';
+ (STAGED_DOM?.view(p) ?? p).appendChild(state.start);
+ (STAGED_DOM?.view(p) ?? p).appendChild(state.end);
+ } else if (oldItems.size < RANGE_CLEAR_MIN_ITEMS) {
+ // Shared parent (other JSX interleaved) — detach the marker span directly.
+ // Each removal takes a whole item subtree, so this is one call per ITEM,
+ // not per node.
+ removeRange(getNextSibling(state.start), state.end);
+ } else if (STAGED_DOM !== null) {
+ STAGED_DOM.clearBetween(state.start, state.end);
} else {
- // Pure-host de-opt item (deoptItemBody with no component descendants):
- // nothing to unmount scope-wise, but its subtree may carry stamped refs
- // that must not keep pointing at the batch-removed DOM. Guarded so the
- // common template-row clear stays a single null check; `deoptRefs`
- // additionally skips the subtree scan for ref-free items.
- if (b.deoptNode !== null && b.deoptRefs) detachDeoptTreeRefs(b.deoptNode, null);
- b.disposed = true;
- if (STAGED_COMMIT_CAPTURE) DEFERRED_LAYOUT_DRIVER!.retireHosts(b);
- else b.retired = ++eventRootEpoch;
+ // Large shared-parent clear — one bulk DOM call amortizes the Range setup.
+ const range = document.createRange();
+ range.setStartAfter(state.start);
+ range.setEndBefore(state.end);
+ range.deleteContents();
}
+ } finally {
+ if (firstItem !== null && --TEARDOWN_DEPTH === 0) dispatchTeardownErrors();
}
- const p = domNode(state.start).parentNode!;
- if (domNode(state.start).previousSibling === null && getNextSibling(state.end) === null) {
- // forBlock owns the parent — nuke everything in one DOM op, then re-add markers.
- (STAGED_DOM?.view(p as Element) ?? (p as Element)).textContent = '';
- (STAGED_DOM?.view(p) ?? p).appendChild(state.start);
- (STAGED_DOM?.view(p) ?? p).appendChild(state.end);
- } else if (oldItems.size < RANGE_CLEAR_MIN_ITEMS) {
- // Shared parent (other JSX interleaved) — detach the marker span directly.
- // Each removal takes a whole item subtree, so this is one call per ITEM,
- // not per node.
- removeRange(getNextSibling(state.start), state.end);
- } else if (STAGED_DOM !== null) {
- STAGED_DOM.clearBetween(state.start, state.end);
- } else {
- // Large shared-parent clear — one bulk DOM call amortizes the Range setup.
- const range = document.createRange();
- range.setStartAfter(state.start);
- range.setEndBefore(state.end);
- range.deleteContents();
- }
oldItems.clear();
}You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 46a8577. Configure here.
Since batchClearItems disposes items before clearing their DOM, each item's unmountBlock was an outermost teardown that dispatched queued cleanup errors on return. An ancestor @catch could then re-render and dispose the list while the clear still wrote through state.start. Hold one teardown bracket across the items and the DOM clear, as unmountBlock does for its own range, so errors reach their boundary only after the list is cleared and its map emptied. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Take main's blur-during-teardown fixture from #1548 and format it, with the fixtures main added, using @tsrx/prettier-plugin 0.5; each compiles to the same output. Co-Authored-By: Claude Opus 5.5 <[email protected]>
* fix(octane): retire a deletion's hosts before its cleanups run Deletion cleanups run parent first. A dialog that restored focus in its own layout cleanup started onBlur on an input owned by a child component the teardown had not reached yet, and the same happened for a value-hole input in a removed @for row: #1548 retired each Block only when its own unmount began. Replace #1548's per-host owner claim and per-Block epoch with #1549's DOM-root stamp, applied before any cleanup at every committed deletion: the deferred range removal, parked keyed rows, root.unmount, and a portal's own content. An inert list clear retires only the row holding the scheduler's captured focus, and parked rows are stamped only when focus was captured, so an unfocused bulk removal does no per-row work. Handler publication no longer writes an owner expando on every host. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(octane): classify the focused-row climb and retire every portal teardown The owned-list clear read row.parentNode directly; read it through domNode so the staged-DOM boundary check classifies it (lint checks). Stamp a portal's own range in unmountBlockInner rather than only in teardownPortalState, so a portal torn down through unmountSlot's portal branch, such as one detaching under a retained hydration parent, retires its content before its cleanups run too. A non-parkable list clear stamps each row before its cleanup under the same captured-focus rule as parked rows. Add a regression for a portal compiled in a template. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(octane): retire a non-parkable list clear's rows before any row's cleanup batchClearItems stamped each row just before that row's own teardown, so an earlier row's cleanup that moved focus could still start onBlur on a later row the same clear was removing. Stamp the whole span between the list's markers first, under the same captured-focus rule as parked rows. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(octane): keep an interleaved independent portal live when its Fragment owner unmounts Stamping every portal Block's range in unmountBlockInner also stamped a foreign portal range parked between a Fragment owner's markers, so a click on that still-mounted portal in the same task started no handler (conformance/fragment-future-children). Retire a portal's range in teardownPortalState again: a portal compiled into a template routes its events through a host element inside its owner, which the enclosing deletion has already retired before any cleanup runs. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(octane): drop the blockless de-opt retirement hook Every transactional blockless de-opt removal now commits through deferRootRange, which retires its nodes before their cleanup runs, so the stamp detachDeoptTreeRefs added for #1549 repeats it. Removing it returns detachDeoptTreeRefs to its single recursive form and keeps root-chained-jsx within the budget main tightened to 84,352 raw bytes. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>


Summary
focusoutsynchronously, after Octane has already disposed the component that owns it. Delegated dispatch no longer starts handlers on hosts whose component has unmounted.onBlurused to reportScopeDisposedError(production error 151). A plainonBlurused to run for an unmounted component, which React never does.Closes #1472
Why
Teardown disposes a Block before detaching its DOM. This order is deliberate: deletion cleanups observe attached DOM, as in React. Removing a focused host makes Chromium dispatch
focusoutwhile the removal is in progress, and Octane's delegation still invoked the retired handlers. The bug reproduced on current main for:root.render(null);@ifarm unmounting the input's owning component;@forrow removal.Changes
setEventHandlerrecords the Block that rendered each event host in$$eventOwner, seeded onElement.prototype. A live claim is never replaced, because lite@forrows republish bare handlers under their list's Block. A disposed claim is replaced, because a hydration retry adopts the same server node under a new Block.retireEventOwner). This applies to Block unmount and to both list-clear paths. A ViewTransition deletion records it only when it publishes, so its committed hosts stay interactive until then.snapshotDelegatedSlotsskips a host only if it retired before the native delivery began, using the delivery's existingEVENT_ROOT_EPOCHstamp.docs/differences-from-react.md.blur-during-teardown/discrete-flush-reentrancypreviously asserted that a disposed@ifarm'sonBlurruns. The counted handler now sits on a live ancestor, so the no-re-entrant-flush purpose is unchanged, and the test asserts that the disposed arm's handler does not run.Differences from the fix proposed in the issue
disposedcheck broke two existing contracts:portal-events.test.ts, browserevent-metadata);view-transition-staging.test.ts).setEventHandlercompiler target can reach it, so it is speculative and untestable through a public path.Validation
pnpm typecheck:filesandpnpm format:files:checkon the changed filespnpm format:check(repo-wide): not runpnpm typecheck(repo-wide): not runpnpm test, replayed locally as CI's four shards (vitest.ci-sharded.config.js, CI excludes), on the pre-merge branch:pnpm testran out of the Vitest main process's 4 GB heap after 29 minutes, which is why the shards were replayed.octane-events-browserandoctane-signals-browser: 28 files, 365 tests, before the merge.retired-event-hosts,discrete-flush-reentrancy,portal-events,view-transition-staging,event-signal-owner, and the hydration retry suites (octaneandoctane-prod, 348 tests), plus the browserretired-event-hostsandevent-metadata(26 tests). All pass. A broader post-merge run hit timeouts at load average ~72; CI covers the full suite.tests/browser/retired-event-hosts: 11 scenarios, each in dev and prod builds.tests/retired-event-hosts.test.ts(octaneandoctane-prod) covers a deletion cleanup that moves focus. It fails on main.@forrow-update case.run-minimal.mjs --budgets ...,behavior-root(unchanged), andbinding-apollo-client.root-chained-jsxneeds +75 gzip / +115 brotli over current main (28,324 → 28,399 gzip) for the Block field, the inline disposal stamp, and the dispatch check, while main had only 60 gzip bytes of headroom left. Its gzip and brotli ceilings rise by one 32-byte step (28,384 → 28,416 and 25,248 → 25,280); raw stays within 85,728 and every other budget is unchanged.benchmarks/view-transitions/effect-cleanup.mjs(function-call budget) passes; clears are back to baseline (tsrx cold clear 47,088 calls against 47,089) because the disposal stamp is inline rather than a per-Block call.batchClearItems' immediate path now disposes items before clearing their DOM.Risk / follow-ups
{editing && <input onBlur={commit} />}) still runs itsonBluron removal, because its owner Block stays live. A stacked follow-up PR covers it.retired). A ViewTransition deletion retires its Blocks through one deferred-layout-driver action per capture, so that code ships only with ViewTransition. The global event-route epoch now advances per retired Block, so a delivery that spans an unmount takes the general (portal-aware) path builder for its remaining phases.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 core delegated event dispatch and teardown ordering during unmount; behavior is well-tested but touches hot paths and ViewTransition staging.
Overview
Fixes #1472: when teardown removes a focused element, Chromium fires synchronous
focusout, and Octane no longer runs delegated handlers on hosts whose component was already disposed.Each event host records its rendering Block in
$$eventOwner. On unmount (and staged ViewTransition publish), blocks get aretiredevent-route epoch before DOM is detached.snapshotDelegatedSlotsdrops handlers on hosts retired before the current native delivery started (usingEVENT_ROOT_EPOCH), while in-flight dispatches and still-mounted ancestors keep working—unlike React, which suppresses all commit-time events.batchClearItemsand related teardown paths now dispose/retire items before bulk DOM removal, with teardown error boundaries aligned tounmountBlock. Docs note the React difference; bundle budget forroot-chained-jsxrises slightly. New browser and jsdom tests cover unmount, portals,@if/@for, and signalonBlurcases.Reviewed by Cursor Bugbot for commit 5ab6b84. Bugbot is set up for automated code reviews on this repo. Configure here.