Skip to content

Commit 2b2990a

Browse files
committed
fix(solid): a served source's arrival re-serves its dependents' answers instead of asking again
Hydrated mid-stream, an async shell memo `b` reading another, `a`, both read only inside a streamed <Loading>, asked again when `a`'s server answer arrived: the landing re-ran `b`, and the hydration latch took the rerun for a client write (f3da41e's "re-entry is always invalidation- driven"; b68a907 computes it at once for a shell node). The server's `b` was computed from that same `a`; nothing on the client diverged. The latch now has one rule: a latched rerun inside hydration's own pass over served answers (NO_CLAIM) re-serves its own answer and arms nothing. That pass is a hydrated failure's content run (the Errored's, or a rejected fragment's fresh render over the outcome the server drew, from the previous commit) and, new here, a served answer's arrival: readHydratedValue hands the runtime a thenable whose landing runs, with the flush that carries it, under NO_CLAIM. The NO_CLAIM check moves to the head of the latch rule, so in-claim and held reruns there re-serve without arming a takeover too. Client writes still compute (the write-before-resume, nav-before-resume and hydration-latch pins), and a retry outside that pass still follows the client rule. Tests: a parity scenario and spec for the b-reads-a shape (0 asks loaded and streamed piece by piece with clock ticks, one real ask after a client write to their input); both fail before this commit. Size: 0 B on every CSR scenario (compiled floor 9,966 B); +19-27 B minified on the hydrating scenarios over the previous commit. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2
1 parent d9a7a49 commit 2b2990a

5 files changed

Lines changed: 197 additions & 25 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 memo that adopted its server answer no longer asks again when the server's answer for one of its sources arrives mid-stream. Hydrated mid-stream, an async shell memo `b` reading another, `a`, re-ran when `a`'s server value landed, and the serialized-value latch took that rerun for a client write and computed `b`. The arrival of a served answer, with the flush that carries it, is now hydration's own pass (as a hydrated failure's content run is): a latched node re-running there re-serves its own answer and arms nothing. Only a client write makes it compute.

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

Lines changed: 47 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -306,11 +306,12 @@ let _snapshotRootOwner: Owner | null = null;
306306
// The boundary owner whose resume window is open (null during a root pass,
307307
// which claims everything). Reached as `sharedConfig.isClaiming`.
308308
let _claimOwner: Owner | null = null;
309-
// The claim window over no owner: a hydrated failure's content run — a
310-
// hydrated `<Errored>`'s (hydratedCreateErrorBoundary), or a rejected
311-
// fragment's fresh render over the outcome the server drew for it
312-
// (resumeBoundaryHydration) — where nothing claims and what the content
313-
// reads is the server's failure (readSerializedOrCompute).
309+
// The claim window over no owner: hydration's own pass over served answers,
310+
// where nothing claims and a latched node re-serves its server answer
311+
// (readSerializedOrCompute) — a hydrated failure's content run (a hydrated
312+
// `<Errored>`'s, hydratedCreateErrorBoundary; a rejected fragment's fresh
313+
// render over the outcome the server drew for it, resumeBoundaryHydration),
314+
// and a served answer's arrival (`arrive`).
314315
const NO_CLAIM = {} as Owner;
315316
function isClaiming(): boolean {
316317
if (!_claimOwner) return true;
@@ -584,6 +585,22 @@ export function syncThenable(value: any) {
584585
};
585586
}
586587

588+
/**
589+
* The async runtime's landing of a served answer that was still in flight
590+
* (readHydratedValue). The arrival and the flush that carries it, run here
591+
* at once, are hydration's own pass (NO_CLAIM):
592+
* a dependent that adopted its own server answer re-runs there because the
593+
* server's answer for a source arrived, not because a client write diverged
594+
* it, and re-serves its answer (readSerializedOrCompute). The landing runs
595+
* from a settled promise, outside any claim window.
596+
*/
597+
const arrive = (f: any) => (x: any) => {
598+
_claimOwner = NO_CLAIM;
599+
f(x);
600+
flush();
601+
_claimOwner = null;
602+
};
603+
587604
/**
588605
* Unwrap a serialized hydration map entry. Only call when the map HAS an
589606
* entry for this id — presence is the caller's decision (`sharedConfig.has`),
@@ -605,16 +622,20 @@ export function readHydratedValue(initP: any, refresh: () => void, options?: any
605622
// claim against placeholder DOM). Hand the async runtime a clean thenable
606623
// (the settled refs are stamped `s`/`v`, which the core would also
607624
// fast-adopt): the landing applies on the microtask after the walk.
608-
if (hasLoadingWindow(options) && typeof initP.then === "function")
609-
return { then: initP.then.bind(initP) };
610-
if (initP.s === 2) {
611-
// The stamp is the consumption: nothing ever `.then`s the serialized
612-
// promise itself, so observe its rejection here or the deserialized
613-
// record surfaces as an unhandled rejection (#2997).
614-
if (typeof initP.then === "function") initP.then(undefined, noop);
615-
throw initP.v;
625+
if (!hasLoadingWindow(options)) {
626+
if (initP.s === 2) {
627+
// The stamp is the consumption: nothing ever `.then`s the serialized
628+
// promise itself, so observe its rejection here or the deserialized
629+
// record surfaces as an unhandled rejection (#2997).
630+
initP.then?.(undefined, noop);
631+
throw initP.v;
632+
}
633+
if (initP.s === 1) return initP.v;
616634
}
617-
if (initP.s === 1) return initP.v;
635+
// Still in flight (or a loading window's): the runtime lands it, its
636+
// arrival marked (`arrive`).
637+
if (typeof initP.then === "function")
638+
return { then: (a: any, b: any) => initP.then(arrive(a), arrive(b)) };
618639
}
619640
return initP;
620641
}
@@ -686,17 +707,17 @@ export function readSerializedOrCompute(compute: (prev: any) => any, prev: any,
686707
// A rerun outside the claim in progress by a node no pending boundary
687708
// holds: its section's hydration is over, so the rerun answers a client
688709
// write and computes, rather than re-adopting the server value until the
689-
// page's last boundary resumes. Not inside a hydrated failure's content
690-
// run (NO_CLAIM): a read there re-runs a node with nothing changed — a
691-
// later tracked read retries an errored async node (PJ-R35) — and the
692-
// server's answer, its error, is what the content shows. It re-serves
693-
// that answer and arms nothing: no ask, no loading flash (#4287, #4306).
694-
if (options?.ssrSource !== "hybrid") {
710+
// page's last boundary resumes. Never in hydration's own pass over
711+
// served answers (NO_CLAIM): a source's server answer arriving, or a
712+
// hydrated failure's content reading the node — a later tracked read
713+
// retries an errored async node (PJ-R35) with nothing changed. No client
714+
// write diverged it there: it re-serves its own answer, an error
715+
// included, and arms nothing — no ask, no loading flash (#4287, #4306).
716+
if (options?.ssrSource !== "hybrid" && _claimOwner !== NO_CLAIM) {
695717
let p: Owner | null = o;
696718
while (p && !(p as any)._hp) p = p._parent;
697-
if (!p && !(sharedConfig.hydrating && isClaiming())) {
698-
if (_claimOwner !== NO_CLAIM) return compute(prev);
699-
} else armLiveTakeover(o);
719+
if (!p && !(sharedConfig.hydrating && isClaiming())) return compute(prev);
720+
armLiveTakeover(o);
700721
}
701722
} else latchedOnce.add(o);
702723
const initP = sharedConfig.load!(o.id!);
@@ -2285,8 +2306,9 @@ function resumeBoundaryHydration(
22852306
// swap brought, listed in the reveal record, #4287) it is that
22862307
// failure's content run, as a hydrated `<Errored>`'s is (NO_CLAIM). A
22872308
// resume runs from a settled promise, never inside a claim window, so
2288-
// there is no claim owner to restore.
2289-
if ((globalThis as any)._$HY?.v?.[id]?.length) _claimOwner = NO_CLAIM;
2309+
// there is no claim owner to restore — an arrival's pass (`arrive`)
2310+
// that is still marked has had its flush, and does not cover this one.
2311+
_claimOwner = (globalThis as any)._$HY?.v?.[id]?.length ? NO_CLAIM : null;
22902312
_hydratingValue = false;
22912313
set();
22922314
flush();
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"name": "served-source-landing",
3+
"shell": "<div _hk=2><!--$--><template id=\"pl-3\"></template><i _hk=30>loading</i><!--pl-3--><!--/--><span>tail</span></div><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"0\"]=$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[\"1\"]=$R[3]=($R[4]=$R[2]()).p;_$HY.r[\"3_fr\"]=$R[5]=($R[6]=$R[2]()).p;</script>",
4+
"rest": "<script>($R[7]=(resolver, data) => {\n\tresolver.s(data);\n\tresolver.p.s = 1;\n\tresolver.p.v = data;\n})($R[1],\"k1\");</script><template id=\"3\"><span _hk=3000>b:<!--$-->k12<!--/--></span></template><script>$R[7]($R[4],\"k12\");$df(\"3\");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[7]($R[6],!0);</script>"
5+
}

‎packages/web/test/harness/scenarios.tsx‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1691,6 +1691,40 @@ function parkedRejectionAsyncFallback(late: boolean) {
16911691
};
16921692
}
16931693

1694+
// ---------------------------------------------------------------------------
1695+
// An async shell memo `b` reading another, `a`, both read only inside a
1696+
// streamed <Loading>: hydrated mid-stream, `a`'s server answer arrives
1697+
// first and re-runs `b`. Nothing on the client changed — the server's `b`
1698+
// was computed from that same `a` — so `b` re-serves its own server answer
1699+
// instead of asking again; a client write to their input still recomputes
1700+
// both.
1701+
let setServedSourceKey!: (v: string) => void;
1702+
let servedSourceAsks = 0;
1703+
export const servedSourceAskCount = () => servedSourceAsks;
1704+
function ServedSourceLanding() {
1705+
const [key, setKey] = createSignal("k");
1706+
setServedSourceKey = setKey;
1707+
const a = createMemo(async () => {
1708+
const k = key();
1709+
await sleep(5);
1710+
return k + "1";
1711+
});
1712+
const b = createMemo(async () => {
1713+
const x = a();
1714+
if (!isServer && Promise === RealPromise) servedSourceAsks++;
1715+
await sleep(5);
1716+
return x + "2";
1717+
});
1718+
return (
1719+
<div>
1720+
<Loading fallback={<i>loading</i>}>
1721+
<span>b:{b()}</span>
1722+
</Loading>
1723+
<span>tail</span>
1724+
</div>
1725+
);
1726+
}
1727+
16941728
// ---------------------------------------------------------------------------
16951729
// #3414: a sync throw the SERVER catches, with a zero-arg fallback thunk
16961730
// (`fallback={() => <Fallback />}`), inside an enclosing boundary. Errored
@@ -3067,6 +3101,15 @@ export const scenarios: Scenario[] = [
30673101
expectedTextAfterUpdate: "user:u8tail",
30683102
stableSelector: "div"
30693103
},
3104+
{
3105+
name: "served-source-landing",
3106+
App: ServedSourceLanding,
3107+
async: true,
3108+
expectedText: "b:k12tail",
3109+
serverText: "loading tail k12",
3110+
update: () => setServedSourceKey("j"),
3111+
expectedTextAfterUpdate: "b:j12tail"
3112+
},
30703113
{
30713114
name: "errored-thunk-fallback-under-errored",
30723115
App: ErroredThunkFallbackUnderErrored,
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
* @vitest-environment jsdom
4+
*
5+
* An async shell memo `b` reading another, `a`, both read only inside a
6+
* streamed `<Loading>`. Hydrated mid-stream, `a`'s server answer arrives
7+
* before `b`'s and re-runs `b`: that rerun is the server's answer for a
8+
* source arriving, not a client write, so `b` re-serves its own server
9+
* answer — nothing is asked again, in either replay order. A client write
10+
* to their input afterwards recomputes them (one real ask for `b`).
11+
*
12+
* Replays the parity harness artifact (test/server/hydration-harness.spec.tsx).
13+
*/
14+
import { describe, expect, test, vi } from "vitest";
15+
import { existsSync, readFileSync } from "node:fs";
16+
import { resolve, dirname } from "node:path";
17+
import { fileURLToPath } from "node:url";
18+
import { createRenderEffect, createRoot, createSignal, flush } from "solid-js";
19+
import { hydrate } from "@solidjs/web";
20+
import { scenarios, servedSourceAskCount } from "../harness/scenarios.jsx";
21+
22+
const name = "served-source-landing";
23+
const file = resolve(
24+
dirname(fileURLToPath(import.meta.url)),
25+
`../harness/__artifacts__/${name}.json`
26+
);
27+
const scenario = scenarios.find(s => s.name === name)!;
28+
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
29+
30+
function applyChunk(container: HTMLDivElement, chunk: string, first: boolean) {
31+
const scriptRe = /<script(?:[^>]*)>([\s\S]*?)<\/script>/g;
32+
const scripts = [...chunk.matchAll(scriptRe)].map(m => m[1]);
33+
const stripped = chunk.replace(scriptRe, "");
34+
if (first) container.innerHTML = stripped;
35+
else container.insertAdjacentHTML("beforeend", stripped);
36+
for (const s of scripts) (0, eval)(s);
37+
}
38+
39+
// An unrelated client write after each stream piece moves the reactive
40+
// clock on, as on any live page.
41+
const [tick, setTick] = createSignal(0);
42+
createRoot(() => createRenderEffect(tick, () => {}));
43+
const pieces = (rest: string) => rest.match(/[\s\S]*?<\/script>/g) ?? [rest];
44+
45+
async function run(mode: "loaded" | "streamed") {
46+
expect(existsSync(file)).toBe(true);
47+
const { shell, rest } = JSON.parse(readFileSync(file, "utf-8"));
48+
// The two answers arrive in separate scripts, `a`'s first.
49+
expect(pieces(rest).length).toBeGreaterThan(1);
50+
const container = document.createElement("div");
51+
document.body.appendChild(container);
52+
(globalThis as any)._$HY = { events: [], completed: new WeakSet(), r: {}, fe() {} };
53+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
54+
const asksBefore = servedSourceAskCount();
55+
let dispose: (() => void) | undefined;
56+
try {
57+
applyChunk(container, shell, true);
58+
if (mode === "loaded") applyChunk(container, rest, false);
59+
dispose = hydrate(() => <scenario.App />, container);
60+
flush();
61+
await sleep(10);
62+
flush();
63+
if (mode === "streamed") {
64+
expect(container.textContent).toBe("loadingtail");
65+
for (const piece of pieces(rest)) {
66+
applyChunk(container, piece, false);
67+
flush();
68+
await sleep(5);
69+
setTick(tick() + 1);
70+
flush();
71+
expect(["loadingtail", "b:k12tail"]).toContain(container.textContent);
72+
}
73+
}
74+
await sleep(30);
75+
flush();
76+
expect(container.textContent).toBe("b:k12tail");
77+
expect(servedSourceAskCount()).toBe(asksBefore);
78+
79+
scenario.update!();
80+
flush();
81+
await sleep(30);
82+
flush();
83+
expect(container.textContent).toBe("b:j12tail");
84+
expect(servedSourceAskCount()).toBe(asksBefore + 1);
85+
expect(warn).not.toHaveBeenCalled();
86+
} finally {
87+
warn.mockRestore();
88+
dispose?.();
89+
await sleep(0);
90+
container.remove();
91+
}
92+
}
93+
94+
describe("a served source's answer arriving does not re-ask its dependent", () => {
95+
test("hydrated after the stream", () => run("loaded"));
96+
test("hydrated mid-stream", () => run("streamed"));
97+
});

0 commit comments

Comments
 (0)