Skip to content

ZSCAN: avoid temporary member and score allocations - #15822

Merged
moticless merged 2 commits into
redis:unstablefrom
filipecosta90:zscan-no-temp-alloc
Sep 29, 2026
Merged

moticless merged 2 commits into
redis:unstablefrom
filipecosta90:zscan-no-temp-alloc

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Skiplist ZSCAN currently allocates temporary copies of each returned member and formatted score. Collect existing skiplist-node pointers and emit replies directly, removing two allocations/frees and one vector entry per member.

Nodes remain live throughout the synchronous command, and reply buffers copy the returned bytes. Score formatting (ld2string), cursor/MATCH behavior, and RESP2/RESP3 reply types are unchanged.

Median throughput versus unstable, three runs per side on AWS m7i (x86) and m8g (ARM), standalone:

Workload x86 ARM
ZSCAN 200K, COUNT 1000 +36.08%† +16.03%†
ZSCAN 200K, COUNT 10 +5.27%† +9.30%†
ZSCAN 1K, fractional scores +3.63%† +2.03%†
ZSCAN 1K, MATCH COUNT 100 +5.42% +7.93%
Listpack ZSCAN control +0.27% -0.35%
HSCAN control -2.97% -0.49%
ZREVRANGE WITHSCORES control -2.87%† -2.40%

† Non-overlapping observed ranges; other ranges overlap. The x86 ZREVRANGE control shows a small slowdown. ZSCAN workloads repeat cursor zero; the 200K sets have 13-byte members and all-zero scores.

Measured 22f8568a8f094d198057530b5504b3aa9a99f98e against unstable 16e021b465fbbc73d5f070b4da5ce9f5ee4baea1, with identical-source repeats. The final patch only refines a comment and test ordering relative to the measured code.

Validation: 398 SCAN/sorted-set tests, 54 ASAN tests, and 24 byte-exact member/score comparisons across RESP2/RESP3. Adds a large binary-reply test using MULTI/EXEC to delete the set before flushing the reply.


Note

Medium Risk
Touches core SCAN reply assembly for skiplist sorted sets; behavior must stay identical while relying on synchronous reply copying when the key can be deleted before the buffer is sent (e.g. MULTI/EXEC).

Overview
Skiplist ZSCAN no longer allocates temporary member/score strings during collection. scanCallback stores zskiplistNode* in the scan vector, drops the vector’s SDS free hook, and scanGenericCommand formats members and scores only when building the client reply (so the output buffer owns the bytes).

A new scan.tcl test runs ZSCAN inside MULTI/EXEC with DEL on the key before the reply is flushed, guarding against use-after-free when many members exceed the stack vector capacity.

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

Collect skiplist node pointers and emit members and scores directly while building the reply. Nodes remain live for the duration of this synchronous command, and the output buffer owns the returned bytes before the command finishes.

Keep the existing ld2string score formatting, cursor traversal and reply types. Add a focused test covering a large binary reply followed by queued deletion.
@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.61%. Comparing base (16e021b) to head (2a2503f).
⚠️ Report is 19 commits behind head on unstable.

Additional details and impacted files
@@             Coverage Diff              @@
##           unstable   #15822      +/-   ##
============================================
+ Coverage     77.44%   77.61%   +0.17%     
============================================
  Files           146      146              
  Lines         87986    88005      +19     
============================================
+ Hits          68138    68306     +168     
+ Misses        19848    19699     -149     
Files with missing lines Coverage Δ
src/db.c 94.51% <100.00%> (-0.10%) ⬇️

... and 28 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

Comment thread src/db.c Resolved
Co-authored-by: Moti Cohen <[email protected]>
@moticless
moticless merged commit 62f115f into redis:unstable Sep 29, 2026
19 checks passed
@fcostaoliveira
fcostaoliveira deleted the zscan-no-temp-alloc branch September 29, 2026 13:42
fcostaoliveira added a commit to filipecosta90/redis that referenced this pull request Sep 29, 2026
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
Skiplist ZSCAN reuses member and score bytes from live nodes
instead of allocating temporary copies for each reply.
Preserves cursor/MATCH behavior, score formatting and RESP
types; reply buffers retain their own copies.

Median throughput gains: 16–36% for large COUNT 1000 scans,
2–9% for other ZSCAN workloads. Controls were mostly flat;
x86 ZREVRANGE showed a small slowdown. Benchmarks used three
runs per side on AWS m7i and m8g.

Validated with 398 scan/sorted-set tests, 54 ASAN tests and
24 byte-exact RESP2/RESP3 comparisons. Added a binary-reply
test that deletes the set in MULTI/EXEC before flushing.

(cherry picked from commit 62f115f)
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 pushed a commit that referenced this pull request Oct 19, 2026
…#15821)

### 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 #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.
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.

3 participants