Skip to content

Commit 56918c6

Browse files
brenelzryansolidClaude via Cursor
authored
fix(server): close serialized iterators on stream abandonment (#3628)
* fix(server): close serialized iterators on stream abandonment (#3626) A memo or projection whose compute yields an async iterable serializes a tapped iterator into the stream. Cancelling the readable or a throwing pipe sink disposes the render, but the tapped iterator kept delegating next() to the source, so seroval pulled it for as long as the source lived and the generator's finally never ran. The tapped iterator now answers done and calls the source's return() once its computation is disposed. The projection pump already stopped on disposal but left its source open; it now closes it too. * fix: address review findings The tapped iterator replays its first value before it checks for disposal, so the value the HTML was rendered from always ships. The source's `return()` runs at most once per tapped iterator, whether the close comes from a pull after disposal or from the wrapper's own `return()`. The spec waits for the source's first pull before it cancels and for the source's `finally` before it asserts, instead of fixed delays, and it also reads each stream to the end and checks that every value arrives. * fix(web): close the serializer when a stream render is abandoned (#3626) The tapped iterator's disposed check runs on the next pull, so a source whose pending `next()` never settles was never returned — the gap the PR body's "Open" section names. `renderToStream`'s `abandon()` now closes the serializer after marking the render dead: seroval's `close()` runs every pending write's cleanup, which calls `return()` on each serialized async iterator immediately, and its `onDone` sees `dead` and skips the shell. `close()` is contained (a custom serializer's `close` is optional and must not escape the teardown; a throw routes to the server error hook when one exists). After the close, the render's remaining writes go to an abandoned serializer that owns their rejections — a closed serializer drops writes without looking, which turned a rejecting `<key>_fr` into an unhandled rejection — and the shell stub batch is drained and disabled. `closeAsyncIterator` also contains a synchronously throwing `return()`, so the pump paths (called from `.then` continuations) cannot leak one. Tests: the never-settling source across `getReader().cancel()`, a rejecting `pipeTo` writable, a throwing `pipe` sink, the async-memo flatten path, a custom `options.serializer` `close()`, the render-failure path (never rejects, one `failed`), and a synchronously throwing `return()`. Co-authored-by: Claude via Cursor <[email protected]> --------- Co-authored-by: Ryan Carniato <[email protected]> Co-authored-by: Claude via Cursor <[email protected]>
1 parent fb35efb commit 56918c6

4 files changed

Lines changed: 613 additions & 18 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"solid-js": patch
3+
"@solidjs/web": patch
4+
---
5+
6+
Close a serialized async iterator once the response that carries it is abandoned. When a `renderToStream` consumer cancels the readable or a `pipe` sink throws, the render is disposed, but the tapped iterator handed to the serializer kept delegating `next()` to the source, so an iterable memo, an async memo that resolves to an iterable, and a generator projection kept pulling (or never ran their `finally`) for as long as the source lived. The tapped iterator now answers `done` and calls the source's `return()` once its computation is disposed, and the projection pump closes its source when it stops for disposal. The render's wind-down also closes the serializer, which returns every async iterator it is still pulling — including a source whose pending `next()` never settles, which the disposed check on the next pull could never reach.

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

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1507,18 +1507,18 @@ function processResult<T>(
15071507
// result, then delegate. Later yields deliberately never advance
15081508
// comp.value — the first-value lock, same as the direct branch.
15091509
let tappedFirst = true;
1510+
const close = tappedCloser(() => iter);
15101511
return {
15111512
[Symbol.asyncIterator]: () => ({
15121513
next() {
15131514
if (tappedFirst) {
15141515
tappedFirst = false;
15151516
return Promise.resolve(r);
15161517
}
1518+
if (comp.disposed) return close();
15171519
return iter.next();
15181520
},
1519-
return(value?: any) {
1520-
return iter.return?.(value);
1521-
}
1521+
return: close
15221522
})
15231523
} as any;
15241524
}
@@ -1728,6 +1728,7 @@ function processResult<T>(
17281728

17291729
if (serializes) {
17301730
let tappedFirst = true;
1731+
const close = tappedCloser(() => iter);
17311732
const tapped = {
17321733
[Symbol.asyncIterator]: () => ({
17331734
next() {
@@ -1739,6 +1740,7 @@ function processResult<T>(
17391740
: (firstResult as IteratorResult<T>)
17401741
);
17411742
}
1743+
if (comp.disposed) return close();
17421744
// Deliberately does NOT advance comp.value: the first-value
17431745
// lock. Document markup rendered from V1 must keep reading V1
17441746
// (a Loading retry re-rendering mid-stream would otherwise
@@ -1749,9 +1751,7 @@ function processResult<T>(
17491751
// no hydration claim exists.
17501752
return iter.next().then((r: IteratorResult<T>) => r);
17511753
},
1752-
return(value?: any) {
1753-
return iter.return?.(value);
1754-
}
1754+
return: close
17551755
})
17561756
};
17571757
ctx.serialize(id, tapped, deferStream);
@@ -1832,11 +1832,28 @@ function processResult<T>(
18321832
comp.epoch = ctx?.commitEpoch?.();
18331833
}
18341834

1835+
// Best-effort `return()` on a source we are done with. Nothing here may
1836+
// escape: a rejection is swallowed, and so is a synchronous throw — the
1837+
// callers run from `.then` continuations and the tapped iterator's
1838+
// `next`/`return`, where an uncaught throw becomes an unhandled rejection.
18351839
function closeAsyncIterator(iter: any, value?: any) {
1836-
const returned = iter.return?.(value);
1837-
if (returned && typeof returned.then === "function") {
1838-
returned.then(undefined, () => {});
1839-
}
1840+
try {
1841+
const returned = iter.return?.(value);
1842+
if (returned && typeof returned.then === "function") {
1843+
returned.then(undefined, () => {});
1844+
}
1845+
} catch {}
1846+
}
1847+
1848+
function tappedCloser<T>(iter: () => AsyncIterator<T>) {
1849+
let closed = false;
1850+
return (value?: any): Promise<IteratorResult<T>> => {
1851+
if (!closed) {
1852+
closed = true;
1853+
closeAsyncIterator(iter(), value);
1854+
}
1855+
return Promise.resolve({ done: true, value });
1856+
};
18401857
}
18411858

18421859
// === Effects ===
@@ -2456,6 +2473,7 @@ export function createProjection<T extends object = {}>(
24562473
pumping = null;
24572474
if (disposed || r.done) {
24582475
logDone = true;
2476+
if (!r.done) closeAsyncIterator(iter);
24592477
return;
24602478
}
24612479
// Apply the replacement through the patch-recording draft BEFORE

‎packages/web/src/server.ts‎

Lines changed: 62 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1890,14 +1890,22 @@ export function renderToStream(code, options = {}) {
18901890
const requestEvent = peekRequestEvent();
18911891
let dispose;
18921892
let dead = false;
1893+
// The serializer (created below, once the sink is assembled) — hoisted so
1894+
// the wind-down can close it. `abandon` is only ever reached after the
1895+
// render starts, by which point it is assigned; the hoist keeps that from
1896+
// being a temporal-dead-zone assumption.
1897+
let serializer;
18931898
// Client-disconnect teardown. A sink that throws from `write`/`end` (its
18941899
// transport is gone) or a consumer cancelling the readable view means
18951900
// nobody is listening anymore: stop touching the sink, mark the render
18961901
// completed so pending fragment resolutions stop emitting and
1897-
// serializing, and dispose in-flight reactive work. Containment matters
1898-
// because deferred writes (`writeTasks`, late fragment flushes) run from
1899-
// the microtask queue — an uncontained sink throw there escapes as an
1900-
// unhandled error and can take the host process down.
1902+
// serializing, dispose in-flight reactive work, and close the serializer
1903+
// so every async source it is still pulling (a serialized async iterator
1904+
// whose `next()` may never settle — #3626) is returned now, not on its
1905+
// next pull. Containment matters because deferred writes (`writeTasks`,
1906+
// late fragment flushes) run from the microtask queue — an uncontained
1907+
// sink throw there escapes as an unhandled error and can take the host
1908+
// process down.
19011909
//
19021910
// `disconnect` names the abandonment a finding (`SSR_STREAM_ABANDONED`):
19031911
// the client left — the sink threw or the consumer cancelled — with work
@@ -1919,6 +1927,19 @@ export function renderToStream(code, options = {}) {
19191927
let disconnected = false;
19201928
let failed = false;
19211929
let onFailed;
1930+
// What the render still hands the serializer once it is torn down: a
1931+
// rejection with nobody to hear it is owned here; an iterable is never
1932+
// started, so there is nothing to return.
1933+
const defuse = p => {
1934+
if (p && typeof p.then === "function") p.then(undefined, () => {});
1935+
};
1936+
const abandonedSerializer = {
1937+
write(_, value) {
1938+
defuse(value);
1939+
},
1940+
flush() {},
1941+
close() {}
1942+
};
19221943
const onFailure = complete => {
19231944
if (failed) return complete(undefined);
19241945
const prev = onFailed;
@@ -1957,6 +1978,37 @@ export function renderToStream(code, options = {}) {
19571978
dispose = () => {};
19581979
d();
19591980
}
1981+
// Close the serializer AFTER `dead` is set: seroval's `close()` runs
1982+
// each pending write's cleanup — a serialized async iterator gets its
1983+
// `return()` called (on a microtask, errors swallowed by seroval), which
1984+
// is what reaches a source whose pending `next()` will never settle and
1985+
// so would never hit the disposed check on its next pull — and then
1986+
// fires `onDone`, which must see `dead` to skip assembling a shell for
1987+
// a disposed render. Contained: a custom serializer's `close()` (the
1988+
// seam's contract is `write`/`flush`, `close` is optional) must not be
1989+
// able to escape the teardown. A throw here is the serializer's failure,
1990+
// so it goes where its other failures go (`handling: "serialize"`,
1991+
// through the render's hook, else the ambient one); with no hook there
1992+
// is nobody to tell and nothing left to protect — the render is already
1993+
// torn down — so it is dropped.
1994+
if (serializer && typeof serializer.close === "function") {
1995+
try {
1996+
serializer.close();
1997+
} catch (err) {
1998+
reportServerError(err, { kind: "render", handling: "serialize" }, null, options.onError);
1999+
}
2000+
}
2001+
// A closed serializer drops writes without looking at them, but the
2002+
// render's promises still settle and the paths that hand them over still
2003+
// run (`registerFragment`'s `<key>_fr`, `context.serialize`) — and a
2004+
// rejection seroval would have consumed is an unhandled one when nobody
2005+
// takes it. Own them instead: every later write, and everything batched
2006+
// for the shell but not yet written, is defused.
2007+
serializer = abandonedSerializer;
2008+
if (stubBatch) {
2009+
for (const p of stubBatch.values()) defuse(p);
2010+
stubBatch = null;
2011+
}
19602012
if (!disconnect) {
19612013
failed = true;
19622014
onFailed && onFailed(sink);
@@ -2225,7 +2277,7 @@ export function renderToStream(code, options = {}) {
22252277
// flows through onData is a contract between the serializer and the sink
22262278
// (hydration scripts for the document sink, keyed codec records for the
22272279
// frame sink); the core never inspects it.
2228-
const serializer = (options.serializer || createHydrationSerializer)({
2280+
serializer = (options.serializer || createHydrationSerializer)({
22292281
scopeId: options.renderId,
22302282
// Containers (projections) serialize as traces on BOTH faces — the
22312283
// document's hydration serializer and the frame sink's codec resolve
@@ -2565,8 +2617,9 @@ export function renderToStream(code, options = {}) {
25652617
// `shellCompleted` (not `firstFlushed`) gates batching: doShell()
25662618
// flushes the batch into the shell's task snapshot, and writes in the
25672619
// microtask window between the two flags must go direct or they'd
2568-
// strand in a batch nobody flushes.
2569-
if (!firstFlushed && canBatchStubs && !shellCompleted) {
2620+
// strand in a batch nobody flushes — as would a write after the
2621+
// wind-down (`dead`), which goes direct to be defused.
2622+
if (!firstFlushed && canBatchStubs && !shellCompleted && !dead) {
25702623
(stubBatch ||= new Map()).set(id, p);
25712624
return;
25722625
}
@@ -2613,7 +2666,8 @@ export function renderToStream(code, options = {}) {
26132666
})
26142667
)
26152668
});
2616-
if (canBatchStubs && !shellCompleted) (stubBatch ||= new Map()).set(key + "_fr", p);
2669+
if (canBatchStubs && !shellCompleted && !dead)
2670+
(stubBatch ||= new Map()).set(key + "_fr", p);
26172671
else serializer.write(key + "_fr", p);
26182672
}
26192673
return (value, error) => {

0 commit comments

Comments
 (0)