Skip to content

fix(hydration): discard the server elements and text a shorter @if/@switch arm leaves unclaimed - #1600

Merged
trueadm merged 4 commits into
mainfrom
fix/branch-arm-host-tails
Oct 2, 2026
Merged

trueadm merged 4 commits into
mainfrom
fix/branch-arm-host-tails

Conversation

@trueadm

@trueadm trueadm commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This is the element/text follow-up to #1564 that was agreed across the overlapping sessions. It supersedes the closed #1565.

When the server rendered a longer @if/@switch arm, the client arm adopts the start of the server's arm range. discardArmTail (#1564, #1587) removes what follows a range the arm claimed. A template, though, leaves the cursor on the elements and text it adopts, so elements or text after the client arm's own roots stayed on screen, and nothing was reported. For example, with server <em>x</em><b>z</b> and client <em>x</em>, the <b>z</b> stayed. A component that adopted its root in place left the same kind of tail.

Validation

Per Dominic's rule while the machine is overloaded, I ran no local test suites on this head. CI does the testing.

  • pnpm sync: no changes.
  • pnpm format:files:check on every changed file.
  • pnpm typecheck:files on the changed runtime, compiler, test and .tsrx fixture files. compiler-template-origins.test.ts has a pre-existing TS2769 on main at lines 149 and 151 (hmr: 'vite'), which this PR does not touch.
  • pnpm format:check, pnpm typecheck and pnpm test were not run locally; CI runs them.
  • New tests:
    • tests/hydration/branch-arm-tail.test.ts, in dev and prod compile plus a production-runtime block that stubs NODE_ENV and asserts no template is parsed. It covers element and text tails after a single root (IfHosts), a fragment (SwitchHosts), static text (IfTextTail), a root whose component moves the cursor into it (IfNestedRoot), and a range after a host (IfRangeAfterHost). It also covers a sole component (IfInheritedHost) and a later component (IfLaterHost) that adopt in place, with matching-arm guards TrailingHosts, NestedArms and HoleWithoutRange.
    • tests/hydration/adopted-branch-tail.test.ts, from fix(hydration): discard the server content an adopted @if/@switch arm leaves unclaimed #1565, with code 337 replaced by 51. It runs in dev compile, prod compile, and prod compile with a prod runtime, and covers HelperFragment (the render-prop helper), OuterBranch, StaticFragment (a tail that repeats the last root's tag) and UnframedComponent (an in-place root stays and the tail after it goes).
  • An earlier version of this change, with its own adoptArm record instead of claimRoots, passed the full octane plus octane-prod run (36,674 tests). A whole-suite probe on that version found discards only in the target tests.

Performance

  • The runtime adds a claim around each adopted arm (two field saves and restores, plus the claimRoots walk the template already pays for in component claims), and one parkPast after an in-place adoption. No hot path gains a branch outside hydration.
  • CI bundle-size check (53db436 → e15d8cd): hydrate-root +89 raw / +22 gz / +16 br; deferred-hydration +108 / +34 / +38; root-static +18 / +11 / −2. The previous version, with its own adoptArm, cost +891 raw / +311 gz on hydrate-root; reusing fix(hydration): discard the server tail of an adopted component range #1576's claim code removed most of that.
  • Compiled output shrinks for formerly pre-wrapped templates, which drop <octane-frag></octane-frag> and gain , 0, N.
  • An A/B hydrate timing on the previous version showed no measurable difference. Per Dominic's rule, it wasn't re-run.

Risk / follow-ups

  • The compiler and runtime must match. An older compiler's frag for a multi-root template would make this runtime miscount roots. Both ship in octane, and apps compile with their own copy.

  • Parking the cursor past the arm template's roots means sweepRebuiltTail no longer runs for an arm whose own template claimed its range. The template's record decides that tail instead.

  • Not covered: a component in a no-template arm that adopts a fragment or text in place, without a server range. renderInPlace reports no adoption for it, so the arm records no end and the server content after it stays, as on main. Tracking that extent means renderInPlace stepping past every adopted root, which changes fix(hydration): continue after a component adopted in place without a range #1567's sibling stepping, so it is left to a follow-up.

Provenance

  • An agent produced this diff (agent-authored)

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.


Note

Medium Risk
Changes core hydration cursor/claim logic for control-flow arms and requires compiler/runtime agreement on multi-root frag counts; mismatched versions could miscount roots, though both ship together in octane.

Overview
Fixes hydration when the client’s @if/@switch arm is shorter than what the server rendered but still adopts the start of that arm’s DOM range. Extra server elements/text after the client arm’s real content used to remain visible with no error; they are now removed and surfaced as a single structural recoverable error (dev diagnostic at the directive, error #51 in production).

Runtime: renderAdoptedArm wraps the arm render in a claim so an arm-owned template can record where its roots end; the hydration cursor is parked past those roots (same idea as after a range claim). Top-level components that adopt a root in place call parkPast after renderInPlace. discardArmTail then trims leftover server nodes from that point and reports once.

Compiler: Multi-root templates are emitted as raw markup plus a root count (frag) instead of baking in a synthetic <octane-frag> wrapper, so production hydration can find the arm boundary without parsing the template (including branches inside render-prop helpers). parseTemplate still adds the wrapper when parsing when needed.

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

…witch arm leaves unclaimed

When the server rendered a longer @if or @switch arm, the client arm adopts
the start of the server's range. discardArmTail removes what follows a
range the arm claimed, but a template leaves the cursor on the elements and
text it adopts, so elements or text after the client arm's own roots stayed
on screen with no report. A component that adopted its root in place left
the same tail.

renderAdoptedArm now opens a claim on the arm's range, so the arm's own
template records where its roots end (claimRoots), and steps the cursor past
them as a range claim parks it. discardArmTail then removes the server
content from there, stops at client-built nodes, and reports code 51 once
with a dev diagnostic at the directive. A component that adopts its root in
place at the arm's top level parks the cursor past that root the same way
(parkPast), so the last such root records the arm's end too.

Production adoption never parses a template, so the compiler now ships
every multi-root template raw with its root count, as resolved-HTML and
foreign ones already did. A branch in a helper passed as a render prop, whose
template was pre-wrapped in <octane-frag> with no count, no longer parses it
in production. The compiler change and adopted-branch-tail.test.ts come from
the closed #1565.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent fix PR: bug fix labels Oct 2, 2026
@github-actions
github-actions Bot marked this pull request as draft October 2, 2026 19:04
@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark report

  • 🔴 bundle-size: 13 value(s) increased
  • 🔴 bundle-reachability: 28 value(s) increased

Compares 2b4b3fc3b with fe3643239 on the same runner. Timing verdicts require a change beyond the combined margin of error (at least 5%) and one 0.1ms timer tick, with the fastest sample also moving beyond that margin. Workflow run

js-framework: 1k/10k row operations (ms, lower is better)

All 20 timed operations (20 within noise)
target operation base head Δ noise
octane-tsrx run 5.05 3.69 −26.9% ±70% ⚪ within noise
octane-tsrx replace 8.02 8.63 +7.6% ±25% ⚪ within noise
octane-tsrx add 3.90 4.60 +17.9% ±36% ⚪ within noise
octane-tsrx update 0.47 0.40 −14.9% ±62% ⚪ within noise
octane-tsrx select 0.17 0.16 −5.9% ±65% ⚪ within noise
octane-tsrx swap 0.40 0.32 −20.0% ±46% ⚪ within noise
octane-tsrx remove 0.37 0.31 −16.2% ±51% ⚪ within noise
octane-tsrx runlots 33.02 42.95 +30.1% ±68% ⚪ within noise
octane-tsrx select_lots 0.18 0.18 −0.0% ±72% ⚪ within noise
octane-tsrx clear 34.01 36.75 +8.1% ±18% ⚪ within noise
octane-jsx run 4.81 5.80 +20.6% ±84% ⚪ within noise
octane-jsx replace 8.72 8.49 −2.6% ±42% ⚪ within noise
octane-jsx add 3.46 4.66 +34.7% ±80% ⚪ within noise
octane-jsx update 0.51 0.60 +17.6% ±44% ⚪ within noise
octane-jsx select 0.34 0.39 +14.7% ±51% ⚪ within noise
octane-jsx swap 0.68 0.74 +8.8% ±57% ⚪ within noise
octane-jsx remove 0.47 0.62 +31.9% ±37% ⚪ within noise
octane-jsx runlots 29.88 33.18 +11.0% ±19% ⚪ within noise
octane-jsx select_lots 2.75 2.56 −6.9% ±29% ⚪ within noise
octane-jsx clear 34.34 35.85 +4.4% ±28% ⚪ within noise

Application bundle size (bytes)

target metric base head Δ
octane-tsrx weather_js_raw 177,747 177,765 +18 (+0.0%) 🔴
octane-tsrx weather_js_gzip 58,105 58,114 +9 (+0.0%) 🔴
octane-tsrx weather_app_gzip 9,045 9,044 −1 (−0.0%) 🟢
octane-tsrx weather_app_brotli 7,559 7,562 +3 (+0.0%) 🔴
octane-tsrx weather_fw_raw 151,012 151,030 +18 (+0.0%) 🔴
octane-tsrx weather_fw_gzip 49,060 49,070 +10 (+0.0%) 🔴
octane-tsrx weather_fw_brotli 42,936 42,933 −3 (−0.0%) 🟢
octane-jsx js_raw 226,315 226,333 +18 (+0.0%) 🔴
octane-jsx js_gzip 72,213 72,220 +7 (+0.0%) 🔴
octane-jsx js_brotli 62,452 62,475 +23 (+0.0%) 🔴
octane-jsx app_gzip 2,941 2,943 +2 (+0.1%) 🔴
octane-jsx app_brotli 2,498 2,501 +3 (+0.1%) 🔴
octane-jsx fw_raw 217,848 217,866 +18 (+0.0%) 🔴
octane-jsx fw_gzip 69,272 69,277 +5 (+0.0%) 🔴
octane-jsx fw_brotli 59,954 59,974 +20 (+0.0%) 🔴

30 other measured values are unchanged.

Public-import reachability bundles (bytes)

target metric base head Δ
root-static raw 202,635 202,653 +18 (+0.0%) 🔴
root-static gzip 64,419 64,428 +9 (+0.0%) 🔴
root-static brotli 55,828 55,878 +50 (+0.1%) 🔴
context raw 110,469 110,488 +19 (+0.0%) 🔴
context gzip 36,585 36,597 +12 (+0.0%) 🔴
context brotli 32,359 32,350 −9 (−0.0%) 🟢
hydrate-root raw 166,199 166,288 +89 (+0.1%) 🔴
hydrate-root gzip 53,027 53,045 +18 (+0.0%) 🔴
hydrate-root brotli 46,168 46,202 +34 (+0.1%) 🔴
deferred-hydration raw 229,105 229,213 +108 (+0.0%) 🔴
deferred-hydration gzip 72,692 72,722 +30 (+0.0%) 🔴
deferred-hydration brotli 62,705 62,797 +92 (+0.1%) 🔴
suspense-transition raw 167,001 167,020 +19 (+0.0%) 🔴
suspense-transition gzip 53,678 53,679 +1 (+0.0%) 🔴
suspense-transition brotli 46,886 46,878 −8 (−0.0%) 🟢
binding-base-ui-vite raw 212,826 212,844 +18 (+0.0%) 🔴
binding-base-ui-vite gzip 67,997 68,005 +8 (+0.0%) 🔴
binding-base-ui-vite brotli 58,985 58,899 −86 (−0.1%) 🟢
binding-base-ui-esbuild raw 210,787 210,805 +18 (+0.0%) 🔴
binding-base-ui-esbuild gzip 67,965 67,973 +8 (+0.0%) 🔴
binding-base-ui-esbuild brotli 58,943 58,934 −9 (−0.0%) 🟢
binding-aria-esbuild gzip 3,361 3,363 +2 (+0.1%) 🔴
binding-aria-esbuild brotli 3,012 3,013 +1 (+0.0%) 🔴
binding-radix-vite raw 214,756 214,774 +18 (+0.0%) 🔴
binding-radix-vite gzip 68,558 68,565 +7 (+0.0%) 🔴
binding-radix-vite brotli 59,397 59,465 +68 (+0.1%) 🔴
binding-radix-esbuild raw 212,677 212,695 +18 (+0.0%) 🔴
binding-radix-esbuild gzip 68,546 68,552 +6 (+0.0%) 🔴
binding-radix-esbuild brotli 59,445 59,424 −21 (−0.0%) 🟢
binding-apollo-client-vite raw 357,881 357,899 +18 (+0.0%) 🔴
binding-apollo-client-vite gzip 112,125 112,130 +5 (+0.0%) 🔴
binding-apollo-client-vite brotli 97,861 97,820 −41 (−0.0%) 🟢
binding-apollo-client-esbuild raw 360,834 360,852 +18 (+0.0%) 🔴
binding-apollo-client-esbuild gzip 114,337 114,346 +9 (+0.0%) 🔴
binding-apollo-client-esbuild brotli 99,545 99,518 −27 (−0.0%) 🟢

70 other measured values are unchanged.

@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.

Stale Bugbot comment from a previous run.

Comment thread packages/octane/src/runtime.ts Resolved
@trueadm
trueadm marked this pull request as ready for review October 2, 2026 19:35

@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 prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Fragment in-place arms keep tails
    • Added inPlace clearing in the fragment match path of adopt(), a parkHere() method for cursor-based arm tracking, and inPlacePark for multi-root fragment cursor advancement so renderInPlace returns true and the arm tail is correctly tracked and discarded.

Create PR

Or push these changes by commenting:

@cursor push d3f10b4443
Preview (d3f10b4443)
diff --git a/.changeset/branch-arm-host-tails.md b/.changeset/branch-arm-host-tails.md
new file mode 100644
--- /dev/null
+++ b/.changeset/branch-arm-host-tails.md
@@ -1,0 +1,5 @@
+---
+'octane': patch
+---
+
+Discard the server elements and text that an `@if` or `@switch` arm leaves unclaimed during hydration. When the server rendered a longer arm, the client arm adopts the start of the server's range. Elements or text after the roots of the client arm's own template, or after a component the arm adopts in place, stayed on screen with no report. Hydration now steps past those roots, removes the server content after them, and reports one structural `onRecoverableError`, with a development diagnostic at the directive. Every compiled multi-root template now carries its root count, so production hydration finds that end without parsing the template, including for a branch in a helper passed as a render prop.

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
@@ -26160,8 +26160,8 @@
 		};
 	}
 
-	// Emit ONE template containing all top-level JSX (wrapping multiple roots in
-	// a synthetic <octane-frag>).
+	// Emit ONE template containing all top-level JSX (the runtime parses
+	// multiple roots inside a synthetic <octane-frag>).
 	// We walk the tree, building HTML and a list of bindings.
 	const elementBindings = []; // ordered list of bindings (per dynamic site)
 	const forCalls = []; // forBlock calls — emitted after the mount/append
@@ -26339,18 +26339,19 @@
 		ctx.runtimeNeeded.add('clone');
 		// Template namespace strategy:
 		//   - HTML single-root: parse the element directly, no flag.
-		//   - HTML multi-root: wrap in <octane-frag> so template() returns the wrap.
+		//   - HTML multi-root: raw markup + its root count; the runtime parses it
+		//     inside an <octane-frag> wrapper and drains the wrapper's children.
 		//   - SVG/MathML single-root: pass ns flag; runtime wraps with <svg>/<math>
 		//     so the HTML5 parser places children in foreign content, then returns
 		//     the inner root.
-		//   - SVG/MathML multi-root: pass ns + frag=1; runtime wraps and returns
-		//     the wrap itself (caller drains its children — no <octane-frag>).
+		//   - SVG/MathML multi-root: pass ns + the root count; runtime wraps and
+		//     returns the wrap itself (caller drains its children — no <octane-frag>).
 		//   - Opaque component bodies/children whose root tags pin the namespace
 		//     statically (every root exists in exactly one namespace — see
 		//     staticNsForOpaqueRoot) compile like fixed HTML/SVG/MathML templates:
 		//     the parse is identical at every destination, so pay nothing per
 		//     clone. Only genuinely ambiguous roots (`a`, `title`, custom/unknown
-		//     tags, mixed fragments) pass flag 3 (+ frag=1 for multiple roots);
+		//     tags, mixed fragments) pass flag 3 (+ the root count for several);
 		//     clone() resolves and caches the concrete namespace from the render
 		//     block's actual parent.
 		// Multi-root fragments at an HTML parent imply SVG only when EVERY element
@@ -26373,11 +26374,6 @@
 				: (parentNs === 'html' || parentNs === 'opaque') && fragImpliesSvg
 					? 'svg'
 					: parentNs;
-		// A resolved-HTML multi-root ships raw markup + frag=1 (parseTemplate adds
-		// the <octane-frag> wrapper) instead of the fixed-HTML path's pre-wrapped
-		// string: same parsed DOM, but the template literal stays as small as the
-		// opaque form it replaces.
-		let resolvedFrag = false;
 		if (tplNs === 'opaque') {
 			// Component-destination template whose root tags didn't imply SVG:
 			// resolve the namespace statically when every root pins the same one.
@@ -26394,7 +26390,6 @@
 					resolved = ns;
 				}
 				tplNs = resolved === null ? 'html' : resolved;
-				resolvedFrag = tplNs !== 'opaque';
 			}
 		}
 		// Binding planning precedes the final template namespace. An inherited
@@ -26407,23 +26402,11 @@
 			}
 		}
 		const flag = nsFlag(tplNs);
-		// A raw multi-root template passes its root count, which hydration reads
-		// without parsing the template to find where the roots it adopted end.
-		const fragArg = !single && (flag !== 0 || resolvedFrag) ? htmlIdx : 0;
-		let template = rootTemplate;
-		if (!single && flag === 0 && !resolvedFrag) {
-			template = templateElement(
-				'octane-frag',
-				'html',
-				false,
-				createTemplateIr(),
-				rootTemplate,
-				null,
-				null,
-				true,
-			);
-		}
-		const tpl = allocTemplate(ctx, template, flag, fragArg);
+		// A multi-root template ships raw markup and its root count; parseTemplate
+		// adds the wrapper the HTML parser needs. Hydration reads the count without
+		// parsing the template to find where the roots it adopted end.
+		const fragArg = single ? 0 : htmlIdx;
+		const tpl = allocTemplate(ctx, rootTemplate, flag, fragArg);
 		// DEV: pass the root element's source location so a STRUCTURAL hydration mismatch
 		// (swapped @if/@switch branch, changed tag) warns with `file:line:col`. Single-root
 		// only (a multi-root <octane-frag> wrapper has no source position); prod omits it.

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
@@ -11881,11 +11881,14 @@
 	anchor: Node | undefined,
 	root: Node,
 ): void {
-	hydration.renderInPlace(
-		() => componentSlotLite(parentScope, slotKey, host, comp, props, invocationSite, anchor),
-		undefined,
-		root,
-	);
+	if (
+		hydration.renderInPlace(
+			() => componentSlotLite(parentScope, slotKey, host, comp, props, invocationSite, anchor),
+			undefined,
+			root,
+		)
+	)
+		hydration.parkHere(parentScope);
 }
 
 // Keep the fresh-subtree callback's extra captures out of ordinary lite dispatch.
@@ -18434,7 +18437,8 @@
 	ns: 0 | 1 | 2 | 3;
 	/**
 	 * Raw multi-root markup: the number of roots, as the compiler counts them.
-	 * 0 = one root, or HTML roots pre-wrapped in `<octane-frag>`.
+	 * 0 = one root, or HTML roots already wrapped in `<octane-frag>`, which the
+	 * compiler no longer emits.
 	 */
 	frag: number;
 	parsed: Array<Node | null>;
@@ -18477,9 +18481,9 @@
 	initDomOperations();
 	const t = (STAGED_DOM?.view(document) ?? document).createElement('template');
 	if (ns === 0) {
-		// Fixed HTML multi-root templates arrive pre-wrapped by the compiler. Opaque
-		// multi-root templates carry raw markup because their eventual namespace is
-		// unknown, so add the equivalent wrapper only after HTML wins at clone time.
+		// Multi-root templates carry raw markup: an opaque one because its eventual
+		// namespace is unknown until clone time. Add the wrapper the HTML parser
+		// needs here. Markup that arrives already wrapped parses the same way.
 		(STAGED_DOM?.view(t) ?? t).innerHTML = frag ? `<octane-frag>${html}</octane-frag>` : html;
 		const root = getFirstChild(t.content) as Element;
 		// Multi-root HTML templates arrive wrapped in a synthetic <octane-frag>. The
@@ -18545,10 +18549,10 @@
 }
 
 /**
- * Is this lazy template a multi-root fragment? SVG/MathML/opaque fragments carry
- * `frag`; HTML multi-root templates arrive from the compiler pre-wrapped in
- * `<octane-frag>` with frag=0, so the wrapper tag is the discriminant there
- * (mirrors parseTemplate's `__oct_frag` stamping of the parsed root).
+ * Is this lazy template a multi-root fragment? Compiled fragments carry `frag`;
+ * HTML roots already wrapped in `<octane-frag>` with frag=0 are discriminated
+ * by the wrapper tag (mirrors parseTemplate's `__oct_frag` stamping of the
+ * parsed root).
  */
 function isLazyFragment(lazy: LazyTemplateRecord): boolean {
 	return lazy.frag !== 0 || lazyRootDescriptor(lazy) === 'octane-frag';
@@ -18556,8 +18560,8 @@
 
 /**
  * How many roots a multi-root template has. The compiler passes the count as
- * a raw fragment's `frag`; a parsed or pre-wrapped template counts its
- * children.
+ * `frag`; a parsed template, or markup already wrapped in `<octane-frag>`,
+ * counts its children.
  */
 function templateRootCount(template: Node | LazyTemplateRecord): number {
 	let parsed: Node;
@@ -18593,8 +18597,8 @@
 
 /**
  * lazyRootMatches for a nested fragment's FIRST logical root, read from the
- * template source. A raw fragment's cached descriptor is that root; a
- * fixed-HTML fragment's starts after its synthetic `<octane-frag>` wrapper. A
+ * template source. A raw fragment's cached descriptor is that root; markup
+ * already wrapped in `<octane-frag>` has it after the wrapper. A
  * leading `<!>` is a dynamic hole whose server form (text, a marker range, or
  * nothing) cannot decide a mismatch, so the first static element root after
  * the leading holes decides, as in fragmentRootMatches.
@@ -18827,6 +18831,12 @@
 	private readonly unframedRootRanges = new WeakMap<Node, Node>();
 	/** The server node renderInPlace's body may adopt, until a template does. */
 	private inPlace: Node | null = null;
+	/**
+	 * When a fragment body clears `inPlace`, the close of its last root's range
+	 * (or the last root itself when it is not a range). renderInPlace steps past
+	 * it so the cursor lands after all fragment roots, not just the first.
+	 */
+	private inPlacePark: Node | null = null;
 	/** Pairs discovered while matching an outer range; released with this hydration pass. */
 	private matchingCloses: WeakMap<Node, Comment> | null = null;
 	/** First unclaimed root sibling after a compiled root clone; undefined until known. */
@@ -19206,6 +19216,7 @@
 	renderInPlace<T>(render: (target: T) => void, target: T, root: Node): boolean {
 		const outer = this.inPlace;
 		this.inPlace = root;
+		this.inPlacePark = null;
 		let adopted = false;
 		try {
 			render(target);
@@ -19213,7 +19224,11 @@
 		} finally {
 			this.inPlace = outer;
 		}
-		if (adopted) this.node = getNextSibling(root);
+		if (adopted) {
+			const last = this.inPlacePark;
+			this.inPlacePark = null;
+			this.node = last !== null ? getNextSibling(last) : getNextSibling(root);
+		}
 		return adopted;
 	}
 
@@ -19660,8 +19675,9 @@
 	}
 
 	/**
-	 * A slot of `parent` claimed the server range that `close` ends. Step the
-	 * cursor past it to the next sibling's server content.
+	 * A slot of `parent` claimed the server range that `close` ends, or adopted
+	 * `close` in place as its root. Step the cursor past it to the next
+	 * sibling's server content.
 	 */
 	parkPast(close: Node, parent: Scope): void {
 		const next = (this.node = getNextSibling(close));
@@ -19672,28 +19688,49 @@
 	}
 
 	/**
+	 * Record the arm tracking at the current cursor, which renderInPlace already
+	 * parked past the adopted content. Unlike parkPast this does not move the
+	 * cursor: renderInPlace already advanced it past all roots (including the
+	 * extra roots of a fragment body).
+	 */
+	parkHere(parent: Scope): void {
+		if (parent === this.arm) {
+			this.armTail = this.node;
+			this.armSlots = parent.slots.length;
+		}
+	}
+
+	/**
 	 * First render of an @if or @switch arm into the server range it adopted,
-	 * `block`'s own. When the arm's content is its own slots and the last of
-	 * them claimed a server range, returns the node that claim parked the
-	 * cursor on: whatever the server rendered from there belongs to no client
-	 * node (discardArmTail). Null when the arm cloned a template of its own, or
-	 * a later slot adopted without claiming a range, since the cursor then
-	 * rests on the roots they adopted.
+	 * `block`'s own. Returns the node from which whatever the server rendered
+	 * belongs to no client node (discardArmTail), with the cursor parked on it:
+	 * the first node after the roots of the arm's own template, which records
+	 * them as the range's content (claimRoots), or else where the arm's last
+	 * slot parked the cursor after the range it claimed, or after the root it
+	 * adopted in place. Null when a later slot adopted without either, since
+	 * the cursor then rests on the roots it adopted.
 	 */
 	renderAdoptedArm(block: Block): Node | null {
 		const outerArm = this.arm;
 		const outerTail = this.armTail;
 		const outerSlots = this.armSlots;
+		const outerClaim = this.beginClaim(getNextSibling(block.startMarker!));
 		this.arm = block;
 		this.armTail = null;
+		let parked: Node | null = null;
+		let claimed: Node | null | undefined;
 		try {
 			renderBlock(block);
-			return this.arm === block && this.armSlots === block.slots.length ? this.armTail : null;
+			if (this.arm === block && this.armSlots === block.slots.length) parked = this.armTail;
 		} finally {
+			claimed = this.endClaim(outerClaim);
 			this.arm = outerArm;
 			this.armTail = outerTail;
 			this.armSlots = outerSlots;
 		}
+		// The cursor rests on the roots the arm's own template adopted, or inside
+		// them: step it past them, as a range claim parks it.
+		return claimed == null ? parked : (this.node = claimed);
 	}
 
 	/**
@@ -19704,7 +19741,8 @@
 	 * something, a server range at the cursor or just after that marker is one
 	 * that nothing in the arm claimed: the server rendered another arm here,
 	 * longer than this one. So is any server content at `parked`, where the
-	 * arm's last slot parked the cursor after its range (renderAdoptedArm).
+	 * arm parked the cursor after its own template's roots, or after its last
+	 * slot's range or in-place root (renderAdoptedArm).
 	 * Discard the server content from there up to `end`, stopping at any
 	 * client nodes that mismatch recovery built there, and report it once.
 	 *
@@ -19713,7 +19751,7 @@
 	 * empty client branch, as an arm with no body is. The cursor does not move
 	 * past the elements and text that a template adopts, so at an element or
 	 * text node it cannot otherwise tell what the arm adopted from what the
-	 * server rendered for another arm. Both stay.
+	 * server rendered for another arm: `parked` does, and anything else stays.
 	 */
 	discardArmTail(scope: Scope, slotKey: number, first: Node, end: Node, parked: Node | null): void {
 		let from = this.node;
@@ -20284,6 +20322,19 @@
 					: lazyFragmentRootMatches(cursor, lazy!, this))
 			) {
 				if (cursor === this.claimFrom) this.claimRoots(cursor, template ?? lazy!);
+				if (cursor === this.inPlace) {
+					this.inPlace = null;
+					const count = templateRootCount(template ?? lazy!);
+					if (count > 1) {
+						let node: Node | null = cursor;
+						for (let i = count; i > 1; i--) {
+							node = this.sibling(node!, 1);
+							if (node === null || isBlockClose(node)) break;
+						}
+						if (node !== null && !isBlockClose(node))
+							this.inPlacePark = this.isOpen(node) ? this.close(node) : node;
+					}
+				}
 				return { __oct_vfrag: true, firstChild: cursor } as unknown as Node;
 			}
 			return this.rebuildFragment(template ?? resolveLazyTemplate(lazy!), cursor, loc);
@@ -32398,6 +32449,8 @@
 					b.endMarker = last;
 				}
 			}
+			// An arm that ends with this root cannot read its end off the cursor.
+			if (adopted) hydration!.parkHere(parentScope);
 		} else {
 			const b = createBlock(
 				'dynamic',

diff --git a/packages/octane/tests/compiler/compiler-template-origins.test.ts b/packages/octane/tests/compiler/compiler-template-origins.test.ts
--- a/packages/octane/tests/compiler/compiler-template-origins.test.ts
+++ b/packages/octane/tests/compiler/compiler-template-origins.test.ts
@@ -230,15 +230,17 @@
 			expect(kinds.has(kind)).toBe(true);
 		}
 
-		const nested = compileInspect().find((template) =>
-			template.html.startsWith('<octane-frag><i>'),
-		)!;
-		const wrapper = nested.ast.parts[0];
-		expect(wrapper.type).toBe('TemplateElement');
-		if (wrapper.type !== 'TemplateElement') throw new Error('expected a template element');
-		expect(wrapper.tag).toBe('octane-frag');
-		expect(wrapper.synthetic).toBe(true);
-		expect(wrapper.children.filter((node) => node.type === 'TemplateElement')).toHaveLength(2);
+		// A multi-root template's roots are its own top-level parts, with no
+		// synthetic wrapper: the runtime adds the one the HTML parser needs.
+		const nested = compileInspect().find((template) => template.html.startsWith('<i>'))!;
+		expect(
+			nested.ast.parts.map((node) =>
+				node.type === 'TemplateElement' ? [node.tag, node.synthetic] : node.type,
+			),
+		).toEqual([
+			['i', false],
+			['b', false],
+		]);
 	});
 
 	it('every origin entry slices cleanly out of both the template HTML and the source', () => {

diff --git a/packages/octane/tests/hydration/_fixtures/adopted-branch-tail.tsrx b/packages/octane/tests/hydration/_fixtures/adopted-branch-tail.tsrx
new file mode 100644
--- /dev/null
+++ b/packages/octane/tests/hydration/_fixtures/adopted-branch-tail.tsrx
@@ -1,0 +1,189 @@
+import type { ComponentBody } from 'octane';
+
+function label(): string {
+	return 'ok';
+}
+
+function Leaf() @{
+	<i>{label() as string}</i>
+}
+
+function Bold() @{
+	<b>{'b'}</b>
+}
+
+function Strike() @{
+	<s>{'s'}</s>
+}
+
+// Each branch renders its `@else` arm on the client. The server renders the
+// `@if` arm, whose content starts with what the `@else` arm renders and ends
+// with a stale tail, so the client adopts the arm's range and leaves the tail.
+export function SoleComponent(props: { server?: boolean }) @{
+	<div>
+		@if (props.server) {
+			<>
+				<Leaf />
+				<s class="foreign">{'f'}</s>
+			</>
+		} @else {
+			<Leaf />
+		}
+	</div>
+}
+
+export function SingleRoot(props: { server?: boolean }) @{
+	<div>
+		@if (props.server) {
+			<>
+				<i>{label() as string}</i>
+				<s class="foreign">{'f'}</s>
+			</>
+		} @else {
+			<i>{label() as string}</i>
+		}
+	</div>
+}
+
+// The stale tail ends with the same tag as the client's last root.
+export function StaticFragment(props: { server?: boolean }) @{
+	<div>
+		@if (props.server) {
+			<>
+				<i>{label() as string}</i>
+				<b>{'b'}</b>
+				<s class="foreign">{'f'}</s>
+				<b class="foreign">{'b'}</b>
+			</>
+		} @else {
+			<>
+				<i>{label() as string}</i>
+				<b>{'b'}</b>
+			</>
+		}
+	</div>
+}
+
+export function HoleFragment(props: { server?: boolean }) @{
+	<div>
+		@if (props.server) {
+			<>
+				<i>{label() as string}</i>
+				<Bold />
+				<s class="foreign">{'f'}</s>
+			</>
+		} @else {
+			<>
+				<i>{label() as string}</i>
+				<Bold />
+			</>
+		}
+	</div>
+}
+
+export function SwitchBranch(props: { server?: boolean }) @{
+	<div>
+		@switch (props.server ? 'server' : 'client') {
+			@case 'server': {
+				<>
+					<i>{label() as string}</i>
+					<s class="foreign">{'f'}</s>
+				</>
+			}
+			@default: {
+				<i>{label() as string}</i>
+			}
+		}
+	</div>
+}
+
+// Both sides render the outer `@if` arm; only the inner arm leaves a tail.
+export function NestedBranch(props: { server?: boolean }) @{
+	<div>
+		@if (true) {
+			<>
+				<Leaf />
+				@if (props.server) {
+					<>
+						<b>{'b'}</b>
+						<s class="foreign">{'f'}</s>
+					</>
+				} @else {
+					<b>{'b'}</b>
+				}
+				<u>{'u'}</u>
+			</>
+		}
+	</div>
+}
+
+// Only the outer arm leaves a tail, after an inner branch both sides render.
+export function OuterBranch(props: { server?: boolean }) @{
+	<div>
+		@if (props.server) {
+			<>
+				<Leaf />
+				@if (true) {
+					<b>{'b'}</b>
+				}
+				<u>{'u'}</u>
+				<s class="foreign">{'f'}</s>
+			</>
+		} @else {
+			<>
+				<Leaf />
+				@if (true) {
+					<b>{'b'}</b>
+				}
+				<u>{'u'}</u>
+			</>
+		}
+	</div>
+}
+
+// The client's last component finds the server's `<s>` where it expects its
+// range and adopts it without one. That `<s>` is client content now.
+export function UnframedComponent(props: { server?: boolean }) @{
+	<div>
+		@if (props.server) {
+			<>
+				<Bold />
+				<s>{'s'}</s>
+				<u class="foreign">{'tail'}</u>
+			</>
+		} @else {
+			<>
+				<Bold />
+				<Strike />
+			</>
+		}
+	</div>
+}
+
+function Slot(props: { render: ComponentBody }) @{
+	const Render = props.render;
+	<section>
+		<Render />
+	</section>
+}
+
+// The branch sits in a template that a helper passed as a render prop returns.
+export function HelperFragment(props: { server?: boolean }) @{
+	const render = () => @{
+		<div>
+			@if (props.server) {
+				<>
+					<i>{label() as string}</i>
+					<b>{'b'}</b>
+					<s class="foreign">{'f'}</s>
+				</>
+			} @else {
+				<>
+					<i>{label() as string}</i>
+					<b>{'b'}</b>
+				</>
+			}
+		</div>
+	};
+	<Slot render={render} />
+}

diff --git a/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx b/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx
--- a/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx
+++ b/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx
@@ -116,6 +116,193 @@
 	</div>
 }
 
+// The client's arm is one element, which adopts the first of the server's.
+export function IfHosts(props: { on: boolean }) @{
+	<div id="r">
+		@if (props.on) {
+			<em>{'x' as string}</em>
+		} @else {
+			<>
+				<em>{'x' as string}</em>
+				<b>{'z' as string}</b>
+			</>
+		}
+	</div>
+}
+
+// The two cases share their first elements, so the server's last one is the
+// only difference.
+export function SwitchHosts(props: { k: string }) @{
+	<div id="r">
+		@switch (props.k) {
+			@case 'one': {
+				<>
+					<em>{'x' as string}</em>
+					<b>{'z' as string}</b>
+				</>
+			}
+			@default: {
+				<>
+					<em>{'x' as string}</em>
+					<b>{'z' as string}</b>
+					<i>{'i' as string}</i>
+				</>
+			}
+		}
+	</div>
+}
+
+// The server's arm ends with static text after the element both arms share.
+export function IfTextTail(props: { on: boolean }) @{
+	<div id="r">
+		@if (props.on) {
+			<em>{'x' as string}</em>
+		} @else {
+			<>
+				<em>{'x' as string}</em>
+				tail
+			</>
+		}
+	</div>
+}
+
+// The client's root holds a component, whose range moves the cursor inside it.
+export function IfNestedRoot(props: { on: boolean }) @{
+	<div id="r">
+		@if (props.on) {
+			<p>
+				<Leaf v="x" />
+			</p>
+		} @else {
+			<>
+				<p>
+					<Leaf v="x" />
+				</p>
+				<b>{'z' as string}</b>
+			</>
+		}
+	</div>
+}
+
+// The client's arm ends with an element after a component range, and the
+// server's arm has another component after it.
+export function IfRangeAfterHost(props: { on: boolean }) @{
+	<div id="r">
+		@if (props.on) {
+			<>
+				<Leaf v="x" />
+				<b>{'b' as string}</b>
+			</>
+		} @else {
+			<>
+				<Leaf v="x" />
+				<b>{'b' as string}</b>
+				<Leaf v="z" />
+			</>
+		}
+	</div>
+}
+
+// The client's arm is a component that borrows the arm's range, so its
+// template adopts the first of the server's elements.
+export function IfInheritedHost(props: { on: boolean }) @{
+	<div id="r">
+		@if (props.on) {
+			<Leaf v="x" />
+		} @else {
+			<>
+				<em>{'x' as string}</em>
+				<b>{'z' as string}</b>
+			</>
+		}
+	</div>
+}
+
+// The arm's second component finds no server range, so it adopts the element
+// there in place, and the server's arm has another element after it.
+export function IfLaterHost(props: { on: boolean }) @{
+	<div id="r">
+		@if (props.on) {
+			<>
+				<Leaf v="x" />
+				<Leaf v="y" />
+			</>
+		} @else {
+			<>
+				<Leaf v="x" />
+				<em>{'y' as string}</em>
+				<b>{'z' as string}</b>
+			</>
+		}
+	</div>
+}
+
+// A hookless component whose body is a fragment (not a single host element).
+function FragLeaf(props: { v: string }) @{
+	<>
+		{props.v as string}
+	</>
+}
+
+// The arm's second component returns a fragment body, which finds no server
+// range and adopts the text node there in place. The server's arm has another
+// element after it that must be discarded.
+export function IfLaterFragment(props: { on: boolean }) @{
+	<div id="r">
+		@if (props.on) {
+			<>
+				<Leaf v="x" />
+				<FragLeaf v="y" />
+			</>
+		} @else {
+			<>
+				<Leaf v="x" />
+				y
+				<b>{'z' as string}</b>
+			</>
+		}
+	</div>
+}
+
+// A component in a hole of the arm's own template finds no server range and
+// adopts the element there in place. The template already recorded where the
+// arm ends, after its last root.
+export function HoleWithoutRange(props: { on: boolean }) @{
+	<div id="r">
+		@if (props.on) {
+			<>
+				<Leaf v="x" />
+				<b>{'b' as string}</b>
+			</>
+		} @else {
+			<>
+				<em>{'x' as string}</em>
+				<b>{'b' as string}</b>
+			</>
+		}
+	</div>
+}
+
+// A branch inside the arm's template, at its start and inside an element,
+// records where its own template ends without disturbing the arm's.
+export function NestedArms(props: { on: boolean; inner: boolean }) @{
+	<div id="r">
+		@if (props.on) {
+			<>
+				@if (props.inner) {
+					<em>{'x' as string}</em>
+				}
+				<p>
+					@if (props.inner) {
+						<i>{'i' as string}</i>
+					}
+				</p>
+				<b>{'b' as string}</b>
+			</>
+		}
+	</div>
+}
+
 export function Tail() @{
 	<u>{'tail' as string}</u>
 }

diff --git a/packages/octane/tests/hydration/adopted-branch-tail.test.ts b/packages/octane/tests/hydration/adopted-branch-tail.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/octane/tests/hydration/adopted-branch-tail.test.ts
@@ -1,0 +1,210 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { act, flushSync, hydrateRoot } from '../../src/index.js';
+import * as ServerRT from 'octane/server';
+import { loadCompiledFixtureSource, loadServerFixture } from '../_server-fixture';
+
+// An @if or @switch slot adopts the server's range for its arm even when the
+// server rendered a different arm, as long as that range starts with what the
+// client arm renders. Whatever the server left after the client arm's content
+// is stale: hydration removes it and reports the mismatch once, while the
+// nodes the arm adopted keep their identity.
+
+const FIXTURE = join(
+	process.cwd(),
+	'packages/octane/tests/hydration/_fixtures/adopted-branch-tail.tsrx',
+);
+const FILE = 'adopted-branch-tail.tsrx';
+const SOURCE = readFileSync(FIXTURE, 'utf8');
+const LINES = SOURCE.split('\n');
+
+/** The `file:line:col` of the first `directive` after the line containing `after`. */
+function siteOf(after: string, directive: string): string {
+	const start = LINES.findIndex((line) => line.includes(after));
+	if (start < 0) throw new Error(`fixture has no line containing ${after}`);
+	const index = LINES.findIndex((line, i) => i > start && line.includes(directive));
+	if (index < 0) throw new Error(`fixture has no ${directive} after ${after}`);
+	return `${FILE}:${index + 1}:${LINES[index].indexOf(directive)}`;
+}
+
+/** Element and text markup, ignoring hydration comments. */
+function markup(node: Element): string {
+	const copy = node.cloneNode(true) as Element;
+	const walker = document.createTreeWalker(copy, NodeFilter.SHOW_COMMENT);
+	const comments: Node[] = [];
+	while (walker.nextNode()) comments.push(walker.currentNode);
+	for (const comment of comments) comment.parentNode!.removeChild(comment);
... diff truncated: showing 800 of 1229 lines

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

Reviewed by Cursor Bugbot for commit 2828027. Configure here.

Comment thread packages/octane/src/runtime.ts Resolved
trueadm and others added 2 commits October 2, 2026 20:46
A component that adopts a fragment or text in place reports no adoption from
renderInPlace, so an arm that ends with one records no end and keeps the
server content after it, as before. Say so in renderAdoptedArm and the
changeset rather than claiming every in-place component.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@trueadm
trueadm merged commit 3770c1e into main Oct 2, 2026
32 checks passed
@trueadm
trueadm deleted the fix/branch-arm-host-tails branch October 2, 2026 20:06
trueadm added a commit that referenced this pull request Oct 2, 2026
… in place

With #1600 merged, an @if/@switch arm reads its end from where its last
in-place component parked the cursor. renderInPlace now parks it past
every root a fragment template adopted (it previously stepped past the
first root only, and only for a single root), so a server arm that
continues after those roots is discarded and reported once at the
directive. Pin that, and say so in the changeset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 2, 2026
… the changeset

Main's #1602 and #1600 now handle the single-root and lite calls at a
component hole in an adopted arm, so this branch's runtime change is reduced
to the unframed (keyed or dynamic) path. A keyed call after the adopted static
root pins that its stale node comes from its anchor rather than the lagging
cursor, which would delete the adopted root.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 fix PR: bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant