Skip to content

Commit 78eaf88

Browse files
ryansolidclaude
andauthored
fix(store): a returned optimistic guess is the keyed diff; landings keep keyed rows while guesses are out (#4737, #4738, #4739) (#4740)
* fix(store): a returned optimistic guess is the keyed diff; a landing keeps keyed rows while guesses are out (#4737, #4738, #4739) A setter that returns a new array on an optimistic family is now written into the draft as the keyed diff (a same-key row recurses into its own draft), so it makes the writes the field edit would: one write per changed row, never an arrangement guess on the list (S-59). Before, the return became a list guess that list readers entered: a guess made during its refresh waited for that refresh (#4739), and the refresh's failure never reached Errored (#4737). While guesses are out, the derive's new object under a keyed row's key is paired with that row's target, not only a guessed row's. A row whose guess settled lost its target at the next landing, so a later guess went to a row the screen no longer showed (#4738). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_0117BoWNSSgtemsSYsaX2hXE * size: raise every-store app cap for #4740 (34.30 KB, accepted) Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_0117BoWNSSgtemsSYsaX2hXE --------- Co-authored-by: Claude <[email protected]>
1 parent 083a0bd commit 78eaf88

6 files changed

Lines changed: 342 additions & 11 deletions

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+
`createOptimisticStore`: a setter that returns a new array is written as the keyed diff of what it changed, so it reads the same at every frame as the equivalent field write (#4737, #4739). While guesses are out, a landing keeps every keyed row's proxy, so a row whose earlier guess settled can be guessed again and shows (#4738).

‎packages/signals/docs/RULES-INDEX.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ Status legend: **live** stated and standing · **ruled** carries an explicit rul
3939
| R (PJ) | 37 | 2 | 5 | 32 |
4040
| R (RS) | 38 | 0 | 2 | 36 |
4141
| § | 24 | 14 | 11 | 7 |
42-
| S | 59 | 16 | 19 | 35 |
42+
| S | 59 | 17 | 19 | 34 |
4343

4444
## Unresolved citations
4545

@@ -529,4 +529,4 @@ Status legend: **live** stated and standing · **ruled** carries an explicit rul
529529
| S-56 | executable, standing | `docs/SCENARIOS.md:1488` | dev.ts×1 | createOptimistic.test.ts×1 superseded-before-first-commit.test.ts×2 uninitialized-visibility.test.ts×2 visibility-oracle.states.ts×3 | [executable, standing] A guess before the first answer is the newest value the node has produced: it shows, and the first answer judges it — F-11, D-22, D-2 |
530530
| S-57 | executable, standing | `docs/SCENARIOS.md:1513` | core.ts×1 lanes.ts×3 scheduler.ts×1 verdict.ts×1 | — | [executable, standing] A change whose derivation became a guess's lane work holds on that flight, and reveals with the lane — F-2, F-1, F-6 |
531531
| S-58 | executable, standing | `docs/SCENARIOS.md:1561` | core.ts×4 lanes.ts×1 scheduler.ts×1 | zombie-errored-retry-4405.test.ts×2 | [executable, standing] A display-ahead gate is the same mainline mount with any number of memos between the probe and the branch — D-25, F-1 (#4708, #4405) |
532-
| S-59 | prose | `docs/SCENARIOS.md:1684` | — | — | [prose] A store guess's slot is the point of write: a whole-array rewrite is the rows it changed — D-33, F-11, D-41 |
532+
| S-59 | prose | `docs/SCENARIOS.md:1684` | store.ts×1 | — | [prose] A store guess's slot is the point of write: a whole-array rewrite is the rows it changed — D-33, F-11, D-41 |

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

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -751,7 +751,8 @@ function foldedRead(c: Computed<any> | null, el: Signal<any> | Computed<any>): u
751751
* reconciles the new object at its slot — in a keyed list, the one with
752752
* the row's key — exactly as a returned landing would: rows match by key,
753753
* a guessed row keeps its target, and its leaves are judged against their
754-
* guesses. Rows nothing guessed are left as the draft wrote them. */
754+
* guesses. With no guess out, rows nothing guessed are left as the draft
755+
* wrote them. */
755756
function pairRows(t: StoreTarget, pb: Record<PropertyKey, any>): void {
756757
const keyFn = t._fam!.key;
757758
for (let c of t._fam!._overlaid ?? []) {
@@ -766,6 +767,24 @@ function pairRows(t: StoreTarget, pb: Record<PropertyKey, any>): void {
766767
// (pairing it would alias the two).
767768
if (isWrappable(nv) && !lookupTarget(nv, t._fam)) reconcileState(nv, c.px, keyFn, true);
768769
}
770+
// While guesses are out, every row of a keyed list keeps its target under
771+
// the derive's new object with its key, not only a guessed one (#4738): a
772+
// row whose guess settled can be guessed again, and the setter writes the
773+
// committed row's target — a landing must not show a new one in its place.
774+
if (keyFn && Array.isArray(pb) && t._fam!._overlaid?.size) {
775+
let byKey: Map<unknown, any> | null = null;
776+
for (const ov of committed(t) as any[]) {
777+
const rt = isWrappable(ov) ? lookupTarget(ov, t._fam) : undefined;
778+
if (rt === undefined) continue;
779+
if (byKey === null) {
780+
byKey = new Map();
781+
for (const r of pb) if (isWrappable(r)) byKey.set(keyFn(r), r);
782+
}
783+
const k = keyFn(ov);
784+
const nv = k === undefined ? undefined : byKey.get(k);
785+
if (nv !== undefined && !lookupTarget(nv, t._fam)) reconcileState(nv, rt.px, keyFn, true);
786+
}
787+
}
769788
}
770789

771790
installOptHooks({

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

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2581,6 +2581,22 @@ export function storeSetter<T>(proxy: T, fn: (draft: T) => T | void, guard = tru
25812581
// inside a projection derive) must keep tracking — they are the derive's
25822582
// dependencies.
25832583
result = fn(proxy);
2584+
// A returned replacement on an optimistic family is a user's edit, and
2585+
// its slot is the point of write (S-59): written into the draft as the
2586+
// keyed diff — a same-key row recurses into its own draft — so it makes
2587+
// the writes the field edit would, and the exit below notifies them.
2588+
if (
2589+
optHooks !== null &&
2590+
guard &&
2591+
target.o &&
2592+
!writeOverride &&
2593+
result !== undefined &&
2594+
result !== proxy &&
2595+
isWrappable(result)
2596+
) {
2597+
optHooks.reconcile(proxy, unwrapValue(result), target._fam?.key ?? null);
2598+
result = undefined;
2599+
}
25842600
} finally {
25852601
writing--;
25862602
writeScopes = prevScopes;
@@ -2600,12 +2616,9 @@ export function storeSetter<T>(proxy: T, fn: (draft: T) => T | void, guard = tru
26002616
// side effects before its invalid-cleanup throw) and before adoption.
26012617
if (__DEV__ && guard) devGuardStoreSetterResult(result);
26022618
if (result !== undefined && result !== proxy && isWrappable(result)) {
2603-
// A returned replacement: on an optimistic family a user's is itself an
2604-
// optimistic edit — diffed against the view as guesses (`next` parity);
2605-
// otherwise it is adopted as the incoming truth.
2606-
if (optHooks !== null && guard && target.o && !writeOverride)
2607-
optHooks.writes(target, unwrapValue(result));
2608-
else adoptPB(target, unwrapValue(result));
2619+
// A returned replacement off the optimistic path is adopted as the
2620+
// incoming truth.
2621+
adoptPB(target, unwrapValue(result));
26092622
}
26102623
// A34 (3), #3612 — the derived store's twin of `setMemo`: a user write to
26112624
// a derivation another transaction holds is nobody's proposal; it becomes
Lines changed: 293 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,293 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
* @vitest-environment jsdom
4+
*/
5+
// #4737, #4738, #4739: a keyed `createOptimisticStore`'s guess reads the same
6+
// at every frame however the setter writes it (S-59: a returned top-level
7+
// array with the same keys is one write per index that differs, like the
8+
// field write), and a guess shows from the flush that carries it (D-33).
9+
import { expect, test } from "vitest";
10+
import {
11+
Loading,
12+
Errored,
13+
For,
14+
action,
15+
createOptimisticStore,
16+
createMemo,
17+
createSignal,
18+
flush,
19+
refresh
20+
} from "solid-js";
21+
import { render } from "../src/index.js";
22+
23+
const tick = async () => {
24+
for (let i = 0; i < 4; i++) {
25+
await new Promise(r => setTimeout(r, 0));
26+
flush();
27+
}
28+
};
29+
const asker = () => {
30+
const asks: { key: string; res: (v: any) => void; rej: (e: any) => void }[] = [];
31+
const ask = (key: string) => new Promise<any>((res, rej) => asks.push({ key, res, rej }));
32+
const pick = (key: string) =>
33+
asks.splice(
34+
asks.findIndex(a => a.key === key),
35+
1
36+
)[0];
37+
return { ask, pick };
38+
};
39+
40+
for (const form of ["field", "return"] as const)
41+
test(`#4737 a failed refresh after a ${form} guess shows its error`, async () => {
42+
const { ask, pick } = asker();
43+
const c = document.body.appendChild(document.createElement("div"));
44+
let assign!: (id: number) => any;
45+
const server = [
46+
{ id: 1, a: "-" },
47+
{ id: 3, a: "-" }
48+
];
49+
const dispose = render(() => {
50+
const [filter] = createSignal("open");
51+
const list = createMemo(() => (filter(), ask("fetch")));
52+
const [rows, set] = createOptimisticStore(
53+
(d: any[]) => {
54+
const r = (list() as any[]).map(x => ({ ...x }));
55+
d.length = r.length;
56+
r.forEach((x, i) => {
57+
d[i] = x;
58+
});
59+
},
60+
[] as any[],
61+
{ key: "id" }
62+
);
63+
assign = action(function* (id: number) {
64+
set((d: any) => {
65+
if (form === "return") return d.map((r: any) => (r.id === id ? { ...r, a: "guest" } : r));
66+
d.find((x: any) => x.id === id).a = "guest";
67+
});
68+
yield ask(`assign:${id}`);
69+
refresh(list);
70+
refresh(rows);
71+
});
72+
return (
73+
<Loading on={filter()} fallback={<i>loading</i>}>
74+
<Errored fallback={(e: any) => <b>list error: {e().message}</b>}>
75+
<For each={rows}>
76+
{(r: any) => (
77+
<i>
78+
[#{r.id} {r.a}]
79+
</i>
80+
)}
81+
</For>
82+
</Errored>
83+
</Loading>
84+
);
85+
}, c);
86+
await tick();
87+
pick("fetch").res(server.map(x => ({ ...x })));
88+
await tick();
89+
expect(c.textContent).toBe("[#1 -][#3 -]");
90+
assign(1);
91+
await tick();
92+
expect(c.textContent).toBe("[#1 guest][#3 -]");
93+
server[0].a = "guest";
94+
pick("assign:1").res({});
95+
await tick();
96+
expect(c.textContent).toBe("[#1 guest][#3 -]");
97+
pick("fetch").rej(new Error("down"));
98+
await tick();
99+
expect(c.textContent).toBe("list error: down");
100+
dispose();
101+
c.remove();
102+
});
103+
104+
for (const withRename of [true, false])
105+
test(`#4738 a field guess shows while other guesses on the store are out (rename ${withRename})`, async () => {
106+
const { ask, pick } = asker();
107+
const c = document.body.appendChild(document.createElement("div"));
108+
let close!: (id: number) => any,
109+
assign!: (id: number, who: string) => any,
110+
rename!: (id: number, t: string) => any;
111+
const dispose = render(() => {
112+
const server = createMemo(() => ask("fetch"));
113+
const [renames, setRenames] = createSignal<any[]>([]);
114+
const [assigns, setAssigns] = createSignal<any[]>([]);
115+
const [closedIds, setClosed] = createSignal<number[]>([]);
116+
const [rows, set] = createOptimisticStore(
117+
(d: any[]) => {
118+
const r = (server() as any[]).map(i => ({
119+
id: i.id,
120+
title:
121+
renames()
122+
.filter(x => x.id === i.id)
123+
.at(-1)?.title ?? i.title,
124+
a:
125+
assigns()
126+
.filter(x => x.id === i.id)
127+
.at(-1)?.a ?? i.a,
128+
gone: closedIds().includes(i.id)
129+
}));
130+
d.length = r.length;
131+
r.forEach((x, i) => {
132+
d[i] = x;
133+
});
134+
},
135+
[] as any[],
136+
{ key: "id" }
137+
);
138+
close = action(function* (id: number) {
139+
const i = rows.findIndex((r: any) => r.id === id);
140+
set((d: any) => {
141+
d[i].gone = true;
142+
});
143+
try {
144+
yield ask(`close:${id}`);
145+
setClosed(cs => [...cs, id]);
146+
} catch {}
147+
});
148+
assign = action(function* (id: number, who: string) {
149+
const i = rows.findIndex((r: any) => r.id === id);
150+
set((d: any) => {
151+
d[i].a = who;
152+
});
153+
try {
154+
yield ask(`assign:${id}`);
155+
setAssigns(as => [...as.filter(a => a.id !== id), { id, a: who }]);
156+
} catch {}
157+
});
158+
rename = action(function* (id: number, t: string) {
159+
const i = rows.findIndex((r: any) => r.id === id);
160+
set((d: any) => {
161+
d[i].title = t;
162+
});
163+
try {
164+
yield ask(`rename:${id}`);
165+
setRenames(rs => [...rs.filter(r => r.id !== id), { id, title: t }]);
166+
} catch {}
167+
});
168+
const visible = createMemo(() => rows.filter((r: any) => !r.gone));
169+
return (
170+
<Loading fallback={<i>loading</i>}>
171+
<For each={visible()}>
172+
{(r: any) => (
173+
<i>
174+
[#{r.id} {r.title} {r.a}]
175+
</i>
176+
)}
177+
</For>
178+
</Loading>
179+
);
180+
}, c);
181+
await tick();
182+
pick("fetch").res([
183+
{ id: 1, title: "A", a: "-" },
184+
{ id: 3, title: "C", a: "-" },
185+
{ id: 4, title: "D", a: "dana" }
186+
]);
187+
await tick();
188+
close(1);
189+
await tick();
190+
close(3);
191+
await tick();
192+
close(4);
193+
await tick();
194+
expect(c.textContent).toBe("");
195+
if (withRename) {
196+
rename(4, "Delta");
197+
await tick();
198+
}
199+
pick("close:3").rej(new Error("declined"));
200+
await tick();
201+
expect(c.textContent).toBe("[#3 C -]");
202+
if (withRename) {
203+
pick("rename:4").res({});
204+
await tick();
205+
}
206+
assign(3, "bob");
207+
await tick();
208+
expect(c.textContent).toBe("[#3 C bob]");
209+
pick("assign:3").res({});
210+
await tick();
211+
expect(c.textContent).toBe("[#3 C bob]");
212+
dispose();
213+
c.remove();
214+
});
215+
216+
for (const [af, form] of [
217+
["field", "field"],
218+
["return", "field"],
219+
["field", "removal"],
220+
["return", "removal"]
221+
] as const)
222+
test(`#4739 ${af} assign, a ${form} close guess made during another action's refresh`, async () => {
223+
const { ask, pick } = asker();
224+
const c = document.body.appendChild(document.createElement("div"));
225+
let assign!: (id: number) => any, close!: (id: number) => any;
226+
const server = [
227+
{ id: 1, a: "-", closed: false },
228+
{ id: 3, a: "-", closed: false },
229+
{ id: 4, a: "dana", closed: false }
230+
];
231+
const dispose = render(() => {
232+
const list = createMemo(() => ask("fetch"));
233+
const [rows, set] = createOptimisticStore(
234+
(d: any[]) => {
235+
const r = (list() as any[]).filter(x => !x.closed).map(x => ({ ...x }));
236+
d.length = r.length;
237+
r.forEach((x, i) => {
238+
d[i] = x;
239+
});
240+
},
241+
[] as any[],
242+
{ key: "id" }
243+
);
244+
assign = action(function* (id: number) {
245+
set((d: any) => {
246+
if (af === "return") return d.map((r: any) => (r.id === id ? { ...r, a: "guest" } : r));
247+
d.find((r: any) => r.id === id).a = "guest";
248+
});
249+
yield ask(`assign:${id}`);
250+
refresh(list);
251+
refresh(rows);
252+
});
253+
close = action(function* (id: number) {
254+
set((d: any) => {
255+
if (form === "removal") return d.filter((r: any) => r.id !== id);
256+
d.find((r: any) => r.id === id).closed = true;
257+
});
258+
yield ask(`close:${id}`);
259+
refresh(list);
260+
refresh(rows);
261+
});
262+
return (
263+
<Loading fallback={<i>loading</i>}>
264+
<Errored fallback={(e: any) => <b>list error: {e().message}</b>}>
265+
<For each={rows.filter((r: any) => !r.closed)}>
266+
{(r: any) => (
267+
<i>
268+
[#{r.id} {r.a}]
269+
</i>
270+
)}
271+
</For>
272+
</Errored>
273+
</Loading>
274+
);
275+
}, c);
276+
await tick();
277+
pick("fetch").res(server.map(x => ({ ...x })));
278+
await tick();
279+
assign(4);
280+
await tick();
281+
expect(c.textContent).toBe("[#1 -][#3 -][#4 guest]");
282+
server[2].a = "guest";
283+
pick("assign:4").res({});
284+
await tick();
285+
close(1);
286+
await tick();
287+
expect(c.textContent).toBe("[#3 -][#4 guest]");
288+
pick("fetch").rej(new Error("down"));
289+
await tick();
290+
expect(c.textContent).toBe("list error: down");
291+
dispose();
292+
c.remove();
293+
});

0 commit comments

Comments
 (0)