Skip to content

Commit 99ed6cf

Browse files
ryansolidClaude via Cursorcursoragent
committed
fix(query): don't cache never-settling promises from hydration tracking runs
A hydrating client re-runs each serialized compute once as a tracking run, with the global Promise and fetch swapped for stubs that never settle (solid's subFetch). The first query() read of a key usually lands there, and two paths cached one of those stubs: - Adoption (since #641) wrapped an already-settled flight entry with the global Promise.resolve/reject, so the cache held a stub. Navigations that reused it inside the preload window hung with isRouting() stuck. Adopted entries are now wrapped with Promise captured at module load. - f513771 stamps adopted entries at boot and lets reads with no navigation in flight adopt at any age, but the cache-hit check never got that rule. A boundary resuming more than PRELOAD_TIMEOUT after boot, after the first reader was disposed (count 0), saw the entry as stale, found the one-shot payload already taken, and ran fn() inside the tracking run. A read with no navigation in flight while hydrating (isHydrating()) now reuses the cached entry at any age. Navigations keep normal freshness. Tests: unit cases for both rules, plus an SSR-stream + hydration JSDOM harness (adapted from #636 by @everton-dgn) covering the round trip after adoption in a tracking run, a boundary resuming 6s after boot for fetch-chain and async query functions (no fn call, no requests), a mid-stream click past the window, and isHydrating() inside the late boundary's tracking run. Fixes solidjs/solid#3721. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 542d644 commit 99ed6cf

6 files changed

Lines changed: 639 additions & 7 deletions

File tree

‎.changeset/query-hydration-hang.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/router": patch
3+
---
4+
5+
Fix navigations hanging after hydration when a `query()` read ran inside Solid's hydration tracking run, where the global `Promise` and `fetch` are swapped for stubs that never settle (solidjs/solid#3721). Adopting a server value that had already settled wrapped it with that stubbed `Promise`, so the cache kept a promise that never settled. A boundary resuming more than 5s after boot treated the entry adopted at boot as stale and called the query function inside the tracking run, caching the same kind of promise. Adopted values are now wrapped with the native `Promise`, and a read with no navigation in flight while hydrating reuses the cached entry at any age, as adoption already did for server payloads. Navigations keep the normal freshness windows.

‎src/data/query.ts‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
getObserver,
44
getOwner,
55
isHydratable,
6+
isHydrating,
67
onCleanup,
78
untrack,
89
type Signal
@@ -57,6 +58,13 @@ const forwardedCookies = /* #__PURE__ */ new WeakMap<CacheEntry, WeakSet<Headers
5758
// hold values the server computed while rendering THIS page, so their age is
5859
// anchored here — not at whenever a late query() call happens to consume one.
5960
const bootTime = Date.now();
61+
// Captured at module load: a hydrating client runs a serialized node's
62+
// compute once as a dependency trace with the global `Promise` swapped for a
63+
// never-settling mock, and a query() read inside that trace still consumes
64+
// and caches its flight entry. Wrapped with the global there, a settled
65+
// entry would cache a promise that never resolves, hanging every navigation
66+
// that reuses it.
67+
const NativePromise = Promise;
6068

6169
// Every hydratable read ships its entry: the writer keeps the first write
6270
// per key, so a read skipped in a NoHydration zone never hides the entry
@@ -200,12 +208,19 @@ export function query<T extends (...args: any) => any>(fn: T, name: string): Cac
200208
onCleanup(() => cached[4].count--);
201209
}
202210

211+
// A read with no navigation in flight while hydrating is claiming server
212+
// DOM, so it takes the cached entry at any age — the rule adoption below
213+
// applies to flight entries. It can come from a boundary resuming long
214+
// after boot, once the entry was adopted and its first reader disposed;
215+
// refetching there would run inside Solid's hydration trace, where fetch
216+
// and Promise never settle, and cache that.
203217
if (
204218
cached &&
205219
cached[0] &&
206220
(isServer ||
207221
intent === "native" ||
208222
cached[4].count ||
223+
(!intent && isHydrating()) ||
209224
Date.now() - cached[0] < PRELOAD_TIMEOUT)
210225
) {
211226
if (tracking) {
@@ -249,8 +264,8 @@ export function query<T extends (...args: any) => any>(fn: T, name: string): Cac
249264
entry.status === "pending"
250265
? entry.promise
251266
: entry.status === "resolved"
252-
? Promise.resolve(entry.value)
253-
: Promise.reject(entry.error);
267+
? NativePromise.resolve(entry.value)
268+
: NativePromise.reject(entry.error);
254269
}
255270
// A payload too old for this intent stays in the registry: it is
256271
// inert while the refetched entry below lives, but a later claim
@@ -259,11 +274,10 @@ export function query<T extends (...args: any) => any>(fn: T, name: string): Cac
259274
if (!adopted) res = fn(...(args as any));
260275

261276
// Adopted entries are stamped at boot — when their data was actually
262-
// fetched — not at consumption. The hydration render burst still dedups
263-
// through the normal window/count reuse above (it happens within
264-
// milliseconds of boot), while a navigation that comes along later sees
265-
// the payload's true age and refetches past PRELOAD_TIMEOUT, exactly as
266-
// it would for a preload performed when the server fetched the data.
277+
// fetched — not at consumption. Later hydration reads still reuse them
278+
// through the claim rule above, while a navigation that comes along later
279+
// sees the payload's true age and refetches past PRELOAD_TIMEOUT, exactly
280+
// as it would for a preload performed when the server fetched the data.
267281
const stamp = adopted ? bootTime : now;
268282
if (cached) {
269283
isServer && forwardedCookies.delete(cached);

‎test/data/query-flight-consumption.spec.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ vi.mock("../../src/routing.js", () => ({
1616
getIntent: () => currentIntent,
1717
getInPreloadFn: () => false
1818
}));
19+
// Whether the read happens while Solid is hydrating (claiming server DOM).
20+
let hydrating = false;
21+
vi.mock("solid-js", async importOriginal => ({
22+
...(await importOriginal<typeof import("solid-js")>()),
23+
isHydrating: () => hydrating
24+
}));
1925

2026
const PRELOAD_TIMEOUT = 5000;
2127
const CACHE_TIMEOUT = 180000;
@@ -36,6 +42,7 @@ describe("query cache freshness windows", () => {
3642
beforeEach(() => {
3743
query.clear();
3844
currentIntent = undefined;
45+
hydrating = false;
3946
});
4047

4148
afterEach(() => {
@@ -232,6 +239,49 @@ describe("query cache freshness windows", () => {
232239
});
233240
});
234241

242+
test("a settled entry adopted inside a hydration trace still resolves for later reads (solid #3721)", async () => {
243+
return createRoot(async () => {
244+
// The registry as the page leaves it once the entry's settlement
245+
// streamed in: the revived promise stamped resolved.
246+
const revived = Object.assign(Promise.resolve("server-data"), { s: 1, v: "server-data" });
247+
(globalThis as any)._$HY = { r: { "tracedAdoption[]": revived } };
248+
let callCount = 0;
249+
const cachedFn = query(async () => {
250+
callCount++;
251+
return "fresh-data";
252+
}, "tracedAdoption");
253+
254+
// Solid's hydration trace: the compute runs once with the global
255+
// Promise swapped for a mock that never settles.
256+
class NeverSettles {
257+
then() {
258+
return new NeverSettles();
259+
}
260+
static resolve() {
261+
return new NeverSettles();
262+
}
263+
static reject() {
264+
return new NeverSettles();
265+
}
266+
}
267+
const Real = globalThis.Promise;
268+
globalThis.Promise = NeverSettles as any;
269+
try {
270+
cachedFn();
271+
} finally {
272+
globalThis.Promise = Real;
273+
}
274+
expect("tracedAdoption[]" in (globalThis as any)._$HY.r).toBe(false);
275+
276+
// A navigation inside the short window reuses the adopted entry.
277+
currentIntent = "navigate";
278+
const result = cachedFn();
279+
expect(result).toBeInstanceOf(Real);
280+
expect(await result).toBe("server-data");
281+
expect(callCount).toBe(0);
282+
});
283+
});
284+
235285
test("an adopted entry satisfies a navigation inside the short window", async () => {
236286
return createRoot(async () => {
237287
seedFlightEntry("adoptedThenQuickNavigate[]", "server-data");
@@ -250,5 +300,64 @@ describe("query cache freshness windows", () => {
250300
expect(callCount).toBe(0);
251301
});
252302
});
303+
304+
test("a late hydration read reuses the adopted entry at any age (solid #3721)", async () => {
305+
return createRoot(async () => {
306+
seedFlightEntry("lateHydrationRead[]", "server-data");
307+
let callCount = 0;
308+
const cachedFn = query(async () => {
309+
callCount++;
310+
return "fresh-data";
311+
}, "lateHydrationRead");
312+
313+
// The first reader adopts the one-shot payload and is gone (count 0).
314+
hydrating = true;
315+
await cachedFn();
316+
expect("lateHydrationRead[]" in (globalThis as any)._$HY.r).toBe(false);
317+
318+
// A boundary resuming past the short window reads the same key while
319+
// still hydrating: it must not run fn inside the hydration trace.
320+
advanceClock(PRELOAD_TIMEOUT + 1000);
321+
const result = await cachedFn();
322+
expect(result).toBe("server-data");
323+
expect(callCount).toBe(0);
324+
});
325+
});
326+
327+
test("outside hydration, a stale read with no navigation refetches", async () => {
328+
return createRoot(async () => {
329+
seedFlightEntry("staleAfterHydration[]", "server-data");
330+
let callCount = 0;
331+
const cachedFn = query(async () => {
332+
callCount++;
333+
return "fresh-data";
334+
}, "staleAfterHydration");
335+
336+
await cachedFn();
337+
advanceClock(PRELOAD_TIMEOUT + 1000);
338+
const result = await cachedFn();
339+
expect(result).toBe("fresh-data");
340+
expect(callCount).toBe(1);
341+
});
342+
});
343+
344+
test("a navigation during hydration refetches an adopted entry past the short window", async () => {
345+
return createRoot(async () => {
346+
seedFlightEntry("navigateWhileHydrating[]", "server-data");
347+
let callCount = 0;
348+
const cachedFn = query(async () => {
349+
callCount++;
350+
return "fresh-data";
351+
}, "navigateWhileHydrating");
352+
353+
hydrating = true;
354+
await cachedFn();
355+
advanceClock(PRELOAD_TIMEOUT + 1000);
356+
currentIntent = "navigate";
357+
const result = await cachedFn();
358+
expect(result).toBe("fresh-data");
359+
expect(callCount).toBe(1);
360+
});
361+
});
253362
});
254363
});
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import { createMemo, isHydrating, Loading, Show } from "solid-js";
2+
import { sharedConfig } from "solid-js/internal";
3+
import { isServer } from "@solidjs/web";
4+
import { createRouter, query, useIsRouting } from "../../src/index.js";
5+
6+
// Captured before hydration can swap the global for a tracking run.
7+
const NativePromise = Promise;
8+
const tracing = () => Promise !== NativePromise;
9+
10+
export function createApp(options: { asyncUser?: boolean } = {}) {
11+
const log: { key: string; tracing: boolean; hydrating: boolean }[] = [];
12+
const record = (key: string) => log.push({ key, tracing: tracing(), hydrating: !!isHydrating() });
13+
let release!: (value: string) => void;
14+
const pending = new Promise<string>(resolve => (release = resolve));
15+
const slow = query(() => (isServer ? pending : Promise.resolve("Slow ready")), "late-slow");
16+
// On the client: a plain fetch chain, or the shape of a server function's
17+
// client stub (async all the way down).
18+
const user = query(
19+
isServer
20+
? () => Promise.resolve("User ready")
21+
: options.asyncUser
22+
? async () => {
23+
record("user");
24+
const response = await fetch("http://localhost/api/user");
25+
return response.text();
26+
}
27+
: () => {
28+
record("user");
29+
return fetch("http://localhost/api/user").then(response => response.text());
30+
},
31+
"late-user"
32+
);
33+
let isRouting!: ReturnType<typeof useIsRouting>;
34+
35+
function UserBadge() {
36+
const name = createMemo(() => (record("badge"), user()));
37+
return <p id="user">{name()}</p>;
38+
}
39+
40+
function Home() {
41+
const status = createMemo(() => slow());
42+
return (
43+
<main>
44+
<h1>{status()}</h1>
45+
<Show when={status()}>
46+
<UserBadge />
47+
</Show>
48+
</main>
49+
);
50+
}
51+
52+
function Other() {
53+
const name = createMemo(() => user());
54+
return (
55+
<main>
56+
<h1>Other: {name()}</h1>
57+
</main>
58+
);
59+
}
60+
61+
const Router = createRouter({
62+
routes: [
63+
{ path: "/", component: Home },
64+
{ path: "/other", component: Other }
65+
],
66+
// App-wide data warmed through the root preload. Its memo is async on the
67+
// server, so hydration adopts the entry inside that memo's tracking run.
68+
preload: () => user(),
69+
scrollRestoration: false
70+
});
71+
72+
function App() {
73+
return (
74+
<Router>
75+
{props => {
76+
isRouting = useIsRouting();
77+
return (
78+
<>
79+
<nav>
80+
<a id="home" href="/">
81+
Home
82+
</a>
83+
<a id="other" href="/other">
84+
Other
85+
</a>
86+
</nav>
87+
<Loading fallback={<h1>Loading...</h1>}>{props.children}</Loading>
88+
</>
89+
);
90+
}}
91+
</Router>
92+
);
93+
}
94+
95+
return {
96+
App,
97+
log,
98+
release: () => release("Slow ready"),
99+
isRouting: () => isRouting(),
100+
isHydrating: () => !!isHydrating(),
101+
isHydrationInProgress: () => sharedConfig.isHydrationInProgress!()
102+
};
103+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { createMemo, Loading } from "solid-js";
2+
import { sharedConfig } from "solid-js/internal";
3+
import { isServer } from "@solidjs/web";
4+
import { createRouter, query, useIsRouting } from "../../src/index.js";
5+
6+
export function createApp() {
7+
let release!: (value: string) => void;
8+
const pending = new Promise<string>(resolve => (release = resolve));
9+
const home = query(() => (isServer ? pending : Promise.resolve("Home ready")), "hydration-home");
10+
const destination = query(async () => "Destination ready", "hydration-destination");
11+
let isRouting!: ReturnType<typeof useIsRouting>;
12+
13+
function Home() {
14+
const data = createMemo(() => home());
15+
return (
16+
<main>
17+
<h1>{data()}</h1>
18+
<a href="/destination">Destination</a>
19+
</main>
20+
);
21+
}
22+
23+
function Destination() {
24+
const data = createMemo(() => destination(), { deferStream: true });
25+
return (
26+
<main>
27+
<h1>{data()}</h1>
28+
<a href="/">Home</a>
29+
</main>
30+
);
31+
}
32+
33+
const Router = createRouter({
34+
routes: [
35+
{ path: "/", component: Home },
36+
{ path: "/destination", component: Destination }
37+
],
38+
scrollRestoration: false
39+
});
40+
41+
function App() {
42+
return (
43+
<Router>
44+
{props => {
45+
isRouting = useIsRouting();
46+
return (
47+
<Loading
48+
fallback={
49+
<main>
50+
<h1>Loading...</h1>
51+
<a href="/destination">Destination</a>
52+
</main>
53+
}
54+
>
55+
{props.children}
56+
</Loading>
57+
);
58+
}}
59+
</Router>
60+
);
61+
}
62+
63+
return {
64+
App,
65+
release: () => release("Home ready"),
66+
isRouting: () => isRouting(),
67+
isHydrationInProgress: () => sharedConfig.isHydrationInProgress!()
68+
};
69+
}

0 commit comments

Comments
 (0)