Skip to content

[Draft] ZSET (ordered index) interface and UTs for zskiplist - preparation to replace zskiplist with fbtree - #3552

Closed
rainsupreme wants to merge 13 commits into
valkey-io:unstablefrom
rainsupreme:ordered-index-unstable-port
Closed

rainsupreme wants to merge 13 commits into
valkey-io:unstablefrom
rainsupreme:ordered-index-unstable-port

Conversation

@rainsupreme

@rainsupreme rainsupreme commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

🚧 Currently a draft, but feel free to take a look. I think it's complete but I'm self-reviewing first. 🚧

This is the first PR that lays the foundation for #3166. I add an interface and unit tests to codify current zskiplist behavior. I also refactored so that across Valkey we respect the interface abstraction and don't leak implementation details.

The next PR planned will introduce the new data structure (fbtree) and use it to implement this interface. Unit tests will run on both zskiplist and fbtree implementations to ensure behavior is the same.

@codecov

codecov Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.08554% with 77 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.81%. Comparing base (5abf79e) to head (3ef0d62).
⚠️ Report is 5 commits behind head on unstable.

Files with missing lines Patch % Lines
src/module.c 0.00% 45 Missing ⚠️
src/skiplist_ordered_index.c 94.32% 16 Missing ⚠️
src/t_zset.c 97.75% 8 Missing ⚠️
src/rdb.c 81.25% 3 Missing ⚠️
src/unit/ordered_index_test.h 95.16% 3 Missing ⚠️
src/db.c 92.30% 1 Missing ⚠️
src/unit/test_ordered_index.cpp 99.94% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##           unstable    #3552      +/-   ##
============================================
+ Coverage     76.34%   76.81%   +0.47%     
============================================
  Files           159      164       +5     
  Lines         80045    82236    +2191     
============================================
+ Hits          61107    63172    +2065     
- Misses        18938    19064     +126     
Files with missing lines Coverage Δ
src/aof.c 80.33% <100.00%> (-0.05%) ⬇️
src/debug.c 54.91% <100.00%> (+0.07%) ⬆️
src/defrag.c 81.29% <100.00%> (-0.97%) ⬇️
src/geo.c 95.24% <100.00%> (+0.03%) ⬆️
src/lazyfree.c 88.38% <100.00%> (ø)
src/object.c 92.33% <100.00%> (+3.75%) ⬆️
src/ordered_index.h 100.00% <100.00%> (ø)
src/server.c 89.48% <ø> (-0.01%) ⬇️
src/server.h 100.00% <100.00%> (ø)
src/skiplist_internal.h 100.00% <100.00%> (ø)
... and 9 more

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

Cherry-picked from zset-ordered-index-interface branch.
Resolved hashtable API conflicts (no key_len on unstable).

Signed-off-by: Rain Valentine <[email protected]>
Cherry-picked from zset-ordered-index-interface branch.

Signed-off-by: Rain Valentine <[email protected]>
Cherry-picked from zset-ordered-index-interface branch.
Resolved hashtable API conflict (no key_len on unstable).

Signed-off-by: Rain Valentine <[email protected]>
…nterface where possible

Adapted from zset-ordered-index-interface branch. Key differences from
source branch: hashtable callbacks use unstable API signatures (no key_len
parameters), zsetHashtableType moved to t_zset.c with entryGetKey returning
SDS element directly.

Signed-off-by: Rain Valentine <[email protected]>
Signed-off-by: Rain Valentine <[email protected]>
Signed-off-by: Rain Valentine <[email protected]>
…ed in OrderedIndexItem for incoming fbtree implementation, misc cleanup

Signed-off-by: Rain Valentine <[email protected]>
Signed-off-by: Rain Valentine <[email protected]>
Signed-off-by: Rain Valentine <[email protected]>
@rainsupreme
rainsupreme force-pushed the ordered-index-unstable-port branch from 727028a to 3ef0d62 Compare April 24, 2026 22:32
@rainsupreme
rainsupreme requested a review from JimB123 April 28, 2026 21:22
@rainsupreme

Copy link
Copy Markdown
Contributor Author

@JimB123 no need to review this whole thing - I'm breaking it down into a series of 6 PRs, but what do you think of the interface?

Comment thread src/ordered_index.h
@@ -0,0 +1,187 @@
#ifndef ORDERED_INDEX_H

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 love to see good documentation in the .h file. This is the API.

Other's have argued that in Valkey, a lot of the documentation should be in the .c file. However we don't have a .c file here - so that's a non-issue.

Please:

  1. Add a good header comment. A big block comment at the top which explains what an "ordered index" is. Talk about the high level concepts of what this data structure provides (but don't explain how it is implemented).
  2. Please add a comment on each of the API functions (below). For each function, give a few lines explaining what it does, and what the parameters represent.

Comment thread src/ordered_index.h
#include "skiplist_ordered_index.h"

/* Lifecycle */
static inline OrderedIndex *orderedIndexCreate(void) {

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.

As I commented in the recent review on dict, I think we should avoid the use of static inline. In the past, this was a good technique to improve performance. But now, with LTO, the benefit isn't there. And though in the code below, each function resolves to a single call to another function - that might not always be the case. It also serves as an example to others - who might not use static inline so carefully.

When misused, this technique can cause code bloat, increasing pressure on L1 cache. (and when used properly provides no benefit over LTO)

@rainsupreme rainsupreme May 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The intent here was to have compile-time dispatch for the interface, such that these are reduced to the implementation function calls they wrap at compile time. This is intended as a more performant alternative to run-time dispatch via a vtable.

That said, you make a good point about setting examples and establishing norms. the same functions in a .c file should get cleaned up by LTO similarly. non-LTO builds will have a small penalty.

Comment thread src/ordered_index.h
}

/* Modification */
static inline OrderedIndexItem *orderedIndexInsertRaw(OrderedIndex *idx, double score, const char *ele, size_t len) {

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.

At this point of reading the header, I have no established mental context for score or ele or why we'd need len.

I have no mental context for "raw" or what it implies to "insert raw". (Why not just "insert"?)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is fair. There are two insert methods, one that takes sds, and this one takes (char*, length), thus being raw data without any header or such attached. I think I'll remove the convenience sds one and just have insert.

Comment thread src/ordered_index.h
return skiplistCreate();
}

static inline void orderedIndexFree(OrderedIndex *idx) {

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.

Using idx as for the OrderedIndex is likely to prove confusing to readers. idx typically indicates a numeric index into an ordered structure (like an array or list index).

Are we sure we want to call this data structure an "ordered index"? If we've already said it's ordered, what's the purpose of the word "index"? Is it an "ordered sds set"? I'm not exactly sure.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think OrderedIndex is a good name. We could also call it OrderedCollection perhaps, or maybe ZsetOrderedIndex because it is specific to zset. It isn't really a set itself because it doesn't enforce uniqueness - the hashtable is used for that.

idx is not the best though - maybe oi instead?

Comment thread src/ordered_index.h
skiplistFreeItem(item);
}

static inline OrderedIndexItem *orderedIndexCreateDetached(double score, const char *ele, size_t len) {

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.

create detached? ???

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

a nice that isn't inserted/attached to a set. this is used for some multi-set operations where we sum scores for all occurrences of an item in a given list of two sets (or more iirc). this avoids the delete+update cost each time we update score for an item that's part of a set.

so that's the intention and reason. could make it cleaner maybe, or use a workaround to avoid this in the interface. I'll give it some thought.

@@ -0,0 +1,54 @@
#ifndef SKIPLIST_ORDERED_INDEX_H

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.

Big header comment. What is this? What's it for? High level concepts?

#include "sds.h"

/* Lifecycle */
OrderedIndex *skiplistCreate(void);

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.

Compilation issue. OrderedIndex is undefined here unless header file ordering is constrained in the calling code (bad).

void skiplistFree(OrderedIndex *idx);

/* Modification */
OrderedIndexItem *skiplistInsert(OrderedIndex *idx, double score, const char *ele, size_t len);

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.

OrderedIndexItem is undefined here. What does this represent from a caller's perspective. How do I use an OrderedIndexItem?

size_t skiplistEstimateMemory(OrderedIndex *idx, size_t sample_size);

/* Defrag */
OrderedIndex *skiplistDefragInternals(OrderedIndex *idx, void *(*defragfn)(void *));

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.

Why exposed?

Comment on lines +50 to +52
/* Debug */
int skiplistGetHeight(OrderedIndex *idx);
int skiplistVerifyIntegrity(OrderedIndex *idx, char *errmsg, size_t errmsg_len);

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.

No need to expose debug functions in the .h (API).

Comment thread src/ordered_index.h

#include "sds.h"

/* Opaque types for ordered index, positions, and iterators */

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.

General comment. This data structure is ordered by a double. It's very specific to data which has a double and a "lexical" string.

Could we use a generic "comparitor" function so that ANY orderable data can be stored? Would this add value?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

as we discussed in person, the data structure assumes that items are contiguous lexically ordered (binary safe) sds strings, and by giving up the arbitrary comparison flexibility it becomes a different class of data structure with higher performance. we can access those gains if we can come up with a transform operation between our items (score double, element string) and the collection's native type (SDS string), which is perhaps the main "trick" of the feature I'm implementing. :)

rainsupreme added a commit to rainsupreme/valkey that referenced this pull request May 13, 2026
- 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]>
rainsupreme added a commit to rainsupreme/valkey that referenced this pull request May 13, 2026
- 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]>
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.

2 participants