Skip to content

Commit 17e08c6

Browse files
ryansolidclaude
andcommitted
test: assert the revert and the refetch commit as one frame; reword for #619
On solid-js rc.11 the "#620 never reverts" symptom is fixed upstream (solidjs/solid#3663, #3674): the existing revert tests pass on `next` without the src change. What the change still fixes is that the optimistic overlay released when the inner action's transition committed, before the revalidation refetch landed, so the rows re-rendered against stale query data in between. The new spec drives every fetch and the action through deferreds and records committed DOM frames with a MutationObserver: three rows through `<For>`, an optimistic store write in a solid `action`, and a router `action` that returns an Error, leaves the data unchanged, commits the swap, or commits the swap plus a change the optimistic write did not predict. It asserts the exact frame sequence — [optimistic, truth] with the revert held until the refetch resolves, or [optimistic] alone when the server confirms it. All four fail on `next` src with the torn `b1/0 a0/1 c2/2` frame committed before the refetch, and pass with the fix. Changeset and src comment reworded to describe the atomic commit rather than "never reverts", referencing #619. Co-authored-by: Claude <[email protected]>
1 parent 1226c01 commit 17e08c6

3 files changed

Lines changed: 183 additions & 2 deletions

File tree

‎.changeset/revert-optimistic-on-resolved-action.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"@solidjs/router": patch
33
---
44

5-
Optimistic writes made around a router action now revert when the action resolves without changing the data (returning an `Error`, a value, or nothing). The action's default revalidation used to run after its inner Solid action had finished, outside the transition, so a refetch that returned the same data never released the caller's optimistic overlay. The response is now applied inside the transition (#620).
5+
A router action's default revalidation now runs inside the action's transition, so the refetch and the release of the caller's optimistic writes commit as one frame. The response used to be applied after the inner Solid action had settled: the optimistic overlay released when that action's transition committed while the refetch was still in flight, so the rows re-rendered against stale query data until it landed — a torn frame when the server rejected the change, and a flash away from and back to the optimistic result when it committed the change (#619).

‎src/data/action.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,8 @@ function actionImpl<T extends Array<any>, U = void>(
270270
}
271271
const read = await readResponse(value, error);
272272
yield;
273-
// revalidate inside the transition so it can release optimistic writes (#620)
273+
// Apply inside the transition so the default revalidation's refetch and
274+
// the release of the caller's optimistic writes commit as one frame (#619).
274275
return applyResponse(
275276
read,
276277
router.navigatorFactory(),
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// @vitest-environment jsdom
2+
import { action, createMemo, createOptimisticStore, For, Loading } from "solid-js";
3+
import { render } from "@solidjs/web";
4+
import {
5+
action as routerAction,
6+
createRouter,
7+
memoryHistory,
8+
query,
9+
useAction
10+
} from "../src/index.js";
11+
12+
// A router action's default revalidation must commit together with the
13+
// caller's optimistic overlay release. Before #621 `handleResponse` ran after
14+
// the inner Solid action had settled, so the overlay released when that
15+
// action's transition committed while the refetch it started was still in
16+
// flight: the rows re-rendered against the stale query data in between (#619).
17+
//
18+
// Every fetch and the action itself resolve through deferreds owned by the
19+
// test, and committed frames are recorded from a MutationObserver, so the
20+
// assertions are on the exact sequence of DOM commits, not on timing.
21+
22+
type Card = { id: string; order: number };
23+
24+
function deferred<T>() {
25+
let resolve!: (value: T) => void;
26+
const promise = new Promise<T>(r => (resolve = r));
27+
return { promise, resolve };
28+
}
29+
30+
// Drain microtasks and a few macrotasks so every settled promise has flushed.
31+
const settle = async (turns = 3) => {
32+
for (let i = 0; i < turns; i++) await new Promise(r => setTimeout(r, 0));
33+
};
34+
35+
function observeFrames(root: HTMLElement) {
36+
const frames: string[] = [];
37+
const observer = new MutationObserver(() => frames.push(root.textContent!));
38+
observer.observe(root, { childList: true, characterData: true, subtree: true });
39+
return { frames, disconnect: () => observer.disconnect() };
40+
}
41+
42+
async function textBecomes(root: HTMLElement, text: string) {
43+
for (let i = 0; i < 100 && root.textContent !== text; i++) await settle(1);
44+
expect(root.textContent).toBe(text);
45+
}
46+
47+
function setup(label: string, serverSide: (db: Card[]) => unknown) {
48+
const db: Card[] = [
49+
{ id: "a", order: 0 },
50+
{ id: "b", order: 1 },
51+
{ id: "c", order: 2 }
52+
];
53+
const fetches: ReturnType<typeof deferred<Card[]>>[] = [];
54+
const getCards = query(() => {
55+
const d = deferred<Card[]>();
56+
fetches.push(d);
57+
return d.promise;
58+
}, `cards-621-${label}`);
59+
const settleFetch = (i: number) => fetches[i].resolve(db.map(c => ({ ...c })));
60+
61+
const server = deferred<void>();
62+
const swapOnServer = routerAction(async () => {
63+
await server.promise;
64+
return serverSide(db);
65+
}, `swap-621-${label}`);
66+
67+
let swap!: () => Promise<unknown>;
68+
const Cards = () => {
69+
const data = createMemo(() => getCards());
70+
const [cards, setCards] = createOptimisticStore(() => data(), [] as Card[]);
71+
const call = useAction(swapOnServer);
72+
swap = action(function* () {
73+
setCards(list => {
74+
const t = list[0].order;
75+
list[0].order = list[1].order;
76+
list[1].order = t;
77+
});
78+
yield call();
79+
});
80+
const sorted = createMemo(() => [...cards].sort((x, y) => x.order - y.order));
81+
return (
82+
<ul>
83+
<For each={sorted()}>
84+
{(card, i) => (
85+
<li>
86+
{card.id}
87+
{card.order}/{i()}{" "}
88+
</li>
89+
)}
90+
</For>
91+
</ul>
92+
);
93+
};
94+
95+
const Router = createRouter({
96+
routes: [{ path: "/", component: Cards }] as const,
97+
history: memoryHistory("/")
98+
});
99+
const root = document.createElement("div");
100+
const dispose = render(
101+
() => <Router>{props => <Loading fallback="…">{props.children}</Loading>}</Router>,
102+
root
103+
);
104+
return { root, dispose, fetches, settleFetch, server, swap: () => swap() };
105+
}
106+
107+
const TRUTH = "a0/0 b1/1 c2/2 ";
108+
const OPTIMISTIC = "b0/0 a1/1 c2/2 ";
109+
110+
// Drives one submission: optimistic write, the action settles while the test
111+
// still holds the refetch it started, then the refetch lands. Returns the
112+
// frames committed between the optimistic write and the end.
113+
async function submit(
114+
t: ReturnType<typeof setup>,
115+
betweenSettleAndRefetch: (frames: string[]) => void
116+
) {
117+
t.settleFetch(0);
118+
await textBecomes(t.root, TRUTH);
119+
const { frames, disconnect } = observeFrames(t.root);
120+
121+
const done = t.swap();
122+
await settle();
123+
expect(frames).toEqual([OPTIMISTIC]);
124+
expect(t.fetches.length).toBe(1);
125+
126+
// The action settles; its default revalidation starts a refetch that the
127+
// test still holds.
128+
t.server.resolve();
129+
await settle();
130+
expect(t.fetches.length).toBe(2);
131+
betweenSettleAndRefetch(frames);
132+
133+
t.settleFetch(1);
134+
await done;
135+
await settle();
136+
disconnect();
137+
t.dispose();
138+
return frames;
139+
}
140+
141+
describe("#621 router action revalidation commits atomically with the optimistic release", () => {
142+
for (const [label, outcome] of [
143+
["returns an Error", () => new Error("rejected")],
144+
["leaves the data unchanged", () => undefined]
145+
] as const) {
146+
test(`${label}: exactly [optimistic, truth], the revert waits for the refetch`, async () => {
147+
const t = setup(label.replace(/\W+/g, "-"), outcome);
148+
const frames = await submit(t, frames => {
149+
// Nothing may commit until the refetch lands: the revert and the
150+
// refetched data are one frame.
151+
expect(frames).toEqual([OPTIMISTIC]);
152+
});
153+
expect(frames).toEqual([OPTIMISTIC, TRUTH]);
154+
});
155+
}
156+
157+
test("commits the change: exactly [optimistic], no intermediate frame", async () => {
158+
const t = setup("commits", db => {
159+
const t = db[0].order;
160+
db[0].order = db[1].order;
161+
db[1].order = t;
162+
});
163+
const frames = await submit(t, frames => expect(frames).toEqual([OPTIMISTIC]));
164+
// The refetch confirms the optimistic frame; the DOM never changed again.
165+
expect(frames).toEqual([OPTIMISTIC]);
166+
});
167+
168+
test("commits the change and more: exactly [optimistic, truth] with the refetched data", async () => {
169+
const t = setup("commits-more", db => {
170+
const t = db[0].order;
171+
db[0].order = db[1].order;
172+
db[1].order = t;
173+
db[2].order = 5;
174+
});
175+
const frames = await submit(t, frames => expect(frames).toEqual([OPTIMISTIC]));
176+
// The part the optimistic write did not predict arrives in the same
177+
// commit as the release — proof the refetch, not just the release, landed.
178+
expect(frames).toEqual([OPTIMISTIC, "b0/0 a1/1 c5/2 "]);
179+
});
180+
});

0 commit comments

Comments
 (0)