Repository navigation
fix(hydration): end a markerless branch arm after every root its template adopted - #1622
Merged
Merged
Conversation
…late adopted A hydrating @if or @switch arm that the server rendered no range for takes the place of the server node at the cursor. Its content was bounded from where its render left the cursor, and clone() parks the cursor on the first root a template adopts, so a multi-root arm ended after its first root. When the arm was the whole content of another arm or of an adopted component, the tail rules then deleted its later roots and reported a mismatch; otherwise switching the arm off left them on screen. The arm's first render now opens a claim owned by its block (HydrationCapability.renderMarkerless/renderOwned), so claimRoots records exactly where its template's roots end. The same holds when the arm suspends inside a deferred <Hydrate> boundary: holdMarkerlessBranch keeps the first render's claimed end instead of the cursor estimate, and renderSuspended re-opens the claim when it resumes a held arm that had not cloned yet (renderHeld). A static last root after the suspended component or after a use() in the arm is now part of the arm, so a later case change removes it, as does a case change while the boundary is pending. renderBranchSlot grows by 9 B raw; the rest lives in HydrationCapability, so bundles that do not hydrate are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm
marked this pull request as ready for review
October 2, 2026 23:58
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Nested claim clobbers parent frame tail
- In renderClaimed, save and clear heldClaim before renderBlock, then use it as from when endClaim returns undefined, so a framed component with no wrapper template correctly settles its claim from the markerless branch's settlement instead of losing it.
Or push these changes by commenting:
@cursor push 2ea1e12d04
Preview (2ea1e12d04)
diff --git a/.changeset/held-markerless-branch-claim.md b/.changeset/held-markerless-branch-claim.md
new file mode 100644
--- /dev/null
+++ b/.changeset/held-markerless-branch-claim.md
@@ -1,0 +1,5 @@
+---
+'octane': patch
+---
+
+Keep every root of a hydrating `@if` or `@switch` arm that suspends inside a deferred `<Hydrate>` boundary while the server rendered no range for it. When the arm's last root was static, after the component that suspended or after a `use()` in the arm itself, the boundary's retry still bounded the arm after its first roots. Hydration looked right, but switching to another case left the arm's later roots on screen, and a case change while the boundary was pending did the same. The arm now ends after every root its template adopted, both when it first suspends and when the boundary retries it.
diff --git a/.changeset/markerless-branch-claim.md b/.changeset/markerless-branch-claim.md
new file mode 100644
--- /dev/null
+++ b/.changeset/markerless-branch-claim.md
@@ -1,0 +1,5 @@
+---
+'octane': patch
+---
+
+Keep every root of a hydrating `@if` or `@switch` branch that the server rendered no range for. Such a branch adopts the server nodes at the cursor in place, and hydration bounded its content after the first root it adopted. When the branch was the whole content of another arm or of a component the client adopted, the rules that remove the server's leftover content then deleted the branch's later roots, which the client still renders, and reported a mismatch for them. A branch that was not deleted from still owned only its first root, so switching it off left the others on screen. The branch now ends after all the roots its template adopted. The server content after them is still removed and reported once, and a branch whose roots outnumber what the server rendered there is built on the client and reported, instead of hydrating without its later roots. This also covers a branch inside a component that was adopted in place.
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
@@ -18958,9 +18958,13 @@
rebuiltTail: Node | null = null;
/**
* The start comment of each markerless branch that holdMarkerlessBranch
- * holds, to where its content reached when it threw.
+ * holds, to where its content reaches: after its template's roots once that
+ * template adopted them (renderOwned), and else where it reached when it
+ * threw.
*/
private heldBranches: WeakMap<Node, Node | null> | null = null;
+ /** The arm of each branch that holdMarkerlessBranch held, to its start comment (renderHeld). */
+ private heldArms: WeakMap<Block, Node> | null = null;
private readonly unframedRootRanges = new WeakMap<Node, Node>();
/** Unframed claims whose render suspended, by the block that claimed (renderUnframed). */
private unframedClaims: WeakMap<Block, UnframedClaim> | null = null;
@@ -19004,6 +19008,15 @@
* does not claim. Undefined until the template adopts claimFrom.
*/
private claimEnd: Node | null | undefined = undefined;
+ /** The markerless branch whose content claim is open, with no open marker (renderOwned). */
+ private claimOwner: Block | null = null;
+ /**
+ * Where the content that the last markerless render claimed ends
+ * (renderOwned). Read only right after such a render, which sets it even
+ * when it throws: the holdMarkerlessBranch after a first render that threw
+ * reads it there.
+ */
+ private heldClaim: Node | null | undefined = undefined;
/** The last suspension thrown out of a client-built subtree (suspend). */
freshSuspension: SuspenseException | null = null;
/** Skip component-frame adoption until the declared container owner. */
@@ -19386,11 +19399,12 @@
unframed = claims.has(block);
if (!unframed) {
const claim = this.suspendedClaims?.get(source);
- if (claim === undefined) renderBlock(source);
- else {
+ const held = this.heldArms?.get(source);
+ if (claim !== undefined) {
this.suspendedClaims!.delete(source);
this.renderClaimed(source, claim[0], claim[1]);
- }
+ } else if (held !== undefined && this.heldBranches!.has(held)) this.renderHeld(source, held);
+ else renderBlock(source);
return;
}
const previousReplay = this.replayDepth;
@@ -19442,6 +19456,8 @@
*/
renderClaimed(block: Block, scope: Scope, slotKey: number): void {
const outer = this.beginClaim(getNextSibling(block.startMarker!));
+ const previousHeld = this.heldClaim;
+ this.heldClaim = undefined;
let from: Node | null | undefined;
try {
renderBlock(block);
@@ -19451,6 +19467,10 @@
throw error;
} finally {
from = this.endClaim(outer);
+ // When the component's content is a markerless branch whose template
+ // adopted the range's first node, its settlement is the frame's.
+ if (from === undefined && this.heldClaim !== undefined) from = this.heldClaim;
+ this.heldClaim = previousHeld;
}
if (!block.disposed) this.settleClaim(block, block.endMarker!, from, scope, slotKey);
}
@@ -20637,6 +20657,7 @@
? this.freshClone(fragment)
: this.rebuildFragment(fragment, cursor, loc);
this.inPlaceEnd = remainder;
+ if (cursor === this.claimFrom) this.claimRoots(cursor, fragment);
return { __oct_vfrag: true, firstChild: cursor } as unknown as Node;
}
// A nested fragment has no server wrapper, so its first logical root must
@@ -20675,9 +20696,10 @@
* after its roots: after `root`, or after the `fragment` template's roots,
* stepped as the compiled walk steps them. The template is the content when
* it renders in the range's owner: the block whose markers the range's
- * are, a component inheriting them, or the lite component that adopted the
- * range. A component that adopts `root` without a range of its own renders
- * in its own scope, and the slots after it claim the nodes after its root.
+ * are, a component inheriting them, the lite component that adopted the
+ * range, or the markerless branch whose content it is (claimOwner). A
+ * component that adopts `root` without a range of its own renders in its
+ * own scope, and the slots after it claim the nodes after its root.
* Returns false when the range ends before the template's roots do: every
* root, a hole included, renders at least one server node, so the server
* rendered other content there. Below a passthrough root, the range may
@@ -20687,9 +20709,10 @@
const open = domNode(root).previousSibling;
const scope = CURRENT_SCOPE;
if (
- open === null ||
scope === null ||
- (scope.block.startMarker !== open && this.liteRanges.get(scope)?.start !== open)
+ (scope.block !== this.claimOwner &&
+ (open === null ||
+ (scope.block.startMarker !== open && this.liteRanges.get(scope)?.start !== open)))
)
return true;
this.claimFrom = null;
@@ -20882,6 +20905,58 @@
}
/**
+ * First render of `block`, a markerless branch that took the place of the
+ * cursor, `first`, before its anchor. Returns where its content ends: after
+ * the roots of its own template, when that template adopted `first`
+ * (claimRoots), and else from where the render left the cursor
+ * (markerlessEnd). The cursor rests on the first root a template adopts,
+ * so a template with several roots claims them all only this way.
+ */
+ renderMarkerless(block: Block, first: Node): Node | null {
+ const before = domNode(first).previousSibling;
+ const claimed = this.renderOwned(block, first);
+ return claimed === undefined
+ ? this.markerlessEnd(before, block.parentNode!, block.endMarker)
+ : claimed;
+ }
+
+ /**
+ * Render `block`, a markerless branch whose content starts at `first`, with
+ * a claim on that content owned by `block`. Returns the first node after
+ * the roots of its own template, when that template adopted `first`
+ * (claimRoots), and else undefined. A render that throws leaves the same
+ * in heldClaim.
+ */
+ private renderOwned(block: Block, first: Node | null): Node | null | undefined {
+ const outer = this.beginClaim(first);
+ const outerOwner = this.claimOwner;
+ this.claimOwner = block;
+ try {
+ renderBlock(block);
+ } finally {
+ this.claimOwner = outerOwner;
+ this.heldClaim = this.endClaim(outer);
+ }
+ return this.heldClaim;
+ }
+
+ /**
+ * Resume `block`, the arm of a branch that holdMarkerlessBranch holds after
+ * `start`, with the claim its first render had. An arm that suspended
+ * before its template adopted anything adopts in this render, and the
+ * cursor rests on the first root it adopts, so only the claim says where
+ * its roots end. The content reaches at least that far (heldBranchEnd),
+ * whether or not this render completes.
+ */
+ private renderHeld(block: Block, start: Node): void {
+ try {
+ this.renderOwned(block, getNextSibling(start));
+ } finally {
+ if (this.heldClaim !== undefined) this.heldBranches!.set(start, this.heldClaim);
+ }
+ }
+
+ /**
* Where the content of a markerless branch that took the cursor's place
* after `before` in `parent` ends, from where its render left the cursor.
* The content is whole nodes and server ranges, from the first one up to at
@@ -20922,7 +20997,7 @@
* `parent` threw while its content was server nodes that it adopted or has
* yet to adopt, so it has no boundary yet. Mark where it starts with a
* comment of the branch's own, which no adoption claims or discards the way
- * it can a server node, and remember where the content reached. A retry of
+ * it can a server node, and remember where the content reaches. A retry of
* the same arm finalizes from that comment, and another arm replaces the
* content after it (heldBranchEnd). An attempt that is discarded instead
* leaves the server DOM as it was.
@@ -20942,15 +21017,20 @@
start,
before === null ? getFirstChild(parent) : getNextSibling(before),
);
- (this.heldBranches ??= new WeakMap()).set(start, this.markerlessEnd(start, parent, after));
+ const claimed = this.heldClaim;
+ (this.heldBranches ??= new WeakMap()).set(
+ start,
+ claimed === undefined ? this.markerlessEnd(start, parent, after) : claimed,
+ );
+ (this.heldArms ??= new WeakMap()).set(state.block!, start);
state.markerlessBefore = start;
}
/**
* Where the content of a held branch that starts after `start` ends, or
* undefined when `start` holds no branch. That is the later of where the
- * content reached when the arm threw and where the arm's last render left
- * the cursor. A render adopts as it advances the cursor, but it can begin
+ * held record says the content reaches and where the arm's last render
+ * left the cursor. A render adopts as it advances the cursor, but it can begin
* from a cursor that an earlier sibling parked on `start`, and slots that
* the first attempt never reached adopt only in a retry. A bound that a
* retry's mismatch recovery discarded no longer counts.
@@ -20969,6 +21049,7 @@
/** Remove a held branch's start comment once its arm is finalized after it. */
dropHeldStart(start: Node, parent: Node): void {
+ this.heldBranches!.delete(start);
this.save(parent);
domNode(start as ChildNode).remove();
}
@@ -43245,8 +43326,10 @@
);
state.block = b;
state.markerlessBefore = before;
+ let contentEnd: Node | null | undefined;
try {
- renderBlock(b);
+ if (cursor === null) renderBlock(b);
+ else contentEnd = hydration!.renderMarkerless(b, cursor);
} catch (error) {
// A branch that throws before inserting anything stays unfinalized so
// a same-branch retry finalizes it. One that already inserted its
@@ -43291,15 +43374,7 @@
hydration!.holdMarkerlessBranch(state, domParent, marker, contentBefore, after, error);
throw error;
}
- finalizeMarkerlessBranch(
- state,
- domParent,
- b,
- marker,
- contentBefore,
- after,
- cursor === null ? after : hydration!.markerlessEnd(contentBefore, domParent, after),
- );
+ finalizeMarkerlessBranch(state, domParent, b, marker, contentBefore, after, contentEnd);
replaceSharedBlockBoundary(
parentBlock,
oldBlockStart,
diff --git a/packages/octane/tests/hydration/_fixtures/adopted-component-tail.tsrx b/packages/octane/tests/hydration/_fixtures/adopted-component-tail.tsrx
--- a/packages/octane/tests/hydration/_fixtures/adopted-component-tail.tsrx
+++ b/packages/octane/tests/hydration/_fixtures/adopted-component-tail.tsrx
@@ -80,3 +80,43 @@
<p>{'after'}</p>
</div>;
}
+
+function ServerPair() @{
+ <>
+ <i>{'ok'}</i>
+ <b>{'b'}</b>
+ </>
+}
+
+function ServerShape() @{
+ <>
+ <i>{'ok'}</i>
+ <b>{'b'}</b>
+ <s class="foreign">{'f'}</s>
+ </>
+}
+
+function ClientShape(props: { inner?: boolean }) @{
+ @if (props.inner) {
+ <>
+ <i>{'ok'}</i>
+ <b>{'b'}</b>
+ </>
+ }
+}
+
+// A component whose identity differs on the client, and whose body is a
+// branch the server rendered no range for: the branch's template adopts the
+// frame's first hosts in place.
+export function BranchBody(props: { server?: 'tail' | 'same'; inner?: boolean }) {
+ const Shape =
+ props.server === 'tail'
+ ? ServerShape
+ : props.server === 'same'
+ ? ServerPair
+ : ClientShape;
+ return <div>
+ <Shape inner={props.inner} />
+ <p>{'after'}</p>
+ </div>;
+}
diff --git a/packages/octane/tests/hydration/_fixtures/branch-arm-claim-tail.tsrx b/packages/octane/tests/hydration/_fixtures/branch-arm-claim-tail.tsrx
--- a/packages/octane/tests/hydration/_fixtures/branch-arm-claim-tail.tsrx
+++ b/packages/octane/tests/hydration/_fixtures/branch-arm-claim-tail.tsrx
@@ -116,6 +116,106 @@
</div>
}
+// The client's arm is a branch the server rendered no range for. Its template
+// adopts the server arm's hosts in place, after which the server's arm ends
+// with a host the client does not render.
+export function MarkerlessArm(props: { server?: boolean; inner?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <s>{'s'}</s>
+ <b>{'a'}</b>
+ <u>{'tail'}</u>
+ </>
+ } @else {
+ @if (props.inner) {
+ <>
+ <s>{'s'}</s>
+ <b>{'a'}</b>
+ </>
+ }
+ }
+ </div>
+}
+
+export function MarkerlessSwitch(props: { server?: boolean; inner?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <s>{'s'}</s>
+ <b>{'a'}</b>
+ <u>{'tail'}</u>
+ </>
+ } @else {
+ @switch (props.inner) {
+ @case true: {
+ <>
+ <s>{'s'}</s>
+ <b>{'a'}</b>
+ </>
+ }
+ }
+ }
+ </div>
+}
+
+// Neither branch has a server range, and the outer one's content is the inner.
+export function MarkerlessNested(props: { server?: boolean; inner?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <s>{'s'}</s>
+ <b>{'a'}</b>
+ <u>{'tail'}</u>
+ </>
+ } @else {
+ @if (props.inner) {
+ @if (props.inner) {
+ <>
+ <s>{'s'}</s>
+ <b>{'a'}</b>
+ </>
+ }
+ }
+ }
+ </div>
+}
+
+// The server's arm renders exactly the client's hosts.
+export function MarkerlessSameArm(props: { server?: boolean; inner?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <>
+ <s>{'s'}</s>
+ <b>{'a'}</b>
+ </>
+ } @else {
+ @if (props.inner) {
+ <>
+ <s>{'s'}</s>
+ <b>{'a'}</b>
+ </>
+ }
+ }
+ </div>
+}
+
+// The server's arm ends before the client's branch renders its second host.
+export function MarkerlessShortArm(props: { server?: boolean; inner?: boolean }) @{
+ <div>
+ @if (props.server) {
+ <s>{'s'}</s>
+ } @else {
+ @if (props.inner) {
+ <>
+ <s>{'s'}</s>
+ <b>{'a'}</b>
+ </>
+ }
+ }
+ </div>
+}
+
// Both arms render the same content: the arm's template adopts the host that
// follows its last component.
export function SameContent(props: { server?: boolean }) @{
diff --git a/packages/octane/tests/hydration/_fixtures/in-place-component-sibling.tsrx b/packages/octane/tests/hydration/_fixtures/in-place-component-sibling.tsrx
--- a/packages/octane/tests/hydration/_fixtures/in-place-component-sibling.tsrx
+++ b/packages/octane/tests/hydration/_fixtures/in-place-component-sibling.tsrx
@@ -73,6 +73,35 @@
</div>
}
+// A component whose body is a branch with two roots.
+function Pair(props: { shown: boolean }) @{
+ @if (props.shown) {
+ <>
+ <em>{'x' as string}</em>
+ <b>{'b' as string}</b>
+ </>
+ }
+}
+
+// The first component's branch has no server range either: its roots are the
+// server arm's first two elements.
+export function BranchArm(props: { on: boolean; shown: boolean; z: string }) @{
+ <div>
+ @if (props.on) {
+ <>
+ <Pair shown={props.shown} />
+ <Leaf v={props.z} />
+ </>
+ } @else {
+ <>
+ <em>{'x' as string}</em>
+ <b>{'b' as string}</b>
+ <Leaf v={props.z} />
+ </>
+ }
+ </div>
+}
+
// The server's arm has no range for the second component.
export function ShortArm(props: { on: boolean; z: string }) @{
<div>
diff --git a/packages/octane/tests/hydration/_fixtures/markerless-arm-retry.tsrx b/packages/octane/tests/hydration/_fixtures/markerless-arm-retry.tsrx
--- a/packages/octane/tests/hydration/_fixtures/markerless-arm-retry.tsrx
+++ b/packages/octane/tests/hydration/_fixtures/markerless-arm-retry.tsrx
@@ -324,3 +324,97 @@
</section>
</div>
}
+
+// The arm's last root is static, after the component that suspends. The
+// arm is the whole content of the @else arm, so the server's @if range
+// ends after it.
+export function TrailingRoot(props: { server?: boolean; k: string; leaf: Promise<string> }) @{
+ <div>
+ <Hydrate split={false} when={load()}>
+ <section>
+ @if (props.server) {
+ <>
+ <s>{'s'}</s>
+ <i>{'z'}</i>
+ <b>{'b'}</b>
+ </>
+ } @else {
+ @if (props.k === 'a') {
+ <>
+ <s>{'s'}</s>
+ <Reader value={props.leaf} />
+ <b>{'b'}</b>
+ </>
+ } @else if (props.k === 'c') {
+ <p>{'c'}</p>
+ }
+ }
+ <em>{'e'}</em>
+ </section>
+ </Hydrate>
+ </div>
+}
+
+// The arm suspends before its template adopts anything, so only the retry
+// says where its roots end.
+export function TrailingClone(props: { server?: boolean; k: string; leaf: Promise<string> }) @{
+ <div>
+ <Hydrate split={false} when={load()}>
+ <section>
+ @if (props.server) {
+ <>
+ <s>{'s'}</s>
+ <i>{'z'}</i>
+ <b>{'b'}</b>
+ </>
+ } @else {
+ @if (props.k === 'a') {
+ const text = use(props.leaf);
+ <>
+ <s>{'s'}</s>
+ <i>{text as string}</i>
+ <b>{'b'}</b>
+ </>
+ } @else if (props.k === 'c') {
+ <p>{'c'}</p>
+ }
+ }
+ <em>{'e'}</em>
+ </section>
+ </Hydrate>
+ </div>
+}
+
+function ServerFrame() @{
+ <>
+ <s>{'s'}</s>
+ <i>{'z'}</i>
+ <b>{'b'}</b>
+ </>
+}
+
+function ClientFrame(props: { k: string; leaf: Promise<string> }) @{
+ @if (props.k === 'a') {
+ <>
+ <s>{'s'}</s>
+ <Reader value={props.leaf} />
+ <b>{'b'}</b>
+ </>
+ } @else if (props.k === 'c') {
+ <p>{'c'}</p>
+ }
+}
+
+// The same arm as the body of a component whose identity differs on the
+// client: the arm's template adopts the server component's roots in place.
+export function TrailingFrame(props: { server?: boolean; k: string; leaf: Promise<string> }) @{
+ const Shape = props.server ? ServerFrame : ClientFrame;
+ <div>
+ <Hydrate split={false} when={load()}>
+ <section>
+ <Shape k={props.k} leaf={props.leaf} />
+ <em>{'e'}</em>
+ </section>
+ </Hydrate>
+ </div>
+}
diff --git a/packages/octane/tests/hydration/adopted-component-tail.test.ts b/packages/octane/tests/hydration/adopted-component-tail.test.ts
--- a/packages/octane/tests/hydration/adopted-component-tail.test.ts
+++ b/packages/octane/tests/hydration/adopted-component-tail.test.ts
@@ -46,6 +46,12 @@
return copy.innerHTML;
}
+/** `actual` holds exactly the `expected` nodes: the same objects, in order. */
+function expectSame(actual: ArrayLike<Node>, expected: readonly Node[]): void {
+ expect(actual).toHaveLength(expected.length);
+ Array.from(actual).forEach((node, i) => expect(node).toBe(expected[i]));
+}
+
function tail(site: string): string {
return (
`Octane hydration mismatch at ${site}: the client expected the end of the component but ` +
@@ -159,6 +165,33 @@
expect(warnings()).toHaveLength(dev ? 1 : 0);
});
+ // The client component's body is a branch the server rendered no range for.
+ // The branch ends after every root its template adopted in place, so only
+ // the server's tail after them goes, and the branch owns them all.
+ it.each([
+ { server: 'tail', stale: true },
+ { server: 'same', stale: false },
+ ] as const)(
+ 'keeps every root of a branch with no server range in the frame (server: $server)',
+ async ({ server: serverShape, stale }) => {
+ render('BranchBody', { server: serverShape });
+ const adopted = [...container.querySelectorAll('i, b, p')];
+
+ const recoverable = await hydrate(client.BranchBody, { inner: true });
+
+ expect(markup(container.firstElementChild!)).toBe('<i>ok</i><b>b</b><p>after</p>');
+ expectSame(container.querySelectorAll('i, b, p'), adopted);
+ expect(recoverable).toEqual(stale ? [expect.stringMatching(MISMATCH)] : []);
+ expect(warnings()).toEqual(
+ dev && stale ? [tail(siteOf('function BranchBody(', '<Shape'))] : [],
+ );
+
+ await act(async () => root!.render(client.BranchBody, { inner: false }));
+ expect(markup(container.firstElementChild!)).toBe('<p>after</p>');
+ expect(container.querySelector('p')).toBe(adopted[adopted.length - 1]);
+ },
+ );
+
it.each(
SHAPES.flatMap((shape) => [
{ ...shape, server: false },
diff --git a/packages/octane/tests/hydration/branch-arm-claim-tail.test.ts b/packages/octane/tests/hydration/branch-arm-claim-tail.test.ts
--- a/packages/octane/tests/hydration/branch-arm-claim-tail.test.ts
+++ b/packages/octane/tests/hydration/branch-arm-claim-tail.test.ts
@@ -46,6 +46,12 @@
return adopted.filter((element) => element.localName !== 'u');
}
+/** `actual` holds exactly the `expected` nodes: the same objects, in order. */
+function expectSame(actual: ArrayLike<Node>, expected: readonly Node[]): void {
+ expect(actual).toHaveLength(expected.length);
+ Array.from(actual).forEach((node, i) => expect(node).toBe(expected[i]));
+}
+
const DISCARDED =
'Hydration mismatch: the server-rendered node did not match the client render; ' +
'the mismatched subtree was rebuilt on the client.';
@@ -61,7 +67,7 @@
compileOptions: { dev },
});
let container: HTMLElement;
- let root: { unmount(): void } | null;
+ let root: { render(component: unknown, props?: unknown): void; unmount(): void } | null;
let errSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
@@ -165,6 +171,62 @@
expect(warnings()).toEqual([]);
});
+ // A branch the server rendered no range for ends after every root its
+ // template adopted in place, not after the first: the arm keeps them all,
+ // and the branch owns them.
+ it.each([
+ { branch: 'an @if', name: 'MarkerlessArm' },
+ { branch: 'a @switch', name: 'MarkerlessSwitch' },
+ { branch: 'an @if inside another', name: 'MarkerlessNested' },
+ ])(
+ 'discards only the server tail after the roots of $branch with no server range',
+ async ({ name }) => {
+ const { div, adopted, recoverable } = await hydrate(name, { server: true }, { inner: true });
+
+ expect(markup(div)).toBe('<s>s</s><b>a</b>');
+ expectSame(div.children, withoutTail(adopted));
+ expect(recoverable).toEqual([DISCARDED]);
+ expect(warnings()).toEqual(dev ? [report(name)] : []);
+
+ flushSync(() => root!.render(client[name], { inner: false }));
+ expect(markup(div)).toBe('');
+ flushSync(() => root!.render(client[name], { inner: true }));
+ expect(markup(div)).toBe('<s>s</s><b>a</b>');
+ },
+ );
+
+ it('keeps every root of a branch with no server range when the server rendered no more', async () => {
+ const { div, adopted, recoverable } = await hydrate(
+ 'MarkerlessSameArm',
+ { server: true },
+ { inner: true },
+ );
+
+ expect(markup(div)).toBe('<s>s</s><b>a</b>');
+ expectSame(div.children, adopted);
+ expect(recoverable).toEqual([]);
+ expect(warnings()).toEqual([]);
+
+ flushSync(() => root!.render(client.MarkerlessSameArm, { inner: false }));
+ expect(markup(div)).toBe('');
+ });
+
+ // Its roots outnumber what the server rendered before the arm's end, so
+ // the branch is built on the client in place of the server's content.
+ it('rebuilds a branch with no server range whose roots the server’s arm ends before', async () => {
+ const { div, recoverable } = await hydrate(
+ 'MarkerlessShortArm',
+ { server: true },
+ { inner: true },
+ );
+
+ expect(markup(div)).toBe('<s>s</s><b>a</b>');
+ expect(recoverable).toEqual([DISCARDED]);
+
+ flushSync(() => root!.render(client.MarkerlessShortArm, { inner: false }));
+ expect(markup(div)).toBe('');
+ });
+
it('keeps a root that recovery rebuilt in the arm while discarding the tail', async () => {
const { div, adopted, recoverable } = await hydrate('RebuiltBeforeClaim', { server: true }, {});
const claimed = adopted.find((element) => element.localName === 's');
diff --git a/packages/octane/tests/hydration/in-place-component-sibling.test.ts b/packages/octane/tests/hydration/in-place-component-sibling.test.ts
--- a/packages/octane/tests/hydration/in-place-component-sibling.test.ts
+++ b/packages/octane/tests/hydration/in-place-component-sibling.test.ts
@@ -203,3 +203,32 @@
expect(recoverable).toEqual([]);
});
});
+
+// A branch with no server range of its own, inside a component adopted in
+// place, owns every root it adopted there: switching it off removes them all,
+// and the next component keeps its server range. As above, only the
+// development compile renders this hookless call against the cursor.
+describe('hydrateRoot — a branch in a component adopted in place', () => {
+ it('owns every root it adopted', async () => {
+ const client = clients.development;
+ const props = { on: true, shown: true, z: 'z' };
+ const { host, serverNodes, recoverable } = await hydrate(
+ client,
+ 'BranchArm',
+ { ...props, on: false },
+ props,
+ );
+
+ expect(markup(host)).toBe('<em>x</em><b>b</b><em>z</em>');
+ expect(host.children).toHaveLength(3);
+ serverNodes.forEach((node, i) => expect(host.children[i]).toBe(node));
+ expect(recoverable).toEqual([]);
+ expect(warnings()).toEqual([]);
+
+ flushSync(() => root!.render(client.BranchArm, { ...props, shown: false }));
+ expect(markup(host)).toBe('<em>z</em>');
+ expect(host.children[0]).toBe(serverNodes[2]);
+ flushSync(() => root!.render(client.BranchArm, props));
+ expect(markup(host)).toBe('<em>x</em><b>b</b><em>z</em>');
+ });
+});
diff --git a/packages/octane/tests/hydration/markerless-arm-retry.test.ts b/packages/octane/tests/hydration/markerless-arm-retry.test.ts
--- a/packages/octane/tests/hydration/markerless-arm-retry.test.ts
+++ b/packages/octane/tests/hydration/markerless-arm-retry.test.ts
@@ -195,6 +195,50 @@
expect(warnings()).toEqual([]);
});
+ // The arm's last root is static. Neither the arm's first render nor its
+ // retry rests the cursor on that root, so only where its template's roots
+ // end says the arm owns it.
+ const TRAILING = [
+ { arm: 'an @if arm', name: 'TrailingRoot' },
+ { arm: 'the body of a component the client adopted', name: 'TrailingFrame' },
+ { arm: 'an @if arm that suspends before it clones', name: 'TrailingClone' },
+ ];
+
+ it.each(TRAILING)('keeps and owns the static last root of $arm', async ({ name }) => {
+ const { leaf, resolveLeaf, nodes, em } = await hydratePending(name);
+ await act(async () => resolveLeaf('z'));
+
+ expect(markup(section())).toBe('<s>s</s><i>z</i><b>b</b><em>e</em>');
+ expectAdopted(nodes);
+ expect(recoverable).toEqual([]);
+ expect(warnings()).toEqual([]);
+
+ render(name, 'c', leaf);
+ expect(markup(section())).toBe('<p>c</p><em>e</em>');
+ expect(tail()).toBe(em);
+ render(name, 'b', leaf);
+ expect(markup(section())).toBe('<em>e</em>');
+ render(name, 'a', leaf);
+ expect(markup(section())).toBe('<s>s</s><i>z</i><b>b</b><em>e</em>');
+ expect(tail()).toBe(em);
+ });
+
+ it.each(TRAILING)('replaces every root of $arm while it is pending', async ({ name }) => {
+ const { leaf, resolveLeaf, em } = await hydratePending(name);
+ render(name, 'c', leaf);
+ await act(async () => {});
+ await act(async () => resolveLeaf('z'));
+
+ expect(markup(section())).toBe('<p>c</p><em>e</em>');
+ expect(tail()).toBe(em);
+ expect(recoverable).toEqual([]);
+ expect(warnings()).toEqual([]);
+
+ render(name, 'a', leaf);
+ expect(markup(section())).toBe('<s>s</s><i>z</i><b>b</b><em>e</em>');
+ expect(tail()).toBe(em);
+ });
+
it('bounds an arm whose render ends inside its root', async () => {
const { nodes, em } = await hydrate('NestedTail', { k: 'a' });You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 0d67b3e. Configure here.
Contributor
Benchmark report
Compares js-framework: 1k/10k row operations (ms, lower is better)All 20 timed operations (20 within noise)
Application bundle size (bytes)
22 other measured values are unchanged. Public-import reachability bundles (bytes)
94 other measured values are unchanged. |
trueadm
added a commit
that referenced
this pull request
Oct 3, 2026
…closing range #1622 lets claimRoots accept a markerless branch's claim (claimOwner), which has no open marker of its own. A rebuilt root that is such a branch's content recorded the node before it as its range's start, which can be an enclosing range's open marker. The commit-time take then removed the nodes after the branch up to that range's end, including a later call's server node (NotFoundError). Only a claim on a marker range records rebuiltRange. Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm
added a commit
that referenced
this pull request
Oct 3, 2026
… over its range (#1614) * fix(hydration): remove the server tail after a component root rebuilt over its range When a range's own single-root template did not match the range's first server node, adopt() rebuilt the root, but only a successful adoption recorded where the range's content ends (claimRoots). settleClaim then fell back to its last-slot heuristic and left the rest of the server range on screen, unreported. The single-root mismatch path now records the claim when it rebuilds the open claim's first node, under claimRoots' existing owner check, and settleClaim removes that tail with sweepRebuiltTail, without a second report. A lite component replayed by a <Hydrate> resume (#1598) sweeps the same tail before stepping past its range. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(hydration): sweep a resumed lite range only when its whole content was rebuilt The <Hydrate> resume path swept the rebuilt root's server tail whenever one was pending. When the rebuilt root came from a call in a fragment's leading hole, that tail was the fragment's own adopted static root, so the resume deleted it. The single-root mismatch path now records the scope whose range's whole content the rebuilt root is (claimRoots' owner check), and a lite replay sweeps only for that scope. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(hydration): sweep a resumed rebuilt root's tail by range, in full component slots too A <Hydrate> resume of a wrapper whose only call inherits its range left the rebuilt root's server tail. The rebuild recorded the inheriting call's scope, but the wrapper's slot is what completes on the resume, and that wrapper renders in a full component slot, which never swept. The rebuild now records the start marker of the range whose whole content it is (rebuiltRange), and both the lite replay and componentSlotImpl's post-render step sweep when their range starts there. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(hydration): take a rebuilt root's range tail when the root commits A <Hydrate> resume completes a range through whichever slot owns it, and each slot kind needed its own sweep of a rebuilt root's server tail. The root that is its range's whole content now takes the rest of that range when it commits (rebuiltAt), while the cursor still rests right after the node it replaces, so every slot kind and every resume path is covered. The sweeps in settleClaim, componentSlotLite's replay and componentSlotImpl are gone. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(hydration): keep a markerless branch's rebuilt root out of the enclosing range #1622 lets claimRoots accept a markerless branch's claim (claimOwner), which has no open marker of its own. A rebuilt root that is such a branch's content recorded the node before it as its range's start, which can be an enclosing range's open marker. The commit-time take then removed the nodes after the branch up to that range's end, including a later call's server node (NotFoundError). Only a claim on a marker range records rebuiltRange. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(hydration): cover a rebuilt root whose component suspends before it commits A <Hydrate> resume claims the range again when the component that rebuilt its single root suspended before committing it (a use() in setup, or in the template after the clone), so the root still takes its range's tail when the resume commits it. Pin that for lite and full slots. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Summary
A hydrating
@if/@switcharm that the server rendered no range for ("markerless") takes the place of the server node at the cursor. Hydration bounded its content from where its render left the cursor.clone()parks the cursor on the first root a template adopts, so a multi-root arm ended after its first root.<Hydrate split={false}>is held. Its retry is bounded by the cursor as well. When the arm's last root is static, after the component that suspended or after ause()in the arm itself, hydration looks right, but a later case change leaves the trailing roots on screen. A case change while the boundary is still pending does the same.The arm now ends after every root its template adopted, on first render, when it is held, and when it is retried.
Changes
All in
packages/octane/src/runtime.ts:HydrationCapability.renderMarkerless(block, first)replaces renderBranchSlot's first-mountrenderBlockwhile hydrating. It renders throughrenderOwned, which opens a claim owned by the branch block (beginClaim+claimOwner).claimRootsaccepts that owner even with no open marker, so it records exactly where the arm template's roots end.adopt()'s in-place fragment path also callsclaimRoots. That covers a lite component adopted in place whose body is the branch.renderOwnedleaves the claimed end inheldClaimeven when the render throws.holdMarkerlessBranchrecords that end, falling back to themarkerlessEndestimate. It used to discard it.renderSuspendedbefore any parent re-render. For a held arm, which it finds throughheldArms, the retry now re-opens the claim from the node after the held start comment (renderHeld). An arm that suspended before cloning gets its exact end there.dropHeldStartreleases the record once the arm is finalized.HydrationCapability.Why the retry claim is in
renderSuspended, not renderBranchSlot's same-branch pathThe task first suggested opening the retry claim in the same-branch path. Tracing showed that this path never clones the arm's template. In the preserved Hydrate activation,
renderSuspended(source)re-renders the arm first, then the parent re-render reaches the same-branch path. A claim opened in the same-branch path settled nothing;TrailingClonestayed red with it. The claim from the first render covers arms that had already cloned before they suspended. TherenderSuspendedclaim covers arms that had not.Deliberately not included
This PR has no defence-in-depth guard that makes tail rules ignore client-minted markerless bounds. The literal rule would also block the now-exact claimed ends that the arm-tail tests rely on. An estimate-only variant (a WeakSet plus
arm = null) regressed a nested markerless branch (@ifinside@if, with server tail<u>): that tail stayed on screen unreported, while the claim alone removes it.Validation
Regression tests, each seen failing first:
branch-arm-claim-tail:@if,@switch, nested@if, same server content, and a short server arm that rebuilds.adopted-component-tail: frame tail and same, in 3 modes.in-place-component-sibling: dev-only shape.markerless-arm-retry:TrailingRoot,TrailingFrameandTrailingClone, each covering both retry-then-case-change and case-change-while-pending.markerless-arm-retryhas 12 new cases, all red on the C1-2 fix alone. Breaking each half shows that both halves are needed:TrailingRoot,TrailingFrame).renderSuspendedclaim: 4 red (TrailingClone).Targeted run,
--project octaneand--project octane-prod, 351/351 each:markerless-arm-retry,markerless-text-hydrate,branch-arm-claim-tail,branch-arm-tail,adopted-branch-tail,adopted-component-tail,in-place-component-sibling,rebuilt-clone-suspended,rebuilt-clone-blocks,unframed-fragment-root.pnpm format:files:checkandpnpm typecheck:fileson the changed files;pnpm syncproduced no changes.Not run locally (CI covers these): full
pnpm test, fullpnpm typecheck,pnpm format:check.pnpm format:check(scoped:format:files:check)pnpm typecheck(scoped:typecheck:files)pnpm test(left to CI)targeted tests: listed above
Bundle size
node benchmarks/bundle-size/run-minimal.mjs, raw / gzip / brotli:The held-retry part adds 0 B to bundles that don't hydrate. C1-2's 9 B in renderBranchSlot does reach them: the PR bench's app bundles (todo, chat, weather) grow by +9 raw and +12–17 gzip each. The run-minimal scenarios above and the CI-enforced budgets are unchanged. The hydrate-root and deferred-hydration budgets are already stale and CI doesn't enforce them.
Risk / follow-ups
claimRootssteps over the template's root count from the adopted first root. Where the server rendered fewer roots and a later sibling's server nodes follow without a close marker, the claim can run into them. That is a mismatch case either way, and the first-render path from C1-2 already behaves like this. This PR extends the claimed end to held arms.claimRootsdoc comment. fix(hydration): discard the server tail after a last call adopted in place #1615 composes; itsinPlaceTailis exact.return.tsrxcomponent whose<Hydrate>children render as descriptors reports "expected another list item" on the held retry and duplicates the first root. It reproduces on main.expectSamehelper, becausetoEqualon DOM nodes is structural. The DOM-node-identity sweep's shared helper can replace it.Provenance
agent-authored)🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Note
Medium Risk
Touches core hydration adoption, branch bounds, and deferred-boundary retry paths in runtime.ts; incorrect bounds could cause DOM leaks or mismatches, but change is narrowly scoped with extensive targeted tests.
Overview
Fixes hydration for markerless
@if/@switcharms (no server range): the runtime used to bound arm content from the hydration cursor, so multi-root arms effectively ended after the first adopted root. That let tail cleanup drop later roots or leave them visible when the arm toggled off, and broke deferred<Hydrate>retries when a static trailing root followed a suspend.HydrationCapabilitynow tracks a branch-owned claim (claimOwner,heldClaim,heldArms). First mount goes throughrenderMarkerless→renderOwned, soclaimRootsrecords where the arm template’s roots end;claimRootsalso runs on in-place fragment adoption. Held arms store that end inholdMarkerlessBranch;renderSuspendedresumes them withrenderHeldand the same claim.renderBranchSlotfinalizes using the claimedcontentEndinstead ofmarkerlessEndalone.Adds changesets and broad hydration regression tests (markerless arms, adopted components, suspense retries, nested branches).
Reviewed by Cursor Bugbot for commit 0d67b3e. Bugbot is set up for automated code reviews on this repo. Configure here.