Repository navigation
fix(client): reuse EVALSHA across multi and pipeline batches - #3647
Cdineshreddy12 wants to merge 3 commits into
Conversation
scriptsInUse only deduplicates within one batch, so every multi() or pipeline re-uploaded the full script source with EVAL on its first use, forever - the server had the script cached from the first batch on. The client now shares a set of known-loaded SHA1s with every batch it creates: the first batch still uploads with EVAL (which caches the script server-side), and once that command succeeds, later batches send EVALSHA. A NOSCRIPT reply to one of those EVALSHAs (SCRIPT FLUSH, or a server that lost its cache) removes the SHA so the next batch re-uploads, and the set is cleared on reconnect, since a reconnect may be a server restart - an EVALSHA inside MULTI..EXEC cannot fall back mid-transaction, so known-loaded must never overstate what the server has. Scoped to the standalone client: the cluster and sentinel multi builders keep the per-batch behavior. Fixes redis#2084
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 57b9117a3e
ℹ️ 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".
| const rawReplies = await this.#executePipeline(this.#multi.queue, this.#selectedDB); | ||
| this.#multi.updateKnownScripts(rawReplies); |
There was a problem hiding this comment.
Evict known SHAs when a pipeline rejects with NOSCRIPT
After a script succeeds in one batch and Redis subsequently loses it, such as through SCRIPT FLUSH, execAsPipeline() never reaches updateKnownScripts(): the standalone client's _executePipeline() uses Promise.all, and the command queue rejects the promise for a NOSCRIPT reply. The await therefore throws while leaving the SHA marked as known, so every newly constructed pipeline continues sending EVALSHA and failing instead of re-uploading on the next batch. Handle script-command rejections when updating the shared cache while preserving the pipeline's rejection contract.
Useful? React with 👍 / 👎.
| .on('ready', () => { | ||
| // a reconnect may be a server restart, which loses the script cache | ||
| this.#knownScripts.clear(); |
There was a problem hiding this comment.
Invalidate known scripts before accepting offline batches
With the default offline queue, a batch constructed in a reconnecting handler after warming a script still sees the old knownScripts set, so addScript() encodes EVALSHA. If the reconnect follows a server restart with an empty script cache, clearing the set here does not rewrite those already-queued arguments: the script fails with NOSCRIPT, while the transaction's other commands still execute. Invalidate the cache on socket loss before accepting offline work, and ensure queued script commands cannot retain a stale SHA-only choice across connection changes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.
Reviewed by Cursor Bugbot for commit 57b9117. Configure here.
…isconnect
A pipeline rejects on its first error reply, so updateKnownScripts never
saw the replies: a NOSCRIPT after SCRIPT FLUSH left the SHA marked and
every new pipeline kept failing. handleExecError now forgets the SHAs a
rejected batch relied on.
The known set is also cleared at disconnect time ('reconnecting'), not
just on 'ready', so a batch built against the offline queue does not
encode EVALSHA from the dead connection's cache. A batch encoded before
the disconnect can still carry a stale EVALSHA; that one fails once,
unmarks, and the next batch re-uploads.
|
Both findings were real — addressed in 53e409c: Pipeline NOSCRIPT rejection: confirmed — Offline batches encoding stale EVALSHA: the set is now cleared at disconnect time ( |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 53e409c9d0
ℹ️ 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".
| .on('connect', () => this.emit('connect')) | ||
| .on('ready', () => { | ||
| // a reconnect may be a server restart, which loses the script cache | ||
| this.#knownScripts.clear(); |
There was a problem hiding this comment.
Clear known SHAs when swapping in a live socket
During an Enterprise MOVING handoff, EnterpriseMaintenanceManager.#onMoving() connects a temporary client and swaps its already-ready socket into the original client through _insertSocket(). Neither ready nor reconnecting fires on the original client, and _insertSocket() leaves #knownScripts intact. If the replacement server lacks the old server's scripts, even fresh transactions created after the handoff send EVALSHA and fail with NOSCRIPT, while their other commands still execute. Invalidate the shared script state when replacing the socket as well.
Useful? React with 👍 / 👎.
| } else if (!(reply instanceof ErrorReply)) { | ||
| knownScripts.add(sha); |
There was a problem hiding this comment.
Skip scripts without a reply in the current execution
When a script is appended to a builder while a preceding exec() or execAsPipeline() is pending, the executor has already snapshotted the submitted commands, but this loop reads the newly appended metadata too. For that entry, rawReplies[index] is undefined, so it passes this check and records a script that was never sent as known. The next independent transaction then emits EVALSHA and fails with NOSCRIPT. Limit bookkeeping to the commands submitted for that execution, or require a corresponding reply before marking the SHA.
Useful? React with 👍 / 👎.
…okkeeping A MOVING handoff installs an already-ready socket via _insertSocket - no 'ready' or 'reconnecting' fires on the client, and the new server may not have the old server's script cache, so the swap now wipes knownScripts the same way it wipes the prepared fieldsets. A script appended to a builder while an execution was already pending has no reply in that result set; it was never sent, so updateKnownScripts now skips entries past the end of the replies instead of recording them.
|
Round-up of the four bot findings — all addressed:
16 builder tests green. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 58c91417c7
ℹ️ 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".
| } else if (!(reply instanceof ErrorReply)) { | ||
| knownScripts.add(sha); |
There was a problem hiding this comment.
Ignore script replies from a replaced socket generation
During an Enterprise MOVING handoff with an EVAL pipeline still in flight, waitForInflightCommandsToComplete() wakes when the final reply is shifted, before execAsPipeline() applies its bookkeeping. The new _insertSocket() clear can therefore run first, after which this add restores a SHA loaded only on the source server. I reproduced a fresh post-handoff batch sending EVALSHA to a target without that script and failing with NOSCRIPT, despite the explicit invalidation. Associate reply updates with the connection/cache generation that executed the batch, and discard old-generation updates.
Useful? React with 👍 / 👎.
| const viaSha = this.scriptsInUse.has(script.SHA1) || this.knownScripts?.has(script.SHA1) === true; | ||
| this.scriptCommands.push({ index: this.queue.length, sha: script.SHA1, viaSha }); | ||
| if (viaSha) { | ||
| redisArgs.push(script.IS_READ_ONLY ? 'EVALSHA_RO' : 'EVALSHA', script.SHA1); |
There was a problem hiding this comment.
Re-encode script commands when re-executing a batch
For a builder created after another batch has warmed the SHA, flush the server's scripts and execute that builder twice. The first NOSCRIPT correctly removes the SHA from the shared set, but the second execution still sends the EVALSHA encoded here; the new error handlers never rewrite the queued arguments. Repeated exec()/execAsPipeline() calls on the same builder are supported, so this builder cannot re-upload the source on retry and continues failing until another operation reloads it. Retain the script source and reconsider the shared-cache decision on each execution.
Useful? React with 👍 / 👎.
|
Thanks. We are going to close this one. Today a script inside If you see a real cost from this, for example large scripts in a busy pipeline, please open a new issue that describes it and we can look at it again. |

Fixes #2084
Still reproduces on master — wire trace via MONITOR, one script through both paths:
Cause:
scriptsInUseis per-batch, so it only deduplicates within onemulti().The client now shares a known-loaded-SHA set with every batch it creates. The first batch still uploads with
EVAL(which caches the script server-side); once that command succeeds, every later batch sendsEVALSHA. Same trace with this change:EVALappears exactly once per client, everything after isEVALSHA.The part that needs care is never overstating what the server has, because an
EVALSHAthat hitsNOSCRIPTinsideMULTI..EXECcan't fall back mid-transaction:EVAL's own reply comes back non-error (a batch aborted byWATCHor a failed upload marks nothing)NOSCRIPTreply to a marked script (externalSCRIPT FLUSH) unmarks it, so the next batch re-uploadsScoped to the standalone client — the cluster and sentinel multi builders keep today's per-batch behavior, since their batches are built before a node is picked (per-node caches would need the known set chosen at routing time; can follow up if there's interest).
Unit tests cover the new paths at the builder level (EVAL once → EVALSHA after, error-reply doesn't mark, NOSCRIPT unmarks, non-NOSCRIPT errors keep the mark, and no shared set = old behavior). I considered the alternative of pipelining
SCRIPT LOADbefore theMULTIand always usingEVALSHAinside (closer to ioredis) — happy to switch to that if preferred; this version keeps the wire shape unchanged.Note
Medium Risk
Changes script encoding for MULTI/pipeline on standalone clients; incorrect cache bookkeeping could cause NOSCRIPT failures inside transactions, though reconnect/NOSCRIPT paths are designed to self-heal.
Overview
Fixes #2084 by tracking server-side script cache at the standalone Redis client level instead of only inside each
MULTI/pipeline batch.The client keeps a shared
#knownScriptsset, passes it into everymulti()builder, andRedisMultiCommandchoosesEVALSHAwhen a SHA is already known (still deduping within a batch viascriptsInUse). Afterexec/execAsPipeline,updateKnownScriptsrecords successfulEVALloads and drops SHAs onNOSCRIPT;handleExecErrorcovers pipeline rejections the same way. The set is cleared on reconnect,reconnecting, and socket swap so offline batches do not assume a stale server cache.Cluster/sentinel multi builders are unchanged (no shared set). New unit tests cover cross-batch
EVAL→EVALSHA, error/NOSCRIPThandling, and backward compatibility when no shared set is provided.Reviewed by Cursor Bugbot for commit 58c9141. Bugbot is set up for automated code reviews on this repo. Configure here.