Skip to content

Commit 5933499

Browse files
authored
Merge pull request #3551 from solidjs/fix/hybrid-store-gate-waits-for-server
fix(solid): hybrid store handoff waits for the server answer to land
2 parents cf01868 + 40cce01 commit 5933499

4 files changed

Lines changed: 961 additions & 24 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
"solid-js": patch
3+
---
4+
5+
Hybrid store hydration waits for the server's answer before handing off to the client (#3498)
6+
7+
Root cause: the hybrid store gate flipped synchronously at the end of the claim pass. With `loadingValue`/`seedLoadingValue` the server serializes a _pending_ placeholder whose real answer arrives later over the stream; flipping before it landed let the client takeover supersede the server flight, so the engine dropped the server's answer and the store never showed it.
8+
9+
The handoff now follows four rules:
10+
11+
1. **It waits for the first server answer to land.** Synchronous when the serialized value is already settled, as before. When it is pending, the handoff happens when that answer lands — resolve or reject — by adopting it as a one-yield stream whose next pull (the engine's own continuation after the landing commits) is the handoff. It never waits on hydration end and never holds hydration open.
12+
2. **Only the handoff run's first yield is the duplicate.** Later runs (a dependency change, `refresh()`) run the client source against the real draft and commit their first yield normally; previously every run kept discarding it.
13+
3. **A rejected server answer is the adopted answer.** The store surfaces the error until a `refresh()` (a non-handoff run) replaces it; the client's handoff run does not paper over the rejection.
14+
4. **A dependency change before the pending answer lands supersedes it.** Like any new pending change, it cancels the incoming server answer: the store goes live on that run — genuinely new work, not a handoff, so its first yield commits — and the abandoned server flight's landing or rejection is dropped without applying to the store or running it again.

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

Lines changed: 142 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -657,6 +657,58 @@ function wrapFirstYield(iterable: any, activate: () => void) {
657657
};
658658
}
659659

660+
/**
661+
* A hybrid store's still-pending server answer, adopted as a ONE-yield stream
662+
* (#3498). The hybrid contract is that the server consumes exactly one yield
663+
* and the client continues the iteration — this is that first yield, and
664+
* the engine's pull for the next one is the handoff.
665+
*
666+
* Why a stream and not the thenable itself: the handoff must run only once
667+
* the answer has actually LANDED in the store. This relies on the engine's
668+
* flight contract — latest-run-wins supersession (PJ-R26 in the signals
669+
* RULES-INDEX; flight-identity cancellation, #3122): `handleAsync` pulls a
670+
* stream's next step only from the previous step's commit (`asyncWrite`'s
671+
* continuation, `iterateOrRelease`), and it drops a landing whose flight is
672+
* no longer the node's `_inFlight` or whose node a newer write dirtied
673+
* (`asyncWrite`'s guards; a recompute nulls `_inFlight` and fires the flight
674+
* teardown first). So the second `next()` pull is the landed-and-committed
675+
* signal: `onLanded` fires exactly when the landing applied, and never for a
676+
* superseded flight — a dependency change that re-ran the store before the
677+
* landing (rule 4) leaves this stream orphaned and silent. A rejection is
678+
* the adopted answer (rule 3): the engine settles the error and pulls
679+
* nothing more, and `onRejected` only marks authority transferred so the
680+
* next non-handoff run (refresh(), a dependency change) runs the client
681+
* source. An orphaned stream's rejection reaches `onRejected` too, but the
682+
* engine drops the error (same guard) and the store is already live.
683+
*/
684+
function adoptedAnswerStream(thenable: any, onLanded: () => void, onRejected: () => void) {
685+
let pulled = false;
686+
return {
687+
[Symbol.asyncIterator]() {
688+
return {
689+
next() {
690+
if (pulled) {
691+
onLanded();
692+
return Promise.resolve({ done: true, value: undefined });
693+
}
694+
pulled = true;
695+
return {
696+
then(res: any, rej: any) {
697+
thenable.then(
698+
(v: any) => res({ done: false, value: v }),
699+
(e: any) => {
700+
onRejected();
701+
rej(e);
702+
}
703+
);
704+
}
705+
};
706+
}
707+
};
708+
}
709+
};
710+
}
711+
660712
function hydrateSignalFromAsyncIterable(coreFn: Function, compute: any, options: any): any {
661713
const parent = getOwner()!;
662714
const expectedId = peekNextChildId(parent);
@@ -1029,10 +1081,11 @@ export function materializeContainerTrace(marker: {
10291081
// --- Hydration-aware implementations ---
10301082

10311083
// The shared pre-hydration gate lifecycle for the ssrSource branches
1032-
// (signal/store × client/hybrid): create the node with a compute that
1033-
// branches on the gate, then flip it — the flip's recompute is the node's
1034-
// first real run. `ownedWrite` because the write happens inside the node's
1035-
// own creation scope.
1084+
// (signal × client/hybrid, store × client): create the node with a compute
1085+
// that branches on the gate, then flip it — the flip's recompute is the
1086+
// node's first real run. `ownedWrite` because the write happens inside the
1087+
// node's own creation scope. (The hybrid STORE branch flips its own gate at
1088+
// the adopted answer's landing instead — see hydrateStoreLikeFn, #3498.)
10361089
function withHydrationGate(create: (hydrated: () => boolean) => any) {
10371090
const [hydrated, setHydrated] = coreSignal(false, { ownedWrite: true });
10381091
const result = create(hydrated);
@@ -1161,27 +1214,95 @@ function hydrateStoreLikeFn(
11611214
);
11621215
}
11631216
if (ssrSource === "hybrid") {
1164-
return withHydrationGate(hydrated =>
1165-
coreFn(
1166-
(draft: any) => {
1167-
const o = getOwner()!;
1168-
if (!hydrated()) {
1169-
if (sharedConfig.has!(o.id!))
1170-
return readHydratedValue(
1171-
sharedConfig.load!(o.id!),
1172-
() => subFetch(fn, draft),
1173-
options
1174-
);
1175-
return fn(draft);
1176-
}
1217+
// Hybrid handoff (#3498). Server is truth: the store adopts the
1218+
// serialized answer, and the client source takes over from it in ONE
1219+
// handoff run whose first yield is discarded as the duplicate of what
1220+
// the server serialized. Three rules order that handoff:
1221+
//
1222+
// 1. It waits for the first server answer to LAND. Synchronous when the
1223+
// serialized value is already settled (the flip below, as before);
1224+
// when it is still pending — a loadingValue placeholder whose real
1225+
// answer arrives later over the stream, or a settled ref the loading
1226+
// window defers past the claim walk — the flip rides the landing
1227+
// itself (adoptedAnswerStream). That answer is late, not stale:
1228+
// flipping earlier let the takeover supersede the flight and lose it.
1229+
// Never hydration end, and nothing here holds hydration open.
1230+
// 2. Only the handoff run is a duplicate. `live` marks authority
1231+
// transferred; every later run (dependency change, refresh()) runs fn
1232+
// on the real draft and commits its first yield normally.
1233+
// 3. A rejected server answer is the adopted answer. It transfers
1234+
// authority without a handoff run, so the error stays visible until a
1235+
// non-handoff run replaces it.
1236+
// 4. A dependency change before the answer lands supersedes it. Like any
1237+
// new pending change, it cancels the incoming server answer: the store
1238+
// goes live on that run — genuinely new work, not a handoff, so its
1239+
// first yield commits — and the abandoned flight's landing or
1240+
// rejection is dropped by the engine (PJ-R26) and flips nothing.
1241+
const id = peekNextChildId(getOwner()!);
1242+
// Nothing serialized: no answer to wait for and nothing for a first
1243+
// yield to duplicate — the client is authoritative from its first run.
1244+
if (!sharedConfig.has!(id)) return coreFn(fn, initialValue, options);
1245+
const initP = sharedConfig.load!(id);
1246+
const [hydrated, setHydrated] = coreSignal(false, { ownedWrite: true });
1247+
let live = false;
1248+
// A late flip — a queued microtask, or a landing the engine kept for a
1249+
// flight this store has since abandoned — must not run a live store again.
1250+
const flip = () => {
1251+
if (!live) setHydrated(true);
1252+
};
1253+
let adopted = false;
1254+
let creating = true;
1255+
let landedOnCreate = false;
1256+
const result = coreFn(
1257+
(draft: any) => {
1258+
if (live) return fn(draft);
1259+
if (hydrated()) {
1260+
// The handoff run.
1261+
live = true;
11771262
const { proxy, activate } = createShadowDraft(draft, options?.shallow);
11781263
const r = fn(proxy);
11791264
return isAsyncIterable(r) ? wrapFirstYield(r, activate) : r;
1180-
},
1181-
initialValue,
1182-
options
1183-
)
1265+
}
1266+
if (adopted) {
1267+
// Rule 4. The gate is down, so this is not the handoff; an adoption
1268+
// already returned, so it is not a NotReady retry of the trace
1269+
// either — a dependency changed. The recompute already released
1270+
// the adopted flight (recompute nulls `_inFlight` and fires the
1271+
// flight teardown), so the server's late landing is dropped and
1272+
// its second pull — the flip — never comes.
1273+
live = true;
1274+
return fn(draft);
1275+
}
1276+
// Adoption. Re-entered only by a NotReady retry of the trace (the
1277+
// pending sibling settled; nothing was adopted yet, so adopt now).
1278+
subFetch(fn, draft);
1279+
let answer: any;
1280+
try {
1281+
answer = readHydratedValue(initP, () => {}, options);
1282+
} catch (e) {
1283+
// The trace above completed, so this is the settled rejection —
1284+
// the adopted answer (rule 3). (A NotReady from the trace is a
1285+
// retry of this same adoption and never reaches here.)
1286+
live = true;
1287+
throw e;
1288+
}
1289+
adopted = true;
1290+
if (answer != null && typeof answer.then === "function")
1291+
return adoptedAnswerStream(answer, flip, () => (live = true));
1292+
// Settled, landing synchronously in this run. The creation run flips
1293+
// right after construction (below, outside the compute — as the gate
1294+
// always has); a retry run is inside a flush, where the flip must
1295+
// not be a self-write, so it follows on a microtask.
1296+
if (creating) landedOnCreate = true;
1297+
else queueMicrotask(flip);
1298+
return answer;
1299+
},
1300+
initialValue,
1301+
options
11841302
);
1303+
creating = false;
1304+
if (landedOnCreate) flip();
1305+
return result;
11851306
}
11861307
const aiResult = hydrateStoreFromAsyncIterable(coreFn, fn, initialValue, options);
11871308
if (aiResult !== null) return aiResult;

0 commit comments

Comments
 (0)