From 70ac6129389836635b64ef6a9030df125ea774ac Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 10:10:12 +0000 Subject: [PATCH 01/10] streams: restore the native source ref when a new reader locks a released stream Releasing a reader calls updateRef(false) on a native stream source so an abandoned stream does not keep the process alive. Nothing called updateRef(true) again, so after a release the next reader on the same stream (Bun.stdin.stream() is one stream per process) parked a read and the process exited with code 0. The console async iterator releases its reader on break, so any stdin consumer after it hit this. --- .../webcore/streams/JSReadableStream.h | 5 + .../streams/ReadableStreamOperations.cpp | 51 +++++-- test/js/bun/console/console-iterator.test.ts | 128 +++++++++++++++++- 3 files changed, 170 insertions(+), 14 deletions(-) diff --git a/src/jsc/bindings/webcore/streams/JSReadableStream.h b/src/jsc/bindings/webcore/streams/JSReadableStream.h index 188d9acbedba..1e33140a6036 100644 --- a/src/jsc/bindings/webcore/streams/JSReadableStream.h +++ b/src/jsc/bindings/webcore/streams/JSReadableStream.h @@ -66,6 +66,11 @@ class JSReadableStream final : public JSC::JSNonFinalObject { // Body.textStream(): the native source adapter decodes each chunk as UTF-8 // text before enqueue. bool m_nativeTextMode : 1 { false }; + // Bun: releasing a reader calls updateRef(false) on the native source so an + // abandoned stream does not keep the process alive. The next reader to lock + // the stream restores that ref. Only a release sets this, so a source that was + // unref'd on purpose (proc.unref(), process.stdin.unref()) stays unref'd. + bool m_nativeRefDroppedOnRelease : 1 { false }; // [[reader]] — a default reader, a BYOB reader, or null (undefined). JSC::WriteBarrier m_reader; diff --git a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp index 05dbedda9385..fc467e25bd30 100644 --- a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp +++ b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp @@ -486,6 +486,33 @@ JSPromise* readableStreamCancel(JSGlobalObject* globalObject, JSReadableStream* return result; } +// Bun: calls `updateRef(value)` on the native source handle of a default-controller stream. +// A no-op for every other stream. +static void updateNativeSourceRef(JSGlobalObject* globalObject, JSReadableStream* stream, bool value) +{ + auto& vm = getVM(globalObject); + auto scope = DECLARE_THROW_SCOPE(vm); + if (stream->m_controllerKind != ControllerKind::Default) + return; + auto* controller = defaultControllerOf(stream); + if (controller->m_algorithms.kind != SourceKind::Native) + return; + const auto* adapter = uncheckedDowncast(controller->m_algorithms.algorithmContext.get()); + auto* handle = adapter->handle(); + if (!handle) + return; + JSValue updateRef = handle->getIfPropertyExists(globalObject, builtinNames(vm).updateRefPublicName()); + RETURN_IF_EXCEPTION(scope, void()); + if (!updateRef || !updateRef.isCallable()) + return; + auto callData = JSC::getCallData(updateRef); + MarkedArgumentBuffer args; + args.append(jsBoolean(value)); + ASSERT(!args.hasOverflowed()); + JSC::call(globalObject, updateRef, callData, handle, args); + RETURN_IF_EXCEPTION(scope, void()); +} + // ReadableStreamReaderGenericInitialize(reader, stream) void readableStreamReaderGenericInitialize(JSGlobalObject* globalObject, JSReadableStreamReaderBase* reader, JSReadableStream* stream) { @@ -496,6 +523,13 @@ void readableStreamReaderGenericInitialize(JSGlobalObject* globalObject, JSReada switch (stream->m_state) { case ReadableStreamState::Readable: reader->m_closedPromise.set(vm, reader, JSPromise::create(vm, globalObject->promiseStructure())); + // Bun: the previous reader's release dropped the native source's event-loop ref. + // This reader is going to read, so put it back. + if (stream->m_nativeRefDroppedOnRelease) { + stream->m_nativeRefDroppedOnRelease = false; + updateNativeSourceRef(globalObject, stream, true); + RETURN_IF_EXCEPTION(scope, void()); + } return; case ReadableStreamState::Closed: { auto* closedPromise = promiseFulfilledWith(globalObject, JSC::jsUndefined()); @@ -555,20 +589,11 @@ void readableStreamReaderGenericRelease(JSGlobalObject* globalObject, JSReadable auto* controller = defaultControllerOf(stream); controller->releaseSteps(); // Bun: drop the native handle's event-loop ref when its consumer releases the lock. + // The next reader to lock the stream restores it (readableStreamReaderGenericInitialize). if (controller->m_algorithms.kind == SourceKind::Native) { - const auto* adapter = uncheckedDowncast(controller->m_algorithms.algorithmContext.get()); - if (auto* handle = adapter->handle()) { - JSValue updateRef = handle->getIfPropertyExists(globalObject, builtinNames(vm).updateRefPublicName()); - RETURN_IF_EXCEPTION(scope, void()); - if (updateRef && updateRef.isCallable()) { - auto callData = JSC::getCallData(updateRef); - MarkedArgumentBuffer args; - args.append(jsBoolean(false)); - ASSERT(!args.hasOverflowed()); - JSC::call(globalObject, updateRef, callData, handle, args); - RETURN_IF_EXCEPTION(scope, void()); - } - } + stream->m_nativeRefDroppedOnRelease = true; + updateNativeSourceRef(globalObject, stream, false); + RETURN_IF_EXCEPTION(scope, void()); } break; } diff --git a/test/js/bun/console/console-iterator.test.ts b/test/js/bun/console/console-iterator.test.ts index f8fa86976645..36c93319bc8d 100644 --- a/test/js/bun/console/console-iterator.test.ts +++ b/test/js/bun/console/console-iterator.test.ts @@ -1,6 +1,6 @@ import { spawn, spawnSync } from "bun"; import { describe, expect, it } from "bun:test"; -import { bunEnv, bunExe } from "harness"; +import { bunEnv, bunExe, isWindows } from "harness"; describe("should work for static input", () => { const inputs = [ @@ -74,3 +74,129 @@ it("can use the console iterator more than once", async () => { expect(await stdout.text()).toBe('["hello","world"]["another"]'); proc.kill(0); }); + +// Bun.stdin.stream() is one stream per process. Releasing its reader (which the +// console iterator does when the loop breaks) unrefs the native stdin reader so +// an abandoned stream does not keep the process alive. The next reader on that +// stream must ref it again, or the process exits with code 0 while a read is +// still pending. No top-level await in the child: it would keep the loop alive +// and hide the bug. +describe("a later stdin consumer keeps the process alive after the reader is released", () => { + const afterConsoleBreak = ` + (async () => { + for await (const line of console) { + console.log("ITER " + line); + break; + } + console.log("READY"); + for await (const chunk of Bun.stdin.stream()) { + console.log("STREAM " + new TextDecoder().decode(chunk).trim()); + break; + } + console.log("DONE"); + })(); + `; + + const afterReleaseLock = ` + (async () => { + const decoder = new TextDecoder(); + const first = Bun.stdin.stream().getReader(); + console.log("FIRST " + decoder.decode((await first.read()).value).trim()); + first.releaseLock(); + console.log("READY"); + const second = Bun.stdin.stream().getReader(); + console.log("SECOND " + decoder.decode((await second.read()).value).trim()); + second.releaseLock(); + console.log("DONE"); + })(); + `; + + async function runWithPipe(script: string) { + await using proc = spawn({ + cmd: [bunExe(), "-e", script], + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + env: bunEnv, + }); + const reader = proc.stdout.getReader(); + const decoder = new TextDecoder(); + let output = ""; + async function waitFor(marker: string) { + while (!output.includes(marker)) { + const { value, done } = await reader.read(); + if (done) throw new Error(`stdout ended before ${JSON.stringify(marker)}; output=${JSON.stringify(output)}`); + output += decoder.decode(value, { stream: true }); + } + } + + proc.stdin.write("first\n"); + proc.stdin.flush(); + await waitFor("READY\n"); + proc.stdin.write("second\n"); + proc.stdin.flush(); + await waitFor("DONE\n"); + for (let { value, done } = await reader.read(); !done; { value, done } = await reader.read()) { + output += decoder.decode(value, { stream: true }); + } + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); + return output; + } + + async function runWithTerminal(script: string) { + const decoder = new TextDecoder(); + let output = ""; + let waiting: { marker: string; resolve: () => void } | undefined; + function waitFor(marker: string) { + return new Promise((resolve, reject) => { + waiting = { marker, resolve }; + proc.exited.then(code => + reject( + new Error(`child exited with ${code} before ${JSON.stringify(marker)}; output=${JSON.stringify(output)}`), + ), + ); + if (output.includes(marker)) resolve(); + }); + } + const proc = spawn({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + terminal: { + data(_terminal, chunk) { + output += decoder.decode(chunk, { stream: true }); + if (waiting && output.includes(waiting.marker)) waiting.resolve(); + }, + }, + }); + const terminal = proc.terminal!; + terminal.write("first\n"); + await waitFor("READY"); + terminal.write("second\n"); + await waitFor("DONE"); + expect(await proc.exited).toBe(0); + terminal.close(); + return output; + } + + it("Bun.stdin.stream() after the console iterator breaks (pipe)", async () => { + expect(await runWithPipe(afterConsoleBreak)).toBe("ITER first\nREADY\nSTREAM second\nDONE\n"); + }); + + it("a second reader after releaseLock() (pipe)", async () => { + expect(await runWithPipe(afterReleaseLock)).toBe("FIRST first\nREADY\nSECOND second\nDONE\n"); + }); + + it.skipIf(isWindows)("Bun.stdin.stream() after the console iterator breaks (tty)", async () => { + const output = await runWithTerminal(afterConsoleBreak); + expect(output).toContain("ITER first"); + expect(output).toContain("STREAM second"); + }); + + it.skipIf(isWindows)("a second reader after releaseLock() (tty)", async () => { + const output = await runWithTerminal(afterReleaseLock); + expect(output).toContain("FIRST first"); + expect(output).toContain("SECOND second"); + }); +}); From 63869037f9ecc438add179b6553b1979b8e159e3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 11:04:07 +0000 Subject: [PATCH 02/10] test: dispose the pty child and terminal on every exit path --- test/js/bun/console/console-iterator.test.ts | 23 ++++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/test/js/bun/console/console-iterator.test.ts b/test/js/bun/console/console-iterator.test.ts index 36c93319bc8d..70d99098e78d 100644 --- a/test/js/bun/console/console-iterator.test.ts +++ b/test/js/bun/console/console-iterator.test.ts @@ -149,6 +149,17 @@ describe("a later stdin consumer keeps the process alive after the reader is rel const decoder = new TextDecoder(); let output = ""; let waiting: { marker: string; resolve: () => void } | undefined; + await using proc = spawn({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + terminal: { + data(_terminal, chunk) { + output += decoder.decode(chunk, { stream: true }); + if (waiting && output.includes(waiting.marker)) waiting.resolve(); + }, + }, + }); + await using terminal = proc.terminal!; function waitFor(marker: string) { return new Promise((resolve, reject) => { waiting = { marker, resolve }; @@ -160,23 +171,11 @@ describe("a later stdin consumer keeps the process alive after the reader is rel if (output.includes(marker)) resolve(); }); } - const proc = spawn({ - cmd: [bunExe(), "-e", script], - env: bunEnv, - terminal: { - data(_terminal, chunk) { - output += decoder.decode(chunk, { stream: true }); - if (waiting && output.includes(waiting.marker)) waiting.resolve(); - }, - }, - }); - const terminal = proc.terminal!; terminal.write("first\n"); await waitFor("READY"); terminal.write("second\n"); await waitFor("DONE"); expect(await proc.exited).toBe(0); - terminal.close(); return output; } From 77eeb36f9411b9d292c162c8ca96cc28c77ef954 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 11:13:20 +0000 Subject: [PATCH 03/10] streams: shorten the ref bookkeeping comments --- src/jsc/bindings/webcore/streams/JSReadableStream.h | 6 ++---- .../bindings/webcore/streams/ReadableStreamOperations.cpp | 7 ++----- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/src/jsc/bindings/webcore/streams/JSReadableStream.h b/src/jsc/bindings/webcore/streams/JSReadableStream.h index 1e33140a6036..65e07f90a3ba 100644 --- a/src/jsc/bindings/webcore/streams/JSReadableStream.h +++ b/src/jsc/bindings/webcore/streams/JSReadableStream.h @@ -66,10 +66,8 @@ class JSReadableStream final : public JSC::JSNonFinalObject { // Body.textStream(): the native source adapter decodes each chunk as UTF-8 // text before enqueue. bool m_nativeTextMode : 1 { false }; - // Bun: releasing a reader calls updateRef(false) on the native source so an - // abandoned stream does not keep the process alive. The next reader to lock - // the stream restores that ref. Only a release sets this, so a source that was - // unref'd on purpose (proc.unref(), process.stdin.unref()) stays unref'd. + // Bun: reader release called updateRef(false) on the native source; the next + // reader lock calls updateRef(true). A deliberate unref() never sets this. bool m_nativeRefDroppedOnRelease : 1 { false }; // [[reader]] — a default reader, a BYOB reader, or null (undefined). diff --git a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp index fc467e25bd30..b7732c76c524 100644 --- a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp +++ b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp @@ -486,8 +486,7 @@ JSPromise* readableStreamCancel(JSGlobalObject* globalObject, JSReadableStream* return result; } -// Bun: calls `updateRef(value)` on the native source handle of a default-controller stream. -// A no-op for every other stream. +// Bun: `updateRef(value)` on a default-controller native source handle; no-op otherwise. static void updateNativeSourceRef(JSGlobalObject* globalObject, JSReadableStream* stream, bool value) { auto& vm = getVM(globalObject); @@ -523,8 +522,7 @@ void readableStreamReaderGenericInitialize(JSGlobalObject* globalObject, JSReada switch (stream->m_state) { case ReadableStreamState::Readable: reader->m_closedPromise.set(vm, reader, JSPromise::create(vm, globalObject->promiseStructure())); - // Bun: the previous reader's release dropped the native source's event-loop ref. - // This reader is going to read, so put it back. + // Bun: restore the event-loop ref that the previous reader's release dropped. if (stream->m_nativeRefDroppedOnRelease) { stream->m_nativeRefDroppedOnRelease = false; updateNativeSourceRef(globalObject, stream, true); @@ -589,7 +587,6 @@ void readableStreamReaderGenericRelease(JSGlobalObject* globalObject, JSReadable auto* controller = defaultControllerOf(stream); controller->releaseSteps(); // Bun: drop the native handle's event-loop ref when its consumer releases the lock. - // The next reader to lock the stream restores it (readableStreamReaderGenericInitialize). if (controller->m_algorithms.kind == SourceKind::Native) { stream->m_nativeRefDroppedOnRelease = true; updateNativeSourceRef(globalObject, stream, false); From 4b1ea0358b915ce9dfd1936afde3469d1ca93156 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 12:01:00 +0000 Subject: [PATCH 04/10] streams: one-line comment on m_nativeRefDroppedOnRelease --- src/jsc/bindings/webcore/streams/JSReadableStream.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/jsc/bindings/webcore/streams/JSReadableStream.h b/src/jsc/bindings/webcore/streams/JSReadableStream.h index 65e07f90a3ba..960a6b302859 100644 --- a/src/jsc/bindings/webcore/streams/JSReadableStream.h +++ b/src/jsc/bindings/webcore/streams/JSReadableStream.h @@ -66,8 +66,7 @@ class JSReadableStream final : public JSC::JSNonFinalObject { // Body.textStream(): the native source adapter decodes each chunk as UTF-8 // text before enqueue. bool m_nativeTextMode : 1 { false }; - // Bun: reader release called updateRef(false) on the native source; the next - // reader lock calls updateRef(true). A deliberate unref() never sets this. + // Bun: a reader release unref'd the native source; the next reader lock re-refs it. bool m_nativeRefDroppedOnRelease : 1 { false }; // [[reader]] — a default reader, a BYOB reader, or null (undefined). From 6887ed4bd0e40ff5e40764813cd60535f55620f5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 13:20:52 +0000 Subject: [PATCH 05/10] streams: only restore a ref that the reader release itself dropped updateRef() now returns the previous ref state. A release that finds the source already unref'd (proc.unref(), process.stdin.unref()) records nothing, so the next reader lock leaves it unref'd. --- src/io/PipeReader.rs | 22 +++++++++--- .../streams/ReadableStreamOperations.cpp | 25 +++++++------ src/runtime/webcore/FileReader.rs | 9 ++--- src/runtime/webcore/ReadableStream.rs | 17 +++++---- test/js/bun/console/console-iterator.test.ts | 35 +++++++++++++++++++ 5 files changed, 82 insertions(+), 26 deletions(-) diff --git a/src/io/PipeReader.rs b/src/io/PipeReader.rs index 762e064ccd1b..923f24118740 100644 --- a/src/io/PipeReader.rs +++ b/src/io/PipeReader.rs @@ -232,18 +232,21 @@ impl PosixBufferedReader { } } - pub fn update_ref(&mut self, value: bool) { + /// Returns the previous ref state. + pub fn update_ref(&mut self, value: bool) -> bool { + let previous = self.flags.contains(PosixFlags::KEEP_ALIVE); // Remember the ref state so a poll created later (lazy start) honours // an unref() that preceded the first registration. self.flags.set(PosixFlags::KEEP_ALIVE, value); let Some(poll) = self.handle.get_poll() else { - return; + return previous; }; // An unarmed poll delivers nothing; `try_register_poll` applies KEEP_ALIVE when it arms. if value && !poll.is_watching() { - return; + return previous; } poll.set_keeping_process_alive(self.vtable.event_loop(), value); + previous } #[inline] @@ -1016,13 +1019,18 @@ bitflags::bitflags! { /// When true, wait for the file operation callback before calling done(). /// Used to ensure proper cleanup ordering when closing during cancellation. const DEFER_DONE_CALLBACK = 1 << 9; + const KEEP_ALIVE = 1 << 10; // default true } } #[cfg(windows)] impl WindowsFlags { pub(crate) const fn new() -> Self { - Self::from_bits_truncate(WindowsFlags::CLOSE_HANDLE.bits() | WindowsFlags::IS_PAUSED.bits()) + Self::from_bits_truncate( + WindowsFlags::CLOSE_HANDLE.bits() + | WindowsFlags::IS_PAUSED.bits() + | WindowsFlags::KEEP_ALIVE.bits(), + ) } } @@ -1101,7 +1109,10 @@ impl WindowsBufferedReader { } } - pub fn update_ref(&mut self, value: bool) { + /// Returns the previous ref state. + pub fn update_ref(&mut self, value: bool) -> bool { + let previous = self.flags.contains(WindowsFlags::KEEP_ALIVE); + self.flags.set(WindowsFlags::KEEP_ALIVE, value); if let Some(source) = self.source.as_mut() { if value { source.ref_(); @@ -1109,6 +1120,7 @@ impl WindowsBufferedReader { source.unref(); } } + previous } pub fn disable_keeping_process_alive(&mut self, _: C) { diff --git a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp index b7732c76c524..6d2c307f9494 100644 --- a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp +++ b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp @@ -486,30 +486,32 @@ JSPromise* readableStreamCancel(JSGlobalObject* globalObject, JSReadableStream* return result; } -// Bun: `updateRef(value)` on a default-controller native source handle; no-op otherwise. -static void updateNativeSourceRef(JSGlobalObject* globalObject, JSReadableStream* stream, bool value) +// Bun: `updateRef(value)` on a default-controller native source handle. Returns whether the +// source held a ref before the call; false when there is no such handle. +static bool updateNativeSourceRef(JSGlobalObject* globalObject, JSReadableStream* stream, bool value) { auto& vm = getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); if (stream->m_controllerKind != ControllerKind::Default) - return; + return false; auto* controller = defaultControllerOf(stream); if (controller->m_algorithms.kind != SourceKind::Native) - return; + return false; const auto* adapter = uncheckedDowncast(controller->m_algorithms.algorithmContext.get()); auto* handle = adapter->handle(); if (!handle) - return; + return false; JSValue updateRef = handle->getIfPropertyExists(globalObject, builtinNames(vm).updateRefPublicName()); - RETURN_IF_EXCEPTION(scope, void()); + RETURN_IF_EXCEPTION(scope, false); if (!updateRef || !updateRef.isCallable()) - return; + return false; auto callData = JSC::getCallData(updateRef); MarkedArgumentBuffer args; args.append(jsBoolean(value)); ASSERT(!args.hasOverflowed()); - JSC::call(globalObject, updateRef, callData, handle, args); - RETURN_IF_EXCEPTION(scope, void()); + JSValue previous = JSC::call(globalObject, updateRef, callData, handle, args); + RETURN_IF_EXCEPTION(scope, false); + return previous.isTrue(); } // ReadableStreamReaderGenericInitialize(reader, stream) @@ -587,10 +589,11 @@ void readableStreamReaderGenericRelease(JSGlobalObject* globalObject, JSReadable auto* controller = defaultControllerOf(stream); controller->releaseSteps(); // Bun: drop the native handle's event-loop ref when its consumer releases the lock. + // A source the user already unref'd has nothing to drop, so nothing gets restored later. if (controller->m_algorithms.kind == SourceKind::Native) { - stream->m_nativeRefDroppedOnRelease = true; - updateNativeSourceRef(globalObject, stream, false); + bool wasRef = updateNativeSourceRef(globalObject, stream, false); RETURN_IF_EXCEPTION(scope, void()); + stream->m_nativeRefDroppedOnRelease = wasRef; } break; } diff --git a/src/runtime/webcore/FileReader.rs b/src/runtime/webcore/FileReader.rs index c22703418fec..81000d954eec 100644 --- a/src/runtime/webcore/FileReader.rs +++ b/src/runtime/webcore/FileReader.rs @@ -899,11 +899,12 @@ impl FileReader { Vec::::move_from_list(mem::take(self.reader().buffer())) } - pub(crate) fn set_ref_or_unref(&self, enable: bool) { + /// Returns the previous ref state. A finished reader has none. + pub(crate) fn set_ref_or_unref(&self, enable: bool) -> bool { if self.done.get() { - return; + return false; } - self.reader().update_ref(enable); + self.reader().update_ref(enable) } fn consume_reader_buffer(&self) { @@ -1124,7 +1125,7 @@ impl readable_stream::SourceContext for FileReader { fn finalize_detach(&mut self) -> bool { Self::finalize_detach(self) } - fn set_ref_unref(&mut self, e: bool) { + fn set_ref_unref(&mut self, e: bool) -> bool { Self::set_ref_or_unref(self, e) } fn drain_internal_buffer(&mut self) -> Vec { diff --git a/src/runtime/webcore/ReadableStream.rs b/src/runtime/webcore/ReadableStream.rs index 8202acb9af8e..b7173aedb5a3 100644 --- a/src/runtime/webcore/ReadableStream.rs +++ b/src/runtime/webcore/ReadableStream.rs @@ -813,8 +813,10 @@ pub trait SourceContext: Sized { /// sweep: no JS. `ByteStream` tells its producer nobody can read it now. fn wrapper_finalized(&mut self) {} - /// `setRefUnrefFn` — default no-op. - fn set_ref_unref(&mut self, _enable: bool) {} + /// `setRefUnrefFn` — returns the previous ref state. Default no-op with no ref. + fn set_ref_unref(&mut self, _enable: bool) -> bool { + false + } /// `drainInternalBuffer` — default returns empty. fn drain_internal_buffer(&mut self) -> Vec { @@ -1088,9 +1090,12 @@ impl NewSource { unsafe { &mut *Self::new(init) } } - pub fn set_ref(&mut self, value: bool) { + /// Returns the previous ref state. + pub fn set_ref(&mut self, value: bool) -> bool { if C::SUPPORTS_REF { - self.context.set_ref_unref(value); + self.context.set_ref_unref(value) + } else { + false } } @@ -1426,8 +1431,8 @@ impl NewSource { call_frame: &CallFrame, ) -> JsResult { let ref_or_unref = call_frame.argument(0).to_boolean(); - self.set_ref(ref_or_unref); - Ok(JSValue::UNDEFINED) + // The previous state, so a caller can restore only what it changed. + Ok(JSValue::js_boolean(self.set_ref(ref_or_unref))) } pub fn finalize(self: Box) { diff --git a/test/js/bun/console/console-iterator.test.ts b/test/js/bun/console/console-iterator.test.ts index 70d99098e78d..ceb54547e42b 100644 --- a/test/js/bun/console/console-iterator.test.ts +++ b/test/js/bun/console/console-iterator.test.ts @@ -198,4 +198,39 @@ describe("a later stdin consumer keeps the process alive after the reader is rel expect(output).toContain("FIRST first"); expect(output).toContain("SECOND second"); }); + + // Only a ref that the release itself dropped comes back. A source the user + // unref'd on purpose stays unref'd across a releaseLock()/getReader() cycle. + it("a second reader does not undo an explicit unref()", async () => { + await using proc = spawn({ + cmd: [ + bunExe(), + "-e", + ` + const child = Bun.spawn({ + cmd: [${JSON.stringify(bunExe())}, "-e", "console.log('hi'); setTimeout(() => {}, 60_000)"], + stdin: "ignore", + stdout: "pipe", + stderr: "ignore", + }); + process.on("exit", () => child.kill()); + child.unref(); + const first = child.stdout.getReader(); + await first.read(); + first.releaseLock(); + const second = child.stdout.getReader(); + second.read().then(() => console.log("unexpected second read")); + console.log("DONE"); + `, + ], + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + env: bunEnv, + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(stdout).toBe("DONE\n"); + expect(exitCode).toBe(0); + }); }); From ddf496021208c77591b70ba9c201ed504e91c7fe Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 13:22:03 +0000 Subject: [PATCH 06/10] streams: one-line comment on updateNativeSourceRef --- src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp index 6d2c307f9494..ac06b299c0c0 100644 --- a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp +++ b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp @@ -486,8 +486,7 @@ JSPromise* readableStreamCancel(JSGlobalObject* globalObject, JSReadableStream* return result; } -// Bun: `updateRef(value)` on a default-controller native source handle. Returns whether the -// source held a ref before the call; false when there is no such handle. +// Bun: `updateRef(value)` on the native source handle, if any; returns the previous ref state. static bool updateNativeSourceRef(JSGlobalObject* globalObject, JSReadableStream* stream, bool value) { auto& vm = getVM(globalObject); From de4ddb5b10180ceaf647b4821cba9a9fcca06e59 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:21:36 +0000 Subject: [PATCH 07/10] streams: keep the dropped-ref bookkeeping in FileReader The reader lock and release now tell the FileReader source directly (FileReader__setReaderLocked). The source remembers that a release took a held ref away and gives it back at the next lock. An explicit updateRef() cancels that, so an unref() is the last word in any order. The handle's updateRef() keeps its old return value and the stream needs no extra bit. --- .../webcore/streams/JSReadableStream.h | 2 - .../streams/ReadableStreamOperations.cpp | 48 +++++-------------- .../webcore/streams/WebStreamsInternals.h | 4 +- src/runtime/webcore/FileReader.rs | 34 +++++++++++-- src/runtime/webcore/ReadableStream.rs | 17 +++---- test/js/bun/console/console-iterator.test.ts | 2 +- 6 files changed, 50 insertions(+), 57 deletions(-) diff --git a/src/jsc/bindings/webcore/streams/JSReadableStream.h b/src/jsc/bindings/webcore/streams/JSReadableStream.h index 960a6b302859..188d9acbedba 100644 --- a/src/jsc/bindings/webcore/streams/JSReadableStream.h +++ b/src/jsc/bindings/webcore/streams/JSReadableStream.h @@ -66,8 +66,6 @@ class JSReadableStream final : public JSC::JSNonFinalObject { // Body.textStream(): the native source adapter decodes each chunk as UTF-8 // text before enqueue. bool m_nativeTextMode : 1 { false }; - // Bun: a reader release unref'd the native source; the next reader lock re-refs it. - bool m_nativeRefDroppedOnRelease : 1 { false }; // [[reader]] — a default reader, a BYOB reader, or null (undefined). JSC::WriteBarrier m_reader; diff --git a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp index ac06b299c0c0..b5675c02a72a 100644 --- a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp +++ b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp @@ -25,6 +25,7 @@ #include "JSWritableStreamDefaultWriter.h" #include "ObjectBindings.h" #include "VectorSizeLimit.h" +#include "ZigGeneratedClasses.h" #include "ZigGlobalObject.h" #include @@ -486,31 +487,17 @@ JSPromise* readableStreamCancel(JSGlobalObject* globalObject, JSReadableStream* return result; } -// Bun: `updateRef(value)` on the native source handle, if any; returns the previous ref state. -static bool updateNativeSourceRef(JSGlobalObject* globalObject, JSReadableStream* stream, bool value) +// Bun: a FileReader source (the only kind with an event-loop ref) drops that ref while no reader holds the stream. +static void setNativeSourceReaderLocked(JSReadableStream* stream, bool locked) { - auto& vm = getVM(globalObject); - auto scope = DECLARE_THROW_SCOPE(vm); if (stream->m_controllerKind != ControllerKind::Default) - return false; + return; auto* controller = defaultControllerOf(stream); if (controller->m_algorithms.kind != SourceKind::Native) - return false; + return; const auto* adapter = uncheckedDowncast(controller->m_algorithms.algorithmContext.get()); - auto* handle = adapter->handle(); - if (!handle) - return false; - JSValue updateRef = handle->getIfPropertyExists(globalObject, builtinNames(vm).updateRefPublicName()); - RETURN_IF_EXCEPTION(scope, false); - if (!updateRef || !updateRef.isCallable()) - return false; - auto callData = JSC::getCallData(updateRef); - MarkedArgumentBuffer args; - args.append(jsBoolean(value)); - ASSERT(!args.hasOverflowed()); - JSValue previous = JSC::call(globalObject, updateRef, callData, handle, args); - RETURN_IF_EXCEPTION(scope, false); - return previous.isTrue(); + if (auto* source = dynamicDowncast(adapter->handle())) + FileReader__setReaderLocked(source->wrapped(), locked); } // ReadableStreamReaderGenericInitialize(reader, stream) @@ -523,12 +510,7 @@ void readableStreamReaderGenericInitialize(JSGlobalObject* globalObject, JSReada switch (stream->m_state) { case ReadableStreamState::Readable: reader->m_closedPromise.set(vm, reader, JSPromise::create(vm, globalObject->promiseStructure())); - // Bun: restore the event-loop ref that the previous reader's release dropped. - if (stream->m_nativeRefDroppedOnRelease) { - stream->m_nativeRefDroppedOnRelease = false; - updateNativeSourceRef(globalObject, stream, true); - RETURN_IF_EXCEPTION(scope, void()); - } + setNativeSourceReaderLocked(stream, true); return; case ReadableStreamState::Closed: { auto* closedPromise = promiseFulfilledWith(globalObject, JSC::jsUndefined()); @@ -584,18 +566,10 @@ void readableStreamReaderGenericRelease(JSGlobalObject* globalObject, JSReadable } break; } - case ControllerKind::Default: { - auto* controller = defaultControllerOf(stream); - controller->releaseSteps(); - // Bun: drop the native handle's event-loop ref when its consumer releases the lock. - // A source the user already unref'd has nothing to drop, so nothing gets restored later. - if (controller->m_algorithms.kind == SourceKind::Native) { - bool wasRef = updateNativeSourceRef(globalObject, stream, false); - RETURN_IF_EXCEPTION(scope, void()); - stream->m_nativeRefDroppedOnRelease = wasRef; - } + case ControllerKind::Default: + defaultControllerOf(stream)->releaseSteps(); + setNativeSourceReaderLocked(stream, false); break; - } case ControllerKind::Byte: byteControllerOf(stream)->releaseSteps(); break; diff --git a/src/jsc/bindings/webcore/streams/WebStreamsInternals.h b/src/jsc/bindings/webcore/streams/WebStreamsInternals.h index a90f7fa8a62a..b244f5fbd761 100644 --- a/src/jsc/bindings/webcore/streams/WebStreamsInternals.h +++ b/src/jsc/bindings/webcore/streams/WebStreamsInternals.h @@ -280,7 +280,9 @@ void setUpReadableStreamDefaultReader(JSC::JSGlobalObject*, JSReadableStreamDefa void setUpReadableStreamBYOBReader(JSC::JSGlobalObject*, JSReadableStreamBYOBReader*, JSReadableStream*); // userJS: no — ReadableStreamOperations.cpp JSC::JSPromise* readableStreamReaderGenericCancel(JSC::JSGlobalObject*, JSReadableStreamReaderBase*, JSC::JSValue reason); // userJS: yes — ReadableStreamOperations.cpp void readableStreamReaderGenericInitialize(JSC::JSGlobalObject*, JSReadableStreamReaderBase*, JSReadableStream*); // userJS: no — ReadableStreamOperations.cpp -void readableStreamReaderGenericRelease(JSC::JSGlobalObject*, JSReadableStreamReaderBase*); // userJS: no (also runs Bun's native-handle updateRef(false) gate) — ReadableStreamOperations.cpp +void readableStreamReaderGenericRelease(JSC::JSGlobalObject*, JSReadableStreamReaderBase*); // userJS: no — ReadableStreamOperations.cpp +// Both of the above tell a FileReader source whether a reader holds its stream; the source drops its event-loop ref while none does. +extern "C" void FileReader__setReaderLocked(void* source, bool locked); // userJS: no — FileReader.rs // Stream-level state ops. JSC::JSPromise* readableStreamCancel(JSC::JSGlobalObject*, JSReadableStream*, JSC::JSValue reason); // userJS: yes — ReadableStreamOperations.cpp diff --git a/src/runtime/webcore/FileReader.rs b/src/runtime/webcore/FileReader.rs index 81000d954eec..27ebcce9f727 100644 --- a/src/runtime/webcore/FileReader.rs +++ b/src/runtime/webcore/FileReader.rs @@ -66,6 +66,8 @@ pub struct FileReader { /// path; `pull_into_sink` is the drain-ack resume. pub(crate) sink: JsCell, pub(crate) sink_paused: Cell, + /// A reader release took a held event-loop ref away; the next reader lock gives it back. An explicit `updateRef` cancels that. + pub(crate) ref_dropped_on_release: Cell, } impl Default for FileReader { @@ -90,6 +92,7 @@ impl Default for FileReader { flowing: Cell::new(true), sink: JsCell::new(SinkHandle::None), sink_paused: Cell::new(false), + ref_dropped_on_release: Cell::new(false), } } } @@ -899,12 +902,25 @@ impl FileReader { Vec::::move_from_list(mem::take(self.reader().buffer())) } - /// Returns the previous ref state. A finished reader has none. - pub(crate) fn set_ref_or_unref(&self, enable: bool) -> bool { + pub(crate) fn set_ref_or_unref(&self, enable: bool) { if self.done.get() { - return false; + return; + } + self.ref_dropped_on_release.set(false); + self.reader().update_ref(enable); + } + + /// A reader locked (`true`) or released (`false`) the stream over this source. A released source does not keep the event loop alive. + pub(crate) fn set_reader_locked(&self, locked: bool) { + if self.done.get() { + return; + } + if !locked { + let was_ref = self.reader().update_ref(false); + self.ref_dropped_on_release.set(was_ref); + } else if self.ref_dropped_on_release.replace(false) { + self.reader().update_ref(true); } - self.reader().update_ref(enable) } fn consume_reader_buffer(&self) { @@ -1069,6 +1085,14 @@ impl FileReader { pub(crate) type Source = readable_stream::NewSource; +/// `readableStreamReaderGenericInitialize` / `readableStreamReaderGenericRelease` (C++): a reader locked or released the stream over this source. +#[unsafe(no_mangle)] +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub(crate) extern "C" fn FileReader__setReaderLocked(source: *mut Source, locked: bool) { + // SAFETY: `source` is the live `Source` that the stream's native handle wraps. + unsafe { (*source).context.set_reader_locked(locked) }; +} + /// Holds a ref on the `Source` that embeds a `FileReader` while a dispatch runs /// user JS. Dropping it releases the ref and can free the source, so a pin must /// outlive every use of the reader it protects. @@ -1125,7 +1149,7 @@ impl readable_stream::SourceContext for FileReader { fn finalize_detach(&mut self) -> bool { Self::finalize_detach(self) } - fn set_ref_unref(&mut self, e: bool) -> bool { + fn set_ref_unref(&mut self, e: bool) { Self::set_ref_or_unref(self, e) } fn drain_internal_buffer(&mut self) -> Vec { diff --git a/src/runtime/webcore/ReadableStream.rs b/src/runtime/webcore/ReadableStream.rs index b7173aedb5a3..8202acb9af8e 100644 --- a/src/runtime/webcore/ReadableStream.rs +++ b/src/runtime/webcore/ReadableStream.rs @@ -813,10 +813,8 @@ pub trait SourceContext: Sized { /// sweep: no JS. `ByteStream` tells its producer nobody can read it now. fn wrapper_finalized(&mut self) {} - /// `setRefUnrefFn` — returns the previous ref state. Default no-op with no ref. - fn set_ref_unref(&mut self, _enable: bool) -> bool { - false - } + /// `setRefUnrefFn` — default no-op. + fn set_ref_unref(&mut self, _enable: bool) {} /// `drainInternalBuffer` — default returns empty. fn drain_internal_buffer(&mut self) -> Vec { @@ -1090,12 +1088,9 @@ impl NewSource { unsafe { &mut *Self::new(init) } } - /// Returns the previous ref state. - pub fn set_ref(&mut self, value: bool) -> bool { + pub fn set_ref(&mut self, value: bool) { if C::SUPPORTS_REF { - self.context.set_ref_unref(value) - } else { - false + self.context.set_ref_unref(value); } } @@ -1431,8 +1426,8 @@ impl NewSource { call_frame: &CallFrame, ) -> JsResult { let ref_or_unref = call_frame.argument(0).to_boolean(); - // The previous state, so a caller can restore only what it changed. - Ok(JSValue::js_boolean(self.set_ref(ref_or_unref))) + self.set_ref(ref_or_unref); + Ok(JSValue::UNDEFINED) } pub fn finalize(self: Box) { diff --git a/test/js/bun/console/console-iterator.test.ts b/test/js/bun/console/console-iterator.test.ts index ceb54547e42b..3412e55adc3f 100644 --- a/test/js/bun/console/console-iterator.test.ts +++ b/test/js/bun/console/console-iterator.test.ts @@ -81,7 +81,7 @@ it("can use the console iterator more than once", async () => { // stream must ref it again, or the process exits with code 0 while a read is // still pending. No top-level await in the child: it would keep the loop alive // and hide the bug. -describe("a later stdin consumer keeps the process alive after the reader is released", () => { +describe.concurrent("a later stdin consumer keeps the process alive after the reader is released", () => { const afterConsoleBreak = ` (async () => { for await (const line of console) { From c92fef89ca3e89365e9c3a6751c19f4d7a2fc838 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:29:35 +0000 Subject: [PATCH 08/10] test: an explicit unref() after a reader release stays in effect --- test/js/bun/console/console-iterator.test.ts | 35 ++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/test/js/bun/console/console-iterator.test.ts b/test/js/bun/console/console-iterator.test.ts index 3412e55adc3f..22fae99e4fbc 100644 --- a/test/js/bun/console/console-iterator.test.ts +++ b/test/js/bun/console/console-iterator.test.ts @@ -233,4 +233,39 @@ describe.concurrent("a later stdin consumer keeps the process alive after the re expect(stdout).toBe("DONE\n"); expect(exitCode).toBe(0); }); + + // The release dropped a held ref, but the unref() after it is the last word: + // the next reader must not bring the ref back. The parent never closes stdin, + // so a child that kept the ref would wait for input and time the test out. + it("an explicit unref() after the release stays in effect for the next reader", async () => { + await using proc = spawn({ + cmd: [ + bunExe(), + "-e", + ` + (async () => { + for await (const line of console) { + console.log("ITER " + line); + break; + } + process.stdin.unref(); + const reader = Bun.stdin.stream().getReader(); + console.log("READING"); + await reader.read(); + console.log("unexpected read"); + })(); + `, + ], + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + env: bunEnv, + }); + proc.stdin.write("first\n"); + proc.stdin.flush(); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(stdout).toBe("ITER first\nREADING\n"); + expect(exitCode).toBe(0); + }); }); From 0961f025c8cb6e54b45b551a6dfddebf418ad14d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 19:00:06 +0000 Subject: [PATCH 09/10] FileReader: note that set_reader_locked must not dispatch a read --- src/runtime/webcore/FileReader.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/runtime/webcore/FileReader.rs b/src/runtime/webcore/FileReader.rs index 27ebcce9f727..ade00c3b4982 100644 --- a/src/runtime/webcore/FileReader.rs +++ b/src/runtime/webcore/FileReader.rs @@ -911,6 +911,7 @@ impl FileReader { } /// A reader locked (`true`) or released (`false`) the stream over this source. A released source does not keep the event loop alive. + /// The C++ callers are `userJS: no`, so this must not dispatch a read. pub(crate) fn set_reader_locked(&self, locked: bool) { if self.done.get() { return; From 228a5e114f64287e29c39787096495288b34c888 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 22 Sep 2026 19:01:49 +0000 Subject: [PATCH 10/10] FileReader: fold the set_reader_locked comment into one line --- src/runtime/webcore/FileReader.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/webcore/FileReader.rs b/src/runtime/webcore/FileReader.rs index ade00c3b4982..b7b726ee1511 100644 --- a/src/runtime/webcore/FileReader.rs +++ b/src/runtime/webcore/FileReader.rs @@ -910,8 +910,7 @@ impl FileReader { self.reader().update_ref(enable); } - /// A reader locked (`true`) or released (`false`) the stream over this source. A released source does not keep the event loop alive. - /// The C++ callers are `userJS: no`, so this must not dispatch a read. + /// A reader locked (`true`) or released (`false`) the stream over this source. Its C++ callers are `userJS: no`: never dispatch a read here. pub(crate) fn set_reader_locked(&self, locked: bool) { if self.done.get() { return;