Skip to content

Fix relation statistics edge cases - #122308

Open
cv4g wants to merge 21 commits into
masterfrom
statistics-fixes-prep
Open

cv4g wants to merge 21 commits into
masterfrom
statistics-fixes-prep

Conversation

@cv4g

@cv4g cv4g commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Extracted from #121736: three independent fixes of the estimates that the planner derives from column statistics, and a few cosmetic changes. Each fix has a stateless test that fails on master. Query results do not change, only the estimates used by join reordering and by the Cascades optimizer.

1. Statistics of an outdated column type

After ALTER TABLE ... MODIFY COLUMN with a conversion that changes the values (e.g. DateTime -> Date), a part keeps the column of the old type and its statistics until a mutation rewrites it: while the mutation is running or waiting, for good after KILL MUTATION, or for a part attached from before the ALTER. A read converts the values, but the statistics still describe the old ones. The relation profile without a filter did not check the type of the statistics, and Cascades passed no metadata to the estimator, so these statistics were used as they are. With a filter, they were rejected.

  • The profile without a filter checks the type like the profile with a filter, and Cascades passes the metadata of the read.
  • isCompatibleStatistics accepts the conversions that keep the values (isRepresentationPreservingConversion, as statistics-based part pruning and skip indexes do, e.g. the metadata-only Enum8 -> Int8), instead of requiring equal types.
  • Cascades loads the statistics of the parts selected by the index analysis, like RelationStatisticsEstimator does.

Tests:

  • 05617_statistics_outdated_type_join_estimate: a Date column with 1 distinct value keeps the DateTime statistics of 9826 distinct values while its mutation waits. A join that returns 100000 rows was estimated at 1.02 thousand rows without a filter and 100.00 thousand rows with one; both are 100.00 thousand now.
  • 05483_statistics_after_modify_column (metadata-only, converted), and unit tests in gtest_stats.cpp.

2. Parts that store a column with different types

Parts can also store a column with different types: after a metadata-only conversion (e.g. UInt32 -> DateTime) followed by inserts, until the old parts are merged, which in a table partitioned by time never happens; while a mutation is running; or for a part attached from before the ALTER. Statistics of different types cannot be merged. ConditionSelectivityEstimatorBuilder kept the type of the first part and skipped the parts of any other type, so the estimate depended on the part order, and, since the profile with a filter rejected an outdated type, on the filter.

The builder now gets the metadata of the read (IStorage::getConditionSelectivityEstimator takes it). It skips the statistics that do not describe the current values, and prefers the statistics of the current type, which all parts get eventually. If the parts carry statistics of different outdated types only, the column gets none.

Statistics of an old type that keep the values but not their representation, e.g. Int32 -> Int64, are still not used: their states cannot be merged with those of the current type, and combining the estimates of different types is left for a follow-up.

Tests:

  • 05618_statistics_mixed_part_types_join_estimate: the same data in two tables that differ only in the partition holding the old type. A join that returns 1000 rows was estimated at 198.22 thousand rows with the old data first, 201.00 thousand rows with a filter, and 2.01 thousand rows with the old data last. All three are 2.01 thousand now.
  • 05483_statistics_after_modify_column (stale first, stale second, inserted after), and unit tests in gtest_stats.cpp.

3. Keys without a known number of distinct values in Cascades

A Cascades read adds an entry to the column statistics of every column it reads, to carry the column width, also for a column without statistics. The number of distinct values (NDV) of such an entry is 0, and several places took it as known:

  • A join copied it into the NDV of the output key, and narrowing the join keys to the smaller NDV erased the known NDV of the other side.
  • INTERSECT did not take a known NDV of a later input when the first input had no known NDV.
  • The +1 of a null-aware function such as assumeNotNull turned the unknown NDV into a known NDV of 1.

They all treat 0 as unknown now, like a missing entry (knownDistinctValues). As before for a missing entry, a join key without a known NDV is bounded by the row count of its side.

Tests:

  • 05394_cascades_group_by_key_without_statistics: e.g. a GROUP BY on a join key with 10 distinct values, whose other side has no statistics, was estimated at 1000000 groups, and at 10 now.
  • 04926_cascades_aggregation_pushdown: the plans of cases 3a and 25 change.
  • 03836_tpch_join_order_plans: Q09 gets an NDV hint for o_orderdate, which its o_year group key inherits.
  • A unit test in gtest_column_stats_derivation.cpp.

4. Cosmetic changes

Include order, extimation -> estimation, an em dash in a comment, and the name of a lambda in a test. No behavior change.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes the row estimates that the query planner derives from column statistics after ALTER TABLE ... MODIFY COLUMN. Statistics of parts that still store the old column type are no longer used when they do not describe the current values, and when parts store a column with different types, the estimates no longer depend on the order of the parts or on whether the query has a filter. Also fixes estimates for join keys without statistics in the experimental Cascades optimizer. Better estimates help the planner choose a better join order; query results are not affected.


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

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c098044]

Summary: ❌

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

AI Review

Summary

Reviewed #122308 at c09804485c9a849c1dc036fc1df0320b0f0628e0, including the prior discussion and fixing commits. The change rejects statistics of incompatible column types, prefers statistics of the current type, and preserves unknown distinct-value counts through Cascades derivation. No remaining blocker or major finding; one metadata nit remains.

PR Metadata

The Bug Fix category is appropriate, and the required changelog entry is present and specific. Its unconditional order-independence claim needs narrowing after the final simplification. Suggested replacement entry:

Fix query-planner row estimates after ALTER TABLE ... MODIFY COLUMN by rejecting incompatible column statistics and consistently preferring statistics of the current column type when available. Also fix estimates for join keys without statistics and propagation of unknown distinct-value counts in the experimental Cascades optimizer. These changes affect plan selection, not query results.

Missing context / blind spots
  • ⚠️ No local build or ClickHouse executable was available. The current head's targeted stateless and bugfix-validation reports did not yet contain test results when checked; completed CI results would close this execution gap. Regression coverage was reviewed in source.
Findings

💡 Nits

  • ConditionSelectivityEstimator.cpp:750: The intentional best-effort path keeps the first usable statistics when neither type matches the current type. The unit test explicitly expects different distinct-value counts for different orders of old types. Update the changelog as suggested above, and replace the description's obsolete sentence saying these columns receive no statistics with: “If parts carry statistics of different compatible outdated types only, the builder keeps statistics matching the first usable part.”
Final Verdict

✅ Approve — no blocker or major findings. The metadata correction is non-blocking.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 25, 2026

void buildQueryGraph(QueryGraphBuilder & query_graph, QueryPlan::Node & node, QueryPlan::Nodes & nodes, int join_steps_limit);

static String dumpStatsForLogs(const RelationStats & stats)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Merged to src/Processors/QueryPlan/Optimizations/RelationStatisticsUtils.cpp

namespace
{

String dumpStatsForLogs(const RelationStats & stats)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Merged to src/Processors/QueryPlan/Optimizations/RelationStatisticsUtils.cpp

namespace DB
{

String dumpRelationStatsForLogs(const RelationStats & stats)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Moved from src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp and src/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp

#include <Processors/QueryPlan/ReadFromMergeTree.h>
#include <Processors/QueryPlan/Serialization.h>
#include <Processors/Transforms/JoiningTransform.h>
#include <Processors/QueryPlan/Optimizations/Optimizations.h>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Include order fix

for (const auto & [column_name, estimator] : column_estimators)
{
if (!isCompatibleStatistics(metadata, estimator.stats, column_name))
continue;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Perform type check on statistics.

A typical sequence is:

  1. Statistics are collected for column x UInt32.
  2. ALTER TABLE ... MODIFY COLUMN x Int64 changes the table metadata.
  3. Existing data parts and their stored statistics may still describe x as UInt32 until the mutation is materialized or parts are rewritten.

During that interval, using the old NDV, min/max, or null statistics for the new logical column type may be invalid. isCompatibleStatistics() compares the statistic’s stored type with the current metadata and skips mismatches.

/// Constrain the inner-product estimate to the join semantics (outer joins keep the preserved side,
/// semi/anti/any bound it). Applied after the join-order hint so a hint cannot exceed a semantic
/// upper bound (e.g. a semi join above its preserved-side row count).
const auto & join_operator = join_step.getJoinOperator();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Moving the definition up to enable use in line 259

#include <fmt/format.h>
#include <Common/Exception.h>
#include <Common/SipHash.h>
#include <Common/assert_cast.h>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Include order fix

rhs_estimation ? toString(rhs_estimation.value()) : "unknown");

if (lhs_extimation && rhs_extimation && lhs_extimation < rhs_extimation)
if (lhs_estimation && rhs_estimation && lhs_estimation < rhs_estimation)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Typo

stats.null_fraction.reset();
}
mapped[outputs[output_lineage.output_position]->result_name] = stats;
mapped[output.result_name] = stats;

@cv4g cv4g Sep 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Make sure statistics of ambiguous column name don't get mixed up. We'd have to make the map position-based to obtain the correct statistics.

We got a similar issue in #121647 (Resolve JOIN runtime filter keys by header position) iirc.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 25, 2026
cv4g added 3 commits October 14, 2026 07:25
After `ALTER TABLE ... MODIFY COLUMN`, a part keeps statistics of the old
type until the mutation rewrites it. `ConditionSelectivityEstimatorBuilder`
kept the type of the first part and skipped parts of another type, while
`total_rows` still counted every part. With the current type first - the
usual state while a mutation runs, since it rewrites the leading parts
first - the column got the NDV and value range of the rewritten parts only.
With the old type first, `isCompatibleStatistics` rejected the column. The
result depended on the part order.

Drop a column whose parts carry statistics for different types for the
whole snapshot. Parts with the same type but a different set of statistics
(e.g. `MODIFY STATISTICS` not materialized yet) keep the previous behavior.
A Cascades read adds an entry to the column statistics of every column it
reads, to carry the column width, whether the column has statistics or
not. Such an entry has `num_distinct_values = 0`, but `keyDistinctValues`
took any entry as a known NDV: `GROUP BY` or `DISTINCT` on a column without
statistics - including one whose statistics were rejected for an outdated
type - estimated a single group with `max_row_count = 0`. The join
derivation copied the zero into the output key NDV, where the shared key
update erased the other side's known NDV, and `INTERSECT` erased a known
NDV the same way.

Add `knownDistinctValues`, which treats zero as unknown, and use it in all
three places, so each falls back as it does for a missing entry: 10% of the
input rows for a group key, the row count for a join key, no bound for
`INTERSECT`.

`remapColumnStats` added the +1 of a null-aware hop (e.g. `assumeNotNull`,
a `CAST` dropping `Nullable`) to an unknown zero as well, which turned it
into a known NDV of 1 and kept such keys at a single group. Keep an
unknown NDV unknown there.

Test changes:
- 04926 case 3a (join key without an NDV hint) now gets the same plan as
  case 3; it still checks that the aggregation is not pushed down.
- 03836 Q09 groups by `toYear(o_orderdate)`; its hint now carries the
  SF100 `o_orderdate` NDV of the base hint, which keeps the plan.
@cv4g

cv4g commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Cherry-picked d5b29b2 from #121736 to fix failing 05210_cascades_shard_partial_aggregation_bucket_order.

@clickhouse-gh

This comment was marked as outdated.

@bacek bacek mentioned this pull request Oct 22, 2026
1 task done
@hanfei1991 hanfei1991 self-assigned this Oct 22, 2026

@hanfei1991 hanfei1991 left a comment

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.

We have some bug fix and comestic changes in this PR. Could we seperate them to make it easier to review?

return;

has_data = true;
if (columns_with_mixed_types.contains(column_name))

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.

Could you please give me an example to reproduce some bug for unequal types? because for some type of unequal types it's OK, for example Int32->Int64.

result.rows = total_rows;
for (const auto & [column_name, estimator] : column_estimators)
{
if (!isCompatibleStatistics(metadata, estimator.stats, column_name))

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.

Could you write a stateless test to cover this case? I couldn't figure out a bug here right now.

@cv4g cv4g left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thank you Han Fei, I'll look into the two issues not covered by tests yet

cv4g added 2 commits November 2, 2026 15:40
…Y COLUMN

A part keeps the statistics of the type it stores. After a metadata-only
`ALTER TABLE ... MODIFY COLUMN` (e.g. `Enum8` -> `Int8`) they still describe
the values a read returns, but the estimator rejected every statistic whose
type was not equal to the current one, in the filtered and now also in the
unfiltered profile. Accept the conversions that keep the representation, like
the statistics part pruning and the skip indexes do, and keep rejecting those
that change the values (e.g. `DateTime` -> `Date` for a part detached
during the `ALTER`).

Move the Cascades regression for a rejected sketch from 05394 to a dedicated
test, which now uses a value-changing conversion.
…nt types

Statistics of different column types cannot be merged. The estimator builder
kept the type of the first part and skipped the others, so the result depended
on the part order, and the previous commit of this PR dropped the column
altogether, also after a metadata-only `MODIFY COLUMN` followed by inserts,
until all old parts were merged.

The builder now gets the metadata of the read. It skips statistics that do not
describe the values of the current type, and prefers the statistics of the
current type, which all parts get eventually. Only of two outdated types, which
are equally good, the column gets none.
EXPECT_FALSE(restored->hasNullCount());
}

namespace

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.

Kindly prefer writing stateless SQL tests instead of low-level unit tests. The latter are harder to run and expensive to maintain.


-- Q09: Product type profit measure (part, supplier, lineitem, partsupp, orders, nation)
-- Filter: p_name LIKE '%green%' -> ~1.13M parts (real selectivity ~5.6%).
-- `o_orderdate` keeps its SF100 NDV: the `o_year` group key inherits it, without it the key would

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.

Someone reading the new comment in a few weeks from now will not be able to understand what it means, better remove it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

estimator->total_rows += rows;
}

/// Compare type names as `ColumnStatistics::structureEquals` does: `Bool` and `UInt8` are equal under

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.

I feel this code should go somewhere into existing function isCompatibleStatistics.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. There is a new matchStatisticsType that returns an enum StatisticsTypeMatch (equal, compatible, incompatible) that is also called by isCompatibleStatistics now.

private:
bool has_data = false;
ConditionSelectivityEstimatorPtr estimator;
/// Columns whose parts carry statistics for different data types. They get no statistics, see `addStatistics`.

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.

How can the parts of a column carry statistics for different data types? In ALTER TYPE, no? In any case this is an edge case and we should rather do something more simple and more dumb like calculating a best-effort estimation instead of adding special handling for them (that needs its own member variable).

@cv4g cv4g Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, it's ALTER TYPE until the mutation rewrites the parts. This can also happen when a part is attached after an alter type it seems. Also column type changes between types with the identical on disk serialization are metadata-only and not converted eagerly by mutation.

I simplified it in 5711d6de48ec: The builder now skips incompatible statistics, merges those of the same structure, and prefers those of the column type. Statistics it can neither merge nor prefer are skipped, like those of a part with the same type but a different set of statistics. That can happen after aMODIFY STATISTICS that is not materialized in all parts yet.

cv4g added 7 commits November 13, 2026 11:34
With 10000 distinct values the `uniq_v2` sketch (`uniqCombined64` with
precision 12) is in its HyperLogLog mode and estimates 9826, so the
`GROUP BY` estimate before the `ALTER` never matched `~10000.0`. Check
that it is close to 10000 instead, which still tells the statistics from
the fallback to 10% of the rows after the `ALTER`.
Two outputs of a query can share a name only when they are the same
expression (e.g. `SELECT k, k`, or `SELECT k, j AS k`, where `k` resolves
to the alias), and then their statistics are the same as well. Dropping
them made `(k, k) INTERSECT DISTINCT (x, y)` estimate 1000 rows, the
fallback, instead of 5, the exact number of rows, as before. Restore the
previous behavior of `remapColumnStats` and of the `INTERSECT` derivation.
A join took the zero NDV of a key without statistics as known, and
narrowing the join keys to the smaller NDV erased the known NDV of the
other side. A `GROUP BY` on that key above the join was estimated at
1000000 groups on master, and at the 10 groups it has now.
While the mutation of a `DateTime` -> `Date` conversion waits, the part
keeps the `DateTime` statistics, which count 9826 distinct values for a
column with 1. The join-order optimizer used them without a filter and
estimated a join that returns 100000 rows at 1.02 thousand rows on
master; with a filter they were rejected. Both estimates are 100.00
thousand rows now.
After a metadata-only `UInt32` -> `DateTime` conversion followed by
inserts, the old and the new partitions store `ts` with different types.
Only the statistics of the first part's type were used, and with a
filter those of the old type were rejected: the same data gave
198.22 thousand, 201.00 thousand and 2.01 thousand rows on master,
depending on the part order and the filter. The current type is
preferred now, and all three are 2.01 thousand rows.
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 17, 2026
cv4g added 2 commits November 18, 2026 11:18
The estimator builder compared statistics types with the metadata in
`isCompatibleStatistics` and `hasCurrentType`, with each other in
`haveSameDataType`, and kept the columns whose parts carried two
outdated types in a member of its own, so that they got no statistics.

`matchStatisticsType` now tells whether the type of statistics is equal
to the column type (by name, as `structureEquals` compares them),
compatible with it (a read converts the values without changing them),
or incompatible, and `isCompatibleStatistics` is built on it. The
builder skips incompatible statistics, merges those of the same
structure, prefers those of the column type, and otherwise keeps the
first ones, as it already did for a different set of statistics. With
two outdated types, or without metadata, the column now keeps the
statistics of the first part instead of none: they still describe the
values, only of a subset of the parts.

#122308 (comment)
#122308 (comment)
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 18, 2026 11:44

AI review of a later commit does not approve the PR, see the AI Review comment.

@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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 19, 2026

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants