Repository navigation
refactor: reduce root render transaction bookkeeping - #982
domgan-oai merged 7 commits into
Conversation
trueadm
left a comment
There was a problem hiding this comment.
Review of bab20fddd against main @ ac690331b. Read the whole diff plus the enclosing functions, ran the new tests (132/132 pass), re-measured the PR head against main on the repo's own harnesses (Node 24.18.0, Chromium 149, ABAB, 8 iterations), and wrote reproductions for the two rollback paths the diff changes most. One blocking correctness regression, one blocking benchmark-gate trip, and the measured gain is modest. Posting as a comment rather than a review state so the maintainer decides.
Blocking
1. A parked keyed row can come back from rollback with no DOM, then crash the root
parkItemForHold now leaves nodes = null for an owned-marker row that stays connected (runtime.ts:3154), and takeParkedItem re-derives the range at rollback time with collectBlockRange (:3359). That only works if nothing detached the row between park and restore. A later window's restoreForSlot does exactly that: its unmatched-node sweep (:3335) removeChilds the parked row's still-connected range, and by the time the earlier window's restore runs takeParkedItem, collectBlockRange sees start.parentNode === null and returns []. The row is relinked into the chain and key Map with no DOM.
Trigger, all through public APIs: a resolved @try containing a keyed @for in its own component, and a root-level use() deeper in the tree. In one act: an urgent parent update reconciles [a,b,c] → [a,c] in the root window (b parked, nodes = null), then a startTransition that both updates the list owner ([a,c] → [c], rendered through renderVisibleTry in a nested window, so journalForSlot snapshots again) and flips the root suspender. Root rollback replays the nested window first.
Observed on the PR head: after the wave the list shows row-a,row-c, row-b.isConnected === false, no cleanup fired; a following urgent insert anchored on b throws NotFoundError: The child can not be found in the parent. and the uncaught-error path unmounts the whole root. On ac690331b the same tests pass (the saved nodes[] were reinserted regardless of liveness). Fixture and test are below; I re-ran them on both checkouts myself.
Reproduction (fixture + test)
// tests/_fixtures/parked-two-windows.tsrx
import { use, useEffect, useLayoutEffect, useState } from 'octane';
function Row(props) @{
const [seen] = useState(props.id + '!');
useLayoutEffect(() => () => props.onLayoutCleanup?.(props.id), []);
useEffect(() => {
props.log?.('mount:' + props.id);
return () => props.log?.('cleanup:' + props.id);
}, []);
<li id={'row-' + props.id}>{seen as string}</li>
}
function ListOwner(props) @{
const [local, setLocal] = useState(0);
props.api.setLocal = setLocal;
const items =
local === 1 ? ['c']
: local === 3 ? ['a', 'x', 'b', 'c']
: props.step === 0 ? ['a', 'b', 'c'] : ['a', 'c'];
<ul id="list">
@for (const id of items; key id) {
<Row id={id} log={props.log} onLayoutCleanup={props.onLayoutCleanup} />
}
</ul>
}
function RootSuspender(props) @{
const [susp, setSusp] = useState(0);
props.api.setSusp = setSusp;
const value = use(props.load(susp));
<span id="value">{value as string}</span>
}
function Deep3(props) @{ <RootSuspender api={props.api} load={props.load} /> }
function Deep2(props) @{ <Deep3 api={props.api} load={props.load} /> }
function Deep1(props) @{ <Deep2 api={props.api} load={props.load} /> }
export function TwoWindowUrgentThenTransition(props) @{
const [step, setStep] = useState(0);
props.api.setStep = setStep;
<div>
@try {
<ListOwner step={step} api={props.api} log={props.log} onLayoutCleanup={props.onLayoutCleanup} />
} @pending {
<span id="fallback">{'fallback'}</span>
}
<Deep1 api={props.api} load={props.load} />
</div>
}// tests/parked-two-windows.test.ts (uses this suite's mount/act helpers)
it('a row parked in the root window survives a nested-window restore sweep', async () => {
const next = deferred<string>();
const load = (s: number) => (s === 0 ? fulfilled('zero') : next.promise);
const api: any = {};
const r = mount(TwoWindowUrgentThenTransition, { api, load, log: () => {}, onLayoutCleanup: () => {} });
await act(() => {});
const original = r.findAll('#list li');
await act(() => {
api.setStep(1);
startTransition(() => { api.setLocal(1); api.setSusp(1); });
});
// Held: every committed row must be back with its own DOM.
expect(r.findAll('#list li').map((li) => li.id)).toEqual(['row-a', 'row-b', 'row-c']); // PR head: ['row-a','row-c']
expect(original[1].isConnected).toBe(true); // PR head: false
await act(() => api.setLocal(3)); // PR head: NotFoundError, root unmounted
next.resolve('one');
r.unmount();
});The saved node list was the thing that made restore independent of what other windows did to the list in between. Either keep capturing it (the walk is the cost the PR wanted to avoid, but it is per removed row, not per render), or make restoreForSlot take parked rows before its sweep and treat an already-detached parked row as an error rather than an empty range.
2. The js-framework mount gate trips on the PR head
benchmarks/js-framework/run.mjs caps octane-tsrx at 35,000 production calls per 1k-row create. Base: 34,081. PR head: 35,081, exactly +1 per row, deterministic across rounds, so the harness aborts before timing and the weekly bench.yml run will go red. Attribution (unminified, totals match the gate):
| function | base | PR |
|---|---|---|
journalUndo / journalObjectOnce |
1,001 / 1,000 | 1 / 0 |
isCreatedInRootRender |
0 | 1,000 |
cloneBindingBag + cloneBag8 |
0 | 1,000 + 1,000 |
Every freshly created row's bag is still snapshotted, now through the arity switch. That is dead work: a block created inside the current transaction is discarded wholesale by JOURNAL_CREATED → undoCreatedInRootRender on rollback, so journalText/journalAttr/journalBag never need to run for writes inside a scope the transaction created. Skipping them when !CURRENT_SCOPE.mounted (and the transaction is neither hydrating nor has the block in retainedCreated) fixes the gate and removes real work on create/append paths. This is the contract-preserving part of #981 item 1 that the raw-thenable argument does not touch: that argument only establishes that writes into committed content need undo entries.
Measured effect
The PR body's own timing is inconclusive and its size numbers show growth, and none of the repo's suites were run. I ran them (bench worktree at bab20fddd vs a detached ac690331b, same toolchain, ABAB):
| benchmark (ms, round 1 / round 2) | base | PR | verdict |
|---|---|---|---|
activity plain_updates |
3.62 / 3.54 | 3.40 / 3.36 | −5.6%, beyond noise |
activity mount_visible |
1.68 / 1.62 | 1.38 / 1.24 | −20.6%, beyond noise |
| activity hide_reveal / visible_updates / hidden_burst / nested | — | — | within noise |
| js-framework create 1k | 2.38 / 2.64 | 2.70 / 2.76 | +8.8% pooled, inside 10% noise |
| js-framework append / replace / runlots / clear | — | — | within noise |
effectful-list update_deps / clear / remove_100 (1 run) |
2.95 / 1.34 / 0.93 | 2.50 / 1.13 / 0.75 | −15% / −16% / −19% |
effectful-list update_nodeps (1 run) |
0.27 | 0.29 | +9%, hint only |
| js-framework fixture, gzip | 29,357 B | 29,921 B | +564 B (+1.9%), all runtime |
work.mjs counters: journalObjectOnce 6,156 → 0 on plain_updates; every other named helper identical; journal* total 24,648 → 18,492 (−25%). So the change is real but bounded: about a quarter of the journal calls and ~6% of a plain update, against +1.9% runtime gzip. For scale, gating the transaction off on the same fixture measured −39% on plain_updates (#981).
The changeset and title should say what was measured; core-engineering.md asks for that before a perf: claim.
Design
- Item 1 of #981 is not a binary choice. The raw-thenable-after-sibling-write case only needs the journal for writes into committed content. Fresh scopes never do (above). And a root that has never suspended could arm lazily: the first raw throw in an unarmed root takes the pre-#833 unmount-and-retry path once, then that root stays armed. Whether that one-time divergence for an exotic pattern (a component throwing a raw promise on a re-render, outside any boundary, having never used
use()) is acceptable is a product call, and the testkeeps committed siblings when a previously synchronous reader throws its first thenablepins the answer as "no" without saying so. Worth an explicit decision in the PR body. - "External DOM edits survive rollback" is a contract this PR introduces. Neither
SUSPENSE_DIVERGENCE.mdnordifferences-from-react.mdpromises it, and the binding guard overwrites a foreign edit on the next value change anyway. If it is wanted, document it in §10 and the per-writenodeValue/getAttributeread is justified. If not, the compiled helpers already receive the previous value (setAttributeIfChanged(value, previous, …),childTextHoleUpdate(…, previous)) and item 3 is a small change. - Whole-bag clones may be the wrong depth. The compiler emits the journal call before
_b.x = _vwith the previous value in hand; a flatJOURNAL_PROP(bag, key, previous)per written field would remove the clone, the brand, the per-bag stamp and the second window stack. If the clone stays, note that the stamp re-clones a bag in the outer window after a nested@trywindow that touched it commits (the old checkpoint dedup skipped that), and the effect cells are journaled at two depths in this PR (fivejournalObjectOnce(effect)sites, one flatjournalRootProperty(e, 'deps')indeactivateScope).
Smaller
transaction.created: Block[]is a dead duplicate of theJOURNAL_CREATEDentries; its only reader (suspendRootRender's warm-memo loop) can scan the log. That is a push per created block on every mount.parkItemForHoldstill allocates a closure, a Set entry and a{block, nodes}record per removed row viaretireRootBlock; thecreatedStamppattern applies here too (retiredStamp+ flat entry).- Two window stacks and two id counters mirror each other (
TRANSITION_JOURNAL_BAG_WINDOWSalongsideTRANSITION_JOURNAL_WINDOWS,NEXT_ROOT_RENDER_CREATED_STAMPalongsideNEXT_TRANSITION_JOURNAL_BAG_WINDOW); one stamp per transaction and(checkpoint, window)pairs on the existing stack do the same job.const windowinjournalBagshadows the global. - The 17
cloneBagN+ switch block is ~244 B gzip, about 40% of the growth;default: { ...bag }is unreachable. A table of 17 arrows keeps the per-arity feedback vectors at a fifth of the size. parkItemForHold's new branch re-implementscollectBlockRange, whichtakeParkedItemnow calls for the same item.createdStampis read throughscope.blockinregisterSlot/childSlot, and that is aLiteBlockImplfor every lite scope, which does not declare it (2-map load; no behavior change).journalForSlotiteratesstate.items.values()on every structural journal to detect Map/chain order divergence; a sticky flag set at the LIS relink and mid-chain insert sites makes the common case O(1).setDangerouslySetInnerHTMLandsetDangerouslySetInnerHTMLSourcesnow read theDANGER_HTML_*symbols unconditionally (the read used to sit behindjournalRootProperty's early return), one of them twice in a row.- The
renderVisibleTrygate reads the try block's queued mode, whilerenderBlockInnercan force that render urgent (urgentTransitionRender); an urgent suspension then takes the@pendingpath with no journal replay and the attempt-advanced effect deps are never restored. I could not reach it through public APIs (a try block is only scheduled directly by thenativeReadsretry paths), so treat it as a one-line hardening: mirrorrenderBlockInner's condition in the gate. - Pre-existing, not introduced here, but the PR rewrote the branch and its new comment says the opposite: a parked
@emptyblock (borrowed markers) saves the whole live range, which includes rows parked earlier in the same wave, so after rollback restores those rowsunmountParkedItem(@empty)removes them again. Reproduced on both base and PR head ([a,b,c]→ emptied → refilled in one drain → root suspension → list is[]while held). - The hydration-rollback behavior change (
unmountBlock'shydratingflip now keeps a parked server row connected) is an improvement over base, which deleted the row from the retained server screen. It deserves a test and a line in the changeset. - Tests: nothing discriminates the cross-window bag dedup after an inner rollback,
mapOrder(the keyed test asserts DOM order, which is Map-order independent), multi-node fragment rows parked without node lists, a first-time conditional hook inside a held transition, or theJOURNAL_CREATEDbranch inrollbackRootRender'sowner.current === nullpath. Also worth saying in the PR body:4221fbfa8broke@emptylists app-wide (12 owning-package tests and the website suite red in CI) beforefcfe7434cfixed it, and the keyed test's first execution anywhere was in CI.
What I ran
pnpm vitest run packages/octane/tests/suspense-preserves-dom.test.ts packages/octane/tests/transitions.test.ts (PR head, 132 pass); the reproduction above on both checkouts; benchmarks/activity/run.mjs 8 --target=octane-tsrx, benchmarks/js-framework/run.mjs 8 (octane-tsrx only), benchmarks/activity/work.mjs, benchmarks/effectful-list/run.mjs once per variant, gzip of the built fixture; pnpm format:files:check on the six files (clean). Static review of every journalRootProperty site (all 60 pass the pre-write value), both log consumers, all four window push/pop pairs, and every effect-cell writer.
Skip disposable fresh binding-bag snapshots and document live DOM restoration. Add regression coverage for nested keyed windows and fresh scopes.
…er-transactions-981
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, but it could not run because the branch was deleted or merged before autofix could start.
Reviewed by Cursor Bugbot for commit 42fb699. Configure here.
|
@trueadm I addressed the two blocking findings and the effect-cell follow-up on the current PR branch:
The root still arms before the first possible raw-thenable throw to preserve the already documented committed-screen hold after earlier sibling writes. The narrowly defined rollback of live text/attribute values, including edits made outside Octane, is now explicit in audit §10. I changed the title from I corrected the new borrowed- Current-head CI is green at |

Summary
.tsrxregressions for multi-node rows, connected cleanup, and subsequent insertion.Root-hold contract
A component may throw its first raw thenable after a committed sibling has written text or attributes. The current root contract restores that sibling and holds the committed screen, so arming transactions only after that throw would change behavior. Fresh blocks created within a transaction can skip their bag snapshot because rollback discards them. Live text and attribute reads on writes into committed DOM remain necessary to restore the immediately preceding value, including an external edit made during a hold; this narrow behavior is now documented in
packages/octane/audit/SUSPENSE_DIVERGENCE.md§10. The authored binding is applied on a successful retry.Changes
@emptycontent and connected cleanup timing.deactivateScopecleanup across suspended retries: undoing only its dependencies could suppress reconnection.Validation
.tsrxregression suites pass in CI (development and production): parked rows across nested rollback windows, and fresh root scopes under a sibling suspension. The first repro fails on the prior PR head and passes with the fix.tsc --noEmit -p packages/octane/tsconfig.json, scoped.tsrxtypecheck, Prettier on changed files (final runtime through the same TS options using an intact dependency checkout), andgit diff --checkpass.7c9aacfd5againstmain1e6ca0ed6: js-framework 1,000-row production mount uses 33,081 / 35,000 calls (1,919 below the ceiling), with eight correctness iterations passing. Artifacts record the exact source revisions, pinned Node 24/Chromium/compiler versions, fixture hash, and Activity ABAB results. The benchmark workflow changed only on an isolated fork branch, never this PR.7c9aacfd5: all 26 jobs passed, including four Node test shards (new.tsrxregressions in development and production), four React parity shards, website and Chromium integration, typecheck, lint, package validation, and provenance.createRoot/Suspensehidden-retry probe logssetup → cleanup → setupacross a root hold; a temporary trace observed two deactivations inside a root journal with dependencies already cleared. The bot’s exact failure was not reproduced, and the selective dependency undo was removed to preserve the reconnect invariant.pnpm sync,pnpm typecheck, and fullpnpm test: the frozen install cannot fetch pinned TSRX packages (registry 403 and gateway timeouts), and the available older installation lacks the current@tsrx/coreexport.pnpm syncstopped at its install precheck; direct version, inventory, and other generators produced no tracked changes. Pinned CI compiles and runs the new.tsrxtests.Risk / follow-ups
@emptyrollback failure described in review reproduces on bothmainand the original PR head. It is tracked separately in #984, with the public repro and rollback ownership gap.Provenance
agent-authored)Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Note
High Risk
Changes core root suspense rollback, keyed-list restore, effect invalidation, and DOM journaling—areas where subtle ordering bugs directly affect visible UI and lifecycle timing.
Overview
This PR reduces work during root-held suspense rollbacks while keeping the same retained-DOM, cleanup timing, and retry semantics documented for issue #821.
Created blocks are tracked with per-transaction
createdStampvalues andJOURNAL_CREATEDundo entries instead of aSetplus per-block unmount callbacks. Blocks born in the current root attempt can skip binding-bag snapshots because rollback tears them down wholesale; existing scopes use fixed-arity bag clones and per-window__journalWindowstamps.Property journaling now records the old value at the write site (numeric slot keys where applicable). Keyed
@forrollback stores a slimmer snapshot (chain + optional map insertion order) and eagerly saves parked row node lists so nested journal windows cannot detach DOM that a later rollback must restore.Transition/suspense rendering skips the subtree effect-deps prewalk when the root journal will replay touched effect cells, but keeps it for urgent supersession, propagation, detached renders, and urgent ancestors forcing transition children.
Docs note that abandoned root attempts restore live text/attributes (including external edits). New
.tsrxtests cover fresh scopes under sibling suspension, multi-window keyed rollback, sibling writes before first raw thenable throw, and effect lifetimes across held transitions.Reviewed by Cursor Bugbot for commit 7c9aacf. Bugbot is set up for automated code reviews on this repo. Configure here.