Skip to content

Commit a9b9f9e

Browse files
ryansolidclaude
andauthored
fix(signals): route async protocol throws and error-formatting failures to the memo (#4112) (#4158)
* signals: route async protocol throws and error-formatting failures to the memo (#4112) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 * signals: golf #4112 fix to +3 B on the core floor Guard only the async continuation sites (iterateOrRelease and the deferred fulfillment callback) instead of the whole iterate() protocol block, and drop registerDeferredClose in favour of cleanup(fn, owner). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2 --------- Co-authored-by: Claude <[email protected]>
1 parent 667dcff commit a9b9f9e

5 files changed

Lines changed: 223 additions & 46 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+
Route synchronous throws from the async iterator / thenable protocol (a later `next()`, a step's `then`, or deferred iterator setup) to the owning memo's error handling instead of escaping as unhandled rejections, and make `StatusError` message formatting best-effort so it never replaces the original error (#4112).

‎packages/signals/src/core/async.ts‎

Lines changed: 38 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ import {
4141
freshHook,
4242
laneStageHook
4343
} from "./scheduler.js";
44-
import type { Computed, Link } from "./types.js";
44+
import type { Computed, Link, Owner } from "./types.js";
4545

4646
// The lazily-created Set is the ONE container for pending sources. Its
4747
// predecessor — a singular slot promoted to a Set on the second source —
@@ -578,18 +578,14 @@ export function handleAsync<T>(
578578
// close registration uses the ambient owner; and DEFERRED (the flattening
579579
// path — a thenable resolved to an iterable in a later microtask), where
580580
// there is no caller to serve and no ambient owner: sync-settled steps
581-
// write through asyncWrite, and close registration goes through the slot
582-
// the thenable branch pre-registered while it still owned the context.
583-
// Returns whether a sync answer landed (first yield or empty completion) —
584-
// meaningful only in the live posture.
585-
const consumeIterator = (
586-
source: AsyncIterable<T>,
587-
registerClose?: (fn: () => void) => void
588-
): boolean => {
581+
// write through asyncWrite, and close registration targets `owner` (el
582+
// itself) directly. Returns whether a sync answer landed (first yield or
583+
// empty completion) — meaningful only in the live posture.
584+
const consumeIterator = (source: AsyncIterable<T>, owner?: Owner): boolean => {
589585
const it = source[Symbol.asyncIterator]();
590586
let hadValue = false;
591587
let completed = false;
592-
let initialRead = !registerClose;
588+
let initialRead = !owner;
593589

594590
const close = () => {
595591
if (completed) return;
@@ -599,7 +595,7 @@ export function handleAsync<T>(
599595
if (isThenable(returned)) returned.then(undefined, () => {});
600596
} catch {}
601597
};
602-
registerClose ? registerClose(close) : cleanup(close);
598+
cleanup(close, owner);
603599
// Flight-identity cancellation (#3122): the registration above is the
604600
// owner-death backstop; the teardown slot fires at the _inFlight release
605601
// sites so supersede stops this stream immediately.
@@ -608,8 +604,15 @@ export function handleAsync<T>(
608604
// Release check before each next pull: an unobserved lazy node must tear
609605
// down (its close above runs via disposal, closing the iterator) instead
610606
// of pumping the stream forever with zero subscribers (#2935).
607+
// Later pulls run from an async continuation with no compute catch above
608+
// them: a throw invoking the protocol (next(), the step's then) settles
609+
// as this flight's error instead of escaping as a rejection (#4112).
611610
const iterateOrRelease = () => {
612-
if (!settleAutodispose()) iterate();
611+
try {
612+
if (!settleAutodispose()) iterate();
613+
} catch (e) {
614+
handleError(e);
615+
}
613616
};
614617

615618
const iterate = (): boolean => {
@@ -700,7 +703,7 @@ export function handleAsync<T>(
700703
// stream itself rather than settling on the iterable object. One level
701704
// only: A+ `then` already collapses nested thenables, so the resolved
702705
// value is never itself a thenable.
703-
const flattenIfIterable = (value: any, registerClose?: (fn: () => void) => void): boolean => {
706+
const flattenIfIterable = (value: any, owner?: Owner): boolean => {
704707
let innerIterator: any = false;
705708
if (typeof value === "object" && value !== null) {
706709
untrack(() => {
@@ -709,8 +712,8 @@ export function handleAsync<T>(
709712
}
710713
if (!innerIterator) return false;
711714
syncValue = undefined as T;
712-
const landed = consumeIterator(value as AsyncIterable<T>, registerClose);
713-
if (!registerClose) liveLanded = landed;
715+
const landed = consumeIterator(value as AsyncIterable<T>, owner);
716+
if (!owner) liveLanded = landed;
714717
return true;
715718
};
716719

@@ -719,34 +722,32 @@ export function handleAsync<T>(
719722
rejected = false,
720723
syncError: any,
721724
isSync = true;
722-
// Close registration for the flattening path. Consumption starts in a
723-
// microtask where the ambient owner is gone (or worse, someone else's),
724-
// so `cleanup()` can't be used — the close targets el's disposal list
725-
// directly, exactly where a live cleanup() during this recompute would
726-
// have put it. Only a flight that actually flattens becomes
727-
// disposal-bearing.
728-
const registerDeferredClose = (fn: () => void) => {
729-
if (!el._disposal) el._disposal = fn;
730-
else if (Array.isArray(el._disposal)) el._disposal.push(fn);
731-
else el._disposal = [el._disposal, fn];
732-
};
733725
(__DEV__ ? watchAsyncTail(el, result as PromiseLike<T>) : (result as PromiseLike<T>)).then(
734726
v => {
735727
if (isSync) {
736728
syncValue = v;
737729
resolved = true;
738-
} else if (
739-
el._x?._inFlight === result &&
740-
!(el._flags & REACTIVE_DISPOSED) &&
741-
flattenIfIterable(v, registerDeferredClose)
742-
) {
743-
// Flattened: the stream is the value. Each yield lands through
744-
// asyncWrite under this flight's identity; the first one clears
745-
// pending exactly like a plain promise resolution would have.
746-
// (Disposed nodes never start a pump — their disposal list has
747-
// already run, so nothing could ever close the iterator.)
748730
} else {
749-
asyncWrite(v);
731+
// Flattening consumes the stream as the value: each yield lands
732+
// through asyncWrite under this flight's identity; the first one
733+
// clears pending exactly like a plain promise resolution would.
734+
// Disposed nodes never start a pump (their disposal list already
735+
// ran, so nothing could close the iterator). Consumption starts in
736+
// a microtask where the ambient owner is gone, so the close
737+
// registers on el's own disposal list. Iterator setup here has no
738+
// compute catch above it: a protocol throw settles as this
739+
// flight's error (#4112).
740+
try {
741+
if (
742+
el._x?._inFlight === result &&
743+
!(el._flags & REACTIVE_DISPOSED) &&
744+
flattenIfIterable(v, el)
745+
)
746+
return;
747+
asyncWrite(v);
748+
} catch (e) {
749+
handleError(e);
750+
}
750751
settleAutodispose();
751752
}
752753
},

‎packages/signals/src/core/error.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,13 @@ export class StatusError extends Error {
5151
public source: any,
5252
original: any
5353
) {
54-
super(original instanceof Error ? original.message : String(original), {
55-
cause: original
56-
});
54+
// Best-effort message: formatting must never replace the original (#4112).
55+
try {
56+
var message: string | undefined = String(
57+
original instanceof Error ? original.message : original
58+
);
59+
} catch {}
60+
super(message, { cause: original });
5761
}
5862
}
5963

‎packages/signals/src/core/owner.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -301,13 +301,15 @@ export function getOwner(): Owner | null {
301301
/**
302302
* Low-level: registers `fn` as a disposal callback on the current owner.
303303
* Most code should use `onCleanup()` from `solid-js`, which adds dev-mode
304-
* checks. `cleanup()` is the unchecked primitive used by internals.
304+
* checks. `cleanup()` is the unchecked primitive used by internals; `owner`
305+
* (internal) targets a specific owner's disposal list instead of the ambient
306+
* one.
305307
*/
306-
export function cleanup(fn: Disposable): Disposable {
307-
if (!context) return fn;
308-
if (!context._disposal) context._disposal = fn;
309-
else if (Array.isArray(context._disposal)) context._disposal.push(fn);
310-
else context._disposal = [context._disposal, fn];
308+
export function cleanup(fn: Disposable, owner: Owner | null = context): Disposable {
309+
if (!owner) return fn;
310+
if (!owner._disposal) owner._disposal = fn;
311+
else if (Array.isArray(owner._disposal)) owner._disposal.push(fn);
312+
else owner._disposal = [owner._disposal, fn];
311313
return fn;
312314
}
313315

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import {
2+
createErrorBoundary,
3+
createMemo,
4+
createRenderEffect,
5+
createRoot,
6+
flush
7+
} from "../src/index.js";
8+
9+
// #4112: throws raised while Solid invokes the async-iterator / thenable
10+
// protocol (not rejections delivered through it) must reach the owning memo's
11+
// error handling, and error formatting must never replace the original error.
12+
13+
afterEach(() => flush());
14+
15+
const tick = () => new Promise<void>(r => setTimeout(r, 0));
16+
const original = (e: any) => e?.cause ?? e;
17+
18+
describe("#4112 async protocol throws reach the memo", () => {
19+
let unhandled: unknown[];
20+
const onUnhandled = (e: unknown) => void unhandled.push(e);
21+
beforeEach(() => {
22+
unhandled = [];
23+
process.on("unhandledRejection", onUnhandled);
24+
});
25+
afterEach(() => void process.off("unhandledRejection", onUnhandled));
26+
27+
// Yields 1 after a timer, then defers to `second` for the next pull.
28+
function iterableWith(second: () => any): AsyncIterable<number> {
29+
return {
30+
[Symbol.asyncIterator]() {
31+
let n = 0;
32+
return {
33+
next() {
34+
if (n++ === 0)
35+
return new Promise<IteratorResult<number>>(r =>
36+
setTimeout(() => r({ done: false, value: 1 }))
37+
);
38+
return second();
39+
}
40+
} as AsyncIterator<number>;
41+
}
42+
};
43+
}
44+
45+
// Mirrors <Errored>{memo()}</Errored>: the boundary's fallback is where a
46+
// protocol failure must surface.
47+
async function run(source: () => any) {
48+
const shown: unknown[] = [];
49+
createRoot(() => {
50+
const memo = createMemo(source as () => number);
51+
const b = createErrorBoundary(
52+
() => memo(),
53+
err => original(err())
54+
);
55+
createRenderEffect(
56+
() => {
57+
try {
58+
return b();
59+
} catch {
60+
return "loading";
61+
}
62+
},
63+
v => void shown.push(v)
64+
);
65+
});
66+
flush();
67+
for (let i = 0; i < 4; i++) {
68+
await tick();
69+
flush();
70+
}
71+
return shown;
72+
}
73+
74+
const last = (shown: unknown[]) => (shown[shown.length - 1] as any)?.message;
75+
76+
it("control: later next() rejecting reaches the boundary", async () => {
77+
const shown = await run(() => iterableWith(() => Promise.reject(new Error("rejected"))));
78+
expect(last(shown)).toBe("rejected");
79+
expect(unhandled).toEqual([]);
80+
});
81+
82+
it("later next() throwing synchronously reaches the boundary", async () => {
83+
const shown = await run(() =>
84+
iterableWith(() => {
85+
throw new Error("next failed");
86+
})
87+
);
88+
expect(last(shown)).toBe("next failed");
89+
expect(unhandled).toEqual([]);
90+
});
91+
92+
it("next step's then() throwing reaches the boundary", async () => {
93+
const shown = await run(() =>
94+
iterableWith(() => ({
95+
then() {
96+
throw new Error("then failed");
97+
}
98+
}))
99+
);
100+
expect(last(shown)).toBe("then failed");
101+
expect(unhandled).toEqual([]);
102+
});
103+
104+
it("deferred iterator factory throwing reaches the boundary", async () => {
105+
const shown = await run(() =>
106+
new Promise(r => setTimeout(r)).then(() => ({
107+
[Symbol.asyncIterator]() {
108+
throw new Error("iterator failed");
109+
}
110+
}))
111+
);
112+
expect(last(shown)).toBe("iterator failed");
113+
expect(unhandled).toEqual([]);
114+
});
115+
116+
it("deferred first next() throwing reaches the boundary", async () => {
117+
const shown = await run(() =>
118+
new Promise(r => setTimeout(r)).then(() => ({
119+
[Symbol.asyncIterator]() {
120+
return {
121+
next() {
122+
throw new Error("first next failed");
123+
}
124+
};
125+
}
126+
}))
127+
);
128+
expect(last(shown)).toBe("first next failed");
129+
expect(unhandled).toEqual([]);
130+
});
131+
});
132+
133+
describe("#4112 error formatting keeps the original error", () => {
134+
function create(thrown: unknown) {
135+
let memo!: () => unknown;
136+
expect(() =>
137+
createRoot(() => {
138+
memo = createMemo(() => {
139+
throw thrown;
140+
});
141+
})
142+
).not.toThrow();
143+
let caught: unknown;
144+
try {
145+
memo();
146+
} catch (e) {
147+
caught = e;
148+
}
149+
expect(original(caught)).toBe(thrown);
150+
}
151+
152+
it("unstringifiable thrown value does not escape createMemo", () => {
153+
create(Object.create(null));
154+
});
155+
156+
it("throwing message getter does not escape createMemo", () => {
157+
const err = new Error("x");
158+
Object.defineProperty(err, "message", {
159+
get() {
160+
throw new Error("getter");
161+
}
162+
});
163+
create(err);
164+
});
165+
});

0 commit comments

Comments
 (0)