diff --git a/src/runtime/valkey_jsc/valkey.rs b/src/runtime/valkey_jsc/valkey.rs index 68ab3d8cbd8b..a7c864cf1255 100644 --- a/src/runtime/valkey_jsc/valkey.rs +++ b/src/runtime/valkey_jsc/valkey.rs @@ -659,48 +659,41 @@ impl ValkeyClient { self.write_buffer.clear_and_free(); // If manually closing, don't attempt to reconnect - if self.flags.is_manually_closed { + let reason: &[u8] = if self.flags.is_manually_closed { debug!("skip reconnecting since the connection is manually closed"); - self.fail(b"Connection closed", RedisError::ConnectionClosed)?; - self.on_valkey_close()?; - return Ok(()); - } - - // If auto reconnect is disabled, just fail - if !self.flags.enable_auto_reconnect { + b"Connection closed" + } else if !self.flags.enable_auto_reconnect { debug!("skip reconnecting since auto reconnect is disabled"); - self.fail(b"Connection closed", RedisError::ConnectionClosed)?; - self.on_valkey_close()?; - return Ok(()); - } - - // Calculate reconnection delay with exponential backoff - self.retry_attempts += 1; - let delay_ms = self.get_reconnect_delay(); + b"Connection closed" + } else { + // Calculate reconnection delay with exponential backoff + self.retry_attempts += 1; + let delay_ms = self.get_reconnect_delay(); + + if delay_ms != 0 && self.retry_attempts <= self.max_retries { + debug!( + "reconnect in {}ms (attempt {}/{})", + delay_ms, self.retry_attempts, self.max_retries + ); + + self.flags.is_reconnecting = true; + self.flags.is_selecting_db_internal = false; + + let rejected = self + .reject_in_flight_commands(b"Connection closed", RedisError::ConnectionClosed); + // Whatever `rejected` is: arms the retry and releases the socket's ref. + self.on_valkey_reconnect(); + return rejected; + } - if delay_ms == 0 || self.retry_attempts > self.max_retries { debug!("Max retries reached or retry strategy returned 0, giving up reconnection"); - self.fail( - b"Max reconnection attempts reached", - RedisError::ConnectionClosed, - )?; - self.on_valkey_close()?; - return Ok(()); - } - - debug!( - "reconnect in {}ms (attempt {}/{})", - delay_ms, self.retry_attempts, self.max_retries - ); - - self.flags.is_reconnecting = true; - self.flags.is_selecting_db_internal = false; - - self.reject_in_flight_commands(b"Connection closed", RedisError::ConnectionClosed)?; + b"Max reconnection attempts reached" + }; - // Signal reconnect timer should be started - self.on_valkey_reconnect(); - Ok(()) + let failed = self.fail(reason, RedisError::ConnectionClosed); + // Whatever `failed` is: runs `onclose` and releases the socket's ref (see `close()`). + let closed = self.on_valkey_close(); + failed.and(closed) } pub(crate) fn send_next_command(&mut self) { diff --git a/test/js/valkey/valkey-gc.test.ts b/test/js/valkey/valkey-gc.test.ts index 4e57b472cae0..50c3bb4ad14c 100644 --- a/test/js/valkey/valkey-gc.test.ts +++ b/test/js/valkey/valkey-gc.test.ts @@ -1,6 +1,7 @@ -import { expect, test } from "bun:test"; +import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isASAN } from "harness"; import net from "node:net"; +import { join } from "node:path"; // Fuzzer found a heap-use-after-free: connect()'s tls_ctx_failed branch // called on_valkey_close() before the socket keep-alive ref was taken, so @@ -42,6 +43,85 @@ test.concurrent("RedisClient survives a failed custom-TLS context without freein expect(exitCode).toBe(0); }); +// The socket's close event (ValkeyClient::on_close) rejects the commands the +// connection still owed replies for, then releases the ref the socket held on +// the client and settles connect()/onclose or arms the retry. Rejecting a +// promise fails once the VM's termination is pending, which is the state a +// terminated worker's teardown closes its sockets in, and on_close() used to +// return at that point, so every RedisClient terminated with commands in flight +// leaked its Box. One case per branch of on_close(): retry +// scheduled, autoReconnect off, retries exhausted. LSan sees the box only when +// the worker's VM has been torn down, hence the worker; the parent's own VM is +// torn down too (BUN_DESTRUCT_VM_ON_EXIT) so its server socket is not reported. +describe.skipIf(!isASAN)("worker.terminate() with commands in flight does not leak the RedisClient", () => { + async function terminateWorkerWithCommandsInFlight(options: object) { + const src = ` + const { Worker } = require("node:worker_threads"); + const HELLO = "%1\\r\\n$5\\r\\nproto\\r\\n:3\\r\\n"; + // Answers HELLO, then never replies: every command sent stays in flight. + // Resolves once the commands have reached the server, so they are in the + // client's in-flight queue (not merely queued) when the worker is stopped. + const { promise: commandsInFlight, resolve: onCommands } = Promise.withResolvers(); + const server = Bun.listen({ + hostname: "127.0.0.1", + port: 0, + socket: { + open(s) { s.data = { buf: "", hello: false }; }, + data(s, chunk) { + s.data.buf += chunk.toString("latin1"); + if (!s.data.hello && s.data.buf.includes("HELLO")) { s.data.hello = true; s.write(HELLO); } + if (s.data.buf.includes("INCR")) onCommands(); + }, + close() {}, + error() {}, + }, + }); + // The client is created from a macrotask on purpose: allocations made + // while the worker's module body is still on the stack match the + // module-evaluation entries of leaksan.supp, and a leaked client would + // then go unreported. + const worker = new Worker( + \`const { workerData } = require("node:worker_threads"); + setImmediate(() => { + const client = new Bun.RedisClient(workerData.url, workerData.options); + globalThis.client = client; + client.connect().then(() => { + for (let i = 0; i < 4; i++) client.incr("k").catch(() => {}); + }); + });\`, + { eval: true, workerData: { url: "redis://127.0.0.1:" + server.port, options: ${JSON.stringify(options)} } }, + ); + worker.on("error", (err) => { console.error(err); process.exit(2); }); + worker.on("exit", (code) => { console.error("worker exited on its own with " + code); process.exit(3); }); + await commandsInFlight; + worker.removeAllListeners("exit"); + console.log("terminated", await worker.terminate()); + server.stop(true); + `; + + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", src], + env: { + ...bunEnv, + BUN_DESTRUCT_VM_ON_EXIT: "1", + ASAN_OPTIONS: [bunEnv.ASAN_OPTIONS, "detect_leaks=1"].filter(Boolean).join(":"), + LSAN_OPTIONS: `print_suppressions=0:suppressions=${join(import.meta.dirname, "../../leaksan.supp")}`, + }, + stdout: "pipe", + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ stdout, stderr, exitCode }).toEqual({ stdout: "terminated 1\n", stderr: "", exitCode: 0 }); + } + + // Symbolizing a leak report takes LSan several seconds on a debug binary. + const timeout = 60_000; + test.concurrent("retry scheduled", () => terminateWorkerWithCommandsInFlight({}), timeout); + test.concurrent("autoReconnect off", () => terminateWorkerWithCommandsInFlight({ autoReconnect: false }), timeout); + test.concurrent("retries exhausted", () => terminateWorkerWithCommandsInFlight({ maxRetries: 0 }), timeout); +}); + // Fuzzer found a heap-use-after-free that survived the ScopedRef refactor: // on_connection_timeout's unconditional `ScopedRef::adopt` released a ref the // timer no longer held, so the ScopedRef drop at scope end brought the