Skip to content

Assume Float columns to be distinct, do not build implicit uniq statistics - #126971

Draft
cv4g wants to merge 3 commits into
masterfrom
disable-uniq-for-float-columns
Draft

cv4g wants to merge 3 commits into
masterfrom
disable-uniq-for-float-columns

Conversation

@cv4g

@cv4g cv4g commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Do not build implicit uniq statistics for Float columns, assume distinct values instead.

Implicit uniq / uniq_v2 statistics from auto_statistics_types are no longer built for Float32 / Float64 columns (also inside Nullable): their values are almost always distinct, and the sketch costs CPU and memory on every insert and merge. Wherever the optimizer needs a cardinality and no sketch exists, it now assumes that all non-NULL values of such a column are distinct, capped using basic statistics (zeros of a non-Nullable column count as one value, min == max means one value).

  • Controlled by the new MergeTree setting auto_statistics_assume_floats_distinct (default true, history entry for 26.10, so compatibility restores the old behaviour).
  • Explicit STATISTICS(uniq...), BFloat16 and LowCardinality(...) columns are unchanged.
  • The assumption applies only if the setting is on and the metadata declares no uniq for the column, so a declared but not yet materialized uniq is not mistaken for a missing one.
  • hasCardinality() keeps meaning "backed by a sketch", so the IN-set bound is not applied to an assumed cardinality.
  • system.parts_columns.estimates.cardinality shows the assumed value when the optimizer uses it.
  • The statistics cache is dropped when the setting or the declared statistics change, and a refresh that started before that does not publish its estimator.
  • No on-disk format change: existing parts drop their implicit Float sketches on their next merge, or with MATERIALIZE STATISTICS.

Changelog category (leave one):

  • New Feature

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

Using the new setting auto_statistics_assume_floats_distinct it is now possible to disable implicit uniq column statistics for Float32, Float64 and assume unique column values instead.


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

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8ef5b86]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Oct 21, 2026
Comment thread src/Storages/Statistics/Statistics.cpp Outdated
Comment on lines +1099 to +1102
if (assume_floats_distinct && canAssumeAllDistinctByType(column.type))
{
stats_desc.types_to_desc.erase(StatisticsType::Uniq);
stats_desc.types_to_desc.erase(StatisticsType::UniqV2);

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.

⚠️ Merge statistics across parts with and without the old sketch

This creates a normal upgrade/setting-transition state where older Float parts have basic, uniq_v2 and newer parts have only basic. However, ConditionSelectivityEstimatorBuilder::addStatistics merges a column only when structureEquals succeeds, and that check requires identical statistics sets. Every part of the other shape is therefore silently skipped, including its valid basic summaries, while incrementRowCount still counts its rows. Applying the cardinality policy afterward cannot recover those summaries.

For example, let the first old part contain the 1,000 distinct values 1..1000, then enable this setting and insert a new part containing 1001..1001000. The estimator retains only the old part's statistics: its cardinality is about 1,000 and f < 1001 is estimated to match all 1,001,000 rows instead of about 1,000. Reversing part order discards the old part instead. This can distort PREWHERE ordering and join planning throughout the transition, potentially indefinitely for old parts that no longer merge.

Please merge the compatible summaries across both shapes and handle incomplete sketch coverage explicitly. Add a focused regression combining both shapes in both orders; the new estimator tests currently exercise a single statistics object per column, and the functional toggle test rewrites a single part without inserting any new parts during the transition.

@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 285f1e582 with master 31dd125f5 (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.

Object file sizes

17 object files changed (+31.65 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/WhatIf/WhatIfStatisticalEstimator.cpp.o 72.25 KiB 90.88 KiB +18.63 KiB (+25.79%)

711 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.

Slowest function optimization changes (ThinLTO)
Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.9 s 18.5 s +10.4 s (+130%)
Compile time of recompiled translation units

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

Job report

@hanfei1991

hanfei1991 commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

If I implement this feature. I would like only change uniqStatisticsValidator and uniqV2StatisticsValidator. If setting .... (whatever) is true, say no to float32/float64/Decimal ...

@cv4g

cv4g commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

If I implement this feature. I would like only change uniqStatisticsValidator and uniqV2StatisticsValidator. If setting .... (whatever) is true, say no to float32/float64/Decimal ...

As far as I understood, this is not possible because the validators don't have access to the table setting and are also executed on server startup. Rejecting the uniq statistics on float columns would lead to ILLEGAL_STATISTICS being thrown, or?

cv4g added a commit that referenced this pull request Nov 13, 2026
With `auto_statistics_types = 'uniq_v2'` (or `'uniq'`), leaving out the implicit uniq of a Float column
left it without any statistics, so the estimator had nothing to apply the assumption to: an equality got
the generic 1% estimate, join planning got no number of distinct values, and a table of only Float
columns got no estimator at all because of the `hasStatistics` guards.

`addImplicitStatistics` now marks the column whose implicit uniq it leaves out with the in-memory flag
`ColumnStatisticsDescription::assume_all_distinct`, and the assumption applies exactly to such columns.
For a flagged column without any statistics, the estimator takes the number of rows from the parts that
store it (`ColumnStatistics::createRowCountOnly`), which is all the assumption needs, and
`system.parts_columns` shows that number. `hasStatistics` is renamed to `hasStatisticsForEstimation`
and counts flagged columns, so the estimator is built for them.

The flag is derived from the settings like the implicit statistics and is never persisted. Nothing is
assumed any more where no uniq was asked for (e.g. `auto_statistics_types = 'basic'`).

Addresses #126971 (comment)
if (!statistics_types_str.empty() && args.table_id.database_name != DatabaseCatalog::SYSTEM_DATABASE)
{
addImplicitStatistics(metadata.columns, statistics_types_str);
addImplicitStatistics(

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.

[Major] Re-derive implicit statistics for a copied table schema

CREATE TABLE ... AS src copies the source's in-memory ColumnsDescription in InterpreterCreateQuery::getTablePropertiesAndNormalizeCreateQuery, including its implicit statistics. For example:

CREATE TABLE src (f Float64) ENGINE = MergeTree ORDER BY tuple()
SETTINGS auto_statistics_types = 'basic, uniq_v2', auto_statistics_assume_floats_distinct = 0;
CREATE TABLE dst AS src ENGINE = MergeTree ORDER BY tuple()
SETTINGS auto_statistics_types = 'basic, uniq_v2', auto_statistics_assume_floats_distinct = 1;

Here metadata.columns already contains uniq_v2(auto). addImplicitStatistics removes the sketch only from its temporary description, then merges into the existing column; its declared.contains check also treats the inherited implicit sketch as an explicit one. Consequently dst keeps building sketches on inserts/merges and never enables the assumption, despite its setting. Reattaching the table changes this behavior because implicit statistics are not persisted.

Please remove inherited implicit statistics and their assumption flag before deriving the destination's policy, including when its auto_statistics_types is empty. Add a focused schema-copy regression with different source/destination settings, while preserving explicitly declared sketches.

@hanfei1991

Copy link
Copy Markdown
Member

As far as I understood, this is not possible because the validators don't have access to the table setting and are also executed on server startup.

It's not executed on server startup. Validators do check in both implicitStatistics and DDL/DML. If the check fails, in addImplicitStatistics it will fail silently, in other cases it will throw ILLEGAL_STATISTICS but we can pass table settings to let it fail silently.

@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 19, 2026
@cv4g
cv4g force-pushed the disable-uniq-for-float-columns branch from e8a765b to 4a4364a Compare November 20, 2026 23:51
cv4g added 3 commits November 23, 2026 15:11
Add the MergeTree setting `auto_statistics_assume_floats_distinct` (enabled by
default). When it is enabled, the implicit statistics from
`auto_statistics_types` leave out `uniq` and `uniq_v2` for `Float32` and
`Float64` columns, also inside `Nullable`. Only implicit statistics are
affected: an explicit `STATISTICS(uniq)` still builds a sketch, and `BFloat16`
and `LowCardinality` columns are unaffected.

Both settings decide the implicit statistics, so a settings `ALTER` derives
them again if either differs from its old value. `auto_statistics_types` is
now compared also when the table definition sets it; before, it always counted
as changed then.
Where the implicit `uniq` / `uniq_v2` of a column was left out by
`auto_statistics_assume_floats_distinct` and no sketch exists, the optimizer
assumes that all non-NULL values are distinct, capped using `basic`. It is also
applied to columns left without any statistics (using the number of rows of the
parts), and the assumed value is shown in `system.parts_columns`.
With `auto_statistics_assume_floats_distinct` (the default), a Float column gets
no implicit uniq sketch, and the optimizer assumes its non-NULL values to be
distinct instead. With the sketch, its distinct count was `measured-statistics`
and kept both distinct-count guarantees. The assumed one was reported as
`synthetic-fallback`, the label of the placeholder for a column without a
distinct-count statistic, and kept none. It replaces the sketch by a documented
policy, so it gets its own origin, `ColumnStatsOrigin::AssumedDistinct`:

- `distinctCount(UpperBound)` gives the assumed value, and it keeps the same
  transformations as a measured upper bound. Like a measured distinct count, it
  describes the rows it counts.
- `distinctCount(Exact)` gives nothing: the value deliberately errs upward.
- Columns without a sketch and without the assumption stay `synthetic-fallback`.

As for a sketch, the guarantees don't cover the numerical error of the value:
the cap for equal minimum and maximum misses NaNs, which the minimum and
maximum skip, and `-0.0`, which compares equal to `0.0`.

The origin only feeds the guarantees and the diagnostic string. The planner
reads `num_distinct_values` as before, so no plan changes.
@cv4g
cv4g force-pushed the disable-uniq-for-float-columns branch from 4a4364a to 8ef5b86 Compare November 23, 2026 23:22

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

comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants