Skip to content

Streams: lifetime and termination handling fixes, backward error propagation in pipeTo() - #7738

Merged
danlapid merged 8 commits into
mainfrom
dlapid/streams-pipe-lifetimes
Oct 14, 2026
Merged

danlapid merged 8 commits into
mainfrom
dlapid/streams-pipe-lifetimes

Conversation

@danlapid

@danlapid danlapid commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

When a Worker exceeds its CPU limit, V8 terminates execution and the exception unwinds through the streams C++ code without running JSG_CATCH blocks. The isolate is reused afterwards, so any bookkeeping skipped by that unwind can still be reached by later continuations. This PR makes the streams implementation robust to that, fixes a pipe source lifetime issue, and adds a test that injects termination at every C++ → JS call across ~30 streams scenarios.

Commits, in order (each builds and passes tests on its own):

  1. Update capnp-cpp to b5ee48b: picks up kj: Throw on null Ptr<T> dereference; releaseSource() compares its Ptr with nullptr instead of calling get().
  2. jsg: Don't swallow termination in addExceptionDetail(): let a termination keep unwinding instead of treating it as an unserializable value (caught by a V8 debug DCHECK in RunMicrotasks()). The TryCatch's destructor hands it back to V8; an explicit ReThrow() is fatal when no JavaScript is on the stack.
  3. streams: Finish pipe teardown when the source was released: if the source's cancel algorithm throws during doError(), the write-side pipe lock was left with no source; pipeLoop() now detects this and finishes tearing down.
  4. streams: Keep a pipe's source alive across its read: a pull algorithm that ends the pipe could drop the last reference to the source while its read was on the stack. The internal loop also built its continuations from a Pipe that the read may have destroyed. Covered by new tests in standard-test.c++ and internal-test.c++.
  5. streams: Don't call into JavaScript from KJ_DEFER: in WritableImpl::abort(), ReadableImpl::enqueue() and ReadableStreamJsController::cancel().
  6. streams: Keep operation and lock bookkeeping exception safe: scopedOperation() instead of manual beginOperation()/endOperation(); unlock the readable even if its cancel throws. The streams README now documents the RAII form.
  7. streams: Add a termination injection test: streams/termination-injection-test.c++. It also fails if an injected termination is swallowed before the end of the run (after each step it enters JavaScript once more, so V8 delivers a pending termination before a microtask checkpoint can end it).
  8. streams: Propagate destination errors backward through pipeTo(): pipeTo() now rejects (rather than resolving or hanging) when the destination errors or closes mid-pipe, with the cancel's error taking precedence per the spec. Enables piping/error-propagation-backward.any.js and piping/close-propagation-backward.any.js, and one more test in piping/abort.any.js. This changes observable pipe outcomes, so it is behind a new compatibility flag, pipe_to_backward_propagation (enabled from 2026-11-17); the piping tests cover both behaviors.

Testing: streams unit tests, the new termination injection test (5 runs, and under ASAN), the streams WPT suites (plain, all-autogates, TS variant), and other stream/fetch/compression tests.

🤖 Generated with Claude Code

Picks up "kj: Throw on null Ptr<T> dereference", which makes
Ptr::get(), operator->() and asRef() throw instead of returning a
null pointer when the Ptr is null, and adds comparing a Ptr with
nullptr.

WritableLockImpl's releaseSource() used get() to check whether it
had already released the source, which now throws once it has.
Compare the Ptr with nullptr instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@danlapid
danlapid requested review from a team as code owners October 14, 2026 03:56
@ask-bonk

ask-bonk Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Since last review: 3 resolved, 1 still open, 1 new.

Updates stream termination handling, pipe lifetime coverage, and compatibility-gated backward pipe error propagation.

Other findings

  • [INFO] src/workerd/api/streams/standard.c++:202: These comments describe shutDown() as always settling/rejecting the pipeTo() promise, but the new flag-off branch intentionally leaves it to the loop, which can resolve it or leave a pending read outstanding. Qualify this comment and the shutDown() declaration comment by compatibility-flag state.

        // Settles the promise returned by pipeTo(). The pipe loop's own outcome feeds it, but when
        // backward propagation is enabled, an external destination error or close can end a pipe
        // stalled on a read, so shutDown() settles it directly.
        jsg::Promise<void>::Resolver resolver;
    
Specialist findings not posted (3)
  • tests#1 [WARNING] src/workerd/io/compatibility-date.capnp:1704: The new flag promises to wait for the source cancel and substitute its rejection reason, but the added piping tests only use synchronous, successful cancel() callbacks. Thus a regression that reject… — The re-enabled WPT backward-propagation suites cover the enabled compatibility branch, beyond the synchronous local regression cases.
  • tests#2 [WARNING] src/tests/streams/piping/pipe-matrix.js:1167: The flag-on assertion observes pipePromise only after rc.close() completes the source's pending read. It therefore passes if the new backward-close path leaves the pipe pending until that read com… — The re-enabled WPT close-propagation suite covers the flag-on stalled-read shutdown outcome; the local cleanup ordering is not independently actionable.
  • compat-flags#1 [WARNING] src/workerd/api/streams/standard.c++:608: The new compatibility branch has no coverage with pipe_to_backward_propagation enabled. The only added standard-stream exercise compiles flags for 2026-10-01 (before this flag's 2026-11-17 enabl… — The piping @all-compat-flags variant exercises the flag-on branch, and the re-enabled WPT suites provide the focused outcome coverage.

Reviewed commit: 485b7b9a · github run

Comment thread src/workerd/api/streams/standard.c++ Resolved
Comment thread src/workerd/api/streams/standard.c++ Resolved
Comment thread src/workerd/api/streams/internal.c++ Resolved
@danlapid danlapid changed the title Update capnp-cpp to b5ee48b Streams: lifetime and termination handling fixes, backward error propagation in pipeTo() Oct 14, 2026
danlapid and others added 7 commits October 14, 2026 04:50
addExceptionDetail() serializes a JS exception into a detail on the
kj::Exception, and treats any failure to serialize as "this value
isn't serializable" and moves on. When execution is being terminated
(e.g. the Worker exceeded its CPU limit), that also swallowed the
termination, so the caller carried on as if JavaScript could still
run.

V8 debug builds catch this with a DCHECK in RunMicrotasks() when it
happens in a microtask, e.g. an AbortSignal triggered by a stream
being aborted.

Let the termination continue to unwind instead. The TryCatch's
destructor hands it back to V8 when JavaScript is on the stack. An
explicit ReThrow() would also leave an exception pending when no
JavaScript is on the stack to receive it (e.g. a call from Rust),
which V8 treats as fatal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the destination of a pipe errors, doError() releases the pipe's
source, canceling it, and then drops the write-side pipe lock. If the
source's cancel algorithm throws an exception that JSG_CATCH doesn't
handle, such as execution being terminated for exceeding the CPU
limit, releaseSource() has already cleared the lock's pointer to the
source but the write-side lock is never released. The isolate is
reused afterwards, so later continuations of the pipe loop could
still reach that lock and use the source it no longer has.

pipeLoop() now checks isSourceReleased() at the start of each
iteration and after each read, and finishes tearing the pipe down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reading from a JS-backed source can run its pull algorithm
synchronously. If that code ends the pipe, for example by erroring
the destination, the pipe drops its reference to the source while the
source's read is still on the stack. That reference can be the last
one, so the source's controller could be destroyed under the read.

Hold a reference to the source for the duration of the read, in both
the JS-backed and the internal pipe loops.

The internal loop also built its continuations from the Pipe after
the read returned, by which point the Pipe itself may have been torn
down. Take what the continuations need before starting the read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
WritableImpl::abort(), ReadableImpl::enqueue() and
ReadableStreamJsController::cancel() ran cleanup that calls into
JavaScript (startErroring(), pullIfNeeded() and the lock's
close/error notifications) from KJ_DEFER. That runs JavaScript while
an exception unwinds. And when the deferred code itself throws after
the function's return value has been constructed, as it does when
execution is terminated, the return value is never destroyed: ASAN
reported the promise handle from abort() leaking.

Do the work inline after the main operation instead. When the
consumer's cancel() throws, cancel() still marks the stream closed,
but no longer notifies the lock, since that would run JavaScript
during the unwind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
deferControllerStateChange() and both onConsumerWantsData() overrides
paired beginOperation() and endOperation() by hand. The end was
skipped when the callback threw an exception that JSG_CATCH doesn't
handle, such as execution being terminated, leaving the stream with
an operation open forever: every later close or error stayed deferred
and the stream stopped making progress. Use the existing
scopedOperation() guard, which also ends the operation on unwind.

Similarly, ReadableLockImpl::releasePipeLock() skipped unlocking the
readable when the cancel algorithm threw. The caller has already let
go of the pipe by then, so the readable stayed pipe-locked for good.
Unlock it in a KJ_DEFER; the transition runs no JavaScript.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When a Worker exceeds its CPU limit, V8 terminates execution: the
next call into JavaScript fails, and the failure unwinds through
whatever C++ made the call, skipping JSG_CATCH blocks. The isolate is
then reused, so stream state left half-updated by the unwind can
still be reached by later continuations, microtasks and the GC.

The test runs about 30 streams scenarios (pipes, tees, transforms,
readers, writers, byte streams, ...) once to count their calls from
C++ into JavaScript, using a BeforeCallEnteredCallback, and then once
per call, terminating execution at it. After each terminated run it
cancels the termination, pokes every stream, reader, writer and
controller the scenario created, drains the microtask queue and
forces a full GC. It fails on KJ assertions, on C++ exceptions that
surface to JavaScript as internal errors, and on runs that never
finish (a watchdog thread terminates those). Under ASAN it also
catches leaks. When an injected termination doesn't reach the end of
the run, something caught it and carried on, so that fails too. V8
only delivers a requested termination at JavaScript's next interrupt
check, so the test enters JavaScript once more after each step to
deliver it before the microtask checkpoint, where V8 ends a
termination itself.

Scenario steps after the first are called directly from C++ rather
than chained on promises, because V8 drops the rest of the microtask
queue when execution is terminated inside a microtask, which would
hide the continuations that do survive in production.

The previous commits fix what this test found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the destination of a pipeTo() errored or closed while the pipe
loop was waiting on a read, doError()/doClose() released the source
and dropped the write-side lock, and left the pipe's promise to the
loop. With the source canceled, the pending read then resolved as
done, and the loop, finding no lock, resolved the pipe as if it had
succeeded. With preventCancel, the read never completed and the pipe
never settled.

pipeTo() now returns a promise backed by its own resolver, stored in
the write-side pipe lock. The loop's outcome still feeds it, but
doError() and doClose() settle it directly through the new
PipeLocked::shutDown(). Following the spec's "shutdown with an
action", releaseSource() now returns the promise of the source's
cancel, and the pipe rejects with the destination's error once the
cancel completes, or with the cancel's error if it fails. The loop's
own backward-propagation branches and its write-failure path use the
same rule.

releaseSource() cancels the source through its controller while it
is still pipe-locked, then releases the lock without an error. The
release runs from a KJ_DEFER so that the readable is unlocked even if
the cancel throws.

This changes when, and with what, a pipe to a JavaScript-backed
WritableStream settles, so it is behind a new compatibility flag,
pipe_to_backward_propagation, enabled from 2026-11-17. Without the
flag, the pipe's promise is still left to the loop and a failed cancel
is not reported.

With the flag, piping/error-propagation-backward.any.js and
piping/close-propagation-backward.any.js pass, so they are enabled,
along with one more test in piping/abort.any.js. The piping tests
expect the new outcome when the flag is on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@danlapid
danlapid force-pushed the dlapid/streams-pipe-lifetimes branch from 3901850 to 485b7b9 Compare October 14, 2026 04:57
@danlapid

Copy link
Copy Markdown
Collaborator Author

Addressed the review-level suggestions:

  • README: the deferred-transition pattern now shows scopedOperation() with explicit end() only to inspect the result.
  • releaseSource() comment and README pipe-lock rule: they now say the source stays pipe-locked while its cancel algorithm is invoked, and that the pipe promise may stay pending on the cancel after the lock is released.
  • IsPipeThrough is now a WD_STRONG_BOOL.

@danlapid
danlapid merged commit ab0ee32 into main Oct 14, 2026
56 of 58 checks passed
@danlapid
danlapid deleted the dlapid/streams-pipe-lifetimes branch October 14, 2026 16:17
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.

2 participants