Skip to content

ZSET B+ Tree PR 2: ordered index interface and full conversion - #3840

Merged
madolson merged 63 commits into
valkey-io:zset-btreefrom
rainsupreme:oi/pr2-interface-and-conversion
Jul 17, 2026
Merged

madolson merged 63 commits into
valkey-io:zset-btreefrom
rainsupreme:oi/pr2-interface-and-conversion

Conversation

@rainsupreme

@rainsupreme rainsupreme commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

This is the second PR for implementing B+ tree for ZSET (#3166)

Overview

The objective in this feature branch is to replace skiplist with a B+ tree.

Motivation

The skiplist is deeply coupled into ZSET operations — ~30 call sites directly access skiplist internals. This makes it impossible to experiment with alternative data structures (B+tree, adaptive index) without rewriting all of t_zset.c. This PR creates a clean boundary: ZSET code calls orderedIndex*() functions, and the backend (currently skiplist) implements them behind the interface.

The unit tests document and establish how skiplist or other implementations need to work for ZSET. In the next PR the same tests will prove that the B+ tree is a drop-in replacement.

Reviewing guide

Suggested reading order:

  1. ordered_index.h (5 min) -- the full API contract
  2. skiplist_ordered_index.c (10 min) -- how skiplist implements each function
  3. t_zset.c diff (15 min) -- the call site migration
  4. Other production code -- mostly mechanical, same patterns repeated
  5. Unit tests, integration tests -- most of the added code is automated testing

Patterns to watch for in the migration:

Most call sites are mechanical renames (zslInsert → orderedIndexInsert), but two changes affect how code reads:

  • Iterator-based traversal: The old code walked the skiplist via node->level[0].forward / node->backward pointer chasing. The new code uses an opaque iterator (orderedIndexInitIterator + orderedIndexNext/orderedIndexPrev), with seek functions for positioned starts. This makes traversal loops slightly more verbose but backend-independent.

  • Opaque elements: Elements were previously accessed as node->ele (an sds). They're now accessed via orderedIndexGetElementRaw(item, &ptr, &len) which returns a raw (ptr, len) pair. This is intentional -- it avoids baking the assumption that elements are sds into the interface, which is needed for the B+ tree backend where elements are stored in a packed format.

What changes

New files:

  • ordered_index.h / ordered_index.c — public API (create, insert, delete, update, iterate, seek, range-delete, pop, get-by-index, get-first/last, defrag, memory)
  • skiplist_ordered_index.h / skiplist_ordered_index.c — skiplist backend implementing the interface

Modified files (by category):

Category Files What changed
ZSET commands t_zset.c All skiplist access replaced with orderedIndex*() calls
Object lifecycle object.c zslCreate → orderedIndexCreate, free/dismiss
Persistence rdb.c, aof.c Iteration via ordered-index iterator
Other commands geo.c, sort.c Iterator + element accessor migration
Infrastructure defrag.c, db.c, debug.c, server.c, lazyfree.c, module.c Element access via orderedIndexGetElementRaw()
Skiplist internals skiplist.h, skiplist.c New iterator API, accessor functions, node creation takes raw ptr+len
Tests test_ordered_index.cpp, ordered_index_test.h 358 parameterized unit tests, C-style (no STL)
Integration tests sort.tcl, zset.tcl New tests forcing skiplist encoding

Testing

  • 358 unit tests (79 new)
  • 337 integration tests (11 new)
  • All pass under AddressSanitizer
  • CI green

Scope boundaries

This PR does NOT:

  • Add a new backend (that's the next PR)
  • Change any runtime behavior or output
  • Modify the skiplist algorithm itself
  • Touch the listpack (small-ZSET) encoding path

zslIsInLexRange called zslGetNodeElement on the tail node before
checking if it was NULL, crashing on an empty skiplist. Move the
NULL checks before the element access.

Same issue existed for the head node check.

Signed-off-by: Rain Valentine <[email protected]>
Add the OrderedIndex abstraction layer for sorted set data structures:

- ordered_index.h: compile-time dispatched interface with inline wrappers
  for lifecycle, modification, query, iteration, memory, defrag, and debug
- skiplist_ordered_index.h/c: skiplist backend implementation
  - Thin wrappers casting between opaque types and zskiplist/zskiplistNode
  - Range deletion by score, rank, and lex with on_delete callback
  - Count range by score and lex
  - Cursor-based batched defrag scan
  - Structural integrity verification
- ordered_index_test.h: parameterized C++ test fixture for future backends
- test_ordered_index.cpp: comprehensive unit tests
  - Deterministic tests for all interface operations
  - Randomized property tests (insert, traverse, delete, update, pop)
  - On-delete callback tests for range deletion
  - Hashtable consistency tests for range deletion

No existing call sites are converted — the interface is only exercised
by the new unit tests. Call-site conversion follows in subsequent PRs.

Signed-off-by: Rain Valentine <[email protected]>
- Remove static inline wrappers; add ordered_index.c with regular
  functions that delegate to the backend (LTO handles inlining)
- Add comprehensive header comment to ordered_index.h explaining what
  an OrderedIndex is, its relationship to the companion hashtable, and
  why it does not enforce uniqueness
- Add per-function doc comments for all API functions
- Add header comment to skiplist_ordered_index.h
- Rename 'idx' parameter to 'oi' throughout to avoid confusion with
  numeric array indices
- Drop orderedIndexInsert(sds) convenience wrapper; rename
  orderedIndexInsertRaw to orderedIndexInsert (callers pass ptr+len)
- Remove debug functions (skiplistGetHeight, skiplistVerifyIntegrity)
  from ordered_index.h public API; they remain in
  skiplist_ordered_index.h for unit tests and DEBUG command
- Fix include ordering: skiplist_ordered_index.h now includes
  ordered_index.h for type visibility

Feedback from JimB123 on PR valkey-io#3552.

Signed-off-by: Rain Valentine <[email protected]>
Fix two bugs in the skiplist OrderedIndex backend:

1. zslDetachNode: use zslCompareNodes (score-based search) instead of
   pointer equality (x->level[i].forward != node). Pointer equality
   overshoots at higher skiplist levels because higher-level forward
   pointers skip over intermediate nodes. The score-based search
   correctly stops at the predecessor at each level.

2. skiplistDeleteRangeByScore/Lex/Rank: when an on_delete callback is
   provided, the callback receives ownership of the item (per the API
   contract in ordered_index.h). The backend must not call zslFreeNode
   after invoking the callback — that would double-free.

Also fix a stale 2-arg next() call in ordered_index_test.h that didn't
get updated when the iterator API changed to pointer-return style.

Signed-off-by: Rain Valentine <[email protected]>
- Replace 'backend' with 'implementation' throughout
- Fix header comment claiming only skiplist exists
- Add consistent min_ex/max_ex documentation on all range functions
- Soften iterator init comment to describe behavior not mandate
- Improve memory estimation and defrag descriptions
- Rename zslDeleteNode -> zslUnlinkNode (detach semantics)
- Remove unnecessary section header in skiplist.c
- Add SPDX copyright header to skiplist_ordered_index.c
- Remove spurious empty lines in skiplist_ordered_index.c
- Fix test header to say 'active implementation' not 'active backend'

Signed-off-by: Rain Valentine <[email protected]>
- skiplist.c: reformat one-liner if statements (clang-format-check)
- test_ordered_index.cpp: use NEG_INF/POS_INF instead of bare INFINITY
  to avoid -Wdouble-promotion on macOS where INFINITY is float
- test_ordered_index.cpp: use TEST_ASSERT_SCORE_EQ for score comparisons
  to avoid -Wfloat-equal from gtest ASSERT_EQ on doubles
- test_ordered_index.cpp: free items in on_delete callbacks to fix
  LeakSanitizer failures (callback takes ownership per API contract)

Signed-off-by: Rain Valentine <[email protected]>
Signed-off-by: Rain Valentine <[email protected]>
- Expand 3 one-liner if/else blocks in skiplist_ordered_index.c to
  satisfy clang-format-18
- Use TEST_ASSERT_SCORE_EQ instead of ASSERT_EQ for double comparison
  in RandomizedForwardBackwardMirror test (gtest 1.17 on macOS triggers
  -Werror,-Wfloat-equal)

Signed-off-by: Rain Valentine <[email protected]>
Convert all sorted set command implementations in t_zset.c to use the
OrderedIndex abstraction instead of direct skiplist calls.

Changes:
- zset struct: zskiplist *zsl -> OrderedIndex *oi (in server.h)
- All zsl* calls in t_zset.c replaced with orderedIndex* equivalents
- Range iteration converted to OrderedIndex iterator API
- Range deletion uses on_delete callback (zsetIndexDeleteCallback)
- orderedIndexCountScoreRange/LexRange replaces rank-difference counting
- orderedIndexGetElementRaw used for element access (cast to sds where
  needed for hashtable compatibility)
- Other files (geo.c, defrag.c, module.c, etc.) use (zskiplist *) cast
  on zs->oi until converted in subsequent PRs

Bug fixes:
- zslDetachNode: fixed search to use zslCompareNodes (score-based)
  instead of pointer equality which overshoots at higher skiplist levels
- skiplistDeleteRangeBy*: fixed double-free when on_delete callback is
  provided (backend no longer frees after invoking callback)

ZUNION/ZINTER/ZDIFF detached-item path still uses raw skiplist calls
with casts — will be converted in a follow-up commit.

All 326 zset integration tests pass.

Signed-off-by: Rain Valentine <[email protected]>
Convert the ZUNION SET_OP_UNION path from raw skiplist calls to the
OrderedIndex detached-item API:
- zslCreateNode + zslRandomLevel -> orderedIndexCreateDetached
- Direct node->score mutation -> orderedIndexDetachedSetScore
- zslInsertNode bulk insert -> orderedIndexInsertDetached

Convert the zuiNext/zuiInitIterator skiplist path from raw backward
pointer traversal to OrderedIndex iterator (orderedIndexPrev).

After this commit, t_zset.c has zero references to zskiplistNode,
zskiplist, or any zsl* function (except range-parsing helpers which
operate on zrangespec/zlexrangespec, not the data structure).

All 326 integration tests and all unit tests pass.

Signed-off-by: Rain Valentine <[email protected]>
Convert module.c, object.c, rdb.c, aof.c, geo.c, sort.c, debug.c,
db.c, server.c, lazyfree.c, defrag.c, and valkey-check-rdb.c to use
the OrderedIndex abstraction instead of direct skiplist access.

Add orderedIndexItemNext/Prev to the interface for item-level
navigation (needed by module API which stores current position
across calls).

After this commit, zero raw skiplist references remain outside of:
- skiplist.c/skiplist.h (the implementation)
- skiplist_ordered_index.c (the backend adapter)
- defrag.c (skiplist-internal node relocation, inherently impl-specific)
- t_zset.c range utilities (zslParseRange, zslValueGteMin, etc. operate
  on zrangespec structs, not the skiplist data structure)

Signed-off-by: Rain Valentine <[email protected]>
Signed-off-by: Rain Valentine <[email protected]>
Add integration tests exercising code paths that changed during the
OrderedIndex abstraction, specifically for skiplist-encoded sorted sets.

tests/unit/sort.tcl:
- SORT BY nosort with skiplist encoding (asc, desc)
- SORT BY nosort + LIMIT with skiplist encoding
- SORT with BY pattern on skiplist encoding

tests/unit/type/zset.tcl:
- ZUNIONSTORE with skiplist inputs (basic + WEIGHTS)
- ZINTERSTORE with skiplist inputs (basic + AGGREGATE MIN)
- ZRANGEBYSCORE with LIMIT on skiplist sets
- ZRANGEBYLEX with LIMIT on skiplist sets
- ZPOPMIN/ZPOPMAX on skiplist sets (single + multiple)
- ZPOPMIN/ZPOPMAX empty skiplist set
- ZCOUNT on skiplist sets
- ZLEXCOUNT on skiplist sets

Signed-off-by: Rain Valentine <[email protected]>
Signed-off-by: Rain Valentine <[email protected]>
The ZUNIONSTORE/ZINTERSTORE tests use multi-key operations (DEL src1
src2 dst, ZUNIONSTORE dst 2 src1 src2) that hit different hash slots
in cluster mode, causing CROSSSLOT errors. Skip these tests in
external-cluster CI.

Signed-off-by: Rain Valentine <[email protected]>
@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a6150130-1112-4a54-b04a-6ffd74c84712

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR introduces an OrderedIndex abstraction layer for Valkey's sorted set implementation, decoupling ZSET operations from the skiplist backend via a new public API. A skiplist-backed implementation and refactored skiplist layer support this abstraction, enabling future substitution of alternative ordered-index backends. All ZSET operations across persistence, commands, introspection, and modules are migrated to use the new ordered-index APIs.

Changes

OrderedIndex Abstraction, Skiplist Implementation, and ZSET Migration

Layer / File(s) Summary
OrderedIndex abstraction layer and skiplist backend
src/ordered_index.h, src/ordered_index.c, src/skiplist_ordered_index.h, src/skiplist_ordered_index.c, cmake/Modules/SourceFiles.cmake, src/Makefile
New OrderedIndex public API defines lifecycle, mutation (insert/delete/update/pop), range deletion by score/index/lex, query (length/index/score/count), iterator, and memory management operations. Skiplist backend (skiplist_ordered_index.c) implements all operations via existing skiplist primitives. Build files updated to compile new source files.
Skiplist refactoring to support OrderedIndex
src/skiplist.h, src/skiplist.c
Skiplist node creation now accepts raw element pointer+length instead of SDS. zslDeleteNode replaced by zslUnlinkNode for pointer-stable detachment. Range comparison helpers (zslValueGteMin, zslValueLteMax, sdscmplex, zslLexValue*) replaced by shared zsetScore* and zsetLex* helpers. New iterator API added: zslIter, zslInitIterator, zslNext, zslPrev, zslSeekTo*. New accessors: zslGetFirst, zslGetScore, zslDetachNode.
ZSET struct change and shared range utility functions
src/server.h
zset struct member changed from zskiplist *zsl to OrderedIndex *oi. Added shared range comparison functions zsetScoreGteMin, zsetScoreLteMax, zsetLexCompare, zsetLexGteMin, zsetLexLteMax for reuse across encodings.
ZSET object creation, freeing, and memory management
src/object.c
ZSET creation switches from zslCreate() to orderedIndexCreate(). Freeing uses orderedIndexFree(). Memory dismissal and estimation use orderedIndexDismissMemory() and orderedIndexEstimateMemory().
ZSET encoding conversions and length operations
src/t_zset.c (conversion section)
zsetConvertAndExpand now creates ordered-index and populates it from listpack elements. Reverse conversion pops ordered-index items into listpack. Length queries use orderedIndexLength().
ZSET score queries, ranking, and basic mutations
src/t_zset.c (score/add/del/rank section)
zsetScore retrieves via orderedIndexGetScore(). zsetAdd inserts via orderedIndexInsert() and updates via orderedIndexUpdateScore(). zsetDel removes via new zsetRemoveFromIndex() helper. zsetRank and zsetDup use ordered-index queries and iteration.
ZSET range deletion and range iteration commands
src/t_zset.c (range deletion and range commands section)
zremrangeGenericCommand and range commands (zrangebyrank, zrangebyscore, zrangebylex, zcount, zlexcount) migrate to ordered-index delete-range APIs and ordered-index iterators with seek/next/prev for traversal. Raw element and score access via ordered-index accessors.
ZSET set algebra operations
src/t_zset.c (zunion/zinter/zdiff section)
ZUNION, ZINTER, ZDIFF now insert results via orderedIndexInsert() and iterate/emit via ordered-index traversal. Accumulator logic uses detached ordered-index items and orderedIndexUpdateScore().
ZSET random sampling, POP, and utility operations
src/t_zset.c (zpop and zrandmember section)
genericZpopCommand fetches endpoints via orderedIndexGetByIndex(). zrandmemberWithCountCommand uses ordered-index raw element access and scores. zsetHashtableGetMaxElementLength uses orderedIndexGetElementRaw().
RDB and AOF persistence for ZSET
src/rdb.c, src/aof.c
RDB save uses orderedIndexLength() and iterator to walk elements. RDB load inserts via orderedIndexInsert(). AOF rewrite uses orderedIndexGetElementRaw() and orderedIndexGetScore().
GEO and SORT commands for ZSET
src/geo.c, src/sort.c
GEO range scanning uses ordered-index iterator and seek. SORT command uses ordered-index iterator and element accessor instead of skiplist traversal.
Infrastructure: defragmentation, scanning, hashing, and introspection
src/defrag.c, src/db.c, src/debug.c, src/server.c, src/lazyfree.c, src/module.c, src/valkey-check-rdb.c
Defragmentation uses orderedIndexScanDefrag and orderedIndexDefragInternals. Hashtable scanning extracts elements via orderedIndexGetElementRaw() and scores via orderedIndexGetScore(). Debug digest uses ordered-index iteration. Hashing uses raw element extraction. Lazy-free effort uses orderedIndexLength(). Module API iterators use ordered-index iteration. RDB validation uses ordered-index element/score accessors.
Test infrastructure and unit tests for OrderedIndex
src/unit/ordered_index_test.h, src/unit/test_ordered_index.cpp
New test API abstraction OrderedIndexTestApi with concrete SkiplistOrderedIndex adapter. Comprehensive unit tests cover creation, insertion, deletion, range operations, seeking, iteration, callbacks, memory estimation, integrity verification, randomized property tests, and edge cases.
Integration tests for ZSET with skiplist encoding
tests/unit/sort.tcl, tests/unit/type/zset.tcl
New tests force skiplist encoding and verify SORT (by nosort, with LIMIT, by pattern), ZUNIONSTORE/ZINTERSTORE, ZRANGEBYSCORE/ZREVRANGEBYSCORE with LIMIT, ZRANGEBYLEX/ZREVRANGEBYLEX with LIMIT, ZPOPMIN/ZPOPMAX, ZCOUNT, and ZLEXCOUNT correctness.

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Suggested reviewers

  • zuiderkwast
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.12% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: introducing an OrderedIndex interface abstraction and completing the conversion of ZSET call sites to use it.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The description clearly matches the changes: an OrderedIndex interface, skiplist backend, call-site migration, and added tests.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented May 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.50694% with 78 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.10%. Comparing base (ea14eeb) to head (71d05ba).

Files with missing lines Patch % Lines
src/module.c 0.00% 38 Missing ⚠️
src/ordered_index.c 94.38% 16 Missing ⚠️
src/skiplist.c 85.26% 14 Missing ⚠️
src/t_zset.c 97.36% 6 Missing ⚠️
src/db.c 72.72% 3 Missing ⚠️
src/unit/test_ordered_index.cpp 99.93% 1 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff               @@
##           zset-btree    #3840      +/-   ##
==============================================
+ Coverage       76.92%   77.10%   +0.17%     
==============================================
  Files             164      166       +2     
  Lines           80707    82577    +1870     
==============================================
+ Hits            62082    63668    +1586     
- Misses          18625    18909     +284     
Files with missing lines Coverage Δ
src/aof.c 80.40% <100.00%> (+0.09%) ⬆️
src/debug.c 55.24% <100.00%> (+0.07%) ⬆️
src/defrag.c 81.32% <100.00%> (+0.19%) ⬆️
src/geo.c 94.35% <100.00%> (+0.03%) ⬆️
src/lazyfree.c 88.38% <100.00%> (ø)
src/object.c 92.36% <100.00%> (+3.79%) ⬆️
src/rdb.c 77.44% <100.00%> (+0.46%) ⬆️
src/server.c 89.56% <100.00%> (+0.04%) ⬆️
src/server.h 100.00% <ø> (ø)
src/skiplist.h 100.00% <ø> (ø)
... and 8 more

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

@rainsupreme
rainsupreme marked this pull request as ready for review May 26, 2026 21:50
@rainsupreme
rainsupreme marked this pull request as draft May 26, 2026 21:57
orderedIndexGetElementRaw returns an opaque pointer+length pair. Several
call sites incorrectly cast the result to sds and called sdslen() on it,
violating the interface abstraction.

Fix all category 1 violations (pure abstraction correctness):

t_zset.c:
- zsetTypeRandomElement: use ele_len_tmp directly
- zsetHashtableGetMaxElementLength: use ele_len_tmp directly
- ZUNION element tracking: use ele_len_tmp directly
- ZRANDMEMBER reply (2 sites): use addReplyBulkCBuffer(c, ptr, len)

db.c:
- hashtableScanCallback: track zset_ele_len for pattern matching,
  use sdsnewlen(ptr, len) instead of sdsdup((sds)ptr) for the copy

Signed-off-by: Rain Valentine <[email protected]>
@rainsupreme
rainsupreme force-pushed the oi/pr2-interface-and-conversion branch from dbcb878 to 8b9797c Compare May 26, 2026 22:27
Replace the skiplist-internal defrag code (activeDefragZsetNode, which
manually walked skiplist levels to relink pointers) with the interface
method orderedIndexScanDefrag. The backend handles node relocation
internally; the callback just updates the hashtable pointer via
hashtableReplaceReallocatedEntry.

This removes the last skiplist dependency from defrag.c:
- Remove #include "skiplist.h"
- Remove zslUpdateNode helper
- Remove activeDefragZsetNode (40 lines of skiplist internals)
- Replace with 5-line defragZsetNodeCallback using the interface

Signed-off-by: Rain Valentine <[email protected]>
No code outside skiplist.c/skiplist_ordered_index.c references zskiplist
directly anymore. The forward declaration in server.h is dead code.

Signed-off-by: Rain Valentine <[email protected]>
Match the orderedIndexNext/Prev interface convention: return the node
pointer (NULL = end) instead of bool + out-param. This simplifies the
adapter to a direct cast.

Signed-off-by: Rain Valentine <[email protected]>
Replace the raw oi->level access (which dereferences an opaque type)
with a call to skiplistGetHeight via a local extern declaration. This
makes the dependency explicit and compiles correctly regardless of
UNSAFE_CRASH_REPORT.

Signed-off-by: Rain Valentine <[email protected]>
No bool types remain in the header after zslNext/zslPrev signature
change.

Signed-off-by: Rain Valentine <[email protected]>
Remove the early NULL check and do-while pattern. A plain while loop
naturally short-circuits when orderedIndexNext returns NULL, producing
the same return value (0) with less code.

Signed-off-by: Rain Valentine <[email protected]>
Replace all comment references to 'skiplist' with 'ordered index' to
reflect the current abstraction. The skiplist.h include remains because
t_zset.c uses range utility functions (zslParseRange, zslValueGteMin,
etc.) that operate on zrangespec structs.

Signed-off-by: Rain Valentine <[email protected]>
Move zset range comparison functions out of skiplist.c into t_zset.c
and rename with zset prefix since they are generic utilities used by
both listpack and ordered index encodings:

  zslValueGteMin  -> zsetScoreGteMin
  zslValueLteMax  -> zsetScoreLteMax
  sdscmplex       -> zsetLexCompare
  zslLexValueGteMin -> zsetLexGteMin
  zslLexValueLteMax -> zsetLexLteMax

Declarations move from skiplist.h to server.h. This removes the need
for t_zset.c, geo.c, and module.c to include skiplist.h.

Signed-off-by: Rain Valentine <[email protected]>
Match the declaration in the header file.

Signed-off-by: Rain Valentine <[email protected]>
Eliminates a temporary sds allocation+free in the ordered index to
listpack conversion path. The function only needs a pointer and length
for lpAppend/lpInsertString.

Signed-off-by: Rain Valentine <[email protected]>
Distinguish item operations from index operations by naming convention:
- orderedIndexGetElementRaw -> orderedIndexItemGetElement
- orderedIndexGetScore      -> orderedIndexItemGetScore
- orderedIndexFreeItem      -> orderedIndexItemFree
- orderedIndexDetachedSetScore -> orderedIndexItemSetScore
- orderedIndexCreateDetached   -> orderedIndexItemCreate
- orderedIndexInsertDetached   -> orderedIndexInsertItem

Functions that operate on an OrderedIndexItem now use the
orderedIndexItem* prefix, making it clear at the call site whether
a function operates on the container or an element.

Signed-off-by: Rain Valentine <[email protected]>
Use consistent language across SeekToIndex, SeekToScoreRange, and
SeekToLexRange: all position a cursor between items, with next/prev
returning the item on either side of that position.

Signed-off-by: Rain Valentine <[email protected]>
Change orderedIndexSeekToIndex(N) to position the cursor before rank N,
so that next() returns rank N and prev() returns rank N-1. This matches
the cursor model already used by SeekToScoreRange and SeekToLexRange,
where next() returns the first item at the specified offset.

Previously SeekToIndex positioned after rank N (next returned N+1, prev
returned N), forcing callers to subtract 1 for forward traversal. The
new model eliminates that adjustment and matches Java's ListIterator(N).

Callers updated:
- sort.c: SeekToIndex(start) instead of SeekToIndex(start-1) for forward
- t_zset.c: same forward fix; reverse uses SeekToIndex(len-start)

Signed-off-by: Rain Valentine <[email protected]>
orderedIndexNext/Prev results are stored into key->u.zset.current
(void *), so they cannot be declared const. Only the read-only 'ln'
variable (loaded from current for GetScore/GetElement) is const.

Signed-off-by: Rain Valentine <[email protected]>
@rainsupreme
rainsupreme force-pushed the oi/pr2-interface-and-conversion branch from 65711b1 to 4549222 Compare June 24, 2026 22:13
When two items have identical (score, element), the skiplist's delete
traversal stops at the first match in traversal order. Deleting a
specific pointer that isn't the first match hits a serverAssert.

Fix: delete via GetFirst (which returns whichever is at rank 0) rather
than assuming a specific insert-returned pointer is directly deletable
when exact duplicates exist.

Signed-off-by: Rain Valentine <[email protected]>
@rainsupreme
rainsupreme requested review from eifrah-aws and enjoy-binbin and removed request for eifrah-aws June 25, 2026 21:27
@rainsupreme rainsupreme moved this from Todo to Needs Review in Valkey 9.2 Jul 8, 2026
@enjoy-binbin enjoy-binbin added the run-extra-tests Run extra tests on this PR (Runs all tests from daily except valgrind and RESP) label Jul 9, 2026

@enjoy-binbin enjoy-binbin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I didn't review every single line, but i did looked at the parts that interest me. The code LGTM overall, minor comments inline. I think we can accept it and push it further, please let me know if you'd like to merge (using squash merge, right?), we can push forward with the third PR as soon as possible.

Also, the top comment might need updating (skiplist_ordered_index is no longer exists). And btw, i noticed that all the function comments are currently in ordered_index.h. Could we also keep a copy in ordered_index.c? (It’s easier to read when comments and implementation are together, though this isn't a blocker.)

Comment thread src/debug.c Resolved
Comment thread src/ordered_index.h Resolved
Comment thread src/ordered_index.c Resolved
Comment thread src/ordered_index.c Resolved
@ranshid

ranshid commented Jul 13, 2026

Copy link
Copy Markdown
Member

Overall LGTM. @rainsupreme can you only followup on the last review comments by @enjoy-binbin ?

The extern declaration in serverLogObjectDebugInfo referenced
orderedIndexGetDepth, which does not exist (the function is
orderedIndexGetHeight). This block is debug-only conditionally compiled
code, so the mismatch never surfaced as a link error.

Signed-off-by: Rain Valentine <[email protected]>
With index == ULONG_MAX, index + 1 wraps to rank 0 and
zslGetElementByRank returns the header sentinel (traversed == 0 matches
at the header), handing callers a garbage item instead of NULL. Guard
with an explicit length check.

Signed-off-by: Rain Valentine <[email protected]>
orderedIndexScanDefrag called defragfn (which frees the old node) and
only then walked the skiplist to build the update[] predecessor array.
During that walk, forward pointers still referencing the freed node were
dereferenced (score and element reads) — a use-after-free read. It went
unnoticed because active defrag only runs under jemalloc, while
sanitizer builds use libc and never exercise the path.

Build the predecessor array before calling defragfn, while the node is
still valid. The walk now stops on pointer identity with <= ordering,
which also finds the exact immediate predecessor when equal
(score, element) duplicates are present.

The search now runs for every scanned node instead of only reallocated
ones; that is the cost of not reading freed memory.

Signed-off-by: Rain Valentine <[email protected]>
@rainsupreme

Copy link
Copy Markdown
Contributor Author

@ranshid Made the updates!

ccov failure is unrelated flake (I opened issue #4153 for the flaky job)

@madolson

Copy link
Copy Markdown
Member

Based on Ran's comment, this seems ready to merge so Rain can mark the next one as ready for review. Anything else we can flow into the next PR.

@madolson
madolson merged commit 0e23ce9 into valkey-io:zset-btree Jul 17, 2026
26 of 27 checks passed
@github-project-automation github-project-automation Bot moved this from Needs Review to Merged in Valkey 9.2 Jul 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-extra-tests Run extra tests on this PR (Runs all tests from daily except valgrind and RESP)

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

6 participants