Repository navigation
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughThis PR updates Valkey close and reconnect handling in the JS runtime, resets reconnect state on manual disconnect, and adds reliability tests for ChangesValkey close/reconnect fix
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 2:59 PM PT - Jul 7th, 2026
❌ @robobun, your commit 5d299ca has 1 failures in
🧪 To try this PR locally: bunx bun-pr 33306That installs a local version of the PR into your bun-33306 --bun |
|
Reproduced on stock 1.4.0 with a scripted in-process RESP3 server: after the server drops the connection, Fix and test: see the PR description. The test is in Adjacent but independent: #32803 stops a stale reconnect timer from clobbering an in-flight socket during an explicit |
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
|
Checked both suggestions; this PR fixes neither, so I'm not adding the #33103 ( Its repro never disconnects, so no reconnect timer is ever armed and the #27861 (response mismatch after auto-reconnect) is about |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/reliability/connection-failures.test.ts`:
- Around line 438-441: The test in connection-failures.test.ts uses a fixed
delay followed by a single assertion in the client.close() / closes check, which
should be replaced with bounded polling. Update the analogous assertion near the
closes counter to use the existing until() helper pattern already used earlier
in this file, so the test repeatedly checks for the expected state within a
timeout instead of sleeping once and checking. Keep the change localized to the
close-flow test logic and reuse the existing closes variable and until() helper.
- Around line 389-421: The test in connection-failures.test.ts leaves the
RedisClient open if an assertion fails before the explicit close(), which can
leak reconnect/keepalive work into later tests. Move client cleanup into a
guaranteed teardown path by registering client.close() in the existing
try/finally before any assertions, or use a resource-scoped cleanup pattern
alongside mockRedisServer() so RedisClient is always closed even on early
failures. Refer to RedisClient, client.close(), and the existing finally block
around the test setup.
🪄 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: 7bc72287-81f9-4453-90b7-1a1237837251
📒 Files selected for processing (3)
src/runtime/valkey_jsc/js_valkey.rssrc/runtime/valkey_jsc/valkey.rstest/js/valkey/reliability/connection-failures.test.ts
|
Pushed f4aba21 for the The fix gates the hand-run close path on the invariant the comment already claimed, a retry armed and no socket for let retry_armed = self.reconnect_timer.get().state == Timer::State::ACTIVE
&& self.client.get().status == valkey::Status::Disconnected;With a socket present, A third test covers it. It passes on main as well (main has no hand-run close path), so it is a guard against reintroducing the double report rather than a fail-before; test 1 is still the one that fails without the fix. |
CI statusThe diff is green. The red lanes are infrastructure, not this change. The new tests run and pass in CI. On build 68210, The failures. Build 68210 finished 283/286 green, with three failures, none of them near
I re-rolled once (47a3fb5, build 68214). The Its own No further retriggers from me. This needs a maintainer to merge or to kick the darwin-aarch64 agent. Zero valkey or redis failures appear in any annotation on either build, and the binary-size annotation reports +0.0 KB on |
There was a problem hiding this comment.
Both prior findings are addressed and I found nothing further on this revision, but this hand-replicates the socket close path inside js_disconnect with intrusive refcounting and poll-ref management — worth a maintainer's eyes on the valkey state machine before merge.
Extended reasoning...
Overview
This PR fixes RedisClient.close() being a no-op while the client sits between auto-reconnect attempts (timer armed, no socket, status == Disconnected). Changes span three files: js_valkey.rs (js_disconnect rewritten to cancel the reconnect timer and run the close path by hand when there is no socket to close; notify_close() extracted from on_valkey_close(); stop_reconnect_timer() helper), valkey.rs (disconnect() now clears is_reconnecting), and three new tests in connection-failures.test.ts using a scripted in-process RESP3 server.
Security risks
None. This is client-side connection lifecycle for Bun's Redis/Valkey client — no auth, crypto, permissions, or untrusted-input parsing is touched.
Level of scrutiny
Moderate-to-high. The native change is small (~50 lines) but sits in a subtle area: intrusive refcounting (ref_/deref), event-loop keepalive (poll_ref), and a state machine with several interacting flags (is_reconnecting, is_manually_closed, failed, timer state, status). The new js_disconnect path hand-replicates what the socket's on_close would normally do — fail() + notify_close() + update_poll_ref() — while deliberately omitting the deref that balances connect()'s socket keep-alive ref (correct, since on_valkey_reconnect already released it). I traced the refcount balance and it looks right, but the first revision of this PR had a real regression (double onclose when the timer was armed with a connecting socket present), which the author fixed in f4aba21 by adding the status == Disconnected gate. That the first cut had a reachable regression is evidence the state space here is non-trivial.
Other factors
Both of my prior inline findings and both CodeRabbit findings were addressed; all threads are resolved. The bug hunter found nothing on the current revision. Test coverage is good: three targeted tests covering the main fix, the retries-exhausted case (no double close), and the arm-and-connect case (guarding the regression fixed in f4aba21). The PR description is exceptionally thorough and the author correctly declined the auto-suggested Fixes # lines after checking they don't apply. No CODEOWNERS for this path. This is close to approvable, but connection-lifecycle code with manual refcount management in a runtime client is exactly where a maintainer who knows the valkey state machine should sign off rather than a bot.
|
Agreed that the hand-run close path is the part worth a careful read, so here is the ledger I worked from, to save the next reader deriving it. Why
The Refs taken and released inside
Net zero, and the count never reaches 0 mid-call because of the guard. The Why the gate is CI update. The re-roll (build 68214) cleared both flaky test failures from 68210. It now stands at 277 of 278 completed jobs green, with the single remaining failure being the |
|
Correcting my earlier count, which I posted while build 68214 was still in flight. It finished at 284 passed, 2 failed, not one:
Both reproduced across two builds on the same two lanes, so neither is a transient that another retrigger would clear. The second is a The new tests passed on every lane that ran them, including the No valkey or redis failure appears in any annotation on either build, and the binary-size annotation reports +0.0 KB on That is the whole picture. I have used my one retrigger and will not push more. Over to a maintainer. |
close() on a client that sits between auto-reconnect attempts was a no-op: js_disconnect returned early on Status::Disconnected and left the reconnect timer armed, so it fired moments later and reopened the connection. The client's `connected` flipped back to true after the user closed it. Cancel the timer, clear is_reconnecting, and run the close path by hand: with no socket to close, nothing else rejects the offline-queued commands or the pending connect() promise, and nothing drops the event-loop keepalive the retry was holding.
An explicit connect() while the retry timer is armed leaves the timer armed and the status at Connecting, so close() closed the socket (which reports the close) and then ran the close path a second time, invoking onclose twice. Gate the hand-run close path on the status the comment already claimed: a retry is armed AND there is no socket for disconnect() to close.
47a3fb5 to
5d299ca
Compare
|
Rebased onto main at 3f5d816 (5d299ca). Only conflict was
Local results on the rebased build: plus the same hand checks against a real Redis (ASAN): basic commands, Dropped the empty |
|
Rebased build 69994 hits the same
It is not specific to this PR. The last 20 finished PR builds on the pipeline show that lane as The only annotation on 69994 so far is the My one retrigger is spent and would not help against a fleet-wide agent problem. This is ready for a maintainer. |
|
Build 69994 near-final (280 passed, 4 scheduled, 2 failed). Same story as before plus two new data points, none of them this diff:
The new tests in this PR run on a scripted in-process RESP3 server, so they do not depend on the docker container. On the failing Windows lane itself: Nothing for me to fix here. Ready for a maintainer. |
|
A second report of this bug came in with a different starting state, noting it here so the rebase can pick it up. This PR's fix covers it; its tests do not exercise it yet. Scenario: a client that has never connected, whose first dial is refused, then import net from "net";
const probe = net.createServer();
await new Promise(r => probe.listen(0, "127.0.0.1", r));
const { port } = probe.address() as net.AddressInfo;
await new Promise(r => probe.close(r)); // first dial is refused
const client = new Bun.RedisClient(`redis://127.0.0.1:${port}`, { maxRetries: 5 });
client.onclose = err => console.log("onclose", err.code);
client.connect().then(() => console.log("connect() resolved"), e => console.log("connect() rejected", e.code));
await new Promise(r => setTimeout(r, 20)); // refusal processed, retry armed
client.close();
let accepted = 0;
const late = net.createServer(s => { accepted++; s.on("data", () => s.write("+OK\r\n")); });
await new Promise(r => late.listen(port, "127.0.0.1", r));
await new Promise(r => setTimeout(r, 300));
console.log("accepted after close():", accepted, "connected:", client.connected);
late.close(); client.close();Current main prints Notes for the rebase (the branch conflicts with main right now):
|
|
Superseded by #39546, which cancels the retry timer from close() and runs the close path once. Your scenarios are kept there as tests. |
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?
RedisClient.close()is ignored while the client is between auto-reconnect attempts. The client reconnects moments later,client.connectedflips back totrueafter the user closed it, and nothing ever settles the commands that were sitting in the offline queue.Reproduction (scripted in-process RESP3 server, same as the test):
Cause
js_disconnectreturned early whenstatus == Disconnected:That is exactly the state a client is in between retries: the socket is gone,
is_reconnectingis set, andreconnect_timeris armed.close()therefore set no flags and cancelled no timer, andon_reconnect_timer()reopened the connection. The only thing that used to settle the offline queue and a pendingconnect()promise was the socket'son_close, and there is no socket.Fix
js_disconnectcancels the reconnect timer and always callsdisconnect();disconnect()already skips the socket close when there is nothing to close.ValkeyClient::disconnect()clearsis_reconnecting, so a retry already in flight stops retrying.js_disconnectruns the close path by hand:fail()rejects the queued commands,notify_close()(split out ofon_valkey_close(), minus thederefthat balancesconnect()'s socket keep-alive ref) rejects the pendingconnect()promise and invokesonclose, andupdate_poll_ref()drops the event-loop keepalive the retry was holding. The condition is the timer beingACTIVEand the status beingDisconnected, which is exactly whendisconnect()finds nothing to close. A client that exhausted its retries (no timer,on_valkey_close()already ran) and a client whose explicitconnect()left a socket connecting under an armed timer both take the normal socket-close path and report the close once.This is adjacent to but distinct from #32803, which stops a stale reconnect timer from clobbering an in-flight socket. That one is about a timer firing during an explicit
connect(); this one is about a timer firing after an explicitclose(). Neither fixes the other.Verification
test/js/valkey/reliability/connection-failures.test.tsgets two tests on a scripted in-process RESP3 server (no docker needed):close()during an armed retry: the server accepts exactly one connection,connectedstaysfalse, the offline-queued command rejects withERR_REDIS_CONNECTION_CLOSED, andonclosefires once.close()after the retries are exhausted:oncloseis not reported a second time.close()during a reconnect attempt (explicitconnect()under an armed timer, socket still connecting):onclosefires once and the pendingconnect()promise rejects.before / after
Also checked by hand against a real redis (
bun bd, ASAN): basic commands,close()on a fresh client,close()thenconnect()recovery,onclosefiring once, concurrentconnect(), auto-reconnect after a server-sideCLIENT KILLwith the offline queue flushing, and pub/sub. All unchanged, process exits cleanly.