Skip to content

Commit 9927ddd

Browse files
ryansolidClaude via Cursorcursoragent
committed
fix(web,solid): a held container-trace fill hydrates like a resident one
Review of the document-face hold (FrameImpl.#argsUnprepared) along five edges — hydration end before the load settles, id determinism, interruption during the hold, record retention, snapshot consistency — each pinned by a spec written against the branch first. Three fixes, each the smallest change that makes the late claim match a resident-at-t=0 run: - solid: the container-trace materializer roots its projection under a DETACHED root (runWithOwner(null, createRoot)). Rooted under the reading owner, a resident materializer consumed one hydration id per trace during the document pass while a late one (no ambient owner) consumed none, so a sibling after the frame hydrated under different keys in the two runs. - solid: materialized for a CLAIM, a replayed backlog beyond the snapshot is parked until hydration ends (onHydrationEnd; a microtask when the document's pass is over). The claim trusts the server markup, which shows the snapshot — a text hole is never rewritten during a claim — so a trace already past the markup left the DOM diverged for good, resident or late. Same treatment hydrateStoreFromAsyncIterable gives its buffered backlog. The frame marks adopt-time args: revive(value, claiming?) -> reviveContainerTraces(value, claiming?) -> materializer(marker, claiming?). - web/frames: an occurrence held on an unresolved ref or unprepared arg mounts with the record it was HELD on (what the server interior was rendered from) and applies a record that replaced it meanwhile (refetch, rebind) as the args change it is — instead of claiming old markup with new args. Pins: test/hydration/container-trace-hold-*.spec.tsx (+ shared helpers). One test.fails pin documents a pre-existing client/server id drift (a keyed sibling after a frame: client adoptBoundary consumes no id, the server's NoHydration owner consumes one), independent of the hold. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent ef61475 commit 9927ddd

10 files changed

Lines changed: 1251 additions & 33 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
"solid-js": patch
3+
"@solidjs/web": patch
4+
---
5+
6+
Make a held (lazily materialized) container-trace fill hydrate like a resident one.
7+
8+
- The container-trace materializer creates its projection under a detached root. Created under the reading owner, a resident materializer consumed one hydration id per trace at t=0 while a late one (no ambient owner) consumed none, so the sibling after a frame hydrated under different keys in the two runs.
9+
- A trace materialized for a claim (a frame's adopt-time mount, at t=0 or late) parks its replayed backlog beyond the snapshot until hydration ends (the same treatment the store-shaped async-iterable hydration gives its buffered backlog). The claim trusts the server's markup, which shows the snapshot; applying the backlog after the claim lets the DOM catch up with a store that moved past the markup — resident or late. A fresh mount folds the whole backlog at once, as before. The frame marks adopt-time args through a new optional second parameter: `FrameHostOptions.revive(value, claiming?)`, forwarded by `reviveContainerTraces(value, claiming?)` to the installed materializer (`setContainerTraceMaterializer((marker, claiming?) => …)`).
10+
- A frame occurrence held on an unresolved ref or an unprepared arg now mounts with the record it was held on (the one the server interior was rendered from) and applies a record that replaced it meanwhile — refetch, address switch — as the args change it is, instead of claiming old markup with new args.

‎packages/solid/src/client/container-trace.ts‎

Lines changed: 69 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
createSignal as coreSignal,
2525
getOwner,
2626
NotReadyError,
27+
runWithOwner,
2728
type Store
2829
} from "@solidjs/signals";
2930
// Read back from the main entry (external: the app's one instance, whose
@@ -32,8 +33,9 @@ import {
3233
// entry (which has none of these) stays inert until something calls it.
3334
import * as core from "solid-js";
3435

35-
// The three seams, typed here because the main entry marks them `@internal`
36-
// and strips them from its declarations (the same arrangement as
36+
// The seams, typed here because the main entry marks them `@internal`
37+
// and strips them from its declarations — `sharedConfig` is public, listed
38+
// for the same member-read discipline (the same arrangement as
3739
// src/internal.ts). Each is a member read ON THE NAMESPACE BINDING at the
3840
// call — never `const x = core` — so the bundler rewrites them to named
3941
// imports of the one `solid-js` instance; a namespace that escapes into a
@@ -48,6 +50,7 @@ interface Seams {
4850
): T;
4951
applyPatches(target: any, patches: any[]): void;
5052
forwardIteratorReturn(it: any, value?: any): any;
53+
sharedConfig: { onHydrationEnd?: (callback: () => void) => void };
5154
}
5255
const applyPatches = (target: any, patches: any[]) =>
5356
(core as unknown as Seams).applyPatches(target, patches);
@@ -58,6 +61,24 @@ const forwardIteratorReturn = (it: any, value?: any) =>
5861
const createProjection = (fn: (draft: any) => any, seed: any): Store<any> =>
5962
(core as unknown as Seams).withStoreHydration(coreProjection as any, fn, seed);
6063

64+
/**
65+
* A root with NO parent. Materialization runs at arg-read, under whatever
66+
* owner is reading — during hydration an id-carrying one — and a root
67+
* created there inherits the next child id, shifting every key the reader
68+
* mints after it. A resident materializer at t=0 thus consumed one root id
69+
* per trace while a late one (no ambient owner) consumed none, and the
70+
* sibling after the frame hydrated under different keys in the two runs.
71+
* The store is shared and memoized per trace; it belongs to no reader's
72+
* id space.
73+
*/
74+
const detachedRoot = <T>(init: () => T): T => runWithOwner(null, () => coreRoot(init))!;
75+
76+
/** Run `callback` once hydration has completed — now (a microtask) when none is in progress. */
77+
function afterHydration(callback: () => void) {
78+
const onHydrationEnd = (core as unknown as Seams).sharedConfig.onHydrationEnd;
79+
onHydrationEnd ? onHydrationEnd(callback) : queueMicrotask(callback);
80+
}
81+
6182
/**
6283
* Materialize a container TRACE — snapshot then patch batches, the
6384
* continuation protocol a server projection serializes as when it crosses a
@@ -66,21 +87,41 @@ const createProjection = (fn: (draft: any) => any, seed: any): Store<any> =>
6687
* the server value did: not-ready until the snapshot lands, then a
6788
* read-only store the batches keep updating, done when the trace ends.
6889
*
69-
* Created under its own root: revival can run inside a render effect's owner,
70-
* and the store is memoized per trace (see the plugin's WeakMap) — a store
71-
* owned by its first reader would be disposed by that reader's re-render
72-
* while other readers still hold it. Consumption is pull-driven and the trace
73-
* is response-bounded, so the projection settles on its own; GC collects the
74-
* pair with the trace.
90+
* Created under a detached root (see `detachedRoot`): revival can run inside
91+
* a render effect's owner, and the store is memoized per trace (see the
92+
* plugin's WeakMap) — a store owned by its first reader would be disposed by
93+
* that reader's re-render while other readers still hold it, and one rooted
94+
* under it would take a hydration id from it. Consumption is pull-driven and
95+
* the trace is response-bounded, so the projection settles on its own; GC
96+
* collects the pair with the trace.
97+
*
98+
* First READ during a claim (the document's hydration pass, or a frame
99+
* fill's scoped late claim), a replayed backlog beyond the snapshot is
100+
* PARKED until hydration ends (`onHydrationEnd`; the next microtask when the
101+
* document's pass is already over). The snapshot is the state the server's
102+
* markup shows; the claim renders the fill against that markup and trusts
103+
* it — a text hole is never rewritten during a claim — so a store already
104+
* past the markup left the DOM diverged from it for good (the trace had
105+
* nothing further to emit). Applied after the claim, the backlog re-runs
106+
* the fill's reads outside hydration and the DOM catches up: the same
107+
* parking solid's store-shaped async-iterable hydration applies to a
108+
* buffered backlog. First read outside a claim (a fresh mount), nothing is
109+
* parked;
110+
* live emissions are unaffected either way (they land after the claim by
111+
* construction). A failure applies in order, after what was queued before
112+
* it, so it, too, waits on a parked backlog.
75113
*
76114
* Consumed by the serialization layer (`@solidjs/web/frames`). Declared, not
77115
* stripped: this entry's whole surface is the seam, and the subpath's
78116
* namespace is what makes it non-public.
79117
*/
80-
export function materializeContainerTrace(marker: {
81-
$tr: AsyncIterable<any> | { __SEROVAL_STREAM__: true };
82-
$ta?: number;
83-
}): Store<any> {
118+
export function materializeContainerTrace(
119+
marker: {
120+
$tr: AsyncIterable<any> | { __SEROVAL_STREAM__: true };
121+
$ta?: number;
122+
},
123+
claiming?: boolean
124+
): Store<any> {
84125
const src = marker.$tr as any;
85126
// Raw seroval stream (the wire shape since the stream-mint protocol):
86127
// `.on()` replays buffered emissions SYNCHRONOUSLY, so a snapshot the
@@ -95,11 +136,15 @@ export function materializeContainerTrace(marker: {
95136
let failed: { error: any } | undefined;
96137
let cursor = 0;
97138
let first = true;
139+
// How far into the queue a compute may apply: everything, except a
140+
// claim's replayed backlog beyond the snapshot, parked until hydration
141+
// ends (see above).
142+
let limit = Infinity;
98143
// Everything lives under the root (see the block comment below):
99144
// materialization runs at arg-read inside a reader's render scope, and
100145
// a version signal owned by that reader would be disposed by its
101146
// re-render while the memoized store lives on.
102-
return coreRoot(() => {
147+
return detachedRoot(() => {
103148
const [version, setVersion] = coreSignal(0);
104149
// Subscribe before creating the projection: the buffered replay runs
105150
// synchronously inside on(), filling the queue the first compute
@@ -123,10 +168,17 @@ export function materializeContainerTrace(marker: {
123168
}
124169
});
125170
live = true;
171+
if (claiming && queue.length > 1) {
172+
limit = 1;
173+
afterHydration(() => {
174+
limit = Infinity;
175+
bump();
176+
});
177+
}
126178
return createProjection(
127179
(draft: any) => {
128180
version();
129-
while (cursor < queue.length) {
181+
while (cursor < queue.length && cursor < limit) {
130182
const value = queue[cursor++];
131183
if (first) {
132184
first = false;
@@ -142,7 +194,8 @@ export function materializeContainerTrace(marker: {
142194
applyPatches(draft, value);
143195
}
144196
}
145-
if (failed) throw failed.error;
197+
// In order: after everything queued before it has applied.
198+
if (failed && cursor === queue.length) throw failed.error;
146199
// Nothing buffered yet (revival raced ahead of the record's data
147200
// script): pending until the snapshot lands, marked on the
148201
// projection's own node — the version bump reruns this compute.
@@ -158,7 +211,7 @@ export function materializeContainerTrace(marker: {
158211
// surfaces as an unhandled error in dev. The root is never disposed —
159212
// the projection settles itself when the trace ends and is collected
160213
// with the store.
161-
return coreRoot(() =>
214+
return detachedRoot(() =>
162215
createProjection(
163216
(draft: any) => ({
164217
[Symbol.asyncIterator]() {

‎packages/web/frames/src/frame-client.ts‎

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ export interface FrameHost {
253253
/** `frameId` is the resolving frame's id — route to its stream's table. */
254254
resolve(ref: { $ref: string }, frameId?: string): unknown;
255255
/** See FrameHostOptions.revive. */
256-
revive?(value: unknown): unknown;
256+
revive?(value: unknown, claiming?: boolean): unknown;
257257
/** See FrameHostOptions.isContainer. */
258258
isContainer?(value: unknown): boolean;
259259
/** See FrameHostOptions.prepareArgs. */
@@ -294,8 +294,10 @@ export interface FrameHostOptions {
294294
* neither `{$ref}` nor `{$frame}`) at arg-resolution time. Document-face
295295
* container traces ride this way — inline in the record, revived by the
296296
* integration (`reviveContainerTraces`) into live local containers.
297+
* `claiming` marks the args of an adopt-time mount — the occurrence is
298+
* about to hydrate server markup rendered from these values.
297299
*/
298-
revive?(value: unknown): unknown;
300+
revive?(value: unknown, claiming?: boolean): unknown;
299301
/**
300302
* An async step a record's LITERAL slot args need before `revive` can
301303
* answer — the container-trace materializer loading, for a document-face
@@ -664,7 +666,7 @@ export function createFrameHost(options?: FrameHostOptions): FrameHost;
664666
* resolve?: (ref: { $ref: string }) => unknown,
665667
* applyData?: (chunk: object) => void,
666668
* prepareData?: (chunk: object) => Promise<unknown>,
667-
* revive?: (value: unknown) => unknown,
669+
* revive?: (value: unknown, claiming?: boolean) => unknown,
668670
* isContainer?: (value: unknown) => boolean,
669671
* prepareArgs?: (args: object) => Promise<unknown> | undefined
670672
* }} [options]
@@ -879,6 +881,12 @@ class FrameImpl {
879881
// The pending re-sync for occurrences held on the host's async arg step
880882
// (FrameHostOptions.prepareArgs — see #argsUnprepared).
881883
#argsRefresh = null;
884+
// Adopt path: the record an unmounted occurrence was first HELD with
885+
// (refs not arrived / args not prepared — see #syncSlots). The adopted
886+
// range's server interior was rendered from that record; should the store
887+
// move on while it waits (a refetch, a rebind), the mount still claims
888+
// with it and the current record applies as the args change it is.
889+
#heldRecords = new Map();
882890
#disposed = false;
883891
// Stable identity so a pending stylesheet holds at most one waiter per
884892
// frame across repeated readiness checks.
@@ -1311,8 +1319,19 @@ class FrameImpl {
13111319
record &&
13121320
record.kind === "slot" &&
13131321
(this.#refsUnresolved(record.args) || this.#argsUnprepared(record.args))
1314-
)
1322+
) {
1323+
// Remember what the adopted interior was rendered from. A hold is
1324+
// the t=0 mount deferred: when it lifts, the mount must do what t=0
1325+
// would have — claim with THIS record — even if a later stream has
1326+
// since replaced it in the store (the mount below falls through to
1327+
// the args-change path for the replacement). A claim with the
1328+
// replacement's args instead would trust markup rendered from the
1329+
// old ones and leave every differing text hole stale: a claim pass
1330+
// never rewrites text.
1331+
if (this.#options.adopt && !this.#mountedSlots.has(occurrence))
1332+
this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, record);
13151333
continue;
1334+
}
13161335
// A mount whose output the morph destroyed (its range was recreated
13171336
// inside a different server parent — ranges only relocate among
13181337
// siblings) is a zombie: remount fresh so content stays correct, even
@@ -1402,7 +1421,19 @@ class FrameImpl {
14021421
// regions yet; discovery is a no-op then, and #resolveArgs creates
14031422
// its entries during the invoke instead.
14041423
if (this.#options.adopt) this.#discoverRegions(occurrence, start);
1405-
const nodes = this.#invokeSlot(occurrence, callback, record, start, this.#options.adopt);
1424+
// A held occurrence mounts with the record it was held on (see the
1425+
// hold above); a current record that differs applies right after,
1426+
// through the mounted path below.
1427+
const held = this.#heldRecords.get(occurrence);
1428+
this.#heldRecords.delete(occurrence);
1429+
const mountRecord = held || record;
1430+
const nodes = this.#invokeSlot(
1431+
occurrence,
1432+
callback,
1433+
mountRecord,
1434+
start,
1435+
this.#options.adopt
1436+
);
14061437
// A data occurrence's nodes are its consuming elements (so the
14071438
// zombie check above sees a morph that replaced them all); its mount
14081439
// never returns nodes to place.
@@ -1425,7 +1456,7 @@ class FrameImpl {
14251456
// large adopted tree).
14261457
if (!this.#options.adopt || nodes) this.#discoverRegions(occurrence, start);
14271458
this.#bindRegions(occurrence);
1428-
continue;
1459+
if (mountRecord === record || !record || record.kind !== "slot") continue;
14291460
}
14301461
// A mounted data occurrence whose CONSUMERS changed — a morph replaced
14311462
// one of its elements, a response added or dropped a bound position
@@ -1569,7 +1600,9 @@ class FrameImpl {
15691600
// already-rendered element from the first render (a client-only
15701601
// toggle can hide/show it at t=0, no re-arming stream needed).
15711602
const props =
1572-
record && record.kind === "slot" ? this.#resolveArgs(occurrence, record.args) : {};
1603+
record && record.kind === "slot"
1604+
? this.#resolveArgs(occurrence, record.args, undefined, adopted)
1605+
: {};
15731606
// Run under the boundary's owner (when the creator provided one): slot
15741607
// content reads the mount point's context (routers, stores) and bounds
15751608
// its lifetime there. The t=0 adopt sync happens to run inside the
@@ -1600,6 +1633,7 @@ class FrameImpl {
16001633
this.#slotUpdaters.delete(key);
16011634
this.#slotRebinders.delete(key);
16021635
this.#slotResolvedRefs.delete(key);
1636+
this.#heldRecords.delete(key);
16031637
this.#removeSlotRecord(key);
16041638
this.#runSlotCleanups(key);
16051639
const regions = this.#slotRegions.get(key);
@@ -1682,7 +1716,7 @@ class FrameImpl {
16821716
return regions;
16831717
}
16841718

1685-
#resolveArgs(slotKey, args, resolve?) {
1719+
#resolveArgs(slotKey, args, resolve?, claiming?) {
16861720
const host = this.#options.host;
16871721
const regions = this.#regionsFor(slotKey);
16881722
const props = {};
@@ -1718,7 +1752,7 @@ class FrameImpl {
17181752
// to revive (document-face container traces arrive as inline
17191753
// literals rather than `{$ref}`s — see reviveContainerTraces). The
17201754
// host hook keeps this module protocol-agnostic.
1721-
props[key] = host && host.revive ? host.revive(value) : value;
1755+
props[key] = host && host.revive ? host.revive(value, claiming) : value;
17221756
}
17231757
}
17241758
return props;

‎packages/web/frames/src/frame-container-plugin.ts‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,9 @@ export function setAsyncIterableSharer(
9292
export function setAsyncIterableSharer(fn) {
9393
state.shareIterable = fn;
9494
} /** Client half: install the reactive core's trace materializer. */
95-
export function setContainerTraceMaterializer(fn: (marker: ContainerTraceMarker) => unknown): void;
95+
export function setContainerTraceMaterializer(
96+
fn: (marker: ContainerTraceMarker, claiming?: boolean) => unknown
97+
): void;
9698

9799
/** Client half: install the reactive core's trace materializer. */
98100
export function setContainerTraceMaterializer(fn) {
@@ -252,10 +254,10 @@ function isShareableIterable(value) {
252254
// across independent revival sites (an eval-face marker read by two
253255
// occurrences, a codec node re-resolved per record — possibly by DIFFERENT
254256
// copies of this module).
255-
function materialize(marker) {
257+
function materialize(marker, claiming) {
256258
let value = state.materialized.get(marker.$tr);
257259
if (value === undefined) {
258-
value = state.materializeTrace(marker);
260+
value = state.materializeTrace(marker, claiming);
259261
state.materialized.set(marker.$tr, value);
260262
if (value !== null && typeof value === "object") state.materializedValues.add(value);
261263
}
@@ -292,23 +294,26 @@ export function isContainerTraceMarker(value) {
292294
const tr = value.$tr;
293295
return tr.__SEROVAL_STREAM__ === true || typeof tr[Symbol.asyncIterator] === "function";
294296
} /** Deep-revive trace markers inside a decoded value (document-face slot args). */
295-
export function reviveContainerTraces(value: unknown): unknown;
297+
export function reviveContainerTraces(value: unknown, claiming?: boolean): unknown;
296298

297299
/**
298300
* Deep-revive trace markers inside a decoded value (document-face slot args
299301
* arrive as literals, and a container can sit at ANY depth of an argument —
300302
* `{ filters: { user: proj } }` is one arg). In-place: args records are
301303
* per-record decoded copies. No-op until the materializer is installed.
304+
* `claiming`: the value's reader is about to hydrate server markup rendered
305+
* from it (a frame's adopt-time mount) — the materializer holds a trace's
306+
* backlog beyond the snapshot the markup shows until hydration ends.
302307
*/
303-
export function reviveContainerTraces(value) {
308+
export function reviveContainerTraces(value, claiming) {
304309
if (!state.materializeTrace || value == null || typeof value !== "object") return value;
305-
if (isContainerTraceMarker(value)) return materialize(value);
310+
if (isContainerTraceMarker(value)) return materialize(value, claiming);
306311
// Plain containers only — anything exotic was either produced by the
307312
// codec plugin (already materialized) or is an app value not ours to walk.
308313
if (Array.isArray(value)) {
309-
for (let i = 0; i < value.length; i++) value[i] = reviveContainerTraces(value[i]);
314+
for (let i = 0; i < value.length; i++) value[i] = reviveContainerTraces(value[i], claiming);
310315
} else if (Object.getPrototypeOf(value) === Object.prototype) {
311-
for (const key of Object.keys(value)) value[key] = reviveContainerTraces(value[key]);
316+
for (const key of Object.keys(value)) value[key] = reviveContainerTraces(value[key], claiming);
312317
}
313318
return value;
314319
}

0 commit comments

Comments
 (0)