Skip to content

refactor: reduce root render transaction bookkeeping - #982

Merged
domgan-oai merged 7 commits into
octanejs:mainfrom
openai-oss-forks:codex/fix-root-render-transactions-981
Sep 7, 2026
Merged

domgan-oai merged 7 commits into
octanejs:mainfrom
openai-oss-forks:codex/fix-root-render-transactions-981

Conversation

@domgan-oai

@domgan-oai domgan-oai commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Refs Track V8 performance audit findings across runtime, SSR, universal core, and compiler output #981. Reduce root render rollback bookkeeping for created blocks, binding bags, keyed lists, property writes, and resolved transition effects.
  • Fix the nested-window parked-row regression reported in review: capture each removed row's exact DOM range before a later rollback window can detach it. Add public .tsrx regressions for multi-node rows, connected cleanup, and subsequent insertion.
  • Skip redundant binding-bag snapshots only for blocks created and discarded by the active root transaction, while preserving journaling for retained/hydrated scopes and externally owned DOM. Add a held fresh-scope regression. This addresses the safe fresh-scope part of item 1 and findings 2, 4, 5, 7, and 8 in Track V8 performance audit findings across runtime, SSR, universal core, and compiler output #981; the lazy parked-range optimization from item 6 has been withdrawn. This PR does not close the coordination issue.

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

  • Track created blocks with transaction stamps and flat journal entries, retaining reverse rollback order.
  • Use fixed-arity binding-bag clones and window stamps for existing scopes, and bypass their snapshots for newly created, non-retained root scopes in the root window.
  • Pass old values at property write sites, use numeric slot indices, and hoist root-journal checks out of keyed survivor loops.
  • Snapshot keyed chains compactly while preserving prior Map insertion order. Capture parked DOM ranges eagerly so nested rollback windows can restore the exact same rows; preserve borrowed @empty content and connected cleanup timing.
  • Avoid the resolved-transition effect-subtree prewalk when the root journal captures touched cells; keep it for urgent supersession, propagation, detached renders, and a queued transition child forced urgent by its ancestor. Keep dependency reset after deactivateScope cleanup across suspended retries: undoing only its dependencies could suppress reconnection.

Validation

  • Two new public .tsrx regression 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.
  • Direct tsc --noEmit -p packages/octane/tsconfig.json, scoped .tsrx typecheck, Prettier on changed files (final runtime through the same TS options using an intact dependency checkout), and git diff --check pass.
  • Final-head pinned compiled benchmark at 7c9aacfd5 against main 1e6ca0ed6: 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.
  • Compiled Activity ABAB (eight samples in each of two base and two candidate runs): mount 4.0/4.0 ms base vs 4.1/4.2 ms candidate; visible updates 10.0/9.5 vs 8.8/9.5; plain updates 9.6/10.3 vs 9.3/9.3; hide/reveal 13.3/13.7 vs 13.6/13.4. All 12 operations passed semantic gates, and named work/DOM-write counters match. Timing drift between two pinned runs is substantial, so no application speedup is claimed. The compiled Activity JS asset grows 216,357 → 218,731 raw bytes (+2,374); Vite reports the candidate js-framework fixture as 30.79 kB gzip, rounded. The reviewer's older gzip number used a different minifier before fix: standardize benchmark Vite minification on esbuild #983, so it is not directly comparable.
  • Current-head CI on 7c9aacfd5: all 26 jobs passed, including four Node test shards (new .tsrx regressions in development and production), four React parity shards, website and Chromium integration, typecheck, lint, package validation, and provenance.
  • Source-only public createRoot/Suspense hidden-retry probe logs setup → cleanup → setup across 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.
  • Local pnpm sync, pnpm typecheck, and full pnpm test: the frozen install cannot fetch pinned TSRX packages (registry 403 and gateway timeouts), and the available older installation lacks the current @tsrx/core export. pnpm sync stopped at its install precheck; direct version, inventory, and other generators produced no tracked changes. Pinned CI compiles and runs the new .tsrx tests.

Risk / follow-ups

  • The source-only descriptor control previously reported an inconclusive update timing and bundle growth; the compiled, pinned results above supersede it. The keyed rollback path remains sensitive to journal window ordering; the new test exercises actual fragment rows, identity, cleanup, and subsequent insertion.
  • Follow-up ideas such as flatter per-property bag journaling, coalescing window stacks, and stamping retired rows need separate performance and rollback evidence. The same-drain @empty rollback failure described in review reproduces on both main and the original PR head. It is tracked separately in #984, with the public repro and rollback ownership gap.

Provenance

  • An agent produced this diff (agent-authored)

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with 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 createdStamp values and JOURNAL_CREATED undo entries instead of a Set plus 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 __journalWindow stamps.

Property journaling now records the old value at the write site (numeric slot keys where applicable). Keyed @for rollback 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 .tsrx tests 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.

@domgan-oai
domgan-oai marked this pull request as ready for review September 7, 2026 19:35
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent perf PR: performance work labels Sep 7, 2026

@trueadm trueadm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 test keeps committed siblings when a previously synchronous reader throws its first thenable pins 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.md nor differences-from-react.md promises 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-write nodeValue/getAttribute read 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 = _v with the previous value in hand; a flat JOURNAL_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 @try window that touched it commits (the old checkpoint dedup skipped that), and the effect cells are journaled at two depths in this PR (five journalObjectOnce(effect) sites, one flat journalRootProperty(e, 'deps') in deactivateScope).

Smaller

  • transaction.created: Block[] is a dead duplicate of the JOURNAL_CREATED entries; its only reader (suspendRootRender's warm-memo loop) can scan the log. That is a push per created block on every mount.
  • parkItemForHold still allocates a closure, a Set entry and a {block, nodes} record per removed row via retireRootBlock; the createdStamp pattern applies here too (retiredStamp + flat entry).
  • Two window stacks and two id counters mirror each other (TRANSITION_JOURNAL_BAG_WINDOWS alongside TRANSITION_JOURNAL_WINDOWS, NEXT_ROOT_RENDER_CREATED_STAMP alongside NEXT_TRANSITION_JOURNAL_BAG_WINDOW); one stamp per transaction and (checkpoint, window) pairs on the existing stack do the same job. const window in journalBag shadows 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-implements collectBlockRange, which takeParkedItem now calls for the same item.
  • createdStamp is read through scope.block in registerSlot/childSlot, and that is a LiteBlockImpl for every lite scope, which does not declare it (2-map load; no behavior change).
  • journalForSlot iterates state.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).
  • setDangerouslySetInnerHTML and setDangerouslySetInnerHTMLSources now read the DANGER_HTML_* symbols unconditionally (the read used to sit behind journalRootProperty's early return), one of them twice in a row.
  • The renderVisibleTry gate reads the try block's queued mode, while renderBlockInner can force that render urgent (urgentTransitionRender); an urgent suspension then takes the @pending path 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 the nativeReads retry paths), so treat it as a one-line hardening: mirror renderBlockInner'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 @empty block (borrowed markers) saves the whole live range, which includes rows parked earlier in the same wave, so after rollback restores those rows unmountParkedItem(@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's hydrating flip 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 the JOURNAL_CREATED branch in rollbackRootRender's owner.current === null path. Also worth saying in the PR body: 4221fbfa8 broke @empty lists app-wide (12 owning-package tests and the website suite red in CI) before fcfe7434c fixed 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.
@domgan-oai domgan-oai changed the title perf: reduce root render transaction bookkeeping refactor: reduce root render transaction bookkeeping Sep 7, 2026
@github-actions github-actions Bot added refactor PR: internal restructuring, no behavior change and removed perf PR: performance work labels Sep 7, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

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.

Comment thread packages/octane/src/runtime.ts Resolved
@domgan-oai

Copy link
Copy Markdown
Contributor Author

@trueadm I addressed the two blocking findings and the effect-cell follow-up on the current PR branch:

  • Nested keyed rollback: 281ba4f88 restores eager capture of each parked row's exact node range. The public multi-node .tsrx regression reproduces the prior missing-row/NotFoundError path, then checks original node identity, connected cleanup, and a later keyed insertion. The lazy parked-range optimization is withdrawn.
  • Production mount gate: journalBag now skips snapshots only for scopes created and discarded in the same root transaction's outer window. It retains snapshots for hydration, retained blocks, and nested boundary windows; live text/attribute writes to committed or external DOM still journal. The final-head pinned compiled benchmark records 33,081 / 35,000 production calls per 1,000-row mount (1,919 margin) with all eight correctness iterations passing; artifact.
  • Effect rollback: I removed the selective deps undo from deactivateScope in 7c9aacfd5. A cleanup cannot be undone, so restoring only deps could suppress the next setup. The ordinary Activity and Suspense hide actions run after root acceptance; a source-only public Suspense hidden-retry/root-hold probe touched the journaled path with already cleared deps and observed setup → cleanup → setup. This is an invariant correction; I did not reproduce the bot's claimed failure through public APIs.

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 perf: to refactor: and do not claim an application speedup from timings that overlap runner variance.

I corrected the new borrowed-@empty comment and filed the pre-existing same-drain overlap as #984. The hydrated parked-row improvement mentioned in review is not established by unmountBlock's guard: unmountParkedItem already calls it with false and explicitly removes saved nodes. I left that claim out of the changeset pending a deterministic SSR/hydration test. The per-property bag journal, window consolidation, retired stamps, and other optional hot-path changes need separate rollback and benchmark evidence.

Current-head CI is green at 7c9aacfd5 (all 26 jobs). Compiled Activity ABAB passed semantics and named work checks. Update timing overlaps runner variance, and the fixture grew 2,374 raw bytes with the current esbuild minifier; the PR description includes all base/candidate timings and provenance. The PR base remains live main at 1e6ca0ed6 and the worktree is clean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-authored Diff or issue body substantially produced by an AI agent refactor PR: internal restructuring, no behavior change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants