Skip to content

Support statistics UniqV2 which internally uses UniqCombined64(12) - #107863

Merged
hanfei1991 merged 27 commits into
ClickHouse:masterfrom
hanfei1991:hanfei/uniqcombined
Jul 14, 2026
Merged

hanfei1991 merged 27 commits into
ClickHouse:masterfrom
hanfei1991:hanfei/uniqcombined

Conversation

@hanfei1991

@hanfei1991 hanfei1991 commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

This is a follow-up to #95474

New Statistics UniqCombined(12) uses less memory than uniq, and faster on insert

uniqcombined
-------------

0%              0.002 sec.      
10%             0.004 sec.      
20%             0.004 sec.      
30%             0.005 sec.      
40%             0.006 sec.      
50%             0.007 sec.      
60%             0.008 sec.      
70%             0.010 sec.      
80%             0.013 sec.      
90%             0.019 sec.      
95%             0.026 sec.      
99%             0.050 sec.      
99.9%           0.076 sec.      
99.99%          0.106 sec.  

uniq
----------------
0%              0.002 sec.      
10%             0.004 sec.      
20%             0.005 sec.      
30%             0.005 sec.      
40%             0.006 sec.      
50%             0.007 sec.      
60%             0.009 sec.      
70%             0.011 sec.      
80%             0.015 sec.      
90%             0.021 sec.      
95%             0.029 sec.      
99%             0.052 sec.      
99.9%           0.089 sec.      
99.99%          0.119 sec.    

Changelog category (leave one):

  • Improvement

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

Support statistics UniqCombined(12) as a lightweight alternative of statistics uniq

Version info

  • Merged into: 26.7.1.957 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ca4006e]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) FAIL
Server died FAIL cidb
04412_projection_added_column_default UNKNOWN cidb
00626_replace_partition_from_table UNKNOWN cidb
03915_exchange_tables_race UNKNOWN cidb, issue
00318_pk_tuple_order UNKNOWN cidb
01865_aggregator_overflow_row UNKNOWN cidb
04051_clear_column_rebuild_dependencies UNKNOWN cidb
02899_restore_parts_replicated_merge_tree UNKNOWN cidb
04095_lazy_final_with_lazy_materialization UNKNOWN cidb
Unknown error FAIL cidb
Integration tests (amd_msan, 7/8) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue

AI Review

Summary

This PR adds the new uniq_v2 column-statistics type backed by uniqCombined64(12), wires it into DDL/settings/docs, and extends the statistics tests. I am not approving it yet because the current estimator merge logic still produces part-order-dependent cardinality estimates during in-flight statistics mutations, and the final docs/metadata still describe a different implementation with unsupported performance claims.

PR Metadata
  • Changelog category: Improvement is reasonable for a new optional statistics type.
  • Changelog entry: required, but the current text is inaccurate and too implementation-centric. It still advertises UniqCombined(12) instead of the user-visible uniq_v2.
  • Exact replacement text: You can now use uniq_v2 column statistics as a lower-memory approximate alternative to uniq for cardinality estimates.
  • The PR body still benchmarks uniqCombined, not the shipped uniqCombined64(12) / uniq_v2, so it does not substantiate the current documentation claims.
Findings
  • ⚠️ Major [src/Storages/Statistics/ConditionSelectivityEstimator.cpp:510] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/107863#discussion_r3574908926] ConditionSelectivityEstimatorBuilder::addStatistics still seeds the estimator from the first part and silently skips later parts whose statistics shape differs, even though markDataPart already counted all of their rows. During ALTER TABLE ... ADD/MODIFY/DROP STATISTICS, that makes join/PREWHERE costing depend on part iteration order rather than the full table state. Merge the compatible per-statistics subset here, or clear the estimator for that column when any incompatible part is seen instead of reusing partial statistics with total_rows.
  • 💡 Nit [docs/en/engines/table-engines/mergetree-family/mergetree.md:1318], [src/Storages/MergeTree/registerStorageMergeTree.cpp:2417] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/107863#discussion_r3544278659] Both user-facing docs still say uniq_v2 internally uses uniqCombined(12) and “can be build faster”, but the implementation is uniqCombined64(12) and the PR body benchmarks uniqCombined, not the shipped statistic. Update both docs to uniqCombined64(12) (or drop the internal aggregate name entirely), and either add focused statistics.packed / materialization / load measurements or remove the performance claim.
Tests
  • ⚠️ There is still no focused regression for a Nullable uniq_v2 statistic built from all NULL values, so the new StatisticsUniqV2::estimateCardinality branch at [src/Storages/Statistics/StatisticsUniqV2.cpp:106] is not proven. A minimal stateless or gtest case that materializes uniq_v2 on all-NULL input and asserts cardinality 0 would close this gap.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Fix the mixed-statistics estimator path in ConditionSelectivityEstimatorBuilder::addStatistics so incompatible parts do not yield partial estimates scaled to total_rows.
  2. Align the docs and changelog/PR description with the shipped implementation (uniqCombined64(12) / uniq_v2) and remove or substantiate the performance claims.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 18, 2026
Comment thread src/Storages/StatisticsDescription.cpp Resolved
Comment thread src/Storages/Statistics/Statistics.h Resolved
Comment thread src/Storages/Statistics/Statistics.cpp Resolved
Comment thread src/Storages/Statistics/Statistics.cpp Resolved
Comment thread src/Storages/Statistics/Statistics.cpp Resolved
@hanfei1991 hanfei1991 changed the title Support statistics UniqCombined(12) Support statistics UniqV2 which internally uses UniqCombined64(12) Jun 23, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Let's make a decision regarding #107863 (comment)

@alexey-milovidov

Copy link
Copy Markdown
Member

@rschu1ze #107863 (comment)

Saving ~4KB per column is much better than ~96KB.

@cv4g cv4g self-assigned this Jul 7, 2026
@hanfei1991

Copy link
Copy Markdown
Member Author

@rschu1ze #107863 (comment)
Saving ~4KB per column is much better than ~96KB.

Sorry to ask but

  1. Where are these numbers coming from?
  2. Maybe I mis-read the sentence but if the size difference is 96kB vs. 100 kB, then it is insignificant.

@hanfei1991 or @cv4g Can you please measure how big uniq vs. uniqCombined statistics are for large high-cardinality parts (e.g. 10 mio rows with 90% distinctness)?

Here is analysis by AI

| Function | Structure | Max bounded state |
|---|---|---|
| `uniq` | `UniquesHashSet` (2^17 buckets x UInt32) | **512 KiB** |
| `uniqCombined` | Combined, K=17, 5-bit HLL | **~80 KiB** (transient ~64 KiB medium during conversion) |
| `uniqCombined64` | Combined, K=17, 6-bit HLL | **~96 KiB** |
| `uniqHLL12` | HLL K=12, 5-bit | **~2.5 KiB** |
| `uniqExact` | exact `HashSet`/`TwoLevelHashSet` of keys | **unbounded** (~2 x sizeof(Key) per distinct value) |

uniqCombined64(12) should be twice of uniqHLL12 which is around 5KB

hanfei1991 and others added 3 commits July 7, 2026 23:11
Randomized index_granularity changed the granule counts printed by EXPLAIN.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ng it

The old branch deserialized a non-null uniqCombined64 state into the start
of the nullable wrapper state, ignoring its flag prefix and nested offset,
so old parts loaded as a corrupted/NULL statistic after MODIFY COLUMN.
Reject the mismatch so the caller ignores and rebuilds the statistic.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

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.

The PR adds a new statistics type. Lots of systematic tests which focus on statistics exist already:

  • 02864_statistics_ddl.sql
  • 02864_statistics_predicates.sql
  • 02864_statistics_create_materialize_drop.sql
    Probably more.

The new test 04357_join_order_dp_uniqcombined.sql will eventually test uniq_v2 statistics, but only indirectly and it does not create the coverage which the existing systematic tests would create. By not updating the existing tests, this PR made them stale as well.

Anyways, just saying. Not a blocker, feel free to ignore.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good point, we can do it in this PR

bool is_null = false;
readBinary(is_null, buf);

/// `is_null` is whether the state was built through the `Null` wrapper (i.e. a `Nullable` column).

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.

StatisticsUniq::deserialize deserves the same code changes to keep things consistent.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

According to the AI review: #107863 (comment)

The uniq is safe here, only uniq_v2 must abort

@rschu1ze

rschu1ze commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

@hanfei1991 Looks good to me in general.

So we established that the legacy uniq is the faster and more accurate than uniq_v2 (#107863 (comment)).

uniq_v2 should at least be significantly smaller, otherwise it's pointless. As per your LLM analysis, that's true. Since only one particular situation was covered (90% distinctness) and since LLMs can hallucinate, could I ask you to measure also 1% distinctness, 50% distinctness and 99% distinctness? Sorry, I don't want to postpone this PR endlessly, but uniq statistics are critical and we better make sure we understand their properties well before changing something that we may regret later.

@hanfei1991

hanfei1991 commented Jul 13, 2026 •

Copy link
Copy Markdown
Member Author

@rschu1ze I wrote a unittest https://gist.github.com/hanfei1991/7503dbdf638b01d1d18ae3bf0b8d78b1 to make graph for uniq and uniqCombined64, the X is number of cardinality, and Y is memory consumption. I didn't make "1% distinctness, 50% distinctness and 99% distinctness" because the memory consumption is only decided by the number of distinct value of the column.
image

So we established that the legacy uniq is the faster and more accurate than uniq_v2 (#107863 (comment)).

It's not true, for insert (1000 rows per insert), uniq_v2 is faster (See the description of this PR). for select, uniq is faster. I don't know why yet. Need more investigation

@rschu1ze

Copy link
Copy Markdown
Member

@rschu1ze I wrote a unittest https://gist.github.com/hanfei1991/7503dbdf638b01d1d18ae3bf0b8d78b1 to make graph for uniq and uniqCombined64, the X is number of cardinality, and Y is memory consumption. I didn't make "1% distinctness, 50% distinctness and 99% distinctness" because the memory consumption is only decided by the number of distinct value of the column. image

So we established that the legacy uniq is the faster and more accurate than uniq_v2 (#107863 (comment)).

It's not true, for insert (1000 rows per insert), uniq_v2 is faster (See the description of this PR). for select, uniq is faster. I don't know why yet. Need more investigation

Thanks. Btw., I just learned by looking at the code that uniq doesn't use HyperLogLog (that's what I thought), it uses BJSTK. This also explains why the size of uniq jumps up like crazy with the number of distinct items ...

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 48.00% 85.80% +37.80%
Functions 60.50% 92.70% +32.20%
Branches 36.80% 77.90% +41.10%

Changed lines: Changed C/C++ lines covered: 183/209 (87.56%) · Uncovered code

Full report · Diff report

@hanfei1991
hanfei1991 added this pull request to the merge queue Jul 14, 2026
Merged via the queue into ClickHouse:master with commit 51819a1 Jul 14, 2026
173 of 176 checks passed
@hanfei1991
hanfei1991 deleted the hanfei/uniqcombined branch July 14, 2026 21:57
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 14, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Support statistics UniqV2 which internally uses UniqCombined64(12)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product 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.

5 participants