Skip to content

Commit 51ba519

Browse files
committed
fix(solid): a truncated fragment's fresh render computes what the server never sent
When a stream is cut before a <Loading> fragment settles, the boundary renders the fragment fresh and adopts the server's records by id (#4319). The truncation sweep removed the records that can no longer settle from the registry only a macrotask after DOMContentLoaded, while the fresh render runs in the microtasks right after it. The render found those records, adopted their pending promises and waited on them forever: the boundary kept its fallback and its async reads never ran. At DOMContentLoaded the sweep now deletes those records first, before any fragment is marked truncated, so the fresh render computes them. Values and errors the server sent before the cut are still adopted. Refs a keyed consumer already took are still rejected a macrotask later, as before.
1 parent 81a12d8 commit 51ba519

6 files changed

Lines changed: 271 additions & 30 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 `<Loading>` whose fragment was cut off by a truncated stream renders fresh on the client and adopts the records the server sent. The records the stream never settled were still in the registry at that point, so the fresh render adopted their promises, which never settle: the boundary stayed on its fallback and its reads never ran. Truncation now removes those records before any boundary resumes. Reads the server never answered compute on the client, and the values and errors it sent before the cut are still adopted.

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

Lines changed: 42 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2656,6 +2656,10 @@ function watchTruncation(hy: any) {
26562656
"DOMContentLoaded",
26572657
() => {
26582658
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);
26592663
for (const key in hy.r) {
26602664
if (key.length <= 3 || !key.endsWith("_fr")) continue;
26612665
const ref = hy.r[key];
@@ -2664,13 +2668,13 @@ function watchTruncation(hy: any) {
26642668
// A macrotask later, on purpose: the fragment rejections above release
26652669
// their boundaries through microtask chains (abort race -> resume ->
26662670
// fresh render), and that teardown disposes the computations that
2667-
// adopted pending owner-id refs while hydrating. Rejecting those refs
2671+
// adopted pending owner-id refs while hydrating. Rejecting refs
26682672
// synchronously would race the disposal and land an unhandled error in
26692673
// a still-live computation, halting the reactive system. After the
2670-
// boundaries have released, whoever still holds a pending ref (keyed
2671-
// consumers like the router's query channel, boundaries waiting on a
2672-
// sync-serialized data ref) is exactly who needs the rejection.
2673-
setTimeout(() => rejectTruncatedRefs(hy));
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));
26742678
},
26752679
{ once: true }
26762680
);
@@ -2686,28 +2690,31 @@ function watchTruncation(hy: any) {
26862690
// arrays for scoped renders) is dead. What each one needs depends on who is
26872691
// left holding its promise:
26882692
//
2693+
// - A ref STILL in the registry either was adopted by a live reactive
2694+
// computation (owner-id channel — never deleted) or awaits a late reader,
2695+
// a cut fragment's fresh render among them. Rejecting those promises raw
2696+
// lands an unhandled error inside live computations (no boundary routes
2697+
// it — the fragment pass already released the boundaries) and halts the
2698+
// reactive system. Deleting the entry instead makes every future presence
2699+
// check (`sharedConfig.has`) fall through to a fresh compute/fetch —
2700+
// recovery, not failure — while already-adopted computations keep their
2701+
// pre-existing stall until their sources re-run. A delete notifies no
2702+
// one, so it runs at the cut itself (dropTruncatedRefs), before the
2703+
// fragment pass resumes any boundary: a fresh render that read the entry
2704+
// first would adopt the dead promise and never ask.
26892705
// - A ref GONE from the registry was consumed one-shot by a keyed consumer
26902706
// (the router deletes `_$HY.r[key]` on load) — that consumer holds the
26912707
// bare promise and hangs permanently unless it actually rejects, and its
2692-
// `.then` chain is built for rejections. Reject through the resolver.
2693-
// Walking the resolvers rather than the registry keys is what reaches
2694-
// these at all.
2695-
// - A ref STILL in the registry either was adopted by a live reactive
2696-
// computation (owner-id channel — never deleted) or awaits a late reader.
2697-
// Rejecting those promises raw lands an unhandled error inside live
2698-
// computations (no boundary routes it — the fragment pass already
2699-
// released the boundaries) and halts the reactive system. Deleting the
2700-
// entry instead makes every future presence check (`sharedConfig.has`)
2701-
// fall through to a fresh compute/fetch — recovery, not failure — while
2702-
// already-adopted computations keep their pre-existing stall until their
2703-
// sources re-run.
2708+
// `.then` chain is built for rejections. Reject through the resolver, a
2709+
// macrotask later (rejectTruncatedRefs). Walking the resolvers rather
2710+
// than the registry keys is what reaches these at all.
27042711
//
27052712
// Settled promises carry the status stamp (`.s`) the settle helpers write,
2706-
// and the fragment pass stamps rejected `_fr` declarations before this
2707-
// runs, so both are skipped.
2708-
function rejectTruncatedRefs(hy: any) {
2713+
// so they are skipped. The `_fr` declarations are the fragment pass's.
2714+
function dropTruncatedRefs(hy: any): any[] {
2715+
const consumed: any[] = [];
27092716
const R = (globalThis as any).$R;
2710-
if (!R || typeof R !== "object") return;
2717+
if (!R || typeof R !== "object") return consumed;
27112718
let registryKeys: Map<any, string> | undefined;
27122719
const sweep = (entry: any) => {
27132720
if (
@@ -2724,10 +2731,20 @@ function rejectTruncatedRefs(hy: any) {
27242731
for (const key in hy.r) registryKeys.set(hy.r[key], key);
27252732
}
27262733
const key = registryKeys.get(entry.p);
2727-
if (key !== undefined) {
2728-
delete hy.r[key];
2729-
return;
2730-
}
2734+
if (key === undefined) consumed.push(entry);
2735+
else if (!key.endsWith("_fr")) delete hy.r[key];
2736+
};
2737+
for (const key in R) {
2738+
const value = R[key];
2739+
if (Array.isArray(value)) for (const entry of value) sweep(entry);
2740+
else sweep(value);
2741+
}
2742+
return consumed;
2743+
}
2744+
2745+
function rejectTruncatedRefs(consumed: any[]) {
2746+
for (const entry of consumed) {
2747+
if (entry.p.s) continue;
27312748
const err = new Error("Hydration value was truncated: the stream ended before it settled.");
27322749
// Mirror seroval's failure helper: reject through the resolver and stamp
27332750
// the promise's status for status-based readers.
@@ -2737,11 +2754,6 @@ function rejectTruncatedRefs(hy: any) {
27372754
// Guard the harness itself against an unhandled-rejection report; the
27382755
// consumer observes the rejection through its own chain.
27392756
entry.p.then(undefined, noop);
2740-
};
2741-
for (const key in R) {
2742-
const value = R[key];
2743-
if (Array.isArray(value)) for (const entry of value) sweep(entry);
2744-
else sweep(value);
27452757
}
27462758
}
27472759

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"shell": "<main _hk=0><!--$--><template id=\"pl-1\"></template>[A]<!--pl-1--><!--/--><!--$--><template id=\"pl-2\"></template>[B]<!--pl-2--><!--/--><!--$--><template id=\"pl-3\"></template>[C]<!--pl-3--><!--/--></main><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"1_fr\"]=$R[0]=($R[1]=($R[2]=() => {\n\tconst resolver = {\n\t\tp: 0,\n\t\ts: 0,\n\t\tf: 0\n\t};\n\tresolver.p = new Promise((resolve, reject) => {\n\t\tresolver.s = resolve;\n\t\tresolver.f = reject;\n\t});\n\treturn resolver;\n})()).p;_$HY.r[\"1000\"]=$R[3]=($R[4]=$R[2]()).p;_$HY.r[\"2_fr\"]=$R[5]=($R[6]=$R[2]()).p;_$HY.r[\"2000\"]=$R[7]=($R[8]=$R[2]()).p;_$HY.r[\"2003\"]=$R[9]=($R[10]=$R[2]()).p;_$HY.r[\"3_fr\"]=$R[11]=($R[12]=$R[2]()).p;_$HY.r[\"3002\"]=$R[13]=($R[14]=$R[2]()).p;_$HY.r[\"300000\"]=$R[15]=($R[16]=$R[2]()).p;</script>",
3+
"chunks": [
4+
"<script>($R[17]=(resolver, data) => {\n\tresolver.s(data);\n\tresolver.p.s = 1;\n\tresolver.p.v = data;\n})($R[8],\"b:fast\");</script><script>($R[19]=(resolver, data) => {\n\tresolver.f(data);\n\tresolver.p.s = 2;\n\tresolver.p.v = data;\n})($R[16],$R[18]=new Error(\"c:bad failed\"));_$HY.r[\"3000\"]=$R[18];</script>",
5+
"<template id=\"1\"><span _hk=1001>a:slow</span></template><script>$R[17]($R[4],\"a:slow\");$df(\"1\");function $df(e){return _$HY.f?_$HY.f(e):$dfr(e)}function $dfr(e,n,o,t){if(!(n=document.getElementById(e)))return 0;if(!(o=document.getElementById(\"pl-\"+e)))return(_$HY.dq=_$HY.dq||{})[e]=1,0;for(;o&&(8!==o.nodeType||o.nodeValue!==\"pl-\"+e);)t=o.nextSibling,o.remove(),o=t;t=o.parentNode,(_$HY.v=_$HY.v||{})[e]=n.hasAttribute(\"e\")?[...n.content.childNodes]:1,o.replaceWith(n.content),n.remove(),_$HY.fe(e,t),_$HY.hp&&_$HY.hp[e]&&($dh(_$HY.hp[e]),delete _$HY.hp[e]),$dfd();return 1}function $dfl(e,o,n){if(!(o=document.getElementById(\"pl-\"+e)))return(_$HY.dlq=_$HY.dlq||{})[e]=1,0;if(o._$fl)return 1;for(n=o.nextSibling;n;){if(8===n.nodeType&&n.nodeValue===\"pl-\"+e){o.parentNode&&o.parentNode.insertBefore(o.content.cloneNode(!0),n),o._$fl=1,$dfd();return 1}n=n.nextSibling}return 0}function $dflj(e,i){for(i=0;i<e.length;i++)$dfl(e[i])}function $dfd(e,i){if(e=_$HY.dq){_$HY.dq=0;for(i in e)$df(i)}if(e=_$HY.dlq){_$HY.dlq=0;for(i in e)$dfl(i)}}function $dfs(e,c,d){(_$HY.sc=_$HY.sc||{})[e]=c,d&&((_$HY.sd=_$HY.sd||{})[e]=1)}function $dfg(e,g,i,k){if(!(g=_$HY.sg&&_$HY.sg[e]))return;for(i=0;i<g.length;i++)if(_$HY.sc&&_$HY.sc[g[i]]>0)return;for(i=0;i<g.length;i++)k=g[i],delete _$HY.sg[k],$df(k)}function $dfc(e){if(--_$HY.sc[e]<=0){delete _$HY.sc[e],_$HY.sg&&_$HY.sg[e]?$dfg(e):!(_$HY.sd&&_$HY.sd[e])&&$df(e);_$HY.sd&&delete _$HY.sd[e]}}function $dfj(e,i,n){for(i=0;i<e.length;i++)if(_$HY.sc&&_$HY.sc[e[i]]>0){for(n=0;n<e.length;n++)(_$HY.sg=_$HY.sg||{})[e[n]]=e;return}for(i=0;i<e.length;i++)$df(e[i])}function $dfe(e,t,k){(t=e.target)&&t.getAttribute&&!t._$dc&&(k=t.getAttribute(\"data-dfc\"))&&(t._$dc=1,$dfc(k))}document.addEventListener(\"load\",$dfe,!0);document.addEventListener(\"error\",$dfe,!0);</script><script>$R[17]($R[1],!0);</script><template id=\"2\"><span _hk=2001>b:fast</span><span _hk=2004>b:slow</span></template><script>$R[17]($R[10],\"b:slow\");$df(\"2\");</script><script>$R[17]($R[6],!0);</script>",
6+
"<template id=\"3\"><b _hk=30010>c:bad failed</b><span _hk=3003>c:slow</span></template><script>$R[17]($R[14],\"c:slow\");$df(\"3\");</script><script>$R[17]($R[12],!0);</script>"
7+
]
8+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*
4+
* Three <Loading> boundaries whose content creates its own async reads, so
5+
* the shell carries each read's record still pending. The chunk at 5 ms
6+
* settles two of them: `b:fast` with its value, and `c:bad` with the
7+
* server's error, which an <Errored> inside C's content catches. The
8+
* fragments land at 40 ms, with the slow reads.
9+
*
10+
* Ending the document after that first chunk is a truncated stream: each
11+
* boundary's fragment is cut, and the client renders it fresh. The fresh
12+
* render adopts what the server sent (`b:fast`'s value, `c:bad`'s error)
13+
* and computes the reads the server never answered (the three slow ones).
14+
*
15+
* Compiled with both generates: test/server/truncated-fragment-fresh-render.gen.spec.tsx
16+
* writes the chunks test/hydration/truncated-fragment-fresh-render.spec.tsx replays.
17+
*/
18+
import { createMemo, Errored, Loading } from "solid-js";
19+
import { isServer } from "@solidjs/web";
20+
21+
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
22+
const RealPromise = Promise;
23+
24+
export function createTruncatedFragmentApp() {
25+
const asks: string[] = [];
26+
// A node adopting its record still runs its compute once, to track its
27+
// sources, under a mocked Promise: only a real ask counts.
28+
const ask = (name: string, ms: number) => {
29+
if (!isServer && Promise === RealPromise) asks.push(name);
30+
return sleep(ms).then(() => {
31+
if (isServer && name === "c:bad") throw new Error("c:bad failed");
32+
return name;
33+
});
34+
};
35+
function Read(props: { name: string; ms: number }) {
36+
const value = createMemo(() => ask(props.name, props.ms));
37+
return <span>{value()}</span>;
38+
}
39+
function App() {
40+
return (
41+
<main>
42+
<Loading fallback="[A]">
43+
<Read name="a:slow" ms={40} />
44+
</Loading>
45+
<Loading fallback="[B]">
46+
<Read name="b:fast" ms={5} />
47+
<Read name="b:slow" ms={40} />
48+
</Loading>
49+
<Loading fallback="[C]">
50+
<Errored fallback={(e: any) => <b>{e().message}</b>}>
51+
<Read name="c:bad" ms={5} />
52+
</Errored>
53+
<Read name="c:slow" ms={40} />
54+
</Loading>
55+
</main>
56+
);
57+
}
58+
return { App, asks: () => asks };
59+
}
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
* @vitest-environment jsdom
4+
*
5+
* A stream cut before its fragments settle (#2958), where each boundary's
6+
* content creates its own async reads, so the shell carries their records
7+
* still pending. Each cut fragment renders fresh on the client and adopts
8+
* what the server sent by id (#4319): `b:fast`'s value, and `c:bad`'s error
9+
* for the <Errored> in C's content. The reads the server never answered
10+
* compute: the cut drops their records from the registry before the fresh
11+
* render reads it, so each slow read asks once and its boundary shows the
12+
* client's value. The records used to be dropped a macrotask after the
13+
* fresh render had already adopted their promises, which never settle: the
14+
* boundaries stayed on their fallbacks and nothing was asked.
15+
*
16+
* The complete stream runs first: the ledger's truncation record is module
17+
* state, and a boundary id it marks stays marked for the rest of the file.
18+
*
19+
* Replays the chunks test/server/truncated-fragment-fresh-render.gen.spec.tsx renders.
20+
*/
21+
import { afterEach, describe, expect, test, vi } from "vitest";
22+
import { readFileSync } from "node:fs";
23+
import { dirname, resolve } from "node:path";
24+
import { fileURLToPath } from "node:url";
25+
import { flush } from "solid-js";
26+
import { hydrate } from "@solidjs/web";
27+
import { createTruncatedFragmentApp } from "../harness/truncated-fragment-fresh-render.jsx";
28+
import { bootstrapHydrationGlobal } from "../harness/hydration-bootstrap.js";
29+
30+
const { shell, chunks } = JSON.parse(
31+
readFileSync(
32+
resolve(
33+
dirname(fileURLToPath(import.meta.url)),
34+
"../harness/__artifacts__/truncated-fragment-fresh-render.json"
35+
),
36+
"utf-8"
37+
)
38+
) as { shell: string; chunks: string[] };
39+
40+
const SERVER_TEXT = "a:slowb:fastb:slowc:bad failedc:slow";
41+
42+
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
43+
async function settle() {
44+
for (let i = 0; i < 4; i++) {
45+
await sleep(15);
46+
flush();
47+
}
48+
}
49+
50+
function applyChunk(container: HTMLElement, chunk: string, first: boolean) {
51+
const scriptRe = /<script(?:[^>]*)>([\s\S]*?)<\/script>/g;
52+
const scripts = [...chunk.matchAll(scriptRe)].map(m => m[1]);
53+
const stripped = chunk.replace(scriptRe, "");
54+
if (first) container.innerHTML = stripped;
55+
else container.insertAdjacentHTML("beforeend", stripped);
56+
for (const s of scripts) (0, eval)(s);
57+
}
58+
59+
// The parser finishing: the document transport's close.
60+
function endDocument() {
61+
Object.defineProperty(document, "readyState", { value: "interactive", configurable: true });
62+
document.dispatchEvent(new Event("DOMContentLoaded"));
63+
}
64+
65+
type Page = { container: HTMLElement; asks: () => string[]; hy: any; start: () => void };
66+
67+
async function withPage(body: (page: Page) => Promise<void>) {
68+
const hy = bootstrapHydrationGlobal();
69+
delete (globalThis as any).$R;
70+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
71+
const error = vi.spyOn(console, "error").mockImplementation(() => {});
72+
const container = document.createElement("div");
73+
document.body.appendChild(container);
74+
// The runtime boots while the document is still streaming: the only
75+
// window where the truncation sweep arms.
76+
Object.defineProperty(document, "readyState", { value: "loading", configurable: true });
77+
const { App, asks } = createTruncatedFragmentApp();
78+
let dispose: (() => void) | undefined;
79+
try {
80+
applyChunk(container, shell, true);
81+
// `body` replays what it needs, then starts hydration.
82+
await body({ container, asks, hy, start: () => (dispose = hydrate(() => <App />, container)) });
83+
const diagnostics = [...warn.mock.calls, ...error.mock.calls].map(c => String(c[0]));
84+
expect(diagnostics).toEqual([]);
85+
} finally {
86+
dispose?.();
87+
container.remove();
88+
warn.mockRestore();
89+
error.mockRestore();
90+
delete (document as any).readyState;
91+
}
92+
}
93+
94+
afterEach(async () => {
95+
await sleep(0);
96+
delete (globalThis as any)._$HY;
97+
});
98+
99+
describe("a fragment's fresh render after a truncated stream", () => {
100+
test("complete stream: every read claims the server's answer, nothing is asked", () =>
101+
withPage(async page => {
102+
page.start();
103+
await settle();
104+
expect(page.container.textContent).toBe("[A][B][C]");
105+
for (const chunk of chunks) {
106+
applyChunk(page.container, chunk, false);
107+
await settle();
108+
}
109+
endDocument();
110+
await settle();
111+
expect(page.container.textContent).toBe(SERVER_TEXT);
112+
expect(page.asks()).toEqual([]);
113+
expect(page.hy.done).toBe(true);
114+
}));
115+
116+
test("cut after the first chunk: what the server sent is adopted, the rest computes", () =>
117+
withPage(async page => {
118+
applyChunk(page.container, chunks[0], false);
119+
page.start();
120+
await settle();
121+
expect(page.container.textContent).toBe("[A][B][C]");
122+
expect(page.asks()).toEqual([]);
123+
124+
endDocument();
125+
await settle();
126+
await settle();
127+
128+
// Each slow read asks once; `b:fast` and `c:bad` are not asked again.
129+
expect(page.asks()).toEqual(["a:slow", "b:slow", "c:slow"]);
130+
// The served value and the served error, beside the client's values.
131+
expect(page.container.textContent).toBe(SERVER_TEXT);
132+
expect(page.hy.done).toBe(true);
133+
}));
134+
});
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*
4+
* Server half of test/hydration/truncated-fragment-fresh-render.spec.tsx:
5+
* renders the fixture and writes its shell plus each later chunk.
6+
*/
7+
import { expect, test } from "vitest";
8+
import { createTruncatedFragmentApp } from "../harness/truncated-fragment-fresh-render.jsx";
9+
import { recordStream, writeArtifact } from "./artifact-recorder.js";
10+
11+
test("render truncated-fragment-fresh-render chunks", async () => {
12+
const { App } = createTruncatedFragmentApp();
13+
const { shell, chunks } = await recordStream(() => <App />);
14+
expect(shell.replace(/<[^>]*>/g, "")).toContain("[A][B][C]");
15+
// The cut lands after the first chunk: it settles `b:fast` and `c:bad`
16+
// and swaps no fragment in. Every fragment swaps in a later chunk.
17+
const [first, ...later] = chunks;
18+
expect(first).toContain('"b:fast"');
19+
expect(first).toContain("c:bad failed");
20+
expect(first).not.toContain("$df(");
21+
for (const id of ["1", "2", "3"]) expect(later.join("")).toContain(`$df("${id}")`);
22+
writeArtifact("truncated-fragment-fresh-render", { shell, chunks });
23+
});

0 commit comments

Comments
 (0)