Skip to content

ZSCAN: format skiplist scores with d2string(), consistent with ZSCORE - #15821

Merged
sundb merged 2 commits into
redis:unstablefrom
filipecosta90:zscan-reply-d2string
Oct 19, 2026
Merged

sundb merged 2 commits into
redis:unstablefrom
filipecosta90:zscan-reply-d2string

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

For the same sorted set member, ZSCAN on a skiplist-encoded key returns a different score string than ZSCORE — and than ZSCAN itself on a listpack-encoded key:

redis> ZADD k 3.3 m            (plus >128 more members, so k is skiplist-encoded)
redis> ZSCORE k m
"3.3"
redis> ZSCAN k 0 MATCH m
1) "0"
2) 1) "m"
   2) "3.2999999999999998"

Root cause

#10587 (7.2) moved d2string() / addReplyDouble() to the fpconv shortest round-trip formatter, but scanCallback()'s OBJ_ZSET branch in db.c kept formatting the score with ld2string(..., LD_STR_AUTO) — i.e. the C library's "%.17Lg" on a double widened to long double. It is the only client-reply ld2string() call fed a double; every other client-facing score reply already uses d2string() (ZSCORE, ZMSCORE, the WITHSCORES variants, ZPOPMIN/ZPOPMAX, and listpack-encoded sorted sets, which store the d2string() form and echo it from ZSCAN as-is). The result is that since 7.2 a key's ZSCAN score strings change form when it converts from listpack to skiplist.

Fix

Two lines: format the skiplist ZSCAN score with d2string() into a MAX_D2STRING_CHARS buffer (128 bytes instead of the 5 KiB MAX_LONG_DOUBLE_CHARS stack buffer). After merging current unstable, including #15822, these lines are in scanGenericCommand() reply construction. The borrowed-node collection and queued-deletion regression test from #15822 are preserved.

Behaviour change (release notes)

This is a formatting consistency improvement, not a numeric correctness fix: the old and new strings parse to the same double. Since the reply text changes, this should be release-noted and does not warrant a bug-fix backport.

ZSCAN on skiplist-encoded sorted sets now returns the same score string as ZSCORE for the same value. Relative to "%.17Lg" the notation can differ in either direction — 1.2345678912345679e+8 where it printed 123456789.12345679, -123456789012345670000000 where it printed -1.2345678901234567e+23 — and integral scores of 18+ digits up to 2^62 print exactly (1152921504606846976 instead of 1.152921504606847e+18). Every form re-parses to the same double through ZADD. Notes for reviewers:

  • ZSCAN is a read-only reply; nothing here is replicated, written to AOF or persisted. AOF rewrite has already emitted the fpconv form since 7.2 (rioWriteBulkDouble).
  • No new syntax class appears: "%.17Lg" already produced exponent notation (1e+100, 9.8813129168249309e-323); fpconv writes minimal exponent digits (e+8 vs e+08), exactly as ZSCORE / ZMSCORE / WITHSCORES have since 7.2, so any client parsing those parses this.
  • Listpack entries written before 7.2 and loaded from an RDB keep their stored "%.17g" text (unchanged by this PR).
  • The precision requirement from ZSCAN scores return gone wrong #2175 (never lose information for tiny values) is preserved; that regression test still passes and its denormal now prints 1e-322, matching ZSCORE.

Out of scope

RM_ScanKey (module scan callback) keeps its current formatting — it is a separate API surface and is left for a follow-up.

Tests

New ZSCAN scores match ZSCORE with encoding {listpack,skiplist} in tests/unit/scan.tcl (runs under both {standalone} and {cluster}): walks the full cursor with COUNT 50, asserts every ZSCAN score is byte-identical to ZSCORE, and pins 3.3, 1, -0.1, 1e-322, inf, -inf, the 25-char -123456789012345670000000, 1152921504606846976 and 1.2345678912345679e+8. Five of those assertions fail on current unstable's skiplist path. unit/scan passes under RESP2 and --force-resp3, and under an AddressSanitizer build.

Performance (secondary)

The measurements below use the original September 18 base and source hashes listed here. They predate #15822 and the September 29 merge; they do not measure the incremental gain over current unstable.

Per score, ld2string() ("%.17Lg" on a long double) costs several times what d2string() does (formatter microbenchmark, x86: 173 → 21 ns for 0, 195 → 67 ns for 0.645108), and a ZSCAN reply over a large sorted set is mostly score formatting once COUNT grows, so the change is visible end-to-end.

Setup: Redis unstable base 16e021b465fbbc73d5f070b4da5ce9f5ee4baea1 vs this change (head cd4d2720d9b1ed5d5173396fe1eb96581827ad72); the benchmarked commits are 9e19b01cc3096a809d45e41dd65b22a63059604c plus two empty commits on top of it (d9ebca1f244c90875f12b8a884182ef3100a0cf0, 1f038c32b3bb776c0f5ec5acfec6a9e54369b918, branch filipecosta90/redis:zscan-reply-d2string-bench) so there are three distinct samples with identical src/. memtier_benchmark specs from redis-benchmarks-specification, oss-standalone. Baseline = the run of the base commit plus the most recent earlier unstable runs on the same runner (n per cell; ARM ZSCAN rows 2026-08-27 → 09-17, HSCAN control from 06-08; x86 200K rows 2026-09-02 → 09-17, 1K row from 06-26, MATCH from 08-10, controls from 04-27). Medians with min–max. The four ZSCAN specs that reach the changed path (skiplist-encoded sorted sets) move and their ranges do not overlap; the three controls (listpack ZSCAN, HSCAN, ZREVRANGE WITHSCORES — code this PR does not touch) are flat.

arm-aws-m8g.metal-24xl (Graviton4):

spec unstable ops/s: median (n, min–max) this change: median (n=3, min–max) Δ
1key-zset-1K-elements-zscan (6-decimal scores → fpconv path) 122,513 (7, 108,622–123,630) 169,500 (166,276–171,707) +38.4%
1key-zset-200K-elements-zscan (COUNT 10; all scores 0 → integer fast path) 126,098 (7, 120,047–129,563) 171,963 (166,876–173,456) +36.4%
1key-zset-200K-elements-zscan-count-1000 (all scores 0) 2,941 (7, 2,907–2,994) 6,644 (6,429–6,654) +125.9%
1key-zset-1K-elements-zscan-match-count-100 (all scores 1; only MATCH hits formatted) 33,433 (7, 29,345–34,821) 40,938 (39,297–43,017) +22.4%
1key-zset-100-elements-zscan (listpack — control, code not touched) 113,465 (7, 112,364–113,876) 113,363 (112,319–113,604) -0.1%
1key-hash-hscan-1K-fields-10B-values (control) 194,251 (7, 193,085–196,941) 197,557 (197,144–201,772) +1.7%
1key-zset-1M-elements-zrevrange-withscores-5-elements-pipeline-10 (control) 941,360 (7, 915,645–983,409) 951,036 (939,177–961,832) +1.0%

x86-aws-m7i.metal-24xl-2 (Sapphire Rapids):

spec unstable ops/s: median (n, min–max) this change: median (n=3, min–max) Δ
1key-zset-1K-elements-zscan (6-decimal scores → fpconv path) 118,746 (7, 108,173–123,190) 144,035 (141,676–145,401) +21.3%
1key-zset-200K-elements-zscan (COUNT 10; all scores 0 → integer fast path) 124,794 (3, 124,701–124,867) 148,942 (147,478–149,964) +19.4%
1key-zset-200K-elements-zscan-count-1000 (all scores 0) 3,854 (3, 3,776–3,909) 6,870 (6,812–6,963) +78.3%
1key-zset-1K-elements-zscan-match-count-100 (all scores 1; only MATCH hits formatted) 25,302 (5, 24,614–26,296) 29,263 (28,401–29,498) +15.7%
1key-zset-100-elements-zscan (listpack — control, code not touched) 110,994 (7, 98,751–113,734) 110,582 (110,545–112,869) -0.4%
1key-hash-hscan-1K-fields-10B-values (control) 165,663 (4, 163,423–170,349) 168,363 (166,331–173,089) +1.6%
1key-zset-1M-elements-zrevrange-withscores-5-elements-pipeline-10 (control) 952,002 (6, 907,688–967,480) 944,455 (926,595–966,131) -0.8%

Top-down microarchitecture analysis (x86 Sapphire Rapids, profiler-instrumented runner, one run each, ZSCAN 200K / ZSCAN 1K): Frontend_Bound 25.8% → 21.6% / 24.6% → 19.1%, Retiring 35.7% → 28.5% / 33.4% → 27.6% — the long-double printf was an instruction- and fetch-heavy path; what remains of the now shorter call is proportionally more memory-bound (the dictScan pointer chasing). Throughput on that profiler-instrumented runner (n=1, counters running): +22.4% / +20.3%.

Supplementary, non-integral scores (laptop, server pinned to one core, memtier on separate cores, 20 s runs, arms alternated, n=3 each; corroborates the 1K rows above): 200K-member skiplist, scores i/7: ZSCAN k 0 COUNT 1000 1,164 (1,108–1,277) → 2,403 (2,402–2,572) ops/s (+106%); with all scores 0, 1,799 (1,789–1,942) → 3,333 (3,161–3,523) (+85%).


Note

Low Risk
Read-only reply formatting in one scan callback; behavior aligns with existing ZSCORE output and is covered by new regression tests.

Overview
ZSCAN on skiplist-encoded sorted sets now formats member scores with d2string() (same shortest round-trip path as ZSCORE / ZMSCORE), instead of ld2string(..., LD_STR_AUTO) in scanCallback()’s OBJ_ZSET branch. That removes the encoding-dependent mismatch (e.g. 3.3 vs 3.2999999999999998) introduced when client replies moved to fpconv in 7.2 but this scan path was left on "%.17Lg". The stack buffer shrinks from MAX_LONG_DOUBLE_CHARS to MAX_D2STRING_CHARS.

Score strings may differ in notation from the old skiplist ZSCAN output (fixed vs scientific exponents, long integers) while still parsing to the same double; listpack ZSCAN is unchanged (stored text). New scan.tcl tests walk ZSCAN for both listpack and skiplist encodings and assert every score is byte-identical to ZSCORE, including edge cases from #2175.

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

The skiplist ZSCAN reply (scanCallback's OBJ_ZSET branch) formatted the
emitted score with ld2string(..., LD_STR_AUTO): it widens the double to
long double and runs libc's "%.17Lg" for a value that is always a plain
double. It was the only client-reply ld2string() call fed a double; every
other client-facing score reply already uses d2string(): ZSCORE, ZMSCORE,
ZRANGE/ZRANGEBYSCORE/ZRANDMEMBER WITHSCORES, ZPOPMIN/ZPOPMAX and friends
via addReplyDouble(), and listpack-encoded sorted sets, which store the
d2string() form (or a listpack integer for integral scores) and echo it
back from ZSCAN as-is.

This is a leftover from redis#10587 (7.2), which moved d2string() and
addReplyDouble() to the shortest round-trip formatter but did not touch
this branch. Since then the same key has returned different score
strings from ZSCAN depending on its encoding, and skiplist ZSCAN has
disagreed with ZSCORE for the same member:

    ZADD k 3.3 m (with more than zset-max-listpack-entries members)
    ZSCORE k m      -> "3.3"
    ZSCAN k 0       -> "3.2999999999999998"

Switch the skiplist ZSCAN path to d2string() as well. The score string
becomes byte-identical to what ZSCORE returns, and to what listpack
ZSCAN returns for scores written since 7.2 (older listpack entries keep
their stored %.17g text): the same short round-trip form d2string()
produces everywhere else. The notation can differ from "%.17Lg" in
either direction (1.2345678912345679e+8 where it
printed 123456789.12345679, -123456789012345670000000 where it printed
-1.2345678901234567e+23), and integral scores of 18 or more digits up
to 2^62 (d2string()'s integer fast path) now print exactly (2^60 ->
1152921504606846976 instead of 1.152921504606847e+18), again matching
ZSCORE. All of these re-parse to the same double through ZADD, and AOF
rewrite has emitted the shortest round-trip form since 7.2. The stack
buffer shrinks from MAX_LONG_DOUBLE_CHARS to MAX_D2STRING_CHARS. It is
also cheaper: ZSCAN COUNT 1000 over a 200K-member skiplist sorted set
roughly doubles in throughput in a same-host A/B.

The module scan callback (RM_ScanKey) keeps its current formatting; it
is a separate API surface and is left for a follow-up.

Add a test asserting that ZSCAN scores are byte-identical to ZSCORE for
the same members, for both encodings, including denormal, infinite and
the longest-formatted values.
@codecov

codecov Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.63%. Comparing base (790d459) to head (2ab607f).
⚠️ Report is 33 commits behind head on unstable.

Additional details and impacted files
@@             Coverage Diff              @@
##           unstable   #15821      +/-   ##
============================================
- Coverage     77.80%   77.63%   -0.17%     
============================================
  Files           146      146              
  Lines         88016    88016              
============================================
- Hits          68477    68335     -142     
- Misses        19539    19681     +142     
Files with missing lines Coverage Δ
src/db.c 94.51% <100.00%> (-0.11%) ⬇️

... and 22 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

LGTM

Keep the borrowed-node reply path and queued-deletion coverage from redis#15822. Apply d2string score formatting in scanGenericCommand and preserve the score-consistency regression tests.
antirez pushed a commit to antirez/redis that referenced this pull request Oct 3, 2026
…s#15821)

Port the final PR delta relative to current unstable onto the B+tree patch stack. Keep d2string in the borrowed-node reply path from redis#15822 and adapt the encoding expectations to B+tree, as in Filipe’s integration branch.

(cherry picked from commit 2ab607f, relative to parent 2)
@sundb sundb added the release-notes indication that this issue needs to be mentioned in the release notes label Oct 17, 2026
@sundb

sundb commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator

Should we consider it a bug? should backport to the old versions?

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

@sundb I would treat this as a formatting consistency improvement, not a numeric correctness bug: 3.2999999999999998 and 3.3 parse to the same double. I would not backport it, since the reply text changes. Added this clarification to the description; the change should be release-noted.

@sundb
sundb merged commit d1a17fa into redis:unstable Oct 19, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-notes indication that this issue needs to be mentioned in the release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants