Skip to content

LowCardinality merge optimization - #114870

Open
bobrik wants to merge 10 commits into
ClickHouse:masterfrom
bobrik:ivan/low-cardinality-speedup
Open

bobrik wants to merge 10 commits into
ClickHouse:masterfrom
bobrik:ivan/low-cardinality-speedup

Conversation

@bobrik

@bobrik bobrik commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

I'm using ClickHouse to store continuous profiling data. ClickHouse itself is subject to said continuous profiling.

There are some bits that I found to be slower than I would've expected, for example this part:

image

The optimizations here are very much AI assisted, based on continuous profiling data. The added benchmarks were used as a guiding star. Each optimization step is a separate commit that can be measured with benchmarks from the first one.

Here are the benchmarks measuring CPU time in ms (WARNING: STALE, see #114870 (comment)):

Benchmark Baseline Sparse mapper Dictionary sharing Final translation Total change
MapSparseOnly/1 9.390 5.807 5.774 5.789 38.4% faster
MapSparseOnly/2 6.621 3.473 3.462 3.463 47.7% faster
MapSparseOnly/4 4.334 2.350 2.341 2.345 45.9% faster
EmptyDestinationDifferentDictionary/1 33.517 29.829 0.031 0.031 99.9% faster
EmptyDestinationDifferentDictionary/2 10.902 7.682 0.031 0.032 99.7% faster
EmptyDestinationDifferentDictionary/4 6.727 4.739 0.031 0.031 99.5% faster
NonEmptyDisjointDictionaries/1 35.233 31.186 30.859 28.318 19.6% faster
NonEmptyDisjointDictionaries/2 24.382 21.184 21.260 20.849 14.5% faster
NonEmptyDisjointDictionaries/4 7.027 4.952 4.936 4.793 31.8% faster
NonEmptyFullyOverlappingDictionaries/1 35.518 29.366 29.150 26.934 24.2% faster
NonEmptyFullyOverlappingDictionaries/2 17.478 14.356 14.301 13.907 20.4% faster
NonEmptyFullyOverlappingDictionaries/4 6.548 4.463 4.462 4.498 31.3% faster
NonEmptyPartiallyOverlapping/1 38.009 32.130 31.700 29.155 23.3% faster
NonEmptyPartiallyOverlapping/2 18.220 15.154 15.033 14.470 20.6% faster
NonEmptyPartiallyOverlapping/4 6.600 4.533 4.515 4.453 32.5% faster
SameDictionary/1 0.034 0.034 0.034 0.035 3.1% slower
SameDictionary/2 0.034 0.034 0.034 0.034 0.6% slower
SameDictionary/4 0.034 0.034 0.034 0.034 1.3% slower
SmallDenseDictionary 1.055 1.034 1.037 1.058 0.3% slower

For the last step we went through a few iterations to land on something that does not regress partial overlaps:

Benchmark Before translation Direct Batched Typed Compact/final
Disjoint/1 30.859 41.588 41.034 40.121 28.318
Disjoint/2 21.260 21.929 22.000 21.464 20.849
Disjoint/4 4.936 5.271 5.208 4.967 4.793
Fully overlapping/1 29.150 35.935 35.592 35.128 26.934
Fully overlapping/2 14.301 8.392 8.353 7.896 13.907
Fully overlapping/4 4.462 4.853 4.818 4.628 4.498
Partially overlapping/1 31.700 38.288 37.867 37.095 29.155
Partially overlapping/2 15.033 8.610 8.440 8.034 14.470
Partially overlapping/4 4.515 4.856 4.848 4.608 4.453

You can see that the wins here are not amazing compared to the rest (just 8%), and there's a fair bit of code. I would understand if you would like to drop it or split in a separate PR.

For the query benchmark added in the first commit, comparing the first commit against the las tone:

  • Disjoint dictionaries: 3.431s -> 2.704s, 21.2% faster (1.27x).
  • Fully overlapping dictionaries: 2.121s -> 1.643s, 22.5% faster (1.29x).

This change removes the long standing TODO from @KochetovNicolai:

/// TODO: Support native insertion from other unique column. It will help to avoid null map creation.

cc @nickitat, @Avogar, @nihalzp, @alexey-milovidov

Changelog category (leave one):

  • Performance Improvement

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

LowCardinality merge optimizations.


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

@thevar1able thevar1able added the can be tested Allows running workflows for external contributors label Aug 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bf15783]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-26fa) FAIL cidb
Stress test (arm_msan) FAIL
Logical error: The metadata stream of AlignStreams ended before all data stream rows were matched (STID: 0250-329b) FAIL cidb
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) ERROR

AI Review

Summary

This PR rewrites ColumnLowCardinality::insertRangeFrom to add a sparse-dictionary translation path, reuse hash-map sizing across repeated LowCardinality rewrites, and speed up ARRAY JOIN / ordered-read workloads that repeatedly merge independently encoded dictionaries. The sparse translation fixes earlier width and bounds issues and the targeted coverage is much better now, but the empty-destination sharing shortcut still weakens the old contract in two important cases, so I would request changes before merge.

PR Metadata
  • Changelog category: Performance Improvement matches the code.
  • Changelog entry: required, but LowCardinality merge optimizations. is too vague. It does not tell users which LowCardinality path changed or where they should expect a benefit. Suggested replacement: Improved performance of merging LowCardinality columns with independently encoded dictionaries during insertRangeFrom, including ordered reads and ARRAY JOIN on arrays of LowCardinality values.
Findings

⚠️ Majors

  • [src/Columns/ColumnLowCardinality.cpp:411-416] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/114870#discussion_r3786653265] The empty-destination fast path now aliases any shared, structurally compatible source dictionary without proving that the copied range already uses every key. ColumnLowCardinality::cut / filter / permute keep is_shared = true while shrinking only the indexes, and SerializationLowCardinality.cpp:717-721 constructs the same kind of shared source during readback, so a partial copy can keep a huge unused dictionary alive and force index width from source_dictionary.size() - 1 even though the old path compacted to the copied keys. Suggested fix: only call setSharedDictionary when [start, start + length) is already minimal for the source dictionary; otherwise stay on the compaction / rewrite path.
  • [src/Columns/ColumnLowCardinality.cpp:411-416] The same sharing branch still skips the float canonicalization that uniqueInsertRangeFrom and uniqueInsertRangeFromDictionary do for -0.0 and NaN payloads. Shared sources are real in SerializationLowCardinality.cpp:717-721 and ArrowColumnToCHColumn.cpp:2411-2413, so insertRangeFrom into an empty destination now changes hash / serialization behavior based only on whether the source dictionary happened to be shared. Suggested fix: disable this shortcut for floating inner types, or prove and canonicalize the source dictionary before sharing it.
Tests
  • ⚠️ Add a regression test where the source is a shared non-minimal slice (for example a cut() of a larger LowCardinality column, or the serialization-style shared global dictionary) and verify that inserting into an empty destination does not retain unused keys or a wider-than-necessary index type.
  • ⚠️ Add the same scenario for LowCardinality(Float64) with -0.0 and multiple NaN payloads, and assert that the empty-destination fast path preserves the old canonical representation or is disabled for floats.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: constrain the empty-destination sharing path to genuinely minimal / canonical source dictionaries, or fall back to the old compaction path.
  • Minimum required action: preserve the old float canonicalization semantics on that path, or explicitly prove and test why reusing shared float dictionaries as-is is safe.
  • Minimum required action: replace the changelog entry with a specific user-facing description of the optimized LowCardinality paths.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 718/756 (94.97%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 14, 2026
@bobrik
bobrik force-pushed the ivan/low-cardinality-speedup branch from 42ca1ed to a9b9e7b Compare August 14, 2026 19:01
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Release-transition baseline: compared against the last 26.8 master because no 26.9 master baseline exists at or before the trusted base-commit anchor.

This PR is a targeted optimization of LowCardinality column merging (cross-dictionary index translation plus a shared-dictionary fast path in insertRangeFrom) and an ARRAY JOIN hash-map reserve cache, and it ships its own dedicated perf test for exactly that path. Neither ClickBench (integer/string aggregation, no ARRAY JOIN) nor the adapted TPC-H set (joins on native types) exercises the changed code, so none of the flagged deltas are plausibly caused by this change. The apparent wins trace to thin base samples (only 2 base builds): several base medians sit above master's current variance band while the source medians sit inside it, and the TPC-H ×20.1/×6.9 'improvements' come with master bands that span the entire measured range (42-1044 ms and 67-554 ms). All flagged regressions and improvements are downgraded to not_sure; ClickBench Q13 was correctly left as no_change.

clickbench

⚠️ 9 inconclusive

Flagged queries (9 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 277 188 -32.1% <0.0001 PR only touches LowCardinality merge and ARRAY JOIN; this COUNT(DISTINCT) query never hits it. Base (k=2) sat above master's band while source sits inside, so -32.1% is thin-baseline variance.
⚠️ 5 not_sure 368 249 -32.3% <0.0001 Off-path: COUNT(DISTINCT SearchPhrase) doesn't exercise the changed LowCardinality merge or ARRAY JOIN. Base sat above master's band, source inside, so -32.3% is thin-baseline variance.
⚠️ 9 not_sure 340 384 +12.9% <0.0001 Flagged regression, but +12.9% keeps source inside master's band [282,431] with base also inside, and this GROUP BY doesn't touch the changed LowCardinality path. Reads as run-to-run variance.
⚠️ 15 not_sure 223 164 -26.5% <0.0001 Off-path for this UserID GROUP BY. Base (k=2) sat above master's band [163,201] while source sits inside it, so -26.5% is a slow base sample, not a PR effect.
⚠️ 16 not_sure 760 599 -21.2% <0.0001 No LowCardinality merge or ARRAY JOIN in this GROUP BY; with only 2 base builds and 19 base runs, -21.2% is thin-baseline variance rather than a PR effect.
⚠️ 17 not_sure 541 243 ×2.2 faster <0.0001 ×2.2 faster looks large, but this GROUP BY doesn't exercise the changed LowCardinality merge path; with only 2 base builds it reads as a slow base sample, not a PR effect.
⚠️ 18 not_sure 1226 1067 -13.0% <0.0001 The base and source measurements here were noisy, and this GROUP BY is off-path for the LowCardinality change, so -13.0% is variance.
⚠️ 30 not_sure 266 237 -10.9% <0.0001 Off-path aggregation for this diff; -10.9% on a thin 2-build baseline is run-to-run variance.
⚠️ 31 not_sure 362 317 -12.4% <0.0001 Off-path aggregation for this diff; -12.4% on a thin 2-build baseline is run-to-run variance.

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

⚠️ 5 inconclusive

Flagged queries (5 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 1044 52 ×20.1 faster <0.0001 ×20.1 faster is a baseline artifact: master's own range here spans [42,1044] ms and the base (k=2) caught the slow end. TPC-H joins on native types don't exercise the LowCardinality change.
⚠️ 7 not_sure 554 80 ×6.9 faster <0.0001 ×6.9 faster is the same artifact: master ranges [67,554] ms and base caught the slow end. This join query doesn't touch the changed LowCardinality path.
⚠️ 8 not_sure 163 88 -46.0% <0.0001 -46.0% with base (163 ms) at the top of master's band [77,163] and source inside it: a slow base sample, not a PR effect. Off-path for this diff.
⚠️ 17 not_sure 65 107 +64.6% <0.0001 Flagged regression, but the source measurements were extremely noisy and this query is off-path for the LowCardinality change, so +64.6% is not a real PR effect.
⚠️ 18 not_sure 72 83 +15.3% <0.0001 +15.3% is an 11 ms swing on a fast query, off-path for the LowCardinality change; reads as run-to-run variance.

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.

Debug info
  • StressHouse run: bee52eab-be40-4e25-9740-65e96a3648e7
  • MIRAI run: e81c8069-74bf-4b4c-914f-f0637ac0641f
  • PR check IDs:
    • clickbench_69151_1787865242
    • clickbench_69258_1787865287
    • clickbench_69373_1787865319
    • tpch_adapted_1_official_69631_1787865501
    • tpch_adapted_1_official_69720_1787865503
    • tpch_adapted_1_official_69773_1787865507

@bobrik
bobrik force-pushed the ivan/low-cardinality-speedup branch from a9b9e7b to bcae8c4 Compare August 14, 2026 22:47
@bobrik

bobrik commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor Author

WARNING: STALE, see #114870 (comment).

I amended the commits with the fair suggestion from #114870 (comment) (measured as 402x regression locally).

New results are below (empty destination is measuring hashing now, not just cheap aliasing).

  • v1 is PR description
  • v2 is the pushed code
  • improvement is v2 vs baseline
Benchmark Baseline v1 v2 improvement
MapSparseOnly/1 9.320 5.789 5.789 1.61x
MapSparseOnly/2 6.821 3.463 3.473 1.96x
MapSparseOnly/4 4.332 2.345 2.356 1.84x
EmptyDestinationDifferentDictionary/1 33.821 0.031 27.648 1.22x
EmptyDestinationDifferentDictionary/2 11.124 0.032 7.370 1.51x
EmptyDestinationDifferentDictionary/4 6.756 0.031 4.607 1.47x
EmptyDestinationMinimalDictionary/1 24.845 — 0.273 91.00x
EmptyDestinationMinimalDictionary/2 4.762 — 0.152 31.43x
EmptyDestinationMinimalDictionary/4 2.707 — 0.092 29.32x
EmptyDestinationTinyRangeThenComputeHash 0.0029 — 0.0024 1.19x
NonEmptyDisjointDictionaries/1 35.355 28.318 17.592 2.01x
NonEmptyDisjointDictionaries/2 14.603 20.849 10.956 1.33x
NonEmptyDisjointDictionaries/4 7.033 4.793 4.773 1.47x
NonEmptyFullyOverlappingDictionaries/1 34.466 26.934 18.142 1.90x
NonEmptyFullyOverlappingDictionaries/2 11.326 13.907 7.989 1.42x
NonEmptyFullyOverlappingDictionaries/4 6.453 4.498 4.512 1.43x
NonEmptyPartiallyOverlapping/1 37.930 29.155 19.171 1.98x
NonEmptyPartiallyOverlapping/2 11.517 14.470 8.039 1.43x
NonEmptyPartiallyOverlapping/4 6.631 4.453 4.477 1.48x
SameDictionary/1 0.0348 0.035 0.0341 1.02x
SameDictionary/2 0.0349 0.034 0.0348 1.00x
SameDictionary/4 0.0344 0.034 0.0346 0.99x
SmallDenseDictionary 1.038 1.058 1.061 0.98x

Re-measuring the SQL tests as they were affected (it's slightly worse, but still better than the baseline):

Test Baseline v1 v2 improvement
Ordered merge — disjoint IDs 3.252 s 2.704 s 2.737 s 1.19x
Ordered merge — overlapping IDs 2.077 s 1.643 s 1.732 s 1.20x

I also rebased to pick up #114872 to unblock builds.

Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
@bobrik
bobrik force-pushed the ivan/low-cardinality-speedup branch from bcae8c4 to 93af56b Compare August 15, 2026 00:27
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
@bobrik

bobrik commented Aug 15, 2026

Copy link
Copy Markdown
Contributor Author

This build timed out, but it was still marked successful:

[2026-08-15 05:41:09] 2026-08-15 06:41:09 [3718 / 4005] 04151_unique_key_sst_rebuild_on_load:                                   [ OK ] 52.51 sec.
[2026-08-15 05:41:27] 2026-08-15 06:41:27 Global time limit reached - stopping all tests gracefully.

That doesn't feel right. Not sure if it's intentional.

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bf1578393 with master 708305557 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 9d8eed34c; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 711.97 MiB 709.48 MiB -2.48 MiB (-0.35%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

18 object files changed (+1.76 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Columns/ColumnUnique.cpp.o 2.93 MiB 4.68 MiB +1.75 MiB (+59.77%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +507.9 s (+6%) in total before that adjustment.

Translation unit Master PR Δ vs median
src/Columns/ColumnUnique.cpp 8.4 s 15.4 s +6.5 s (+73%)

Job report

@bobrik
bobrik force-pushed the ivan/low-cardinality-speedup branch from c2d9aac to c127da4 Compare August 17, 2026 21:30
@bobrik

bobrik commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

Comparing baseline vs this + #114982 + #114993 shows modest improvements.

This is the query, two runs each:

SELECT *
FROM r0.profiles_v4_replica
WHERE (timestamp >= '2026-08-18 00:00:00') AND (timestamp < '2026-08-19 00:00:00')
ORDER BY
    serviceName ASC,
    profileType ASC,
    label_app_name ASC,
    label_instance ASC,
    timestamp ASC
FORMAT `Null`
SETTINGS max_threads = 64, read_in_order_use_buffering = 1, max_memory_usage_for_user = 160000000000

Baseline:

0 rows in set. Elapsed: 387.294 sec. Processed 190.24 million rows, 195.35 GB (491.21 thousand rows/s., 504.40 MB/s.)
0 rows in set. Elapsed: 390.118 sec. Processed 190.24 million rows, 195.35 GB (487.66 thousand rows/s., 500.75 MB/s.)
image

Patched:

0 rows in set. Elapsed: 363.267 sec. Processed 190.24 million rows, 195.35 GB (523.70 thousand rows/s., 537.76 MB/s.)
0 rows in set. Elapsed: 366.351 sec. Processed 190.24 million rows, 195.35 GB (519.30 thousand rows/s., 533.23 MB/s.)
image

Diff (zoomed in a bit more, red = added, green = removed):

image

That's about 6% improvement in the runtime.

@bobrik
bobrik force-pushed the ivan/low-cardinality-speedup branch from c127da4 to a4de03e Compare August 19, 2026 06:10
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
@bobrik

bobrik commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor Author

WARNING: STALE, see #114870 (comment).

I combed through the profile (better screenshots in #114993 (comment)), and I found some more optimizations. I'm calling it v3. Two key improvements:

  • Default compareAt checks are gone
  • HashMaps for ReverseIndex and mapUniqueIndex are preallocated

C++:

Benchmark Baseline v1 v2 v3 improvement
MapSparseOnly/1 9.320 5.789 5.789 3.272 2.85x
MapSparseOnly/2 6.821 3.463 3.473 2.697 2.53x
MapSparseOnly/4 4.332 2.345 2.356 2.394 1.81x
EmptyDestinationDifferentDictionary/1 33.821 0.031 27.648 16.737 2.02x
EmptyDestinationDifferentDictionary/2 11.124 0.032 7.370 5.243 2.12x
EmptyDestinationDifferentDictionary/4 6.756 0.031 4.607 3.702 1.82x
EmptyDestinationMinimalDictionary/1 24.845 — 0.273 0.273 90.93x
EmptyDestinationMinimalDictionary/2 4.762 — 0.152 0.151 31.55x
EmptyDestinationMinimalDictionary/4 2.707 — 0.092 0.093 29.03x
EmptyDestinationTinyRangeThenComputeHash 0.0029 — 0.0024 0.0025 1.16x
NonEmptyDisjointDictionaries/1 35.355 28.318 17.592 14.188 2.49x
NonEmptyDisjointDictionaries/2 14.603 20.849 10.956 9.584 1.52x
NonEmptyDisjointDictionaries/4 7.033 4.793 4.773 4.590 1.53x
NonEmptyFullyOverlappingDictionaries/1 34.466 26.934 18.142 15.133 2.28x
NonEmptyFullyOverlappingDictionaries/2 11.326 13.907 7.989 6.598 1.72x
NonEmptyFullyOverlappingDictionaries/4 6.453 4.498 4.512 4.247 1.52x
NonEmptyPartiallyOverlapping/1 37.930 29.155 19.171 16.085 2.36x
NonEmptyPartiallyOverlapping/2 11.517 14.470 8.039 6.759 1.70x
NonEmptyPartiallyOverlapping/4 6.631 4.453 4.477 4.232 1.57x
SameDictionary/1 0.0348 0.035 0.0341 0.0338 1.03x
SameDictionary/2 0.0349 0.034 0.0348 0.0337 1.04x
SameDictionary/4 0.0344 0.034 0.0346 0.0338 1.02x
SmallDenseDictionary 1.038 1.058 1.061 1.035 1.00x

SQL:

Test Baseline v1 v2 v3 improvement
Ordered merge — disjoint IDs 3.252 s 2.704 s 2.737 s 2.733 s 1.19x
Ordered merge — overlapping IDs 2.077 s 1.643 s 1.732 s 1.651 s 1.26x

@bobrik
bobrik force-pushed the ivan/low-cardinality-speedup branch from c92d73e to 4650350 Compare August 20, 2026 02:39
@bobrik

bobrik commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

Same query, with the v3 updates:

SELECT *
FROM r0.profiles_v4_replica
WHERE (timestamp >= '2026-08-18 00:00:00') AND (timestamp < '2026-08-19 00:00:00')
ORDER BY
    serviceName ASC,
    profileType ASC,
    label_app_name ASC,
    label_instance ASC,
    timestamp ASC
FORMAT `Null`
SETTINGS max_threads = 64, read_in_order_use_buffering = 1, max_memory_usage_for_user = 160000000000
  • Before:
0 rows in set. Elapsed: 390.466 sec. Processed 190.24 million rows, 195.35 GB (487.22 thousand rows/s., 500.30 MB/s.)
0 rows in set. Elapsed: 395.997 sec. Processed 190.24 million rows, 195.35 GB (480.42 thousand rows/s., 493.31 MB/s.)
image
  • After:
0 rows in set. Elapsed: 345.518 sec. Processed 190.24 million rows, 195.62 GB (550.61 thousand rows/s., 566.15 MB/s.)
0 rows in set. Elapsed: 337.455 sec. Processed 190.24 million rows, 195.62 GB (563.76 thousand rows/s., 579.68 MB/s.)
image

That's -15% on the second run! Pretty good.

@bobrik

bobrik commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

I updated with a v4 with uniqueInsertRangeFromDictionary optimization.

C++:

Benchmark Baseline v1 v2 v3 v4 improvement
MapSparseOnly/1 9.320 5.789 5.789 3.272 3.294 2.83x
MapSparseOnly/2 6.821 3.463 3.473 2.697 2.717 2.51x
MapSparseOnly/4 4.332 2.345 2.356 2.394 2.400 1.80x
EmptyDestinationDifferentDictionary/1 33.821 0.031 27.648 16.737 9.446 3.58x
EmptyDestinationDifferentDictionary/2 11.124 0.032 7.370 5.243 3.321 3.35x
EmptyDestinationDifferentDictionary/4 6.756 0.031 4.607 3.702 2.791 2.42x
EmptyDestinationMinimalDictionary/1 24.845 — 0.273 0.273 0.272 91.39x
EmptyDestinationMinimalDictionary/2 4.762 — 0.152 0.151 0.153 31.05x
EmptyDestinationMinimalDictionary/4 2.707 — 0.092 0.093 0.093 29.09x
EmptyDestinationTinyRangeThenComputeHash 0.0029 — 0.0024 0.0025 0.0022 1.32x
NonEmptyDisjointDictionaries/1 35.355 28.318 17.592 14.188 14.678 2.41x
NonEmptyDisjointDictionaries/2 14.603 20.849 10.956 9.584 9.570 1.53x
NonEmptyDisjointDictionaries/4 7.033 4.793 4.773 4.590 4.638 1.52x
NonEmptyFullyOverlappingDictionaries/1 34.466 26.934 18.142 15.133 15.400 2.24x
NonEmptyFullyOverlappingDictionaries/2 11.326 13.907 7.989 6.598 6.749 1.68x
NonEmptyFullyOverlappingDictionaries/4 6.453 4.498 4.512 4.247 4.278 1.51x
NonEmptyPartiallyOverlapping/1 37.930 29.155 19.171 16.085 15.944 2.38x
NonEmptyPartiallyOverlapping/2 11.517 14.470 8.039 6.759 7.526 1.53x
NonEmptyPartiallyOverlapping/4 6.631 4.453 4.477 4.232 4.271 1.55x
SameDictionary/1 0.0348 0.035 0.0341 0.0338 0.0344 1.01x
SameDictionary/2 0.0349 0.034 0.0348 0.0337 0.0337 1.04x
SameDictionary/4 0.0344 0.034 0.0346 0.0338 0.0339 1.02x
SmallDenseDictionary 1.038 1.058 1.061 1.035 1.063 0.98x

SQL:

Test Baseline v1 v2 v3 v4 improvement
Ordered merge — disjoint IDs 3.252 s 2.704 s 2.737 s 2.733 s 2.540 s 1.28x
Ordered merge — overlapping IDs 2.077 s 1.643 s 1.732 s 1.651 s 1.504 s 1.38x

@bobrik
bobrik force-pushed the ivan/low-cardinality-speedup branch from a74e796 to cdabfbb Compare August 21, 2026 01:12
bobrik added 3 commits August 26, 2026 17:07
This adds a benchmark query to exercise the problematic path.

It also adds a bunch of C++ benchmarks:

* Sparse indices
* Empty destination with a non-minimal source dictionary
* Empty destination with a minimal source dictionary
* Tiny range from an oversized dictionary followed by hashing
* Disjoint dictionaries
* Partially overlapping dictionaries
* Fully overlapping dictionaries
* Same dictionary fastpath
* Dense dictionary control

Plus some correctness C++ tests that will be expanded in following commits.
Each source index now performs exactly one `HashMap::emplace`. A newly seen
source index is assigned its compact index immediately and is appended to
the compact-to-source mapping in the first-seen order. The input index
array is also rewritten in the same pass.

Additionally, the old sparse mapper always:

* Copied the entire input index array
* Rewrote all the indexes
* Scanned everything to verify

Tha latter is an expensive correctness check that doesn't need to exist
in a normal release build, so it is now guarded for debug/sanitizers.
Add coverage for dictionary sharing, CoW behavior, nullable dictionaries,
and zero-length range insertions.

Update the benchmark to exercise the existing shared-dictionary fast path.
@bobrik
bobrik force-pushed the ivan/low-cardinality-speedup branch from cdabfbb to 847c6c0 Compare August 27, 2026 01:59
@bobrik

bobrik commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

I rebased and took advantage of #115961 here. It gave us faster EmptyMinimal and -100 lines of the diff:

Test Before After Improvement
EmptyMinimal/1 272.8 31.0 -88.63%
EmptyMinimal/2 150.3 30.9 -79.43%
EmptyMinimal/4 89.2 30.8 -65.44%

That's a whopping 800x improvement for EmptyMinimal/1 over the baseline!

Otherwise it's within the noise at ±3% (including the SQL bench).

Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
bobrik added 7 commits August 26, 2026 19:47
* Dense source-index ranges retain the previous gather-based implementation.

* Sparse ranges compact the referenced source positions in first-seen order,
then translate only those distinct positions directly into the destination
dictionary. Source key columns are no longer gathered into a temporary
column on this path.

* If every position in the range is distinct, the translated indexes are
returned directly and the final expansion gather is skipped.

* Source index columns are dispatched as `UInt8`, `UInt16`, `UInt32`, or
`UInt64` without converting their storage.

`IColumnUnique` now exposes `uniqueInsertRangeFromDictionary`, with the typed
implementation in `ColumnUnique`. It reads keys at supplied source-dictionary
positions, inserts or finds them through the destination reverse index, and
returns destination indexes in a width selected from a checked upper bound on
the resulting dictionary size. The implementation handles nullable values,
nested defaults, and canonical NaN insertion consistently with the existing
dictionary insertion behavior, updates the null mask on exit, and checks that
each produced index fits the selected destination type.
Benchmarks appear to be within the noise.
…x checks

| Benchmark group                         | Improvement |
|-----------------------------------------|------------:|
| Empty destination, different dictionary |    3.5–6.3% |
| Non-empty, disjoint dictionaries        |    4.4–9.9% |
| Non-empty, fully overlapping            |    6.4–6.9% |
| Non-empty, partially overlapping        |    6.6–7.8% |
Instead of growing the hashmap for each block, remember how big it was before.

* MapSparseOnly: 42.6% faster /1, 21.5% faster /2, 2.3% slower /4.
* End-to-end /1: 4.5–11.7% faster.
* End-to-end /2: 7.7–12.4% faster.
* End-to-end /4: effectively flat (−1.1% to +0.2%).
Same as the previous commit:

* Empty destination /1: 58.3% faster
* /2: 14.4% faster
* /4: 16.4% faster
`uniqueInsertRangeFromDictionary` receives distinct source dictionary
positions. For empty non-floating numeric destinations, append these
values directly and translate null/default positions structurally instead
of building and probing a `ReverseIndex`.

Keep the reverse index lazy so later insertions build it from the populated
dictionary. Retain the existing path for non-empty destinations, floating-
point dictionaries, and already-built indexes.

Results:

* Empty destination: 25–43% faster
* Ordered merge with disjoint IDs: 6.8% faster
* Ordered merge with overlapping IDs: 7.4% faster
@bobrik

bobrik commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

This will need another rebase after #116637.

@bobrik

bobrik commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor Author

In #117123 I added parallelism instead, which cuts latency much deeper.

There's some synergy, but parallelism alone is a much bigger bang for the buck for a pure ordered select.

This branch has not been deployed

No deployments
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 comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants