Skip to content

Commit 7f9bd7a

Browse files
ryansolidClaude via Cursorcursoragent
committed
lazy() preload/moduleUrl and getTraceContext resolve the caller's render, not the global context
`lazy()`'s `preload()` and `moduleUrl` getter, and `getTraceContext()` outside a request scope, read the module-global `sharedConfig.context`. That is whichever render started or finished last. So under concurrent requests a call made outside the component's own render pass landed in another request's render: - `preload()` from a route data function, or from code after an `await`, put this request's modulepreload/stylesheet/preload links into another request's head. This page missed them. - a `moduleUrl` read there resolved through the other render's manifest and filed its modulepreload hint there, and a read after a `renderToString` finished resolved through that render's lingering context - an unscoped `getTraceContext()` after an `await` returned the render that last took the global In real apps, Solid Router calls `component.preload()` synchronously in `createRouteContext` during render, which was already attributable. The leaking paths are user code run outside render: route `preload` data functions run by `createFlightDataCollector` after its `await resolveLazyMatches(...)` (Solid Start's server-function single-flight path), and anything after an `await` in an async memo. Solid Start's `withRouteAssets` forwards `preload`/`moduleUrl` to the lazy component unchanged. Both now resolve the render through the caller's owner, walking to the root the renderer claimed in the render-root table added for `getRequestEvent`. solid-js's server entry reads that table directly through the registered symbol, so there is no new export. A call no render can be attributed to hints nowhere: the import still starts and the component's own render registers its assets when it mounts. `moduleUrl` returns the raw specifier and `getTraceContext()` returns `undefined`. The render path's own context read (the component body, captured at creation inside a pass like every server primitive) is unchanged. A render's `"render"` observe record settles off its pass, after the string root returned or from the stream's completion. It now settles under the render's root owner, so a listener reading `getTraceContext()` from its callback still finds its own render's trace. concurrent-render-lazy-assets.spec.tsx and concurrent-render-trace.spec.tsx interleave two renders with per-request manifests. The seven leak cases fail on the parent commit: preload and moduleUrl with and without the owner, moduleUrl after a finished string render, and trace reads with and without the owner. Four guards pass on both: preload in its own render pass, and the string, piped stream and awaited stream listeners. In nohydration.spec.ts, a unit case for a foreign global context fails on the parent too. The solid unit tests that modelled a render by setting the global now run their preload/moduleUrl calls inside a claimed root (test/server/render-root.ts). Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 51a1a49 commit 7f9bd7a

8 files changed

Lines changed: 406 additions & 29 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
"solid-js": patch
3+
"@solidjs/web": patch
4+
---
5+
6+
`lazy()`'s `preload()` and `moduleUrl`, and `getTraceContext()` outside a request scope, resolve the caller's own render instead of the global SSR context
7+
8+
Both read the module-global `sharedConfig.context`, which is whichever render started or finished last. A `preload()` or `moduleUrl` read made outside the component's own render pass (a route data function, code after an `await`) registered its modulepreload/stylesheet hints into, and resolved its URL through the manifest of, whatever render held the global, possibly another concurrent request's page. An unscoped `getTraceContext()` read the same way could return another render's trace. Both now resolve the render through the caller's owner, walking to the render root the renderer claimed. A call no render can be attributed to hints nowhere, and `moduleUrl` returns the raw specifier and `getTraceContext()` returns `undefined`. The component's own render still registers its assets when it mounts. A render's `"render"` observe record settles under the render's root owner, so its listener still reads that render's trace.

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

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,26 @@ function observedComponent<T extends Record<string, any>>(
114114

115115
type AssetContext = NonNullable<typeof sharedConfig.context>;
116116

117+
// The render a call made outside a render pass belongs to (`preload()`, the
118+
// `moduleUrl` getter — a router warming a route, a route data function, code
119+
// after an `await`): the caller's own, found by walking its owner to the root
120+
// its renderer claimed. `@solidjs/web` files each render's root owner → its
121+
// context in a process-wide WeakMap under this registered symbol, releasing
122+
// it on the root's disposal. The module-global `sharedConfig.context` is
123+
// whichever render started or finished last — possibly another request's.
124+
const RENDER_ROOTS = Symbol.for("@solidjs/web/render-roots");
125+
126+
function callerRenderContext(): AssetContext | undefined {
127+
const roots = (globalThis as any)[RENDER_ROOTS] as WeakMap<object, AssetContext> | undefined;
128+
if (!roots) return undefined;
129+
// `_parent` is one of the cross-package owner fields (see `emitFinding`).
130+
// Disposal unlinks it, so a disposed subtree walks to no render at all.
131+
for (let o: any = getOwner(); o; o = o._parent) {
132+
const ctx = roots.get(o);
133+
if (ctx) return ctx;
134+
}
135+
}
136+
117137
// Dev CHECK: a `lazy()` component whose client assets the render could not
118138
// map — `LAZY_ASSET_UNMAPPED`. One condition, two shapes: the resolver threw
119139
// (`data.reason: "resolution-failed"`, `data.id`, `data.error`), or the module
@@ -217,13 +237,16 @@ function resolveLazyAssets(
217237
* resolves and reads the module's bundler-injected `$$moduleUrl` export
218238
* instead.
219239
*
220-
* The returned component's `moduleUrl` property resolves through the active
221-
* request's asset manifest: inside SSR it returns the client-loadable entry
222-
* URL for the module (e.g. `/assets/About-abc123.js`), suitable for stamping
223-
* into markup (island containers and similar). Outside a request context it
224-
* returns the raw module specifier. Reading it during SSR also registers a
225-
* modulepreload hint for the module's chunks — accessing the resolved client
226-
* URL on the server is treated as a declaration that the client will fetch it.
240+
* The returned component's `moduleUrl` property resolves through the asset
241+
* manifest of the render it is read in (the caller's, through its owner):
242+
* there it returns the client-loadable entry URL for the module (e.g.
243+
* `/assets/About-abc123.js`), suitable for stamping into markup (island
244+
* containers and similar). Read where no render can be attributed — outside
245+
* one, or after an `await` without the owner — it returns the raw module
246+
* specifier. Reading it in a render also registers a modulepreload hint for
247+
* the module's chunks — accessing the resolved client URL on the server is
248+
* treated as a declaration that the client will fetch it. `preload()` hints
249+
* into the caller's render the same way, and into none without one.
227250
*/
228251
export function lazy<M extends Record<string, any>, K extends keyof M & string>(
229252
fn: () => Promise<M>,
@@ -421,10 +444,13 @@ export function lazy<T extends Component<any>>(
421444
};
422445
// Hints the module's assets now instead of at its render, so a router
423446
// warming a matched route gets the links into the head earlier. The import
424-
// is never gated on resolution; a resolver failure only warns.
447+
// is never gated on resolution; a resolver failure only warns. The hints go
448+
// to the caller's render; a call no render can be attributed to hints
449+
// nowhere — the import still starts, and the component's own render
450+
// registers its assets when it mounts.
425451
wrap.preload = () => {
426452
const cur = load();
427-
const ctx = sharedConfig.context;
453+
const ctx = callerRenderContext();
428454
if (!ctx?.resolveAssets || !ctx.registerAsset) return cur;
429455
// As in the render path, a no-hydrate subtree needs its CSS but never
430456
// fetches the module. Reading the context needs an owner.
@@ -486,7 +512,9 @@ export function lazy<T extends Component<any>>(
486512
};
487513
Object.defineProperty(wrap, "moduleUrl", {
488514
get() {
489-
const ctx = sharedConfig.context;
515+
// Resolved through the caller's render (see `preload`); outside one,
516+
// the raw specifier.
517+
const ctx = callerRenderContext();
490518
if (moduleUrl && ctx?.resolveAssets) {
491519
// A getter can't await, so prefer the sync resolution path (async
492520
// dev resolvers expose one carrying the js URLs); without one, fall

‎packages/solid/test/server/nohydration.spec.ts‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { createRoot, createMemo, createProjection, lazy } from "../../src/server
44
import { NoHydration, Hydration } from "../../src/server/hydration.js";
55
import { sharedConfig } from "../../src/server/shared.js";
66
import { NoHydrateContext, getContext, createErrorBoundary } from "../../src/server/signals.js";
7+
import { inClaimedRender } from "./render-root.js";
78

89
function createMockSSRContext(options: { async?: boolean } = {}) {
910
const serialized = new Map<string, any>();
@@ -660,6 +661,23 @@ describe("NoHydration / Hydration (server)", () => {
660661
expect(LazyComp.moduleUrl).toBe("/assets/MyComp-abc123.js");
661662
});
662663

664+
test("lazy() moduleUrl and preload() ignore a global context that is not the caller's render", async () => {
665+
// Another request's render, left as the global: nothing attributes the
666+
// read or the hint to it.
667+
const { context, modules } = createMockSSRContext({ async: true });
668+
context.resolveAssetsSync = context.resolveAssets;
669+
sharedConfig.context = context;
670+
671+
const LazyComp = lazy(
672+
() => Promise.resolve({ default: () => "content" }),
673+
undefined,
674+
"src/MyComp.tsx"
675+
);
676+
expect(LazyComp.moduleUrl).toBe("src/MyComp.tsx");
677+
await LazyComp.preload();
678+
expect(modules).toEqual([]);
679+
});
680+
663681
test("lazy() moduleUrl is undefined when not provided", () => {
664682
const LazyComp = lazy(() => Promise.resolve({ default: () => "content" }));
665683
expect(LazyComp.moduleUrl).toBeUndefined();
@@ -675,7 +693,7 @@ describe("NoHydration / Hydration (server)", () => {
675693
"src/MyComp.tsx"
676694
);
677695
// The mock manifest resolves every id to js: ["module.js"].
678-
expect(LazyComp.moduleUrl).toBe("module.js");
696+
expect(inClaimedRender(context, () => LazyComp.moduleUrl)).toBe("module.js");
679697
});
680698

681699
test("lazy() moduleUrl access registers modulepreload hints (island signal)", () => {
@@ -695,7 +713,7 @@ describe("NoHydration / Hydration (server)", () => {
695713
);
696714
// Access without rendering — as an island renderer stamping a container
697715
// attribute would. This is the only preload signal for NoHydration lazy.
698-
void LazyComp.moduleUrl;
716+
inClaimedRender(context, () => LazyComp.moduleUrl);
699717

700718
const jsAssets = modules.filter(m => m.type === "module");
701719
const preloadAssets = modules.filter(m => m.type === "preload");
@@ -713,7 +731,7 @@ describe("NoHydration / Hydration (server)", () => {
713731
undefined,
714732
"src/MyComp.tsx"
715733
);
716-
expect(LazyComp.moduleUrl).toBe("src/MyComp.tsx");
734+
expect(inClaimedRender(context, () => LazyComp.moduleUrl)).toBe("src/MyComp.tsx");
717735
});
718736

719737
test("lazy() moduleUrl uses the sync resolution fast path (islands in dev)", () => {
@@ -729,7 +747,7 @@ describe("NoHydration / Hydration (server)", () => {
729747
undefined,
730748
"src/MyComp.tsx"
731749
);
732-
expect(LazyComp.moduleUrl).toBe("/src/MyComp.tsx");
750+
expect(inClaimedRender(context, () => LazyComp.moduleUrl)).toBe("/src/MyComp.tsx");
733751
// The access is still the island preload signal.
734752
const jsAssets = modules.filter(m => m.type === "module");
735753
expect(jsAssets.map(a => a.href)).toEqual(["/src/MyComp.tsx"]);
@@ -746,6 +764,6 @@ describe("NoHydration / Hydration (server)", () => {
746764
undefined,
747765
"src/MyComp.tsx"
748766
);
749-
expect(LazyComp.moduleUrl).toBe("src/MyComp.tsx");
767+
expect(inClaimedRender(context, () => LazyComp.moduleUrl)).toBe("src/MyComp.tsx");
750768
});
751769
});
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { createRoot, getOwner } from "../../src/server/index.js";
2+
3+
/**
4+
* Runs `fn` in a root claimed for `context` the way `@solidjs/web`'s
5+
* renderers claim theirs: the root owner → the render's context in the
6+
* process-wide table under `Symbol.for("@solidjs/web/render-roots")`. Calls
7+
* made outside a render pass — `lazy()`'s `preload()` and `moduleUrl` —
8+
* resolve their render through it from the caller's owner, never from the
9+
* global `sharedConfig.context`.
10+
*/
11+
export function inClaimedRender<T>(context: object, fn: () => T): T {
12+
const g = globalThis as any;
13+
const key = Symbol.for("@solidjs/web/render-roots");
14+
const roots: WeakMap<object, object> = g[key] || (g[key] = new WeakMap());
15+
return createRoot(dispose => {
16+
const owner = getOwner()!;
17+
roots.set(owner, context);
18+
try {
19+
return fn();
20+
} finally {
21+
roots.delete(owner);
22+
dispose();
23+
}
24+
});
25+
}

‎packages/solid/test/server/ssr-async.spec.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { ssrHandleError } from "../../src/server/hydration.js";
1717
import { Loading } from "../../src/server/flow.js";
1818
import { sharedConfig } from "../../src/server/shared.js";
1919
import { createErrorBoundary, shareAsyncIterable } from "../../src/server/signals.js";
20+
import { inClaimedRender } from "./render-root.js";
2021

2122
// ============================================================================
2223
// Mock SSR Context Infrastructure
@@ -4437,7 +4438,7 @@ describe("Asset Manifest + lazy()", () => {
44374438
undefined,
44384439
"./Route.tsx"
44394440
);
4440-
await LazyRoute.preload!();
4441+
await inClaimedRender(context, () => LazyRoute.preload!());
44414442

44424443
expect(registered).toEqual([
44434444
{ type: "style", value: "/assets/Route.css" },
@@ -4471,8 +4472,8 @@ describe("Asset Manifest + lazy()", () => {
44714472
undefined,
44724473
"./Once.tsx"
44734474
);
4474-
await LazyOnce.preload!();
4475-
await LazyOnce.preload!();
4475+
await inClaimedRender(context, () => LazyOnce.preload!());
4476+
await inClaimedRender(context, () => LazyOnce.preload!());
44764477
createRoot(
44774478
() => {
44784479
LazyOnce({});
@@ -4661,7 +4662,7 @@ describe("Asset Manifest + lazy()", () => {
46614662

46624663
const Comp = (props: any) => "async-dev";
46634664
const LazyComp = lazy(() => Promise.resolve({ default: Comp }), undefined, "./AsyncDev.tsx");
4664-
await LazyComp.preload!();
4665+
await inClaimedRender(context, () => LazyComp.preload!());
46654666
// preload() now hints the module too; this case covers the render pass.
46664667
registered.length = 0;
46674668

@@ -4760,7 +4761,7 @@ describe("Asset Manifest + lazy()", () => {
47604761
const LazyComp = lazy(() =>
47614762
Promise.resolve({ default: Comp, $$moduleUrl: "src/Glob.tsx" } as any)
47624763
);
4763-
await LazyComp.preload!();
4764+
await inClaimedRender(context, () => LazyComp.preload!());
47644765

47654766
let thunk: any;
47664767
createRoot(

‎packages/web/src/server.ts‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1788,12 +1788,13 @@ export function renderToString(code, options = {}) {
17881788
context.trace = requestEvent ? traceForEvent(requestEvent) : traceFor(context, undefined);
17891789
const render = timeDocument(context, context.trace, "string", requestEvent);
17901790
let dispose;
1791+
let rootOwner;
17911792
let rendered = false;
17921793
try {
17931794
const html = root(
17941795
d => {
17951796
dispose = d;
1796-
claimRenderRoot(context);
1797+
rootOwner = claimRenderRoot(context);
17971798
return resolveSSRSync(escape(code()));
17981799
},
17991800
{ id: renderId }
@@ -1838,7 +1839,7 @@ export function renderToString(code, options = {}) {
18381839
} finally {
18391840
// The render record settles before the trace is let go: a listener
18401841
// reading `getTraceContext()` from its callback finds the render's.
1841-
if (render) render.settle(rendered ? "complete" : "error");
1842+
if (render) settleRender(render, rootOwner, rendered ? "complete" : "error");
18421843
// Release the graph before returning (#3385): a deferred dispose held
18431844
// every root — and every memo under it — until the next macrotask, so
18441845
// nothing was freed across a synchronous loop of renders.
@@ -1945,6 +1946,7 @@ export function renderToStream(code, options = {}) {
19451946
// The render's `"render"` record (`timeDocument`, once the context is up):
19461947
// its shell stamped at `doShell`, settled at `onDone` or by the wind-down.
19471948
let render;
1949+
let rootOwner;
19481950
// The serializer (created below, once the sink is assembled) — hoisted so
19491951
// the wind-down can close it. `abandon` is only ever reached after the
19501952
// render starts, by which point it is assigned; the hoist keeps that from
@@ -2025,7 +2027,7 @@ export function renderToStream(code, options = {}) {
20252027
if (disconnect) disconnected = true;
20262028
// The render's record ends here, with how: the client left, or the
20272029
// render failed (the render error's finding says why).
2028-
if (render) render.settle(disconnect ? "abandoned" : "error");
2030+
if (render) settleRender(render, rootOwner, disconnect ? "abandoned" : "error");
20292031
// The live sink wrapper (post-shell) is handed to the failure
20302032
// completion below; pre-shell there is none yet.
20312033
const sink = writable;
@@ -2239,7 +2241,7 @@ export function renderToStream(code, options = {}) {
22392241
completed = true;
22402242
// The stream is whole: the render record settles (its shell was stamped
22412243
// by `doShell` above), before the graph it describes is released.
2242-
if (render) render.settle("complete");
2244+
if (render) settleRender(render, rootOwner, "complete");
22432245
if (firstFlushed) dispose();
22442246
};
22452247
// FrameSink seam (design in frame-sink.js): semantic emission routes through
@@ -2906,7 +2908,7 @@ export function renderToStream(code, options = {}) {
29062908
if (onAbort) signal.removeEventListener("abort", onAbort);
29072909
d();
29082910
};
2909-
claimRenderRoot(context);
2911+
rootOwner = claimRenderRoot(context);
29102912
const res = resolveSSRNode(escape(code()));
29112913
if (!res.h.length) return res.t[0];
29122914
rootHoles = [];
@@ -6165,6 +6167,16 @@ function claimRenderRoot(context) {
61656167
const roots = renderRoots();
61666168
roots.set(owner, context);
61676169
onCleanup(() => roots.delete(owner));
6170+
return owner;
6171+
}
6172+
6173+
// A render record settles off its render's pass — after the string root
6174+
// returned, from the stream's completion or wind-down — so it settles under
6175+
// the render's root owner: a listener reading `getTraceContext()` from its
6176+
// callback finds this render's trace. `root` is unset only for a stream torn
6177+
// down before its root existed.
6178+
function settleRender(render, root, outcome) {
6179+
runWithOwner(root || null, () => render.settle(outcome));
61686180
}
61696181

61706182
// Disposal unlinks an owner (`_parent = null`), so a disposed subtree walks
@@ -6237,16 +6249,19 @@ function timeDocument(context, trace, mode, requestEvent) {
62376249
* otherwise; in observe/dev builds, merged with the installed provider's
62386250
* answer (`OBSERVE.server.trace`). Same object for every read within the
62396251
* request, direct server-function calls included. For a render outside a
6240-
* request scope, the render's own trace. `undefined` outside both, and on
6241-
* the client. Forward it downstream from a server function with
6242-
* `getTraceContext()?.entries.traceparent`.
6252+
* request scope, the render's own trace, read within it (under its owner).
6253+
* `undefined` outside both, and on the client. Forward it downstream from a
6254+
* server function with `getTraceContext()?.entries.traceparent`.
62436255
*/
62446256
export function getTraceContext(): TraceContext | undefined;
62456257

62466258
export function getTraceContext() {
62476259
const event = peekRequestEvent();
62486260
if (event) return traceForEvent(event).context;
6249-
const ctx = sharedConfig.context;
6261+
// Outside a request scope the trace is the caller's own render's, found
6262+
// through its owner (see `getRequestEvent`) — never the module global's,
6263+
// which can be another render's.
6264+
const ctx = renderContextOf(getOwner());
62506265
return ctx && ctx.trace ? ctx.trace.context : undefined;
62516266
}
62526267

0 commit comments

Comments
 (0)