Skip to content

Commit 590ff3a

Browse files
authored
Merge pull request #3507 from brenelz/fix/hydrating-root-snapshot-scope-3504
fix(solid,web): hydration-pass writes land as client renders (#3504)
2 parents f46ae70 + 17c0a3b commit 590ff3a

11 files changed

Lines changed: 347 additions & 6 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"solid-js": patch
3+
"@solidjs/web": patch
4+
---
5+
6+
A signal written from `onSettled` or `createEffect` during hydration no longer strands the DOM it reveals (#3504). Two halves: a root created while hydrating marks the hydration snapshot scope itself, so a write during the root pass is held until the pass completes and then replays — previously the scope was marked lazily by the first hydration-aware primitive, so a `<Show>` condition created before that sat outside it and the write cascaded mid-claim. And a streamed boundary's resume window now claims only the subtree under that boundary: a write from the resumed content that reaches a signal above it (a route's `onSettled` adding a toast to a provider) re-renders that already-hydrated region as a client render — fresh nodes, live inserts — instead of claiming against the server registry, missing with a "Hydration key miss" warning, and rendering detached.

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

Lines changed: 83 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import {
3737
type StoreSetter,
3838
type RevealOrder,
3939
createOwner,
40-
createRoot,
40+
createRoot as coreRoot,
4141
getContext,
4242
setContext,
4343
type Context
@@ -172,6 +172,18 @@ type SharedConfig = {
172172
* @internal
173173
*/
174174
onHydrationEnd?: (callback: () => void) => void;
175+
/**
176+
* Whether a render under the current owner is part of the claim in
177+
* progress. The root pass claims everything; a streamed boundary's resume
178+
* window claims only the subtree under that boundary. A write landing in
179+
* the window (the resumed content's `onSettled` reaching a signal above
180+
* the boundary, #3504) re-renders an already-hydrated region: that render
181+
* is a client render — fresh nodes, live inserts — not a claim against the
182+
* registry. Assigned by enableHydration(); absent means "claiming".
183+
*
184+
* @internal
185+
*/
186+
isClaiming?: () => boolean;
175187
};
176188

177189
/**
@@ -204,6 +216,19 @@ let _hydrationEndCallbacks: (() => void)[] | null = null;
204216
let _pendingBoundaries = 0;
205217
let _hydrationDone = false;
206218
let _snapshotRootOwner: Owner | null = null;
219+
// The boundary owner whose resume window is open (null during a root pass,
220+
// which claims everything). Reached as `sharedConfig.isClaiming`.
221+
let _claimOwner: Owner | null = null;
222+
223+
function isClaiming(): boolean {
224+
if (!_claimOwner) return true;
225+
let owner: Owner | null = getOwner();
226+
while (owner) {
227+
if (owner === _claimOwner) return true;
228+
owner = owner._parent;
229+
}
230+
return false;
231+
}
207232

208233
function markTopLevelSnapshotScope() {
209234
if (_snapshotRootOwner) return;
@@ -267,6 +292,7 @@ let _doneValue = false;
267292
// (no hydrate() import), the hydrated* functions and their dependencies
268293
// (MockPromise, subFetch) are eliminated by the bundler.
269294

295+
let _createRoot: Function | undefined;
270296
let _createMemo: Function | undefined;
271297
let _createSignal: Function | undefined;
272298
let _createErrorBoundary: Function | undefined;
@@ -899,7 +925,7 @@ export function materializeContainerTrace(marker: {
899925
// below): materialization runs at arg-read inside a reader's render
900926
// scope, and a version signal owned by that reader would be disposed by
901927
// its re-render while the memoized store lives on.
902-
return createRoot(() => {
928+
return coreRoot(() => {
903929
const [version, setVersion] = coreSignal(0);
904930
// Subscribe before creating the projection: the buffered replay runs
905931
// synchronously inside on(), filling the queue the first compute
@@ -958,7 +984,7 @@ export function materializeContainerTrace(marker: {
958984
// surfaces as an unhandled error in dev. The root is never disposed —
959985
// the projection settles itself when the trace ends and is collected
960986
// with the store.
961-
return createRoot(() =>
987+
return coreRoot(() =>
962988
createProjection(
963989
(draft: any) => ({
964990
[Symbol.asyncIterator]() {
@@ -1168,6 +1194,29 @@ function hydrateStoreLike(coreFn: Function, fn: any, initialValue: any, options?
11681194
return hydrateStoreLikeFn(coreFn, fn, initialValue, options, options?.ssrSource);
11691195
}
11701196

1197+
// --- Hydration-aware root ---
1198+
1199+
// A hydrating root is the snapshot scope from its first child on. The scope
1200+
// used to be marked lazily, by the first hydration-aware primitive created
1201+
// under it — so a control-flow memo made before that (Show's condition, on
1202+
// the core createMemo) sat outside it, and a user-tier write during the
1203+
// hydration pass (onSettled, createEffect) cascaded through it live: the
1204+
// branch it revealed claimed fresh templates against the registry, missed,
1205+
// and rendered detached (#3504). Marking at the root makes the scope
1206+
// creation-order independent: every write during the pass is held and
1207+
// replays at release, once the claim pass is over.
1208+
function hydratedCreateRoot(init: Function, options?: { id?: string; transparent?: boolean }) {
1209+
return coreRoot(
1210+
sharedConfig.hydrating
1211+
? dispose => {
1212+
markTopLevelSnapshotScope();
1213+
return init(dispose);
1214+
}
1215+
: (init as any),
1216+
options
1217+
);
1218+
}
1219+
11711220
// --- Hydration-aware effect implementations ---
11721221

11731222
function hydratedEffect(coreFn: Function, compute: any, effectFn: any, options?: any) {
@@ -1271,6 +1320,7 @@ function lazyHydrationLookup<T>(
12711320
}
12721321

12731322
export function enableHydration() {
1323+
_createRoot = hydratedCreateRoot;
12741324
_createMemo = hydratedCreateMemo;
12751325
_createSignal = hydratedCreateSignal;
12761326
_createErrorBoundary = hydratedCreateErrorBoundary;
@@ -1292,6 +1342,7 @@ export function enableHydration() {
12921342
// the exact CSR behavior onHydrationEnd itself had.
12931343
sharedConfig.isHydrationInProgress = isHydrationInProgress;
12941344
sharedConfig.onHydrationEnd = onHydrationEnd;
1345+
sharedConfig.isClaiming = isClaiming;
12951346

12961347
// Take ownership of streamed-fragment reveals (see the fragment ledger).
12971348
// The header script creates `_$HY` before any module runs, so the hook is
@@ -1759,6 +1810,27 @@ export const createOptimisticStore: {
17591810
: (coreOptimisticStore as Function)(...args);
17601811
}) as any;
17611812

1813+
/**
1814+
* Creates a non-tracked owner scope that doesn't auto-dispose. Pass `id`
1815+
* to seed hydration ids for the tree it owns.
1816+
*
1817+
* ```ts
1818+
* const dispose = createRoot(dispose => {
1819+
* // ...
1820+
* return dispose;
1821+
* });
1822+
* ```
1823+
*
1824+
* **Hydration:** a root created during hydration marks itself as the
1825+
* snapshot scope, so writes landing during the hydration pass are held
1826+
* until the pass completes (the mark used to depend on which primitive
1827+
* ran first under it).
1828+
*
1829+
* @description https://docs.solidjs.com/reference/reactive-utilities/create-root
1830+
*/
1831+
export const createRoot: typeof coreRoot = ((...args: any[]) =>
1832+
(_createRoot || coreRoot)(...args)) as typeof coreRoot;
1833+
17621834
/**
17631835
* Creates a reactive computation that runs during the render phase as
17641836
* DOM elements are created and updated but not necessarily connected.
@@ -1886,6 +1958,7 @@ function resumeBoundaryHydration(
18861958
// synchronous resume window; without a capture the live globals apply.
18871959
const prevRegistry = sharedConfig.registry;
18881960
const prevGather = sharedConfig.gather;
1961+
const prevClaim = _claimOwner;
18891962
if (scope) {
18901963
sharedConfig.registry = scope.registry;
18911964
sharedConfig.gather = scope.gather;
@@ -1896,14 +1969,21 @@ function resumeBoundaryHydration(
18961969
if (shouldHydrate) {
18971970
markSnapshotScope(o);
18981971
_snapshotRootOwner = o;
1972+
// The window claims this boundary's subtree only: the rest of the
1973+
// tree hydrated in the root pass, and a re-render it takes during the
1974+
// window (a write from the resumed content's user effects) is a
1975+
// client render (#3504).
1976+
_claimOwner = o;
18991977
}
19001978
set();
19011979
flush();
19021980
if (shouldHydrate) _snapshotRootOwner = null;
19031981
_hydratingValue = false;
1982+
_claimOwner = prevClaim;
19041983
if (shouldHydrate) releaseSnapshotScope(o);
19051984
flush();
19061985
} finally {
1986+
_claimOwner = prevClaim;
19071987
if (scope) {
19081988
sharedConfig.registry = prevRegistry;
19091989
sharedConfig.gather = prevGather;

‎packages/solid/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ export {
55
affects,
66
createOwner,
77
createReaction,
8-
createRoot,
98
createTrackedEffect,
109
deep,
1110
flatten,
@@ -99,6 +98,7 @@ export type { ArrayElement, Element } from "./types.js";
9998
export {
10099
sharedConfig,
101100
enableHydration,
101+
createRoot,
102102
createErrorBoundary,
103103
createLoadingBoundary,
104104
createRevealOrder,
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/**
2+
* @vitest-environment jsdom
3+
*
4+
* #3504: a user-tier effect (onSettled / createEffect) fires during the
5+
* hydration pass and writes a signal read by a control-flow memo created on
6+
* the core `createMemo` (the way <Show> builds its condition). Nothing
7+
* hydration-aware ran under the root before that memo, so the lazily marked
8+
* snapshot scope did not cover it and the write cascaded live, mid-claim.
9+
* A root created while hydrating now marks the scope itself: the write is
10+
* held until hydration ends, then replays.
11+
*/
12+
import { describe, expect, test, afterEach } from "vitest";
13+
import { flush, onSettled, createMemo as coreMemo } from "@solidjs/signals";
14+
import {
15+
enableHydration,
16+
sharedConfig,
17+
createRoot,
18+
createRenderEffect,
19+
createSignal,
20+
createEffect
21+
} from "../src/client/hydration.js";
22+
23+
enableHydration();
24+
25+
function startHydration() {
26+
sharedConfig.hydrating = true;
27+
(sharedConfig as any).has = () => false;
28+
(sharedConfig as any).load = () => undefined;
29+
(sharedConfig as any).gather = () => {};
30+
}
31+
32+
function stopHydration() {
33+
sharedConfig.hydrating = false;
34+
(sharedConfig as any).has = undefined;
35+
(sharedConfig as any).load = undefined;
36+
(sharedConfig as any).gather = undefined;
37+
}
38+
39+
// A hydrating root whose only derived node is a core memo (no hydration-aware
40+
// primitive marks the scope), with `write` fired from the user tier.
41+
function mount(write: (set: () => void) => void) {
42+
const seen: number[] = [];
43+
createRoot(
44+
() => {
45+
const [toasts, setToasts] = createSignal<string[]>([]);
46+
const cond = coreMemo(() => toasts().length);
47+
createRenderEffect(
48+
() => cond(),
49+
v => {
50+
seen.push(v);
51+
}
52+
);
53+
write(() => setToasts(p => ["t", ...p]));
54+
},
55+
{ id: "t" }
56+
);
57+
return seen;
58+
}
59+
60+
describe("#3504 hydrating root marks the snapshot scope before its first child", () => {
61+
afterEach(() => stopHydration());
62+
63+
test("onSettled write during the hydration pass is held until release", () => {
64+
startHydration();
65+
const seen = mount(set => {
66+
onSettled(() => {
67+
set();
68+
});
69+
});
70+
flush();
71+
// Held: the claim pass sees the server-rendered state only.
72+
expect(seen).toEqual([0]);
73+
stopHydration();
74+
flush();
75+
// Replayed once the pass is over.
76+
expect(seen).toEqual([0, 1]);
77+
});
78+
79+
test("createEffect write during the hydration pass is held until release", () => {
80+
startHydration();
81+
const seen = mount(set => {
82+
createEffect(
83+
() => 1,
84+
() => {
85+
set();
86+
}
87+
);
88+
});
89+
flush();
90+
expect(seen).toEqual([0]);
91+
stopHydration();
92+
flush();
93+
expect(seen).toEqual([0, 1]);
94+
});
95+
96+
test("outside hydration the root is a plain root: the write applies in the same flush", () => {
97+
const seen = mount(set => {
98+
onSettled(() => {
99+
set();
100+
});
101+
});
102+
flush();
103+
expect(seen).toEqual([0, 1]);
104+
});
105+
});

‎packages/web/src/client.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2327,6 +2327,12 @@ export function runHydrationEvents() {
23272327
// Internal Functions
23282328
function isHydrating(node) {
23292329
if (!sharedConfig.hydrating) return false;
2330+
// A streamed boundary's resume window claims only the subtree under that
2331+
// boundary; the rest of the page hydrated in the root pass. A render the
2332+
// window forces outside it — the resumed content's onSettled writing a
2333+
// signal above the boundary, revealing a <Show> there (#3504) — is a
2334+
// client render: fresh nodes, live inserts, no registry lookup.
2335+
if (sharedConfig.isClaiming && !sharedConfig.isClaiming()) return false;
23302336
if (!node || node.isConnected) return true;
23312337
// Connectivity tells claimed SSR nodes apart from fresh template clones,
23322338
// but a claimed tree isn't always IN the document: a frame adoption whose
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"name": "effect-write-show",
3+
"shell": "<main _hk=31>Hello</main>",
4+
"rest": ""
5+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"name": "onsettled-write-show-loading",
3+
"shell": "<main _hk=30001>Hello</main>",
4+
"rest": ""
5+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"name": "onsettled-write-show-streamed",
3+
"shell": "<template id=\"pl-30\"></template><main _hk=300>Loading…</main><!--pl-30--><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"$B\"]=($R[0]={30000:$R[1]=($R[2]=($R[3]=() => {\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,\"30_fr\":$R[4]=($R[5]=$R[3]()).p});(b=>{for(var k in b)_$HY.r[k]=b[k];delete _$HY.r[\"$B\"]})(_$HY.r[\"$B\"]);</script>",
4+
"rest": "<template id=\"30\"><main _hk=30002>Hello</main></template><script>($R[6]=(resolver, data) => {\n\tresolver.s(data);\n\tresolver.p.s = 1;\n\tresolver.p.v = data;\n})($R[2],\"Hello\");$df(\"30\");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,o.replaceWith(n.content),n.remove(),(_$HY.v=_$HY.v||{})[e]=1,_$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])};</script><script>$R[6]($R[5],!0);</script>"
5+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"name": "onsettled-write-show",
3+
"shell": "<main _hk=31>Hello</main>",
4+
"rest": ""
5+
}

0 commit comments

Comments
 (0)