Skip to content

redis: cancel the armed auto-reconnect timer in close() - #33306

Closed
robobun wants to merge 4 commits into
mainfrom
farm/1eb15047/redis-close-during-reconnect
Closed

robobun wants to merge 4 commits into
mainfrom
farm/1eb15047/redis-close-during-reconnect

Conversation

@robobun

@robobun robobun commented Jul 3, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

RedisClient.close() is ignored while the client is between auto-reconnect attempts. The client reconnects moments later, client.connected flips back to true after 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):

const client = new RedisClient(`redis://127.0.0.1:${port}`, { autoReconnect: true });
await client.connect();

serverSocket.destroy();             // the client arms its 50ms reconnect timer
while (client.connected) await delay(1);

const queued = client.get("orphan"); // goes into the offline queue
client.close();

await delay(500);
client.connected;                    // true  -- the timer reconnected anyway
await queued;                        // never settles

Cause

js_disconnect returned early when status == Disconnected:

if self.client.get().status == valkey::Status::Disconnected {
    return Ok(JSValue::UNDEFINED);
}
self.client_mut().disconnect();

That is exactly the state a client is in between retries: the socket is gone, is_reconnecting is set, and reconnect_timer is armed. close() therefore set no flags and cancelled no timer, and on_reconnect_timer() reopened the connection. The only thing that used to settle the offline queue and a pending connect() promise was the socket's on_close, and there is no socket.

Fix

  • js_disconnect cancels the reconnect timer and always calls disconnect(); disconnect() already skips the socket close when there is nothing to close.
  • ValkeyClient::disconnect() clears is_reconnecting, so a retry already in flight stops retrying.
  • When a cancelled retry leaves no socket behind, js_disconnect runs the close path by hand: fail() rejects the queued commands, notify_close() (split out of on_valkey_close(), minus the deref that balances connect()'s socket keep-alive ref) rejects the pending connect() promise and invokes onclose, and update_poll_ref() drops the event-loop keepalive the retry was holding. The condition is the timer being ACTIVE and the status being Disconnected, which is exactly when disconnect() finds nothing to close. A client that exhausted its retries (no timer, on_valkey_close() already ran) and a client whose explicit connect() 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 explicit close(). Neither fixes the other.

Verification

test/js/valkey/reliability/connection-failures.test.ts gets two tests on a scripted in-process RESP3 server (no docker needed):

  • close() during an armed retry: the server accepts exactly one connection, connected stays false, the offline-queued command rejects with ERR_REDIS_CONNECTION_CLOSED, and onclose fires once.
  • close() after the retries are exhausted: onclose is not reported a second time.
  • close() during a reconnect attempt (explicit connect() under an armed timer, socket still connecting): onclose fires once and the pending connect() promise rejects.
before / after
# unfixed (src/ stashed), USE_SYSTEM_BUN=1 bun test .../connection-failures.test.ts
error: expect(received).toEqual(expected)
  [
    1,
+   2,
  ]
(fail) Valkey: close() during auto-reconnect > close() cancels the armed retry and settles the offline queue

# with the fix, bun bd test .../connection-failures.test.ts
(pass) Valkey: close() during auto-reconnect > close() cancels the armed retry and settles the offline queue
(pass) Valkey: close() during auto-reconnect > close() after the retries are exhausted does not report a second close

Also checked by hand against a real redis (bun bd, ASAN): basic commands, close() on a fresh client, close() then connect() recovery, onclose firing once, concurrent connect(), auto-reconnect after a server-side CLIENT KILL with the offline queue flushing, and pub/sub. All unchanged, process exits cleanly.

@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 33e77e3e-a374-472f-aad5-f941bd70db02

📥 Commits

Reviewing files that changed from the base of the PR and between 6a1b130 and 47a3fb5.

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

Walkthrough

This PR updates Valkey close and reconnect handling in the JS runtime, resets reconnect state on manual disconnect, and adds reliability tests for close() during auto-reconnect.

Changes

Valkey close/reconnect fix

Layer / File(s) Summary
Reconnect timer helper
src/runtime/valkey_jsc/js_valkey.rs
Adds stop_reconnect_timer() and routes stop_timers() and on_valkey_reconnect() through it.
Close notification helper
src/runtime/valkey_jsc/js_valkey.rs
Extracts notify_close() for connection-promise rejection and onclose invocation, and updates on_valkey_close to use it.
js_disconnect settles armed reconnects
src/runtime/valkey_jsc/js_valkey.rs
js_disconnect now stops the reconnect timer, disconnects, and when reconnect was armed, fails the client, notifies close, and updates the poll ref.
Disconnect flag reset
src/runtime/valkey_jsc/valkey.rs
ValkeyClient::disconnect clears flags.is_reconnecting and updates its doc comment.
Auto-reconnect close tests
test/js/valkey/reliability/connection-failures.test.ts
Adds a mock TCP server and tests covering close() during armed reconnect and after retries are exhausted.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: cancelling the armed auto-reconnect timer on close().
Description check ✅ Passed It covers the purpose, root cause, fix, and verification, though the verification section is labeled differently than the template.
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.

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

@github-actions github-actions Bot added the claude label Jul 3, 2026
@robobun

robobun commented Jul 3, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 2:59 PM PT - Jul 7th, 2026

❌ @robobun, your commit 5d299ca has 1 failures in Build #69994 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 33306

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

bun-33306 --bun

@robobun

robobun commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Reproduced on stock 1.4.0 with a scripted in-process RESP3 server: after the server drops the connection, close() leaves the 50ms reconnect timer armed, the client reopens the connection ~50ms later, client.connected is true again, and a command queued while offline never settles.

Fix and test: see the PR description. The test is in test/js/valkey/reliability/connection-failures.test.ts and needs no docker.

Adjacent but independent: #32803 stops a stale reconnect timer from clobbering an in-flight socket during an explicit connect(). Neither change fixes the other.

@github-actions

github-actions Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Found 2 issues this PR may fix:

  1. RedisClient.close() while subscribed keeps the process alive #33103 - close() while subscribed keeps the process alive; the reconnect timer not being cancelled is a plausible root cause for the event-loop reference keeping the process alive
  2. [CRITICAL] redis client response mismatch #27861 - redis client response mismatch after auto-reconnect; the PR's changes to reject queued commands and clear is_reconnecting on disconnect address the stale in-flight queue problem

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

Fixes #33103
Fixes #27861

🤖 Generated with Claude Code

@robobun

robobun commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Checked both suggestions; this PR fixes neither, so I'm not adding the Fixes lines.

#33103 (close() while subscribed keeps the process alive) still hangs with this branch:

$ timeout 15 ./build/debug/bun-debug repro.ts; echo "exit $?"
got: hello
closed both clients, process should exit now
exit 124

Its repro never disconnects, so no reconnect timer is ever armed and the update_poll_ref() call added here never runs. What holds the loop there is the subscription callback map, not the retry. #33104 is the change for it.

#27861 (response mismatch after auto-reconnect) is about in_flight not being drained on the auto-reconnect path of ValkeyClient::on_close(). That branch is untouched here: this PR only rejects in_flight/queue when close() cancels an armed retry, which is the path where the client is being torn down rather than reconnected. The reply-desynchronization family is #32858.

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1498d7b and 0911314.

📒 Files selected for processing (3)
  • src/runtime/valkey_jsc/js_valkey.rs
  • src/runtime/valkey_jsc/valkey.rs
  • test/js/valkey/reliability/connection-failures.test.ts

Comment thread src/runtime/valkey_jsc/js_valkey.rs Resolved
@robobun

robobun commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed f4aba21 for the retry_armed finding: it was a real regression introduced by this PR, not a theoretical one. Reproduced it on a scripted RESP3 server that only answers the first HELLO, so the explicit connect() sits in Connecting with the timer still armed:

connected=true
[client] reconnect timer armed
[client] conn#2 open, status should be Connecting
onclose fired 2x  (expect 1, bug = 2)

The fix gates the hand-run close path on the invariant the comment already claimed, a retry armed and no socket for disconnect() to close:

let retry_armed = self.reconnect_timer.get().state == Timer::State::ACTIVE
    && self.client.get().status == valkey::Status::Disconnected;

With a socket present, disconnect() closes it and the socket close path reports the close once, as it did before this PR.

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.

@robobun

robobun commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI status

The diff is green. The red lanes are infrastructure, not this change.

The new tests run and pass in CI. On build 68210, test/js/valkey/reliability/connection-failures.test.ts ran on a linux test-bun shard against a real Redis (docker-compose) and reported:

--- [3/239] test/js/valkey/reliability/connection-failures.test.ts
bun test v1.4.0-canary.1 (f4aba21cd)
Redis container ready via docker-compose on ports 32770:6379 and 32771:6380
15 pass
1 skip
0 fail
Ran 16 tests across 1 file. [11.06s]

The failures. Build 68210 finished 283/286 green, with three failures, none of them near src/runtime/valkey_jsc/:

lane failure
:darwin: 26 aarch64 buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun' — no tests ran
:darwin: 14 x64 terminal.test.ts → creates subprocess with terminal attached timed out after 90000ms
:ubuntu: 25.04 x64 v8-heap-snapshot.test.ts → main process killed by SIGKILL but no core file found (OOM)

I re-rolled once (47a3fb5, build 68214). The :darwin: 26 aarch64 shard failed identically, on the same agent, again before running a single 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).
  at getExecPathFromBuildKite (.../runner.node.mjs:2182:13)

Its own :darwin: aarch64 - build-bun step passed in both builds, so the artifact exists; the agent just cannot download it. That is an agent/S3 problem and re-running will not fix it.

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 bun-darwin-aarch64 and bun-linux-x64.

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

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.

@robobun

robobun commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

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 notify_close() omits the deref that on_valkey_close() does. connect() takes a +1 keep-alive ref for the socket it opens (the second self.ref_(), whose errdefer is disarmed on success). Exactly one of two places releases it:

  • on_valkey_close(), via the deref in its scopeguard, on the terminal branches of ValkeyClient::on_close();
  • on_valkey_reconnect(), via its trailing deref, on the auto-reconnect branch, which is the one branch that does not call on_valkey_close().

The retry_armed state is reached only through that auto-reconnect branch, so the socket's keep-alive ref is already gone. Calling on_valkey_close() there would over-deref. notify_close() is its JS-visible half (reject the cached connect() promise, invoke onclose) with no ref accounting of its own.

Refs taken and released inside js_disconnect.

self.ref_() + deref_guard(self) scoped, balanced. Keeps self alive across remove_timer's deref and the JS re-entry in notify_close().
stop_reconnect_timer() → remove_timer() one deref, balancing the keep-alive ref_() that add_timer() took when it armed the timer. Cancelling the timer is exactly when that ref should go.

Net zero, and the count never reaches 0 mid-call because of the guard.

The poll_ref. has_activity includes flags.is_reconnecting (js_valkey.rs:1801), so while the retry is armed the event loop stays referenced. disconnect() clears is_reconnecting, and the update_poll_ref() that follows drops the keepalive so the process can exit. Without it, cancelling the timer would strand the ref and hang. It sits inside the retry_armed branch only because every other path reaches SocketHandler::on_close, which calls update_poll_ref() itself.

Why the gate is timer ACTIVE && status == Disconnected. disconnect() closes a socket only when status is Connected or Connecting, so Disconnected is precisely "disconnect() will find nothing to close". When there is a socket, its close path runs fail() + on_valkey_close() on its own, and running it a second time is what produced the double onclose in the first cut. fail_with_js_value() early-returns on flags.failed and notify_close() clears the promise slot to JSValue::ZERO before rejecting, so those two are idempotent; onclose is not, which is why the gate carries the weight.


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 :darwin: 26 aarch64 artifact-download timeout described above. The new tests passed on both builds:

--- [3/239] test/js/valkey/reliability/connection-failures.test.ts
bun test v1.4.0-canary.1 (47a3fb52b)
Redis container ready via docker-compose on ports 32770:6379 and 32771:6380
15 pass
1 skip
0 fail
Ran 16 tests across 1 file. [11.32s]

@robobun

robobun commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Correcting my earlier count, which I posted while build 68214 was still in flight. It finished at 284 passed, 2 failed, not one:

lane failure also on 68210?
:darwin: 26 aarch64 buildkite-agent artifact download timed out after 120s — zero tests ran yes, identical
:darwin: 14 x64 terminal.test.ts → creates subprocess with terminal attached timed out after 90000ms yes, identical

Both reproduced across two builds on the same two lanes, so neither is a transient that another retrigger would clear. The second is a Bun.spawn PTY test; this PR touches only src/runtime/valkey_jsc/.

The new tests passed on every lane that ran them, including the :darwin: 14 x64 lane that reports the terminal.test.ts failure:

# :darwin: 14 x64  (no docker, so the docker-gated tests skip and the three new mock-server tests run)
--- [3/1055] test/js/valkey/reliability/connection-failures.test.ts
3 pass
13 skip
0 fail
Ran 16 tests across 1 file. [1085.00ms]

# linux test-bun  (docker available, so everything runs)
--- [3/239] test/js/valkey/reliability/connection-failures.test.ts
15 pass
1 skip
0 fail
Ran 16 tests across 1 file. [11.32s]

No valkey or redis failure appears in any annotation on either build, and the binary-size annotation reports +0.0 KB on bun-darwin-aarch64 and bun-linux-x64.

That is the whole picture. I have used my one retrigger and will not push more. Over to a maintainer.

robobun added 4 commits July 7, 2026 17:03
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.
@robobun
robobun force-pushed the farm/1eb15047/redis-close-during-reconnect branch from 47a3fb5 to 5d299ca Compare July 7, 2026 17:09
@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main at 3f5d816 (5d299ca). Only conflict was test/js/valkey/reliability/connection-failures.test.ts, where #33072 added a Valkey: Auto-Reconnect In-Flight Commands describe block at the same spot this PR appends its Valkey: close() during auto-reconnect block. Kept both. The import net from "net" line this PR originally added is now redundant (main already has it), so the test diff dropped one line.

src/runtime/valkey_jsc/{js_valkey.rs,valkey.rs} auto-merged cleanly and cargo check -p bun_runtime is green.

Local results on the rebased build:

bun bd test test/js/valkey/reliability/connection-failures.test.ts
  4 pass  13 skip  0 fail

plus the same hand checks against a real Redis (ASAN): basic commands, close() on a fresh client, close()→connect() recovery, onclose firing once, auto-reconnect after CLIENT KILL with the offline queue flushing. All unchanged.

Dropped the empty ci: retrigger commit from the history while I was at it.

@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased build 69994 hits the same :darwin: 26 aarch64 - test-bun agent failure:

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

darwin-aarch64-build-bun itself passed (the artifact exists), so zero tests ran on that shard. This is the third consecutive build of this PR (68210, 68214, 69994) to die there on agent darwin-aarch64-26-5-1-1.

It is not specific to this PR. The last 20 finished PR builds on the pipeline show that lane as failed or canceled on every unrelated branch I checked (builds 69981, 69982, 69984, 69988, 69989, across s3/websocket/css/eventemitter changes). The lane is not part of main-branch builds, so it only blocks PRs.

The only annotation on 69994 so far is the flaky category (update_interactive_install.test.ts and hot.test.ts on Windows, retried to green). No valkey or redis failure anywhere.

My one retrigger is spent and would not help against a fleet-wide agent problem. This is ready for a maintainer.

@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Build 69994 near-final (280 passed, 4 scheduled, 2 failed). Same story as before plus two new data points, none of them this diff:

lane failure
:darwin: 26 aarch64 buildkite-agent artifact download timed out after 120s on agent darwin-aarch64-26-5-1-1, zero tests ran. Fourth consecutive build of this PR, and the lane is failed/cancelled on every recent PR build (see my earlier comment)
:windows: 2019 x64-baseline napi.test.ts → napi > napi_wrap > has the right lifetime (4 retries). N-API only; this diff does not touch src/napi/
ubuntu 25.04 aarch64 (flaky, retried green) docker failed to build the redis_unified container (failed to prepare extraction snapshot); the pre-existing docker-gated tests in describe.skipIf(!isEnabled)("Valkey: Connection Failures", ...) timed out waiting for it; the retry built the container and passed

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:

--- [3/595] test/js/valkey/reliability/connection-failures.test.ts
bun test v1.4.0-canary.1 (5d299cabf)
Redis is not enabled, skipping tests
4 pass
13 skip
0 fail
Ran 17 tests across 1 file. [1287.00ms]

Nothing for me to fix here. Ready for a maintainer.

@robobun

robobun commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator Author

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 close() during the armed retry. On current main the retry window for that client is the same state this PR targets (on_connect_error sets status = Disconnected after on_close() has armed the timer, so retry_armed as written here matches it), and without the fix the retry still dials, the pending connect() promise resolves and connected flips to true after the user closed the client:

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 connect() resolved, then accepted after close(): 1 connected: true. Expected: connect() rejects, onclose fires once, the late server accepts nothing.

Notes for the rebase (the branch conflicts with main right now):

  • js_disconnect on main now holds self.ref_scope() and early-returns on NeverConnected | Disconnected (the NeverConnected arm came in with valkey: fold is_authenticated and needs_to_open_socket into Status #37971). A client that is genuinely NeverConnected has no timer and no socket, so dropping the early return is still fine for it: disconnect() only sets is_manually_closed, which the next connect() resets.
  • The timers are RefCountedTimers now (redis: encapsulate EventLoopTimer keep-alive refs in RefCountedTimer #34760): stop_timers() is two .disarm(self) calls and remove_timer is gone, so stop_reconnect_timer() collapses to self.reconnect_timer.disarm(self). on_valkey_close() now releases the socket keep-alive via ScopedRef::adopt at the top, so notify_close() is everything after that adopt.
  • The three tests here all start from an established connection or from exhausted retries. Worth adding the refused-first-dial case above to the new describe block (pending connect() rejects with ERR_REDIS_CONNECTION_CLOSED, onclose fires exactly once, a server started on the same port afterwards sees no connection), since it is the path the second report hit.

@alii

alii commented Aug 18, 2026

Copy link
Copy Markdown
Member

Superseded by #39546, which cancels the retry timer from close() and runs the close path once. Your scenarios are kept there as tests.

@alii alii closed this Aug 18, 2026
alii added a commit that referenced this pull request Aug 18, 2026
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>
Jarred-Sumner pushed a commit that referenced this pull request Aug 22, 2026
### 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 -->
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.

2 participants