Skip to content

Stop pipeLoop from chaining a promise per chunk - #8962

Draft
oddharsh wants to merge 1 commit into
cloudflare:mainfrom
oddharsh:fix/pipeloop-promise-chain
Draft

oddharsh wants to merge 1 commit into
cloudflare:mainfrom
oddharsh:fix/pipeloop-promise-chain

Conversation

@oddharsh

Copy link
Copy Markdown

When a JS-backed ReadableStream pipes to a JS-backed WritableStream, each read and write continuation in WritableStreamJsController::pipeLoop() returns the next pipeLoop() 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 identity pipeThrough() 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, and tryPipeFrom() attaches its handlers in the same turn. Settling through the resolver there would attach them a microtask later, so a destination that errored in start() would raise an unhandledrejection event 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. Under pipe_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 the pipeTo() call, against 5n+7 on main. On main, the count from the destination's close() 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-test fails 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 in start() and checks that no unhandledrejection event 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 an unhandledrejection event, and the pipe lock stays held, so both streams stay locked; I haven't run that path. The sources I found are the KJ_ASSERT_NONNULL in PipeLocked::read, execution termination, and a synchronous throw from .then() itself, which standard.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, or bazel test //.... docs/streams.md and the streams README already describe this loop as equivalent to a for await loop, 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 is workerd serve config.capnp --inspector-addr=127.0.0.1:9229, sampling Runtime.queryObjects(Promise.prototype) every 4 s. Same machine (macOS arm64), 2026-11-27. Each run uses seconds=22, so the stream outlasts the 20 s sample and pipes 4,400 chunks (the response's done 4401 counts 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.

Binary Query 4 s 8 s 12 s 16 s 20 s Heap at 20 s
main e7d43bd pipes=3 3,491 6,953 10,433 13,889 17,381 1.14 MB
this branch 2f96a2e pipes=3 38 38 38 38 38 0.28 MB
1.20261125.1 (npm) pipes=3 3,575 7,127 10,703 14,267 17,837 1.16 MB
all 3 pipes=0 11 11 11 11 11 0.27 MB

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
$ bazel test //src/workerd/api/tests:pipe-loop-promise-chain-test@ //src/workerd/api/tests:pipe-loop-promise-chain-test@all-compat-flags //src/workerd/api/tests:pipe-loop-promise-chain-test@all-autogates --nocache_test_results --test_output=errors

# standard.c++ at e7d43bddb
AssertionError: Values are not strictly equal:
-   2004
+   7
[ FAIL ] pipe-loop-promise-chain-test:pipeToSettlesInTicksIndependentOfChunkCount
Executed 3 out of 3 tests: 3 fail locally.

# the earlier fix without its first-iteration return, applied to e7d43bddb (--test_output=all)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ [ 'Error: early' ]
- []
[ FAIL ] pipe-loop-promise-chain-test:pipeToErroredDestinationReportsNoUnhandledRejection
//src/workerd/api/tests:pipe-loop-promise-chain-test@all-compat-flags    PASSED in 2.5s
//src/workerd/api/tests:pipe-loop-promise-chain-test@                    FAILED in 2.5s
//src/workerd/api/tests:pipe-loop-promise-chain-test@all-autogates       FAILED in 2.6s
Executed 3 out of 3 tests: 1 test passes and 2 fail locally.

# HEAD 2f96a2e21
//src/workerd/api/tests:pipe-loop-promise-chain-test@                    PASSED in 4.2s
//src/workerd/api/tests:pipe-loop-promise-chain-test@all-autogates       PASSED in 4.2s
//src/workerd/api/tests:pipe-loop-promise-chain-test@all-compat-flags    PASSED in 4.2s
Executed 3 out of 3 tests: 3 tests pass.

@all-compat-flags passes without the first-iteration return because unhandled_rejection_after_microtask_checkpoint is on there, so the late handler still lands in time. The case relies on the default date because the regression needs pipe_to_backward_propagation off; with it on, main fires the event too without the checkpoint flag, so @all-compat-flags can't separate them.

Existing streams tests and WPT on this branch: all pass; WPT subtest results identical to main
//src/workerd/api:streams/standard-test@                                 PASSED
//src/workerd/api:streams/standard-test@all-autogates                    PASSED
//src/workerd/api:streams/termination-injection-test@                    PASSED (7 shards)
//src/workerd/api:streams/termination-injection-test@all-autogates       PASSED (7 shards)
//src/workerd/api/tests:leak-fetch-test@                                 PASSED
//src/workerd/api/tests:pipe-source-error-uaf-test@                      PASSED
//src/workerd/api/tests:pipe-source-error-uaf-test@all-compat-flags      PASSED
//src/workerd/api/tests:pipe-source-error-uaf-test@gc-stress             PASSED
//src/workerd/api/tests:streams-error-edge-cases-test@                   PASSED
//src/workerd/api/tests:streams-error-edge-cases-test@all-compat-flags   PASSED
//src/workerd/api/tests:streams-error-edge-cases-test@gc-stress          PASSED
//src/workerd/api/tests:pipe-loop-promise-chain-test@gc-stress           PASSED
//src/wpt:streams@                                                       PASSED
//src/wpt:streams@all-autogates                                          PASSED

The @gc-stress targets ran on their own, with --test_tag_filters=gc-stress. //src/wpt:streams@gc-stress fails on both main and this branch, in the same 2 files (readableStreamsGarbageCollectionAny and readableStreamsGeneralAny, "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 ReadableStream into a JS WritableStream and records how pipeTo() settles, the order of source and sink callbacks, and every unhandledrejection event. 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 unhandledrejection events match in all 47 cases with pipe_to_backward_propagation off 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.

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.
@oddharsh
oddharsh requested review from a team as code owners November 27, 2026 20:26
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T20:30:42.365502Z 2f96a2e PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clanky-the-clanker

Copy link
Copy Markdown

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 clanky review (or clanker review or @clanky-the-clanker review), optionally followed by instructions (e.g. clanky review focus on the retry logic).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

@oddharsh
oddharsh marked this pull request as draft November 27, 2026 21:08
@oddharsh

Copy link
Copy Markdown
Author

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Bug Report — Runtime APIs: pipeTo/pipeThrough between JS-backed streams retains ~2 pending promises per chunk until the pipe ends

1 participant