Skip to content

Commit 2c9fdd9

Browse files
ryansolidclaude
andauthored
fix(solid): a rejected fragment's fresh render claims what the server sent (#4319)
* fix(solid,web): draw an Errored fallback for a Loading's async failure, and adopt it (#4287) Outside a server component, a <Loading> whose async read failed during a streamed render settled its fragment blank, and the hydrating client rendered the failed boundary from scratch: it asked again and showed the loading fallback. Server: the failing <Loading> now asks the enclosing <Errored> for its outcome outside server components too, passing its own id. The Errored answers only when that Loading is all of its content (its resolved markup is the Loading's placeholder): its fallback is drawn into the fragment, or inlined pre-flush, and the error is serialized at the Errored id. Deeper in the content it answers nothing, as before. A rejected fragment's template is marked `e`, and `$dfr` records the nodes it swaps in for it. Client: inside a hydrated Errored's no-claim content run, a <Loading> runs its content with its data adopted instead of waiting on its fragment, so the Errored holds the client's own error and tracks the content's inputs (#4273). A boundary that claimed its fallback and then renders a rejected fragment fresh clears the nodes the swap put in first, so nothing of the server's outcome is left beside the client's render. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * fix(solid): serialize an Errored's error only when its fallback markup is sent When a streamed <Loading> fails after the shell and asks the enclosing <Errored> for its outcome, the fallback may hold an async hole that has not resolved yet. renderOutcome then returns no markup (the fragment settles as a plain rejection), but handleError had already serialized the error at the Errored id. A client hydrating after the failure read that record, claimed a fallback that was never sent, and went blank with a hydration key miss. The outcome path now defers the record and writes it only once the fallback resolved to finished markup. Without it the client renders the failure itself, as on `next`. Server-only; no client bytes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018LY7F9czoRqdMEvk2QwPr1 * fix(solid,web): stream a parked Errored fallback once its async hole resolves (#4306) An <Errored> whose fallback reads async data, around a <Loading> that fails after the shell inside an outer <Loading> still pending, lost its region: the outcome render met the fallback's pending hole, answered no markup, and the parked fragment spliced a blank into the outer one while its `_fr` resolved. The client claimed against the blank and showed nothing there, with hydration warnings. renderOutcome now answers a still-resolving fallback with a function that waits out its holes and returns the finished markup, serializing the error only then. The <Loading> calls it only while its fragment is parked in an enclosing pending one (the registry's new `parked()` query on the settle function), where nothing of the failure shows yet: the outer fragment carries the fallback, or, if the outer settles first, the inner fragment streams it when it lands. A failure in a region already shown settles at once, as before. Server-only; no client bytes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * fix(solid,web): a failed Errored always waits for its fallback's async holes (#4306) Per RULES-DERIVED D-18 (a swap to a fallback waits for the fallback to be ready), the wait for an Errored fallback's async holes no longer depends on the fragment being parked. A <Loading> that fails after the shell under an <Errored> whose fallback is still resolving keeps its placeholder until the finished fallback is ready, then streams it with the error record, in the parked case (carried by the outer fragment while that is pending) and the unparked one alike. The registry's `parked()` query is dropped. #4303's async-fallback scenario now expects the server's finished fallback and its record: a client hydrating after the failure arrived claims it and asks nothing again. Server-only; no client bytes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * fix(solid,web): a hydrated failure re-serves the server's error instead of asking again (#4287, #4306) A client hydrating mid-stream asked again for an async memo whose server read failed, and flashed back to the inner <Loading> fallback after the failure showed: Errored > Loading > read, with the read failing after the shell, unparked (the fragment rejects and the client renders the failure fresh over the swapped-in Errored fallback) or parked in a pending outer Loading (the outer resume runs the hydrated Errored's content, NO_CLAIM). Both content runs read the shell memo a cycle after its error landed, and a later tracked read retries an errored async node (PJ-R35). The retry re-enters the hydration latch, which since f3da41e has taken every re-entry for a dependency change ("re-entry is always invalidation- driven"), and since b68a907 computes such a rerun at once for a shell node outside the claim in progress: one real ask, the Loading fallback for its duration. Before f3da41e the latch re-served the serialized answer on every re-entry while hydrating, so the retry asked nothing. Inside a hydrated failure's content run (NO_CLAIM) a latched rerun now re-serves the server's answer, its error included, and arms nothing. A rejected fragment's fresh render runs as such a content run when the swap brought the outcome the server drew for the failure (the reveal record lists its nodes); to make that list the outcome alone, a rejected fragment with no outcome streams an empty template instead of a lone space. Uncontained failures (no outcome) keep rendering fresh as before. Tests: the #4287/#4306 hydration specs stream piece by piece with a clock tick between pieces (the plain-fallback case only passed because no flush ran between the error landing and the fresh read), assert 0 asks in both modes and no flash back to a loading fallback, and cover the parked plain-fallback scenario, which now has an ask counter and an update pass (the Errored tracks the memo, #4273). Size: 0 B on every CSR scenario (compiled floor 9,966 B); +65-71 B minified on the hydrating scenarios. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * 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 * fix(solid): a served pass never swallows a client write A served answer's arrival is hydration's own pass (NO_CLAIM): a latched node re-running there re-serves its server answer. A client write carried by that same flush must still make the node compute. - Client writes already made (pending, unflushed) flush first, outside the pass (`servedPass`). The async runtime's landing flushes synchronously, and that flush would otherwise carry them. - The pass covers only the flush round its served write lands in (`_servedAt = clock`). An effect's write runs in a later round of the same flush, and a latched node re-run there computes. The latch tests `clock > _servedAt`. `@solidjs/signals` exports its flush-round counter (`clock`), an internal live binding, at 0 B. Landings cannot be coalesced into one pass per microtask batch without changing signals. `asyncWrite` already flushes synchronously on every landing (`schedule(); flush()`) at the #4308 head, so a served pass adds no flush per landing. Its trailing `flush()` is a no-op after a value landing. Tests: in served-source-landing, a write before the flush and an effect's write in the landing's flush both give the written value with 1 ask. Both fail on 2b2990a. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * perf(solid): golf the served-pass client code This changes no behaviour. Client bytes over next go from about +130 B to +58 B minified. - A hydrated `<Errored>`'s content run and a served pass are one window kind: `_claimOwner = ~clock`, a window over no owner for the flush round it opened in. `~` keeps it truthy when clock is 0. - That replaces both `NO_CLAIM` and `_servedAt`. The latch checks one thing, `_claimOwner !== ~clock`, and a later round of an arrival's flush (an effect's write) still computes. `isClaiming` reads a number as no owner, so nothing claims, as before. - `servedPass` is curried (`servedPass(f)(x)`), so the arrival thenable is `initP.then(servedPass(a), servedPass(b))`. - A resume clears the hydration flag once, before either branch. The fresh branch's own flush was redundant with the resume's trailing one. The outcome check reads `?.[0]` instead of `?.length`. The pre-flush stays on both paths. Removing it makes the write-before-landing test fail, and comparing only `_claimOwner` without the round makes the effect-write test fail. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * fix(solid): a rejected fragment's fresh render claims what the server sent Hydration never asks again for an answer the server sent. When a streamed <Loading> fragment rejects with no outcome (no <Errored> on the server could draw the failure: the one above it was already on the wire, or there is none), the client still renders the fragment fresh, so the graph under the boundary is created. Now every read in that render claims its serialized record instead of asking again: - a read the server resolved takes its value; - a read whose record is an error throws that error (as the server serialized it: redacted unless markSafeError) to the nearest client boundary through the normal path, or is an uncaught error when there is none; - only a read with no record at all computes (a truncated stream's refs are dropped from the registry). How: a rejection (the server's, or the stream cut short) now resumes the boundary with 0 rather than false, and resumeBoundaryHydration runs every fresh render as a served pass (`servedPass(set, adopt)`), adopting (`_hydratingValue`) only after a rejection. A superseded render and an asset failure do not adopt. servedPass resets its state in a `finally`, because an uncaught error leaves the flush by throwing. Recovery is a real input change or a client boundary's reset(), as for any hydrated failure (#4273). Changed expectations: async-memo-element-4242.spec.tsx, uncontained variants and their `-reference` twins (the generic "server render error at this position" path, so both change together; they still compare equal): - runs: [] for the jsx shape. `outer` adopts the server's error and never runs. (The loaded-mode check used to expect the client to compute the element: "jsx-41Count: 1".) The issue shape keeps ["inner"]. That run is the fixture's own: the dry run's continuation escapes the mock Promise through a real timer and builds the inner slot, whose memo has no owner id to adopt by. - halted: true, done: false (were false/true in loaded mode). The adopted error has no client boundary to reach (a <Loading> does not catch), so it is uncaught, as on any client render. The reactive system halts, and the halted resume never completes hydration. - text "", afterClick undefined (were "jsx-41Count: 1"/"Count: 1", and "nested-41"). The element came from the errored memo, so it never renders and there is no counter to click. - shown ["outer", ""] streamed, [""] loaded: the fallback, then nothing. client-hydration.spec.ts, "rejected _fr resumes without hydrating serialized children" -> "rejected _fr resumes fresh, adopting serialized children": memo() 0 -> 7. The fresh DOM stays, but the serialized 7 is the server's answer, so the client uses it rather than computing 0. client-recovery-record.spec.ts (three tests): b.memo() 0 -> 7, for the same reason. The recovery records are unchanged. New: served-error-no-reask.spec.tsx with two parity-harness scenarios. - nested-rejection-no-outcome: a shell <Errored> over a streamed outer <Loading> (a resolved read, a counter) and an inner <Loading> whose read fails on the server beside a read the server resolved. The inner fragment rejects with no outcome. The fresh render shows the server's error in the shell Errored, with 0 asks for either read. reset() asks once, and the recreated graph is live (the counter clicks). - served-error-reread: a served error mid-hydration (a slow boundary still pending) stands with no ask. reset() is a real retry: one ask, and it recovers while hydration still runs. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * fix(web): a fresh render adopts only what the server answered, by aligned ids The previous commit made a rejected fragment's fresh render adopt what the server sent by id. That exposed two wrong-data cases. Abandoned records. When a fragment fails on the server with nested reads still pending, abandonSubtree settles those records to release seroval, and they reached the client as `undefined`. The fresh render adopted that `undefined` as the server's answer. The server now also unregisters them: a record not yet on the wire is dropped from the stub batch, and one already registered gets a `delete _$HY.r[id]` document task, queued ahead of the `_fr` rejection that triggers the fresh render. The read then has no record and computes. Frame sinks are untouched, since they have no reader for these records. Server-only: 0 B on the client for this part. Id alignment. The server spends a child id on every element's hydration key. A non-claiming client render did not (getNextElement only read the key while claiming), so in a fresh render every owner after an element got a shifted id. It could miss its own record or take a sibling's. Now getNextElement consumes the key whenever hydration is on, claiming or not. A non-adopting fresh render runs with the flag off, so it is unchanged. Hydratable-compiled bundles only. Test: abandoned-sibling-computes (loaded and streamed). A <Loading> holds a read `a`, a read `d` after an element, and a nested <Loading> with a read `c` (50ms on the server). Its content throws on the server once `a` lands, a render error that no record carries. The fragment rejects with `c` still pending. The client shows "adc!an0tail": `a` and `d` are adopted with 0 asks, `c` computes once and gets its own value, and the counter clicks. Without the server change `c` shows "" (it adopts `undefined`). Without the key change `d` asks. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * perf(solid): read the page's _$HY directly on the recover path A recover only runs while hydrating, so the guarded globalThis read is dead weight: -12 B minified on every hydrating and page scenario. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018LY7F9czoRqdMEvk2QwPr1 * test(web): #4316's parked late case and twin warnings under adopted fresh renders With the fresh render adopting the server's records, the uncaught late variant halts (no client boundary, as on the server) and hydration never completes, as #4242's uncontained variants do. The parked twin parity now compares warnings too: the streamed key miss it excluded no longer happens. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * fix(solid,web): a rejected fragment's fresh render creates Dynamic tags and mounts Portals Review of #4319 found two regressions, both in a <Loading> whose server render threw. Both are caused by c376083: the adopting fresh render runs with `sharedConfig.hydrating` on (servedPass sets `_hydratingValue = adopt`, packages/solid/src/client/hydration.ts:605 at 57b6925) but claims nothing. Before it, a fresh render ran with hydration off. 1. <Dynamic component="p"> threw "Hydration Mismatch. Unable to find DOM nodes for hydration key", and the page halted. staticElement (packages/web/src/index.ts:323-330) branches on the bare flag and calls getNextElement() with no template. Off the claim, getNextElement can only create from a template, so it threw. That has been the case since before the key change too. Fix: pass the create thunk. The key is spent (ids stay aligned) and the element is created, like a compiled template. This is the only template-less getNextElement caller. getHydrationKey has no other client callers. 2. <Portal> never mounted. Its content memo is `ssrSource: "client"` (packages/web/src/index.ts:155), so with hydration on it goes through withHydrationGate (hydration.ts:1174-1178), which writes setHydrated(true) right after creation. hydrateSignalLike calls markTopLevelSnapshotScope (hydration.ts:1191, 327-335). In the fresh render no window owned the snapshot root, so it marked the page root as a snapshot scope. The root's scope is released only by the `hydrating` setter (hydration.ts:1557-1564), and servedPass bypasses the setter. The scope stayed open, the gate write stayed held, and the gate memo never re-ran (confirmed: it ran once, with hydrated() false). Fix: an adopting servedPass sets `_snapshotRootOwner` for its duration, so the render opens no snapshot scope. That is a client render, as before c376083. The rest of the gated nodes (the Portal anchor memo, index.ts:225) are fixed by the same change. Sweep of the other sites that branch on the bare flag during such a render. None breaks: - clientOnly (index.ts:458/468) shows its fallback and swaps at hydration end; - lazy (component.ts:188/276), the dynamic factory warm-up (dynamic.ts:173) and eager list mapping (flow.ts:106) are harmless or keep ids aligned; - reclaimRegion (client.ts:1484) only acts on a connected parent whose tracked nodes are detached, which is the cleared fallback region here. Nits: - resumeBoundaryHydration runs checkHydrationComplete in a finally. An adopted error with no client boundary throws out of the render, but the boundary has resumed, so hydration completes. Updated: #4242's uncontained variants and twins, and #4316's late case (16cec07), now expect done true. halted stays true. - getNextElement: the reviewer's trim (node read only while claiming, one `!node` test). Tests (served-error-no-reask.spec.tsx; new scenarios rejected-fragment-dynamic and rejected-fragment-portal, a server-only render throw after the shell): loaded and streamed, the text is "adyn!atail" / "a!aportaltail", hydration is done, and there are no console errors. Before the fixes: "tail" (halted) and "a!atail" (no portal). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * perf(solid,web): one try/finally for a served pass that throws servedPass's `finally` now runs checkHydrationComplete itself, after resetting the pass state. resumeBoundaryHydration drops its own try/finally: a boundary's fresh render is that resume, and its uncaught error still completes hydration. Everywhere else a served pass's check is a no-op: a landing comes when hydration is done, or while boundaries are still pending. getNextElement reads isHydrating() inline instead of through a variable (the dev mismatch warning calls it again, dev only). Behaviour is unchanged. It saves 8 B minified on every hydrating bundle (5 B in the compiled ones). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * chore(size): raise the hydrating + store cap for #4319 over #4314 Size-Exception accepted by the maintainer (2026-10-27): +34 B minified over the recorded size on "app: hydrating + every store primitive family". Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * fix(solid,web): a rejected fragment's fresh render renders NoHydration and gates its stylesheets The adopting fresh render (#4319) runs with sharedConfig.hydrating on but claims nothing. Two readers took the bare flag for "claiming server DOM": - NoHydration returned nothing, so its children vanished ("a!atail" instead of "anh!atail"). - gateHeadResource skipped the stylesheet reveal gate, so content the server never drew revealed before its sheet loaded. Both now read isHydrating(), the claiming check. 0 B on every size scenario. The other bare readers stay: For's eager map, createUniqueId, the store, memo and signal wrappers and the Loading wrapper spend or adopt ids the server spent; clientOnly and Portal's tree marker defer through the hydration-end gate; the lazy lookup reads the module cache; the head flush and reclaimRegion never run inside the pass or are guarded on connectivity. New scenarios pin NoHydration, clientOnly, For, a nested Loading and a stylesheet inside a rejected fragment. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 --------- Co-authored-by: Claude <[email protected]>
1 parent 0c6db49 commit 2c9fdd9

24 files changed

Lines changed: 872 additions & 74 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
A streamed boundary that fails on the server can leave nested reads still pending. The server abandons those reads, and their records used to settle as `undefined`, which the client's fresh render of the failed fragment would then adopt as the server's answer. The server now unregisters abandoned records, so those reads compute on the client. The fresh render also spends an id on each element's hydration key, as the server did, so its reads line up with the server's records by id.
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 boundary whose server render failed is rendered fresh on the client while adopting the server's records. Inside that render, a `<Dynamic>` tag now creates its element instead of throwing a hydration mismatch, and a `<Portal>` mounts. Hydration also completes when the adopted error has no client boundary to catch it.
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+
Hydration never asks again for what the server sent, even when a streamed boundary's fragment rejects with no outcome (no `<Errored>` on the server could draw the failure). The client still renders that fragment fresh, so its graph is created, but every read in it now claims its serialized record: reads the server resolved take their values, and a read whose record is an error throws that error to the nearest client boundary, or is an uncaught error when there is none. Only reads with no record, such as those cut off by a truncated stream, compute. Recovery comes from a real input change or a boundary's `reset()`, as for any hydrated failure.

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

Lines changed: 49 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,6 @@ import { IS_DEV, IS_OBSERVE } from "./core.js";
5454
// enableHydration().
5555
import { hydrateStoreLike } from "./store-hydration.js";
5656

57-
declare const _$HY: any;
58-
5957
type HydrationSsrFields = {
6058
/**
6159
* Defer the SSR stream flush until this primitive's first value is
@@ -590,8 +588,9 @@ export function syncThenable(value: any) {
590588
/**
591589
* A served pass: `write(x)` lands a served answer — the server's answer for a
592590
* node arriving (the async runtime writes it and flushes, synchronously),
593-
* or a rejected fragment's fresh render over the outcome the server drew
594-
* (the boundary's trigger) — and the flush round that carries it is
591+
* or a boundary's fresh render (its trigger; `adopt`: hydrating, so what it
592+
* creates adopts its server answer by id, claiming nothing) — and the
593+
* flush round that carries it is
595594
* hydration's own pass over served answers (`_claimOwner`, that round). A
596595
* node that adopted its own server answer re-runs there because the
597596
* server's answer for something it reads arrived, not because a client
@@ -601,12 +600,27 @@ export function syncThenable(value: any) {
601600
* the flush, where a node it reaches computes. Runs from a settled promise,
602601
* outside any claim window.
603602
*/
604-
const servedPass = (write: (x?: any) => void) => (x?: any) => {
603+
const servedPass = (write: (x?: any) => void, adopt?: boolean) => (x?: any) => {
605604
flush();
605+
// Adopting, hydration is on but nothing claims: the render is a client
606+
// render, so it opens no snapshot scope either (the `hydrating` setter,
607+
// which would release one, is bypassed here). A scope left open would hold
608+
// every write made in it — a client-only node's gate (a <Portal>) never
609+
// opening.
610+
_hydratingValue = _snapshotRootOwner = adopt as any;
606611
_claimOwner = ~clock;
607-
write(x);
608-
flush();
609-
_claimOwner = null;
612+
// An uncaught error (no client boundary for a served error) leaves the
613+
// flush by throwing: the pass still ends, and hydration still completes
614+
// — a boundary's fresh render is its resume, done all the same. (Outside
615+
// a resume the check is a no-op: hydration is done, or boundaries are
616+
// pending.)
617+
try {
618+
write(x);
619+
flush();
620+
} finally {
621+
_claimOwner = _hydratingValue = _snapshotRootOwner = null as any;
622+
checkHydrationComplete();
623+
}
610624
};
611625

612626
/**
@@ -2306,7 +2320,7 @@ function resumeBoundaryHydration(
23062320
id: string,
23072321
set: () => void,
23082322
release: () => boolean,
2309-
shouldHydrate = true
2323+
shouldHydrate: boolean | 0 = true
23102324
) {
23112325
// Read before release(): releasing removes the boundaryScopes entry.
23122326
const scope = sharedConfig.boundaryScopes?.get(id);
@@ -2334,12 +2348,15 @@ function resumeBoundaryHydration(
23342348
scope,
23352349
o
23362350
)
2337-
: // The client renders the boundary fresh (recover): no claim. Over the
2338-
// outcome the server drew for the failure (an `<Errored>` fallback the
2339-
// swap brought, listed in the reveal record, #4287) it is that
2340-
// failure's content run, as a hydrated `<Errored>`'s is: a served pass.
2341-
// A recover only runs while hydrating, so the page's `_$HY` exists.
2342-
(_$HY.v?.[id]?.[0] ? servedPass(set) : set)();
2351+
: // The client renders the boundary fresh (recover): no claim, a served
2352+
// pass. After a rejection (0: the server's, or the stream cut short)
2353+
// the render adopts what the server sent by id, as a hydrated
2354+
// `<Errored>`'s content run does: the failing read's error included,
2355+
// thrown to the nearest client boundary — the outcome the server drew
2356+
// for it, if any (#4287), or an uncaught error — instead of asking
2357+
// again. What the server never sent (a truncated ref is dropped from
2358+
// the registry) computes.
2359+
servedPass(set, shouldHydrate === 0)();
23432360
flush();
23442361
checkHydrationComplete();
23452362
}
@@ -2355,7 +2372,7 @@ function resumeBoundaryHydration(
23552372
function recover(
23562373
id: string,
23572374
registeredAt: number,
2358-
resume: (shouldHydrate?: boolean) => void
2375+
resume: (shouldHydrate?: boolean | 0) => void
23592376
): void {
23602377
if (registeredAt < 0 || !OBSERVE!.records.observed("recovery")) {
23612378
resume(false);
@@ -2373,7 +2390,7 @@ function recover(
23732390
function initBoundaryResume(
23742391
o: Owner,
23752392
id: string
2376-
): [trigger: () => void, resume: (shouldHydrate?: boolean) => void, release: () => boolean] {
2393+
): [trigger: () => void, resume: (shouldHydrate?: boolean | 0) => void, release: () => boolean] {
23772394
_pendingBoundaries++;
23782395
(o as any)._hp = 1;
23792396
// Capture the current root's registry/gather pair for this boundary's
@@ -2733,17 +2750,17 @@ function fragmentAbort(id: string): Promise<never> {
27332750

27342751
function waitAndResume(
27352752
p: any,
2736-
resume: (shouldHydrate?: boolean) => void,
2753+
resume: (shouldHydrate?: boolean | 0) => void,
27372754
assetPromise?: Promise<void>,
2738-
hydrateRejected = true,
2755+
hydrateRejected: boolean | 0 = true,
27392756
abort?: Promise<never>
27402757
) {
27412758
// Settle data and assets independently: an asset error must not be written
27422759
// into the data ref's rejected state, and a data rejection must still keep
27432760
// its own hydrate semantics. (`p` may be an exotic thenable — coerce first.)
27442761
// An abort promise (fragment truncation) races the data: its rejection
27452762
// flows through the same rejected-state write as a server-sent rejection.
2746-
const data: Promise<boolean> = (
2763+
const data: Promise<boolean | 0> = (
27472764
abort ? Promise.race([Promise.resolve(p), abort]) : Promise.resolve(p)
27482765
).then(
27492766
() => {
@@ -2786,7 +2803,7 @@ function reportAssetFailure(err: any) {
27862803

27872804
function scheduleResumeAfterAssets(
27882805
id: string,
2789-
resume: (shouldHydrate?: boolean) => void,
2806+
resume: (shouldHydrate?: boolean | 0) => void,
27902807
assetPromise?: Promise<void>
27912808
): boolean {
27922809
sharedConfig.gather?.(id);
@@ -2973,7 +2990,7 @@ function hydratedCreateLoadingBoundary<T, U>(
29732990
// branch and `recover` with it.
29742991
waitAndResume(
29752992
1,
2976-
IS_OBSERVE ? () => recover(id, registeredAt, resume) : () => resume(false),
2993+
IS_OBSERVE ? () => recover(id, registeredAt, () => resume(0)) : () => resume(0),
29772994
assetPromise
29782995
);
29792996
return undefined;
@@ -3016,9 +3033,13 @@ function hydratedCreateLoadingBoundary<T, U>(
30163033
// (#4287) — beside the range the fresh render takes: clear
30173034
// them first.
30183035
(revealed || hy.v?.[id]?.forEach?.((n: ChildNode) => n.remove()),
3019-
IS_OBSERVE ? recover(id, registeredAt, resume) : resume(false)),
3036+
IS_OBSERVE
3037+
? recover(id, registeredAt, () => resume(shouldHydrate))
3038+
: resume(shouldHydrate)),
30203039
assetPromise,
3021-
false,
3040+
// A rejection (the server's, or the stream cut short) resumes with 0:
3041+
// the fresh render adopts what the server sent (resumeBoundaryHydration).
3042+
0,
30223043
fragmentAbort(id)
30233044
);
30243045
return revealed ? undefined : fallback();
@@ -3057,7 +3078,10 @@ export function NoHydration(props: { children: SolidElement }): SolidElement {
30573078
const o = createOwner();
30583079
return runWithOwner(o, () => {
30593080
setContext(NoHydrateContext, true);
3060-
if (sharedConfig.hydrating) return undefined as unknown as SolidElement;
3081+
// Claiming, not the bare flag: a rejected fragment's fresh render
3082+
// (adopting by id, claiming nothing) renders the children like any
3083+
// client render.
3084+
if (isHydrating()) return undefined as unknown as SolidElement;
30613085
return props.children;
30623086
}) as unknown as SolidElement;
30633087
}

‎packages/solid/test/client-hydration.spec.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4697,7 +4697,7 @@ describe("Loading boundary: fragment registration channel (_fr)", () => {
46974697
expect(memo()).toBe(99);
46984698
});
46994699

4700-
test("rejected _fr resumes without hydrating serialized children", async () => {
4700+
test("rejected _fr resumes fresh, adopting serialized children", async () => {
47014701
let rejectFr!: (e: any) => void;
47024702
const frPromise: any = new Promise<boolean>((_, rej) => (rejectFr = rej));
47034703
frPromise.s = 0;
@@ -4739,7 +4739,8 @@ describe("Loading boundary: fragment registration channel (_fr)", () => {
47394739
await new Promise<void>(r => setTimeout(r, 50));
47404740
flush();
47414741

4742-
expect(memo()).toBe(0);
4742+
// Fresh DOM, but the server's answer is used: hydration never refetches.
4743+
expect(memo()).toBe(7);
47434744
});
47444745

47454746
test("_fr with assets waits for both fragment and assets", async () => {

‎packages/solid/test/client-recovery-record.spec.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,8 @@ describe.skipIf(OBSERVE === undefined)("recovery record", () => {
119119
rejectFr(new Error("stream error"));
120120
await new Promise<void>(r => setTimeout(r, 20));
121121
flush();
122-
// Fresh client DOM: the serialized 7 was never adopted.
123-
expect(b.memo()).toBe(0);
122+
// Fresh client DOM, the serialized 7 adopted: hydration never refetches.
123+
expect(b.memo()).toBe(7);
124124
expect(records).toEqual([{ id: "t0", at: T0, waitedMs: 30, renderMs: RENDER_MS }]);
125125
});
126126

@@ -133,7 +133,7 @@ describe.skipIf(OBSERVE === undefined)("recovery record", () => {
133133
const b = boundary();
134134
await new Promise<void>(r => setTimeout(r, 10));
135135
flush();
136-
expect(b.memo()).toBe(0);
136+
expect(b.memo()).toBe(7);
137137
// The rejection had already arrived when the boundary registered: the
138138
// clock did not move between registration and the recovery, so the
139139
// person saw no fallback — `waitedMs` is exactly 0.
@@ -163,7 +163,7 @@ describe.skipIf(OBSERVE === undefined)("recovery record", () => {
163163
const b = boundary();
164164
await new Promise<void>(r => setTimeout(r, 10));
165165
flush();
166-
expect(b.memo()).toBe(0);
166+
expect(b.memo()).toBe(7);
167167
// The runtime never read the clock: `registeredAt` is -1 with no listener.
168168
expect(performance.now).not.toHaveBeenCalled();
169169
});

‎packages/web/src/client.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2234,10 +2234,12 @@ function gateHeadResource(props) {
22342234
// errored) sheet must acquire synchronously — cached sheets add zero
22352235
// wait, adopted server-emitted sheets never stall — and even a
22362236
// settled promise costs a microtask through the async machinery.
2237-
// Hydrating content is already visible; the server gated its reveal.
2237+
// Claimed content is already visible; the server gated its reveal. A
2238+
// fresh render under hydration (a rejected fragment's) gates like any
2239+
// client render.
22382240
if (
22392241
gateable &&
2240-
!sharedConfig.hydrating &&
2242+
!isHydrating() &&
22412243
entry.loadState === "pending" &&
22422244
typeof waitAsset === "function"
22432245
)
@@ -2580,20 +2582,22 @@ export function hydrate(code, element, options = {}) {
25802582
export function getNextElement(template?: () => Element): Element;
25812583

25822584
export function getNextElement(template) {
2583-
let node,
2584-
key,
2585-
hydrating = isHydrating();
2586-
if (!hydrating || !(node = sharedConfig.registry.get((key = getHydrationKey())))) {
2585+
// The key is consumed whenever hydration is on, claiming or not: a
2586+
// rejected fragment's fresh render adopts its server answers by id, and
2587+
// the server spent one on this element, so ids after it line up.
2588+
let key = sharedConfig.hydrating && getHydrationKey(),
2589+
node = isHydrating() && sharedConfig.registry.get(key);
2590+
if (!node) {
25872591
if (!template) {
25882592
throw new Error(`Hydration Mismatch. Unable to find DOM nodes for hydration key: ${key}`);
25892593
}
25902594
// A key miss during the hydration walk is a real mismatch: fresh renders
2591-
// (portals, rejected fragments, post-hydration content) all run with the
2592-
// hydrating flag off, so there is no legitimate way to get here. The
2595+
// (portals, rejected fragments, post-hydration content) all run outside
2596+
// the claim, so there is no legitimate way to get here. The
25932597
// detached element returned below keeps the render alive but never lands
25942598
// in the document — without a report that reads as a silently frozen
25952599
// page (solidjs/solid#3000).
2596-
if ("_SOLID_DEV_" && hydrating) {
2600+
if ("_SOLID_DEV_" && isHydrating()) {
25972601
hydrationKeyMisses++;
25982602
console.warn(
25992603
`Hydration key miss for "${key}": no server-rendered element carries this key` +

‎packages/web/src/index.ts‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -325,14 +325,16 @@ function staticElement(tag: string, props: any): JSX.Element {
325325
// CREATED (customized built-in / namespace), so they are read once here,
326326
// untracked — the DOM can't change either after creation — and then flow
327327
// through spread() like any attribute. Hydration claims the
328-
// parser-namespaced node, so neither applies.
329-
const el = hydrating
330-
? getNextElement()
331-
: createElement(
332-
tag,
333-
untrack(() => props.is),
334-
untrack(() => props.xmlns)
335-
);
328+
// parser-namespaced node, so neither applies — when it claims: a fresh
329+
// render under hydration (a rejected fragment's, adopting by id) spends
330+
// the key and creates, like a compiled template.
331+
const create = () =>
332+
createElement(
333+
tag,
334+
untrack(() => props.is),
335+
untrack(() => props.xmlns)
336+
);
337+
const el = hydrating ? getNextElement(create) : create();
336338
spread(el, props);
337339
// Compiled JSX emits runHydrationEvents() after an element that carries
338340
// event handlers. Handlers bound through spread() here need the same call,

‎packages/web/src/server.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2662,9 +2662,10 @@ export function renderToStream(code, options = {}) {
26622662
// resume loops may be parked on promises that never settle), and pending
26632663
// serialized values under the errored key would gate seroval's onDone the
26642664
// same way. Settle both. Descendant `_fr` stubs resolve clean (not
2665-
// rejected) and abandoned data ids resolve undefined: the client re-renders
2666-
// the errored region fresh off the OUTER fragment's rejection, so nothing
2667-
// consumes these — a rejection would only raise unhandled-rejection noise.
2665+
// rejected) and abandoned data ids resolve undefined, and are unregistered
2666+
// on the client: it re-renders the errored region fresh off the OUTER
2667+
// fragment's rejection, so nothing consumes these — a rejection would only
2668+
// raise unhandled-rejection noise.
26682669
//
26692670
// A finding (`SSR_SUBTREE_ABANDONED`) when the discard took work with it —
26702671
// nested fragments still rendering, serialized values still pending: the
@@ -2686,13 +2687,24 @@ export function renderToStream(code, options = {}) {
26862687
fragments++;
26872688
}
26882689
}
2690+
const unregister = [];
26892691
for (const [id, settle] of pendingSerialized) {
26902692
if (id.startsWith(key)) {
26912693
pendingSerialized.delete(id);
26922694
settle();
26932695
serialized++;
2696+
// Not yet on the wire: never registered. Otherwise the client drops
2697+
// it (below).
2698+
if (!stubBatch?.delete(id)) unregister.push(`delete _$HY.r[${JSON.stringify(id)}]`);
26942699
}
26952700
}
2701+
// The settle above only releases seroval: `undefined` is not the
2702+
// server's answer. The client renders this subtree fresh, adopting what
2703+
// the server sent by id, so an abandoned record must not be there to
2704+
// adopt: unregister it (a document task, ahead of the `_fr` rejection
2705+
// that triggers the fresh render) and the read computes. A frame sink
2706+
// has no reader for these records.
2707+
if (unregister.length && !options.sink) pushTask(unregister.join(";"));
26962708
if ("_SOLID_OBSERVE_" && (fragments || serialized))
26972709
emitFinding(
26982710
{
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"name": "abandoned-sibling-computes",
3+
"shell": "<div _hk=0><!--$--><template id=\"pl-1\"></template><i _hk=10>loading</i><!--pl-1--><!--/--><span>tail</span></div><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"1006_fr\"]=$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_fr\"]=$R[3]=($R[4]=$R[2]()).p;_$HY.r[\"1000\"]=$R[5]=($R[6]=$R[2]()).p;_$HY.r[\"1003\"]=$R[7]=($R[8]=$R[2]()).p;_$HY.r[\"1006000\"]=$R[9]=($R[10]=$R[2]()).p;</script>",
4+
"rest": "<script>($R[11]=(resolver, data) => {\n\tresolver.s(data);\n\tresolver.p.s = 1;\n\tresolver.p.v = data;\n})($R[8],\"d\");</script><template id=\"1\" e></template><script>$R[11]($R[6],\"a\");delete _$HY.r[\"1006000\"];$df(\"1\");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[11]($R[10],void 0);$R[11]($R[1],!0);($R[13]=(resolver, data) => {\n\tresolver.f(data);\n\tresolver.p.s = 2;\n\tresolver.p.v = data;\n})($R[4],$R[12]=new Error(\"server render\"));</script>"
5+
}

0 commit comments

Comments
 (0)