Repository navigation
fix: handle rejection from the db-restoring select on reconnectOnError - #2229
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
PavelPashov
left a comment
There was a problem hiding this comment.
Thanks for tracking this down! This is the last bare this.select(...) in lib/, and the .catch((err) => this.silentEmit("error", err)) matches the other restore paths, so the fix looks good to merge once the test is slimmed down (see inline comment).
| import { expect } from "chai"; | ||
| import MockServer from "../helpers/mock_server"; | ||
| import Redis from "../../lib/Redis"; | ||
|
|
||
| const READONLY_ERROR = "READONLY You can't write against a read only replica."; | ||
| const INVALID_DB_INDEX = "ERR DB index is out of range"; | ||
|
|
||
| // The restoring `SELECT` is protocol-independent, but the connection setup | ||
| // around it is not: under RESP3 the client sends HELLO before anything else. | ||
| const PROTOCOLS = [3, 2] as const; | ||
|
|
||
| PROTOCOLS.forEach((protocol, index) => { | ||
| describe(`reconnectOnError db restoration (RESP${protocol})`, () => { | ||
| const port = 17930 + index; | ||
| let savedListeners: any[] = []; | ||
| let unhandled: string[] = []; | ||
|
|
||
| beforeEach(() => { | ||
| unhandled = []; | ||
| // test/helpers/global.ts installs an unhandledRejection listener that | ||
| // throws; record rejections here instead and restore it afterwards. | ||
| savedListeners = process.listeners("unhandledRejection"); | ||
| process.removeAllListeners("unhandledRejection"); | ||
| process.on("unhandledRejection", (reason) => { | ||
| unhandled.push(String(reason)); | ||
| }); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| process.removeAllListeners("unhandledRejection"); | ||
| for (const listener of savedListeners) { | ||
| process.on("unhandledRejection", listener); | ||
| } | ||
| }); | ||
|
|
||
| it("surfaces a failing db-restoring SELECT as an error event", async () => { | ||
| // `get` fails on the first connection only, so reconnectOnError fires | ||
| // once; `select` fails from the reconnect onwards. | ||
| let connections = 0; | ||
| const server = new MockServer(port, (argv) => { | ||
| const name = String(argv[0]).toLowerCase(); | ||
| if (name === "info") { | ||
| return "# Server\r\nredis_version:7.0.0\r\n"; | ||
| } | ||
| if (name === "get" && connections < 2) { | ||
| return new Error(READONLY_ERROR); | ||
| } | ||
| if (name === "select" && connections >= 2) { | ||
| return new Error(INVALID_DB_INDEX); | ||
| } | ||
| return "OK"; | ||
| }); | ||
| server.on("connect", () => connections++); | ||
|
|
||
| const redis = new Redis({ | ||
| port, | ||
| protocol, | ||
| lazyConnect: true, | ||
| retryStrategy: () => 40, | ||
| // 2 = reconnect and resend, the branch that restores the command's db. | ||
| reconnectOnError: (err: Error) => | ||
| err.message.startsWith("READONLY") ? 2 : false, | ||
| }); | ||
| const errors: string[] = []; | ||
| redis.on("error", (err: Error) => errors.push(err.message)); | ||
| await redis.connect(); | ||
|
|
||
| // `select(2)` is sent before the `get` reply arrives, so the failed | ||
| // `get` (issued against db 0) needs its db restored before the resend. | ||
| await Promise.all([ | ||
| redis.get("foo").catch(() => {}), | ||
| redis.select(2).catch(() => {}), | ||
| ]); | ||
| await new Promise((resolve) => setTimeout(resolve, 500)); | ||
|
|
||
| redis.disconnect(); | ||
| await server.disconnectPromise(); | ||
|
|
||
| expect(unhandled).to.eql([]); | ||
| expect(errors).to.include(INVALID_DB_INDEX); | ||
| }); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Could we replace this file with a single case in test/unit/redis.ts that calls handleReconnection directly? The behavior doesn't depend on the protocol or a real socket, and test/helpers/global.ts already fails the run on unhandled rejections, so we don't need the mock server, the RESP2/RESP3 loop, the unhandledRejection swap, or the 500ms sleep.
it("emits an error when the db-restoring select fails on reconnectOnError", async () => {
const redis = new Redis({ lazyConnect: true, reconnectOnError: () => 2 });
const selectError = new Error("ERR DB index is out of range");
sinon.stub(redis, "disconnect");
sinon.stub(redis, "sendCommand");
sinon.stub(redis, "select").rejects(selectError);
const emitted = new Promise((resolve) => redis.once("error", resolve));
redis.handleReconnection(new Error("READONLY"), {
command: new Command("get", ["foo"]),
select: 2,
});
expect(await emitted).to.equal(selectError);
});There was a problem hiding this comment.
Done in bb87c3c: the file is gone and the case is in test/unit/redis.ts as you wrote it. It fails with the unhandled rejection on the old lib/Redis.ts and passes with the fix; the unit suite is 517 passing.
Replace the mock-server test with a single case in test/unit/redis.ts that calls handleReconnection directly, as suggested in review.
# [6.1.0](v6.0.0...v6.1.0) (2026-11-23) ### Bug Fixes * accept field arrays in hmget/hmgetBuffer types ([#2167](#2167)) ([c0cd66c](c0cd66c)) * align auto-pipeline callbacks for dynamic commands ([#2180](#2180)) ([7479cab](7479cab)) * apply the legacy reply shape to uppercase command names ([#2252](#2252)) ([8ecb423](8ecb423)) * clean up Sentinel failover subscriptions after quit ([#2198](#2198)) ([727edfa](727edfa)) * close the monitor connection when monitor() rejects ([#2247](#2247)) ([3cfe93f](3cfe93f)) * cluster stuck in close ([#2217](#2217)) ([a5fad1d](a5fad1d)) * **cluster:** bucket autopipelined MSET objects by their first key ([#2207](#2207)) ([b4e3237](b4e3237)) * **cluster:** do not reject pipeline commands for connecting nodes when offline queue is disabled ([#2277](#2277)) ([71516ca](71516ca)), closes [#2096](#2096) [Cluster#sendCommand](https://github.com/Cluster/issues/sendCommand) [#2276](#2276) * **cluster:** do not throw when auto-pipelining meets an uncached slot ([#2233](#2233)) ([e04bb49](e04bb49)) * **cluster:** don't fall back to a replica when no primary is left ([#2275](#2275)) ([c353e34](c353e34)) * **cluster:** emit sharded subscriber connect errors silently ([#2241](#2241)) ([00c9a22](00c9a22)) * **cluster:** end when quit() or disconnect() is called while reconnecting ([#2240](#2240)) ([8526785](8526785)) * **cluster:** hash autopipelined Buffer keys by their bytes ([#2208](#2208)) ([a8378bd](a8378bd)), closes [Command#getSlot](https://github.com/Command/issues/getSlot) * **cluster:** hash lone surrogates as the UTF-8 Node sends ([#2242](#2242)) ([cfa464d](cfa464d)) * **cluster:** keep forwarding sharded messages after reconnecting from end ([#2251](#2251)) ([326e987](326e987)) * **cluster:** map every slot when stringNumbers is enabled ([#2255](#2255)) ([8ce4115](8ce4115)) * **cluster:** match Buffer shard channels when unsubscribing ([#2203](#2203)) ([d997d01](d997d01)) * **cluster:** pass the retry delay to the reconnecting event ([#2291](#2291)) ([ed50383](ed50383)) * **cluster:** resend only the redirected command in a pipeline ([#2214](#2214)) ([46b3191](46b3191)), closes [#2075](#2075) [Pipeline#exec](https://github.com/Pipeline/issues/exec) [Cluster#sendCommand](https://github.com/Cluster/issues/sendCommand) [Pipeline#exec](https://github.com/Pipeline/issues/exec) [Cluster#sendCommand](https://github.com/Cluster/issues/sendCommand) [Pipeline#exec](https://github.com/Pipeline/issues/exec) * **cluster:** stay ended when nodes removed by disconnect() end late ([#2237](#2237)) ([61896e5](61896e5)), closes [#2217](#2217) * **cluster:** stop refreshing slots when disconnect() is called during a refresh ([#2249](#2249)) ([80501ed](80501ed)) * **cluster:** support zero-argument sunsubscribe with sharded subscribers ([#2137](#2137)) ([13ff050](13ff050)), closes [#2133](#2133) * **cluster:** vendor cluster-key-slot to fix empty hash tag slot bug ([#2172](#2172)) ([b479b76](b479b76)) * correct Sentinel retry ordering after node connection failures ([#2246](#2246)) ([a10e0fa](a10e0fa)) * decode integer replies up to MAX_SAFE_INTEGER exactly ([#2164](#2164)) ([28940b5](28940b5)) * decode RESP3 attribute replies instead of failing the connection ([#2213](#2213)) ([6a8cb3e](6a8cb3e)), closes [#decodeNestedType](https://github.com/redis/ioredis/issues/decodeNestedType) [#decodeMapAsObject](https://github.com/redis/ioredis/issues/decodeMapAsObject) [#decodeMapKey](https://github.com/redis/ioredis/issues/decodeMapKey) * decode RESP3 doubles with Number ([#2150](#2150)) ([6fb5a10](6fb5a10)) * end when quit() or disconnect() is called while reconnecting ([#2245](#2245)) ([81bc16a](81bc16a)) * handle rejection from the db-restoring select on reconnectOnError ([#2229](#2229)) ([1b744ca](1b744ca)) * handle rejections from auto-resubscribe and select on reconnect ([#2187](#2187)) ([de2fbdf](de2fbdf)) * inherit connectTimeout for cluster subscribers ([#2220](#2220)) ([db57c2d](db57c2d)) * keep String.prototype in fast mode after defining VerbatimString ([#2206](#2206)) ([90e1261](90e1261)) * keep subscriber mode while other channel kinds remain subscribed ([#2196](#2196)) ([eb97beb](eb97beb)) * keep the exec error out of its own previousErrors ([#2218](#2218)) ([2c602cf](2c602cf)) * keep the selected db for commands queued while reconnecting ([#2235](#2235)) ([9f90154](9f90154)) * preserve empty keys and match patterns in scan streams ([#2199](#2199)) ([b169c3a](b169c3a)) * redact credentials from the command attached to errors ([#2231](#2231)) ([a26f8de](a26f8de)), closes [#1713](#1713) * reject unfulfilled commands dropped on reconnect ([#2194](#2194)) ([d95d05a](d95d05a)), closes [#2193](#2193) * reset retry attempts when connect() is called after giving up ([#2204](#2204)) ([b597303](b597303)), closes [#1463](#1463) * reset the manual close state when connect() is called after end ([#2250](#2250)) ([7713c4b](7713c4b)) * resolve argument-less (p)unsubscribe once its own kind is empty ([#2238](#2238)) ([280812b](280812b)) * restore the db selected by a non-lowercase SELECT after reconnecting ([#2248](#2248)) ([400b774](400b774)) * **sentinel:** handle errors on failover detector connections ([#2257](#2257)) ([09bcda5](09bcda5)) * **sentinel:** retry unreachable sentinels in a loop instead of recursing ([#2270](#2270)) ([6bee8d2](6bee8d2)) * **types:** accept documented TLS profile options ([#2195](#2195)) ([56a7fb8](56a7fb8)), closes [#1626](#1626) * **types:** add event overloads to Cluster interface ([#2201](#2201)) ([3996eaf](3996eaf)), closes [#2191](#2191) * **types:** add smessage and smessageBuffer event overloads ([#2191](#2191)) ([ee48f4c](ee48f4c)), closes [#2190](#2190) * **types:** allow number for zrange stop argument ([#2163](#2163)) ([932f4c2](932f4c2)) ### Features * add BITRANGEINTARRAY command ([#2279](#2279)) ([b141399](b141399)) * add set member expiration commands ([#2261](#2261)) ([5efba6b](5efba6b)), closes [redis/redis#15938](redis/redis#15938) * bless commands ([#2209](#2209)) ([9181ee0](9181ee0)) * **cluster:** allow configuring node role for Pub/Sub subscriber ([#2176](#2176)) ([6b9130c](6b9130c)) * sharded subscriber health check ([#2268](#2268)) ([1b25ffb](1b25ffb)) * smart client handoffs ([#2165](#2165)) ([d8ae3cb](d8ae3cb)) * sorted set move commands ([#2288](#2288)) ([2f4f09d](2f4f09d))
|
🎉 This PR is included in version 6.1.0 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
Small, isolated bug fix with a focused test, submitted under the carve-out in
.github/CONTRIBUTING.md("Small, isolated bug fixes where the cause and solution are clear and a focused test demonstrates the fix"). Happy to open an issue first if you'd prefer that route.Summary
reconnectOnErrorreturns2,handleReconnectionreconnects and resends the failed command. If the command was issued against a different db, it first callsthis.select(item.select)to restore it.SELECTis rejected after the reconnect, the rejection is unhandled even when the client has anerrorlistener, which Node's default--unhandled-rejections=throwmode turns into an uncaught exception.readyHandlerinlib/redis/event_handler.ts(fix: handle rejections from auto-resubscribe and select on reconnect #2187) use.catch((err) => self.silentEmit("error", err)).Fix
The
this.select(item.select)call inhandleReconnectiongets the same.catch((err) => this.silentEmit("error", err)). The resend after it is unchanged. 3 insertions, 1 deletion inlib/Redis.ts.Test
test/unit/reconnectOnError.ts: one case under RESP3 and RESP2, built liketest/unit/resubscribe.tsfrom #2187 (MockServer, with the globalunhandledRejectionlistener swapped for a recorder).getfails withREADONLYon the first connection whileselect(2)is in flight, soreconnectOnErrorreturns2and the client restores theget's db before resending it; the mock rejectsSELECTfrom the second connection on.prettier --checkpasses on the new test file andlib/Redis.ts.eslintonlib/Redis.tsreports the same 18 warnings asmainand no errors.AI assistance: the bug was traced and the fix and test were drafted with AI tooling in my workflow; the test, prettier and eslint were executed as pasted above. I'm responsible for the change and will handle review feedback.
Note
Low Risk
Narrow reconnect error-handling change aligned with existing select().catch patterns; no auth or data-path behavior change beyond surfacing failures as error events.
Overview
When
reconnectOnErrorreturns2, the client reconnects and resends the failed command; if the command was on a non-default DB,handleReconnectionfirst callsthis.select(item.select)to restore it.That
SELECTwas invoked without handling rejection, so a failed restore could become an unhandled promise rejection even when the client has anerrorlistener. The PR adds the same.catch((err) => this.silentEmit("error", err))pattern already used in offline-queue replay.A unit test stubs a failing
selectduringhandleReconnectionand asserts the error is emitted on the client.Reviewed by Cursor Bugbot for commit bb87c3c. Bugbot is set up for automated code reviews on this repo. Configure here.