Repository navigation
Conversation
WalkthroughAdds a reconnect-status guard and socket-closed assertion in the Valkey client, plus a concurrent integration test that exercises explicit ChangesValkey reconnect race fix
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 3:11 AM PT - Jul 11th, 2026
❌ @robobun, your commit e7f52e6 has 2 failures in
🧪 To try this PR locally: bunx bun-pr 32803That installs a local version of the PR into your bun-32803 --bun |
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
|
#18895 is a different bug, so I'm not adding the auto-close line. That issue is about connection attempts that fail (connection refused or an unresolvable host): the This PR is about the opposite situation: a connection attempt that succeeds while a stale reconnect timer starts a second one, which orphans the in-flight socket. It does not make #18895's promises settle, so it should not close it. |
There was a problem hiding this comment.
LGTM — the guard is strictly narrowing (reconnect only from Disconnected) and the debug_assert is release-inert.
Extended reasoning...
Overview
This PR touches src/runtime/valkey_jsc/js_valkey.rs (two hunks: a 3-line early-return guard in reconnect() and a debug_assert! in connect()) and adds a regression test to test/js/valkey/valkey-gc.test.ts. The fix prevents a stale auto-reconnect timer from calling connect() while another connection is already in Connecting/Connected, which previously overwrote client.socket and orphaned a live fd whose late callbacks then drove a client with a weak/collected JS wrapper.
Security risks
None. This is internal connection-lifecycle bookkeeping for Bun.RedisClient; no auth, crypto, parsing, or user-input handling is touched. The change strictly reduces the set of states from which a new socket can be opened.
Level of scrutiny
Low-to-moderate. The source change is tiny and conservative:
- The new guard only adds an early return — it cannot cause
reconnect()to do more than before, only less. The one other caller ofreconnect()(do_connect()) already gates onStatus::Disconnectedbefore calling it, so the new check is a no-op there and only constrains the timer path. debug_assert!(socket.is_closed())is release-inert; I verifiedis_closed()returnstruefor theDetachedvariant (src/uws_sys/socket.rs:272-276), which is what every transition intoDisconnectedand the initial state assign, so the assert holds on existing call paths.
Other factors
- No CODEOWNERS entry for valkey.
- The PR description is unusually thorough (full repro trace, cause analysis, before/after test output on both debug and release builds).
- The regression test has two independent oracles (accepted-connection count, clean exit) so it does not depend on debug assertions, and I traced the with-fix path to confirm the count is deterministically 3 regardless of whether the stale timer fires before or after the explicit
connect(). - The test is somewhat timing-orchestrated (
sleepSync(60), 50ms reconnect-delay assumption), but the primary oracle (no 4th accept) holds under any interleaving once the guard is in place, so flakiness risk is low. - Bug hunter found nothing; no prior human review comments to address.
2dd220a to
71214e2
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/js/valkey/valkey-gc.test.ts`:
- Line 230: The timing-sensitive subprocess fixture in valkey-gc.test.ts is
being run under test.concurrent, which can skew reconnect-timer deadlines and
leave child processes unmanaged. Change the affected test group to run
sequentially using the existing test wrapper in this file, and keep the
child-process/reconnect logic under a non-concurrent test declaration. Use the
surrounding test case setup in valkey-gc.test.ts to locate the concurrent block
and make only this fixture sequential.
- Around line 212-229: The comment block in the valkey GC test is too long and
includes bug-history details that should not live in source comments. Trim the
preamble in the test fixture to only the durable invariant and keep the rest of
the failure narrative in the PR description; update the comment near the
scripted RESP3 server/reconnect scenario so it stays within the 3-line limit and
still identifies the reconnect/orphaned socket edge case.
- Around line 316-324: The reconnect flow in the valkey GC test is not being
asserted, because c.connect() is fire-and-forget and its rejection is ignored.
Update the test around the explicit reconnect on c so it awaits the reconnect
promise and fails the test if it rejects, then only close c after the awaited
reconnect completes. Use the c.connect() call and the surrounding HELLO-reply
release logic to locate the spot, and make the test assert that reconnect really
succeeds before checking the accepted socket count.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: abe01aa8-63d0-4631-a6f5-cfb5b7320113
📒 Files selected for processing (2)
src/runtime/valkey_jsc/js_valkey.rstest/js/valkey/valkey-gc.test.ts
|
CI on the rebased head (e7f52e6, build 71876, final): 284 jobs passed. The new regression test in The two red lanes are both darwin-14-aarch64 shards failing on runner environment issues unrelated to this diff:
Their first attempt also expired waiting on an agent before the retries above ran. One yellow: Review feedback addressed, all threads resolved. The diff is green; the red lanes need a runner fix or a skip, not a code change. I'm not pushing retrigger commits. |
|
Independently reproduced the mechanism in this PR on stock 1.4.0 with a scripted RESP3 server: after While reproducing it I hit an adjacent bug this diff does not cover: Verified both are independent: with the |
An auto-reconnect timer armed by a connection loss stays armed when an explicit connect() starts a new connection. When it fired, reconnect() called connect() again, which overwrote `client.socket` without closing the in-flight socket. The orphaned socket's late open/data callbacks then drove a client that had already moved on: they reset `is_authenticated`, sent another HELLO, and handled its reply while the client was Disconnected and its JS wrapper only weakly referenced, failing `debug_assert!(self.this_value.get().is_strong())` in on_valkey_connect and, in release builds, running against a wrapper the GC is free to collect. reconnect() now only proceeds from Status::Disconnected, and connect() debug-asserts that the previous socket is closed or detached.
Run it sequentially, trim the preamble to the invariant, and await the explicit connect() so a rejection fails the test instead of being swallowed.
a2c7855 to
e7f52e6
Compare
|
Status note: this still reproduces. On the current release (1.4.0) a client whose first dial was refused, then given an explicit The same sequence came up again in review of #37993 (noted there as pre-existing and out of that PR's scope), so this is worth landing. The branch now conflicts with main: #37971 removed repro script used (in-process net server, no redis needed)import net from "node:net";
import { RedisClient } from "bun";
const port: number = await new Promise(resolve => {
const l = net.createServer();
l.listen(0, "127.0.0.1", () => {
const p = (l.address() as net.AddressInfo).port;
l.close(() => resolve(p));
});
});
const client = new RedisClient(`redis://127.0.0.1:${port}`, { maxRetries: 5 });
// first dial via a command so no connect() promise is cached; refused -> 50ms retry armed
const cmd = client.get("x").catch(() => {});
await new Promise(r => setTimeout(r, 15));
let accepted = 0;
const sockets: net.Socket[] = [];
const server = net.createServer(sock => {
accepted++;
sockets.push(sock);
sock.on("data", () => setTimeout(() => sock.write("+OK\r\n"), 200));
});
await new Promise<void>(r => server.listen(port, "127.0.0.1", () => r()));
await Promise.all([client.connect(), new Promise(r => setTimeout(r, 400))]);
console.log({ accepted }); // { accepted: 2 } on 1.4.0, expected 1
client.close();
for (const s of sockets) s.destroy();
server.close();
await cmd; |
|
Superseded by #39546, which disarms the retry timer before any dial and gates reconnect() on the client having no socket, so one client can only ever have one. Your held-HELLO scenario is kept there as a test. |
Stacks on #39543 (the socket keep-alive ref moves to the close event's entry); this PR is based on that branch and its diff shows only the timer changes. The problem The RedisClient has two timers. `reconnect_timer` schedules the next retry. `timer` bounds one attempt (connect timeout) or one idle period. Only the retry path and the finalizer disarmed them. Three things went wrong because of that. 1. `close()` during a retry delay did nothing. The client was `Disconnected`, so `close()` returned early. The retry timer stayed armed. It dialled a closed client, fired `onconnect` on it, and kept the process alive for the whole retry schedule. 2. `connect()` during a retry delay dialled at once but left the retry timer armed. The timer fired into the in-flight dial and opened a second socket on the same client. Both sockets then drove one state machine. 3. The connect timer of an attempt that ended in a terminal close stayed armed. A dial that fails outright arms no timer of its own, so the stale one fired "Connection timeout" into the next attempt. What changed `close()` during a retry delay cancels the retry. It disarms `reconnect_timer`, marks the close as manual, and runs the close path once: the cached `connect()` promise rejects, `onclose` runs once, and the event loop ref is released. Nothing dials again. This path takes no ref of its own: the timer's ref goes back with the disarm, and there was never a socket ref to release, which is the accounting #39543 established for a dial that never got a socket. `reconnect()` disarms `reconnect_timer` before it dials. It only dials from `Disconnected` with no socket. A `connect()` that takes over a pending retry is now the one dial. A retry timer that fires while a dial is in flight does nothing. `on_valkey_close` disarms `timer`, as `on_valkey_reconnect` already did. No attempt's timer outlives it. `connect()` asserts in debug builds that the client has no live socket, and the deferred close of a dial that failed outright asserts the same instead of returning early on a live socket, since no dial can start during its hold. Visible changes `close()` between retries is honoured. `onclose` receives `ERR_REDIS_CONNECTION_CLOSED` with the message "Connection closed". A `connect()` promise still pending from before the retries rejects with the same error. Queued commands reject with it too. The process can exit. `connect()` between retries: if a `connect()` promise is still pending (the client has not connected yet and its first dial is being retried), it is returned and the retry schedule is left alone. Otherwise the pending retry is cancelled, the client dials at once, and retry counting starts over from zero, so a client one retry from giving up gets a full `maxRetries` budget again. Before, the dial happened too, but on top of the retry, which then opened a second socket. Tests New tests in `test/js/valkey/reliability/connection-failures.test.ts`: - `close()` during the retry delay fires `onclose` once, rejects the queued command, and the stub sees no second connection. - A spawned process that calls `close()` during the retry delay exits with one `onclose` and no second `onconnect`. - `close()` after the retries are exhausted does not report a second close. - `connect()` during the retry delay opens one connection while HELLO is held past the retry deadline, then resolves. - `connect()` during the retry delay starts the retry budget over: with `maxRetries: 2` and a stub that drops every later connection, the client is dropped three more times before it gives up. - `close()` during that in-flight dial reports the close once. - The connect timer of an attempt ended by `close()` does not fire into a next attempt whose dial fails outright in the same loop iteration. The stale deadline is measured from before the first `connect()`, and the test asserts the callback ran before it, so a slow machine fails the test rather than passing it vacuously. New case in the ASAN block of `test/js/valkey/valkey-gc.test.ts`: a worker calls `close()` during the retry delay and is then terminated; LSan reports nothing, which pins the ref accounting above. The first, second, fourth and seventh fail on main. The third, fifth and sixth pin behaviour that already held (the fifth passes without the fix too: the stub drops each connection within the 50ms retry delay, so the stale retry timer is re-armed before it can fire). The valkey-gc case fails with the `cancel_reconnect` of the first commit, which took a ref of its own: LSan reports the `Box<JSValkeyClient>`. This supersedes #33306 and #32803. Their tests are kept in adapted form here. Not in this PR The failure reason reported to `connect()` and `onclose` (#39542). The `Connection` state enum. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/valkey/reliability/connection-failures.test.ts test/js/valkey/valkey-gc.test.ts <!-- robobun:evidence:end --> --------- Co-authored-by: robobun <117481402+robobun@users.noreply.github.com>
### Problem - GitHub closes only the first reference after a keyword, so "Fixes #1, #2" leaves #2 open. "Supersedes #3" links nothing, and no reference closes a pull request. - The last 1000 merged PRs name 274 such references. PR #32292 is open although merged #36135 says "Supersedes #32292". ### Fix - `.github/workflows/close-linked-issues.yml` runs on `pull_request_target` `closed` (a merge into the default branch of `oven-sh/bun`) and on `workflow_dispatch` with a PR number and `dry_run`. Everything is inline in one `actions/github-script` step, with no checkout. - Each open target is closed as `completed` with the comment "Closed as completed by #N." or "Superseded by #N.". Closed or missing targets, the PR itself and other repositories are skipped. - The parser has no regex. A closing keyword (close, fix, resolve, supersede, replace, any tense) must lead the reference, alone or in a list. A negated, hedged or noun keyword, or one whose subject is another reference, does not count ("may fix", "the rm fix #1", "#100 supersedes #1"). - Verified: `test/internal/close-linked-issues.test.ts` (333 cases) runs the YAML's script against fake `github`, `context` and `core`. Also the 1000-PR parse (Notes). ### Background - GitHub's own keywords are close, fix and resolve (-s, -ed). Each links one reference, and only a merge into the default branch closes it. - `pull_request_target` runs in the base repository with a write token, also for fork PRs. That is safe only when no PR-controlled code runs. Here the description is the only PR input, parsed as text. <details><summary>Notes</summary> A close through the API does not create the "closed this in #N" timeline link that GitHub makes for its own closes. The comment carries the PR number instead. How the parser was calibrated. I pulled the descriptions of the last 1000 merged PRs and listed every line with a keyword next to a reference. The keyword families, list shapes and reference forms in the script are the ones that appear there. A reference is `#1`, `owner/repo#1`, an issue or pull URL (bare or in `<>`), or a markdown link. Four lines would have been wrong with a plain keyword-then-reference rule, and each led to a rule: - "the open `rm` fix #37521" (#38379): "fix" as a noun. Base forms (fix, close, resolve, supersede, replace) count only at the start of a sentence or line, or after will, should, does, and, and a few similar words. "to" is not one of them ("unable to fix #1", "how to fix #1"). - "May also fix #12318 / #10046, untested" (#38242): hedged. may, might, could, would, partially and the negations disqualify the keyword, looking past adverbs such as "also". - "Supersedes the closed #26040" (#36289) and "a comment on closed #35351" (#35365): "closed" as an adjective. A determiner or preposition before the keyword disqualifies it. - "supersedes #33130's optimisation" (#35843): a number that continues into a word is not a reference. Review added: a reference before the keyword is the subject ("#100 supersedes #1"), also through "which" or "that" ("reverts #100, which fixed #1") and across a removed span ("#100 ~~also~~ fixes #1"). A hedge two words before the keyword disqualifies it ("hopefully this fixes #1", "could this fix #1?"). A clause that starts with if, when, once, until or unless is not a statement. The tokenizer keeps a line break as a token so that "Fixes #1" on one line and "Fixes #2" on the next stay two statements. Code spans, fences, indented code, blockquotes, HTML comments and strikethrough are skipped. The block stripping follows CommonMark for fences (also inside a blockquote), indented code, blockquotes with lazy continuation, setext underlines and HTML comments, and GFM for `~~` flanking. Result over the 1000 descriptions: 274 distinct references in 135 PRs. I checked the current state of all of them through GraphQL. All but one are closed (202 issues completed, 5 duplicates, 66 pull requests). The one open target is PR #32292, superseded by merged #36135. No open target is a false positive. Every review change kept this result. Patterns that are deliberately not handled: a bulleted list under "Closes:" on its own line (not seen in the sample), references separated by whitespace only ("#1 #2"), "fix for #1", and GH-1 style references. A `?` after the list is not treated as a question. The block parser tracks no list containers, so a second paragraph of a list item indented by four spaces is read as an indented code block and skipped. A removed span or inline comment reads as one word, so "Fixes <!-- n --> #1" finds nothing. The test suite covers: the phrases above, stopping at the right place in real sentences, CRLF descriptions, URLs with fragments or a `/files` suffix, case-insensitive `Owner/Repo#1`, the fake API where a lookup, an update or a comment fails, the `dry_run` input, an invalid `pr_number` input, an unmerged PR, a PR merged into a non-default branch, the merge event body against a later edit, and a description with no closing statement. The first revision of this PR checked out the repository and ran `scripts/close-linked-issues.ts`. Jarred asked for no checkout and no script file, so the script moved inline into the workflow and the test now reads it out of the YAML. </details> <!-- robobun:evidence:begin --> --- **[stamp-90s]** gate passed · iteration 9 · 2 files touched <details><summary>passes on PR (with fix)</summary> ```console Test-only change. Debug/ASAN (expected pass): $ bun bd test 'test/internal/close-linked-issues.test.ts' $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/internal/close-linked-issues.test.ts bun test v1.4.1 (4448a2e) test/internal/close-linked-issues.test.ts: (pass) finds "Fixes #39852" [176.21ms] (pass) finds "Closes #31772. Fixes #31771." [22.28ms] (pass) finds "- Fixes #39930" [12.28ms] (pass) finds "Fixes: #30429" [10.46ms] (pass) finds "FIXES #1" [7.86ms] (pass) finds "(Fixes #1)" [8.97ms] (pass) finds "**Fixes #1**" [10.20ms] (pass) finds "__Fixes #1__" [9.83ms] (pass) finds "_Fixes #1_" [11.25ms] (pass) finds "Fixes **#1**" [9.72ms] (pass) finds "**Fixes** #1" [7.13ms] (pass) finds "**Fixes:** #1" [8.11ms] (pass) finds "Fixes #1 and **#2**" [11.47ms] (pass) finds "Fixes **#1**, **#2**" [9.13ms] (pass) finds "## Why (fixes #13771, closes #30543)" [16.08ms] (pass) finds "Closes #11418" [19.46ms] (pass) finds "Resolves #1. Resolved #2. Resolve #3." [12.09ms] (pass) finds "Fixes #34055, #30327, #24394, #20816, #32403, #11898, #10056." [17.11ms] (pass) finds "Fixes #18192 and #31675 as a consequence" [10.45ms] (pass) finds "Fixes #1, #2, and #3" [10.96ms] (pass) finds "Fixes #1 & #2" [7.63ms] (pass) finds "Closes #33280, Closes #32864 and Closes #29696 (the timer in #32949 is orthogonal)" [20.29ms] (pass) finds "Closes #33182 and #32947 on top of current main (which already has #36304 for catalogs)." [16.12ms] (pass) finds "Fixes #1,\n#2" [7.76ms] (pass) finds "Fixes #1, #2,\nand #3" [9.27ms] (pass) finds "Fixes #1\nand #2" [8.57ms] (pass) finds "Fixes #1\n& #2" [6.80ms] (pass) finds "Fixes #1 and\n#2" [7.31ms] (pass) finds "Supersedes #39908 (same change, moved from a fork branch)" [13.21ms] (pass) finds "Supersedes #38778 and #38391. Carries the entry point arm of #35053." [14.43ms] (pass) finds "Supersedes #39193 and keeps its three tests." [11.48ms] (pass) finds "This supersedes #33306 and #32803. Their tests are kept here." [13.73ms] (pass) finds "- This replaces #33793. Its ... (truncated) Exit: 0 ``` </details> <details><summary>diff hotspot</summary> ``` .github/workflows/close-linked-issues.yml | 950 ++++++++++++++++++++++++++++++ test/internal/close-linked-issues.test.ts | 598 +++++++++++++++++++ 2 files changed, 1548 insertions(+) ``` </details> **gate history** · 29 passed · 0 rejected · iteration 9 <details><summary>evidence per changed file</summary> ``` file reads edits tests .github/workflows/close-linked-issues.yml 6 12 0 test/internal/close-linked-issues.test.ts 3 11 0 ``` </details> <!-- robobun:evidence:end -->
What does this PR do?
Fixes a
Bun.RedisClientconnection-lifecycle bug where a stale auto-reconnect timer starts a second, competing connection and orphans the one already in flight. On debug/assertion builds the orphan's late traffic trips:On release builds the same sequence silently runs socket callbacks against a client whose JS wrapper is only weakly referenced (it is also an fd leak: the orphaned socket is never closed).
Reproduction (scripted in-process RESP3 server; full version is the test):
connect().do_connect()starts a new socket; the timer stays armed.is_reconnectingis still set when the timer fires.on_reconnect_timer()->reconnect()->connect()creates another socket and assigns it toclient.socket, orphaning the in-flight one.on_openresetsis_authenticatedand writes a HELLO, but never setsstatus = Connectingor re-upgrades the wrapper ref, so by the time the reply arrives the client is Disconnected with a weak (or collected) wrapper, andon_valkey_connectasserts.Cause
reconnect()only checkedis_reconnecting. A reconnect timer armed by a connection loss is not cancelled by a later explicitconnect(), andconnect()assignsclient.socketwithout closing the previous one, so the timer firing while a connection is in flight (Status::Connecting, or evenConnected) clobbers a live socket.is_reconnectingis only cleared by a successful HELLO, so a withheld or slow HELLO response is enough to keep the stale timer armed and active.Fix
reconnect()returns unlessstatus == Disconnected.Disconnectedis the only state with no live socket attached (every transition into it detaches or closes the socket first), soconnect()can no longer overwrite a live one.connect()nowdebug_assert!s that the previous socket is closed or detached, so any future path that violates the one-live-socket invariant fails loudly in debug and fuzz builds instead of orphaning a socket.Not included here: making the
SocketHandlercallbacks ignore events from a socket other thanclient.socket(defense in depth for the same class). With the invariant restored at the source that condition is unreachable, and filteringon_close/on_connect_errorinteracts with the per-socket keep-alive refcount, so it deserves its own change if we want it.Related but distinct open PRs in this area: #32768 and #32779 fix synchronously-failing
connect()paths; this one is about a successful competing connect.Verification
test/js/valkey/valkey-gc.test.tsgets a spawned fixture with a scripted in-process RESP3 server. It has two oracles, so it does not depend on debug assertions:[review] gate passed · iteration 4 · 2 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 0 rejected · iteration 4
evidence per changed file