Skip to content

fix(client): reuse EVALSHA across multi and pipeline batches - #3647

Closed
Cdineshreddy12 wants to merge 3 commits into
redis:masterfrom
Cdineshreddy12:fix/multi-evalsha
Closed

Cdineshreddy12 wants to merge 3 commits into
redis:masterfrom
Cdineshreddy12:fix/multi-evalsha

Conversation

@Cdineshreddy12

@Cdineshreddy12 Cdineshreddy12 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2084

Still reproduces on master — wire trace via MONITOR, one script through both paths:

single command:  EVALSHA, EVAL   (NOSCRIPT fallback — fine, and caches it server-side)
single command:  EVALSHA
multi() #1:      EVAL            (full source, though the server has it cached)
multi() #2:      EVAL            (full source again — every batch, forever)
execAsPipeline:  EVAL, EVALSHA   (first use per batch pays the upload)

Cause: scriptsInUse is per-batch, so it only deduplicates within one multi().

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 sends EVALSHA. Same trace with this change: EVAL appears exactly once per client, everything after is EVALSHA.

The part that needs care is never overstating what the server has, because an EVALSHA that hits NOSCRIPT inside MULTI..EXEC can't fall back mid-transaction:

  • a SHA is only marked after its EVAL's own reply comes back non-error (a batch aborted by WATCH or a failed upload marks nothing)
  • a NOSCRIPT reply to a marked script (external SCRIPT FLUSH) unmarks it, so the next batch re-uploads
  • the set is cleared on reconnect, since a reconnect may be a server restart with an empty script cache

Scoped 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 LOAD before the MULTI and always using EVALSHA inside (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 #knownScripts set, passes it into every multi() builder, and RedisMultiCommand chooses EVALSHA when a SHA is already known (still deduping within a batch via scriptsInUse). After exec / execAsPipeline, updateKnownScripts records successful EVAL loads and drops SHAs on NOSCRIPT; handleExecError covers 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/NOSCRIPT handling, 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.

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
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 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-20T06:00:25.369721Z 58c9141 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.

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

Comment on lines +249 to +250
const rawReplies = await this.#executePipeline(this.#multi.queue, this.#selectedDB);
this.#multi.updateKnownScripts(rawReplies);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines 1118 to +1120
.on('ready', () => {
// a reconnect may be a server restart, which loses the script cache
this.#knownScripts.clear();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 57b9117. Configure here.

Comment thread packages/client/lib/client/index.ts Resolved
…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.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

Both findings were real — addressed in 53e409c:

Pipeline NOSCRIPT rejection: confirmed — _executePipeline is a Promise.all over per-command promises, so the first error reply rejects the whole await and updateKnownScripts never saw the replies, leaving the SHA marked. There's now a handleExecError on the batch: a thrown NOSCRIPT forgets every SHA the batch relied on (over-forgetting is harmless — one extra EVAL), unrelated rejections keep the set. Covered by two new unit tests.

Offline batches encoding stale EVALSHA: the set is now cleared at disconnect time ('reconnecting'), not just on 'ready', so a batch built against the offline queue encodes EVAL. One residual window stays: a batch encoded before the disconnect and still sitting in the write queue carries its EVALSHA args — rewriting already-encoded queued arguments would reach into the queue's domain, so instead that command fails once with NOSCRIPT, unmarks via the first fix, and the next batch re-uploads. Worth noting that's no worse than what any EVALSHA user faces across a restart, and it self-heals; can revisit if you'd rather re-encode on reconnect.

@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: 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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +94 to +95
} else if (!(reply instanceof ErrorReply)) {
knownScripts.add(sha);

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

Copy link
Copy Markdown
Contributor Author

Round-up of the four bot findings — all addressed:

  • Pipeline NOSCRIPT never unmarks (Bugbot High, Codex P1): fixed in 53e409c — handleExecError forgets a rejected batch's SHAs on a thrown NOSCRIPT (both bots reviewed the pre-fix commit for this one).
  • Offline batches encode stale EVALSHA (Codex P1): fixed in 53e409c — the set clears on 'reconnecting', so batches built against the offline queue upload with EVAL.
  • Socket swap keeps the old server's cache (Bugbot Medium, Codex P1 re-review): real — a MOVING handoff installs an already-ready socket through _insertSocket, no 'ready'/'reconnecting' fires, and the new server may not have the old scripts. Fixed in 58c9141: the swap now wipes knownScripts right beside the existing prepared-fieldsets wipe, which exists for exactly this reason.
  • Script appended during a pending exec gets recorded without a reply (Codex P2): real — rawReplies[index] was undefined, which passed the not-an-error check. Fixed in 58c9141: bookkeeping skips entries past the end of the result set, with a unit test.

16 builder tests green.

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

Comment on lines +97 to +98
} else if (!(reply instanceof ErrorReply)) {
knownScripts.add(sha);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +60 to 63
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);

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 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 👍 / 👎.

@nkaradzhov

Copy link
Copy Markdown
Collaborator

Thanks. We are going to close this one.

Today a script inside MULTI can never fail with NOSCRIPT, because each batch sends EVAL before any EVALSHA. With a client-wide cache, any gap in the cache, such as a reconnect, a socket swap, a SCRIPT FLUSH or a race between them, turns into a partly applied transaction: the script fails and the other commands still commit. The review rounds here kept finding new gaps of this kind, and two are still open. The gain is the bytes of the script source once per batch, since the server already has the script cached. For us that trade is not worth it.

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.

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.

Scripts execution always uses EVAL with multi.

2 participants