Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions build/deps/gen/deps.MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ bazel_dep(name = "brotli", version = "1.2.0.bcr.3")
# capnp-cpp
http.archive(
name = "capnp-cpp",
sha256 = "9ee3c9c1d193e784d7413b5399caf77110e1ed3d8423adb42e64759e7734842b",
strip_prefix = "capnproto-capnproto-35e6067/c++",
sha256 = "cc15b6f82a2c91ae15c52410305c7d0db7a81e1fb0d5add49fd8a9d5d4b3b179",
strip_prefix = "capnproto-capnproto-b5ee48b/c++",
type = "tgz",
url = "https://github.com/capnproto/capnproto/tarball/35e606794552c0a318d41d54488b64f2c5eaf03e",
url = "https://github.com/capnproto/capnproto/tarball/b5ee48b9f3586fc83af8c429623e2c0d2435ec59",
)
use_repo(http, "capnp-cpp")

Expand Down
14 changes: 8 additions & 6 deletions src/tests/streams/piping/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ identity suite's pipe-integration.js.

The suite COMPLEMENTS WPT (`//src/wpt:streams`). The C++ seeds in
piping/error-propagation-forward largely root-cause to harness shapes
plus ledger #5/#6 below; piping/close-propagation-backward and
error-propagation-backward are DISABLED for hangs — this suite covers
that territory with BOUNDED observations (a pinned 'pending' outcome is
a deliberate defect pin, not a hole).
plus ledger #5/#6 below. piping/close-propagation-backward and
error-propagation-backward pass with `pipe_to_backward_propagation`,
which the WPT run enables through its future compatibility date; this
suite pins the unflagged behavior with BOUNDED observations (a pinned
'pending' outcome is a deliberate defect pin, not a hole).

## Divergence ledger (C++ vs TypeScript)

Expand All @@ -21,10 +22,10 @@ a deliberate defect pin, not a hole).
| 1 | non-byte chunks piped into native identity | strings are UTF-8 encoded and pass through on both; the NUMBER chunk fails the pipe — C++ rejects 'This WritableStream only supports writing byte types.'; TypeScript surfaces the identity validation TypeError through the non-fatal write-rejection pipe path (dest aborted, downstream reads reject) | `pipeThroughJsToInternal` |
| 2 | writable lock after a completed pipeThrough | stays locked; getWriter throws | spec finalize: both locks release when the pipe settles — one macrotask after the output's done, `.locked` is deterministically false and getWriter() succeeds (the release cascade is not synchronized with the output's done delivery, so loop-exit-instant reads are unspecified; `.locked` and getWriter share one predicate and never disagree at an instant) | `pipeThroughJsToInternalCloses` |
| 3 | write-after-close rejection message | 'This WritableStream has been closed.' | 'Cannot write to a stream that is closing or closed' (`CLOSED_WRITE_MSG` helper) | `pipeToInternalToJsSimple`, `pipeToInternalToJsClose` |
| 4 | ws.close() queued BEFORE pipeTo | pipe locks both ends, waits, cancels source with 'This destination writable stream is closed.', then RESOLVES (see the TODO(conform) in the test) | pipe REJECTS IMMEDIATELY 'Destination closed before the pipe completed', cancels source with the same error (preventCancel suppresses), locks never observed held | `pipeToJsToJsCloseQueuedDestination`(+`PreventCancel`) |
| 4 | ws.close() queued BEFORE pipeTo | pipe locks both ends, waits, cancels source with 'This destination writable stream is closed.', then RESOLVES; with `pipe_to_backward_propagation` it rejects with that TypeError (spec) | pipe REJECTS IMMEDIATELY 'Destination closed before the pipe completed', cancels source with the same error (preventCancel suppresses), locks never observed held | `pipeToJsToJsCloseQueuedDestination`(+`PreventCancel`) |
| 5 | pipeTo brand check on a broken `this` | THROWS synchronously (before the capture_async_api_throws wrapper; the WPT general.any seed); a real stream with a bad destination REJECTS | both reject (spec) | `brandChecks` |
| 6 | destination hwm 0 (never desires) | pipe writes an available chunk anyway — ignores desiredSize (the WPT 'dest never desires chunks' seed family) | never writes (spec) | `sourceErroredAfterChunkHwmZero` |
| 7 | dest controller error()s while the pipe waits on a read | HALF-PROPAGATES: cancels the source with the error but FULFILLS the pipe promise | rejects the pipe and cancels the source with the error (spec) | `destControllerErrorsMidPipe`, `destErroringWaitsForInFlightWrite` |
| 7 | dest controller error()s while the pipe waits on a read | HALF-PROPAGATES: cancels the source with the error but FULFILLS the pipe promise; with `pipe_to_backward_propagation` it rejects with the error (spec) | rejects the pipe and cancels the source with the error (spec) | `destControllerErrorsMidPipe`, `destErroringWaitsForInFlightWrite` |
| 8 | FixedLengthStream length violations via pipe | overflow: pipe NEVER SETTLES (bounded); underflow: never settles | overflow: rejects RangeError; underflow: never settles (parity of nonconformance) | `fixedLengthStreamPipeOverflow`/`Underflow` |
| 9 | already-closed source → already-closed dest | rejects TypeError (a C++ deviation: the spec's ordered shutdown conditions give closing-forward priority) | FULFILLS (spec; WPT multiple-propagation 'closed readable to closed writable' pins the fulfillment) | `closedSourceToClosedDest` |
| 10 | SharedArrayBuffer-backed views into CompressionStream | copies the shared bytes; round-trips | write path REJECTS TypeError 'The provided value is not of type (ArrayBuffer or ArrayBufferView)' (spec: BufferSource without [AllowShared]) — while its identity stream ACCEPTS the same views | `sabViewThroughCompressionRoundTrip` |
Expand Down Expand Up @@ -70,6 +71,7 @@ the source FIRST, then releasing the write (`pipeStopsPullingWhenDestStalls`).
| `streams_enable_constructors` + `transformstream_enable_standard_constructor` (2022-11-30) | yes (JS-backed endpoints) | `piping-cpp-legacy`: JS ctors throw the flag-naming Error; NATIVE→NATIVE pipes (body ↔ IdentityTransformStream) work unflagged |
| `capture_async_api_throws` | ledger #5's bad-dest rejection shape | — |
| `pedantic_wpt` (dateless opt-in) | `piping-cpp-pedantic` cell | zero observable deltas on this suite's surface |
| `pipe_to_backward_propagation` | off (ledger #4, #7 pin the unflagged outcome) | on in the C++ `@all-compat-flags` variants, which take the spec branch (`pipeToBackwardPropagation` in which-impl.js) |
| others (nodejs_compat, getters-on-prototype, toString tag, backpressure fixup, spec-compliant writer) | as in the sibling suites | — |

## Module map
Expand Down
12 changes: 7 additions & 5 deletions src/tests/streams/piping/close-propagation.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// deliberate defect pin, not a hole.

import { strictEqual, rejects } from 'node:assert';
import { usingTsImpl } from 'which-impl';
import { usingTsImpl, pipeToBackwardPropagation } from 'which-impl';

const outcomeOf = (p, ms = 250) =>
Promise.race([
Expand Down Expand Up @@ -131,7 +131,8 @@ export const destWriteThrowsMidPipePreventCancel = {
// waits on a read: backward error propagation with nothing in flight.
// DIVERGENCE: TypeScript rejects the pipe with the error and cancels
// the source with it (spec); C++ half-propagates — it cancels the
// source with the error but FULFILLS the pipe promise.
// source with the error but FULFILLS the pipe promise — unless
// pipe_to_backward_propagation is enabled.
export const destControllerErrorsMidPipe = {
async test() {
const derr = new Error('dest-err');
Expand All @@ -154,7 +155,7 @@ export const destControllerErrorsMidPipe = {
await scheduler.wait(1);
wc.error(derr);
const outcome = await outcomeOf(pipeP);
if (usingTsImpl) {
if (usingTsImpl || pipeToBackwardPropagation) {
strictEqual(outcome.state, 'rejected');
strictEqual(outcome.reason, derr);
strictEqual(cancelArg, derr);
Expand All @@ -169,7 +170,8 @@ export const destControllerErrorsMidPipe = {
// destination is erroring until the write settles, and only then errored.
// Backward propagation waits for errored (spec), so the source is not
// cancelled while the write is outstanding. DIVERGENCE (ledger #7): C++
// then cancels the source with the error but FULFILLS the pipe promise.
// then cancels the source with the error but FULFILLS the pipe promise,
// unless pipe_to_backward_propagation is enabled.
export const destErroringWaitsForInFlightWrite = {
async test() {
const derr = new Error('dest-err');
Expand Down Expand Up @@ -202,7 +204,7 @@ export const destErroringWaitsForInFlightWrite = {
strictEqual(cancelArg, 'not-called');
releaseWrite();
const outcome = await outcomeOf(pipeP);
if (usingTsImpl) {
if (usingTsImpl || pipeToBackwardPropagation) {
strictEqual(outcome.state, 'rejected');
strictEqual(outcome.reason, derr);
} else {
Expand Down
29 changes: 22 additions & 7 deletions src/tests/streams/piping/pipe-matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import { strictEqual, ok, rejects, deepStrictEqual, throws } from 'node:assert';
import { mock } from 'node:test';
import { usingTsImpl } from 'which-impl';
import { usingTsImpl, pipeToBackwardPropagation } from 'which-impl';

// Writing to a closed JS WritableStream rejects with per-implementation
// messages.
Expand Down Expand Up @@ -1097,10 +1097,17 @@ export const pipeToJsToJsCloseQueuedDestination = {
const writer = ws.getWriter();
await writer.closed;

// TODO(conform): The spec's "closing must be propagated backward" would have
// rejected the pipe promise with the TypeError above. The pipe loop bails out
// once the pipe lock is gone, so the promise currently resolves instead.
await pipePromise;
// The spec's "closing must be propagated backward" rejects the pipe promise
// with the TypeError above. Without pipe_to_backward_propagation the pipe loop
// bails out once the pipe lock is gone, so the promise resolves instead.
if (pipeToBackwardPropagation) {
await rejects(pipePromise, {
name: 'TypeError',
message: 'This destination writable stream is closed.',
});
} else {
await pipePromise;
}
},
};

Expand Down Expand Up @@ -1155,10 +1162,18 @@ export const pipeToJsToJsCloseQueuedDestinationPreventCancel = {
const reader = rs.getReader();

// Close the source to settle the pipe's still-pending read, which lets the
// pipe promise settle.
// pipe promise settle without pipe_to_backward_propagation. With it, the
// pipe has already rejected with the backward-propagated close.
rc.close();
await reader.closed;
await pipePromise;
if (pipeToBackwardPropagation) {
await rejects(pipePromise, {
name: 'TypeError',
message: 'This destination writable stream is closed.',
});
} else {
await pipePromise;
}
},
};

Expand Down
6 changes: 6 additions & 0 deletions src/tests/streams/piping/which-impl.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@
export const usingTsImpl =
globalThis.Cloudflare.compatibilityFlags['typescript_implemented_streams'];

// True when the C++ implementation propagates destination errors and closure backward through
// a pipe as the spec requires (ledger #4 and #7 in AGENTS.md). Off in the pinned cells; on in
// their @all-compat-flags variants.
export const pipeToBackwardPropagation =
globalThis.Cloudflare.compatibilityFlags['pipe_to_backward_propagation'];

// True in the transform-cpp-pedantic cell: the dateless opt-in pedantic_wpt
// flag aligns the C++ finish-operation coordination (abort/close/cancel
// races) with the spec.
Expand Down
1 change: 1 addition & 0 deletions src/workerd/api/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,7 @@ wd_cc_library(
"streams/draining-read-uaf-test.c++",
"streams/queue-test.c++",
"streams/standard-test.c++",
"streams/termination-injection-test.c++",
]
]

Expand Down
21 changes: 14 additions & 7 deletions src/workerd/api/streams/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,14 +292,19 @@ When `pumpTo()` is called on the adapter:
- **When**: Calling code that may invoke JS callbacks during a read/write operation
- **Why**: JS callbacks can trigger close/error mid-operation; state must not change
until operation completes
- **How**: `beginOperation()` increments counter; `endOperation()` applies pending
transition when counter hits 0
- **Entry point**: `deferControllerStateChange()` in `standard.h`
- **How**: `scopedOperation()` returns an RAII guard that increments the operation
counter and decrements it when destroyed, applying any pending transition when the
counter hits 0. Call `end()` explicitly only when the caller needs to know whether a
transition was applied. The guard keeps the counter balanced on exceptions and on
termination, so prefer it to manual `beginOperation()`/`endOperation()` calls.
- **Entry point**: `deferControllerStateChange()` in `standard.c++`

```cpp
controller.state.beginOperation(); // Increment counter
auto result = readCallback(); // May trigger JS that calls close()
controller.state.endOperation(); // Apply pending state if counter == 0
auto operation = controller.state.scopedOperation();
auto result = readCallback(); // May trigger JS that calls close()
if (operation.end()) { // Apply pending state if counter == 0
// Notify the lock about the applied transition.
}
```

### Pattern: Consumer Snapshot
Expand Down Expand Up @@ -385,7 +390,9 @@ auto onSuccess = [this, ref = addRef(), ...](...) mutable {
into the source's `PipeLocked` lock state. `kj::Ptr` tracks liveness (asserting in
debug builds): the `PipeLocked` state must not be destroyed while any pointer to its
`PipeController` remains.
- **Rule**: The source stays `PipeLocked` for the entire lifetime of the pipe. ONLY the
- **Rule**: The source stays `PipeLocked` until the destination's pipe machinery tears
the pipe down, including while the source's cancel algorithm is invoked. The pipe
promise may stay pending after that, waiting on the cancel's promise. ONLY the
destination's pipe machinery may release the lock, and only via
`ReadableStreamController::releasePipeLock()` *after* dropping every
`kj::Ptr<PipeController>` it holds (`Pipe::releaseSource()` /
Expand Down
42 changes: 42 additions & 0 deletions src/workerd/api/streams/internal-test.c++
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,48 @@ KJ_TEST("WritableStreamInternalController pipeLoop abort during pending read") {
});
}

KJ_TEST("WritableStreamInternalController pipe keeps its source alive across its read") {
auto fixture = makeAbortClearsQueueTestFixture();
struct Streams {
kj::Maybe<jsg::Ref<ReadableStream>> source;
kj::Maybe<jsg::Ref<WritableStream>> sink;
};
Streams streams;
int pullCount = 0;
bool pipeRejected = false;
fixture.runInIoContext([&](const TestFixture::Environment& env) -> kj::Promise<void> {
// The pipe loop's second read runs the source's pull() synchronously. pull() aborts the
// destination, which tears the pipe down and drops its reference to the source, and drops
// the last other reference too. The source must survive until its read returns.
streams.sink = env.js.alloc<WritableStream>(env.context, kj::heap<NoopSink>(), kj::none);
streams.source = ReadableStream::constructor(env.js,
UnderlyingSource{.pull =
[&](jsg::Lock& js, UnderlyingSource::Controller controller) {
auto& c = KJ_ASSERT_NONNULL(controller.tryGet<jsg::Ref<ReadableStreamDefaultController>>());
if (++pullCount == 1) {
c->enqueue(js, jsg::JsUint8Array::create(js, {1, 2, 3, 4}));
return js.resolvedPromise();
}
// Aborting cancels the source, which destroys this lambda, so take what we need first.
auto& state = streams;
auto sink = kj::mv(KJ_ASSERT_NONNULL(state.sink));
state.sink = kj::none;
sink->getController().abort(js, js.typeError("abort"_kj)).markAsHandled(js);
state.source = kj::none;
js.v8Isolate->LowMemoryNotification();
return js.resolvedPromise();
}},
StreamQueuingStrategy{.highWaterMark = 0});

auto pipe = KJ_ASSERT_NONNULL(streams.source)
->pipeTo(env.js, KJ_ASSERT_NONNULL(streams.sink).addRef(), PipeToOptions{})
.catch_(env.js, [&](jsg::Lock&, jsg::Value) { pipeRejected = true; });
return env.context.awaitJs(env.js, kj::mv(pipe));
});
KJ_ASSERT(pullCount == 2);
KJ_ASSERT(pipeRejected);
}

// ======================================================================================
// DrainingReader tests for internal streams
//
Expand Down
13 changes: 10 additions & 3 deletions src/workerd/api/streams/internal.c++
Original file line number Diff line number Diff line change
Expand Up @@ -2734,9 +2734,16 @@ jsg::Promise<void> WritableStreamInternalController::Pipe::pipeLoop(jsg::Lock& j
return js.rejectedPromise<void>(destClosed);
}

// The read can run the source's pull algorithm, and that code can end this pipe, destroying
// *this and dropping the last reference to the source, while the read is still on the stack.
// Keep the source alive until the read returns, and take everything the continuations need
// from *this before starting it.
auto readableRef = readable.addRef();
Comment thread
ask-bonk[bot] marked this conversation as resolved.
Resolved
auto state = getState();
auto errorState = state.addRef();
return source->read(js).then(js,
ioContext.addFunctor(
[state = getState()](jsg::Lock& js, ReadResult result) mutable -> jsg::Promise<void> {
[state = kj::mv(state)](jsg::Lock& js, ReadResult result) mutable -> jsg::Promise<void> {
if (state->isAborted() || state->checkSignal(js) || result.done) {
return js.resolvedPromise();
}
Expand Down Expand Up @@ -2777,8 +2784,8 @@ jsg::Promise<void> WritableStreamInternalController::Pipe::pipeLoop(jsg::Lock& j
// The error condition will be handled at the start of the next iteration.
return state->pipeLoop(js);
}),
ioContext.addFunctor(
[state = getState()](jsg::Lock& js, jsg::Value reason) mutable -> jsg::Promise<void> {
ioContext.addFunctor([state = kj::mv(errorState)](
jsg::Lock& js, jsg::Value reason) mutable -> jsg::Promise<void> {
if (state->isAborted() || state->isSourceReleased()) {
return js.resolvedPromise();
}
Expand Down
Loading
Loading