Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(cluster): hash lone surrogates as the UTF-8 Node sends
Ported from redis/ioredis#2242.

Signed-off-by: Jacob Ley <jacobtley@gmail.com>
  • Loading branch information
JacobLey committed Oct 22, 2026
commit 1c4b7513479a20a06c42da0810a62d3ca76aa93a
9 changes: 9 additions & 0 deletions lib/utils/calculateSlot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,15 @@ function toUTF8Array(str: string): number[] {
utf8[p++] = ((char >> 6) & 63) | 128;
utf8[p++] = (char & 63) | 128;
} else {
// A lone surrogate has no UTF-8 encoding, so Node writes it as U+FFFD
// (EF BF BD), both to a socket and in `Buffer.from(str)`. Encoding it
// the same way hashes the bytes the server receives. Node's UTF-8 write
// passes V8 `kReplaceInvalidUtf8`, which replaces orphan surrogates:
// https://github.com/nodejs/node/blob/59e46cac2943/src/string_bytes.cc#L305-L316
// https://github.com/nodejs/node/blob/59e46cac2943/deps/v8/include/v8-primitive.h#L222-L225
if ((char & 0xf800) === 0xd800) {
char = 0xfffd;
}
utf8[p++] = (char >> 12) | 224;
utf8[p++] = ((char >> 6) & 63) | 128;
utf8[p++] = (char & 63) | 128;
Expand Down
28 changes: 28 additions & 0 deletions test/unit/calculateSlot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,34 @@ describe("calculateSlot", () => {
});
});

describe("lone UTF-16 surrogates", () => {
// Node writes string keys to the socket as UTF-8, replacing any lone
// surrogate with U+FFFD (EF BF BD). The slot must be computed from those
// same bytes, or the server answers with MOVED on every command.
const keys: Array<[string, string]> = [
["a lone high surrogate", "x\ud800y"],
["a lone low surrogate", "x\udc00"],
["a high surrogate at the end", "abc\ud83d"],
["a low surrogate followed by a high one", "a\udc00\ud800b"],
];

for (const [name, key] of keys) {
it(`hashes ${name} as the UTF-8 bytes Node sends`, () => {
expect(calculateSlot(key)).to.eql(calculateSlot(Buffer.from(key)));
});
}

it("matches the server's slot for a lone low surrogate", () => {
// Measured with `CLUSTER KEYSLOT` against a live Redis 8 server.
expect(calculateSlot("x\udc00")).to.eql(13299);
});

it("still hashes a valid surrogate pair as one code point", () => {
const key = "x\ud83d\ude00";
expect(calculateSlot(key)).to.eql(calculateSlot(Buffer.from(key)));
});
});

describe("generateMulti()", () => {
it("returns the shared slot when all keys hash to the same slot", () => {
// "a{}b}c" and "42703" both land on slot 2041 under the corrected
Expand Down