Skip to content

Commit 06db679

Browse files
fix(solid,web): unified For — external audit round (ownership, dynamic rows, anchors, guards, hydration text)
Responds to the 2026-09-07 external audit of #3281 (8 P1 / 4 P2). P1-2 (the substantive one): rows whose top level resolves to a function — a component returning <Show>/<Dynamic>/a conditional, a memo, a fragment with accessor leaves — no longer demote. They are DYNAMIC rows: built once (owned, untracked) and resolved by the slot's own compute, tracked — the same `flatten` read classic's insert effect performs for such rows, moved into the slot. No per-row effect, no marker nodes (mount cost: one field), no shape demotion, so user row code never runs twice and a late dynamic row never remounts its siblings. A flip splices only that row's range, reusing positional text nodes with a `.data` write. NotReady from a row's resolution parks the built plan; the retry reuses the rows (mapArray parity — rebuilding would re-fire per-row async and never settle). P1-1: slot owner under For's creation owner (`$for.owner`), where mapArray's internal owner lives; the insert cleanup disposes it explicitly. P1-3: list end anchor is the committed tail's nextSibling while it is still ours (classic contiguity) — appends stay before a foreign trailing node. P1-4: removes are parent-guarded; migrated row nodes are left alone. P1-5: buildParts disposes the row owner when the row fn throws. P1-6: the hydrating fill commit adopts positional server text nodes for primitive rows (node identity survives; zero-write). P1-7 is moot: with no shape demote, nothing can demote MID-fill (duplicates are only detectable on a later partial op; a non-array subject demotes before any row is built) — the claim record/restore stack is deleted. P1-8 disputed: `map.length > 1` is mapArray's own index-arity contract. P2-1: fresh-key duplicates are caught via the existing probe map (-1). P2-4: the slot's node type is opaque (`SlotNode = object`) — core declares no DOM types; the one direct DOM read moved behind `ops.owns`. Tests: for.unified.audit.spec (one per finding, classic as oracle); the former demote-mid-fill hydration scenarios become dynamic-row scenarios (engaged, zero demotes, server nodes); text-row hydration pins text-node identity; text mismatches now report the repair honestly. Size: +~850 B on For-bearing bundles (structural: resolution, parked-plan reuse, anchors, guards), +61 B floor (four domOps methods). Chrome A/B interleaved pre/post on jfb-signal and jfb-deep reorder: parity. Co-authored-by: Cursor <[email protected]>
1 parent 57e5f53 commit 06db679

15 files changed

Lines changed: 1250 additions & 481 deletions

‎.changeset/unified-for-slot.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66

77
Unified For: keyed `<For>` is driven by one persistent slot that owns both row bookkeeping and DOM placement — an intrusive row chain + incremental key map updated by a prefix/suffix/LIS pass inside an ordinary two-phase render effect — replacing the mapArray + reconcileArrays double pass. Structural operations (swap, reorder, insert, remove) run 1.2–7x faster across jfb and uibench; creation and clear stay at parity via flat-mode first fills (parallel arrays, structure materializes lazily on the first partial structural op).
88

9-
Default-on with zero new API and zero compiler involvement: the slot rides For's own module graph (`$for.impl`), web's insert engages it with its renderer-ops singleton, and the slot algorithm tree-shakes out of apps without For (~2.1 KB rides For-bearing bundles; ~0.3 KB of engagement seam in `insert` — the `$for` guards, renderer ops, and hole hand-off — is retained by every web bundle; hydration adds ~0.8 KB to hydrating bundles only). A For passed through a component's `{props.children}` engages too — the hole seam hands the wrapper's hole to the slot, tears it down cleanly when the children change, and routes a post-engage demote back through the hosting effect's classic path. Bulk-clear fast paths honor classic's ownership rules — `null` markers (trailing child with preceding siblings) and streamed foreign nodes are never wiped. Empty-rendering rows hold their position with a placeholder instead of demoting.
9+
Default-on with zero new API and zero compiler involvement: the slot rides For's own module graph (`$for.impl`), web's insert engages it with its renderer-ops singleton, and the slot algorithm tree-shakes out of apps without For (~2.1 KB rides For-bearing bundles; ~0.3 KB of engagement seam in `insert` — the `$for` guards, renderer ops, and hole hand-off — is retained by every web bundle; hydration adds ~0.8 KB to hydrating bundles only). A For passed through a component's `{props.children}` engages too — the hole seam hands the wrapper's hole to the slot, tears it down cleanly when the children change, and routes a post-engage demote back through the hosting effect's classic path. Bulk-clear fast paths honor classic's ownership rules — `null` markers (trailing child with preceding siblings) and streamed foreign nodes are never wiped — and the list end stays contiguous (fresh rows append before a foreign node that follows the list, as classic's `tail.nextSibling` rule does); removes only detach nodes still under the list's parent (a row node the user migrated elsewhere is left alone). Empty-rendering rows hold their position with a placeholder instead of demoting.
1010

11-
Hydration: lists engage during hydration and claim the server rows themselves — whole-parent holes and comment-bounded anchored holes alike (the hydrating client resolves anchored holes to their `<!--/-->` marker with the bounded region). The slot's row parent takes the same id classic's mapArray owner spends (For peeks it via an `enableHydration()`-installed hook; mapArray gains an internal `lazy` option so the classic pass no longer claims first), so rows mint identical hydration keys; claims are recorded so a demote mid-fill hands them back and classic's re-run claims the same nodes; the fill commit reconciles against the region only on server/client mismatch. All hydration behavior lives in a module installed by `enableHydration()` — CSR bundles shake it.
11+
Rows live under the `<For>`'s creation owner (mapArray parity): context, boundaries and lifetime follow where the list was written, not where its accessor was inserted; the inserting scope's cleanup disposes them. Rows whose top level resolves to a function — a component returning `<Show>`/`<Dynamic>`/a conditional, a memo, a fragment with accessor children — are DYNAMIC rows: built once (owned, untracked) and then resolved by the slot's own compute, tracked, exactly the `flatten` read classic's insert effect performs for them. No per-row effect, no marker nodes, no shape demotion — so user row code never runs twice and a late dynamic row never remounts its siblings; a flip splices only that row's range, reusing positional text nodes with a `.data` write. A NotReady thrown from a row's resolution parks the built plan and the retry reuses the rows (classic keeps rows in mapArray across an insert-effect NotReady). A row that throws during its own build disposes its owner before the error rides the boundary.
1212

13-
Declines to classic mapArray: key functions, duplicate keys, dynamic top-level rows, `fallback`, non-array subjects; post-engage contract exits demote to classic under the original owner.
13+
Hydration: lists engage during hydration and claim the server rows themselves — whole-parent holes and comment-bounded anchored holes alike (the hydrating client resolves anchored holes to their `<!--/-->` marker with the bounded region). The slot's row parent takes the same id classic's mapArray owner spends (For peeks it via an `enableHydration()`-installed hook; mapArray gains an internal `lazy` option so the classic pass no longer claims first), so rows mint identical hydration keys; primitive rows adopt the server's positional text nodes (node identity survives); the fill commit reconciles against the region only on server/client mismatch and reports the repair once in dev. Nothing can demote mid-fill (row shapes never demote; duplicates are only detectable on a later partial op; a non-array subject demotes before any row is built), so claims never need handing back. All hydration behavior lives in a module installed by `enableHydration()` — CSR bundles shake it.
14+
15+
Declines to classic mapArray: key functions, `fallback`, rows taking the index parameter (arity ≥ 2 — the same `Function.length` contract mapArray itself uses to decide whether to mint index signals); duplicate identity keys and non-array subjects demote to classic post-engage under the original owner.

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,10 @@ export function For<T extends readonly any[], U extends SolidElement>(props: {
135135
each: () => props.each,
136136
row: props.children,
137137
keyed: props.keyed,
138+
// For's CREATION owner: the slot's rows live under it (mapArray's own
139+
// parent), so context/boundaries/lifetime follow the <For>'s source
140+
// position, not wherever the accessor is later inserted.
141+
owner,
138142
// The slot rides For's OWN module graph: apps without For tree-shake
139143
// it; a renderer's insert() engages it by passing its SlotOps.
140144
impl: unifiedForSlot,

‎packages/solid/src/client/for-slot-hydration.ts‎

Lines changed: 50 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -10,32 +10,20 @@
1010
* region as `initial`). Row templates then CLAIM server nodes
1111
* exactly as classic's would — the slot's row parent takes the SAME id
1212
* classic's mapArray owner spends, so rows mint identical hydration keys.
13-
* Claims are RECORDED so a demote mid-fill hands them back: classic's re-run
14-
* mints the same ids and claims the same nodes (never a stranded claim).
15-
* The fill commit mutates only on MISMATCH (leftover server rows removed,
16-
* key-missed fresh rows inserted); the normal case is zero DOM writes.
13+
* Nothing can demote mid-fill (see Slot.hyd), so claims are never handed
14+
* back. The fill commit mutates only on MISMATCH (leftover server rows
15+
* removed, key-missed fresh rows inserted); primitive rows ADOPT the
16+
* server's text nodes, so the normal case is zero DOM writes.
1717
*/
1818
import { sharedConfig } from "./hydration.js";
1919
import { IS_DEV } from "./core.js";
20-
import { installSlotHydration, type FlatPlan, type Slot } from "./for-slot.js";
21-
22-
/** RECORDING STACK. Nested lists hydrate INSIDE an outer row's build (row →
23-
* inner insert → inner engage → inner fill, all synchronous), so recording
24-
* must nest: the OUTERMOST record() installs the registry shadow once, every
25-
* active log on the stack receives every deletion, an inner commitFill drops
26-
* only its OWN log, and an outer restore() hands back everything claimed
27-
* beneath it — including nested slots' already-committed claims, which the
28-
* classic re-run's re-engaged nested lists will mint again with the same
29-
* ids. (Per-slot shadows broke both: the inner `finally` tore down the
30-
* outer's shadow, and committed inner claims were in no log at all.) */
31-
const logs: [string, Element][][] = [];
32-
let shadowed = false;
20+
import { installSlotHydration, type FlatPlan, type Slot, type SlotNode } from "./for-slot.js";
3321

3422
const hooks = {
3523
engage(
3624
meta: any,
37-
marker: Node | null | undefined,
38-
region: Node[] | undefined
25+
marker: SlotNode | null | undefined,
26+
region: SlotNode[] | undefined
3927
): { id: string } | null | false {
4028
if (!sharedConfig.hydrating) return false;
4129
// Whole-parent (marker undefined) and comment-bounded holes (the
@@ -46,89 +34,71 @@ const hooks = {
4634
return { id: meta.hid };
4735
},
4836

49-
record<T>(slot: Slot, fn: () => T): T {
50-
const reg = sharedConfig.registry as Map<string, Element> | undefined;
51-
if (!reg) return fn();
52-
logs.push((slot.hydLog ??= []));
53-
const installed = !shadowed;
54-
if (installed) {
55-
shadowed = true;
56-
const proto = Map.prototype.delete;
57-
(reg as any).delete = function (this: Map<string, Element>, key: string): boolean {
58-
const node = this.get(key);
59-
if (node !== undefined) for (let i = 0; i < logs.length; i++) logs[i].push([key, node]);
60-
return proto.call(this, key);
61-
};
62-
}
63-
try {
64-
return fn();
65-
} finally {
66-
logs.pop();
67-
if (installed) {
68-
delete (reg as any).delete; // back to the prototype method
69-
shadowed = false;
70-
}
71-
}
72-
},
73-
74-
restore(slot: Slot): void {
75-
// Nothing was placed (compute never writes DOM); only registry keys were
76-
// consumed. Hand them all back, and un-complete the nodes.
77-
slot.hyd = false;
78-
const reg = sharedConfig.registry as Map<string, Element> | undefined;
79-
const log = slot.hydLog;
80-
if (reg && log !== null) {
81-
for (let i = 0; i < log.length; i++) {
82-
reg.set(log[i][0], log[i][1]);
83-
(sharedConfig as any).completed?.delete(log[i][1]);
84-
}
85-
}
86-
slot.hydLog = null;
87-
},
88-
8937
commitFill(slot: Slot, fp: FlatPlan): void {
90-
// Past this point the slot owns the rows for good: drop the claim log.
9138
slot.hyd = false;
92-
slot.hydLog = null;
9339
const ops = slot.ops;
40+
// This module IS the web hydration binding: nodes are DOM nodes here.
41+
const parent = slot.parent as Node;
42+
const region = slot.region as Node[];
43+
const nodes = fp.nodes as (Node | Node[])[];
44+
// Primitive rows: ADOPT the positional server text node (classic's
45+
// normalizeIncomingArray rule) — zero-write hydration and node identity
46+
// for text rows (pre-hydration edits/selection survive). Rows and region
47+
// walk in lockstep, skipping the server's separator comments; the walk
48+
// stops at the first misaligned element (a mismatch — repaired below).
49+
let cursor = 0;
50+
adopt: for (let i = 0; i < nodes.length; i++) {
51+
const nd = nodes[i];
52+
const arr = Array.isArray(nd) ? nd : null;
53+
const n = arr !== null ? arr.length : 1;
54+
for (let k = 0; k < n; k++) {
55+
const c = arr !== null ? arr[k] : (nd as Node);
56+
let s = region[cursor];
57+
while (s !== undefined && s.nodeType === 8) s = region[++cursor];
58+
if (s === undefined) break adopt;
59+
cursor++;
60+
if (s === c) continue;
61+
if (c.nodeType !== 3 || s.nodeType !== 3 || ops.contains(parent, c)) break adopt;
62+
if ((s as Text).data !== (c as Text).data) (s as Text).data = (c as Text).data;
63+
if (arr !== null) arr[k] = s;
64+
else nodes[i] = s;
65+
}
66+
}
9467
const ours = new Set<Node>();
95-
for (let i = 0; i < fp.nodes.length; i++) {
96-
const nd = fp.nodes[i];
68+
for (let i = 0; i < nodes.length; i++) {
69+
const nd = nodes[i];
9770
if (Array.isArray(nd)) for (const n of nd) ours.add(n);
9871
else ours.add(nd);
9972
}
10073
// Leftovers: server rows the client no longer has, separator comments.
10174
let removed = 0;
10275
let inserted = 0;
103-
const region = slot.region!;
10476
for (let i = 0; i < region.length; i++)
105-
if (!ours.has(region[i]) && ops.contains(slot.parent, region[i])) {
77+
if (!ours.has(region[i]) && ops.contains(parent, region[i])) {
10678
ops.remove(region[i]);
107-
// Element rows only: primitive rows currently re-create their text
108-
// node (fresh text swaps in for the server's — correct DOM, not a
109-
// mismatch). Adopting server text nodes for primitive rows is the
110-
// follow-up that makes that path zero-write too.
111-
if ((region[i] as any).nodeType === 1) removed++;
79+
// Separator comments are not rows; text leftovers past the adoption
80+
// walk are (a shorter client list).
81+
if (region[i].nodeType !== 8) removed++;
11282
}
11383
// Fresh rows (template key-missed → detached; the runtime already
11484
// warned) are inserted at their position, back to front so anchors are
11585
// always attached. The list ends at the hole's end marker (or the
11686
// parent's end for whole-parent holes).
117-
let anchor: Node | null = slot.end;
118-
for (let i = fp.nodes.length - 1; i >= 0; i--) {
119-
const nd = fp.nodes[i];
87+
let anchor: Node | null = slot.end as Node | null;
88+
for (let i = nodes.length - 1; i >= 0; i--) {
89+
const nd = nodes[i];
12090
if (Array.isArray(nd)) {
12191
for (let k = nd.length - 1; k >= 0; k--) {
122-
if (!ops.contains(slot.parent, nd[k])) {
123-
ops.insert(slot.parent, nd[k], anchor);
124-
if ((nd[k] as any).nodeType === 1) inserted++;
92+
if (!ops.contains(parent, nd[k])) {
93+
ops.insert(parent, nd[k], anchor);
94+
inserted++;
12595
}
12696
anchor = nd[k];
12797
}
12898
} else {
129-
if (!ops.contains(slot.parent, nd)) {
130-
ops.insert(slot.parent, nd, anchor);
131-
if ((nd as any).nodeType === 1) inserted++;
99+
if (!ops.contains(parent, nd)) {
100+
ops.insert(parent, nd, anchor);
101+
inserted++;
132102
}
133103
anchor = nd;
134104
}
@@ -143,7 +113,7 @@ const hooks = {
143113
`The DOM was repaired, but server and client should render the same list.`
144114
);
145115
slot.region = undefined;
146-
slot.flat = { items: fp.items, owners: fp.owners, nodes: fp.nodes };
116+
slot.flat = { items: fp.items, owners: fp.owners, nodes: fp.nodes, fns: fp.fns };
147117
slot.size = fp.len;
148118
}
149119
};

0 commit comments

Comments
 (0)