Skip to content

Commit b6a90f9

Browse files
fix(ssr): lazy() module loads hold the shell; dynamic() gains deferStream (#3299)
A lazy module load is code, not data: the shell's "no new async discovered during the sync render" rule cannot be evaluated for a segment whose code has not run, so a deferStream read inside a code-split route was created after the shell shipped and silently ignored. lazy() now blocks the shell on its module promise (and asset registration) even under a boundary, while still suspending into that boundary so the data the loaded code discovers streams as before. Only the first render per process to reach an un-preloaded chunk pays; a lazy mounted post-shell streams. The flush loop also re-awaits blockers registered while a boundary resumed during the drain: allSettled now reports the size it awaited and doShell / the thenable gate compare against that snapshot, closing the microtask gap where a warm import's deferStream landed after the check but before the attempt. dynamic() keeps streaming its source by default and gains { deferStream } to opt in, applied at the instance (dynamic() is routinely hoisted with no render context). Re-pins the July gating specs to the new contract. Co-authored-by: Cursor <[email protected]>
1 parent 6e7c42b commit b6a90f9

8 files changed

Lines changed: 345 additions & 64 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
"solid-js": patch
3+
"@solidjs/web": patch
4+
---
5+
6+
Fix `deferStream` being a silent no-op inside a code-split `lazy()` component (#3299). A module load is code, not data: the shell's "no new async discovered during the sync render" rule cannot be evaluated for a segment whose code has not run, so the shell now waits for the chunk even under a `<Loading>` (the boundary still owns the data the loaded code discovers — plain async streams behind the fallback as before, and a `deferStream` read inside the chunk holds the shell exactly like one in an eagerly imported component). Only the first render that reaches an un-preloaded chunk pays; a lazy mounted by a post-shell fragment streams as before.
7+
8+
Also closes a gap in the flush loop where a shell blocker registered while a boundary resumed during the drain — after the awaited set had settled but before the flush attempt snapshotted it — was never re-awaited.
9+
10+
`dynamic()` keeps streaming its source by default (a source is data of unknown cost) and gains a `deferStream` option to opt into holding the shell on it, with the same meaning as `createMemo`'s.

‎documentation/solid-2.0/03-control-flow.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,12 @@ The `<Dynamic component={...}>` JSX wrapper from 1.x still exists and is unchang
169169

170170
`source` may return a `Promise<Component | string | undefined>`. The factory composes with `Loading` / `Errored` through the normal `NotReadyError` flow — no separate suspense primitive or user-side `await`.
171171

172+
Under SSR a pending source streams in behind its boundary by default — a source is data of unknown cost (a server component call, say). Pass `{ deferStream: true }` to hold the document's first flush until it settles, the same option `createMemo` takes ([RFC 05](05-async-data.md)); the client ignores it. This is the one place `dynamic` and `lazy` differ: a `lazy()` module load is code, not data, and always holds the shell — the shell cannot decide it has discovered all async until the segment's code has run — while the boundary still owns whatever async that code then discovers.
173+
174+
```jsx
175+
const Page = dynamic(() => loadPageComponent(params.id), { deferStream: true });
176+
```
177+
172178
#### Notes
173179

174180
- The source evaluation is shared across all mounted instances of the returned component, so using one `dynamic(...)` in many places doesn't duplicate work.

‎packages/solid/src/server/component.ts‎

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -320,17 +320,29 @@ export function lazy<T extends Component<any>>(
320320
assetsPending = assetsPending.then(clear, clear);
321321
}
322322
}
323-
// The module promise is deliberately NOT registered as a renderer-blocking
324-
// promise. Doing so gates the shell flush on the module load, so an
325-
// enclosing boundary never shows its fallback and a slow module stalls the
326-
// whole document. Suspending on read (below) lets the nearest boundary own
327-
// the wait and stream the module in behind its placeholder; with no
328-
// boundary to defer to the read becomes a root hole and the renderer
329-
// blocks the shell on it anyway.
330-
//
331-
// Asset ordering does not depend on this: `assetsPending` gates the render
332-
// memo separately, so a fragment still cannot flush before its styles and
333-
// module map are registered.
323+
// The module load is CODE, not data: the shell's "no new async discovered
324+
// during the sync render" rule cannot be evaluated for a segment whose
325+
// code has not run yet. So the shell waits for the chunk (and its asset
326+
// registration) even under a boundary — otherwise a `deferStream` read
327+
// inside a code-split route is created after the shell has shipped and is
328+
// silently a no-op (#3299). The render below still suspends into the
329+
// nearest boundary, which keeps owning the DATA the loaded code discovers:
330+
// plain async streams behind the fallback as before. Only the first render
331+
// that reaches an un-preloaded chunk pays (`p` is module-cached); a loaded
332+
// module is a no-op here, and `block` is a no-op once the shell has flushed,
333+
// so a lazy mounted by a post-shell fragment streams like any other content.
334+
// Rejections are swallowed on this branch — the render memo surfaces
335+
// `cur.error` to the nearest <Errored> and clearing the block is all the
336+
// shell needs.
337+
if (ctx?.async && ((cur.v === undefined && !cur.errored) || assetsPending)) {
338+
const gate = assetsPending ? cur.then(() => assetsPending) : cur;
339+
ctx.block(
340+
gate.then(
341+
() => {},
342+
() => {}
343+
)
344+
);
345+
}
334346
return createMemo(
335347
() => {
336348
if (cur.errored) throw cur.error;

‎packages/web/src/index.server.ts‎

Lines changed: 47 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -63,30 +63,69 @@ export type ComponentProps<T extends ValidComponent> =
6363
? JSX.IntrinsicElements[T]
6464
: Record<string, unknown>;
6565

66+
export interface DynamicOptions {
67+
/**
68+
* SSR only: hold the document's first flush until the source settles, so
69+
* the resolved component renders into the shell instead of streaming in
70+
* behind its boundary's fallback. Same meaning as `createMemo`'s
71+
* `deferStream`. Default `false` — a `dynamic()` source is data of unknown
72+
* cost and streams by default (a code-split `lazy()` always holds the shell
73+
* for its module load, since its code is a prerequisite to the render).
74+
*/
75+
deferStream?: boolean;
76+
}
77+
6678
export function dynamic<T extends ValidComponent>(
67-
source: () => T | Promise<T> | null | undefined | false
79+
source: () => T | Promise<T> | null | undefined | false,
80+
options?: DynamicOptions
6881
): Component<ComponentProps<T>> {
6982
// Mirrors the client exactly: a factory-level memo over the source, then a
7083
// per-instance memo that applies props. An async source needs no bespoke
7184
// handling — the (async-aware, non-`sync`) server memo suspends the read
7285
// while pending, and the nearest boundary owns it and streams.
7386
//
74-
// Notably the pending read must NOT be registered as a renderer-blocking
75-
// promise: that gates the shell flush on the source, so the boundary never
76-
// shows its fallback and a slow source stalls the whole document. With no
77-
// boundary to defer to the read becomes a root hole and resolveRootHoles
78-
// blocks the shell on it anyway — correct, since there is nothing else to
79-
// do.
87+
// By default the pending read is NOT a renderer-blocking promise: a source
88+
// is data of unknown cost (a server component call, say), and gating the
89+
// shell on it means the boundary never shows its fallback and a slow source
90+
// stalls the whole document. With no boundary to defer to the read becomes a
91+
// root hole and resolveRootHoles blocks the shell on it anyway. Unlike
92+
// lazy(), whose module load always holds the shell (code is a prerequisite
93+
// to knowing what the segment contains), dynamic() leaves that call to the
94+
// author: `deferStream` holds the shell on the source's settle, with the
95+
// same meaning it has on createMemo. It is applied at the INSTANCE, not on
96+
// the factory memo: dynamic() is routinely hoisted, so the factory runs with
97+
// no render context, and only the mount knows which document to hold.
8098
//
8199
// `serialize: false` because the resolved component must never cross the
82100
// wire (it isn't serializable, and the client re-runs `source()` during
83101
// hydration anyway, the same way lazy() re-imports its module). The owner
84102
// id is still allocated, so hydration keys stay aligned with the client.
85103
const cached = createMemo(source as () => any, { serialize: false } as any);
104+
const deferStream = !!options?.deferStream;
86105
return props => {
106+
// Client `solid-js` types don't expose the server `sharedConfig.context`.
107+
const ctx = (sharedConfig as { context?: any }).context;
108+
let gated = !deferStream || !ctx?.async;
87109
return createMemo(
88110
() => {
89-
const c: unknown = cached();
111+
let c: unknown;
112+
try {
113+
c = cached();
114+
} catch (err) {
115+
// Hold the shell on the source once per instance. A no-op after the
116+
// shell has flushed, like every blocker; a rejection is the memo's
117+
// to surface on the retry, the block only needs to clear.
118+
if (!gated && err instanceof NotReadyError) {
119+
gated = true;
120+
ctx.block(
121+
Promise.resolve(err.source).then(
122+
() => {},
123+
() => {}
124+
)
125+
);
126+
}
127+
throw err;
128+
}
90129
if (c) {
91130
if (typeof c === "function") return (c as Function)(props);
92131
if (typeof c === "string") {

‎packages/web/src/index.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,10 @@ function portalImpl(props: { mount?: Element; children: JSX.Element }): JSX.Elem
238238
* propagates as `NotReadyError` through the surrounding reactive scope, so
239239
* async swaps compose with `<Loading>` boundaries the same way as `lazy`.
240240
*
241+
* During SSR a pending source streams in behind its boundary by default. Pass
242+
* `{ deferStream: true }` to hold the document's first flush until it settles
243+
* (the same option `createMemo` takes); the client ignores it.
244+
*
241245
* @example
242246
* ```tsx
243247
* // `source` can return either a custom Component or a native tag
@@ -265,8 +269,19 @@ function bindingOf(value: any): { component: Function; address: string } | undef
265269
);
266270
}
267271

272+
export interface DynamicOptions {
273+
/**
274+
* SSR only: hold the document's first flush until the source settles, so
275+
* the resolved component renders into the shell instead of streaming in
276+
* behind its boundary's fallback. Same meaning as `createMemo`'s
277+
* `deferStream`. Ignored on the client.
278+
*/
279+
deferStream?: boolean;
280+
}
281+
268282
export function dynamic<T extends ValidComponent>(
269-
source: () => T | Promise<T> | null | undefined | false
283+
source: () => T | Promise<T> | null | undefined | false,
284+
_options?: DynamicOptions
270285
): Component<ComponentProps<T>> {
271286
// `prev` threads into the resolution so a source switching server-component
272287
// calls of the same function DELIVERS instead of swapping: the memo keeps

‎packages/web/src/server.ts‎

Lines changed: 38 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1764,6 +1764,10 @@ export function renderToStream(code, options = {}) {
17641764
};
17651765
const onDone = () => {
17661766
writeTasks();
1767+
// Every blocker has settled by definition here (the render is complete),
1768+
// so doShell's growth gate has nothing to wait for: align its baseline
1769+
// rather than let a stale flush-loop snapshot hold a finished shell.
1770+
lastBlockingSize = blockingPromises.size;
17671771
doShell();
17681772
onCompleteAll &&
17691773
onCompleteAll({
@@ -2313,18 +2317,20 @@ export function renderToStream(code, options = {}) {
23132317
// context. Restore this stream before re-pulling them so hydration data
23142318
// is serialized into the response that owns the rendered markup.
23152319
sharedConfig.context = context;
2316-
// A hole that completes by MOUNTING content can register new shell
2317-
// blockers as it renders: a deferStream read under a boundary created
2318-
// during this very re-invocation adds its source promise via
2319-
// serialize() (solidjs/solid#3047 — the code-split lazy route shape).
2320-
// This attempt already runs inside the previous allSettled snapshot's
2321-
// continuation, so flushing now would ship the fallback deferStream
2322-
// exists to prevent. Bail on growth; the flush loop re-awaits the grown
2323-
// set, and the boundary's pre-flush replace() splices the resolved
2324-
// content into the held shell before the retry flushes it.
2325-
const blockersBefore = blockingPromises.size;
2320+
// Content that MOUNTS after the awaited blockers settle can register new
2321+
// shell blockers as it renders: a deferStream read under a boundary that
2322+
// resumes during the drain (its lazy module just landed — the code-split
2323+
// route shape, solidjs/solid#3047, #3299) or under a root hole re-pulled
2324+
// below adds its source promise via serialize(). This attempt already runs
2325+
// inside the previous allSettled snapshot's continuation, so flushing now
2326+
// would ship the fallback deferStream exists to prevent. Bail on growth
2327+
// since that snapshot (`lastBlockingSize`, taken when the loop scheduled
2328+
// this attempt); the flush loop re-awaits the grown set, and the
2329+
// boundary's pre-flush replace() splices the resolved content into the
2330+
// held shell before the retry flushes it.
2331+
if (blockingPromises.size !== lastBlockingSize) return;
23262332
if (!resolveRootHoles()) return;
2327-
if (blockingPromises.size !== blockersBefore) return;
2333+
if (blockingPromises.size !== lastBlockingSize) return;
23282334
// Root-owned head registrations join the shell-hole contract: a pending
23292335
// prop blocks the shell on its source and this attempt bails; the flush
23302336
// loop re-awaits and retries (#2975 follow-up).
@@ -2385,10 +2391,14 @@ export function renderToStream(code, options = {}) {
23852391
// cost is nanoseconds — and keep extending while fragments are actually
23862392
// completing (registry churn), so nested settled boundaries drain fully.
23872393
const MIN_DRAIN_TURNS = 8;
2394+
// Size of the blocking set when the current attempt was scheduled — i.e.
2395+
// the snapshot the preceding allSettled awaited. doShell (and the thenable's
2396+
// gate) compare against it: anything added since was discovered during the
2397+
// drain and has NOT been awaited.
23882398
let lastBlockingSize = -1;
23892399
let lastRegistrySize = -1;
23902400
let drainTurn = 0;
2391-
const scheduleFlush = fn => {
2401+
const scheduleFlush = (fn, awaited) => {
23922402
const attempt = () => {
23932403
// Flush batched stubs at the TOP of the drain, not at doShell: a
23942404
// promise that already settled emits its fulfillment on a microtask
@@ -2406,8 +2416,8 @@ export function renderToStream(code, options = {}) {
24062416
}
24072417
fn();
24082418
};
2409-
const progressed = blockingPromises.size !== lastBlockingSize;
2410-
lastBlockingSize = blockingPromises.size;
2419+
const progressed = awaited !== lastBlockingSize;
2420+
lastBlockingSize = awaited;
24112421
lastRegistrySize = -1;
24122422
drainTurn = 0;
24132423
progressed ? queue(attempt) : setTimeout(attempt);
@@ -2429,7 +2439,7 @@ export function renderToStream(code, options = {}) {
24292439
let resolve;
24302440
const p = new Promise(r => (resolve = r));
24312441
function flush() {
2432-
allSettled(blockingPromises).then(() => {
2442+
allSettled(blockingPromises).then(awaited => {
24332443
scheduleFlush(() => {
24342444
if (dead) return resolve();
24352445
// Root-hole retries and shell assembly run inside this microtask —
@@ -2490,7 +2500,7 @@ export function renderToStream(code, options = {}) {
24902500
dispose();
24912501
writable.end();
24922502
} else flushEnd();
2493-
});
2503+
}, awaited);
24942504
});
24952505
}
24962506
flush();
@@ -2535,7 +2545,7 @@ export function renderToStream(code, options = {}) {
25352545
};
25362546
} else onCompleteAll = complete;
25372547
function flush() {
2538-
allSettled(blockingPromises).then(() => {
2548+
allSettled(blockingPromises).then(awaited => {
25392549
scheduleFlush(() => {
25402550
// Same gates as doShell: pending root head props are shell
25412551
// blockers, so flushEnd must not run ahead of them (their
@@ -2544,10 +2554,10 @@ export function renderToStream(code, options = {}) {
25442554
// new blockers (deferStream under a just-mounted boundary,
25452555
// solidjs/solid#3047) must be re-awaited before completion.
25462556
try {
2547-
const blockersBefore = blockingPromises.size;
25482557
if (
2558+
blockingPromises.size !== lastBlockingSize ||
25492559
!resolveRootHoles() ||
2550-
blockingPromises.size !== blockersBefore ||
2560+
blockingPromises.size !== lastBlockingSize ||
25512561
!headShellReady(headRegistry, p => blockingPromises.add(p))
25522562
)
25532563
return flush();
@@ -2563,7 +2573,7 @@ export function renderToStream(code, options = {}) {
25632573
return resolve(tmp);
25642574
}
25652575
queue(flushEnd);
2566-
});
2576+
}, awaited);
25672577
});
25682578
}
25692579
flush();
@@ -2573,7 +2583,7 @@ export function renderToStream(code, options = {}) {
25732583
pipe(w) {
25742584
claimConsumer("pipe");
25752585
function flush() {
2576-
allSettled(blockingPromises).then(() => {
2586+
allSettled(blockingPromises).then(awaited => {
25772587
scheduleFlush(() => {
25782588
if (dead) return;
25792589
try {
@@ -2599,7 +2609,7 @@ export function renderToStream(code, options = {}) {
25992609
dispose();
26002610
writable.end();
26012611
} else flushEnd();
2602-
});
2612+
}, awaited);
26032613
});
26042614
}
26052615
flush();
@@ -4071,11 +4081,16 @@ function queue(fn) {
40714081
// Node; timer fallback for hosts without it (workerd, browsers).
40724082
const deferFlush = typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
40734083

4084+
// Resolves with the size of the set it awaited. The caller snapshots THAT,
4085+
// not the size when its continuation runs: a blocker registered in the
4086+
// microtask between the growth check here and the caller's `.then` (a
4087+
// boundary resuming on the same settlement — its lazy module landed and the
4088+
// mounted content took a deferStream read) has not been awaited (#3299).
40744089
function allSettled(promises) {
40754090
let size = promises.size;
40764091
return Promise.allSettled(promises).then(() => {
40774092
if (promises.size !== size) return allSettled(promises);
4078-
return;
4093+
return size;
40794094
});
40804095
}
40814096

‎packages/web/test/server/dynamic-shell-gating.spec.tsx‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
* @jsxImportSource @solidjs/web
33
*/
44
// A promise-backed dynamic() must suspend on READ and let the nearest
5-
// <Loading> own the wait. It must not gate the shell flush on its source.
5+
// <Loading> own the wait. By default it must not gate the shell flush on its
6+
// source: unlike a lazy() module load (code — always held, see
7+
// lazy-shell-gating.spec.tsx) a dynamic() source is data of unknown cost, and
8+
// the author opts into holding the shell with `deferStream`.
69
//
710
// Found in the hackernews server-components example: a slow server component
811
// under a <Loading> pushed the whole document's first flush out by the full
@@ -11,6 +14,7 @@
1114
// waited on the slowest server function.
1215
import { describe, expect, test } from "vitest";
1316
import { renderToStream, Loading, dynamic } from "@solidjs/web";
17+
import { createMemo } from "solid-js";
1418

1519
const wait = (ms: number) => new Promise(r => setTimeout(r, ms));
1620

@@ -71,6 +75,48 @@ describe("promise-backed dynamic() under a boundary", () => {
7175
expect(html).not.toContain(">waiting…</span>");
7276
});
7377

78+
test("deferStream opts the source into holding the shell", async () => {
79+
const Slow = dynamic(() => wait(DELAY).then(() => () => <b>content</b>), {
80+
deferStream: true
81+
});
82+
83+
const { shell, shellAt, html } = await collectTimed(() => (
84+
<div>
85+
<Loading fallback={<span>waiting…</span>}>
86+
<Slow />
87+
</Loading>
88+
</div>
89+
));
90+
91+
expect(shellAt).toBeGreaterThanOrEqual(DELAY - 5);
92+
expect(shell).toContain(">content</b>");
93+
expect(html).not.toContain(">waiting…</span>");
94+
});
95+
96+
test("deferStream holds the shell for the source only; the resolved component's data still streams", async () => {
97+
const Slow = dynamic(
98+
() =>
99+
wait(50).then(() => () => {
100+
const data = createMemo(() => wait(DELAY).then(() => "data"));
101+
return <b>{data()}</b>;
102+
}),
103+
{ deferStream: true }
104+
);
105+
106+
const { shell, shellAt, html } = await collectTimed(() => (
107+
<div>
108+
<Loading fallback={<span>waiting…</span>}>
109+
<Slow />
110+
</Loading>
111+
</div>
112+
));
113+
114+
expect(shellAt).toBeGreaterThanOrEqual(45);
115+
expect(shellAt).toBeLessThan(DELAY);
116+
expect(shell).toContain(">waiting…</span>");
117+
expect(html).toContain(">data</b>");
118+
});
119+
74120
test("with no boundary to defer to, the shell still waits for the source", async () => {
75121
const Slow = dynamic(() => wait(DELAY).then(() => () => <b>content</b>));
76122

0 commit comments

Comments
 (0)