Skip to content

Commit 9379257

Browse files
authored
perf(store): track and snapshot plain records in one deep() walk (#4603)
1 parent aeca8da commit 9379257

3 files changed

Lines changed: 185 additions & 20 deletions

File tree

‎.changeset/deep-one-walk.md‎

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+
`deep()` tracks and snapshots a plain store record in one walk instead of two. Records in a projection or optimistic family, chained stores and overlays keep the two walks.

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

Lines changed: 77 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2714,10 +2714,44 @@ export function deep<T>(value: T): T {
27142714
walkT(ct);
27152715
}
27162716
};
2717+
// One pass where the tracked view is the snapshot's backing; else two walks.
2718+
const seen = new Map<object, any>();
2719+
const fast = (t: StoreTarget, raw: object): object | undefined => {
2720+
if (t._fam !== null || t.ch || t.ovl || (raw !== t.px && lookupTarget(raw, null) !== t)) return;
2721+
const src = enumerationSource(t);
2722+
if (src !== snapshotBacking(t) || visited.has(src) || seen.has(src) || !isWrappable(src))
2723+
return;
2724+
// snapshotWalk's resolution must stop at `src` too.
2725+
if (src !== raw) {
2726+
const st = lookupTarget(src, null);
2727+
if (st !== undefined && st !== t) return;
2728+
}
2729+
visited.add(src);
2730+
readNode(getDeepNode(t));
2731+
return src;
2732+
};
2733+
const step: DeepStep = (t, cv, key, trackOnly) => {
2734+
const ct = childTarget(t, cv, key);
2735+
const src = ct && !trackOnly ? fast(ct, cv) : undefined;
2736+
if (src) return snapshotRecord(src, seen, null, ct!, step);
2737+
if (ct) walkT(ct);
2738+
if (!trackOnly) return snapshotWalk(cv, seen, null);
2739+
};
2740+
try {
2741+
const src = fast(t0, value as object);
2742+
if (src) return snapshotRecord(src, seen, null, t0, step);
2743+
} catch (e) {
2744+
// A snapshot read threw mid-pass: subscribe the rest, as the two walks did.
2745+
visited.clear();
2746+
walkT(t0);
2747+
throw e;
2748+
}
27172749
walkT(t0);
2718-
return snapshot(value);
2750+
return snapshotWalk(value, seen, t0._fam);
27192751
}
27202752

2753+
type DeepStep = (t: StoreTarget, cv: object, key: PropertyKey, trackOnly?: boolean) => any;
2754+
27212755
/** Non-tracking snapshot: source identity for unowned subtrees (zero copy),
27222756
* a copy for owned ones (they are by definition modified relative to the
27232757
* source). Sees the pending backing (R27). */
@@ -2726,6 +2760,22 @@ export function snapshot<T>(value: T): T {
27262760
return snapshotWalk(value, new Map(), t?._fam ?? null);
27272761
}
27282762

2763+
/** R27: a snapshot sees the batch's pending backing — a held one (another
2764+
* transaction's future) only from its own draft, or from a pass the
2765+
* container node serves the future (its landing flush, a memo joining). */
2766+
function snapshotBacking(t: StoreTarget): Record<PropertyKey, any> {
2767+
let backing = t.v;
2768+
const pb = t.pb;
2769+
if (pb !== null) {
2770+
const k = t.k;
2771+
if (inDraft(t) || writeOverride || k === null || !(k._config & CONFIG_HELD)) backing = pb;
2772+
else if (stagingReader() !== null) backing = asBacking(untrack(() => readNode(k)));
2773+
// materializePB is a no-op (returns pb) without an overlay.
2774+
if (backing === pb) backing = materializePB(t);
2775+
}
2776+
return optHooks && optRead(t) ? optHooks.view(t, backing) : backing;
2777+
}
2778+
27292779
function snapshotWalk(value: any, seen: Map<object, any>, fam: StoreFamily | null): any {
27302780
if (value === null || typeof value !== "object") return value;
27312781
let src = value;
@@ -2740,39 +2790,42 @@ function snapshotWalk(value: any, seen: Map<object, any>, fam: StoreFamily | nul
27402790
if (outer !== undefined) t = outer;
27412791
}
27422792
if (t._fam !== null) fam = t._fam;
2743-
// R27: a snapshot sees the batch's pending backing — a held one (another
2744-
// transaction's future) only from its own draft, or from a pass the
2745-
// container node serves the future (its landing flush, a memo joining).
2746-
let backing = t.v;
2747-
const pb = t.pb;
2748-
if (pb !== null) {
2749-
const k = t.k;
2750-
if (inDraft(t) || writeOverride || k === null || !(k._config & CONFIG_HELD)) backing = pb;
2751-
else if (stagingReader() !== null) backing = asBacking(untrack(() => readNode(k)));
2752-
// materializePB is a no-op (returns pb) without an overlay.
2753-
if (backing === pb) backing = materializePB(t);
2754-
}
2755-
if (optHooks && optRead(t)) backing = optHooks.view(t, backing);
2793+
const backing = snapshotBacking(t);
27562794
if (backing === src) break;
27572795
src = backing;
27582796
}
27592797
if (!isWrappable(src)) return src;
27602798
const cached = seen.get(src);
2761-
if (cached !== undefined) return cached;
2799+
return cached !== undefined ? cached : snapshotRecord(src, seen, fam, null, null);
2800+
}
2801+
2802+
/** `t`/`step` set: `deep()`'s one pass, which also tracks `t`'s children. */
2803+
function snapshotRecord(
2804+
src: any,
2805+
seen: Map<object, any>,
2806+
fam: StoreFamily | null,
2807+
t: StoreTarget | null,
2808+
step: DeepStep | null
2809+
): any {
27622810
if (isOwned(src)) {
27632811
const isArr = Array.isArray(src);
27642812
const copy: any = isArr ? [] : Object.create(Object.getPrototypeOf(src));
27652813
seen.set(src, copy);
27662814
for (const key of Reflect.ownKeys(src)) {
27672815
if ((isArr && key === "length") || key === $OWNER) continue;
27682816
const desc = Object.getOwnPropertyDescriptor(src, key)!;
2769-
if (typeof key === "symbol" && !desc.enumerable) continue;
2817+
const cv = desc.value;
2818+
const obj = cv !== null && typeof cv === "object";
2819+
if (typeof key === "symbol" && !desc.enumerable) {
2820+
if (step && obj) step(t!, cv, key, true);
2821+
continue;
2822+
}
27702823
if (desc.get || desc.set) {
2824+
if (t) t.a = true;
27712825
Object.defineProperty(copy, key, desc);
27722826
continue;
27732827
}
2774-
const cv = desc.value;
2775-
const walked = cv !== null && typeof cv === "object" ? snapshotWalk(cv, seen, fam) : cv;
2828+
const walked = obj ? (step ? step(t!, cv, key) : snapshotWalk(cv, seen, fam)) : cv;
27762829
if (desc.enumerable && desc.writable && desc.configurable) copy[key] = walked;
27772830
else Object.defineProperty(copy, key, { ...desc, value: walked });
27782831
}
@@ -2783,10 +2836,14 @@ function snapshotWalk(value: any, seen: Map<object, any>, fam: StoreFamily | nul
27832836
let copy: any = null;
27842837
for (const key of Reflect.ownKeys(src)) {
27852838
const desc = Object.getOwnPropertyDescriptor(src, key);
2786-
if (!desc || desc.get || desc.set) continue;
2839+
if (!desc) continue;
2840+
if (desc.get || desc.set) {
2841+
if (t) t.a = true;
2842+
continue;
2843+
}
27872844
const cv = desc.value;
27882845
if (cv === null || typeof cv !== "object") continue;
2789-
const walked = snapshotWalk(cv, seen, fam);
2846+
const walked = step ? step(t!, cv, key) : snapshotWalk(cv, seen, fam);
27902847
if (walked !== cv) {
27912848
if (copy === null) {
27922849
copy = Array.isArray(src)
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// deep() tracks and snapshots a plain store in one pass: the result keeps
2+
// snapshot()'s shape and identity, and every reachable record stays subscribed.
3+
import { createEffect, createRoot, createStore, deep, flush, snapshot } from "../../src/index.js";
4+
5+
const HIDDEN = Symbol("hidden");
6+
7+
function setup(init: any) {
8+
let dispose!: () => void;
9+
let runs = 0;
10+
let last: any;
11+
const [store, setStore] = createRoot(d => {
12+
dispose = d;
13+
const pair = createStore<any>(init);
14+
createEffect(
15+
() => deep(pair[0]),
16+
value => {
17+
runs++;
18+
last = value;
19+
}
20+
);
21+
return pair;
22+
});
23+
flush();
24+
return { store, setStore, dispose, runs: () => runs, last: () => last };
25+
}
26+
27+
it("matches snapshot() for unowned and owned records", () => {
28+
const shared = { n: 1 };
29+
const s = setup({ a: shared, b: shared, list: [{ x: 1 }, { x: 2 }] });
30+
try {
31+
const first = s.last();
32+
expect(first).toBe(snapshot(s.store));
33+
expect(first.a).toBe(first.b);
34+
s.setStore(d => {
35+
d.list[1].x = 3;
36+
});
37+
flush();
38+
const next = s.last();
39+
expect(next).toEqual({ a: { n: 1 }, b: { n: 1 }, list: [{ x: 1 }, { x: 3 }] });
40+
expect(next.a).toBe(shared);
41+
expect(next.a).toBe(next.b);
42+
expect(next.list[0]).toBe(first.list[0]);
43+
expect(next.list).not.toBe(first.list);
44+
} finally {
45+
s.dispose();
46+
}
47+
});
48+
49+
it("keeps cycles and accessors as snapshot() does", () => {
50+
const root: any = { child: { v: 1 } };
51+
root.child.up = root;
52+
Object.defineProperty(root, "computed", { get: () => 42, enumerable: true });
53+
const s = setup(root);
54+
try {
55+
const out = s.last();
56+
expect(out.child.up).toBe(out);
57+
expect(Object.getOwnPropertyDescriptor(out, "computed")?.get).toBeTypeOf("function");
58+
s.setStore(d => {
59+
d.child.v = 2;
60+
});
61+
flush();
62+
expect(s.last().child.v).toBe(2);
63+
} finally {
64+
s.dispose();
65+
}
66+
});
67+
68+
it("stays subscribed below a non-enumerable symbol key of an owned record", () => {
69+
const init: any = { title: "a" };
70+
Object.defineProperty(init, HIDDEN, { value: { count: 0 }, enumerable: false });
71+
const s = setup(init);
72+
try {
73+
s.setStore(d => {
74+
d.title = "b";
75+
});
76+
flush();
77+
const before = s.runs();
78+
s.setStore(d => {
79+
d[HIDDEN].count = 1;
80+
});
81+
flush();
82+
expect(s.runs()).toBe(before + 1);
83+
} finally {
84+
s.dispose();
85+
}
86+
});
87+
88+
it("re-runs for writes to a record reached only through a shared subtree", () => {
89+
const leaf = { deep: { count: 0 } };
90+
const s = setup({ left: { leaf }, right: { leaf } });
91+
try {
92+
const before = s.runs();
93+
s.setStore(d => {
94+
d.right.leaf.deep.count = 1;
95+
});
96+
flush();
97+
expect(s.runs()).toBe(before + 1);
98+
expect(s.last().left.leaf.deep.count).toBe(1);
99+
expect(s.last().left.leaf).toBe(s.last().right.leaf);
100+
} finally {
101+
s.dispose();
102+
}
103+
});

0 commit comments

Comments
 (0)