Skip to content

Commit e87d694

Browse files
ryansolidMonkeylordzClaude via Cursorcursoragent
committed
fix(store): shallow store leaves stay raw in drafts, shadows and SSR snapshots (#3498)
`{ shallow: true }` promises raw leaf references, but three projection paths treated a shallow store as deep: `wrapDraft` wrapped every nested value read through the derive's draft in another proxy (identity lost; an object-valued non-configurable property on a frozen leaf tripped a Proxy invariant), and the loading shadow, its commit copy, the SSR draft/snapshots and the hydration replay shadow were `JSON.parse(JSON.stringify(...))` copies of the whole tree (`Date` -> string, `NaN` -> null, `undefined` dropped, BigInt and cycles throw). The shallow flag now short-circuits the draft recursion (no indirect call; the nested recursion never happens for a shallow store, so nothing is passed down), `createDeepProxy` skips child proxies when shallow, and the copies go through `cloneState(v, shallow)`: the root container alone for a shallow store — its leaves are raw by contract and stay so — the tree otherwise. The deep path is unchanged in behavior. For shallow stores every touched path does strictly less work: no per-read proxy allocation in the draft, a root `slice()`/spread instead of a tree clone in loading windows and hydration. `cloneState` is mirrored in the solid server runtime rather than exported: it is an implementation detail with an ugly contract, and the server layer is by design a reimplementation that already carries its own copies of this kind of logic. The shallow half of #3499 (Leon Schiffler), reduced: the hybrid hydration resequencing in that PR makes new rules about handoff and stays there for a ruling. Tests are his, minus the hybrid describes; all 15 fail on unfixed `next`. Signals, solid, web (client/server/hydrate) green. Size: hydrating (no stores) 20,208 -> 20,260 B, hydrating + stores 30,303 -> 30,469 B, caps ratcheted with notes; signals+store 16.65 -> 16.72 kB under cap; CSR and the signal-only floor flat. Co-authored-by: Leon Schiffler <[email protected]> Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent e171fc2 commit e87d694

8 files changed

Lines changed: 246 additions & 26 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@solidjs/signals": patch
3+
"solid-js": patch
4+
---
5+
6+
`{ shallow: true }` computed stores keep their leaves raw on every path (#3498). The projection draft no longer wraps a nested value in a draft proxy — leaf identity holds and a frozen leaf can no longer trip a Proxy invariant — and the loading shadow, its commit copy, the SSR draft and snapshots, and the hydration replay shadow copy only the root container instead of JSON-cloning the tree, which turned `Date` into a string, `NaN` into `null`, dropped `undefined` properties, and could not represent BigInt or cycles. Deep stores are unchanged.

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

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ import type { StoreNextFamily } from "./target.js";
6464
function wrapDraft(
6565
inner: any,
6666
isActive?: () => boolean,
67-
aroundWrite?: (op: () => void) => void
67+
aroundWrite?: (op: () => void) => void,
68+
shallow?: boolean
6869
): any {
6970
const write = (op: () => void) => (aroundWrite ? aroundWrite(op) : op());
7071
const traps: ProxyHandler<any> = {
@@ -79,8 +80,9 @@ function wrapDraft(
7980
setWriteOverride(false);
8081
setProjectionWriteActive(was);
8182
}
82-
if (prop === $TARGET) return value;
83-
return typeof value === "object" && value !== null
83+
// A shallow store's leaves are raw by contract (#3498): no draft proxy
84+
// over them, so identity holds and a frozen leaf is never trapped.
85+
return !shallow && typeof value === "object" && value !== null && prop !== $TARGET
8486
? wrapDraft(value, isActive, aroundWrite)
8587
: value;
8688
},
@@ -236,6 +238,13 @@ export function createStoreDerivedNext<T extends object = {}>(
236238
];
237239
}
238240

241+
// A detached copy of projection state: the root container alone for a shallow
242+
// store — its leaves are raw references by contract and stay so (#3498) — the
243+
// whole tree otherwise.
244+
function cloneState<T extends object>(v: T, shallow: boolean): T {
245+
return shallow ? (Array.isArray(v) ? (v.slice() as T) : { ...v }) : JSON.parse(JSON.stringify(v));
246+
}
247+
239248
export function runProjectionComputedNext<T extends object>(
240249
wrappedStore: Store<T>,
241250
fn: (draft: T) => void | T | Promise<void | T> | AsyncIterable<void | T>,
@@ -244,19 +253,19 @@ export function runProjectionComputedNext<T extends object>(
244253
aroundDraftWrite?: (op: () => void) => void
245254
): Computed<void | T> {
246255
const owner = getOwner() as Computed<void | T>;
256+
const target = (wrappedStore as any)[$TARGET];
247257
let settled = false;
248258
let result: void | T | Promise<void | T> | AsyncIterable<void | T>;
249259
// Open loading window (seedLoadingValue): the observable store IS commit #0
250260
// for the whole first flight — the derive works a detached shadow of the
251261
// seed so draft writes cannot tear through to readers (#2988). Every commit
252262
// point reconciles the shadow through the normal commit path.
253-
const shadow = owner._loading
254-
? (JSON.parse(JSON.stringify((wrappedStore as any)[$TARGET][STORE_VALUE])) as T)
255-
: null;
263+
const shadow = owner._loading ? cloneState(target[STORE_VALUE] as T, target.s) : null;
256264
const draft = wrapDraft(
257265
wrappedStore,
258266
() => !settled || owner._x?._inFlight === result,
259-
aroundDraftWrite
267+
aroundDraftWrite,
268+
target.s
260269
);
261270
storeSetterNext(
262271
draft,
@@ -267,8 +276,7 @@ export function runProjectionComputedNext<T extends object>(
267276
// Shadow run: commit a detached snapshot, never the shadow itself
268277
// (adoption takes the value by identity — handing it the live shadow
269278
// would fuse the draft to the observable store).
270-
if (shadow && (v === undefined || v === (shadow as any)))
271-
v = JSON.parse(JSON.stringify(shadow)) as T;
279+
if (shadow && (v === undefined || v === (shadow as any))) v = cloneState(shadow, target.s);
272280
if (v === (s as any) || v === undefined) return;
273281
const write = () =>
274282
storeSetterNext(wrappedStore, st => reconcileNextState(v, st, key, true), false);
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { describe, expect, test } from "vitest";
2+
import {
3+
createRoot,
4+
createStore,
5+
createOptimisticStore,
6+
flush,
7+
NotReadyError
8+
} from "../../src/index.js";
9+
10+
describe("shallow loading projections", () => {
11+
for (const optimistic of [false, true])
12+
for (const array of [false, true])
13+
for (const loading of [false, true]) {
14+
test(`retains raw leaf identity: optimistic=${optimistic}, array=${array}, loading=${loading}`, async () => {
15+
const original = Object.freeze({
16+
time: new Date(0),
17+
missing: undefined,
18+
n: NaN,
19+
key: {}
20+
});
21+
const replacement = Object.freeze({ ...original, time: new Date(1) });
22+
let release!: () => void, dispose!: () => void, seen: unknown;
23+
const gate = new Promise<void>(resolve => {
24+
release = resolve;
25+
});
26+
const seed: { [key: number]: typeof original | undefined } = array
27+
? [original]
28+
: { 0: original };
29+
const [state] = createRoot(d => {
30+
dispose = d;
31+
return (optimistic ? createOptimisticStore : createStore)(
32+
async draft => {
33+
seen = draft[0];
34+
draft[0] = replacement;
35+
await gate;
36+
},
37+
seed,
38+
{ shallow: true, seedLoadingValue: loading }
39+
);
40+
});
41+
try {
42+
expect(seen).toBe(original);
43+
if (loading) expect(state[0]).toBe(original);
44+
else expect(() => state[0]).toThrow(NotReadyError);
45+
release();
46+
for (let i = 0; i < 30; i++) await Promise.resolve();
47+
flush();
48+
expect(state[0]).toBe(replacement);
49+
} finally {
50+
release();
51+
dispose();
52+
}
53+
});
54+
}
55+
});

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

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -589,8 +589,13 @@ function isAsyncIterable(v: any): boolean {
589589
return v != null && typeof v[Symbol.asyncIterator] === "function";
590590
}
591591

592-
function createShadowDraft(realDraft: any) {
593-
const shadow = JSON.parse(JSON.stringify(realDraft));
592+
function createShadowDraft(realDraft: any, shallow?: boolean) {
593+
// A shallow store's leaves are raw by contract: copy the root only (#3498).
594+
const shadow = shallow
595+
? Array.isArray(realDraft)
596+
? realDraft.slice()
597+
: { ...realDraft }
598+
: JSON.parse(JSON.stringify(realDraft));
594599
let useShadow = true;
595600
return {
596601
proxy: new Proxy(shadow, {
@@ -747,7 +752,7 @@ function hydrateStoreFromAsyncIterable(
747752
// dependencies read before the first suspension are tracked. Writes go
748753
// to a shadow of the draft and are discarded — the server iterator is
749754
// authoritative and drives the real draft via the iterable below.
750-
const { proxy } = createShadowDraft(draft);
755+
const { proxy } = createShadowDraft(draft, options?.shallow);
751756
subFetch(fn, proxy);
752757
const process = (res: any) => {
753758
if (res.done) {
@@ -1169,7 +1174,7 @@ function hydrateStoreLikeFn(
11691174
);
11701175
return fn(draft);
11711176
}
1172-
const { proxy, activate } = createShadowDraft(draft);
1177+
const { proxy, activate } = createShadowDraft(draft, options?.shallow);
11731178
const r = fn(proxy);
11741179
return isAsyncIterable(r) ? wrapFirstYield(r, activate) : r;
11751180
},

‎packages/solid/src/server/signals.ts‎

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1147,7 +1147,8 @@ export type PatchOp =
11471147
export function createDeepProxy<T extends object>(
11481148
target: T,
11491149
patches: PatchOp[],
1150-
basePath: PropertyKey[] = []
1150+
basePath: PropertyKey[] = [],
1151+
shallow?: boolean
11511152
): T {
11521153
const childProxies = new Map<PropertyKey, any>();
11531154

@@ -1191,7 +1192,7 @@ export function createDeepProxy<T extends object>(
11911192
}
11921193

11931194
const value = Reflect.get(obj, key, receiver);
1194-
if (value !== null && typeof value === "object" && typeof key !== "symbol") {
1195+
if (!shallow && value !== null && typeof value === "object" && typeof key !== "symbol") {
11951196
if (!childProxies.has(key)) {
11961197
childProxies.set(key, createDeepProxy(value, patches, [...basePath, key]));
11971198
}
@@ -2046,17 +2047,29 @@ export function getProjectionTrace(value: unknown): ProjectionTrace | undefined
20462047
return typeof value === "object" && value !== null ? projectionTraces.get(value) : undefined;
20472048
}
20482049

2050+
// A detached copy of projection state — the root container alone for a
2051+
// shallow store (its leaves are raw references by contract, #3498), the whole
2052+
// tree otherwise. Twin of the client's `cloneState` (store/next/projection.ts).
2053+
function cloneState<T extends object>(v: T, shallow?: boolean): T {
2054+
return shallow ? (Array.isArray(v) ? (v.slice() as T) : { ...v }) : JSON.parse(JSON.stringify(v));
2055+
}
2056+
20492057
// Settles-once projections (promise-driven retry, thenable derives, hybrid
20502058
// iterables): the trace is one snapshot after settlement, then done — the
20512059
// border analogue of "reads pass through once markReady runs". A rejection
20522060
// propagates through the iterable so the consumer's read errors rather
20532061
// than hanging.
2054-
function registerSettledTrace(pending: object, ready: Promise<any>, state: object) {
2062+
function registerSettledTrace(
2063+
pending: object,
2064+
ready: Promise<any>,
2065+
state: object,
2066+
shallow?: boolean
2067+
) {
20552068
projectionTraces.set(pending, {
20562069
array: Array.isArray(state),
20572070
subscribe: async function* () {
20582071
await ready;
2059-
yield JSON.parse(JSON.stringify(state));
2072+
yield cloneState(state, shallow);
20602073
}
20612074
});
20622075
}
@@ -2143,7 +2156,9 @@ export function createProjection<T extends object = {}>(
21432156
const usesHybrid = (source: AsyncIterable<unknown>) =>
21442157
ssrSource === "hybrid" || !!(source as any)[LIVE_SOURCE];
21452158
const patches: PatchOp[] = [];
2146-
const draft = useProxy ? createDeepProxy(state as any, patches) : (state as any as T);
2159+
const draft = useProxy
2160+
? createDeepProxy(state as any, patches, [], options?.shallow)
2161+
: (state as any as T);
21472162
const takeFirst = (source: AsyncIterable<void | T>) =>
21482163
Promise.resolve().then(() => {
21492164
const iter = source[Symbol.asyncIterator]();
@@ -2171,7 +2186,7 @@ export function createProjection<T extends object = {}>(
21712186
// declared first paint (#2988 ruling; the client's shadow draft enforces
21722187
// the same line, and hydration claims against the plain seed).
21732188
const seedLoading = !!options?.seedLoadingValue;
2174-
const frozenSeed = seedLoading ? (JSON.parse(JSON.stringify(state)) as T) : undefined;
2189+
const frozenSeed = seedLoading ? cloneState(state, options?.shallow) : undefined;
21752190

21762191
const runProjection = () => {
21772192
resetOwnerForRerun(owner);
@@ -2200,7 +2215,7 @@ export function createProjection<T extends object = {}>(
22002215
markError,
22012216
() => disposed
22022217
);
2203-
registerSettledTrace(pending, deferred.promise, state);
2218+
registerSettledTrace(pending, deferred.promise, state, options?.shallow);
22042219
if (ctx?.async && !getContext(NoHydrateContext) && owner.id)
22052220
ctx.serialize(owner.id, deferred.promise, options?.deferStream);
22062221
return recordSlot(pending);
@@ -2233,7 +2248,7 @@ export function createProjection<T extends object = {}>(
22332248
markError,
22342249
() => disposed
22352250
);
2236-
registerSettledTrace(pending, deferred.promise, state);
2251+
registerSettledTrace(pending, deferred.promise, state, options?.shallow);
22372252
if (ctx?.async && !getContext(NoHydrateContext) && owner.id)
22382253
ctx.serialize(owner.id, deferred.promise, options?.deferStream);
22392254
return recordSlot(pending);
@@ -2279,7 +2294,7 @@ export function createProjection<T extends object = {}>(
22792294
// `state` (for draft/patch correctness) but reads go through the frozen
22802295
// copy. With seedLoadingValue the lock already sits at commit #0 — the
22812296
// seed — so V1 must NOT retarget it (undefined keeps the read target).
2282-
markReady(seedLoading ? undefined : (JSON.parse(JSON.stringify(state)) as T));
2297+
markReady(seedLoading ? undefined : cloneState(state, options?.shallow));
22832298
return undefined;
22842299
},
22852300
markError,
@@ -2335,7 +2350,7 @@ export function createProjection<T extends object = {}>(
23352350
let cursor = log.length;
23362351
consumers++;
23372352
try {
2338-
yield JSON.parse(JSON.stringify(state)) as T;
2353+
yield cloneState(state, options?.shallow);
23392354
while (true) {
23402355
if (cursor < log.length) {
23412356
yield log[cursor++];
@@ -2382,7 +2397,7 @@ export function createProjection<T extends object = {}>(
23822397
markError,
23832398
() => disposed
23842399
);
2385-
registerSettledTrace(pending, deferred.promise, state);
2400+
registerSettledTrace(pending, deferred.promise, state, options?.shallow);
23862401
if (ctx?.async && !getContext(NoHydrateContext) && owner.id)
23872402
ctx.serialize(owner.id, deferred.promise, options?.deferStream);
23882403
return recordSlot(pending);
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/** @vitest-environment node */
2+
import { describe, expect, test } from "vitest";
3+
import { createRoot, createStore } from "../../src/server/index.js";
4+
import { getProjectionTrace } from "../../src/server/signals.js";
5+
6+
describe("shallow SSR projections", () => {
7+
test("returns frozen leaves without wrapping them", () => {
8+
const value = Object.freeze({ key: {} });
9+
createRoot(() => {
10+
const [state] = createStore(
11+
draft => {
12+
expect(draft.value).toBe(value);
13+
expect(draft.value.key).toBe(value.key);
14+
},
15+
{ value },
16+
{ shallow: true }
17+
);
18+
expect(state.value).toBe(value);
19+
});
20+
});
21+
22+
for (const array of [false, true]) {
23+
test(`preserves stream leaf identity and the first answer: array=${array}`, async () => {
24+
const value = Object.freeze({ key: {}, time: new Date(0), missing: undefined, n: NaN });
25+
const replacement = Object.freeze({ ...value, time: new Date(1) });
26+
let dispose!: () => void;
27+
const seed: { [key: number]: typeof value | undefined } = array ? [] : { 0: undefined };
28+
const [state] = createRoot(d => {
29+
dispose = d;
30+
return createStore(
31+
async function* (draft) {
32+
draft[0] = value;
33+
yield;
34+
draft[0] = replacement;
35+
yield;
36+
},
37+
seed,
38+
{ shallow: true }
39+
);
40+
});
41+
try {
42+
for (let i = 0; i < 30; i++) await Promise.resolve();
43+
expect(state[0]).toBe(value);
44+
const iterator = getProjectionTrace(state)!.subscribe()[Symbol.asyncIterator]();
45+
expect((await iterator.next()).value[0]).toBe(value);
46+
const patch = (await iterator.next()).value;
47+
expect(patch[0][1]).toBe(replacement);
48+
expect(state[0]).toBe(value);
49+
await iterator.return?.();
50+
} finally {
51+
dispose();
52+
}
53+
});
54+
}
55+
});

0 commit comments

Comments
 (0)