Repository navigation
Streams: lifetime and termination handling fixes, backward error propagation in pipeTo() - #7738
Merged
Merged
Conversation
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>
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
Specialist findings not posted (3)
Reviewed commit: 485b7b9a · github run |
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
force-pushed
the
dlapid/streams-pipe-lifetimes
branch
from
October 14, 2026 04:57
3901850 to
485b7b9
Compare
jasnell
approved these changes
Oct 14, 2026
Collaborator
Author
|
Addressed the review-level suggestions:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
When a Worker exceeds its CPU limit, V8 terminates execution and the exception unwinds through the streams C++ code without running
JSG_CATCHblocks. 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):
kj: Throw on null Ptr<T> dereference;releaseSource()compares itsPtrwithnullptrinstead of callingget().addExceptionDetail(): let a termination keep unwinding instead of treating it as an unserializable value (caught by a V8 debug DCHECK inRunMicrotasks()). TheTryCatch's destructor hands it back to V8; an explicitReThrow()is fatal when no JavaScript is on the stack.doError(), the write-side pipe lock was left with no source;pipeLoop()now detects this and finishes tearing down.Pipethat the read may have destroyed. Covered by new tests instandard-test.c++andinternal-test.c++.KJ_DEFER: inWritableImpl::abort(),ReadableImpl::enqueue()andReadableStreamJsController::cancel().scopedOperation()instead of manualbeginOperation()/endOperation(); unlock the readable even if its cancel throws. The streams README now documents the RAII form.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).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. Enablespiping/error-propagation-backward.any.jsandpiping/close-propagation-backward.any.js, and one more test inpiping/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