From 8fbbe6f7239a6a2775d824af8018cd5a27b598fc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 21 Jul 2026 01:17:48 +0000 Subject: [PATCH 1/7] redis: gate the socket keep-alive adopt and defer destruction to finalize on_valkey_close/on_valkey_reconnect adopted connect()'s socket ref unconditionally. Under connection-timeout + reconnect churn the close/fail teardown can be re-entered from on_connection_timeout such that the adopt spends a ref that is not outstanding, stealing the JS wrapper's +1; the ScopedRef drops at the end of on_connection_timeout then bring the count to 0 and free the box while the wrapper is live, and GC finalize -> stop_timers reads the freed allocation. Two changes, layered: - Track outstanding socket refs in a Cell (incremented at each socket_ref.forget() in connect()) and have on_valkey_close / on_valkey_reconnect adopt via take_socket_ref(), which returns None when the counter is 0. Same pattern RefCountedTimer applied to the timer refs in #34760; a counter rather than a bool because a stale reconnect can leave more than one us_socket_t in flight for the same client. - Guard the RefCounted destructor: if the count reaches 0 before the JS wrapper has been finalized, restore the stolen +1 and return without freeing, so finalize() frees normally instead of touching freed memory. Assertion builds panic here so any remaining over-release path is caught. --- src/runtime/valkey_jsc/js_valkey.rs | 55 ++++++++++++++++++--- test/js/valkey/valkey-gc.test.ts | 76 +++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+), 8 deletions(-) diff --git a/src/runtime/valkey_jsc/js_valkey.rs b/src/runtime/valkey_jsc/js_valkey.rs index 9f6c186dcb90..e38b5fcf7e16 100644 --- a/src/runtime/valkey_jsc/js_valkey.rs +++ b/src/runtime/valkey_jsc/js_valkey.rs @@ -359,6 +359,11 @@ pub struct JSValkeyClient { pub timer: RefCountedTimer, pub reconnect_timer: RefCountedTimer, + /// Keep-alive refs handed to open sockets by [`connect`](Self::connect). + /// Released by [`take_socket_ref`](Self::take_socket_ref). A counter (not + /// a bool) because the reconnect path can have more than one in-flight + /// `us_socket_t` with this client in its ext slot. + socket_refs: Cell, pub ref_count: bun_ptr::RefCount, } @@ -466,6 +471,22 @@ impl bun_ptr::RefCounted for JSValkeyClient { unsafe { &raw mut (*this).ref_count } } unsafe fn destructor(this: *mut Self, _ctx: ()) { + // SAFETY: last ref dropped; `this` is live until `deinit` reclaims it. + let this_ref = unsafe { &*this }; + if !this_ref.client.get().flags.finalized && this_ref.this_value.get().is_not_empty() { + // Reaching 0 while the JS wrapper is still attached means a ref + // was released that was not owned (the wrapper's `+1` is only + // ever consumed by `finalize()`). Freeing here would make the + // later `finalize()` a heap-use-after-free, so donate the stolen + // ref back and leave the allocation live; `finalize()` then frees + // normally. Assertion builds panic so the over-release is caught. + debug_assert!( + false, + "JSValkeyClient refcount reached 0 before the JS wrapper was finalized", + ); + this_ref.ref_(); + return; + } // SAFETY: last ref dropped; sole owner. unsafe { JSValkeyClient::deinit(this) }; } @@ -501,6 +522,25 @@ impl JSValkeyClient { // SAFETY: `self` is live; the guard's own ref keeps it alive past Drop. unsafe { ScopedRef::new(self.as_ctx_ptr()) } } + /// Adopt a socket keep-alive ref recorded by [`connect`](Self::connect) + /// into the calling scope. Returns `None` when no ref is outstanding, so a + /// close/reconnect dispatch that arrives without a live socket ref cannot + /// release one it does not own. + #[inline] + fn take_socket_ref(&self) -> Option> { + let n = self.socket_refs.get(); + if n == 0 { + debug_assert!( + false, + "on_valkey_close/on_valkey_reconnect without a live socket ref", + ); + return None; + } + self.socket_refs.set(n - 1); + // SAFETY: `connect()` took this `+1` via `socket_ref.forget()` and + // recorded it in `socket_refs`; this scope consumes it. + Some(unsafe { ScopedRef::adopt(self.as_ctx_ptr()) }) + } #[inline] pub fn new(init: JSValkeyClient) -> *mut JSValkeyClient { // bun.TrivialNew(@This()) → heap::alloc(Box::new(init)) @@ -818,6 +858,7 @@ impl JSValkeyClient { _secure: Cell::new(None), timer: RefCountedTimer::new(Timer::Tag::ValkeyConnectionTimeout), reconnect_timer: RefCountedTimer::new(Timer::Tag::ValkeyConnectionReconnect), + socket_refs: Cell::new(0), })) } @@ -938,6 +979,7 @@ impl JSValkeyClient { _secure: Cell::new(None), timer: RefCountedTimer::new(Timer::Tag::ValkeyConnectionTimeout), reconnect_timer: RefCountedTimer::new(Timer::Tag::ValkeyConnectionReconnect), + socket_refs: Cell::new(0), })) } @@ -1379,11 +1421,7 @@ impl JSValkeyClient { // Callback for when Valkey client needs to reconnect pub fn on_valkey_reconnect(&self) { - // SAFETY: adopts connect()'s socket keep-alive ref for the just-closed - // socket. Reached only from `ValkeyClient::on_close()`'s reconnect - // branch, which never calls `on_valkey_close()`, so this scope is the - // sole releaser. The caller holds its own scoped ref, so count > 0. - let _socket_ref = unsafe { ScopedRef::adopt(self.as_ctx_ptr()) }; + let _socket_ref = self.take_socket_ref(); self.reconnect_timer .arm(self, self.client.get().get_reconnect_delay()); @@ -1393,9 +1431,7 @@ impl JSValkeyClient { pub fn on_valkey_close(&self) -> JsTerminatedResult<()> { let global_object = self.global_object; - // SAFETY: adopts connect()'s socket keep-alive ref; the caller holds - // its own scoped ref so count stays > 0 until this drops. - let _socket_ref = unsafe { ScopedRef::adopt(self.as_ctx_ptr()) }; + let _socket_ref = self.take_socket_ref(); let _defer = scopeguard::guard(BackRef::new(self), |p| p.update_poll_ref()); let Some(this_jsvalue) = self.this_value.get().try_get() else { @@ -1596,6 +1632,7 @@ impl JSValkeyClient { // `on_valkey_close()` consumes the socket ref; hand it over so it // isn't released twice. socket_ref.forget(); + self.socket_refs.set(self.socket_refs.get() + 1); self.client_mut().on_valkey_close()?; self.client_mut().status = valkey::Status::Disconnected; return Ok(()); @@ -1637,6 +1674,7 @@ impl JSValkeyClient { // Disarm on success: the socket now owns the keep-alive ref. scopeguard::ScopeGuard::into_inner(errdefer_status); socket_ref.forget(); + self.socket_refs.set(self.socket_refs.get() + 1); Ok(()) } @@ -1709,6 +1747,7 @@ impl JSValkeyClient { debug_assert!(this_ref.client.get().socket.is_closed()); debug_assert!(!this_ref.timer.ref_held.get()); debug_assert!(!this_ref.reconnect_timer.ref_held.get()); + debug_assert_eq!(this_ref.socket_refs.get(), 0); if let Some(s) = this_ref._secure.get() { // SAFETY: SSL_CTX is C-refcounted; this releases our ref. unsafe { boringssl::c::SSL_CTX_free(s) }; diff --git a/test/js/valkey/valkey-gc.test.ts b/test/js/valkey/valkey-gc.test.ts index 1a4a8e9e2dfe..931161cf0ee1 100644 --- a/test/js/valkey/valkey-gc.test.ts +++ b/test/js/valkey/valkey-gc.test.ts @@ -181,6 +181,82 @@ test.concurrent("RedisClient survives subscribe() + close() against a server tha expect(exitCode).toBe(0); }); +// Same fault class as above, with the yield point moved so the server-side +// close is processed before `close()`: on_close takes the auto-reconnect +// branch, and the still-armed connection-timeout timer then fires against a +// Disconnected client. on_valkey_close/on_valkey_reconnect previously adopted +// the socket keep-alive ref unconditionally; when the close/fail path re-enters +// under the fired timer that adopt could spend the JS wrapper's own +1, so the +// guards at the end of on_connection_timeout dropped the count to 0 and freed +// the Box while the wrapper was live. GC finalize -> stop_timers then read the +// freed allocation. +test.concurrent( + "RedisClient survives on_connection_timeout firing after an auto-reconnect close", + async () => { + const src = ` + const CRLF = "\\r\\n"; + const blk = s => "$" + s.length + CRLF + s + CRLF; + const sockets = []; + const server = Bun.listen({ + hostname: "127.0.0.1", + port: 0, + socket: { + open(s) { s.data = { buf: "" }; sockets.push(s); }, + data(s, d) { + s.data.buf += d.toString("latin1"); + if (s.data.buf.includes("HELLO")) s.write("%1" + CRLF + blk("proto") + ":3" + CRLF); + else if (s.data.buf.includes(CRLF)) s.write("+OK" + CRLF); + s.data.buf = ""; + }, + close() {}, + }, + }); + const url = "redis://127.0.0.1:" + server.port; + const clients = []; + for (let round = 0; round < ${isASAN ? 80 : 200}; round++) { + const c = new Bun.RedisClient(url, { autoReconnect: true, connectionTimeout: 2000 }); + c.onconnect = () => {}; c.onclose = () => {}; + try { await c.connect(); } catch {} + const s = sockets.pop(); + try { s?.terminate?.(); s?.end?.(); } catch {} + // Let the close reach the client so on_close takes the reconnect branch + // (is_manually_closed is still false at that point). + await new Promise(r => setImmediate(r)); + await new Promise(r => setImmediate(r)); + try { c.subscribe("ch" + round, () => {}).catch(() => {}); } catch {} + try { c.close(); } catch {} + clients.push(c); + if (round % 8 === 0) Bun.gc(false); + await new Promise(r => setTimeout(r, 1)); + } + // Drive GC so finalize() runs and would touch any freed allocation. + Bun.gc(true); + await new Promise(r => setTimeout(r, 50)); + Bun.gc(true); + for (const c of clients) { + if (typeof c.connected !== "boolean") throw new Error("expected boolean"); + } + while (sockets.length) try { sockets.pop()?.terminate?.(); } catch {} + server.stop(true); + console.log("OK"); + process.exit(0); + `; + + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", src], + env: bunEnv, + stdout: "pipe", + stderr: "inherit", + }); + + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + + expect(stdout.trim()).toBe("OK"); + expect(proc.signalCode).toBeNull(); + expect(exitCode).toBe(0); + }, +); + // Fuzzer found a flaky SIGILL when a RedisClient is constructed, a command // throws during argument validation (before any connection attempt), and the // client is then garbage collected. `updatePollRef` could be reached after From 76afaa37acc582b952bdf512905fc9015d5678ac Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 21 Jul 2026 01:20:24 +0000 Subject: [PATCH 2/7] [autofix.ci] apply automated fixes --- test/js/valkey/valkey-gc.test.ts | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/test/js/valkey/valkey-gc.test.ts b/test/js/valkey/valkey-gc.test.ts index 931161cf0ee1..fc60fe30b679 100644 --- a/test/js/valkey/valkey-gc.test.ts +++ b/test/js/valkey/valkey-gc.test.ts @@ -190,10 +190,8 @@ test.concurrent("RedisClient survives subscribe() + close() against a server tha // guards at the end of on_connection_timeout dropped the count to 0 and freed // the Box while the wrapper was live. GC finalize -> stop_timers then read the // freed allocation. -test.concurrent( - "RedisClient survives on_connection_timeout firing after an auto-reconnect close", - async () => { - const src = ` +test.concurrent("RedisClient survives on_connection_timeout firing after an auto-reconnect close", async () => { + const src = ` const CRLF = "\\r\\n"; const blk = s => "$" + s.length + CRLF + s + CRLF; const sockets = []; @@ -242,20 +240,19 @@ test.concurrent( process.exit(0); `; - await using proc = Bun.spawn({ - cmd: [bunExe(), "-e", src], - env: bunEnv, - stdout: "pipe", - stderr: "inherit", - }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", src], + env: bunEnv, + stdout: "pipe", + stderr: "inherit", + }); - const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); - expect(stdout.trim()).toBe("OK"); - expect(proc.signalCode).toBeNull(); - expect(exitCode).toBe(0); - }, -); + expect(stdout.trim()).toBe("OK"); + expect(proc.signalCode).toBeNull(); + expect(exitCode).toBe(0); +}); // Fuzzer found a flaky SIGILL when a RedisClient is constructed, a command // throws during argument validation (before any connection attempt), and the From b909587a3f1d08eb3ad662041196701fa3187086 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 21 Jul 2026 01:36:54 +0000 Subject: [PATCH 3/7] test: let wrappers be collected so finalize() actually runs The clients array kept every wrapper reachable past both Bun.gc(true) calls, so the "drive GC so finalize() runs" comment described something that could not happen. Move the .connected probe into the loop and let c fall out of scope at round end, matching the sibling tests, and reword the header to be honest that the interleaving is timing-dependent. --- test/js/valkey/valkey-gc.test.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/test/js/valkey/valkey-gc.test.ts b/test/js/valkey/valkey-gc.test.ts index fc60fe30b679..5ee8911a21ee 100644 --- a/test/js/valkey/valkey-gc.test.ts +++ b/test/js/valkey/valkey-gc.test.ts @@ -183,13 +183,13 @@ test.concurrent("RedisClient survives subscribe() + close() against a server tha // Same fault class as above, with the yield point moved so the server-side // close is processed before `close()`: on_close takes the auto-reconnect -// branch, and the still-armed connection-timeout timer then fires against a -// Disconnected client. on_valkey_close/on_valkey_reconnect previously adopted -// the socket keep-alive ref unconditionally; when the close/fail path re-enters -// under the fired timer that adopt could spend the JS wrapper's own +1, so the -// guards at the end of on_connection_timeout dropped the count to 0 and freed -// the Box while the wrapper was live. GC finalize -> stop_timers then read the -// freed allocation. +// branch, the reconnect timer is armed, and the still-armed connection-timeout +// timer later fires against a Disconnected client. This is the interleaving +// under which the fuzzer drives on_connection_timeout to drop the final ref +// while the JS wrapper is live; the race is timing-dependent and does not +// fire deterministically in CI, so this test exercises the path and relies on +// ASAN plus the assertion in `JSValkeyClient::destructor` to catch an +// over-release if one occurs. test.concurrent("RedisClient survives on_connection_timeout firing after an auto-reconnect close", async () => { const src = ` const CRLF = "\\r\\n"; @@ -210,7 +210,6 @@ test.concurrent("RedisClient survives on_connection_timeout firing after an auto }, }); const url = "redis://127.0.0.1:" + server.port; - const clients = []; for (let round = 0; round < ${isASAN ? 80 : 200}; round++) { const c = new Bun.RedisClient(url, { autoReconnect: true, connectionTimeout: 2000 }); c.onconnect = () => {}; c.onclose = () => {}; @@ -223,17 +222,18 @@ test.concurrent("RedisClient survives on_connection_timeout firing after an auto await new Promise(r => setImmediate(r)); try { c.subscribe("ch" + round, () => {}).catch(() => {}); } catch {} try { c.close(); } catch {} - clients.push(c); + // Read through the Box while the wrapper is still live; under ASAN this + // trips heap-use-after-free if the round over-released. + if (typeof c.connected !== "boolean") throw new Error("expected boolean"); if (round % 8 === 0) Bun.gc(false); await new Promise(r => setTimeout(r, 1)); } - // Drive GC so finalize() runs and would touch any freed allocation. + // Wrappers from earlier rounds are now unreachable; collect so + // finalize() -> stop_timers runs (and would touch a freed Box if one + // was over-released without having crashed the .connected probe). Bun.gc(true); await new Promise(r => setTimeout(r, 50)); Bun.gc(true); - for (const c of clients) { - if (typeof c.connected !== "boolean") throw new Error("expected boolean"); - } while (sockets.length) try { sockets.pop()?.terminate?.(); } catch {} server.stop(true); console.log("OK"); From e29310e38a53a06819f08a17966f6887db556a2e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 15:38:53 +0000 Subject: [PATCH 4/7] redis: drop the destructor guard and debug_assert; gate is the fix The unconditional ScopedRef::adopt in on_valkey_close/on_valkey_reconnect is the only release on the teardown path that is not tracked against its acquire. The close/fail paths can re-enter: on_data -> parse fail (or on_connection_timeout -> client_fail) -> fail_with_js_value -> close() dispatches on_close synchronously, and the enter_event_loop_scope drain inside on_valkey_close runs the connect() rejection while the outer socket-handler frames are still on the stack, so user code (or a second dispatch in the same batch) can reach on_valkey_close again with the ref already released. take_socket_ref() mirrors RefCountedTimer: connect() records each forget() in a counter, and the adopt is a checked_sub so a re-entrant caller with no outstanding ref returns None instead of over-releasing. Replaced the timing-dependent churn test with a malformed-RESP-reply test that drives on_data -> close deterministically. --- src/runtime/valkey_jsc/js_valkey.rs | 46 +++++++--------------- test/js/valkey/valkey-gc.test.ts | 61 +++++++++-------------------- 2 files changed, 34 insertions(+), 73 deletions(-) diff --git a/src/runtime/valkey_jsc/js_valkey.rs b/src/runtime/valkey_jsc/js_valkey.rs index e38b5fcf7e16..28b1092ba7a5 100644 --- a/src/runtime/valkey_jsc/js_valkey.rs +++ b/src/runtime/valkey_jsc/js_valkey.rs @@ -471,22 +471,6 @@ impl bun_ptr::RefCounted for JSValkeyClient { unsafe { &raw mut (*this).ref_count } } unsafe fn destructor(this: *mut Self, _ctx: ()) { - // SAFETY: last ref dropped; `this` is live until `deinit` reclaims it. - let this_ref = unsafe { &*this }; - if !this_ref.client.get().flags.finalized && this_ref.this_value.get().is_not_empty() { - // Reaching 0 while the JS wrapper is still attached means a ref - // was released that was not owned (the wrapper's `+1` is only - // ever consumed by `finalize()`). Freeing here would make the - // later `finalize()` a heap-use-after-free, so donate the stolen - // ref back and leave the allocation live; `finalize()` then frees - // normally. Assertion builds panic so the over-release is caught. - debug_assert!( - false, - "JSValkeyClient refcount reached 0 before the JS wrapper was finalized", - ); - this_ref.ref_(); - return; - } // SAFETY: last ref dropped; sole owner. unsafe { JSValkeyClient::deinit(this) }; } @@ -522,24 +506,24 @@ impl JSValkeyClient { // SAFETY: `self` is live; the guard's own ref keeps it alive past Drop. unsafe { ScopedRef::new(self.as_ctx_ptr()) } } - /// Adopt a socket keep-alive ref recorded by [`connect`](Self::connect) - /// into the calling scope. Returns `None` when no ref is outstanding, so a - /// close/reconnect dispatch that arrives without a live socket ref cannot - /// release one it does not own. + /// Adopt one socket keep-alive ref recorded by [`connect`](Self::connect) + /// into the calling scope, or `None` when none is outstanding. The + /// close/fail paths can re-enter (`on_data` parse fail or + /// `on_connection_timeout` → `fail_with_js_value` → `close()` dispatches + /// `on_close` synchronously, and the `enter_event_loop_scope` drain inside + /// `on_valkey_close` runs JS that can close again), so a second caller + /// sees 0 here and releases nothing. #[inline] fn take_socket_ref(&self) -> Option> { - let n = self.socket_refs.get(); - if n == 0 { - debug_assert!( - false, - "on_valkey_close/on_valkey_reconnect without a live socket ref", - ); - return None; + match self.socket_refs.get().checked_sub(1) { + None => None, + Some(n) => { + self.socket_refs.set(n); + // SAFETY: `connect()` took this `+1` via `socket_ref.forget()` + // and recorded it in `socket_refs`; this scope consumes it. + Some(unsafe { ScopedRef::adopt(self.as_ctx_ptr()) }) + } } - self.socket_refs.set(n - 1); - // SAFETY: `connect()` took this `+1` via `socket_ref.forget()` and - // recorded it in `socket_refs`; this scope consumes it. - Some(unsafe { ScopedRef::adopt(self.as_ctx_ptr()) }) } #[inline] pub fn new(init: JSValkeyClient) -> *mut JSValkeyClient { diff --git a/test/js/valkey/valkey-gc.test.ts b/test/js/valkey/valkey-gc.test.ts index 5ee8911a21ee..911e36247464 100644 --- a/test/js/valkey/valkey-gc.test.ts +++ b/test/js/valkey/valkey-gc.test.ts @@ -181,60 +181,37 @@ test.concurrent("RedisClient survives subscribe() + close() against a server tha expect(exitCode).toBe(0); }); -// Same fault class as above, with the yield point moved so the server-side -// close is processed before `close()`: on_close takes the auto-reconnect -// branch, the reconnect timer is armed, and the still-armed connection-timeout -// timer later fires against a Disconnected client. This is the interleaving -// under which the fuzzer drives on_connection_timeout to drop the final ref -// while the JS wrapper is live; the race is timing-dependent and does not -// fire deterministically in CI, so this test exercises the path and relies on -// ASAN plus the assertion in `JSValkeyClient::destructor` to catch an -// over-release if one occurs. -test.concurrent("RedisClient survives on_connection_timeout firing after an auto-reconnect close", async () => { +// A malformed reply drives on_data -> parse fail -> fail_with_js_value -> +// close(), which dispatches SocketHandler::on_close synchronously. Its +// on_valkey_close() previously adopted the socket keep-alive ref +// unconditionally; the enter_event_loop_scope drain inside on_valkey_close runs +// the connect() promise rejection, so user code re-enters close() while the +// socket handler frames are still on the stack. With take_socket_ref() the +// second caller sees no outstanding ref and releases nothing. +test.concurrent("RedisClient survives a malformed RESP reply that closes the socket from on_data", async () => { const src = ` const CRLF = "\\r\\n"; - const blk = s => "$" + s.length + CRLF + s + CRLF; - const sockets = []; const server = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { - open(s) { s.data = { buf: "" }; sockets.push(s); }, - data(s, d) { - s.data.buf += d.toString("latin1"); - if (s.data.buf.includes("HELLO")) s.write("%1" + CRLF + blk("proto") + ":3" + CRLF); - else if (s.data.buf.includes(CRLF)) s.write("+OK" + CRLF); - s.data.buf = ""; - }, + open() {}, + data(s) { s.write("!garbage" + CRLF); }, close() {}, }, }); - const url = "redis://127.0.0.1:" + server.port; - for (let round = 0; round < ${isASAN ? 80 : 200}; round++) { - const c = new Bun.RedisClient(url, { autoReconnect: true, connectionTimeout: 2000 }); - c.onconnect = () => {}; c.onclose = () => {}; + for (let i = 0; i < 50; i++) { + const c = new Bun.RedisClient("redis://127.0.0.1:" + server.port, { + autoReconnect: false, + connectionTimeout: 5000, + }); + c.onclose = () => {}; try { await c.connect(); } catch {} - const s = sockets.pop(); - try { s?.terminate?.(); s?.end?.(); } catch {} - // Let the close reach the client so on_close takes the reconnect branch - // (is_manually_closed is still false at that point). - await new Promise(r => setImmediate(r)); - await new Promise(r => setImmediate(r)); - try { c.subscribe("ch" + round, () => {}).catch(() => {}); } catch {} + if (typeof c.connected !== "boolean") throw new Error("connected getter broken"); try { c.close(); } catch {} - // Read through the Box while the wrapper is still live; under ASAN this - // trips heap-use-after-free if the round over-released. - if (typeof c.connected !== "boolean") throw new Error("expected boolean"); - if (round % 8 === 0) Bun.gc(false); - await new Promise(r => setTimeout(r, 1)); + Bun.gc(true); + await new Promise(r => setImmediate(r)); } - // Wrappers from earlier rounds are now unreachable; collect so - // finalize() -> stop_timers runs (and would touch a freed Box if one - // was over-released without having crashed the .connected probe). - Bun.gc(true); - await new Promise(r => setTimeout(r, 50)); - Bun.gc(true); - while (sockets.length) try { sockets.pop()?.terminate?.(); } catch {} server.stop(true); console.log("OK"); process.exit(0); From ec40209b36d5c28791200d699bd34fc03d32baa5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 15:40:31 +0000 Subject: [PATCH 5/7] redis: trim doc comments to fit the 3-line limit --- src/runtime/valkey_jsc/js_valkey.rs | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/src/runtime/valkey_jsc/js_valkey.rs b/src/runtime/valkey_jsc/js_valkey.rs index 28b1092ba7a5..d2691258fafd 100644 --- a/src/runtime/valkey_jsc/js_valkey.rs +++ b/src/runtime/valkey_jsc/js_valkey.rs @@ -359,10 +359,8 @@ pub struct JSValkeyClient { pub timer: RefCountedTimer, pub reconnect_timer: RefCountedTimer, - /// Keep-alive refs handed to open sockets by [`connect`](Self::connect). - /// Released by [`take_socket_ref`](Self::take_socket_ref). A counter (not - /// a bool) because the reconnect path can have more than one in-flight - /// `us_socket_t` with this client in its ext slot. + /// Socket keep-alive refs outstanding from [`connect`](Self::connect); + /// consumed by [`take_socket_ref`](Self::take_socket_ref). socket_refs: Cell, pub ref_count: bun_ptr::RefCount, } @@ -506,13 +504,8 @@ impl JSValkeyClient { // SAFETY: `self` is live; the guard's own ref keeps it alive past Drop. unsafe { ScopedRef::new(self.as_ctx_ptr()) } } - /// Adopt one socket keep-alive ref recorded by [`connect`](Self::connect) - /// into the calling scope, or `None` when none is outstanding. The - /// close/fail paths can re-enter (`on_data` parse fail or - /// `on_connection_timeout` → `fail_with_js_value` → `close()` dispatches - /// `on_close` synchronously, and the `enter_event_loop_scope` drain inside - /// `on_valkey_close` runs JS that can close again), so a second caller - /// sees 0 here and releases nothing. + /// Adopt one socket keep-alive ref from [`connect`](Self::connect), or + /// `None` when the re-entrant close/fail path has already taken it. #[inline] fn take_socket_ref(&self) -> Option> { match self.socket_refs.get().checked_sub(1) { From b60158602e63393b65d84e7b9b504ea2ea3ee6de Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 16:01:02 +0000 Subject: [PATCH 6/7] test: reword malformed-RESP comment to not claim a repro it does not have --- test/js/valkey/valkey-gc.test.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/test/js/valkey/valkey-gc.test.ts b/test/js/valkey/valkey-gc.test.ts index 911e36247464..b90031305b3c 100644 --- a/test/js/valkey/valkey-gc.test.ts +++ b/test/js/valkey/valkey-gc.test.ts @@ -181,13 +181,11 @@ test.concurrent("RedisClient survives subscribe() + close() against a server tha expect(exitCode).toBe(0); }); -// A malformed reply drives on_data -> parse fail -> fail_with_js_value -> -// close(), which dispatches SocketHandler::on_close synchronously. Its -// on_valkey_close() previously adopted the socket keep-alive ref -// unconditionally; the enter_event_loop_scope drain inside on_valkey_close runs -// the connect() promise rejection, so user code re-enters close() while the -// socket handler frames are still on the stack. With take_socket_ref() the -// second caller sees no outstanding ref and releases nothing. +// Drives on_data -> parse fail -> fail_with_js_value -> close() -> synchronous +// on_close -> on_valkey_close, with the connect() rejection drained while the +// socket-handler frames are still on the stack. Path coverage for +// take_socket_ref(); the fuzzer interleaving that over-releases here is not +// reproduced deterministically. test.concurrent("RedisClient survives a malformed RESP reply that closes the socket from on_data", async () => { const src = ` const CRLF = "\\r\\n"; From efea2cca50c6cece4a1cbe2d2b6820a7508d77e4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 29 Jul 2026 23:06:48 +0000 Subject: [PATCH 7/7] ci: retrigger