Repository navigation
Description
In workerd 1.20261121.1, cancelling a ReadableStream whose source called controller.enqueue() and then controller.close() resolves without ever calling the source's cancel(). Drop the close() and the source's cancel() runs. Node v26.13.1, Bun 1.4.4, and workerd with typescript_implemented_streams call it in both cases.
I hit this in a lane that runs a site's contract tests a second time inside workerd: a test that checks a redirected response's body gets cancelled failed only there.
This looks like the root cause behind row 18 of the divergence ledger in src/tests/streams/readable/AGENTS.md (errorAfterCloseWithQueuedChunk, from #7335), where the C++ controller treats a requested close as final. That row covers error(); nothing pins cancel() while the close is still pending. The practical cost is cleanup: a source that clears a timer or releases an upstream reader in cancel() never hears about it when a consumer drops the body after the source finished enqueuing.
Repro (zsh on macOS 27.3 arm64; the script is plain POSIX sh)
mkdir cancel-repro && cd cancel-repro
cat > worker.mjs <<'EOF'
function source(closeAfterEnqueue) {
const seen = { cancelled: false };
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode("x"));
if (closeAfterEnqueue) controller.close();
},
cancel() {
seen.cancelled = true;
},
});
return { stream, seen };
}
export async function run() {
const out = {};
for (const close of [true, false]) {
let s = source(close);
await s.stream.cancel();
out[`stream.cancel() close=${close}`] = s.seen.cancelled;
s = source(close);
await new Response(s.stream).body.cancel();
out[`Response body.cancel() close=${close}`] = s.seen.cancelled;
}
return out;
}
export default {
async test() {
console.log(JSON.stringify(await run(), null, 1));
},
};
EOF
cat > config.capnp <<'EOF'
using Workerd = import "/workerd/workerd.capnp";
const config :Workerd.Config = (services = [(name = "main", worker = .w)]);
const w :Workerd.Worker = (
modules = [(name = "worker.mjs", esModule = embed "worker.mjs")],
compatibilityDate = "2026-06-01",
);
EOF
cat > ts.capnp <<'EOF'
using Workerd = import "/workerd/workerd.capnp";
const config :Workerd.Config = (services = [(name = "main", worker = .w)]);
const w :Workerd.Worker = (
modules = [(name = "worker.mjs", esModule = embed "worker.mjs")],
compatibilityDate = "2026-06-01",
compatibilityFlags = ["typescript_implemented_streams", "experimental"],
);
EOF
npx --yes workerd@1.20261121.1 test config.capnp
npx --yes workerd@1.20261121.1 test --experimental ts.capnp
node -e 'import("./worker.mjs").then(async (m) => console.log(JSON.stringify(await m.run(), null, 1)))'Expected: true for all 4 keys. While a chunk is still queued, ReadableStreamDefaultControllerClose only sets [[closeRequested]], so the stream is still "readable" and ReadableStreamCancel runs the cancel algorithm. The Cloudflare ReadableStream reference says the same: "reason will be passed to the underlying source's cancel algorithm".
Actual (config.capnp):
{
"stream.cancel() close=true": false,
"Response body.cancel() close=true": false,
"stream.cancel() close=false": true,
"Response body.cancel() close=false": true
}
ts.capnp and Node print true for all 4 keys.
From reading standard.c++ at 42ee37e (not stepped through a debugger): ReadableImpl::close() moves the controller to Closed and doClose() clears the algorithms even with chunks queued, so a later cancel() takes the early return its own comment says "shouldn't happen".
workerd/src/workerd/api/streams/standard.c++
Lines 1160 to 1165 in 42ee37e
| jsg::Lock& js, jsg::Ref<Self> self, jsg::JsValue reason) { | |
| if (state.template is<StreamStates::Closed>()) { | |
| // We are already closed. There's nothing to cancel. | |
| // This shouldn't happen but we handle the case anyway, just to be safe. | |
| return js.resolvedPromise(); | |
| } |
workerd/src/workerd/api/streams/standard.c++
Lines 1252 to 1278 in 42ee37e
| template <typename Self> | |
| void ReadableImpl<Self>::close(jsg::Lock& js) { | |
| JSG_REQUIRE(canCloseOrEnqueue(), TypeError, "This ReadableStream is closed."); | |
| auto& queue = state.template getUnsafe<Queue>(); | |
| if (queue.hasPartiallyFulfilledRead()) { | |
| auto err = js.typeError("This ReadableStream was closed with a partial read pending."); | |
| doError(js, err); | |
| js.throwException(err); | |
| return; | |
| } | |
| // Moving the queue preserves its native identity and owns the whole fan-out independently | |
| // of this controller. Settlement can synchronously invoke another terminal operation. | |
| auto closingQueue = kj::mv(queue); | |
| state.template transitionTo<StreamStates::Closed>(); | |
| doClose(js); | |
| closingQueue.close(js); | |
| } | |
| template <typename Self> | |
| void ReadableImpl<Self>::doClose(jsg::Lock& js) { | |
| // The state should have already been set to closed. | |
| KJ_ASSERT(state.template is<StreamStates::Closed>()); | |
| algorithms.clear(); | |
| } |
Environment: compatibility date 2026-06-01, no other flags needed. Reproduces on 1.20261121.1 (bare workerd test, above) and on 1.20261113.1 (the workerd in a pkg.pr.new Miniflare build), with and without nodejs_compat. I didn't build main; the 72 commits between 1.20261121.1 and 42ee37e don't touch standard.c++, standard.h, or queue.c++.
8 cancel paths: every one skips the source's cancel() after close() in workerd
Same source as above. Each cell is whether the source's cancel() ran.
| Cancel via | workerd, with close() | workerd, without close() | workerd + typescript_implemented_streams |
Node v26.13.1, Bun 1.4.4 |
|---|---|---|---|---|
stream.cancel() |
false | true | true | true |
new Response(stream).body.cancel() |
false | true | true | true |
new Response(stream, { status: 301, headers: { location: "https://x/" } }).body.cancel() |
false | true | true | true |
stream.getReader().cancel() |
false | true | true | true |
stream.cancel() on a type: "bytes" stream |
false | true | true | true |
async iterator return() |
false | true | true | true |
cancel() on both tee() branches |
false | true | true | true |
reader.cancel() after 1 of 2 queued chunks is read |
false | true | true | true |
All on workerd 1.20261121.1, compatibility date 2026-06-01, 2026-11-21.
Searched issues, PRs, and discussions for "cancel after close", "cancel not called", "ReadableStream cancel", "underlying source cancel", and "closeRequested". The nearest is the pump-drop cancel report #6832, its merged fix #7600, and the open PR #6896, which take a different path.
Two questions, given row 18:
- Would you take a ledger row beside 18 with a test that pins
cancel()after a pending close in both implementations? Happy to send that as a PR. - Is a compat-flagged fix to the C++ path wanted while
typescript_implemented_streamsis still experimental, or should production Workers wait for TS streams?
AI-assisted. Recon and issue text by houseguest.
Activity
jasnell commentedon Nov 22, 2026
At this point, since the plan is to fully replace the C++ implementation with the TypeScript impl, which handles this, it's not really worth changing the C++ implementation, pinning the behavior, or introducing a compat flag'd fix.
piscisaureus commentedon Dec 1, 2026
Thanks for the report. As noted above, the C++ streams implementation is being replaced by the TypeScript implementation (typescript_implemented_streams), which already handles this case correctly, so we won't be changing the C++ behaviour.