Repository navigation
fix(hydration): discard server ranges a shorter @if/@switch arm leaves unclaimed - #1564
Conversation
…s unclaimed When the server rendered another arm, the client arm adopts the server's arm range from its start. A shorter client arm claimed only a prefix, and the server's remaining components stayed on screen until the next arm swap, reported only as a text mismatch. After the arm's first hydrating render, a server range still at the cursor is one nothing in the arm claimed: every slot claim parks the cursor past its range. discardArmTail removes from there to the arm's end, stopping at client nodes a mismatch rebuild placed there, and reports one structural recoverable error with a dev diagnostic at the directive. A dormant <Hydrate> whose captures changed discards quietly. Template adoption leaves the cursor on adopted elements, so a tail that starts with an element or text is left for a follow-up. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…aker-9545a4 # Conflicts: # packages/octane/src/runtime.ts
Benchmark report
Compares js-framework: 1k/10k row operations (ms, lower is better)All 20 timed operations (20 within noise)
Application bundle size (bytes)
23 other measured values are unchanged. Public-import reachability bundles (bytes)
98 other measured values are unchanged. CI job durations
Compares the CI run for
Not compared (skipped, failed, or not run on this pull request): Lynx compatibility (minimum), heavy integration (runtime-loaders), Three compatibility (minimum r156), Three compatibility (current), heavy integration (browser), heavy integration (eval-corpus), Lynx compatibility (current), test shard (Node 22.22.2, 1/4), heavy integration (package-builds), heavy integration (astro), test shard (Node 22.22.2, 2/4), test shard (Node 22.22.2, 3/4), test shard (Node 22.22.2, 4/4), test (22). All 26 timed jobs
|
…er arm
The website integration suite failed on every route. TanStack Router's
ScrollRestorationScript takes `@if (script)` on the server and its empty
`@else { <></> }` arm on the client, where the script helper returns null.
That empty arm claims nothing of the server's arm range, so the cursor
stayed on the range's first node, an open marker, and discardArmTail
discarded and reported the server's whole arm as a tail.
The tail check now measures only from what the arm claimed: a cursor still
on the arm's first node means the range is the server's other arm, not a
tail after this one, and it keeps main's behavior. A regression covers the
empty-arm shape.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…aker-9545a4 # Conflicts: # packages/octane/src/runtime.ts
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: Close-marker cursor skips leftover tails
- Added a while loop in discardArmTail that walks past consecutive close markers (from @Try and deopt-list slots that don't advance past their outer range) before checking isOpen, so leftover server content following those blocks is correctly identified and discarded.
Or push these changes by commenting:
@cursor push 58aaf77f36
Preview (58aaf77f36)
diff --git a/.changeset/branch-arm-tail-hydration.md b/.changeset/branch-arm-tail-hydration.md
new file mode 100644
--- /dev/null
+++ b/.changeset/branch-arm-tail-hydration.md
@@ -1,0 +1,5 @@
+---
+'octane': patch
+---
+
+Discard the server content an `@if` or `@switch` arm leaves unclaimed during hydration. When the server rendered a different arm, the client arm adopts the server's range from its start. Server components or ranges left after the client arm's content stayed on screen until the next arm swap. Hydration now removes them and reports one structural `onRecoverableError`, with a development diagnostic at the directive. A dormant `<Hydrate>` boundary whose captures changed before activation discards them without a report.
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
@@ -19345,6 +19345,58 @@
}
/**
+ * Runs after a branch's first hydrating render, which adopted the server's
+ * arm range from `first` to `end`. Every range the arm claims parks the
+ * cursor past it, so once the arm has claimed something, a server range
+ * still at the cursor is one that nothing in the arm claimed: the server
+ * rendered another arm here, longer than this one. Discard the server
+ * content from the cursor up to `end`, stopping at any client nodes that
+ * mismatch recovery built there, and report it once.
+ *
+ * An arm that claimed nothing leaves the cursor on `first`, and the whole
+ * range is then the server's other arm rather than a tail after this one.
+ * The cursor does not move past the elements and text that a template
+ * adopts either, so at an element or text node it cannot tell what the arm
+ * adopted from what the server rendered for another arm. Both stay.
+ *
+ * Some slots (@try, deopt lists) park the cursor on their close marker
+ * rather than advancing past the outer range. A close marker is never
+ * ambiguous — the block it closes is finished — so the method walks past
+ * consecutive close markers before inspecting the unclaimed tail.
+ */
+ discardArmTail(scope: Scope, slotKey: number, first: Node, end: Node): void {
+ let from: Node | null = this.node;
+ if (from === first) return;
+ // A close marker means a control-flow block or slot parked the cursor on
+ // its end rather than advancing past the outer range (e.g. @try, deopt
+ // lists). Walk past consecutive close markers — each belongs to a finished
+ // claimed block — so `from` lands on the first unclaimed sibling.
+ while (from !== null && from !== end && this.isClose(from)) from = getNextSibling(from);
+ if (from === null || from === end || !this.isOpen(from)) return;
+ let stop: Node | null = null;
+ let node: Node | null = from;
+ while (node !== null && node !== end) {
+ if (stop === null && this.freshNodes.has(node)) stop = node;
+ node = getNextSibling(node);
+ }
+ // Clear it only when the cursor precedes `end`.
+ if (node === null) return;
+ if (PRESENTATION_HYDRATION?.revision !== undefined) presentationMiss();
+ this.save(domNode(end).parentNode!);
+ // Captures that changed before a dormant boundary activated legitimately
+ // differ from the server's; still discard, but there is nothing to report.
+ if (!this.staleServerValues) {
+ noteRecoverableHydrationError(() => new Error(formatClientError(51)));
+ if (process.env.NODE_ENV !== 'production') {
+ const loc = siteLoc(scope, slotKey);
+ if (loc) this.warnStructural(loc, 'the end of the branch', this.describe(from));
+ }
+ }
+ removeRange(from, stop ?? end);
+ this.node = end;
+ }
+
+ /**
* Remove the server content from `from` up to `end` that a child slot's
* value cannot adopt, and point the cursor at `end`. Reports the structural
* mismatch (`expected`, and the `actual` server node or a description of
@@ -41797,6 +41849,7 @@
let rebuild = false;
let inner: Comment | null = null;
let innerEnd: Comment | null = null;
+ let first: Node | null = null;
if (hydration !== null && hydration.isOpen(getNextSibling(state.start))) {
inner = getNextSibling(state.start) as Comment;
innerEnd = hydration.close(inner);
@@ -41832,7 +41885,7 @@
if (inner !== null) {
bStart = inner;
bEnd = innerEnd as Comment;
- hydration!.node = getNextSibling(inner);
+ hydration!.node = first = getNextSibling(inner);
} else {
bStart = state.start;
bEnd = state.end as Node;
@@ -41866,6 +41919,9 @@
hydration!.node = getNextSibling(state.end as Node);
} else {
renderBlock(b);
+ // The server may have rendered another arm here, longer than this one.
+ if (inner !== null && hydration!.node !== bEnd)
+ hydration!.discardArmTail(parentScope, slotKey, first!, bEnd);
}
} else if (hydration !== null && getNextSibling(state.start) !== state.end) {
if (PRESENTATION_HYDRATION?.revision !== undefined) throw new Error(formatClientError(75));
diff --git a/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx b/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx
new file mode 100644
--- /dev/null
+++ b/packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx
@@ -1,0 +1,167 @@
+import { Hydrate, type ComponentBody } from 'octane';
+import type { HydrationStrategy } from 'octane/hydration';
+
+function Leaf(props: { v: string }) @{
+ <em>{props.v}</em>
+}
+
+// The server's else arm renders two components where the client's then arm
+// renders one, which adopts the first of them.
+export function IfComponents(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <Leaf v="x" />
+ } @else {
+ <>
+ <Leaf v="y" />
+ <Leaf v="z" />
+ </>
+ }
+ </div>
+}
+
+// The two cases share their first component, so the server's extra one is the
+// only difference.
+export function SwitchComponents(props: { k: string }) @{
+ <div id="r">
+ @switch (props.k) {
+ @case 'one': {
+ <Leaf v="x" />
+ }
+ @default: {
+ <>
+ <Leaf v="x" />
+ <Leaf v="z" />
+ </>
+ }
+ }
+ </div>
+}
+
+// The client's empty arm claims nothing of the server's other arm, the shape
+// the router binding renders its server-only scroll restoration script with.
+export function EmptyArm(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <Leaf v="x" />
+ } @else {
+ <></>
+ }
+ </div>
+}
+
+// The arm ends with elements after its component, which the arm adopts.
+export function TrailingHosts(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <>
+ <Leaf v="x" />
+ <b>{'b' as string}</b>
+ <i>{'i' as string}</i>
+ </>
+ }
+ </div>
+}
+
+export function Tail() @{
+ <u>{'tail' as string}</u>
+}
+
+// The arm ends with a boundary whose child is still loading on the client.
+export function TrailingTry(props: { on: boolean; Child: ComponentBody }) @{
+ const Child = props.Child;
+ <div id="r">
+ @if (props.on) {
+ <>
+ <Leaf v="x" />
+ @try {
+ <Child />
+ } @pending {
+ <p>{'loading' as string}</p>
+ }
+ </>
+ }
+ </div>
+}
+
+// A pending child after the branch holds the first attempt, which then replays.
+export function IfThenChild(props: { on: boolean; Child: ComponentBody }) @{
+ const Child = props.Child;
+ <div id="r">
+ @if (props.on) {
+ <Leaf v="x" />
+ } @else {
+ <>
+ <Leaf v="x" />
+ <Leaf v="z" />
+ </>
+ }
+ <Child />
+ </div>
+}
+
+// Inside a boundary, the suspended attempt leaves what it built for the next one.
+export function TryIfThenChild(props: { on: boolean; Child: ComponentBody }) @{
+ const Child = props.Child;
+ <div id="r">
+ @try {
+ <section>
+ @if (props.on) {
+ <Leaf v="x" />
+ } @else {
+ <>
+ <Leaf v="x" />
+ <Leaf v="z" />
+ </>
+ }
+ <Child />
+ </section>
+ } @pending {
+ <p>{'loading' as string}</p>
+ }
+ </div>
+}
+
+// The client arm ends with a @try boundary, which parks the cursor on its
+// inner close marker rather than advancing past the outer range. The server's
+// longer else arm has an extra component after the shared @try that the client
+// arm must discard.
+export function IfTryThenTail(props: { on: boolean }) @{
+ <div id="r">
+ @if (props.on) {
+ <>
+ @try {
+ <Leaf v="x" />
+ } @pending {
+ <p>{'loading' as string}</p>
+ }
+ </>
+ } @else {
+ <>
+ @try {
+ <Leaf v="x" />
+ } @pending {
+ <p>{'loading' as string}</p>
+ }
+ <Leaf v="z" />
+ </>
+ }
+ </div>
+}
+
+export function DormantIf(props: { on: boolean; when: HydrationStrategy }) @{
+ <div id="r">
+ <Hydrate when={props.when} split={false}>
+ <section>
+ @if (props.on) {
+ <Leaf v="x" />
+ } @else {
+ <>
+ <Leaf v="x" />
+ <Leaf v="z" />
+ </>
+ }
+ </section>
+ </Hydrate>
+ </div>
+}
diff --git a/packages/octane/tests/hydration/branch-arm-tail.test.ts b/packages/octane/tests/hydration/branch-arm-tail.test.ts
new file mode 100644
--- /dev/null
+++ b/packages/octane/tests/hydration/branch-arm-tail.test.ts
@@ -1,0 +1,290 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { act, flushSync, hydrateRoot, lazy } from '../../src/index.js';
+import type { ComponentBody } from '../../src/index.js';
+import { condition, load } from 'octane/hydration';
+import * as ServerRT from 'octane/server';
+import { loadCompiledFixtureSource, loadServerFixture } from '../_server-fixture';
+
+// When the server rendered another arm of an @if or @switch, the client arm
+// adopts the server's arm range from its start. Server content that the client
+// arm leaves unclaimed at the end of that range must not stay on screen: the
+// client discards it and reports the structural mismatch once, at the
+// directive's own site, even when a pending sibling replays the hydration
+// attempt.
+
+const FIXTURE = join(
+ process.cwd(),
+ 'packages/octane/tests/hydration/_fixtures/branch-arm-tail.tsrx',
+);
+const FILE = 'branch-arm-tail.tsrx';
+const SOURCE = readFileSync(FIXTURE, 'utf8');
+const LINES = SOURCE.split('\n');
+
+/** `line:column` of the first `directive` after the line containing `text`. */
+function siteLoc(text: string, directive: string): string {
+ const from = LINES.findIndex((line) => line.includes(text));
+ if (from < 0) throw new Error(`fixture has no line containing ${text}`);
+ const index = LINES.findIndex((line, i) => i > from && line.includes(directive));
+ return `${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);
+ return copy.innerHTML;
+}
+
+const STRUCTURAL = /the mismatched subtree was rebuilt on the client/;
+
+describe.each([
+ { name: 'development compile', dev: true },
+ { name: 'production compile', dev: false },
+])('hydrateRoot — a branch arm shorter than the server arm ($name)', ({ dev }) => {
+ const server = loadServerFixture(FIXTURE, { id: FILE });
+ const client = loadCompiledFixtureSource(SOURCE, {
+ id: FILE,
+ mode: 'client',
+ compileOptions: { dev },
+ });
+ let container: HTMLElement;
+ let root: { unmount(): void } | null;
+ let errSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = null;
+ errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ root?.unmount();
+ container.remove();
+ errSpy.mockRestore();
+ });
+
+ const warnings = () =>
+ errSpy.mock.calls
+ .map((call: unknown[]) => String(call[0]))
+ .filter((message: string) => message.includes('hydration mismatch'));
+
+ const tailReport = (component: string, directive: string) =>
+ `Octane hydration mismatch at ${FILE}:${siteLoc(`function ${component}(`, directive)}: ` +
+ 'the client expected the end of the branch but the server rendered a control-flow ' +
+ 'block. The mismatched subtree was rebuilt on the client.';
+
+ async function hydrate(
+ name: string,
+ serverProps: Record<string, unknown>,
+ props: Record<string, unknown>,
+ ) {
+ container.innerHTML = ServerRT.renderToString(server[name], serverProps).html;
+ const host = container.querySelector('#r')!;
+ const nodes = [...host.querySelectorAll('*')];
+ const ems = [...host.querySelectorAll('em')];
+ const recoverable: string[] = [];
+ const active = hydrateRoot(container, client[name], props, {
+ onRecoverableError: (error: unknown) => recoverable.push((error as Error).message),
+ });
+ root = active;
+ flushSync(() => {});
+ // Recoverable reports are delivered after the hydration burst.
+ await act(async () => {});
+ return {
+ host,
+ nodes,
+ ems,
+ recoverable,
+ render: (next: Record<string, unknown>) => flushSync(() => active.render(client[name], next)),
+ };
+ }
+
+ it('discards the server components after the adopted @if arm and reports it once', async () => {
+ const s = await hydrate('IfComponents', { on: false }, { on: true });
+
+ expect(container.querySelector('#r')).toBe(s.host);
+ expect(markup(s.host)).toBe('<em>x</em>');
+ expect(s.host.querySelector('em')).toBe(s.ems[0]);
+ expect(s.recoverable).toEqual([expect.stringMatching(STRUCTURAL)]);
+ expect(warnings()).toEqual(
+ dev
+ ? [
+ tailReport('IfComponents', '@if'),
+ expect.stringContaining('server rendered text "y" but the client rendered "x"'),
+ ]
+ : [],
+ );
+
+ s.render({ on: false });
+ expect(markup(s.host)).toBe('<em>y</em><em>z</em>');
+ s.render({ on: true });
+ expect(markup(s.host)).toBe('<em>x</em>');
+ });
+
+ it('discards the server components after the adopted @switch case and reports it once', async () => {
+ const s = await hydrate('SwitchComponents', { k: 'two' }, { k: 'one' });
+
+ expect(markup(s.host)).toBe('<em>x</em>');
+ expect(s.host.querySelector('em')).toBe(s.ems[0]);
+ expect(s.recoverable).toEqual([expect.stringMatching(STRUCTURAL)]);
+ expect(warnings()).toEqual(dev ? [tailReport('SwitchComponents', '@switch')] : []);
+
+ s.render({ k: 'two' });
+ expect(markup(s.host)).toBe('<em>x</em><em>z</em>');
+ s.render({ k: 'one' });
+ expect(markup(s.host)).toBe('<em>x</em>');
+ });
+
+ it('discards the server component after a @try that ends the adopted arm', async () => {
+ const s = await hydrate('IfTryThenTail', { on: false }, { on: true });
+
+ expect(container.querySelector('#r')).toBe(s.host);
+ expect(markup(s.host)).toBe('<em>x</em>');
+ expect(s.host.querySelector('em')).toBe(s.ems[0]);
+ expect(s.recoverable).toEqual([expect.stringMatching(STRUCTURAL)]);
+ expect(warnings()).toEqual(dev ? [tailReport('IfTryThenTail', '@if')] : []);
+
+ s.render({ on: false });
+ expect(markup(s.host)).toBe('<em>x</em><em>z</em>');
+ s.render({ on: true });
+ expect(markup(s.host)).toBe('<em>x</em>');
+ });
+
+ it('builds the components a longer client arm adds and reports it once', async () => {
+ const s = await hydrate('SwitchComponents', { k: 'one' }, { k: 'two' });
+
+ expect(markup(s.host)).toBe('<em>x</em><em>z</em>');
+ expect(s.host.querySelector('em')).toBe(s.ems[0]);
+ expect(s.recoverable).toEqual([expect.stringMatching(STRUCTURAL)]);
+ });
+
+ it.each([
+ { name: 'IfComponents', props: { on: false }, html: '<em>y</em><em>z</em>' },
+ { name: 'SwitchComponents', props: { k: 'two' }, html: '<em>x</em><em>z</em>' },
+ { name: 'TrailingHosts', props: { on: true }, html: '<em>x</em><b>b</b><i>i</i>' },
+ ])(
+ 'adopts every node of a matching $name arm without a report',
+ async ({ name, props, html }) => {
+ const s = await hydrate(name, props, props);
+
+ expect(markup(s.host)).toBe(html);
+ expect([...s.host.querySelectorAll('*')]).toEqual(s.nodes);
+ expect(s.recoverable).toEqual([]);
+ expect(warnings()).toEqual([]);
+ },
+ );
+
+ // The tail check measures from what the arm claimed. An empty client arm
+ // claims nothing, so the server's whole range is the other arm, not a tail
+ // after this one, and it is left to the existing empty-arm handling.
+ it('does not report a client arm that renders nothing over the server arm', async () => {
+ const s = await hydrate('EmptyArm', { on: true }, { on: false });
+
+ expect(s.recoverable).toEqual([]);
+ expect(warnings()).toEqual([]);
+
+ s.render({ on: true });
+ expect(markup(s.host)).toBe('<em>x</em>');
+ s.render({ on: false });
+ expect(markup(s.host)).toBe('');
+ });
+
+ it('keeps the server content of a boundary that ends the arm while it loads', async () => {
+ container.innerHTML = ServerRT.renderToString(server.TrailingTry, {
+ on: true,
+ Child: server.Tail,
+ }).html;
+ const host = container.querySelector('#r')!;
+ const tail = container.querySelector('u')!;
+ const recoverable: string[] = [];
+ let deliver!: (module: { default: ComponentBody }) => void;
+ const Child = lazy(
+ () => new Promise<{ default: ComponentBody }>((accept) => (deliver = accept)),
+ );
+ await act(() => {
+ root = hydrateRoot(
+ container,
+ client.TrailingTry,
+ { on: true, Child },
+ { onRecoverableError: (error: unknown) => recoverable.push((error as Error).message) },
+ );
+ });
+
+ expect(markup(host)).toBe('<em>x</em><u>tail</u>');
+ expect(container.querySelector('u')).toBe(tail);
+
+ await act(async () => deliver({ default: client.Tail }));
+
+ expect(markup(host)).toBe('<em>x</em><u>tail</u>');
+ expect(container.querySelector('u')).toBe(tail);
+ expect(recoverable).toEqual([]);
+ expect(warnings()).toEqual([]);
+ });
+
+ it.each([
+ { attempt: 'the root', name: 'IfThenChild', html: '<em>x</em><u>tail</u>' },
+ {
+ attempt: 'a @try boundary',
+ name: 'TryIfThenChild',
+ html: '<section><em>x</em><u>tail</u></section>',
+ },
+ ])('reports the discard once when a pending sibling replays $attempt', async ({ name, html }) => {
+ container.innerHTML = ServerRT.renderToString(server[name], {
+ on: false,
+ Child: server.Tail,
+ }).html;
+ const host = container.querySelector('#r')!;
+ const em = container.querySelector('em')!;
+ const recoverable: string[] = [];
+ let deliver!: (module: { default: ComponentBody }) => void;
+ const Child = lazy(
+ () => new Promise<{ default: ComponentBody }>((accept) => (deliver = accept)),
+ );
+ await act(() => {
+ root = hydrateRoot(
+ container,
+ client[name],
+ { on: true, Child },
+ { onRecoverableError: (error: unknown) => recoverable.push((error as Error).message) },
+ );
+ });
+ await act(async () => deliver({ default: client.Tail }));
+
+ expect(markup(host)).toBe(html);
+ expect(container.querySelector('em')).toBe(em);
+ expect(recoverable).toEqual([expect.stringMatching(STRUCTURAL)]);
+ expect(warnings()).toEqual(dev ? [tailReport(name, '@if')] : []);
+ });
+
+ // Captures that changed before a dormant boundary activated legitimately
+ // differ from the server's: discard the other arm's content, but report
+ // nothing.
+ it('discards silently in a dormant boundary whose branch changed before activation', async () => {
+ const serverProps = { on: false, when: condition(false) };
+ container.innerHTML = ServerRT.renderToString(server.DormantIf, serverProps).html;
+ const section = container.querySelector('section')!;
+ const em = container.querySelector('em')!;
+ const recoverable: string[] = [];
+ const active = hydrateRoot(container, client.DormantIf, serverProps, {
+ onRecoverableError: (error: unknown) => recoverable.push((error as Error).message),
+ });
+ root = active;
+ flushSync(() => {});
+ expect(markup(section)).toBe('<em>x</em><em>z</em>');
+
+ await act(() => active.render(client.DormantIf, { on: true, when: load() }));
+ await act(async () => {});
+
+ expect(container.querySelector('section')).toBe(section);
+ expect(markup(section)).toBe('<em>x</em>');
+ expect(container.querySelector('em')).toBe(em);
+ expect(recoverable).toEqual([]);
+ expect(warnings()).toEqual([]);
+ });
+});
diff --git a/packages/octane/tests/hydration/rebuilt-clone-blocks.test.ts b/packages/octane/tests/hydration/rebuilt-clone-blocks.test.ts
--- a/packages/octane/tests/hydration/rebuilt-clone-blocks.test.ts
+++ b/packages/octane/tests/hydration/rebuilt-clone-blocks.test.ts
@@ -135,22 +135,41 @@
expect(warnings()).toEqual(dev ? [rebuilt(leaf)] : []);
});
+ /** The arm's report for a server range that nothing in the client's arm claimed. */
+ function armTail(component: string): string {
+ return (
+ `Octane hydration mismatch at ${FILE}:${lineOf(`function ${component}(`) + 2}:2: the client ` +
+ 'expected the end of the branch but the server rendered a control-flow block. The ' +
+ 'mismatched subtree was rebuilt on the client.'
+ );
+ }
+
it.each([
- { output: 'element', name: 'ForeignNodeBranch', leaf: 'IfLeaf', html: '<s>c</s>ok' },
{
+ output: 'element',
+ name: 'ForeignNodeBranch',
+ leaf: 'IfLeaf',
+ html: '<s>c</s>ok',
+ discarded: false,
+ },
+ {
output: 'list range',
name: 'ForeignListBranch',
leaf: 'ForLeaf',
html: '<s>x</s><s>y</s>ok',
+ discarded: true,
},
])(
'does not claim a server $output that follows the rebuilt clone',
- async ({ name, leaf, html }) => {
+ async ({ name, leaf, html, discarded }) => {
const recoverable = await hydrate(name, { server: true }, {});
expect(markup(container.querySelector('i')!)).toBe(html);
expect(recoverable).toEqual([expect.stringMatching(STRUCTURAL)]);
- expect(warnings()).toEqual(dev ? [rebuilt(leaf)] : []);
+ // Nothing in the client's arm claims a server range, so the arm
+ // discards it: a second recovery, with its own diagnostic.
+ if (discarded) expect(markup(container.firstElementChild!)).toBe(`<i>${html}</i>`);
+ expect(warnings()).toEqual(dev ? [rebuilt(leaf), ...(discarded ? [armTail(name)] : [])] : []);
},
);You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 639dabe. Configure here.
…ition Keep both sweeps after an adopted @if/@switch arm renders. This branch's sweepRebuiltTail runs first: the server content a rebuilt root left after it is the rest of what that root's mismatch replaced, and it goes quietly under that one report. #1564's discardArmTail then reports any other server range the arm left unclaimed. rebuilt-clone-blocks' ForeignListBranch therefore expects one diagnostic, not two, and both foreign tails are now asserted removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…at renders nothing (#1580) * fix(tanstack-router): hydrate the scroll restoration script arm the server rendered router-core's browser build of getScrollRestorationScriptForRouter always returns null, so the client hydrated ScrollRestorationScript's empty arm over the server's ScriptOnce arm and the server <script> stayed in the document with no report. The client now takes the arm the server took, ScriptOnce adopts the server script without comparing its content and drops it after hydration, and a client-only ScriptOnce renders nothing as upstream's does. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(hydration): discard and report a server arm under a client arm that renders nothing An @if with no client arm discards the server's other arm and reports it as an empty branch, but a client arm with an empty body (@else { <></> }) claimed nothing and left the server arm on screen with no report: #1564's tail discard skipped an arm whose cursor never left its first node. That cursor position is only ambiguous at elements and text, which a template adopts without moving the cursor; every range an arm claims moves it. When the arm's first node opens a server range, discard it and report an empty branch, as the null-body path does. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
…rm (#1578) A @Try whose body throws on the client during hydration builds its catch arm fresh and parks the hydration cursor on its own close marker (rebuiltSlot), not past it. When that boundary ends a shorter client @if/@switch arm, discardArmTail found the close marker instead of the server range after it and returned, so the components the server's longer arm rendered after the boundary stayed on screen, unreported. The slot that parked the cursor there claimed through its close marker, so discardArmTail now looks one node past a close marker for the unclaimed range. Reported by Cursor Bugbot on #1564. Co-authored-by: Claude Opus 5.5 <[email protected]>


Summary
Hydration left server content on screen when an
@ifor@switcharm was shorter than the arm the server rendered.The server's arm markers are plain
<!--[-->pairs and don't record which arm was rendered, so the client arm adopts the server's arm range from its start. A shorter client arm claimed only a prefix of that range. Example:The server renders
{ on: false }and the client hydrates with{ on: true }. The DOM ended up as<em>x</em><em>z</em>, and the only report was the text mismatch fromytox(code 61). The stalezstayed through same-arm re-renders until the next arm swap removed the whole range. Inline ternaries lower to the same branch slot and behaved the same way.Fix. A new
HydrationCapability.discardArmTailruns after the arm's first hydrating render inrenderBranchSlot. Every slot claim (component frame, nested block, list, child slot) parks the hydration cursor past its server range. So a block-open marker still at the cursor before the arm's end is a server range that nothing in the arm claimed. The method:onRecoverableError(code 51), plus a development diagnostic at the directive: "the client expected the end of the branch…";<Hydrate>boundary whose captures changed before activation.Why only open markers. Template adoption doesn't advance the cursor past the elements and text it adopts, so on the normal path the cursor often sits on adopted DOM. I instrumented the whole
octane+octane-prodsuite (36.5k tests). Many correct hydrations end an arm with the cursor on adopted hosts. The cursor ended an arm on a block-open marker in only two scenarios, and both were real stale content: this repro, and the stale server list inrebuilt-clone-blocks'ForeignListBranch. Discarding from a cursor on an element would delete live DOM, so a tail that starts with an element or text is left alone (see follow-ups).Why only after the arm claimed something. The first CI run failed the website integration suite on every route. TanStack Router's
ScrollRestorationScriptrenders@if (script) { <ScriptOnce/> } @else { <></> }, and router-core's client build of the script helper always returnsnull. So the client hydrates the empty@elsearm over the server's then-arm, and that arm claims nothing. The cursor stays on the range's first node, an open marker, and the check treated the server's whole arm as a tail.discardArmTailnow runs only when the cursor moved off the arm's first node, which means the arm claimed something and the leftover really is a tail after it. An arm that claims nothing keepsmain's behavior. Whether to discard and report such an arm is a separate decision that would first require fixing the binding's arm swap (see follow-ups).Why not detect the swap up front. That needs arm identity in the server markers, which is an SSR protocol change.
Why not reuse
discard()/reportRebuiltRange(). Both record the range end inHYDRATION_REBUILT. For the arm's inner end, that could make a later boundary retry'sclaimRangeat the same end treat adopted content as already rebuilt and rebuild it quietly. A discarded tail can't be detected again by a retry, because a boundary retry runs over the trimmed DOM and a root rollback restores the DOM and drops the held report. The replay tests below cover both cases.Hot path:
renderBranchSlotgains one comparison after the arm renders (inner !== null && cursor !== end). The method call happens only while hydrating an adopted arm whose cursor isn't on the arm's end, and it returns after a node-type check unless the cursor is on an open marker.Validation
pnpm format:check: I ranpnpm format:files:checkon the changed files instead (passes).pnpm typecheck: I ranpnpm typecheck:fileson the changed files, with the.tsrxfixture passed explicitly (passes).pnpm test: I ran theoctaneandoctane-prodVitest projects instead (results below). CI covers the rest.tests/hydration/branch-arm-tail.test.tswith fixture_fixtures/branch-arm-tail.tsrx, run in dev and prod compiles. It asserts final DOM, adopted-node identity, exactly oneonRecoverableError, and the exact development diagnostics.main):@if,@switch, a pending lazy sibling replaying the root attempt, the same inside a@tryboundary, and a dormant<Hydrate>whose branch changed before activation (discards silently). All 10 fail on currentmain(the 5 cases × dev/prod), each with the stale<em>z</em>still present.@trywhose child is still loading (its server content must survive).rebuilt-clone-blocks.tests/hydration/rebuilt-clone-blocks.test.ts: in theForeignListBranch("list range") case, the server's[p, q]list used to stay on screen next to the rebuilt<i>; the test only checked the<i>. It now asserts the list is gone, and in development it expects a second diagnostic for that discard. The recoverable-error count stays at one.octaneandoctane-prodprojects on the current head (after the guard and the latestmainmerge): 36,847 passed and 46 failed out of 36,897 (4 skipped). All 46 failures were in 9 load-sensitive files (behavior-root,hydration-ssr-diagnostics,web3-island,volar,compiler-vite-options,text-sibling-hydrate, …) and were 5 s timeouts at load average around 40. Each of those files passes when run alone. The run before the guard was clean, with 36,869 passing.EmptyArmcase: a client arm that renders nothing over the server's other arm reports nothing, and later swaps converge to the correct DOM. It fails without the guard.website/tests/ssr-hydration.e2e.test.ts), run locally: 68 of 69 passed. The remaining failure, a playground source-mapping assertion ("hovering @case in types marked nothing"), passes in both dev and prod builds when rerun alone.benchmarks/bundle-size/run-minimal.mjs, against base 4ab33b6). Mergingmaindidn't change this code delta.hydrate-root: +288 raw / +75 gzip / +3 brotli.deferred-hydration: +289 raw / +68 gzip / +7 brotli.binding-radix-esbuild, has the same raw size and gzip -5 / brotli -34.Risk / follow-ups
fix/adopted-branch-tail). It covers this PR's range tail and also leftover elements and text, using a compiler root count passed totemplate()and a new error code 337. It carries this PR'sbranch-arm-tailtest and fixture, adjusted to code 337. The two conflict inrenderBranchSlot, so only one can land, and Dominic is choosing. If fix(hydration): discard the server content an adopted @if/@switch arm leaves unclaimed #1565 is chosen, this PR closes. If this one lands first, an element/text follow-up should replacediscardArmTailrather than add a second check.sweepRebuiltTail(bEnd)at the same call site, for a tail after a root rebuilt over a mismatch. This PR covers the no-rebuild case, which fix(hydration): keep a rebuilt clone where the server node it replaced stood #1561 lists as an unfixed follow-up. Whichever lands second should callsweepRebuiltTailfirst: it parks the cursor atbEnd, sodiscardArmTailthen does nothing for a tail the rebuild already reported. Under fix(hydration): keep a rebuilt clone where the server node it replaced stood #1561, theForeignListBranchlist goes through the quiet sweep, so the second development diagnostic expected here would go away.ScrollRestorationScripthydrates a different arm from the one the server rendered, so the server<script>and its markers stay in the client DOM for good, silently, exactly as onmain. A follow-up should fix the binding first, then decide whether a client arm that claims nothing should discard and report, as thebody === nullempty-branch path already does.<em>x</em><b>z</b>and the client then arm renders<em>x</em>:<b>z</b>stays, with no report. Fixing it needs adopt-time tracking of how far an arm's templates claimed. A separate session is investigating 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 cursor/adoption logic for control-flow arms; wrong tail detection could remove live DOM or double-report, though behavior is gated on open markers and covered by broad hydration tests.
Overview
Fixes hydration leaving stale server DOM when the client takes a different
@if/@switcharm than SSR and that arm is shorter than the server’s (e.g. server else renders two<Leaf>s, client then adopts only the first).Adds
discardArmTailon the hydration runtime and invokes it fromrenderBranchSlotafter the arm’s first hydrating render when the cursor has not reached the adopted arm end. It strips unclaimed server nodes up to the arm boundary (stopping at client-built mismatch recovery nodes), advances the cursor, fires one structuralonRecoverableError(client error 51), and in dev logs a directive-level “expected end of branch” diagnostic. Dormant<Hydrate>boundaries whose captures changed before activation still discard but do not report.New
branch-arm-tailhydration tests cover@if,@switch, lazy replay,@try, and dormant boundaries;rebuilt-clone-blocksexpects the list tail inForeignListBranchto be removed with an extra dev warning when applicable.Reviewed by Cursor Bugbot for commit 639dabe. Bugbot is set up for automated code reviews on this repo. Configure here.