Skip to content

Commit 309b087

Browse files
ryansolidClaude via Cursorcursoragent
committed
docs: hydration tracking run — known limitations
Document the two ways work escapes the hydration tracking run: a non-fake await before a request sends a real, discarded duplicate (including the server-function client when prepareRequest or the argument codec is in use), and caches must not keep promises created during the run. Clarify that "server" mode computes are traced on the client, not re-run. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 8950bb7 commit 309b087

2 files changed

Lines changed: 56 additions & 1 deletion

File tree

‎documentation/solid-2.0/05-async-data.md‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ Because async lives in ordinary computations, SSR/hydration policy is a per-prim
188188

189189
**`ssrSource`** is the hydration policy: what initial value the client uses, and whether the compute re-runs.
190190

191-
- `"server"` _(default)_ — the client uses the serialized server value as its initial state. The compute does **not** re-run for the initial value; the serialized result is authoritative. Choose this when the compute is deterministic from server-available inputs — the common data-fetch case, where it means no duplicate fetch on load.
191+
- `"server"` _(default)_ — the client uses the serialized server value as its initial state. The compute does **not** re-run for the initial value; the serialized result is authoritative (the client only traces it to record dependencies — see [the tracking run](#the-tracking-run-known-limitations)). Choose this when the compute is deterministic from server-available inputs — the common data-fetch case, where it means no duplicate fetch on load.
192192
- `"hybrid"` — the client seeds from the serialized server value; then, for a compute that returns an **async iterable**, the client continues the stream from it. The server consumed exactly one yield; the client re-runs the generator once the adopted answer has landed, its first yield duplicates that answer and is discarded, and later yields update the node. That handoff is the tail of the initial load, not a refetch: the node reads settled through it — `isPending` is `false`, and a `<Loading>` created in that window shows content — until the stream produces something new. For a **sync or promise-shaped** compute, `"hybrid"` is identical to `"server"`: there is no stream for the client to continue, so the serialized value is adopted and the compute does not re-run until a dependency changes or `refresh()`. Choose `"hybrid"` for streaming sources (live feeds, subscriptions) the client should keep consuming after hydration; for computes over client-only inputs use `"client"`.
193193
- `"client"` — skip the server value entirely. On the server the compute never runs (an owner is still created so hydration ids stay aligned); on the client it is deferred until hydration completes, then runs as if first-mounted. Choose this for client-only state where serialization is meaningless. What the server renders in the compute's place is the author's choice of channel:
194194
- **Bare (structural)** — with no declaration, the source is a hole the server can never fill. Reads suspend _finally_: the nearest `Loading` boundary flushes its fallback into the HTML and hands the position to the client, which renders the content fresh after hydration. Read outside a `Loading` boundary this is a render error (the stream would otherwise hang), so bare client sources must sit under a boundary.
@@ -222,6 +222,59 @@ const widget = createMemo(() => measureBrowserThing(), { ssrSource: "client" });
222222
223223
**`transparent: true`** (integration tier — accepted by effects and memos) makes the node invisible to hydration: it inherits its parent's id instead of consuming a child slot, and its compute runs live during hydration instead of adopting the serialized server value. It exists for **client-only reactive nodes created while hydrating** — nodes the server never rendered, so an id-consuming owner would shift every later sibling's hydration id and break serialized lookups and template claims (this is how `@solidjs/router` wires link state and scroll restoration). It is also the supported alternative to branching on hydration state (`if (hydrating) createEffect(...)`), which freezes the first run's decision: create the node unconditionally and mark it `transparent` so it observes live state. SSR ignores the option (server-side nodes always allocate their id slot), so only mark nodes the server does not create; outside hydration it is a no-op. A node created with no owner (`runWithOwner(null, …)`), or under a root without an `id`, has no id slot to consume and takes this path on its own.
224224
225+
#### The tracking run: known limitations
226+
227+
A compute that adopts a serialized value (`"server"`, `"hybrid"`) still has dependencies to record, so the hydrating client runs it synchronously and discards the result. For that synchronous window the global `Promise` and `fetch` are replaced by fakes whose promises never settle. The fake `fetch` sends nothing, and code awaiting a fake never resumes, so a request further down that chain is never made either. Two things escape the window: work that resumes after it, and fake promises kept beyond it.
228+
229+
**A non-fake `await` before the request sends a duplicate.** `await` and `async` functions use the engine's own Promise, not the global. Code after an `await` on anything that isn't a fake resumes a microtask after the window closes, when `fetch` is real again:
230+
231+
```js
232+
const user = createMemo(async () => {
233+
const token = await getToken(); // async; returns a cached token without fetching
234+
const res = await fetch(`/api/users/${id()}`, { headers: { Authorization: token } });
235+
return res.json();
236+
});
237+
```
238+
239+
The same happens after `await 0`, an already-resolved promise, or a promise created before hydration. The request goes out and its answer is discarded. Nothing hangs or corrupts; it is wasted work. The fix is to start the request synchronously and put async preparation in the chain after it — or, as here, to avoid a non-fake `await` before the request in a hydrated compute (read the token synchronously).
240+
241+
The server-function client awaits before it sends in two cases: when `prepareRequest` is configured (it is awaited even if it returns synchronously), and when the arguments need the codec (`serializeArgs`, installed by `enableRichArguments()`). Calling the server function first in the compute does not help there; the `await` is inside the client. Calls are POST by default, so the duplicate runs the function again on the server: a server function called from a hydrating compute should be a read.
242+
243+
**Caches must not keep promises created during the tracking run.** A promise that awaits the fake `fetch`, or one built from the fake `Promise`, never settles. Stored in a cache that outlives the run, it hangs every later reader of that entry:
244+
245+
```js
246+
const users = new Map();
247+
const fetchUser = async id => (await fetch(`/api/users/${id}`)).json();
248+
249+
const user = createMemo(() => {
250+
if (!users.has(id())) users.set(id(), fetchUser(id())); // never settles if set while tracing
251+
return users.get(id());
252+
});
253+
// `Promise.resolve(value)` inside the compute is the fake too, and never settles either.
254+
```
255+
256+
The rule for a cache seeded from hydration data: while `isHydrating()` (`solid-js`) is true, treat the seeded value as fresh, and do not populate the cache by running the fetcher. To wrap a hydrated value in a real promise, capture the constructor at module load. The fakes only replace the global inside the window.
257+
258+
```js
259+
import { isHydrating } from "solid-js";
260+
import { takeHydrationValue } from "@solidjs/web";
261+
262+
const NativePromise = Promise; // captured at module load, outside any tracking run
263+
const cache = new Map();
264+
265+
function cached(key, fetcher) {
266+
if (!cache.has(key)) {
267+
const seed = takeHydrationValue("mylib:" + key); // written on the server with getHydrationWriter()
268+
if (seed?.status === "resolved") cache.set(key, NativePromise.resolve(seed.value));
269+
else if (seed?.status === "pending") cache.set(key, seed.promise);
270+
// Hydrating with no seed: this may be the tracking run, so don't cache.
271+
else if (isHydrating()) return fetcher();
272+
else cache.set(key, fetcher());
273+
}
274+
return cache.get(key);
275+
}
276+
```
277+
225278
## Migration / replacement
226279
227280
### `createResource` → async computations + `Loading`

‎documentation/solid-2.0/10-server-functions.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,8 @@ configureServerFunctionsClient({
266266

267267
**Single hook, not a chain** — composition is userland (wrap functions if you need layers). Note the symmetry this completes: server-side global policy is the existing handler hooks (`createEvent` / `transformResult` / `handleNoJS`); client-side global policy is `prepareRequest`.
268268

269+
**Hydration cost.** The hook is awaited before the request is sent, as is argument encoding through the codec. So once either is in play, a server function called from a compute that adopts a serialized value during hydration sends a real, discarded duplicate request (see [RFC 05 — the tracking run](05-async-data.md#the-tracking-run-known-limitations)). Keep server functions called from hydrating computes to reads.
270+
269271
#### `invoke`: the per-call invocator
270272

271273
The call-scoped slot was empty in the first draft — its two candidate consumers had found better homes, and the standing rule was "revisit only with a concrete use case in hand." The use case arrived ([#3057](https://github.com/solidjs/solid/issues/3057)): a data layer supersedes a query — navigation, a newer search keystroke — and needs the in-flight HTTP request cancelled, which no declaration or session hook can express because it is a fact about _one call_. `invoke` fills the slot:

0 commit comments

Comments
 (0)