Skip to content

countmin statistics: optimize creation for LowCardinality columns - #109227

Closed
cv4g wants to merge 15 commits into
masterfrom
optimize-countmin-on-lowcardinality-columns
Closed

cv4g wants to merge 15 commits into
masterfrom
optimize-countmin-on-lowcardinality-columns

Conversation

@cv4g

@cv4g cv4g commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Found during benchmarking ColumnStatistics. CountMinSketch does currently not have a optimized code path for LowCardinality columns. This PR adds such code path.

Related: StatisticsUniq has an optimized code path too. StatisticsTDigest does not. StatisticsMinMax calls ColumnLowCardinality::getExtemes() which materializes the full indexed column.

Changelog category (leave one):

  • Performance Improvement

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

CountMinSketch based column statistics are now more efficiently computed on LowCardinality columns.


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

@scanhex12 scanhex12 added the can be tested Allows running workflows for external contributors label Jul 2, 2026
@clickhouse-gh clickhouse-gh Bot closed this Jul 2, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Jul 2, 2026
Comment thread tests/performance/insert_statistics.xml Resolved
@rschu1ze rschu1ze self-assigned this Jul 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7fa0f2b]

Summary: ❌

job_name test_name status info comment
Stress test (arm_tsan) FAIL
Logical error: Initiator received more initial requests than there are replicas: replica_num=A (STID: 8765-7341) FAIL cidb
Performance Comparison (arm_release, master_head, 3/6) FAIL Performance dashboard
serialization_pool_lookup #0 FAIL dashboard

AI Review

Summary

This PR adds a LowCardinality fast path for countmin statistics together with stronger regression and performance coverage. The new exact-estimate SQL test is much better than the earlier PREWHERE-ordering proxy, but the current reuse heuristic still keys both fast-path decisions off total row count rather than the rows that actually update the sketch. That leaves a real nullable low-reuse regression in the insert path, so I cannot approve it yet.

Findings

⚠️ Majors

  • [src/Storages/Statistics/StatisticsCountMinSketch.cpp:160,178] The dense and sparse cutoffs both use column_low_cardinality->size(), but StatisticsCountMinSketch::build skips NULL rows when it actually calls sketch.update. For LowCardinality(Nullable(T)) blocks with many NULLs and mostly unique non-NULL values, the old row-wise path does work proportional to the non-NULL rows, while the new logic can still choose countKeys or spend almost the whole block building the sparse prefix map before it falls back. That violates the PR's performance contract on a supported column shape.
    Suggested fix: derive both cutoffs from the non-NULL row count for nullable low-cardinality columns (for example size() - getNumberOfDefaultRows()), then keep the existing dense/sparse selection on top of that adjusted count.
Tests
  • ⚠️ Keep one focused performance regression case for a LowCardinality(Nullable(String)) block with mostly NULL rows and mostly unique non-NULL values. The committed performance suite keeps the repeated-non-NULL nullable case, but the results note that the mostly-distinct nullable shape was dropped, which is exactly the shape that still regresses here.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: base the dense and sparse reuse thresholds on non-NULL rows for LowCardinality(Nullable(...)), and keep a performance case that locks in that mostly-NULL / mostly-unique shape.

LLVM Coverage Report

Measured on commit 7fa0f2b.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 46/51 (90.20%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 9, 2026
@cv4g

cv4g commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

Performance improvements:

  • Large dictionary LowCardinality countmin: 16.10ms -> 7.05ms, -56.2%, p=2.94e-225
  • Numeric LowCardinality countmin: 248.96ms -> 166.48ms, -33.1%, p=1.33e-12
  • String LowCardinality countmin: 321.84ms -> 228.11ms, -29.1%, p=1.97e-10
  • FixedString LowCardinality countmin: 295.31ms -> 211.31ms, -28.4%, p=1.10e-9

I also got two regressions but these code paths are not changed:

  • FixedString LowCardinality none: 197.98ms -> 206.74ms, +4.42%
  • FixedString LowCardinality uniq: 200.57ms -> 208.87ms, +4.14%

Measurements obtained by running the new xml performance test files against both 8a863a7 (baseline, master) and f15a0e0.

@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 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

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 9a21f261-6bda-4c1f-93a5-d9a6976bb6e4
  • MIRAI run: 01d2d62c-d15a-4607-850c-2f91a6b44c86
  • PR check IDs:
    • clickbench_1889324_1790395054
    • clickbench_1889330_1790395055
    • clickbench_1889336_1790395054
    • tpch_adapted_1_official_1889347_1790395055
    • tpch_adapted_1_official_1889358_1790395055
    • tpch_adapted_1_official_1889394_1790395055

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.80% -0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.10% 78.00% -0.10%

Changed lines: Changed C/C++ lines covered: 33/37 (89.19%) · Uncovered code

Full report · Diff report

@@ -0,0 +1,230 @@
-- Tags: no-fasttest

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.

This PR implements a performance optimization. The PR also includes a performance test (good). Do we really need a functional test then? The effects of statistics are only indirectly observable, and below test goes great lengths (complexity) because of that.

(asking because the test still fails in CI, and we could simplify our lives by omitting the test)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We still need one semantic regression in addition to the performance test, but it does not have to be SQL if SQL cannot observe the exact estimate precisely enough.

This change is not only about insert speed; it changes the countmin equality counts that ConditionSelectivityEstimator consumes. The current PREWHERE-ordering test is too coarse for that contract: in the sliced-dictionary fixture, lc_value = 42 still sorts after selective_probe = 1 whether the estimate is the correct 3 or a biased 4, and lc_value = 5 still sorts before the 10 KB payload column because MergeTreeWhereOptimizer falls back to columns_size when selectivities tie or are close. If there is no stable SQL surface for exact estimateEqual values, restoring the small direct gtest is the practical way to pin the behavior.

@rschu1ze rschu1ze changed the title Optmize code path for LowCardinality columns in CountMin Optimize code path for LowCardinality columns in CountMin Jul 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Dear @rschu1ze, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@rschu1ze rschu1ze changed the title Optimize code path for LowCardinality columns in CountMin countmin statistics: optimize creation for LowCardinality columns Aug 18, 2026
@rschu1ze

Copy link
Copy Markdown
Member

@cv4g This is a useful PR but it starts to mold. Let's give it one more pass and then merge?

@rschu1ze rschu1ze self-assigned this Aug 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7fa0f2b16 with master 3d9e5ef14 (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

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
continue;
auto data = column->getDataAt(row);
sketch.update(data.data(), data.size(), 1);
const size_t max_dense_distinct_values = column_low_cardinality->size() / min_dense_dictionary_value_reuse;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

max_dense_distinct_values is based on column_low_cardinality->size(), so LowCardinality(Nullable(T)) blocks with many NULLs are treated as high-reuse even when every non-NULL value is unique. For example, 90 NULL rows plus 10 distinct strings give N = 100 and dictionary.size() == 12, so this branch still takes countKeys(). The old row-wise build already skips the 90 NULLs, so both paths perform only 10 sketch.updates, but the new one adds a full index-counting pass and a ColumnUInt64 allocation.

Please base the dense cutoff on non-NULL rows for nullable LowCardinality columns (for example size() - getNumberOfDefaultRows()), or keep this shape on the row-wise fallback. A focused nullable low-reuse regression would help keep the cutoff honest.

/// A filtered column may retain a large dictionary while referencing
/// only a few entries. Bound the temporary hash map more conservatively
/// than the dense counter.
const size_t max_sparse_distinct_values = column_low_cardinality->size() / min_sparse_dictionary_value_reuse;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This sparse cutoff has the same Nullable hole as the dense branch above. size() counts NULL rows, but updateSketchRowWise skips them, so a LowCardinality(Nullable(String)) block with, for example, 90 NULLs and 10 distinct non-NULL values in a retained dictionary still gets max_sparse_distinct_values = 10. If the NULLs come first, countTouchedDictionaryIndexes walks the whole block, allocates the hash map, and only breaks on the last row, even though the old row-wise path would have done just 10 sketch.updates. That regresses the same low-reuse shape this fallback is supposed to protect. Please derive the sparse cutoff from the non-NULL row count for nullable LowCardinality columns as well.

@rschu1ze

Copy link
Copy Markdown
Member

This PR somehow blew up. Can we merge a minimal version with max. +20 LOC C++ changes (please see my earlier comment about the weird path of small dictionaries) + a single .xml performance test + a single .sql test? We don't need to overthink this PR - count-min statistics are and will not be the default.

@rschu1ze

Copy link
Copy Markdown
Member

This PR is generally useful but stuck and less of a priority at the moment. Allow me to close it to get it off the radar for now. We can re-open at some point (but then it would need more activity).

@rschu1ze rschu1ze closed this Oct 14, 2026
@clickhouse-gh clickhouse-gh Bot added comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 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 comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants