Skip to content

Compute bitmap intersection cardinality without materializing the result - #117478

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
anandheritage:bitmap-cardinality-avoid-materialization
Sep 4, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
anandheritage:bitmap-cardinality-avoid-materialization

Conversation

@anandheritage

@anandheritage anandheritage commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Improved performance of bitmapAndCardinality, bitmapOrCardinality, bitmapXorCardinality, bitmapAndnotCardinality and bitmapHasAny by computing the result directly instead of first materializing the intersection bitmap.


Problem

rb_and_cardinality answered "how large is the intersection" by constructing the entire intersection bitmap, reading its cardinality and discarding it:

std::shared_ptr<RoaringBitmap> new_rb = r1.isSmall() ? r1.getNewRoaringBitmapFromSmall() : r1.roaring_bitmap;
ret = (*roaring_bitmap & *new_rb).cardinality();

rb_intersect used the same construct to answer a boolean question:

if ((*roaring_bitmap & *r1.roaring_bitmap).cardinality() > 0)
    return 1;

operator& allocates and populates a fresh container for every overlapping container pair. In the boolean case it also removes any possibility of an early exit, because the whole intersection is built before the first element is examined.

CRoaring already provides roaring_bitmap_and_cardinality and roaring_bitmap_intersect for exactly these two questions. Both walk the container pairs and accumulate or short-circuit without allocating or writing a result structure.

Change

  • rb_and_cardinality now calls and_cardinality().
  • rb_intersect now calls intersect(), which stops at the first shared element.
  • rb_and_cardinality previously promoted a small set to a full Roaring bitmap whenever the larger operand came first, then ran a complete intersection over it. It now iterates the small side against contains(). This mirrors what rb_intersect already did for the same operand shape, and matches the operand swap that FunctionsBitmap.h already performs for bitmapAnd for the same reason:
// bitmapAnd(RoaringBitMap, SmallSet) is slower than bitmapAnd(SmallSet, RoaringBitMap), so we can exchange the position of two arguments for the speed

Five SQL functions are affected: bitmapAndCardinality and bitmapHasAny directly, and bitmapOrCardinality, bitmapXorCardinality and bitmapAndnotCardinality transitively, since all three derive their result from rb_and_cardinality by inclusion-exclusion.

Scope: 32-bit element types

RoaringBitmapWithSmallSet selects roaring::Roaring64Map when sizeof(T) >= 8. Roaring64Map exposes neither and_cardinality nor intersect (still true on CRoaring master), so UInt64 and Int64 bitmaps keep the previous implementation behind if constexpr (sizeof(T) < 8). Adding those routines to Roaring64Map would be a separate upstream change.

Both routines are read-only, so results and the serialization format are unchanged.

Testing

tests/queries/0_stateless/05055_bitmap_cardinality_intersect_paths.sql covers every combination of small-set and Roaring representation, including the Large x Small operand order, which previously had no coverage for these functions.

The assertions are differential: each cardinality function is checked against bitmapAnd combined with bitmapCardinality, which reaches the same answer through rb_and followed by size() and shares no code with the paths changed here. Every assertion prints 1 when the two agree. Covered:

  • Small x Small, Small x Large, Large x Small (with and without overlap), Large x Large (overlapping and disjoint)
  • Operands spread across many 16-bit containers, with and without a shared element, so the container walk is exercised both with and without an early exit
  • Operand-order commutativity for the commutative functions
  • Exact expected cardinalities, pinning the arithmetic independently of the reference path
  • UInt64 including values above the 32-bit range, plus Int32 and Int16, so the Roaring64Map fallback and the signed dispatch are both exercised
  • Empty operands on either side

tests/performance/bitmap_cardinality.xml measures the changed paths with operand construction hoisted into scalar subqueries, so the measured loop contains only the operation under test. It covers dense (bitset container) and sparse (array container) operands, bitmapOrCardinality reaching rb_and_cardinality indirectly, the Large x Small operand order, and two bitmapHasAny shapes: one where the operands share their lowest element so the predicate can exit immediately, and one where both operands occupy the same container keys but share no element, which is the worst case with no early exit available.


Workflow [PR]
Sync PR [sync-upstream/pr/117478]

bitmapAndCardinality built the full intersection bitmap, counted it and threw it
away, and bitmapHasAny used the same construct to answer a boolean question.
CRoaring provides roaring_bitmap_and_cardinality and roaring_bitmap_intersect,
which reach the answer without allocating or populating a result, and the latter
can stop at the first shared element. Use them for 32-bit element types.

bitmapOrCardinality, bitmapXorCardinality and bitmapAndnotCardinality all derive
their answer from rb_and_cardinality by inclusion-exclusion, so they benefit too.

rb_and_cardinality also promoted a small set to a Roaring bitmap whenever the
larger operand came first, then ran a full intersection. It now iterates the
small side against contains(), matching what rb_intersect already did and the
operand swap that FunctionsBitmap.h already performs for bitmapAnd.

UInt64 and Int64 bitmaps are backed by Roaring64Map, which exposes neither
routine, so those instantiations keep the previous implementation.
@anandheritage

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov
Kindly help me get this reviewd.
Thanks !

@cv4g cv4g added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors labels Sep 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f16bd91]

Summary: ❌

job_name test_name status info comment
Integration tests (arm_binary, distributed plan, 1/4) FAIL
test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR replaces materialized bitmap intersections with direct CRoaring and_cardinality / intersect calls for 32-bit-backed bitmaps, keeps the existing Roaring64Map fallback for 64-bit element types, and adds broad stateless coverage plus a repaired microbenchmark. The core code path and correctness tests look reasonable, but I cannot approve a Performance Improvement PR yet because the current discussion still does not include before/after results from the new benchmark, and the changelog entry currently overstates the scope of the speedup.

PR Metadata

Changelog category Performance Improvement matches the change. A changelog entry is required.

💡 The current changelog entry reads like all bitmap element widths benefit, but UInt64 / Int64 still take the old materializing path. Suggested replacement:

Improves performance of bitmapAndCardinality, bitmapOrCardinality, bitmapXorCardinality, bitmapAndnotCardinality, and bitmapHasAny for 32-bit and smaller bitmap element types by computing intersection results without materializing an intermediate bitmap.

Missing context / blind spots
  • ⚠️ There is no local clickhouse binary or build in this workspace, so I could not run 05055_bitmap_cardinality_intersect_paths or tests/performance/bitmap_cardinality.xml locally. Focused local before/after benchmark numbers, or the pending PR performance job, would close that gap.
Tests
  • ⚠️ tests/performance/bitmap_cardinality.xml now exercises the non-constant execution path correctly, but the PR still does not show benchmark results against master. For a Performance Improvement PR, please attach focused before/after numbers from this benchmark, at least one dense bitmapAndCardinality case and the two bitmapHasAny shapes, or explain why a smaller subset is representative.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: attach before/after results from the new benchmark against master so the claimed performance improvement is demonstrated. While updating the PR text, narrow the changelog entry to 32-bit and smaller bitmap element types so it matches the actual scope.

LLVM Coverage Report

Measured on commit f16bd91.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f16bd9153 with master 7466e9341 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

23 translation units recompiled, 238 s compile time in total, 23 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 32 not_sure 1315 1385 +5.3% 0.0001
⚠️ 33 not_sure 1217 1291 +6.1% <0.0001
⚠️ 34 not_sure 1204 1270 +5.5% <0.0001

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: bffc9825-9621-4453-b258-447d5a1178f3
  • MIRAI run: 196ede72-49d5-4c5e-9bcd-a512f68a591c
  • PR check IDs:
    • clickbench_1057383_1788456120
    • clickbench_1057495_1788456130
    • clickbench_1057597_1788456144
    • tpch_adapted_1_official_1057712_1788456219
    • tpch_adapted_1_official_1057824_1788456257
    • tpch_adapted_1_official_1057954_1788456334

@anandheritage

Copy link
Copy Markdown
Contributor Author

@cv4g
Let me know if all looks good to merge.
cc: @alexey-milovidov

@PedroTadim PedroTadim self-assigned this Sep 3, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@anandheritage can you show the performance improvement you got?

Both operands of every measured call were scalar subqueries, so every argument
was constant. bitmapAndCardinality and bitmapHasAny use the default
implementation for constants, which evaluates the call once on a single row and
broadcasts the result as a constant, so the loop measured the sum over a
precomputed value rather than rb_and_cardinality or rb_intersect. The CI
performance comparison accordingly reported every query within noise, between
-2.7% and +3.3%.

Wrap one operand of each call in materialize(). That leaves the arguments not
all constant, so defaultImplementationForConstantArguments declines and
executeImpl runs over the real row count. The other operand stays constant and
is not expanded, because the function already reads both arguments through
is_column_const. materialize() is cheap here: it converts a constant
ColumnAggregateFunction to a full column via replicate, which copies the
aggregate state pointer per row and does not copy the bitmap.

Build the operands once into a Memory table instead of in scalar subqueries, so
that construction is no longer part of the measured time. It previously
dominated it: the dense query spent about 65 ms of its 67 ms building two
3-million-element bitmaps. Iteration counts are raised to keep each run in the
100 ms range now that the loop does the work, well below the 2 second per-run
limit, and max_threads is pinned to 1 to match bitmap_contains.xml and
bitmap_array_element.xml.

The operand shapes are unchanged: dense bitset containers, sparse array
containers, bitmapOrCardinality reaching rb_and_cardinality by
inclusion-exclusion, the Large x Small order, and the two bitmapHasAny cases
with and without an available early exit.
@CLAassistant

CLAassistant commented Sep 3, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@PedroTadim

Copy link
Copy Markdown
Member

@anandheritage please sign the CLA

@anandheritage

Copy link
Copy Markdown
Contributor Author

@anandheritage can you show the performance improvement you got?

@PedroTadim here are the numbers from the perf comparison on f16bd91 (client time, bitmap_cardinality, all Strong confidence):

old (ms) new (ms) diff speedup arch
60.5 3.5 -94.1% 17.3x arm
48.5 4.2 -91.3% 11.5x amd
61.0 21.2 -65.2% 2.9x amd
61.3 21.6 -64.8% 2.8x amd
9.0 3.5 -60.5% 2.6x arm
73.4 29.4 -59.9% 2.5x arm
73.5 29.9 -59.3% 2.5x arm
8.6 3.6 -57.4% 2.4x amd
120.8 70.9 -41.4% 1.7x amd

Full dashboard: https://performance.ci.clickhouse.com/runs/pr-117478-f16bd915376ca86311467bcc49d5723204ed3d19

These are all nine of the above-threshold speedups in the run. The one strong slowdown reported is an INSERT INTO codec_mon_UInt64_ZSTD query on arm, which doesn't touch this code path.

@anandheritage

Copy link
Copy Markdown
Contributor Author

@anandheritage can you show the performance improvement you got?

@PedroTadim here are the numbers from the perf comparison on f16bd91 (client time, bitmap_cardinality, all Strong confidence):

old (ms) new (ms) diff speedup arch
60.5 3.5 -94.1% 17.3x arm
48.5 4.2 -91.3% 11.5x amd
61.0 21.2 -65.2% 2.9x amd
61.3 21.6 -64.8% 2.8x amd
9.0 3.5 -60.5% 2.6x arm
73.4 29.4 -59.9% 2.5x arm
73.5 29.9 -59.3% 2.5x arm
8.6 3.6 -57.4% 2.4x amd
120.8 70.9 -41.4% 1.7x amd
Full dashboard: https://performance.ci.clickhouse.com/runs/pr-117478-f16bd915376ca86311467bcc49d5723204ed3d19

These are all nine of the above-threshold speedups in the run. The one strong slowdown reported is an INSERT INTO codec_mon_UInt64_ZSTD query on arm, which doesn't touch this code path.

@PedroTadim Let me know if any more details are required or we are good to merge ?

@PedroTadim
PedroTadim added this pull request to the merge queue Sep 4, 2026
Merged via the queue into ClickHouse:master with commit 3c9f065 Sep 4, 2026
172 of 174 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants