Repository navigation
ZSET B+ Tree PR 2: ordered index interface and full conversion - #3840
Conversation
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]>
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughThis PR introduces an ChangesOrderedIndex Abstraction, Skiplist Implementation, and ZSET Migration
🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
Codecov Report❌ Patch coverage is
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
🚀 New features to boost your workflow:
|
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]>
dbcb878 to
8b9797c
Compare
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]>
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]>
65711b1 to
4549222
Compare
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]>
Signed-off-by: Rain Valentine <[email protected]>
enjoy-binbin
left a comment
There was a problem hiding this comment.
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.)
|
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]>
|
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. |
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 callsorderedIndex*()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:
ordered_index.h(5 min) -- the full API contractskiplist_ordered_index.c(10 min) -- how skiplist implements each functiont_zset.cdiff (15 min) -- the call site migrationPatterns 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->backwardpointer 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 viaorderedIndexGetElementRaw(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 interfaceModified files (by category):
t_zset.corderedIndex*()callsobject.czslCreate→orderedIndexCreate, free/dismissrdb.c,aof.cgeo.c,sort.cdefrag.c,db.c,debug.c,server.c,lazyfree.c,module.corderedIndexGetElementRaw()skiplist.h,skiplist.ctest_ordered_index.cpp,ordered_index_test.hsort.tcl,zset.tclTesting
Scope boundaries
This PR does NOT: