Skip to content

redis: fix abort and hangs after a synchronously failing reconnect - #32779

Closed
robobun wants to merge 4 commits into
mainfrom
farm/e75b0550/fix-redis-enqueue-unreachable
Closed

robobun wants to merge 4 commits into
mainfrom
farm/e75b0550/fix-redis-enqueue-unreachable

Conversation

@robobun

@robobun robobun commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes a process abort (and the hangs behind it) in Bun.RedisClient reachable through the public API with no fault injection.

panic: internal error: entered unreachable code
  ValkeyClient::enqueue   src/runtime/valkey_jsc/valkey.rs   (`_ => unreachable!()`)
  ValkeyClient::send      (offline-queue arm)

Reproduction (against a minimal in-process RESP server that answers +OK; the unix socket only makes the reconnect's connect(2) fail synchronously with ENOENT, socket(2) returning EMFILE under fd pressure reaches the same branch for TCP):

const sock = "/tmp/vk.sock";
let srv = Bun.listen({ unix: sock, socket: { data(s) { s.write("+OK\r\n"); } } });

const c = new Bun.RedisClient(`redis+unix://${sock}`);
await c.connect();
await c.set("k", "v");   // authenticated
c.close();
srv.stop(true);          // unlinks the socket

c.connect().catch(() => {});  // reconnect's connect(2) fails synchronously
await c.send("INFO", []);     // aborts the whole process

Fixes #18895

Cause

Three holes in the connection state machine stack up:

  1. ValkeyClient::on_close() only cleared flags.is_authenticated on its auto-reconnect branch. After a manual close() (or a server-side close with autoReconnect: false), a disconnected client still reported connection_ready() == true.
  2. do_connect() clears the sticky failed flag so an explicit connect() can recover (Bun Redis Multiple visits with 'Connection has failed' #29925). If that reconnect's connect() then fails synchronously, reconnect()'s error branch only fired the JS onclose callback: it never marked the client failed, never settled the cached connection promise, and ignored autoReconnect / maxRetries.
  3. enqueue() assumed connection_ready() implies Connecting | Connected and put _ => unreachable!() in the status match. With (1) and (2), the client reaches Status::Disconnected with connection_ready() true and failed false, and the next command that cannot be auto-pipelined (send("INFO"), or any command with enableAutoPipelining: false) lands on the unreachable!().

Writing the fix exposed two more in the same class (a terminal failure must settle the connection promise and release the event loop reference):

  1. After fail() the stale is_reconnecting flag kept update_poll_ref() holding the event loop open forever, so a process whose client exhausted maxRetries never exited.
  2. When connectionTimeout fires between reconnect attempts, the socket is already detached, so fail()'s close() is a no-op and no close callback ever reaches on_valkey_close(). The connect() 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() clears is_authenticated and is_selecting_db_internal unconditionally. A closed socket is never an authenticated session.
  • reconnect() routes a synchronous connect() failure through ValkeyClient::on_close(), the same state machine the asynchronous on_connect_error path already uses. That settles the pending connection promise (via on_valkey_close), rejects queued commands, and honors autoReconnect / maxRetries with backoff. connect() releases its own keep-alive ref on the failure path, and on_close() releases one, so the branch takes one ref to balance. JSValkeyClient::fail_with_js_value loses its only caller and is deleted.
  • enqueue() gates the direct-write fast path on status == Connected and 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-existing Status::Connecting arm, which would have written command bytes before the HELLO handshake if reached with a stale is_authenticated.)
  • ValkeyClient::fail_with_js_value() clears is_reconnecting when the client enters the terminal failed state.
  • on_connection_timeout() runs on_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 by autoReconnect / maxRetries, and connectionTimeout is 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: connectionPromise double-settle and a GC leak) also edits reconnect()'s synchronous-failure branch, so the two will conflict textually. They fix different bugs: #32768 does not touch on_close() or enqueue(), and this PR does not touch the stale promise slot in do_connect()'s needs_to_open_socket branch (#32768's item 1). This PR's reconnect() change is the on_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 balancing ref_() 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):

  • a non-pipelined command after the failed reconnect rejects with ERR_REDIS_CONNECTION_CLOSED instead of aborting (autoReconnect: false)
  • same with enableAutoPipelining: false
  • with autoReconnect on, the failed reconnect retries with backoff and the offline queue drains once it succeeds
  • the process exits after auto-reconnect exhausts maxRetries (previously hung forever)
  • connectionTimeout firing between reconnect attempts rejects the connect() 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 from reliability/recovery.test.ts (#29925) were re-verified against a local redis-server.

Reported by bun-sys-fuzz.

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.
@robobun

robobun commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:38 PM PT - Jun 26th, 2026

❌ @robobun, your commit 8d068cb has 1 failures in Build #65143 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 32779

That installs a local version of the PR into your bun-32779 executable, so you can run:

bun-32779 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 2 issues this PR may fix:

  1. redis.connect behave very wrong when failed to connect (see description) #18895 - PR fixes connection promise settlement on synchronous connect failure and stale is_reconnecting holding the event loop open, directly addressing the reported hang when connecting to unreachable hosts
  2. bun test leaving open handles when using ioredis and global afterAll hook does not run #5996 - PR clears is_reconnecting in fail(), preventing update_poll_ref() from holding the event loop open indefinitely after connection close, matching the "open handles preventing process exit" symptom

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #18895
Fixes #5996

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@robobun, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6ff06986-3498-490e-9151-9ee7da148969

📥 Commits

Reviewing files that changed from the base of the PR and between 7516e1d and 8d068cb.

📒 Files selected for processing (2)
  • src/runtime/valkey_jsc/js_valkey.rs
  • test/js/valkey/valkey-reconnect-failure.test.ts

Walkthrough

Valkey 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.

Changes

Valkey reconnect failure handling

Layer / File(s) Summary
Close and reconnect state
src/runtime/valkey_jsc/valkey.rs, src/runtime/valkey_jsc/js_valkey.rs
fail_with_js_value clears is_reconnecting; on_close clears authentication and DB-selection flags before reconnect scheduling; JSValkeyClient::reconnect now calls on_close() on connect() failure and the JS onClose helper is removed.
Direct write gating
src/runtime/valkey_jsc/valkey.rs
enqueue now requires a connected socket and an empty queue for direct writes, and direct-write failures reject the promise with an out-of-memory JS error instead of branching on status.
Reconnect failure tests
test/js/valkey/valkey-reconnect-failure.test.ts
The new test file starts a Unix-socket RESP server, forces synchronous reconnect failure, checks recovery and queue draining, and verifies maxRetries exhaustion exits without hanging.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: aborts and hangs after a synchronous reconnect failure.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description covers the change, cause, fix, and verification, and includes the required content despite not matching the template headings exactly.

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. redis: clear the cached connectionPromise when connect() fails synchronously #32768 - Both fix the synchronous connect() failure path in reconnect() within js_valkey.rs; redis: clear the cached connectionPromise when connect() fails synchronously #32768 fixes the stale connectionPromise slot while this PR fixes the state machine routing, and the two will conflict textually

🤖 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.
@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

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 connectionTimeout fires between reconnect attempts the socket is already detached, so fail()'s close() is a no-op and no close callback ever reaches on_valkey_close(). The connect() promise stays pending and update_poll_ref keeps the event loop referenced. Every scenario from that issue, tested on 942c22237 (current canary) versus this branch:

scenario 942c22237 this branch
localhost:<closed port>, connectionTimeout: 5000 rejects at 31s, then the process hangs forever rejects, process exits
localhost:<closed port>, connectionTimeout: 30 rejects at 51ms, then the process hangs forever rejects at 34ms, process exits
unresolvable host, connectionTimeout: 1000 process exits at ~80ms, promise never settles rejects at ~1.8s, process exits
unresolvable host, connectionTimeout: 5000 process exits at ~80ms, promise never settles rejects at ~31s, process exits

One caveat for whoever reviews the Fixes line: with default options the time to rejection is still governed by autoReconnect / maxRetries (20 retries with backoff, about 31s), because connectionTimeout is re-armed on every reconnect attempt and so bounds each attempt rather than the whole connect(). That is pre-existing and out of scope here; what this PR fixes is that the promise always settles and the process always exits. If that caveat makes Fixes too strong, happy to drop it to a plain reference.

#5996: no. That issue is about ioredis, a userland client over node:net. It never touches Bun.RedisClient or src/runtime/valkey_jsc/, so nothing in this PR can affect it. Not adding it.

On the duplicate-PR flag: #32768 is not a duplicate (different primary bug, connectionPromise double-settle versus this abort), but the two do conflict textually in reconnect(). That is already covered in the "Overlap with #32768" section of the description and in a comment I left on #32768.

@robobun

robobun commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

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.

  • node-tls-connect.test.ts (the live bun.sh certificate losing its OCSP URI) was the only real red test lane on the earlier builds. It was fixed on main by test: stop asserting an OCSP URI on the live bun.sh certificate #32789; Buildkite builds the PR head rather than a merge commit, so the branch had to pick the fix up itself. Merged origin/main in 8d068cb (no conflicts, no valkey changes on main since the base) and that lane is now green.
  • :darwin: 26 aarch64 - test-bun, parallel shard 0: never runs a test.
    Error: buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun'.
    Refusing to continue with a partial download (would silently fall back to the wrong binary).
    
    The darwin aarch64 - build-bun artifact it is fetching built successfully, and shard 1 of the same lane downloads it fine. The same job failed identically on all three builds of this PR (65107, 65134, 65143) and on unrelated builds (for example 65138), so it is a degraded macOS 26 agent pool. It needs a job retry from someone with Buildkite write access, or the pool to recover.
  • :darwin: 14 aarch64 - test-bun: the one test failure with an error-level annotation, test/js/web/websocket/autobahn.test.ts. It never reaches a WebSocket assertion; its Docker service cannot start on that agent:
    autobahn The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8)
    autobahn-1  | exec /opt/pypy/bin/wstest: exec format error
    
    That is an amd64-only bun-autobahn:local image on an arm64 Docker host. It also appears on unrelated builds (65130) and nothing in this PR can influence the architecture a Docker image was built for.
  • :windows: 2019 x64, :windows: 2019 x64-baseline, and :windows: 11 aarch64 test-bun shards report failed, but each one ran its full shard to completion with zero test failures (their logs contain no nonzero fail counts and no failed-test markers). They exit 2 because Bun's runner marks a job failed when a test needed a retry, and each of those lanes had unrelated flaky tests that passed on retry (update_interactive_install, bake/dev-and-prod hmr, serve sendfile abort, spawn-pipe-leak, node-http-connect, spawn.test.ts timeout). They are recorded in the warning-level "flaky" annotation, not as failures.
  • Every x64-musl, x64-musl-baseline, and aarch64-musl build, build-cpp, build-rust, and verify job on this build passed. There are no musl build failures on any build of this PR.

No failing or flaky job in any build of this PR touches src/runtime/valkey_jsc/ or test/js/valkey/. The two valkey-reconnect-failure.test.ts cases that run on Windows pass on every Windows shard that executed them, and all five pass on the ASAN lane. A whole-pipeline retrigger cannot change the two deterministic environment failures above (the macOS 26 artifact pool and the arm64 autobahn image), so I have not pushed one. This is ready for review as is.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ts failing on all platforms — almost certainly unrelated (this PR doesn't touch TLS or node:net), but worth a glance.
  • Clearing is_reconnecting in fail_with_js_value and routing sync connect failures through on_close() are behavior changes (now honors autoReconnect/maxRetries on 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.
@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

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: ValkeyClient::on_close() releases exactly one JSValkeyClient intrusive ref, through whichever branch it takes.

  • auto-reconnect branch -> on_valkey_reconnect() -> the explicit JSValkeyClient::deref at its end (its existing comment documents that it balances the keep-alive ref connect() took for the socket that just closed)
  • the three fail branches (manual close, autoReconnect: false, max retries) -> on_valkey_close() -> its _defer runs update_poll_ref() then JSValkeyClient::deref(p)

Every pre-existing caller (SocketHandler::on_close, on_connect_error, the semi-socket branch of ValkeyClient::close()) enters on_close() with that connect() keep-alive ref still outstanding, which is what gets released. The two new call sites have no such outstanding ref, so each takes exactly one self.ref_() immediately before the call that releases one:

  1. reconnect()'s synchronous failure branch: connect() already released its own ref on that path (errdefer_deref) before returning Err, so the branch takes one for on_close() to release.
  2. on_connection_timeout()'s already-detached branch: it calls on_valkey_close() directly (not via on_close()), whose defer releases one, so it takes one first.

Both directions of getting this wrong are covered:

  • An extra release drives the count to zero while reconnect()'s / on_connection_timeout()'s own deref_guard is still armed, which is a use-after-free on guard drop. The CI gate runs all five new tests under the ASAN debug build and none reports one.
  • A leaked ref surfaces as the event loop or the strong this_value root staying alive, both driven by update_poll_ref(). Four of the five tests assert the child process exits on its own (exitCode: 0, signalCode: null), which fails if either is left referenced. Deleting the is_reconnecting = false line reproduces exactly that hang.

Reviewing this also caught one redundancy: the self.update_poll_ref() after on_valkey_close() in the timeout path was a no-op because on_valkey_close()'s defer already runs it. Dropped in 49adf69.

On the other points: the overlap with #32768 is documented in the description and in a comment on that PR, and the node-tls-connect.test.ts failure is the live bun.sh certificate losing its OCSP URI, fixed on main by #32789, so this push should pick that up.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ts OCSP 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 an unreachable!() and tightens the direct-write gate to Status::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.

@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

The refcount invariant for the two new ref_() sites, and how both the UAF and leak directions are covered by the tests, is spelled out in #32779 (comment).

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 x64-musl, x64-musl-baseline, and aarch64-musl build, build-cpp, build-rust, and verify job passed, and the same is true of 65134 (49adf69) and 65107.

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 test-bun shards each ran their full file list with zero test failures and are only marked failed because unrelated tests flaked once and passed on retry.

Agreed on merge order with #32768 being a human call; the coordination note is on that PR.

@robobun

robobun commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@alii alii closed this Aug 13, 2026
alii added a commit that referenced this pull request Aug 18, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

redis.connect behave very wrong when failed to connect (see description)

2 participants