Repository navigation
Conversation
A RedisClient that had authenticated and was then closed kept
flags.is_authenticated set: ValkeyClient::on_close() only cleared it on
the auto-reconnect branch. If a later connect() failed synchronously
inside reconnect() (the unix socket path is gone, or socket() hits
EMFILE), the error branch fired the JS onclose callback but never marked
the client failed, never settled the cached connection promise, and left
status == Disconnected with connection_ready() still true. The next
non-pipelined command then fell into enqueue()'s '_ => unreachable!()'
arm and aborted the process:
panic: internal error: entered unreachable code
ValkeyClient::enqueue src/runtime/valkey_jsc/valkey.rs
ValkeyClient::send (offline-queue arm)
Changes:
- on_close(): clear is_authenticated / is_selecting_db_internal
unconditionally. A closed socket can never be an authenticated
session; every branch below must see connection_ready() == false.
- reconnect(): route a synchronous connect() failure through
ValkeyClient::on_close(), the same state machine the asynchronous
on_connect_error path uses. This settles the pending connection
promise, rejects queued commands, and honors autoReconnect /
maxRetries. connect() already released its own keep-alive ref on
this path, so take one to balance the release inside on_close().
The now-unused JSValkeyClient::fail_with_js_value is deleted.
- enqueue(): gate the direct-write fast path on status == Connected
instead of assuming connection_ready() implies it, and delete the
'_ => unreachable!()' arm. A wire client must never be able to abort
the process from state reachable through its public API.
- fail_with_js_value(): clear is_reconnecting when the client enters
the failed state. A stale is_reconnecting kept update_poll_ref()
holding the event loop open forever, so a process whose client
exhausted maxRetries never exited.
|
Updated 3:38 PM PT - Jun 26th, 2026
❌ @robobun, your commit 8d068cb has 1 failures in
🧪 To try this PR locally: bunx bun-pr 32779That installs a local version of the PR into your bun-32779 --bun |
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
|
Warning Review limit reached
More reviews will be available in 3 minutes and 6 seconds. Learn how PR review limits work. Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file). ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits. 🚦 How do rate limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughValkey reconnect failure handling now updates client close state instead of building a JS error on failed connect. Command enqueue routing was tightened, and new tests cover synchronous reconnect failure, recovery, and max-retry termination. ChangesValkey reconnect failure handling
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
…t attempts on_connection_timeout relied on fail()'s close() to reach on_valkey_close(), which is what rejects the cached connection promise and re-evaluates the event loop reference. Between reconnect attempts the socket is already detached, so close() is a no-op and no close callback ever arrives: the connect() promise stayed pending and update_poll_ref kept the event loop referenced forever. When the socket is already closed at the time the timeout fires, run on_valkey_close() directly (with a balancing ref for the release its defer performs) and re-evaluate the poll ref. Fixes #18895: connecting to a host with nothing listening left the process hung after the connect promise eventually rejected, and connecting to an unresolvable host exited with the connect promise never settled.
|
Checked both suggestions from the find-issues bot against a build of this branch rather than taking them at face value. #18895: yes. Verifying it also turned up a fifth hole in the same class, now fixed in e91aded: when
One caveat for whoever reviews the #5996: no. That issue is about On the duplicate-PR flag: #32768 is not a duplicate (different primary bug, |
|
CI status (final for build https://buildkite.com/bun/bun/builds/65143 at 8d068cb): the diff is green. Every red job is Buildkite infrastructure or an unrelated test, with specifics below so none of it has to be taken on faith.
No failing or flaky job in any build of this PR touches |
There was a problem hiding this comment.
I didn't find any bugs, but this reworks the Valkey connection state machine with manual intrusive-refcount balancing across reconnect()/on_close()/on_connection_timeout() and overlaps textually with #32768, so it's worth a human look.
Extended reasoning...
Overview
This PR fixes a process abort (unreachable!() in ValkeyClient::enqueue) and several related hangs in Bun.RedisClient by tightening the connection state machine across five interlocking holes. It touches src/runtime/valkey_jsc/js_valkey.rs (reconnect routing, connection-timeout handling, deletes fail_with_js_value), src/runtime/valkey_jsc/valkey.rs (on_close now unconditionally clears auth flags, fail_with_js_value clears is_reconnecting, enqueue gates direct-write on Status::Connected and removes the panic arm), and adds a new subprocess-based test file covering all five scenarios.
Security risks
None identified. The change is purely state-machine/lifecycle bookkeeping for the Redis client; no auth, crypto, input parsing, or permission boundaries are affected.
Level of scrutiny
This warrants careful human review. The fix is well-reasoned and thoroughly tested (five subprocess tests, ASAN-verified, existing suites re-run), but it threads manual intrusive-refcount balancing through new paths: reconnect() and on_connection_timeout() each take an extra self.ref_() specifically to balance the deref inside on_valkey_close() / on_close(). The PR description correctly explains why each is needed, but getting the count wrong in either direction means a leak or a use-after-free, and the invariants depend on which branch ValkeyClient::on_close() takes (the reconnect branch derefs via on_valkey_reconnect, the others via on_valkey_close). That's the kind of subtlety a maintainer who owns this state machine should sign off on.
Other factors
- The PR explicitly conflicts textually with open PR #32768 in
reconnect()'s sync-failure branch; the author has documented the overlap and left coordination notes, but a human should decide merge order. - CI shows
test/js/node/tls/node-tls-connect.test.tsfailing on all platforms — almost certainly unrelated (this PR doesn't touch TLS ornode:net), but worth a glance. - Clearing
is_reconnectinginfail_with_js_valueand routing sync connect failures throughon_close()are behavior changes (now honorsautoReconnect/maxRetrieson a path that previously didn't), which is the intended fix but still a semantic change to the reconnect policy.
…meout path on_valkey_close()'s defer already calls update_poll_ref() before it releases its ref, so the explicit call after it was a no-op.
|
Thanks. Spelling out the refcount invariant so it is quick to check against the source, since that is the part that deserves the scrutiny. The contract is:
Every pre-existing caller (
Both directions of getting this wrong are covered:
Reviewing this also caught one redundancy: the On the other points: the overlap with #32768 is documented in the description and in a comment on that PR, and the |
…is-enqueue-unreachable
There was a problem hiding this comment.
I didn't find any bugs, but the manual ref_()/on_close() balancing and the merge coordination with #32768 are the kind of thing a human should sign off on.
Extended reasoning...
Overview
This PR fixes a process abort and several event-loop hangs in Bun.RedisClient when a reconnect's connect() fails synchronously. It touches the connection state machine in src/runtime/valkey_jsc/valkey.rs (on_close, fail_with_js_value, enqueue) and js_valkey.rs (reconnect, on_connection_timeout), deletes the now-unused JSValkeyClient::fail_with_js_value, and adds a new subprocess-based test file with five scenarios.
Security risks
None identified. The change is confined to error/close-path handling in the Redis client; no auth, crypto, or untrusted-input parsing surface is touched.
Level of scrutiny
This warrants careful human review. The fix threads through intrusive refcounting (ref_() / deref() / deref_guard) and adds two new call sites that must each take exactly one balancing ref before invoking a path that releases one. The author explicitly spelled out the refcount invariant in a follow-up comment as "the part that deserves the scrutiny." Getting it wrong in either direction is a UAF (caught by ASAN, which passes) or an event-loop leak (caught by the process-exit assertions, which pass) — but the reasoning is subtle enough that a maintainer familiar with the JSValkeyClient lifecycle should confirm it.
Other factors
- There is a known textual conflict with #32768 in
reconnect()'s synchronous-failure branch; whichever lands second needs a rebase, and a human should decide merge order. - The latest CI run (49adf69) shows x64-musl build failures and the unrelated
node-tls-connect.test.tsOCSP failure; the author addressed the TLS one (fixed on main by #32789) but the musl build failures on the most recent push aren't discussed. - The
enqueue()change removes anunreachable!()and tightens the direct-write gate toStatus::Connected— defensible and well-reasoned, but it's a behavior change on a hot path that benefits from a second pair of eyes.
Given the manual refcount balancing in unsafe-adjacent code, the cross-PR coordination needed, and the author's own flag that this deserves scrutiny, deferring to human review.
|
The refcount invariant for the two new One factual correction so nobody goes hunting for it: there are no x64-musl build failures on any build of this PR. On the current build (65143 at 8d068cb) every The complete, verified breakdown of what is red on the current build and why none of it involves this diff is kept current in #32779 (comment). Short version: one macOS 26 aarch64 shard times out downloading the build artifact before running any test (same on unrelated builds, needs a Buildkite job retry), and the three Windows Agreed on merge order with #32768 being a human call; the coordination note is on that PR. |
|
Heads up for the rebase: #37971 folded is_authenticated and needs_to_open_socket into the Status enum, and #37993 now clears is_reconnecting in fail() and always closes the socket there, so those parts of this diff are covered. What is still unique to this PR, and still needed after #37993, is routing the synchronous connect() failure in reconnect() through on_close() (a unix socket path that disappears between connections still only fires onclose today and leaves the client stuck); a review on #37993 flagged that path and it was left to this PR. |
…cted before onclose runs (#39511) This is the second PR of a stack split out of #37993. The first is #39513. The third is #38281. This PR does not depend on #39513. #38281 is stacked on this PR. Part of #18895. The stack as a whole fixes it; #38281 closes it. The problem When a RedisClient failed, it did not close the socket. The client was then half alive: - `failed` was set, but the socket stayed open. - `client.connected` still read true. - The `connect()` promise never settled. - If `onclose` called `connect()`, the new connection could receive replies from the old one. - Code that was still unwinding from the failure could close the new connection. The rule this PR sets After a failure, four things are always true: - The socket is closed. - The client reads as disconnected. - The close path runs exactly once. It settles the `connect()` promise, runs `onclose`, applies the retry policy, and updates the event loop ref. - A `connect()` called from `onclose` starts a fresh attempt. Nothing from the old attempt touches it. What changed `fail()` now always closes the socket. It uses `CloseCode::Failure`. It also clears `is_reconnecting`. Why `Failure`: it is the only close code that runs the close callback before `close()` returns. `Normal` waits for the peer to answer close_notify. `FastShutdown` waits while the socket still holds unsent TLS data. A peer that stopped reading never lets either finish. On TCP, `Failure` sends RST instead of FIN. That is fine, because every command on the connection is already rejected. `disconnect()` and the finalizer use `FastShutdown`. So a user `close()` over rediss:// no longer waits for the peer. The close path reads `failed` to skip the retry policy. It does not use `is_manually_closed` for this. `duplicate()` copies `is_manually_closed`, and a duplicate of a failed client must still reconnect. The socket close handler and the connect error handler now set the status to disconnected before the close path runs, not after. Before, a `connect()` from `onclose` saw the old status and did not dial. The old code also overwrote the status of the new attempt. When a retry is scheduled, the connection timer of the failed attempt is disarmed. Before, it fired during the retry delay. With `is_reconnecting` now cleared by `fail()`, that stopped the retry and `connect()` never settled. A read is dropped as soon as the socket it came from is no longer the client's socket. So replies from a failed connection are not read as the next connection's HELLO reply. The TLS handshake path and the rejected HELLO path no longer close a second time after `fail()`. The second close hit the socket that `onclose` had just opened. Visible changes - `client.connected` is false inside `onclose` when the server drops an established connection. Before, it read true. - A failure the client detects after HELLO (idle timeout, protocol error) now closes the client and runs `onclose`. As before, it is not retried, even with `autoReconnect` on. Only closes from the peer go through the retry policy. This is one known difference from ioredis. An explicit `connect()` still works after it. - `close()` or a failure over rediss:// completes at once. Before, it waited for the peer's close_notify. Tests The tests are in the "Recovering After fail()" block of connection-failures.test.ts. They run against net and tls stubs and closed ports, over redis:// and rediss://. Two of them use a TLS peer that never answers close_notify, and one that has stopped reading. The rest of test/js/valkey that runs without a container is unchanged. Not in this PR - A test for the connection timeout during a TLS handshake. - Disarming the connection timer on the final close path, not only on the retry path. Both are follow-ups. Supersedes #33479. Covers the `is_reconnecting` part of #32779. #39015 (postgres and mysql) shares the CloseCode note.
What does this PR do?
Fixes a process abort (and the hangs behind it) in
Bun.RedisClientreachable through the public API with no fault injection.Reproduction (against a minimal in-process RESP server that answers
+OK; the unix socket only makes the reconnect'sconnect(2)fail synchronously withENOENT,socket(2)returningEMFILEunder fd pressure reaches the same branch for TCP):Fixes #18895
Cause
Three holes in the connection state machine stack up:
ValkeyClient::on_close()only clearedflags.is_authenticatedon its auto-reconnect branch. After a manualclose()(or a server-side close withautoReconnect: false), a disconnected client still reportedconnection_ready() == true.do_connect()clears the stickyfailedflag so an explicitconnect()can recover (Bun Redis Multiple visits with 'Connection has failed' #29925). If that reconnect'sconnect()then fails synchronously,reconnect()'s error branch only fired the JSonclosecallback: it never marked the client failed, never settled the cached connection promise, and ignoredautoReconnect/maxRetries.enqueue()assumedconnection_ready()impliesConnecting | Connectedand put_ => unreachable!()in the status match. With (1) and (2), the client reachesStatus::Disconnectedwithconnection_ready()true andfailedfalse, and the next command that cannot be auto-pipelined (send("INFO"), or any command withenableAutoPipelining: false) lands on theunreachable!().Writing the fix exposed two more in the same class (a terminal failure must settle the connection promise and release the event loop reference):
fail()the staleis_reconnectingflag keptupdate_poll_ref()holding the event loop open forever, so a process whose client exhaustedmaxRetriesnever exited.connectionTimeoutfires between reconnect attempts, the socket is already detached, sofail()'sclose()is a no-op and no close callback ever reacheson_valkey_close(). Theconnect()promise stays pending and the event loop stays referenced. This is redis.connect behave very wrong when failed to connect (see description) #18895: on current main,new Bun.RedisClient("redis://localhost:<closed port>", { connectionTimeout: 30 }).connect()rejects and then hangs the process forever, and an unresolvable host leaves the connect promise unsettled.Fix
on_close()clearsis_authenticatedandis_selecting_db_internalunconditionally. A closed socket is never an authenticated session.reconnect()routes a synchronousconnect()failure throughValkeyClient::on_close(), the same state machine the asynchronouson_connect_errorpath already uses. That settles the pending connection promise (viaon_valkey_close), rejects queued commands, and honorsautoReconnect/maxRetrieswith backoff.connect()releases its own keep-alive ref on the failure path, andon_close()releases one, so the branch takes one ref to balance.JSValkeyClient::fail_with_js_valueloses its only caller and is deleted.enqueue()gates the direct-write fast path onstatus == Connectedand drops the_ => unreachable!()arm entirely. A wire client must not be able to abort the process from state reachable through its public API. (Note: (1) alone already makes the panic unreachable; this removes the panic as a mechanism and also closes the pre-existingStatus::Connectingarm, which would have written command bytes before theHELLOhandshake if reached with a staleis_authenticated.)ValkeyClient::fail_with_js_value()clearsis_reconnectingwhen the client enters the terminal failed state.on_connection_timeout()runson_valkey_close()itself when the socket is already detached, so the connection promise settles and the poll ref is re-evaluated even though no socket close callback will arrive.With these, every scenario in #18895 now settles the
connect()promise and lets the process exit (details in the comment below). The total time to rejection with default options is still governed byautoReconnect/maxRetries, andconnectionTimeoutis still re-armed on every reconnect attempt (a per-attempt bound, not a total one); that is pre-existing and unchanged here.Overlap with #32768
#32768 (a different fuzz finding:
connectionPromisedouble-settle and a GC leak) also editsreconnect()'s synchronous-failure branch, so the two will conflict textually. They fix different bugs: #32768 does not touchon_close()orenqueue(), and this PR does not touch the stale promise slot indo_connect()'sneeds_to_open_socketbranch (#32768's item 1). This PR'sreconnect()change is theon_close()routing that #32768's description explicitly deferred ("Fixing that requires calling on_valkey_close() from a context that did not take the socket keep-alive ref"); the balancingref_()here is that refcount change. I left a comment on #32768 with the details so whichever lands second can rebase.Verification
test/js/valkey/valkey-reconnect-failure.test.ts(in-process mock RESP server, no real Redis needed; each case in its own subprocess because the bug aborts the whole process):ERR_REDIS_CONNECTION_CLOSEDinstead of aborting (autoReconnect: false)enableAutoPipelining: falseautoReconnecton, the failed reconnect retries with backoff and the offline queue drains once it succeedsmaxRetries(previously hung forever)connectionTimeoutfiring between reconnect attempts rejects theconnect()promise and the process exits (previously the promise stayed pending and the process hung)On
bun-v1.4.0-canary (942c22237)all five fail: the first three abort with the panic above, the last two hang. With the fix all five pass under the ASAN debug build. The existing mock-server valkey suites (valkey-gc,valkey-incremental-scan,valkey-tls-verify,reliability/resp-nesting-depth) still pass, and both scenarios fromreliability/recovery.test.ts(#29925) were re-verified against a localredis-server.Reported by bun-sys-fuzz.