Skip to content

Commit a2dff39

Browse files
brenelzryansolid
authored andcommitted
fix(signals): hold a store container write for snapshot-scoped readers (#3950)
A structural store write during hydration's snapshot capture notified the container node through insertSubs without the write-time snapshot a leaf write records in setSignal. In-scope readers of the container, a hydrated <For> among them, re-ran inside the claim and read the snapshot length beside the live items, so a row removed from onSettled rendered as a row for undefined, threw, and halted reactivity. The container now records its pre-write backing like a leaf, so the scope's release re-runs the reader against the live list. Fixes #3950
1 parent bb66b43 commit a2dff39

9 files changed

Lines changed: 219 additions & 1 deletion

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/signals": patch
3+
---
4+
5+
A structural store write during hydration's snapshot capture (a row removed from an array from `onSettled`, by `splice` or `reconcile`) records the container's pre-write backing as its snapshot, the way a leaf write already does. Readers inside the snapshot scope, such as a hydrated `<For>`, are held on the server's list until the scope is released instead of re-running mid-claim against a snapshot `length` and live items, which rendered a row for `undefined`, threw, and halted reactivity (#3950).

‎packages/signals/src/core/core.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1937,7 +1937,7 @@ export function notePromotedWrite(el: Signal<any> | Computed<any>): void {
19371937
* REVEALS — the creation-time arm skips pending computeds for the same
19381938
* reason. Firewall leaves belong to a projection whose compute is the tree's
19391939
* own work, captured (or deliberately not) at creation. */
1940-
function captureWriteSnapshot<T>(el: Signal<T> | Computed<T>, current: T): void {
1940+
export function captureWriteSnapshot<T>(el: Signal<T> | Computed<T>, current: T): void {
19411941
if (
19421942
el._config & CONFIG_NO_SNAPSHOT ||
19431943
(el as Computed<T>)._fn !== undefined ||

‎packages/signals/src/store/store.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import {
4747
STATUS_PENDING
4848
} from "../core/constants.js";
4949
import {
50+
captureWriteSnapshot,
5051
context,
5152
isEqual,
5253
notePromotedWrite,
@@ -55,6 +56,7 @@ import {
5556
REACTIVE_WRITE_IN_OWNED_SCOPE_SIGNAL_MESSAGE,
5657
setSignal,
5758
slotSignal,
59+
snapshotCaptureActive,
5860
stagedRead,
5961
stagedScreen,
6062
strictRead,
@@ -516,6 +518,7 @@ function notifyContainer(k: Signal<any>, pb: Record<PropertyKey, any>): void {
516518
if (k._config & CONFIG_OVERRIDE) setSignal(k, pb);
517519
else {
518520
if (k._config & CONFIG_HELD) joinFuture(txOf(k));
521+
if (snapshotCaptureActive) captureWriteSnapshot(k, k._value);
519522
insertSubs(k);
520523
schedule();
521524
}

‎packages/signals/tests/snapshot.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ import {
88
createStore,
99
flush,
1010
getOwner,
11+
mapArray,
1112
markSnapshotScope,
13+
onSettled,
1214
releaseSnapshotScope,
1315
runWithOwner,
1416
setSnapshotCapture,
@@ -756,6 +758,45 @@ describe("store snapshot support", () => {
756758

757759
expect(target.child?.[meta]).toBe("keep");
758760
});
761+
762+
it("a structural write to a store array during capture is held for scoped readers", () => {
763+
let labels!: () => string[];
764+
let owner!: any;
765+
let runs = 0;
766+
767+
createRoot(() => {
768+
setSnapshotCapture(true);
769+
owner = getOwner()!;
770+
markSnapshotScope(owner);
771+
772+
const [state, setState] = createStore({ items: [{ label: "remove" }, { label: "keep" }] });
773+
labels = mapArray(
774+
() => state.items,
775+
item => {
776+
runs++;
777+
return item.label;
778+
}
779+
);
780+
expect(labels()).toEqual(["remove", "keep"]);
781+
782+
onSettled(() => {
783+
setState(s => {
784+
s.items.splice(0, 1);
785+
});
786+
});
787+
});
788+
flush();
789+
790+
expect(labels()).toEqual(["remove", "keep"]);
791+
expect(runs).toBe(2);
792+
793+
releaseSnapshotScope(owner);
794+
flush();
795+
796+
expect(labels()).toEqual(["keep"]);
797+
expect(runs).toBe(2);
798+
clearSnapshots();
799+
});
759800
});
760801

761802
describe("pending projection skips snapshot capture", () => {
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"shell": "<main _hk=1><template id=\"pl-2\"></template><p _hk=20>pending</p><!--pl-2--></main><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"$B\"]=($R[0]={0:$R[1]=($R[2]=($R[3]=() => {\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,\"2_fr\":$R[4]=($R[5]=$R[3]()).p});(b=>{for(var k in b)_$HY.r[k]=b[k];delete _$HY.r[\"$B\"]})(_$HY.r[\"$B\"]);</script>",
3+
"chunks": [
4+
"<template id=\"2\"><ul _hk=2001><li _hk=200200>remove</li><li _hk=200210>keep</li></ul></template><script>($R[10]=(resolver, data) => {\n\tresolver.s(data);\n\tresolver.p.s = 1;\n\tresolver.p.v = data;\n})($R[2],$R[6]={items:$R[7]=[$R[8]={id:\"a\",label:\"remove\"},$R[9]={id:\"b\",label:\"keep\"}]});$df(\"2\");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,o.replaceWith(n.content),n.remove(),(_$HY.v=_$HY.v||{})[e]=1,_$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[10]($R[5],!0);</script>"
5+
]
6+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"shell": "<main _hk=1><template id=\"pl-2\"></template><p _hk=20>pending</p><!--pl-2--></main><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"$B\"]=($R[0]={0:$R[1]=($R[2]=($R[3]=() => {\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,\"2_fr\":$R[4]=($R[5]=$R[3]()).p});(b=>{for(var k in b)_$HY.r[k]=b[k];delete _$HY.r[\"$B\"]})(_$HY.r[\"$B\"]);</script>",
3+
"chunks": [
4+
"<template id=\"2\"><ul _hk=2001><li _hk=200200>remove</li><li _hk=200210>keep</li></ul></template><script>($R[10]=(resolver, data) => {\n\tresolver.s(data);\n\tresolver.p.s = 1;\n\tresolver.p.v = data;\n})($R[2],$R[6]={items:$R[7]=[$R[8]={id:\"a\",label:\"remove\"},$R[9]={id:\"b\",label:\"keep\"}]});$df(\"2\");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,o.replaceWith(n.content),n.remove(),(_$HY.v=_$HY.v||{})[e]=1,_$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[10]($R[5],!0);</script>"
5+
]
6+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*
4+
* Fixture for solidjs/solid#3950: a streamed `<Loading>` whose content
5+
* renders a store array through `<For>` and, from `onSettled`, removes the
6+
* first row — the "render what the server rendered, then switch to the
7+
* client value" pattern `isHydrating()` documents. Compiled with both
8+
* generates: test/server/onsettled-store-write-3950.gen.spec.tsx writes the
9+
* chunks test/hydration/onsettled-store-write-3950.spec.tsx replays.
10+
*/
11+
import { createStore, For, Loading, onSettled, reconcile } from "solid-js";
12+
13+
type Item = { id: string; label: string };
14+
type State = { items: Item[] };
15+
16+
const sleep = (ms: number) => new Promise<void>(r => setTimeout(r, ms));
17+
18+
function createApp(write: (state: State) => void) {
19+
return function App() {
20+
const [state, setState] = createStore<State>(
21+
async () => {
22+
await sleep(20);
23+
return {
24+
items: [
25+
{ id: "a", label: "remove" },
26+
{ id: "b", label: "keep" }
27+
]
28+
};
29+
},
30+
{ items: [] }
31+
);
32+
function Content() {
33+
onSettled(() => setState(write));
34+
return (
35+
<ul>
36+
<For each={state.items}>{item => <li>{item.label}</li>}</For>
37+
</ul>
38+
);
39+
}
40+
return (
41+
<main>
42+
<Loading fallback={<p>pending</p>}>
43+
<Content />
44+
</Loading>
45+
</main>
46+
);
47+
};
48+
}
49+
50+
export const variants = [
51+
{
52+
name: "onsettled-store-write-3950-splice",
53+
App: createApp(s => {
54+
s.items.splice(0, 1);
55+
})
56+
},
57+
{
58+
name: "onsettled-store-write-3950-reconcile",
59+
App: createApp(s => reconcile({ items: s.items.slice(1) }, "id")(s))
60+
}
61+
] as const;
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
* @vitest-environment jsdom
4+
*
5+
* solidjs/solid#3950: a store write from `onSettled` while hydration still
6+
* holds the snapshot scope removes a row a hydrated `<For>` claimed. The
7+
* list must end on the client value with the removed row gone, with no
8+
* hydration key miss and no halted reactivity. Replays the chunks
9+
* test/server/onsettled-store-write-3950.gen.spec.tsx renders.
10+
*/
11+
import { afterEach, describe, expect, test, vi } from "vitest";
12+
import { readFileSync } from "node:fs";
13+
import { dirname, resolve } from "node:path";
14+
import { fileURLToPath } from "node:url";
15+
import { flush } from "solid-js";
16+
import { hydrate } from "@solidjs/web";
17+
import { variants } from "../harness/onsettled-store-write-3950.jsx";
18+
19+
const artifactsDir = resolve(dirname(fileURLToPath(import.meta.url)), "../harness/__artifacts__");
20+
21+
function loadArtifact(name: string): { shell: string; chunks: string[] } {
22+
return JSON.parse(readFileSync(resolve(artifactsDir, `${name}.json`), "utf-8"));
23+
}
24+
25+
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
26+
27+
function applyChunk(container: HTMLElement, chunk: string, first: boolean) {
28+
const scriptRe = /<script(?:[^>]*)>([\s\S]*?)<\/script>/g;
29+
const scripts = [...chunk.matchAll(scriptRe)].map(m => m[1]);
30+
const stripped = chunk.replace(scriptRe, "");
31+
if (first) container.innerHTML = stripped;
32+
else container.insertAdjacentHTML("beforeend", stripped);
33+
for (const s of scripts) (0, eval)(s);
34+
}
35+
36+
afterEach(async () => {
37+
await sleep(0);
38+
delete (globalThis as any)._$HY;
39+
});
40+
41+
describe("store write from onSettled during hydration of a <For> (#3950)", () => {
42+
for (const variant of variants) {
43+
test(`${variant.name}: the removed row leaves the claimed list`, async () => {
44+
const { shell, chunks } = loadArtifact(variant.name);
45+
(globalThis as any)._$HY = { events: [], completed: new WeakSet(), r: {}, fe() {} };
46+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
47+
const error = vi.spyOn(console, "error").mockImplementation(() => {});
48+
const container = document.createElement("div");
49+
document.body.appendChild(container);
50+
const rows = () => [...container.querySelectorAll("li")].map(li => li.textContent);
51+
52+
applyChunk(container, shell, true);
53+
for (const c of chunks) applyChunk(container, c, false);
54+
expect(rows()).toEqual(["remove", "keep"]);
55+
const kept = container.querySelectorAll("li")[1];
56+
57+
const dispose = hydrate(() => <variant.App />, container);
58+
await vi.waitFor(() => {
59+
flush();
60+
expect(rows()).toEqual(["keep"]);
61+
});
62+
expect(container.querySelector("li")).toBe(kept);
63+
64+
const diagnostics = [...warn.mock.calls, ...error.mock.calls].map(c => String(c[0]));
65+
dispose();
66+
container.remove();
67+
warn.mockRestore();
68+
error.mockRestore();
69+
expect(diagnostics).toEqual([]);
70+
});
71+
}
72+
});
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*
4+
* Server half of test/hydration/onsettled-store-write-3950.spec.tsx: renders
5+
* each variant and writes its shell plus the boundary's chunk.
6+
*/
7+
import { describe, expect, test } from "vitest";
8+
import { variants } from "../harness/onsettled-store-write-3950.jsx";
9+
import { recordStream, writeArtifact } from "./artifact-recorder.js";
10+
11+
const visibleText = (html: string) =>
12+
html.replace(/<script[\s\S]*?<\/script>/g, "").replace(/<[^>]*>/g, "");
13+
14+
describe("store write from onSettled under a streamed Loading (#3950) — server render", () => {
15+
for (const variant of variants) {
16+
test(`${variant.name}: suspends into the shell, streams both rows`, async () => {
17+
const { shell, chunks } = await recordStream(() => <variant.App />);
18+
expect(visibleText(shell)).toBe("pending");
19+
expect(chunks).toHaveLength(1);
20+
expect(visibleText(chunks[0])).toBe("removekeep");
21+
writeArtifact(variant.name, { shell, chunks });
22+
});
23+
}
24+
});

0 commit comments

Comments
 (0)