Add Roaring Bitmap support (issue #1270)
Add Roaring Bitmap support (issue #1270)
Resolves #1270.
Summary
Adds a Roaring Bitmaps extension to Garnet that introduces a new compressed
bitmap object type plus four R.* RESP commands. Implemented entirely as a
host extension in main/GarnetServer/Extensions/RoaringBitmap/ — zero
changes to libs/server/ — so this is a clean, reviewable foundation that
can be deepened in follow-up PRs.
Why Roaring?
A naive uint32 bitmap is 512 MiB. Roaring partitions the universe into
65 536 chunks of 65 536 bits and represents each chunk as either:
- Array container — sorted
ushort[], used while a chunk holds ≤ 4 096 set bits (~2·countbytes). - Bitmap container —
ulong[1024](8 KiB exactly), used once a chunk exceeds the threshold.
Empty chunks consume zero memory. Chunks promote (array → bitmap) and demote (bitmap → array) automatically as cardinality changes.
Commands
| Command | Description |
|---|---|
R.SETBIT key offset value |
Set bit at offset ∈ [0, 2³²-1] to 0/1. Returns previous bit. |
R.GETBIT key offset |
Returns bit at offset. 0 for missing keys. |
R.BITCOUNT key |
Population count. 0 for missing keys. |
R.BITPOS key bit [from] |
First bit (0/1) at or after from. -1 if none. |
Docs: website/docs/commands/roaring-bitmap.md.
Design notes
- The data structure (
RoaringBitmap.cs,Containers/*) is a pure C# library with no Garnet dependencies → independently unit-testable. RoaringBitmapObject(CustomObjectBase) wraps the structure and tracks size deltas viabitmap.ByteSizefor the per-object size accounting.- All four commands are registered as
CommandType.ReadModifyWrite. The reads (R.GETBIT/R.BITCOUNT/R.BITPOS) do not mutate state, but the RMW path is required so thatNeedInitialUpdateis invoked on missing keys — the framework'sReadpath simply returns nil otherwise. Missing-key responses (0/-1) are written fromNeedInitialUpdatewhich then returnsfalseto decline key creation. NeedInitialUpdateerror paths usewriter.WriteError(...)+return falserather thanAbortWithErrorMessage(which returnstrueand would cause the framework to proceed intoInitialUpdater/Updater, double-writing the response and corrupting the protocol stream).
Tests
| Suite | Count | Status |
|---|---|---|
RoaringBitmapDataTests (pure data structure) |
27 | ✅ Pass |
RespRoaringBitmapTests (RESP integration via SE.Redis) |
14 | ✅ Pass |
Coverage highlights:
- Empty bitmap, single bit, idempotent set/clear.
- Promotion threshold (
4096↔4097) and demotion across both directions. - 100 K random ops vs
HashSet<uint>oracle. - Boundary offsets
0,65535,65536,2³¹,2³²-1. - Serialize → deserialize round-trip equality (empty / sparse / dense / mixed).
- RESP-level:
R.SETBIT/R.GETBITparity with oracle,R.BITCOUNT,R.BITPOS(set / unset /fromoffset), large offsets, persistence across restart, concurrent setbits from multiple clients, error paths (bad offset, bad bit, bad value, wrong arity), and the two-store key separation property.
$ dotnet test test\Garnet.test\Garnet.test.csproj -c Debug -f net8.0 \
--filter "FullyQualifiedName~RoaringBitmap" --nologo
Passed! - Failed: 0, Passed: 43, Skipped: 0, Total: 43
Known limitations (intentional v1 scope)
- Run container is not implemented. Adds ~30% extra compression on contiguous ranges; the array/bitmap pair captures the bulk of real-world savings.
R.BITOP AND/OR/XOR/NOTis not exposed. The data structure supports these natively; only command surface is needed.- Empty-key removal: clearing the last bit leaves an empty bitmap object
rather than removing the key. This is a property of the custom-object
framework's tombstone path (
output.HasRemoveKeyis honoured only on the built-in path) and is best fixed inlibs/server/Storage/Functions/ObjectStorein a separate PR.
Files
main/GarnetServer/Extensions/RoaringBitmap/
Containers/IContainer.cs
Containers/ArrayContainer.cs
Containers/BitmapContainer.cs
RoaringBitmap.cs
RoaringBitmapObject.cs
RoaringBitmapCommands.cs
main/GarnetServer/Program.cs (registration only)
test/Garnet.test/RoaringBitmapDataTests.cs (27 tests)
test/Garnet.test/RespRoaringBitmapTests.cs (14 tests)
website/docs/commands/roaring-bitmap.md (docs)
Thanks for the thorough review! Pushed 65ac9f1d4 addressing each comment. Summary:
| # | File / line | Resolution |
|---|---|---|
| 1 | RoaringBitmapDataTests.cs:175 — bits[actual0] index |
Applied. (int)actual0 cast plus an explicit actual0 >= 0 guard. (Note: array indexers in C# do accept long per the language spec, which is why the original compiled — but the cast makes intent obvious and removes the runtime OverflowException risk.) |
| 2 | RoaringBitmap.cs:189 — ByteSize doc/impl mismatch |
Applied. Updated the XML doc to state that the per-entry SortedDictionary node overhead is included (the implementation was already correct; only the comment was misleading). |
| 3 | RoaringBitmapCommands.cs:51 — RSetBit.NeedInitialUpdate always returns true |
Applied. NeedInitialUpdate now validates offset and value against a copy of the ObjectInput (it's a struct, so var validation = input; snapshots it without disturbing what Updater sees). On bad input it writes the error and returns false, so a malformed R.SETBIT no longer creates an empty tombstone-style key. |
| 4 | RoaringBitmapCommands.cs:6 — using Garnet.common; flagged as unused |
Disagreed (with evidence). RespMemoryWriter lives in Garnet.common, and removing the using produces 8 × CS0246: The type or namespace name 'RespMemoryWriter' could not be found errors across all NeedInitialUpdate / Updater / Reader signatures. Restored. |
| 5 | RoaringBitmapObject.cs:29 — inconsistent default-ctor Size |
Applied. Default ctor now sets this.Size = ObjectOverhead + bitmap.ByteSize, matching the deserialized constructor so freshly-created and round-tripped objects report identical memory baselines and ByteSize-based mutation deltas don't double-count the empty-bitmap baseline. |
All 27 data-structure tests + 14 RESP integration tests still pass:
Passed! - Failed: 0, Passed: 43, Skipped: 0, Total: 43
@microsoft-github-policy-service agree company="Microsoft"
@microsoft-github-policy-service agree company="Microsoft"
@microsoft-github-policy-service agree company="Microsoft"
Thanks for your contribution! This extension is interesting, but instead of putting it in main, we should place it in https://github.com/microsoft/garnet/tree/main/modules (where e.g., GarnetJSON is kept) so that it is not bundled by default in the server.
Also, main is closed to new features, so we would request that you retarget your PR to the dev (v2) branch.
Thanks for the review! Both points addressed in the latest force-push:
- Moved extension into
modules/RoaringBitmap/— mirrorsGarnetJSON: newGarnetRoaringBitmap.csproj, newRoaringBitmapModule : ModuleBaseentry point that registers the factory +R.SETBIT/R.GETBIT/R.BITCOUNT/R.BITPOS, namespace renamedGarnet.Extensions.RoaringBitmap→GarnetRoaringBitmapto avoid the namespace/class collision, wired intoGarnet.slnxandtest/Garnet.test/Garnet.test.csproj. Nothing inmain/GarnetServerreferences it anymore — it is no longer bundled by default. - Retargeted PR base to
dev. Branch was rebased onto currentupstream/devand theCustomObjectFunctions/CustomObjectBaseoverrides updated to the newscoped ReadOnlySpan<byte>andHeapMemorySizeAPIs.
Local validation: all 43 RoaringBitmap tests (29 data + 14 RESP) pass on net8.0, dotnet format is clean.
Thank you for your reviews Will address all these in next PR
Updated — all review comments addressed
Force-pushed 47d62b29b (rebased onto current dev from dd3e2dabb).
Highlights:
RoaringBitmapchunk store refactored fromSortedDictionary<ushort, IContainer>to two parallel arrays (ushort[] highKeys+IContainer[] containers) withMemoryExtensions.BinarySearch—BitPosnow skips to the first relevant chunk in O(log N).Add/Remove/SetBit/GetBit/BitPos.bitmigrated frominttobool(RESP int↔bool bridging stays inRoaringBitmapObject).RoaringBitmapnow implementsIEnumerable<uint>.ArrayContainerandBitmapContainerrewritten usingSpan<T>.IndexOfAnyExcept(0)/LastIndexOfAnyExcept(0),MemoryExtensions.BinarySearch,MemoryMarshal.AsBytesfor bulk serialize, andStream.ReadExactlyfor bulk deserialize.EnsureCapacityadopts the geometric1,2,4,…,4096growth pattern viaBitOperations.RoundUpToPowerOf2.- All unreachable / illegal-state guards removed; impossible
BitmapContainer.cardinality == 0/cardinality == 1branches gone. Readeroverrides added onRGetBit/RBitCount/RBitPosas the existing-key fast path;NeedInitialUpdateretained for typed missing-key responses (with an inline architectural note flagging the question for @badrishc).var(IDE0007) sweep across all changed files;ArgumentNullException.ThrowIfNullswapped in everywhere; style nits resolved.ContainerKind.Runremoved (unused).Microsoft.VisualStudio.Threading.Analyzersadded to the module csproj.- Docs corrected — module is loaded manually via
MODULE LOADCS, not wired into the default host. - New
ConcurrentReadsWhileWrites_StayConsistentintegration test (4 reader tasks running 5000R.GETBIT/R.BITCOUNTops concurrently with a bit-toggling writer).
Build: 0 warnings, 0 errors.
Tests: 44/44 Roaring tests passing on both net8.0 and net10.0.
Two threads contain open questions for @badrishc about whether the read commands can be expressed as pure Reader ops (avoiding the ReadModifyWrite registration that NeedInitialUpdate requires for missing-key responses). I've replied to each thread inline and the code carries a matching architectural comment — happy to refactor if you confirm a cleaner pattern.
@badrishc — two open architectural questions on this PR I'd love your read on. Both relate to how a read-only custom object command should emit a Redis-compatible missing-key response (0 / -1) without materializing an empty object:
- R.GETBIT / R.BITCOUNT — https://github.com/microsoft/garnet/pull/1741#discussion_r3174777004
- R.BITPOS — https://github.com/microsoft/garnet/pull/1741#discussion_r3174780061
TL;DR: the three read commands are currently registered as ReadModifyWrite because NeedInitialUpdate is the only hook that lets us return a typed missing-key response. Reader is wired in as the existing-key fast path. Threads are left unresolved.
On a second review of this, we have concerns about the write commands being registered as RMW. That implies reads will proceed sequentially rather than in parallel.
Unfortunately there's no existing way to customize the RESP response of a custom read command today, you always get a null.
I'm going to take a look at fixing that in general (and moving existing extensions to use it if necessary). Once that's merged you can update this PR to use the new infra and catch up to main (now that dev has been merged in we no longer need to target dev). I'll try and get that done tomorrow, or shortly after the holiday weekend.
Thank you. Sounds good @kevin-montrose will look for updates on this from you following week.
Infra changes for this are pending review here: #1820
Note that linked PR has merged.
Thanks @kevin-montrose will push new changes this week.
Pushed an update (12a9ce2) addressing the open review feedback and re-syncing with main:
Addressed @kevin-montrose's review (both threads resolved):
- R.GETBIT / R.BITCOUNT / R.BITPOS no longer use the
NeedInitialUpdate/Updater(RMW-on-read) workaround. They're nowCommandType.Readand flow throughReaderfor existing keys and the newNotFoundcallback (#1820) for missing keys, so a read never creates a key. - R.SETBIT (a genuine write) intentionally keeps validation in
NeedInitialUpdateso a malformed offset/value is rejected before an empty object is allocated.
Re-synced with main:
- Merged latest
main(resolved the test-project relocationtest/Garnet.test->test/standalone/Garnet.test). PR is mergeable again. - Dropped the Allure test attributes (present on
devbut notmain) so the tests build againstmain.
Verification:
- All 44 Roaring Bitmap tests pass (net10.0).
- Full solution builds clean (0 warnings / 0 errors).
dotnet formatclean.- Diff vs
mainis purely additive (newmodules/RoaringBitmap+ tests; only single-line solution/test-project wiring touched), no changes tolibs/or core, so no breaking changes.