Skip to content

feat: close the React 19 parity implementation gaps (#711) - #715

Merged
trueadm merged 2 commits into
mainfrom
feat/react19-impl-gaps
Aug 12, 2026
Merged

trueadm merged 2 commits into
mainfrom
feat/react19-impl-gaps

Conversation

@trueadm

@trueadm trueadm commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Closes the "Implementation gaps" section of #711 (rebased onto main after #712 merged). Five gaps implemented; the sixth bullet (streaming post-shell resources) deliberately stays documented behavior per the issue.

  • Nested-under-host document metadata — the client/server asymmetry is gone in React's direction: <title>/<meta>/<link> and Float resources nested inside host elements now serialize into the head channel on the server too (previously a ssrUnsupported: HeadHoist compile error). The nested hoist is an expression fragment in the html evaluation: the head write happens at the authored position (identical conditional timing to the client's arm-scoped headBlock — a hoist in an @if arm registers only while that arm renders), the head emit functions now return '' so the body markup gains nothing, and the hydration cursor stays aligned with the client template. Hydration adopts with zero mismatch warnings.
  • prerenderToNodeStream — octane/static gains the stream variant with React's semantics: resolves only after the await-everything render completes; prelude streams the complete document bytes (scoped-style tags, then folded html; byte-identical to buffered prerender's css + html, pinned by test). No postponed field — postpone/resume stays a documented non-goal. node:stream loads lazily on call so edge bundles pay nothing; headChannel: 'separate' is ignored with a dev diagnostic.
  • Teardown errors reach the root callbacks — effect-cleanup and ref-detach throws during unmount route through onCaughtError (boundary-claimed) / onUncaughtError (unclaimed; replaces console.error). Implementation threads the outermost deleted block through the existing channels: TEARDOWN_BLOCK beside TEARDOWN_HANDLER, ref-detach queue stride 3→4, deferred passive-unmount pairs→triples. Routing semantics unchanged; controls pin the no-option behavior.
  • Resource hints share the Float identity model — preinit(as:'style') routes through stylesheetResource (honors precedence, default "default", joins the groups, dedupes against the rendered form), preinit(as:'script') through scriptResource; preload/preloadModule after the matching init are no-ops (one-way upgrade — preload-then-init keeps both tags); image preloads with imageSrcSet key on the srcset+sizes pair; malformed calls (missing/invalid as, empty href) warn in dev and stay no-ops. Client and SSR mirrored.
  • Universal renderer root callbacks — onCaughtError/onUncaughtError wired into octane/universal roots across every scheduler-owned channel (scheduled flush, transported async work, suspense replays, effect/commit callbacks), mirroring the DOM runtime's WeakMap-off-the-shape pattern. Two deliberate bounds, pinned by tests and doc comments: a direct render()/renderAsync() throw remains the documented result channel (unlike DOM's void root.render(), consuming it would leave nothing to return), and there is no onRecoverableError (the universal renderer has no hydration channel). Unclaimed event-handler errors still throw to the dispatcher (React parity).

Why

Issue #711's implementation-gap list, i.e. everything the React 19.2 parity audit found functionally missing that wasn't already decided away. The nested-metadata fix in particular removes a compile-time trap discovered while building #709's Float fixtures.

Changes

  • packages/octane/src/compiler/compile.js — HeadHoist case in ssrEmitNode (nested emission as an html-expression fragment).
  • packages/octane/src/runtime.server.ts — prerenderToNodeStream; head emit functions (ssrHeadEl, ssrStylesheetResource, ssrStyleResource, ssrScriptResource) return ''; hint validation + unified identity + image keying.
  • packages/octane/src/runtime.ts — teardown-block threading; hint validation/unification (preinit routes through the Float inserts, hasHeadHint, image-srcset keys).
  • packages/octane/src/universal-core.ts — universal root error callbacks (UniversalRootOptions.onCaughtError/onUncaughtError, handler WeakMap, claim + consumption sites).
  • packages/octane/src/static/index.ts — prerenderToNodeStream export + accurate module doc.
  • Ledger: ReactDOMFizzStaticNode-test.js "should call prerenderToNodeStream" → covered with evidence; coverage report regenerated.
  • Docs: differences-from-react.md (nested hoisting, teardown-error reporting, unified hint model), docs/ssr.md (prerenderToNodeStream implemented).
  • Tests: hydration/nested-head.test.ts (+fixture), static-prerender-stream.test.ts, teardown cases in root-error-callbacks.test.ts (+fixture throwers), hint hardening cases in resource-hints.test.ts, universal callback cases in universal-scheduling.test.ts. Changeset included.

Contract and hot paths

All additions are cold-path or compile-time: teardown threading adds one global write per outermost unmount and one extra queue slot per ref detach/passive unmount (teardown-only paths); the hint changes affect imperative hint calls only; the nested-head compiler case runs per authored nested-metadata element at compile time; universal handlers cost one module-null check on already-cold catch paths. The head emit functions' void → '' return-type change is invisible to existing compiled output (top-level emission is statement-position). No benchmarks run and none claimed — no hot path changed.

Validation

  • pnpm format:check

  • pnpm typecheck

  • pnpm test — 18,583/18,585. The two failures are pre-existing load-timing flakes (the phosphor-icons differential and one octane-events-browser native-change case); both pass in isolation, and neither touches any changed code path.

  • node scripts/react-parity/check.mjs (full — executes the new evidence record) and --validate-only

  • targeted: nested-head (6), static-prerender-stream (6), root-error-callbacks (+4 teardown), resource-hints (30), universal-scheduling (86), plus sweeps: head/svg/streaming/fizz/serialization (632), compiler suites (1,127), universal-importing files (36 files / 653).

  • Every behavior change was reproduced red-first: the nested-head suite failed with the exact ssrUnsupported: HeadHoist compile error; the teardown cases failed with zero callback invocations; the stream tests failed on the missing export; the hint cases failed 12/12; the universal agent-run cases each have recorded pre-fix failure output.

  • Self-review findings the full suite forced (all fixed before this PR): (1) prerenderToNodeStream's first implementation used await import('node:stream'), which broke the server runtime's platform-neutral bundling contract (ssr-production-bundle.test.ts, esbuild platform: 'neutral'); the new Function import indirection then failed under vitest's module runner ("dynamic import callback not specified"); the final form uses process.getBuiltinModule — a plain runtime call no bundler follows — with the non-Node failure as production error code 57. (2) The React-hosted island policy (§9.2: islands may not hoist head content) had been enforced by the very compile error this PR removes; its test now pins the octane/react/server runtime guard instead, which still throws at hosted-render time. (3) untrusted-url's hint collector scanned [data-oct-hint] only; preinit-style tags now carry the Float resource markers, so the collector (and its cleanup) covers both.

  • Review-fix commit 445fa1a (both Bugbot findings, red-first): the client planner now lifts nested HeadHoists out of host-element walks into the plan's head list (client-only renders previously dropped nested metadata silently — the original hydration test was too weak to see it), and resetScopeChildren (the Provider children-dialect flip) threads TEARDOWN_BLOCK like the other teardown brackets. Full suite re-run: 18,626/18,639 — the 13 are the phosphor flake plus the octane-events-browser native-change file failing as a whole under load (12/12 in isolation, environmental).

Risk / follow-ups

  • Nested metadata inside streamed-late boundaries follows the existing documented head divergence (client re-creates on hydration) — the React 19 parity: outstanding gaps and follow-ups after #709 #711 bullet that deliberately stays documented behavior.
  • The head-emit '' return is now load-bearing for nested emission; the type change is source-visible to bindings that (incorrectly) consumed these compiler-ABI helpers directly.
  • Hint identity keys changed for preinit (preinit:as:href → shared sheet:/script: namespaces): a page server-rendered by an older Octane and hydrated by this one would double-insert preinit'd tags once — acceptable on the 0.x track, noted here for the changelog.
  • After merge: tick the five implementation-gap checkboxes in React 19 parity: outstanding gaps and follow-ups after #709 #711.

Provenance

  • An agent produced this diff (agent-authored)

Note

Medium Risk
Touches SSR head serialization, unmount error reporting, and resource-hint identity—areas that can affect hydration and error observability—but changes are mostly cold-path and heavily tested. Mixed-version SSR/hydrate can double-insert preinit tags due to the new shared identity keys.

Overview
Closes five React 19 parity gaps from the outstanding-work issue (streaming post-shell resources stays documented behavior).

Nested document metadata now hoists from any depth on the server too. Nested <title>/<meta>/<link> and Float resources serialize into the head channel at their authored position (including conditional arms), host bodies keep only real children, and hydration adopts without mismatches.

prerenderToNodeStream lands in octane/static: resolves after the await-everything render and streams complete document bytes via prelude (scoped CSS, then folded HTML). No postponed field—postpone/resume remains a non-goal.

Teardown errors (effect cleanups and ref detaches during unmount) now report through onCaughtError / onUncaughtError with existing boundary routing unchanged. The same options are wired into octane/universal roots for scheduler-owned work; direct render() throws stay the documented result channel.

Resource hints share the Float identity model: preinit(as:'style'|'script') joins stylesheet/script resources (precedence, dedupe), later matching preload/preloadModule no-ops, image preloads key on srcset+sizes, and malformed calls warn in development.

Reviewed by Cursor Bugbot for commit 445fa1a. Bugbot is set up for automated code reviews on this repo. Configure here.

Nested-under-host document metadata serializes on the server (React's
hoist-from-anywhere model; the head emit functions return '' so a nested
hoist rides the html expression at its authored position), octane/static
gains prerenderToNodeStream (complete-document prelude via
process.getBuiltinModule, keeping the neutral-platform bundle contract;
error code 57 for non-Node runtimes), teardown-phase errors report
through the root callbacks, resource hints share the Float identity
model (preinit routes through the resource inserts, one-way preload
upgrade, imageSrcSet keying, dev validation), and the universal renderer
gains onCaughtError/onUncaughtError. Executes the implementation-gaps
section of #711.

Co-Authored-By: Claude Fable 5 <[email protected]>
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent feat PR: new feature or capability labels Aug 11, 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 2 potential issues.

Fix All in Cursor

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Teardown block missed in reset
    • Added the missing TEARDOWN_BLOCK = block assignment in resetScopeChildren when TEARDOWN_DEPTH === 0, matching the pattern used by unmountBlock and resetHmrBlock, so teardown errors during mid-render deletion cleanups correctly route to root-level error callbacks.
  • ✅ Fixed: Nested head never mounts client-side
    • Added a HeadHoist case in emitElementHtml's children walk that collects nested head nodes into a ctx._nestedHeadNodes accumulator (save/restored in planJsx like _switchCalls/_portalCalls), then merges them with top-level head nodes before calling emitHeadClient, so nested metadata elements are now emitted on the client.

Create PR

Or push these changes by commenting:

@cursor push 2e1215ea3b
Preview (2e1215ea3b)
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
@@ -19518,6 +19518,10 @@
 	// on `ctx` so we don't thread an extra param through every emit signature.
 	const _prevSwitchCalls = ctx._switchCalls;
 	ctx._switchCalls = [];
+	// Nested HeadHoist nodes discovered inside host elements during the
+	// emitElementHtml walk — same save/restore pattern as portals/switches.
+	const _prevNestedHeadNodes = ctx._nestedHeadNodes;
+	ctx._nestedHeadNodes = [];
 	// Top-level Fragment ref pairing stack — same save/restore reason as
 	// portals/switches so nested planJsx invocations (e.g. sub-templates
 	// inside components) don't leak FragmentStart bindings into each other.
@@ -20271,7 +20275,10 @@
 	for (let i = 0; i < allConstructs.length; i++) allConstructs[i].slotIndex = i + slotBase;
 	// Hoisted head elements take the slots AFTER the constructs (and `plan.head` runs
 	// after `plan.after`), so the scope's `slots` array fills 0,1,…,N,N+1,… packed.
-	const headEmit = emitHeadClient(headNodes, ctx, allConstructs.length + slotBase);
+	// Merge top-level head nodes with any nested ones collected from host elements.
+	const allHeadNodes =
+		ctx._nestedHeadNodes.length > 0 ? [...headNodes, ...ctx._nestedHeadNodes] : headNodes;
+	const headEmit = emitHeadClient(allHeadNodes, ctx, allConstructs.length + slotBase);
 	// Is a construct's host a real in-template element (append / insert INTO it) vs
 	// the block's own parentNode (insert BEFORE __block.endMarker so the slot's range
 	// stays inside the block)? In-template hosts are the navigated `_el…` vars and the
@@ -21078,6 +21085,8 @@
 	}
 	// Restore the outer plan's switch-call list — pairs with the save above.
 	ctx._switchCalls = _prevSwitchCalls;
+	// Restore the outer plan's nested-head-node list — pairs with the save above.
+	ctx._nestedHeadNodes = _prevNestedHeadNodes;
 	// Restore the outer plan's fragment-ref pairing stack.
 	if (ctx._fragRefStack && ctx._fragRefStack.length) {
 		throw new Error('Unclosed <Fragment ref={…}> — FragmentStart without matching FragmentEnd');
@@ -23689,6 +23698,8 @@
 					appendTemplatePart(html, '<!>', 'anchor');
 					childIdx++;
 				}
+			} else if (child.type === 'HeadHoist') {
+				(ctx._nestedHeadNodes ??= []).push(child);
 			}
 		}
 	}

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
@@ -7016,6 +7016,7 @@
 	const block = scope.block;
 	if (TEARDOWN_DEPTH === 0) {
 		TEARDOWN_HANDLER = findTryHandler(block.parentBlock) ?? rendererRegionTryHandler(block);
+		TEARDOWN_BLOCK = block;
 	}
 	TEARDOWN_DEPTH++;
 	// The bracket spans the WHOLE reset, not just the teardown call: a queued error is dispatched

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit 512dc65. Configure here.

Comment thread packages/octane/src/runtime.ts Resolved
Comment thread packages/octane/src/compiler/compile.js Resolved
…ugh dialect-flip resets

The client planner now lifts HeadHoist children out of host-element walks
into the plan's head list (scope-owned headBlock / global resource mounts,
arm-scoped like the server), and resetScopeChildren threads TEARDOWN_BLOCK
like the other teardown brackets. Addresses both Bugbot findings on #715.

Co-Authored-By: Claude Fable 5 <[email protected]>
@trueadm
trueadm marked this pull request as ready for review August 12, 2026 00:18
@trueadm
trueadm merged commit ffadd39 into main Aug 12, 2026
22 of 47 checks passed
@trueadm
trueadm deleted the feat/react19-impl-gaps branch August 12, 2026 00:18
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 feat PR: new feature or capability

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant