Repository navigation
fix(client): keep Buffer and VerbatimString replies intact in the client-side cache - #3544
Conversation
…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
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. |
There was a problem hiding this comment.
💡 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".
| copy: Record<string, unknown> = {}, | ||
| keys = Object.keys(source); | ||
| for (let i = 0; i < keys.length; i++) { | ||
| copy[keys[i]] = typeAwareCopy(source[keys[i]]); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if (Array.isArray(value)) { | ||
| const copy = new Array(value.length); | ||
| for (let i = 0; i < value.length; i++) { | ||
| copy[i] = typeAwareCopy(value[i]); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if (Array.isArray(value)) { | ||
| const copy = new Array(value.length); | ||
| for (let i = 0; i < value.length; i++) { | ||
| copy[i] = typeAwareCopy(value[i]); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Fixed in 35d23cc: holes are skipped, so they stay holes. Covered by keeps array holes.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 5282e53. Configure here.
…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.
|
The bot reviews found four cases where 35d23cc fixes them. The copy now records each array, object, |
There was a problem hiding this comment.
💡 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".
| for (let i = 0; i < value.length; i++) { | ||
| if (i in value) copy[i] = typeAwareCopy(value[i], copies); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| const copy = structuredClone(value); | ||
| copies.set(value, copy); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.

Description
Fixes #3536, using the approach agreed there.
BasicClientSideCache.handleCache()returns astructuredClone()of the reply, on a cache hit and on the miss that fills the cache.structuredClone()turns aBufferinto a plainUint8Array, and aVerbatimStringinto aStringobject without itsformat. So withcommandOptions: { typeMapping: { [RESP_TYPES.BLOB_STRING]: Buffer } }and the cache on, every cached read returned aUint8Array, the first one included.Both return paths now choose the copy from the type mapping. If
BLOB_STRING,SIMPLE_STRINGorVERBATIM_STRINGmaps toBuffer, orVERBATIM_STRINGmaps toVerbatimString, the reply goes throughtypeAwareCopy(). It copies aBufferwithBuffer.from(), createsnew VerbatimString(value.format, String(value))for aVerbatimString, and walks arrays,Mapkeys and values,Sets and plain objects. Primitives are returned as they are. Anything else still goes throughstructuredClone(), and so does every reply for clients without such a mapping. LikestructuredClone(), the copy keeps cycles and shared arrays, objects,Maps andSets (it records each one it copies in aMap), leaves array holes as holes, and keeps a"__proto__"field as an own property.Buffers andVerbatimStrings 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
BufferorVerbatimString, the same as with the cache off, instead of aUint8ArrayorString.Tests in
cache.spec.ts:handleCache() copies of cached repliesruns once per mapping and once without a mapping. The reply nests arrays, an object, aMapand aSet, and holds every type the decoder can produce: a string, an integer, a double, aBigInt, a boolean andnull, plus aBufferand aVerbatimStringin the mapped cases. It goes through the miss and two hits. Each copy mustdeepStrictEqualthe original, which also compares classes andformat. 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 containersandkeeps array holescover replies that aJSON.GETorJSON.MGETreviver, or a"__proto__"field in a document, can produce. All three fail on the first commit of this PR.testAllreturns Buffers from the cacheusesBLOB_STRING: Bufferand checks thatget()andhGetAll()return aBufferon 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'scommandOptions, 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.Cached replies stay Buffers with a Buffer type mappingchecks for aBufferon the miss and on the hit, and counts one of each. It fails on master.Benchmark:
benchmark/lib/client-side-cachehaslocal.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 withINFO commandstatsthat in the hit cases only the first read of each variant reaches the server, and in the miss case every read does.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 testpasses exceptSocket 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
npm testpass with this change (including linting)? All but the socket test above, which also fails on master here.docs/client-side-caching.mddescribes.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.typeMappingthat maps string types toBufferorVerbatimString. Cached hits (and the return path after a miss) usedstructuredClone, which turnedBufferintoUint8Arrayand strippedVerbatimString.format.BasicClientSideCache.handleCache()now pickstypeAwareCopywhen the mapping targets those types; otherwise it still usesstructuredClone.typeAwareCopydeep-copies nested structures likestructuredClonebut preserves buffer and verbatim semantics, including edge cases (__proto__own properties, sparse arrays, cycles).Adds broad
cache.spec.tscoverage (unit + live client/pool) and abenchmark/lib/client-side-cacheharness (default vsBLOB_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.