Skip to content

Commit a18099f

Browse files
committed
fix(solid): sweep truncated fragments when hydration starts after parse
watchTruncation only armed its DOMContentLoaded listener when the runtime booted with document.readyState === "loading". An entry that runs later (a deferred module, or one that waits on a route chunk that lands after DOMContentLoaded) never swept, so a truncated stream left its _fr declarations pending and hydration never finished. Under the in-render bootstrap (_$HY.s) every declaration and settle is a parser-inserted script, so once parsing is over a pending _fr can only be truncated. Run the same sweep at boot in that case: drop the records that can no longer settle, reject the cut fragments, and a macrotask later reject the refs a keyed consumer already took. Host-placed bootstraps keep the current behavior.
1 parent 5e68925 commit a18099f

7 files changed

Lines changed: 230 additions & 40 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"solid-js": patch
3+
---
4+
5+
A stream cut short no longer hangs hydration when the client runtime starts after the parser finished (#2958). The truncation sweep only armed when `hydrate()` ran while `document.readyState` was still `"loading"`. An entry that ran later, such as one waiting on a route module that arrives after `DOMContentLoaded`, or a deferred module entry, left every unsettled `_fr` declaration pending, so its `<Loading>` kept the fallback and hydration never ended. When the document carries the in-render bootstrap (`<HydrationScript />`, which declares `_$HY.s`), a runtime that boots after parsing now runs the same sweep at boot: the records that can no longer settle leave the registry, the cut fragments are rejected, and a macrotask later the refs a keyed consumer already took are rejected. Documents with a host-placed bootstrap (`generateHydrationScript()`) are unchanged.

‎documentation/server-components/server-components-principles.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -837,10 +837,12 @@ DOM; nothing per-mount survives unmount.
837837
any `_fr` declaration still unsettled then is marked rejected with a truncation
838838
error, releasing its boundary through the normal rejection path and its
839839
document-adoption waiters through the ledger (closes solidjs/solid#2958 for
840-
documents). The sweep arms only when the runtime booted while the document was
841-
still streaming — a late-loaded runtime can't tell a completed page from a
842-
truncated one. Frame-stream truncation (pump ends without the root's `complete`
843-
chunk) lands with the `:error` content-state records above, not before them.
840+
documents). A runtime that boots after parsing sweeps at boot, but only under
841+
the in-render bootstrap (`_$HY.s`): every declaration and settle there is a
842+
parser-inserted script, so a declaration still pending can no longer settle.
843+
Under a host-placed bootstrap a late runtime stays out. Frame-stream truncation
844+
(pump ends without the root's `complete` chunk) lands with the `:error`
845+
content-state records above, not before them.
844846

845847
### 5.6 Head and assets
846848

‎packages/solid/src/client/hydration.ts‎

Lines changed: 38 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2646,38 +2646,45 @@ function subscribeFragments(cb: (id: string, parent?: ParentNode) => void): () =
26462646
// unsettled then can never settle, because the script that would resolve it
26472647
// executes during parse. Each one becomes a rejected fragment: an
26482648
// error-class write, distinguishable from a server-sent rejection by its
2649-
// error, surfaced through the boundary's normal rejection path. The sweep
2650-
// only arms when the runtime booted while the document was still streaming;
2651-
// a runtime loaded after parse can't tell a completed page from a truncated
2652-
// one and stays out of it.
2649+
// error, surfaced through the boundary's normal rejection path. A runtime
2650+
// that boots while the document is still streaming sweeps at
2651+
// DOMContentLoaded. One that boots after the parser finished (an entry that
2652+
// waits on a route module, a deferred entry) sweeps at boot, but only under
2653+
// the in-render bootstrap (`_$HY.s`, #3971): every declaration and settle in
2654+
// that document is a parser-inserted script, so the transport has already
2655+
// closed. Both passes then run before hydrate()'s claim walk: the records
2656+
// that can no longer settle leave the registry, boundaries register against
2657+
// rejected declarations, and only the rejection of consumed refs waits its
2658+
// macrotask. Without the ledger (a host-placed bootstrap, a
2659+
// hand-built `_$HY`) nothing says the parser carried the records, and a late
2660+
// runtime stays out.
26532661
function watchTruncation(hy: any) {
2654-
if (typeof document === "undefined" || document.readyState !== "loading") return;
2655-
document.addEventListener(
2656-
"DOMContentLoaded",
2657-
() => {
2658-
if (!hy.r) return;
2659-
// First, before any boundary below resumes: a cut fragment's fresh
2660-
// render adopts by id, so the records that can no longer settle must
2661-
// already be gone from the registry when it reads them.
2662-
const consumed = dropTruncatedRefs(hy);
2663-
for (const key in hy.r) {
2664-
if (key.length <= 3 || !key.endsWith("_fr")) continue;
2665-
const ref = hy.r[key];
2666-
if (ref && typeof ref === "object" && !ref.s) markTruncated(hy, key.slice(0, -3));
2667-
}
2668-
// A macrotask later, on purpose: the fragment rejections above release
2669-
// their boundaries through microtask chains (abort race -> resume ->
2670-
// fresh render), and that teardown disposes the computations that
2671-
// adopted pending owner-id refs while hydrating. Rejecting refs
2672-
// synchronously would race the disposal and land an unhandled error in
2673-
// a still-live computation, halting the reactive system. After the
2674-
// boundaries have released, whoever still holds a consumed ref (keyed
2675-
// consumers like the router's query channel) is exactly who needs the
2676-
// rejection.
2677-
setTimeout(() => rejectTruncatedRefs(consumed));
2678-
},
2679-
{ once: true }
2680-
);
2662+
if (typeof document === "undefined") return;
2663+
const sweep = () => {
2664+
if (!hy.r) return;
2665+
// First, before any boundary below resumes: a cut fragment's fresh
2666+
// render adopts by id, so the records that can no longer settle must
2667+
// already be gone from the registry when it reads them.
2668+
const consumed = dropTruncatedRefs(hy);
2669+
for (const key in hy.r) {
2670+
if (key.length <= 3 || !key.endsWith("_fr")) continue;
2671+
const ref = hy.r[key];
2672+
if (ref && typeof ref === "object" && !ref.s) markTruncated(hy, key.slice(0, -3));
2673+
}
2674+
// A macrotask later, on purpose: the fragment rejections above release
2675+
// their boundaries through microtask chains (abort race -> resume ->
2676+
// fresh render), and that teardown disposes the computations that
2677+
// adopted pending owner-id refs while hydrating. Rejecting refs
2678+
// synchronously would race the disposal and land an unhandled error in
2679+
// a still-live computation, halting the reactive system. After the
2680+
// boundaries have released, whoever still holds a consumed ref (keyed
2681+
// consumers like the router's query channel) is exactly who needs the
2682+
// rejection.
2683+
setTimeout(() => rejectTruncatedRefs(consumed));
2684+
};
2685+
if (document.readyState === "loading")
2686+
document.addEventListener("DOMContentLoaded", sweep, { once: true });
2687+
else if (hy.s) sweep();
26812688
}
26822689

26832690
// The fragment pass above releases BOUNDARIES, but the registry also carries
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
* @vitest-environment jsdom
4+
*
5+
* The cut from truncated-fragment-fresh-render.spec.tsx (#4413), with a
6+
* runtime that boots after the parser finished. Under the in-render
7+
* bootstrap (`_$HY.s`) the sweep runs at hydrate() instead of at
8+
* DOMContentLoaded, and it still drops the dead records before any fresh
9+
* render reads them: each slow read asks once, and what the server sent
10+
* before the cut is adopted. Separate file because the ledger's truncation
11+
* record is module state.
12+
*
13+
* Replays the chunks test/server/truncated-fragment-fresh-render.gen.spec.tsx renders.
14+
*/
15+
import { expect, test, vi } from "vitest";
16+
import { readFileSync } from "node:fs";
17+
import { dirname, resolve } from "node:path";
18+
import { fileURLToPath } from "node:url";
19+
import { flush } from "solid-js";
20+
import { hydrate } from "@solidjs/web";
21+
import { createTruncatedFragmentApp } from "../harness/truncated-fragment-fresh-render.jsx";
22+
import { bootstrapHydrationGlobal } from "../harness/hydration-bootstrap.js";
23+
24+
const { shell, chunks } = JSON.parse(
25+
readFileSync(
26+
resolve(
27+
dirname(fileURLToPath(import.meta.url)),
28+
"../harness/__artifacts__/truncated-fragment-fresh-render.json"
29+
),
30+
"utf-8"
31+
)
32+
) as { shell: string; chunks: string[] };
33+
34+
const SERVER_TEXT = "a:slowb:fastb:slowc:bad failedc:slow";
35+
36+
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
37+
async function settle() {
38+
for (let i = 0; i < 4; i++) {
39+
await sleep(15);
40+
flush();
41+
}
42+
}
43+
44+
function applyChunk(container: HTMLElement, chunk: string, first: boolean) {
45+
const scriptRe = /<script(?:[^>]*)>([\s\S]*?)<\/script>/g;
46+
const scripts = [...chunk.matchAll(scriptRe)].map(m => m[1]);
47+
const stripped = chunk.replace(scriptRe, "");
48+
if (first) container.innerHTML = stripped;
49+
else container.insertAdjacentHTML("beforeend", stripped);
50+
for (const s of scripts) (0, eval)(s);
51+
}
52+
53+
test("cut after the first chunk, late boot: what the server sent is adopted, the rest computes", async () => {
54+
const hy = bootstrapHydrationGlobal();
55+
// The in-render bootstrap declares the shell-end ledger, and the shell's
56+
// marker has run: the whole shell parsed, then the connection dropped.
57+
hy.s = { "": 1 };
58+
delete (globalThis as any).$R;
59+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
60+
const error = vi.spyOn(console, "error").mockImplementation(() => {});
61+
const container = document.createElement("div");
62+
document.body.appendChild(container);
63+
const { App, asks } = createTruncatedFragmentApp();
64+
let dispose: (() => void) | undefined;
65+
try {
66+
applyChunk(container, shell, true);
67+
applyChunk(container, chunks[0], false);
68+
// Parsing is over before the entry runs: DOMContentLoaded is behind us.
69+
Object.defineProperty(document, "readyState", { value: "interactive", configurable: true });
70+
71+
dispose = hydrate(() => <App />, container);
72+
await settle();
73+
await settle();
74+
75+
// Each slow read asks once; `b:fast` and `c:bad` are not asked again.
76+
expect(asks()).toEqual(["a:slow", "b:slow", "c:slow"]);
77+
// The served value and the served error, beside the client's values.
78+
expect(container.textContent).toBe(SERVER_TEXT);
79+
expect(hy.done).toBe(true);
80+
const diagnostics = [...warn.mock.calls, ...error.mock.calls].map(c => String(c[0]));
81+
expect(diagnostics).toEqual([]);
82+
} finally {
83+
dispose?.();
84+
container.remove();
85+
warn.mockRestore();
86+
error.mockRestore();
87+
delete (document as any).readyState;
88+
await sleep(0);
89+
delete (globalThis as any)._$HY;
90+
}
91+
});

‎packages/web/test/hydration/truncated-fragment-fresh-render.spec.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,10 @@ async function withPage(body: (page: Page) => Promise<void>) {
7171
const error = vi.spyOn(console, "error").mockImplementation(() => {});
7272
const container = document.createElement("div");
7373
document.body.appendChild(container);
74-
// The runtime boots while the document is still streaming: the only
75-
// window where the truncation sweep arms.
74+
// The runtime boots while the document is still streaming, so the sweep
75+
// waits for DOMContentLoaded. A runtime that boots after the parser
76+
// finished sweeps at hydrate() instead
77+
// (truncated-fragment-fresh-render-late-start.spec.tsx).
7678
Object.defineProperty(document, "readyState", { value: "loading", configurable: true });
7779
const { App, asks } = createTruncatedFragmentApp();
7880
let dispose: (() => void) | undefined;
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
* @vitest-environment jsdom
4+
*
5+
* Truncation (#2958) when the runtime boots after the parser finished: an
6+
* entry that waits on a route module, or a deferred one, runs hydrate() once
7+
* `readyState` has left "loading", so there is no DOMContentLoaded left to
8+
* wait for. Under the in-render bootstrap (`_$HY.s`) every declaration and
9+
* every settle is a parser-inserted script, so a `_fr` still unsettled at
10+
* that point was cut off and has to release its boundary the same way.
11+
* Separate file because the ledger's truncation record is module state.
12+
*/
13+
import { expect, test, vi } from "vitest";
14+
import { readFileSync } from "node:fs";
15+
import { resolve, dirname } from "node:path";
16+
import { fileURLToPath } from "node:url";
17+
import { flush } from "solid-js";
18+
import { hydrate } from "@solidjs/web";
19+
import { scenarios } from "../harness/scenarios.jsx";
20+
21+
const artifactsDir = resolve(dirname(fileURLToPath(import.meta.url)), "../harness/__artifacts__");
22+
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
23+
const scenario = scenarios.find(s => s.name === "late-boundary-after-done")!;
24+
const scriptRe = /<script(?:[^>]*)>([\s\S]*?)<\/script>/g;
25+
26+
test("a runtime that boots after the parser finished releases a truncated boundary", async () => {
27+
const { shell } = JSON.parse(
28+
readFileSync(resolve(artifactsDir, `${scenario.name}.json`), "utf-8")
29+
) as { shell: string; rest: string };
30+
const key = shell.match(/_\$HY\.r\["([^"]+)_fr"\]/)![1];
31+
const container = document.createElement("div");
32+
document.body.appendChild(container);
33+
// The in-render bootstrap declares the shell-end ledger, and the shell's
34+
// marker has run: the whole shell parsed, then the connection dropped.
35+
(globalThis as any)._$HY = {
36+
events: [],
37+
completed: new WeakSet(),
38+
r: {},
39+
s: { "": 1 },
40+
fe() {}
41+
};
42+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
43+
// Parsing is over before the entry runs: DOMContentLoaded is behind us
44+
// (or about to fire with nothing left to deliver).
45+
Object.defineProperty(document, "readyState", { value: "interactive", configurable: true });
46+
47+
container.innerHTML = shell.replace(scriptRe, "");
48+
for (const m of shell.matchAll(scriptRe)) (0, eval)(m[1]);
49+
const hy = (globalThis as any)._$HY;
50+
// The shell's own pending data ref (the boundary's async memo), which the
51+
// cut drops from the registry before the fragment pass.
52+
const pendingData = Object.keys(hy.r).filter(
53+
k => !k.endsWith("_fr") && typeof hy.r[k]?.then === "function" && !hy.r[k].s
54+
);
55+
expect(pendingData.length).toBeGreaterThan(0);
56+
expect(hy.r[`${key}_fr`].s).toBeFalsy();
57+
58+
const dispose = hydrate(() => <scenario.App />, container);
59+
flush();
60+
61+
// Both passes ran at boot: the fragment is rejected and the dead data
62+
// refs are already out of the registry.
63+
const ref = hy.r[`${key}_fr`];
64+
expect(ref.s).toBe(2);
65+
expect(String(ref.v)).toContain("truncated");
66+
for (const k of pendingData) expect(k in hy.r).toBe(false);
67+
68+
await sleep(20);
69+
flush();
70+
await sleep(20);
71+
flush();
72+
73+
// The boundary released through the rejection path, hydration finished,
74+
// and the dead data refs stayed out of the registry so later reads compute
75+
// fresh.
76+
expect(hy.done).toBe(true);
77+
for (const k of pendingData) expect(k in hy.r).toBe(false);
78+
79+
warn.mockRestore();
80+
dispose();
81+
container.remove();
82+
delete (document as any).readyState;
83+
});

‎packages/web/test/hydration/truncated-stream.spec.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,9 @@ describe("stream truncated before a declared fragment settles (#2958)", () => {
6666
(globalThis as any)._$HY = { events: [], completed: new WeakSet(), r: {}, fe() {} };
6767
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
6868

69-
// The runtime boots while the document is still streaming — the only
70-
// window where the truncation sweep arms (a runtime loaded after parse
71-
// can't tell a completed page from a truncated one).
69+
// The runtime boots while the document is still streaming, so the sweep
70+
// waits for DOMContentLoaded (booting after parse is covered in
71+
// truncated-stream-late-start.spec.tsx).
7272
Object.defineProperty(document, "readyState", { value: "loading", configurable: true });
7373

7474
for (const s of applyChunk(container, shell, true)) (0, eval)(s);

0 commit comments

Comments
 (0)