Skip to content
1 change: 1 addition & 0 deletions src/runtime/api/streams.classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ function source(name) {
construct: false,
noConstructor: true,
finalize: true,
hasPendingActivity: true,
configurable: false,
memoryCost: true,
proto: {
Expand Down
12 changes: 12 additions & 0 deletions src/runtime/webcore/FileReader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,18 @@ impl FileReader {
unsafe { (*self.parent()).increment_count() };
}
}
#[cfg(windows)]
{
// Non-lazy fromPipe path (Bun.spawn stdout/stderr): hold a
// ref across the pending uv_read_start so the source is not
// finalized while IOCP has a read queued on it.
if !self.started.get() && self.reader().source.is_some() && !self.reader().is_done()
{
self.waiting_for_on_reader_done.set(true);
// SAFETY: see `parent()`.
unsafe { (*self.parent()).increment_count() };
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

#[cfg(unix)]
Expand Down
100 changes: 83 additions & 17 deletions src/runtime/webcore/ReadableStream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,10 @@ pub trait SourceContext: Sized {
fn js_on_drain_callback_set_cached(this: JSValue, global: &JSGlobalObject, value: JSValue);
/// `js_${NAME}InternalReadableStreamSource::on_drain_callback_get_cached`
fn js_on_drain_callback_get_cached(this: JSValue) -> Option<JSValue>;
/// `js_${NAME}InternalReadableStreamSource::on_close_callback_set_cached`
fn js_on_close_callback_set_cached(this: JSValue, global: &JSGlobalObject, value: JSValue);
/// `js_${NAME}InternalReadableStreamSource::on_close_callback_get_cached`
fn js_on_close_callback_get_cached(this: JSValue) -> Option<JSValue>;

fn on_start(&mut self) -> streams::Start;
fn on_pull(&mut self, buf: &mut [u8], view: JSValue) -> streams::Result;
Expand Down Expand Up @@ -639,14 +643,15 @@ pub trait SourceContext: Sized {
pub struct NewSource<C: SourceContext> {
pub context: C,
pub cancelled: bool,
pub ref_count: u32,
/// Atomic so the GC-thread `has_pending_activity` can read it while the
/// JS thread mutates it in `increment_count`/`decrement_count`.
pub ref_count: core::sync::atomic::AtomicU32,
pub pending_err: Option<syscall::Error>,
pub close_handler: Option<fn(Option<*mut c_void>)>,
/// Borrowed opaque context for native `close_handler`s (never
/// owned/freed here). The JS path stores
/// `on_js_close` and leaves this `None` — see [`Self::on_close`].
pub close_ctx: Option<NonNull<c_void>>,
pub close_jsvalue: bun_jsc::strong::Optional,
/// R-2: cleared via `&self` from `FetchTasklet::clear_stream_cancel_handler`
/// (through `ByteStream::parent_const`), so interior-mutable.
pub cancel_handler: Cell<Option<fn(Option<*mut c_void>)>>,
Expand All @@ -668,11 +673,10 @@ impl<C: SourceContext + Default> Default for NewSource<C> {
Self {
context: C::default(),
cancelled: false,
ref_count: 1,
ref_count: core::sync::atomic::AtomicU32::new(1),
pending_err: None,
close_handler: None,
close_ctx: None,
close_jsvalue: bun_jsc::strong::Optional::empty(),
cancel_handler: Cell::new(None),
cancel_ctx: Cell::new(None),
global_this: None,
Expand All @@ -692,9 +696,11 @@ pub(crate) trait NewSourceCodegen {
fn pending_promise_set_cached(this: JSValue, global: &JSGlobalObject, value: JSValue);
fn on_drain_callback_set_cached(this: JSValue, global: &JSGlobalObject, value: JSValue);
fn on_drain_callback_get_cached(this: JSValue) -> Option<JSValue>;
fn on_close_callback_set_cached(this: JSValue, global: &JSGlobalObject, value: JSValue);
fn on_close_callback_get_cached(this: JSValue) -> Option<JSValue>;
}

/// Binds the four `SourceContext::js_*` accessors to the codegen'd
/// Binds the `SourceContext::js_*` accessors to the codegen'd
/// `crate::generated_classes::js_${Name}InternalReadableStreamSource` module
/// (one per `.classes.ts` entry: `Blob`, `File`, `Bytes`). The extern symbols
/// are declared exactly once inside that module — no local `extern "C"` block.
Expand Down Expand Up @@ -732,6 +738,20 @@ macro_rules! source_context_codegen {
) -> Option<$crate::webcore::jsc::JSValue> {
$crate::generated_classes::$gen::on_drain_callback_get_cached(this)
}
#[inline]
fn js_on_close_callback_set_cached(
this: $crate::webcore::jsc::JSValue,
global: &$crate::webcore::jsc::JSGlobalObject,
value: $crate::webcore::jsc::JSValue,
) {
$crate::generated_classes::$gen::on_close_callback_set_cached(this, global, value)
}
#[inline]
fn js_on_close_callback_get_cached(
this: $crate::webcore::jsc::JSValue,
) -> Option<$crate::webcore::jsc::JSValue> {
$crate::generated_classes::$gen::on_close_callback_get_cached(this)
}
};
}

Expand All @@ -754,6 +774,12 @@ impl<C: SourceContext> NewSourceCodegen for NewSource<C> {
fn on_drain_callback_get_cached(this: JSValue) -> Option<JSValue> {
C::js_on_drain_callback_get_cached(this)
}
fn on_close_callback_set_cached(this: JSValue, global: &JSGlobalObject, value: JSValue) {
C::js_on_close_callback_set_cached(this, global, value)
}
fn on_close_callback_get_cached(this: JSValue) -> Option<JSValue> {
C::js_on_close_callback_get_cached(this)
}
}

// Enforce the layout invariant `from_js`/`Source` rely on.
Expand Down Expand Up @@ -870,14 +896,37 @@ impl<C: SourceContext> NewSource<C> {
fn on_js_close(ptr: Option<*mut c_void>) {
// SAFETY: ptr was set to `self as *mut NewSource<C>` in on_close()/set_on_close_from_js.
let this = unsafe { &mut *(ptr.unwrap().cast::<NewSource<C>>()) };
if let Some(cb) = this.close_jsvalue.try_swap() {
this.global_this().queue_microtask(cb, &[]);
if this.this_jsvalue != JSValue::ZERO {
let global_this = this.global_this();
if let Some(cb) =
<Self as NewSourceCodegen>::on_close_callback_get_cached(this.this_jsvalue)
{
if !cb.is_undefined() {
global_this.queue_microtask(cb, &[]);
}
}
<Self as NewSourceCodegen>::on_close_callback_set_cached(
this.this_jsvalue,
global_this,
JSValue::UNDEFINED,
);
Comment thread
robobun marked this conversation as resolved.
Resolved
}
this.close_jsvalue.deinit();
}

pub fn increment_count(&mut self) {
self.ref_count += 1;
self.ref_count
.fetch_add(1, core::sync::atomic::Ordering::SeqCst);
}

/// Called from the GC thread via the codegen
/// `{Blob,Bytes,File}InternalReadableStreamSource__hasPendingActivity`
/// thunks. Returns true while any ref other than the JS wrapper's own is
/// held (in practice: a `FileReader` `waiting_for_on_reader_done` I/O ref),
/// so the wrapper stays marked and `this_jsvalue` is never read after the
/// cell is dead-but-unswept. Only touches the atomic field so `&self` is
/// sound across threads.
pub fn has_pending_activity(&self) -> bool {
self.ref_count.load(core::sync::atomic::Ordering::SeqCst) > 1
}

/// Release one reference. If the count hits zero, runs context teardown and
Expand All @@ -893,18 +942,16 @@ impl<C: SourceContext> NewSource<C> {
pub unsafe fn decrement_count(this: *mut Self) -> u32 {
// SAFETY: caller contract — `this` is live for the duration of this block.
let remaining = unsafe {
let r = &mut (*this).ref_count;
let r = &(*this).ref_count;
#[cfg(debug_assertions)]
if *r == 0 {
if r.load(core::sync::atomic::Ordering::SeqCst) == 0 {
panic!("Attempted to decrement ref count below zero");
}
*r -= 1;
*r
r.fetch_sub(1, core::sync::atomic::Ordering::SeqCst) - 1
};
if remaining == 0 {
// SAFETY: still live; run side-effect teardown while fields are valid.
unsafe {
(*this).close_jsvalue.deinit();
(*this).context.deinit_fn();
}
// SAFETY: `this` originated from `Box::into_raw` in `Self::new`. No
Expand Down Expand Up @@ -1084,7 +1131,13 @@ impl<C: SourceContext> NewSource<C> {
self.global_this = Some(bun_ptr::BackRef::new(global_object));

if value.is_undefined() {
self.close_jsvalue.deinit();
if self.this_jsvalue != JSValue::ZERO {
<Self as NewSourceCodegen>::on_close_callback_set_cached(
self.this_jsvalue,
global_object,
JSValue::UNDEFINED,
);
}
return Ok(());
}

Expand All @@ -1096,7 +1149,13 @@ impl<C: SourceContext> NewSource<C> {
));
}
let cb = value.with_async_context_if_needed(global_object);
self.close_jsvalue.set(global_object, cb);
if self.this_jsvalue != JSValue::ZERO {
<Self as NewSourceCodegen>::on_close_callback_set_cached(
self.this_jsvalue,
global_object,
cb,
);
}
Ok(())
}

Expand Down Expand Up @@ -1133,7 +1192,14 @@ impl<C: SourceContext> NewSource<C> {
}

pub fn get_on_close_from_js(&mut self, _global_object: &JSGlobalObject) -> JSValue {
self.close_jsvalue.get().unwrap_or(JSValue::UNDEFINED)
if self.this_jsvalue != JSValue::ZERO {
if let Some(val) =
<Self as NewSourceCodegen>::on_close_callback_get_cached(self.this_jsvalue)
{
return val;
}
}
JSValue::UNDEFINED
}

pub fn get_on_drain_from_js(&mut self, _global_object: &JSGlobalObject) -> JSValue {
Expand Down
119 changes: 119 additions & 0 deletions test/js/web/streams/native-source-onclose-leak.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { heapStats } from "bun:jsc";
import { expect, test } from "bun:test";

// The JS onClose callback is installed on the native source wrapper when the
// lazy stream is first pulled. Storing it in a JSC::Strong rooted a cycle
// (source wrapper -> m_ctx NewSource -> Strong(onClose) -> bound fn ->
// NativeReadableStreamSource -> $stream -> source wrapper) that only broke
// when EOF ran the JS-side callClose or the cancel algorithm ran #cancel. A
// stream that is read partially and then dropped (releaseLock without cancel)
// never hits either path, so the source wrapper leaked forever. Storing
// onClose in the GC-traced onCloseCallback WriteBarrier slot (as onDrain
// already did) turns the cycle into an ordinary intra-heap cycle that
// mark-sweep collects.

test("native ReadableStream source is collectable after partial read + releaseLock", async () => {
// Payload must exceed the native pull buffer (ByteBlobLoader caps
// chunk_size at 2MB) so the first pull does not return *AndDone and
// callClose is never queued.
const payload = Buffer.alloc(8 * 1024 * 1024, "x");
async function once() {
const stream = new Blob([payload]).stream();
const reader = stream.getReader();
await reader.read();
reader.releaseLock();
}

for (let i = 0; i < 5; i++) await once();
Bun.gc(true);
const before = heapStats().objectTypeCounts.BlobInternalReadableStreamSource ?? 0;

for (let i = 0; i < 30; i++) await once();
Bun.gc(true);
await 1;
Bun.gc(true);
const after = heapStats().objectTypeCounts.BlobInternalReadableStreamSource ?? 0;

// Pre-fix this grew by exactly 30 (one pinned wrapper per iteration).
expect(after - before).toBeLessThan(8);
});

test("fetch body native source is collectable after partial read + releaseLock", async () => {
const payload = Buffer.alloc(4 * 1024 * 1024, "x");
using server = Bun.serve({
port: 0,
fetch() {
return new Response(payload);
},
});
const url = `http://127.0.0.1:${server.port}/`;

async function once() {
const res = await fetch(url);
const reader = res.body!.getReader();
await reader.read();
reader.releaseLock();
}

for (let i = 0; i < 5; i++) await once();
Bun.gc(true);
const countSources = () => {
const c = heapStats().objectTypeCounts;
return (c.BlobInternalReadableStreamSource ?? 0) + (c.BytesInternalReadableStreamSource ?? 0);
};
const before = countSources();

for (let i = 0; i < 30; i++) await once();
Bun.gc(true);
await 1;
Bun.gc(true);
const after = countSources();

// Pre-fix this grew by ~30.
expect(after - before).toBeLessThan(8);
});

// Regression guard: the cycle-breaking paths that already worked must keep
// working after switching storage.
test("native ReadableStream source is collectable after full consumption", async () => {
const payload = Buffer.alloc(8 * 1024 * 1024, "x");
async function once() {
const stream = new Blob([payload]).stream();
for await (const _ of stream) {
}
}

for (let i = 0; i < 5; i++) await once();
Bun.gc(true);
const before = heapStats().objectTypeCounts.BlobInternalReadableStreamSource ?? 0;

for (let i = 0; i < 30; i++) await once();
Bun.gc(true);
await 1;
Bun.gc(true);
const after = heapStats().objectTypeCounts.BlobInternalReadableStreamSource ?? 0;

expect(after - before).toBeLessThan(8);
});

test("native source onClose callback still fires after switching to cached slot", async () => {
// proc.stdout is a FileInternalReadableStreamSource; closing stdin makes
// cat exit, which EOFs stdout. FileReader.on_reader_done -> parent.on_close
// -> on_js_close must still find and invoke the JS onClose callback now
// that it lives in a WriteBarrier slot rather than a Strong.
await using proc = Bun.spawn({
cmd: ["cat"],
stdin: "pipe",
stdout: "pipe",
env: { PATH: process.env.PATH },
});
const reader = proc.stdout.getReader();
const pending = reader.read();
proc.stdin.end();
const { done } = await pending;
// If on_js_close did not fire, the pending pull promise would never resolve
// with done:true and this test would hang.
expect(done).toBe(true);
reader.releaseLock();
await proc.exited;
});
Loading