Skip to content

feat(client): add experimental rejectInFlight to time out and abort sent commands - #3636

Merged
nkaradzhov merged 9 commits into
redis:masterfrom
nkaradzhov:003-command-timeout
Nov 23, 2026
Merged

nkaradzhov merged 9 commits into
redis:masterfrom
nkaradzhov:003-command-timeout

Conversation

@nkaradzhov

@nkaradzhov nkaradzhov commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

This pull request adds an experimental rejectInFlight command option. Today, timeout and abortSignal stop working once a command is written to the socket. If the server is slow to reply, the call waits for as long as the reply takes. With rejectInFlight: true, they keep working until the reply arrives.

When a sent command times out or is aborted, it rejects with the new TimeoutReadError or AbortReadError. These errors mean that the server may have run the command, so retry it only if it is idempotent. The connection stays open: the command keeps its place in the reply order, and its reply is dropped when it arrives. The option is off by default. Without it, nothing changes. It works per call or as a default in commandOptions for a client, cluster, sentinel or pool.

How it works:

  • Blocking commands (BLPOP, XREAD, WAIT, ...) keep only the write-queue timeout, because the server keeps blocking after a client-side timeout. abortSignal still applies to them. A pipeline that holds a blocking command does the same. MULTI does not, because commands inside MULTI don't block. The client finds blocking commands through the blocking flag in the command metadata, which is exported as isBlocking.
  • MULTI and pipelines keep one timer until their last reply. If it fires after part of the batch was written, every pending command rejects with the read error, and the rest of the batch is still written, so the connection is never left inside MULTI.
  • The maintenance timeout also relaxes the timers of sent commands. They then reject with CommandTimeoutReadDuringMaintenanceError.
  • In-flight timeouts use the deadline lists from perf(client): replace per-command AbortSignal timeouts with deadline lists #3618, so there is still no timer per command.
  • The multi-db default error filter skips AbortReadError, just like AbortError.
  • OTel now puts every command timeout in the network error category: TimeoutError, TimeoutReadError and their maintenance subclasses.
  • The write-queue TimeoutError now states the timeout in its message.

Breaking change (minor). TimeoutError now always means "never sent, safe to retry". Two rare paths used to reject commands that were already sent with it:

  • Slot migration: when a cluster slot migration (SMIGRATED) stops waiting for the source node's replies after 5 s, those commands now reject with TimeoutReadError.
  • Maintenance socket timeout: SocketTimeoutDuringMaintenanceError now extends TimeoutReadError. It only fires when maintenance notifications are on and the socket stays silent for the relaxed maintenance timeout.

This should not affect real users:

  • Rare paths: both happen only during server maintenance or slot migration, and only when the server stops replying for a while.
  • Narrow check: the only code that notices is code that checks err instanceof TimeoutError on these errors. The error messages and the SocketTimeoutDuringMaintenanceError class name are unchanged.
  • The old behavior was misleading: such code would treat a command that may already have run as safe to retry. With the new class it doesn't, which is what it should have done all along.

Known limitations, documented in docs/command-options.md:

  • Session state changed by a command that hit a read error is unknown. For example, after SELECT the client's tracked database may not match the server's. Repeat the command, or turn the option off for that call.
  • The migration flush empties the read queue while the connection stays open, so late replies can reach the wrong commands. This bug is older than this PR and is tracked in Cluster slot migration: late replies go to the wrong commands after the in-flight flush #3635.

Note

High Risk
Changes core command-queue timeout/abort semantics and error types for commands that may have executed on the server; incorrect retry logic after TimeoutReadError could cause data corruption.

Overview
Adds an experimental commandOptions.rejectInFlight flag (default false) so timeout and abortSignal keep applying while a command is already on the wire, not only while it waits in the write queue.

With the flag on, slow or aborted in-flight calls reject with new TimeoutReadError / AbortReadError (reply dropped, connection kept); queued-but-unsent commands still use TimeoutError / AbortError. The command queue was reworked to hold deadlines and abort listeners past write, handle MULTI/pipeline batches as a unit, skip read timeouts for blocking commands (via new isBlocking metadata), and extend maintenance relaxed timeouts to in-flight commands. exec / execAsPipeline now forward the option.

Minor breaking change: TimeoutError is narrowed to “never sent”; cluster migration flush and SocketTimeoutDuringMaintenanceError now surface TimeoutReadError instead. Related updates: client-side cache retries shared loads when the first caller aborts; multi-db defaultErrorFilter ignores AbortReadError; OTel classifies command timeouts via TimeoutError / TimeoutReadError. Docs describe behavior, error matrix, and caveats.

Reviewed by Cursor Bugbot for commit 7ad55ff. Bugbot is set up for automated code reviews on this repo. Configure here.

…Flight)

Add the experimental `rejectInFlight` command option. With it, `timeout`
and `abortSignal` also apply after a command is written, until its reply
arrives. Such a command rejects with the new `TimeoutReadError` or
`AbortReadError`: the server may have run it. Its entry stays in the read
queue and its late reply is dropped, so the connection stays open and
later replies stay matched.

- Commands flagged `blocking` in the command metadata keep only the
  write-queue timeout; abort still applies to them.
- MULTI and pipelines keep one timer until their last reply. If it fires
  after part of the batch is written, every pending command rejects with
  the read error and the rest of the batch is still written.
- The maintenance timeout also relaxes in-flight timers, including a
  batch's, and expires with `CommandTimeoutReadDuringMaintenanceError`.
- The multi-db default error filter skips `AbortReadError`.
- The command `TimeoutError` now states the timeout in its message.

Default `false`: without the flag, behavior is unchanged.
With rejectInFlight, a single blocking command drops its timer once it is
written, because the server keeps blocking after a client-side timeout.
A pipeline did not: its batch timer kept running, so a pipeline that held
a blocking command rejected with TimeoutReadError.

Commands in a pipeline block on the server, unlike commands inside MULTI.
Drop the timer when the first command of such a pipeline is written. The
abort signal still applies, and MULTI keeps its timer.
…Error

TimeoutError means the command was never sent and is safe to retry. Two
paths rejected commands that were already written with it:

- A cluster slot migration that stops waiting for the replies of the
  source node now rejects them with TimeoutReadError.
- SocketTimeoutDuringMaintenanceError now extends TimeoutReadError.

BREAKING CHANGE: neither error is an instance of TimeoutError any more.
The server may have executed the command: retry only if it is idempotent.
…egory

TimeoutError and TimeoutReadError, with their maintenance subclasses, now map to the network category. Before, only the maintenance write timeouts did, and plain and read timeouts fell through to other. Abort errors stay in other.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T18:32:16.746247Z 7ad55ff New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

The blocking-command tests set a 100 ms timeout with rejectInFlight in
clientOptions, so it also applied to the harness's FLUSHALL before and
after each test. On a slow runner FLUSHALL took longer, failed with
TimeoutReadError, skipped client.destroy(), and the leaked client then
failed the root after-all hook when the server stopped.

Set the options with withCommandOptions on the call under test instead.
When several callers read the same cached key at once, they share the
first caller's pending load. If that caller aborts, every waiter used to
reject with the first caller's AbortError or AbortReadError, although
none of them aborted. Waiters now drop the dead entry and load again,
sharing one new load. Other errors are still shared.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 013b163e5a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +747 to +749
if (err instanceof AbortError || err instanceof AbortReadError) {
if (cacheEntry.validate()) this.delete(cacheKey);
return this.handleCache(client, parser, fn, transformReply, typeMapping, isStorable);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Skip cache reloads for callers whose own signal is aborted

When concurrent cache-coalesced calls share an AbortSignal, cancelling it aborts every waiter, not just the load's owner. This branch nevertheless retries each waiter: the first replacement load immediately fails addCommand's already-aborted-signal check, and all remaining waiters recursively retry that failure again. This makes bulk cancellation quadratic: a real-client reproduction with 1,001 coalesced GETs performed 501,501 handleCache calls and stalled the event loop for roughly half a second. The regression also affects queued commands without rejectInFlight. Check the waiter's own cancellation state before retrying the shared load.

Useful? React with 👍 / 👎.

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

Read this with the slot-migration interactions in mind, since the tombstone semantics ("stays in the read queue, reply discarded on arrival") touch the same positional-pairing invariants as #3642. Three notes:

The tombstone × waitForInflightCommandsToComplete interplay is coherent — worth stating in a comment. A rejected-in-flight command keeps #waitingForReply non-empty until its reply actually arrives, so during an SMIGRATED pause the bounded wait can now be extended by commands whose callers already got their read error. That's correct: the queue genuinely isn't drained, and if the 5s flush fires, the source connection is dropped (#3642), so the discarded replies die with the socket instead of desyncing anything. One small cleanup it suggests: #flushWaitingForReply now re-rejects entries that are already rejected — benign promise-wise, but skipping them would keep the flush's error/telemetry counts meaning "callers actually affected".

The node: undefined deadline safety is an invariant spread across three members — consider tying it with an assert. #onTimeout only dereferences node! on the not-in-flight path, and that's safe today because both #relaxInFlight call sites guarantee #isInFlight(head) (read-queue entries are written; the #toWrite site requires head.written || #isBatchStarted(head), and either disjunct satisfies #isInFlight). But the proof lives in the conjunction of #relaxInFlight's guards, #isInFlight's definition, and #onTimeout's branch order — a one-line assert (or a comment naming the invariant) at #setDeadline(undefined, …) would keep a future caller from quietly breaking it.

For the record, the interplay with #3647 (if both land) converges safely: a discarded reply can under-inform the shared script cache — an EVAL that actually ran isn't marked (costs one extra upload later), and a discarded NOSCRIPT doesn't unmark (the next surfaced failure does). Both err in the safe direction, so nothing needed — just noting it was checked.

The docs paragraph on batches ("pending commands reject, the rest of the batch is still sent") and the blocking-command carve-out both read exactly right to me.

# Conflicts:
#	packages/client/lib/client/commands-queue.ts
A rejectInFlight command that already rejected stays in the read queue to keep
reply order. A flush now skips it instead of rejecting it again.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor

The red tests (22, 8.2, 8.2) cell here isn't from this PR — it's the sentinel flake from #3650: destroy() from an end listener tears down a reentrant reopen racing the reentrant teardown under load (the isOpen assertion at lifecycle-events.spec.ts:176). #3651 makes it deterministic by awaiting the teardown instead of a fixed delay, so a rerun — or merging #3651 — should clear it.

@nkaradzhov
nkaradzhov merged commit da1dff8 into redis:master Nov 23, 2026
14 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants