Skip to content

fix(client): keep Buffer and VerbatimString replies intact in the client-side cache - #3544

Merged
nkaradzhov merged 2 commits into
redis:masterfrom
OmBhandwaldar:fix/client-side-cache-buffer
Oct 28, 2026
Merged

nkaradzhov merged 2 commits into
redis:masterfrom
OmBhandwaldar:fix/client-side-cache-buffer

Conversation

@OmBhandwaldar

@OmBhandwaldar OmBhandwaldar commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #3536, using the approach agreed there.

BasicClientSideCache.handleCache() returns a structuredClone() of the reply, on a cache hit and on the miss that fills the cache. structuredClone() turns a Buffer into a plain Uint8Array, and a VerbatimString into a String object without its format. So with commandOptions: { typeMapping: { [RESP_TYPES.BLOB_STRING]: Buffer } } and the cache on, every cached read returned a Uint8Array, the first one included.

Both return paths now choose the copy from the type mapping. If BLOB_STRING, SIMPLE_STRING or VERBATIM_STRING maps to Buffer, or VERBATIM_STRING maps to VerbatimString, the reply goes through typeAwareCopy(). It copies a Buffer with Buffer.from(), creates new VerbatimString(value.format, String(value)) for a VerbatimString, and walks arrays, Map keys and values, Sets and plain objects. Primitives are returned as they are. Anything else still goes through structuredClone(), and so does every reply for clients without such a mapping. Like structuredClone(), the copy keeps cycles and shared arrays, objects, Maps and Sets (it records each one it copies in a Map), leaves array holes as holes, and keeps a "__proto__" field as an own property. Buffers and VerbatimStrings are copied wherever they appear: decoded replies never share them, and recording them made large replies noticeably slower.

Behavior change: with one of these mappings, a cached read now returns a Buffer or VerbatimString, the same as with the cache off, instead of a Uint8Array or String.

Tests in cache.spec.ts:

  • handleCache() copies of cached replies runs once per mapping and once without a mapping. The reply nests arrays, an object, a Map and a Set, and holds every type the decoder can produce: a string, an integer, a double, a BigInt, a boolean and null, plus a Buffer and a VerbatimString in the mapped cases. It goes through the miss and two hits. Each copy must deepStrictEqual the original, which also compares classes and format. After each read the test changes every part of the copy, so a value shared with the cache would show up on the next hit. The four mapped cases fail on master.
  • keeps an own __proto__ field, keeps cycles and shared containers and keeps array holes cover replies that a JSON.GET or JSON.MGET reviver, or a "__proto__" field in a document, can produce. All three fail on the first commit of this PR.
  • testAll returns Buffers from the cache uses BLOB_STRING: Buffer and checks that get() and hGetAll() return a Buffer on the first and second call. The client case fails on master. The cluster case passes on master too, because a cluster with a custom type mapping doesn't cache. Its node clients are created without the cluster's commandOptions, and a client only stores replies made with its own type mapping. In this test the cluster gets 0 hits and 0 misses, while the existing cluster cache tests, which have no type mapping, do get hits.
  • The pool test Cached replies stay Buffers with a Buffer type mapping checks for a Buffer on the miss and on the hit, and counts one of each. It fails on master.

Benchmark: benchmark/lib/client-side-cache has local.js (default mapping), local-buffer.js (BLOB_STRING: Buffer) and one yml per case. In the miss case the cache holds a single entry and the reads go through 1,000 keys in turn, so every read misses. I checked with INFO commandstats that in the hit cases only the first read of each variant reaches the server, and in the miss case every read does.

cached reads/s, median of 5 rounds, master (b1e1e3a) and this branch on top of it alternating, 100,000 reads, concurrency 100
Node v24.16.0, Redis 8.2.10 in Docker on the same machine, macOS

                               default mapping              BLOB_STRING: Buffer
                            master     branch           master     branch
get() 16 B                1,298,921  1,290,114          935,102  1,384,544   (+48%)
get() 1 MB                    8,064      7,694           15,361     25,301   (+65%)
hGetAll() 1,000 fields       13,652     13,250            6,666      9,829   (+47%)
get() 16 B, every read a miss
                            206,110    191,944          195,841    225,582   (+15%)

With the default mapping the branch runs the same code as master, plus the mapping check, and each difference is inside the spread of the rounds. For example, the miss case ranged from 143,993 to 211,277 across the master rounds and from 100,533 to 199,092 across the branch rounds.

npm test passes except Socket reconnectStrategy retry counter is sequential after a post-ready socket loss, which fails the same way on master on my machine (macOS). Lint is clean.


Checklist

  • Does npm test pass with this change (including linting)? All but the socket test above, which also fails on master here.
  • Is the new or changed code fully tested?
  • Is a documentation update included (if this change modifies existing APIs, or introduces new ones)? Not needed: no API change, and the cache now behaves as docs/client-side-caching.md describes.

Note

Medium Risk
Touches hot-path cache return logic for all cached reads when Buffer/VerbatimString mappings are used; behavior fix is localized but deep-copy correctness is security-sensitive for mutable replies.

Overview
Fixes incorrect reply types when client-side caching is enabled with commandOptions.typeMapping that maps string types to Buffer or VerbatimString. Cached hits (and the return path after a miss) used structuredClone, which turned Buffer into Uint8Array and stripped VerbatimString.format.

BasicClientSideCache.handleCache() now picks typeAwareCopy when the mapping targets those types; otherwise it still uses structuredClone. typeAwareCopy deep-copies nested structures like structuredClone but preserves buffer and verbatim semantics, including edge cases (__proto__ own properties, sparse arrays, cycles).

Adds broad cache.spec.ts coverage (unit + live client/pool) and a benchmark/lib/client-side-cache harness (default vs BLOB_STRING: Buffer, hit/miss scenarios) to measure copy overhead.

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

…ent-side cache

The client-side cache returned a structuredClone() of the reply, on a
cache hit and on the miss that fills the cache. structuredClone() turns
a Buffer into a plain Uint8Array and drops a VerbatimString's format,
so a client that maps strings to Buffer got a Uint8Array from every
cached read.

When the type mapping returns Buffer or VerbatimString, both paths now
use typeAwareCopy(), which keeps those classes. Other clients keep
structuredClone(). Also adds a client-side-cache benchmark suite.

Fixes redis#3536
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T14:44:18.170062Z 35d23cc 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: 5282e53cfc

ℹ️ 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 thread packages/client/lib/client/cache.ts Outdated
copy: Record<string, unknown> = {},
keys = Object.keys(source);
for (let i = 0; i < keys.length; i++) {
copy[keys[i]] = typeAwareCopy(source[keys[i]]);

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 Define __proto__ as an own property in cloned replies

With client-side caching and any mapping that selects typeAwareCopy, a cacheable JSON.GET reply may legitimately contain an own __proto__ field. Writing that key into {} invokes the inherited setter, so both the cache-fill response and later hits lose the field and instead acquire its object value as their prototype; the previous structuredClone preserved the exact object shape. Create the copy without that setter or define each property as an own data property.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 35d23cc: "__proto__" is now defined as an own property instead of assigned, so the copy keeps the field and its prototype stays Object.prototype. Covered by keeps an own __proto__ field.

Comment thread packages/client/lib/client/cache.ts Outdated
if (Array.isArray(value)) {
const copy = new Array(value.length);
for (let i = 0; i < value.length; i++) {
copy[i] = typeAwareCopy(value[i]);

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 Memoize containers before recursively cloning replies

When a mapped cacheable transform returns a cycle or reuses an object in multiple places—JSON.GET's public reviver can produce either—each recursive call copies the value without memoizing it. A self-referential array now rejects the cache fill with a RangeError, while repeated Buffer/object references lose their identity; the old structuredClone handled cycles and preserved aliases. Thread a WeakMap through the copy and register each clone before descending.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 35d23cc: the copy records each array, object, Map and Set in a Map before walking into it and reuses that copy, so cycles and shared containers come out as they do with structuredClone(). Buffers and VerbatimStrings are still copied wherever they appear, since decoded replies never share them and recording every Buffer made a cached 1,000-field hGetAll() much slower. Covered by keeps cycles and shared containers.

Comment thread packages/client/lib/client/cache.ts Outdated
if (Array.isArray(value)) {
const copy = new Array(value.length);
for (let i = 0; i < value.length; i++) {
copy[i] = typeAwareCopy(value[i]);

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 Keep holes sparse when copying arrays

With a mapped client, a cacheable transform can return a sparse array; for example, a JSON.GET reviver that returns undefined for an array element makes JSON.parse delete that index. This loop nevertheless assigns every index, turning each hole into an own property whose value is undefined, so Object.keys, the in operator, and deep equality change only when caching is enabled. Preserve absent indices instead of assigning them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 35d23cc: holes are skipped, so they stay holes. Covered by keeps array holes.

@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 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 5282e53. Configure here.

Comment thread packages/client/lib/client/cache.ts Resolved
…he cache copy

typeAwareCopy() didn't remember what it had already copied, so a reply
that contains itself, which a JSON.GET reviver can build, threw a
RangeError, and an object used twice came back as two copies. It also
filled array holes with undefined, and copied a "__proto__" field with
an assignment, which set the copy's prototype instead of creating the
field. structuredClone() handles all four.

The copy now records each array, object, Map and Set it copies in a Map
and reuses it, skips holes, and defines "__proto__" as an own property.
Buffers and VerbatimStrings are still copied wherever they appear:
decoded replies never share them, and recording them made large replies
noticeably slower.
@OmBhandwaldar

Copy link
Copy Markdown
Contributor Author

The bot reviews found four cases where typeAwareCopy() didn't match structuredClone(). All of them need one of the four mappings and a cached JSON.GET or JSON.MGET. A reply that contains itself, which a reviver can build, threw a RangeError. An object used twice came back as two copies. Array holes became undefined. And a "__proto__" field in a document became the copy's prototype.

35d23cc fixes them. The copy now records each array, object, Map and Set it copies in a Map and reuses it, skips holes, and defines "__proto__" as an own property. That goes beyond your notes. I first recorded Buffers too, which also keeps one Buffer used twice as one copy, but a cached hGetAll() of 1,000 Buffers then gained only about 7% over master instead of 47%. Decoded replies never share a Buffer, so the copy now leaves them out of the Map. The benchmark numbers in the description are from this version. If you'd rather keep the walk without the Map, I can take it out and keep only the hole and __proto__ fixes, which brings back the cycle crash and the split copies from the first commit.

@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: 35d23ccc55

ℹ️ 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 +505 to +506
for (let i = 0; i < value.length; i++) {
if (i in value) copy[i] = typeAwareCopy(value[i], copies);

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 Copy every own enumerable array property

With client-side caching and a Buffer/VerbatimString type mapping, a cacheable transform can return an array with enumerable named properties (for example, a JSON.GET reviver can attach array.meta). This index-only loop drops those properties from both the fill response and cache hits, whereas the previous structuredClone preserved them; i in value can also materialize inherited numeric properties rather than restricting the copy to own enumerable keys. Copy the array's own enumerable keys while preserving its length and special property names.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Left as is: keeping named properties means calling Object.keys() on every array, which builds one string per element on every cached read of a large list. Decoded replies never have them, so the copy keeps the walk agreed in #3536 and only goes through the indices.

// keeps Buffers as Buffers and VerbatimStrings with their `format`. Those two are copied wherever
// they appear: decoded replies never share them, and tracking them would slow down large replies.
function typeAwareCopy<T>(value: T, copies = new Map<object, unknown>()): T {
if (typeof value !== 'object' || value === null) return value;

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 Reject callable reviver values instead of sharing them

With client-side caching and a Buffer/VerbatimString type mapping, a JSON.GET reviver can return a function, but this early return treats that mutable callable as a primitive. The function stored in the cache is then returned by reference on the fill and every hit, so mutating its properties or closure state through one response contaminates later responses; the previous structuredClone instead rejected such a value with DataCloneError. Keep the structured-clone rejection behavior for functions rather than returning them directly.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Left as is: a reviver that returns a function already failed with every cached client before this PR, because structuredClone() throws DataCloneError for functions. With one of the four mappings the copy now returns the function itself, the same one on every read. If you'd rather keep the error, I can send functions to the structuredClone() fallback.

Comment on lines +547 to +548
const copy = structuredClone(value);
copies.set(value, copy);

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 Preserve links across fallback clone boundaries

With client-side caching and a Buffer/VerbatimString type mapping, a reviver can return a cloneable class instance whose parent field points back to its containing plain object. The parent is already registered in copies, but this fallback clones the instance and parent as an independent subgraph, so the returned copy.child.parent is not copy; the previous whole-value structuredClone preserved that cycle. Fallback values need to participate in the same clone graph rather than being cloned independently.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Left as is: anything other than arrays, plain objects, Maps, Sets, Buffers and VerbatimStrings goes to structuredClone() on its own, as agreed in #3536. Keeping a link from such a value back to its parent would mean rebuilding structured clone for class instances, and structuredClone() already turns those into plain objects.

@nkaradzhov nkaradzhov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks, LGTM!

@nkaradzhov
nkaradzhov merged commit 835e9f2 into redis:master Oct 28, 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.

Client-side cache returns Uint8Array instead of Buffer when the client maps strings to Buffer

2 participants