Repository navigation
Conversation
When a JavaScript ReadableStream is piped to a JavaScript WritableStream, WritableStreamJsController::pipeLoop() started each iteration by returning the next pipeLoop() from the previous iteration's read and write continuations. Each iteration's promise was then resolved with the next one's, so every one stayed pending until the pipe ended. A pipe kept a few promises per chunk alive, and long pipeThrough() chains ran Durable Objects out of memory (cloudflare#8901). pipeLoop() now takes the resolver for the loop's outcome. The continuations start the next iteration and return nothing, so no iteration's promise waits on another's, and each terminal branch in a continuation settles the resolver directly. The reference implementation fixed the same leak this way in whatwg/streams#968. A pipe can also end during the first pipeLoop() call, which runs inside tryPipeFrom(), when either stream has already closed or errored or the signal has already aborted. pipeLoop() returns that outcome, and tryPipeFrom() attaches its handlers to it in the same turn, as before. Settling the resolver with it instead would attach them a microtask later. Without unhandled_rejection_after_microtask_checkpoint, an outcome that is already rejected would then be reported as an unhandled rejection, although the caller handles pipeTo(). Once pipeLoop() has scheduled a read it returns kj::none, and tryPipeFrom() attaches the handlers to the loop's promise. The new pipe-loop-promise-chain-test counts the microtasks between the destination's close() and pipeTo() settling. On main it takes 2004 for 1000 chunks and 7 for 1 chunk, one per link in the chain; with this change the count no longer depends on the chunk count. A second case pipes into a destination that errors in start() and checks that no unhandledrejection event fires. There is no compatibility flag. Apart from the case below, the value and rejection reason that pipeTo() settles with don't change; only the microtask timing does. A pipe of n chunks now settles 3n+7 microtasks after the pipeTo() call, against 5n+7 before. Both that count and the one from close() to settling grew with the chunk count before this change, so no Worker can rely on them. A flag would also keep the leak for every Worker on an older compatibility date, including the one in cloudflare#8901. One case does change. If a pipe continuation itself throws (the KJ_ASSERT_NONNULL in PipeLocked::read, execution termination, or a rare synchronous throw from .then()), the throw now rejects a promise nothing holds, so pipeTo() stays pending where it used to reject. That rejection probably also surfaces as an unhandledrejection event, and the pipe lock stays held, so both streams stay locked. Neither path was run.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
This pull request was not reviewed automatically because its author does not have write access to this repository. A maintainer with write access can start a review by commenting |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2f96a2e21e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // on the stack. Keep it alive until the read returns. | ||
| auto sourceRef = pipeLock.readableStreamRef.addRef(); | ||
| return pipeLock.source->read(js).then(js, kj::mv(onSuccess), kj::mv(onFailure)); | ||
| pipeLock.source->read(js).then(js, kj::mv(onSuccess), kj::mv(onFailure)); |
There was a problem hiding this comment.
Propagate dropped continuation failures to the loop resolver
With the default preventAbort: false, if a pending source read errors with an object whose overloaded or retryable accessor throws, the read's failure continuation re-enters pipeLoop(), and WritableImpl::abort() throws while AbortSignal::triggerAbort() converts that reason. V8 then rejects the promise produced on this line, but the new code discards that promise instead of returning it, so loop.resolver is never settled and source.pipeTo(destination) remains pending indefinitely (with an unhandled derived rejection); the old chain propagated the exception. Route failures from the dropped read/write continuation promises into resolver.
Useful? React with 👍 / 👎.
|
Ahead of folks spending cycles here: on #8787, james'd said the plan was to replace the C++ streams implementation with the TypeScript one, so I ran the #8901 repro against it. On main (e7d43bd) with typescript_implemented_streams, live promises hold at 43 for the whole 20 s run, against 3,491 to 17,381 on the C++ path. So the TypeScript implementation already fixes this. This being said, the C++ path is still the default, and it's what the Durable Objects in #8901 run today. If a C++ fix is worth carrying until the TypeScript implementation ships, I'll finish this one. If it isn't worth it, I'll close this. I've moved it to draft until then! |
When a JS-backed
ReadableStreampipes to a JS-backedWritableStream, each read and write continuation inWritableStreamJsController::pipeLoop()returns the nextpipeLoop()call's promise. Every iteration's promise is resolved with the next one's, so the whole chain stays pending until the pipe ends. With 3 identitypipeThrough()stages at about 200 chunks/s, live promises on main climb from 3,491 at 4 s to 17,381 at 20 s.#8901 reports Durable Objects hitting their memory limit this way on AI SDK streams with about 15 stages. I found the issue while looking for open workerd bugs and reproduced it on workerd 1.20261125.1 before writing this. The recursive shape goes back to the initial import (a265d5c), and #7738 last rewrote these lines.
pipeLoop()now takes the resolver for the loop's outcome. Each terminal branch in a continuation settles that resolver with the promise it used to return. The continuations start the next iteration without returning anything, so no iteration waits on another. When the pipe ends on its first iteration,pipeLoop()returns the outcome synchronously as on main, andtryPipeFrom()attaches its handlers in the same turn. Settling through the resolver there would attach them a microtask later, so a destination that errored instart()would raise anunhandledrejectionevent that main doesn't. whatwg/streams#968 fixed the same leak in the reference implementation this way. I kept the loop's resolver separate from the pipe lock's. Underpipe_to_backward_propagation,shutDown()settles the pipe lock's resolver directly, and the loop's later outcome has to stay ignored there.There's no compat flag. #7738 gated its
pipeTo()change, which moved the rejection reason as well as its timing. Apart from the throw case below, the value, rejection reason, and side effects stay the same. Only the microtask timing changes: a pipe of n chunks settles 3n+7 microtasks after thepipeTo()call, against 5n+7 on main. On main, the count from the destination'sclose()to settling also grows with the chunk count: 2004 for 1000 chunks, 7 for 1. So I don't think any Worker can depend on either. A flag would also keep the leak for every Worker on an older compatibility date, including the one in #8901. If you want a rollout switch anyway, I can put it behind an autogate.With the fix, the same repro holds at 38 live promises for all 20 s, the count a hand-written reader/writer loop over the same 3 stages gives. The new
pipe-loop-promise-chain-testfails on main and passes here, and the WPT streams results are identical before and after across 1460 subtests. The test's second case pipes into a destination that errors instart()and checks that nounhandledrejectionevent fires, as on main.One behavior I know changes: an exception thrown inside a pipe continuation itself (a rejected read or write still reaches the resolver) now rejects a dropped promise, so
pipeTo()stays pending where it used to reject. That rejection probably also shows up as anunhandledrejectionevent, and the pipe lock stays held, so both streams stay locked; I haven't run that path. The sources I found are theKJ_ASSERT_NONNULLinPipeLocked::read, execution termination, and a synchronous throw from.then()itself, whichstandard.c++notes can happen in rare cases such as out of memory. I only ran this on macOS arm64, and didn't run clang-tidy, ASan, orbazel test //....docs/streams.mdand the streams README already describe this loop as equivalent to afor awaitloop, so I left them alone.CONTRIBUTING asks for discussion before a change like this, and #8901 has no reply yet. The branch is on main at e7d43bd and touches the same return sites as #8835. If you'd rather land #8835 first, I'll rebase onto it; if you'd rather fix this in-house, feel free to close this.
Fixes #8901.
Measurements
Inspector repro, 3 pipeThrough stages: 17,381 live promises at 20 s on main, 38 with this change
The Worker is the repro from #8901 (compat date 2024-04-03,
nodejs_compat_v2). Each run isworkerd serve config.capnp --inspector-addr=127.0.0.1:9229, samplingRuntime.queryObjects(Promise.prototype)every 4 s. Same machine (macOS arm64), 2026-11-27. Each run usesseconds=22, so the stream outlasts the 20 s sample and pipes 4,400 chunks (the response'sdone 4401counts the closing pull). The issue's default,seconds=20, pipes 4,000.All 6 runs went back to back, the pipes=3 rows first. The main binary is this branch's tree with
standard.c++checked out from e7d43bd. Main and this branch carry V8 15.9.128.39 from #8900; the npm release carries 15.8.62.5.A hand-written reader/writer loop over the same 3
TransformStreams on 1.20261125.1 stays at 38 for all 5 samples.pipe-loop-promise-chain-test: leak case fails 3/3 on main (2004 !== 7), unhandledrejection case fails 3/3 on the earlier fix without its first-iteration return, both pass 3/3 on this branch and 10/10 on reruns
@all-compat-flagspasses without the first-iteration return becauseunhandled_rejection_after_microtask_checkpointis on there, so the late handler still lands in time. The case relies on the default date because the regression needspipe_to_backward_propagationoff; with it on, main fires the event too without the checkpoint flag, so@all-compat-flagscan't separate them.Existing streams tests and WPT on this branch: all pass; WPT subtest results identical to main
The
@gc-stresstargets ran on their own, with--test_tag_filters=gc-stress.//src/wpt:streams@gc-stressfails on both main and this branch, in the same 2 files (readableStreamsGarbageCollectionAnyandreadableStreamsGeneralAny, "detected that your Worker's code had hung"). The 1460 (subtest, status) pairs are identical between main and this branch in all 3 WPT variants.Pipe behavior battery, 47 cases x 2 flag settings x 3 reps: outcome and unhandledrejection events match main in all 47, callback logs in 46
Each case pipes a JS
ReadableStreaminto a JSWritableStreamand records howpipeTo()settles, the order of source and sink callbacks, and everyunhandledrejectionevent. The cases cover 0 to 1000 chunks,preventClose, source and destination errors early and mid-pipe, streams closed or errored before the pipe, aborts,pipeThrough, and 2 concurrent pipes. The binaries are main e7d43bd and this branch 2f96a2e, with each rep in its own workerd process. In the plain cases with 0 to 1000 chunks,pipeTo()settles 5n+7 microtasks after the call on main and 3n+7 on this branch, in both flag settings (5007 and 3007 at n=1000).Outcome and
unhandledrejectionevents match in all 47 cases withpipe_to_backward_propagationoff and on. The callback log differs only in "plain n=5 async both", which is still pending at its 300 ms cutoff on both binaries. With the flag off, its log varies between reps on both binaries alike. With it on, main gave the shorter log in 2 of 3 reps and this branch in 0 of 3. Run 10 times in one process, both binaries gave the shorter log 10 of 10 times in both flag settings.