Skip to content

Track and cache provenance-aware relation statistics for JOIN optimization - #121736

Draft
cv4g wants to merge 24 commits into
masterfrom
relation-statistics-provenance
Draft

cv4g wants to merge 24 commits into
masterfrom
relation-statistics-provenance

Conversation

@cv4g

@cv4g cv4g commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Extracted from #121647.
Prep for #96779 (MinMaxRuntimeFilter), #97501 (statistics based disabling of RuntimeFilters).

Changes extracted from this PR that need to be merged before:


Relation statistics previously retained values such as row counts, NDVs, and min/max ranges without recording how those values were obtained or transformed. Consumers could therefore treat statistics from filtered rows, partial part coverage, estimated clamps, or unsupported plan steps as stronger evidence than they actually were.

JOIN optimizations also independently recalculated statistics for the same relation subtrees.

Changes:

  • Track independent provenance for column NDVs and value ranges.
  • Record transformations such as filtering, non-uniform row subsets, estimated/exact row clamps, partial part coverage, expressions, and unsupported plan steps.
  • Track whether relation row counts are exact.
  • Add predicates through which consumers request specific guarantees, such as an exact distinct count or representative value range.
  • Make relation-statistics traversal iterative.
  • Cache relation statistics across the second-pass JOIN optimizations, with invalidation and rebinding around plan mutations.
  • Drop statistics for ambiguous duplicate output names.
  • Make IEJoin selectivity estimation use only representative ranges.
  • Preserve statistics through provably non-truncating limits while failing closed for grouping sets, overflow rows, and unsupported transformations.
  • Include provenance in optimizer trace diagnostics.

The change set builds on a lot of insights created by #120784 (PoC: Data properties for join order cardinality cap).

Changelog category (leave one):

  • Improvement

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

Improved JOIN planning by tracking the provenance and exactness of relation statistics, rejecting unreliable statistics where stronger guarantees are required, and caching statistics across JOIN optimization passes.


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

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d5b29b2]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: Duplicate announcement received for replica number A (STID: 8765-6e14) FAIL cidb
Stress test (arm_debug) FAIL
Received signal 6 (internal) (STID: 3593-560a) FAIL cidb

AI Review

Summary

This PR adds provenance-aware relation statistics plus a pass-local cache for join planning. The main estimator and most consumers now respect the new provenance model, but the Cascades-only derivation still bypasses it in two places, so make_distributed_plan = 1 with enable_cascades_optimizer = 1 can still treat weak read or aggregation statistics as exact and make planning decisions on them.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:435] deriveReadStatistics copies estimateRelationProfile directly into the Cascades stats, but it never adds the read-step provenance downgrades that estimateDirectRelationStats applies for FINAL, row-level filters, lightweight deletes, SAMPLE, masking policies, and on-the-fly mutations. In those cases the distributed Cascades path can still expose whole-part NDVs and ranges as exact to later consumers such as AggregationPushdown, join selectivity, and IEJoin.
  • [src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:726] deriveAggregatingStatistics still copies grouped-key stats verbatim instead of reusing makeGroupingKeyStats and the Unsupported / NonUniformRowSubset tagging from estimateAggregatingStepStats. Under Cascades, grouped keys therefore retain exact-looking NDV and range provenance through estimated row-count clamps, GROUPING SETS, overflow rows, and non-THROW max_rows_to_group_by, which can make later join and aggregation decisions rely on guarantees the new contract explicitly rejects.
Tests
  • Missing regression coverage for Cascades reads with read-step-only provenance changes and for grouped-key provenance downgrades in deriveAggregatingStatistics.
Final Verdict

Needs fixes before merge: the Cascades read and aggregation derivations still need to mirror the new provenance rules that the main relation-statistics estimator now enforces.

LLVM Coverage Report

Measured on commit d5b29b2.

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

Changed lines: Changed C/C++ lines covered: 787/829 (94.93%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 23, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 23, 2026
@cv4g
cv4g force-pushed the relation-statistics-provenance branch from 9d7306d to 2c33e9d Compare September 23, 2026 12:14
Predicate-filtered, PREWHERE-filtered, and trivial-LIMIT join inputs deliberately lose representative value ranges and choose IEJoin keys in syntax order. Non-truncating  inputs continue to use statistics-based key selection.
Allow-listed query-plan steps now retain row counts and column-statistics provenance when they pass existing values through unchanged. Unknown row-preserving transforms still fail closed as unsupported. The correlated EXISTS stateless case was omitted because the decorrelated plan did not produce an IEJoin Conditions line.
NULL fractions now follow range provenance and are cleared by generic distinct-value-bound expressions that may change NULL semantics. Row subsets retain the diagnostic fraction while consumers continue to require a matching range guarantee.
Vector-search reads, top-k skip-index pruning, and non-throwing GROUP BY limits now invalidate exact or representative relation statistics when they can emit a subset without an explicit filter step. GROUP BY limits fall back to syntax-order IEJoin keys. Vector and top-k read cases remain without direct tests because constructing a real ReadFromMergeTree fixture is not practical and adding a skip index would perturb the shared stateless fixture.
Equi-key NDVs are now reduced only on join sides whose rows may be filtered. LEFT, RIGHT, FULL, ANTI, and SEMI joins retain the preserved-side estimate instead of treating the other side as an upper bound. Existing join-order references remain unchanged.
A sorting limit over an unknown input row count now records the synthesized limit as inexact. Limit and sorting tests cover the public estimator with exactness set but no row estimate.
Cached estimates now snapshot each node step and child addresses. Release builds self-heal stale entries as misses, while debug and sanitizer builds assert to expose missed invalidations. Rebinding preserves valid snapshots. IEJoin cache threading remains a TODO because physical conversion is also called from lazy-materialization optimization outside the local signature chain.
Representative ranges explicitly use today’s exact-range guarantee, provenance formatting now has its own translation unit, and optimizer trace formatting has one shared implementation. Trace message bytes and planner behavior remain unchanged.
Thread the optimizer pass's optional non-owning statistics cache through logical-to-physical join conversion. IEJoin key selection now reuses estimates already computed for its inputs, while callers without a cache retain the existing temporary-estimation behavior.
FINAL reads can synthesize values in merging engines such as SummingMergeTree, so on-disk NDVs and ranges are not necessarily bounds for their output. Mark every FINAL read as Unsupported in addition to RowSubset, and cover the guarantee predicates and a SummingMergeTree optimizer trace.
Limit the initial cache to the join-optimization phase. Delayed physical conversion after filter, PREWHERE, parallel-replica, and distributed rewrites now uses a fresh cache, preventing IEJoin from reusing stale pre-rewrite estimates while retaining reuse within the final plan.
Distributed aggregation now uses grouping-key NDVs only when their provenance establishes exact row coverage. Filtered or otherwise transformed NDVs fall back to the existing row-count or unknown strategy path instead of being treated as lower bounds; regression coverage keeps exact NDVs eligible.
Join cardinality estimation now consumes column NDVs only when their provenance preserves the distinct-count upper-bound contract, falling back to relation rows otherwise. Join-key propagation also avoids letting an unsafe clamped NDV reduce a valid estimate on the opposite side.
Mark test-only table statistics hints and randomized join statistics as explicit synthetic overrides. Allow those overrides through provenance gates while keeping heuristic synthetic fallbacks untrusted.
: Float64(relation_profile.rows);
for (const auto & [column_name, column_stats] : relation_profile.column_stats)
statistics.column_statistics[column_name].num_distinct_values = column_stats.num_distinct_values;
statistics.column_statistics[column_name] = column_stats;

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.

deriveReadStatistics now copies the full ColumnStats, but it still never layers on the extra read-step provenance that estimateDirectRelationStats adds for modifiers outside the explicit PREWHERE: FINAL, row-level filters, lightweight deletes, SAMPLE, masking policies, on-the-fly mutations, and similar cases. In those plans the Cascades path will keep whole-part NDV/range provenance and downstream consumers such as AggregationPushdown, join selectivity, or IEJoin range checks can still treat the stats as exact even though the main estimator now fails closed.

Can we mirror the has_row_subset / has_unsupported_value_changes handling from RelationStatisticsEstimator.cpp here before returning the read stats? estimateRelationProfile already covers the explicit PREWHERE, but the read-step-only transformations are still missing.

{
/// Grouping retains the set of key values. Preserve its NDV and range provenance;
/// null fraction is not meaningful after one output row is produced per group.
auto column_stats = input_column_statistics->second;

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.

deriveAggregatingStatistics still diverges from the new provenance contract in makeGroupingKeyStats / estimateAggregatingStepStats. This path copies the input key stats verbatim, so a grouped key keeps looking exact through cases that the main estimator now downgrades: an NDV numerically clamped by an estimated input row count, GROUPING SETS / overflow rows, and max_rows_to_group_by with a non-THROW overflow mode.

That means make_distributed_plan = 1 with enable_cascades_optimizer = 1 can still feed unsafe grouped-key NDVs into later consumers such as AggregationPushdown or deriveJoinStatistics. For example, after a filtered input with estimated_row_count = 100, a key whose carried NDV is 1000 will still be copied out as 1000 with an apparently valid upper-bound provenance instead of failing closed. Please reuse makeGroupingKeyStats here and mirror the Unsupported / NonUniformRowSubset tagging from estimateAggregatingStepStats.

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d5b29b2ea with master ef8d752e5 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 313e6e829; 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

347 object files changed (+152.57 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp.o 182.14 KiB 215.71 KiB +33.57 KiB (+18.43%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/RelationStatisticsUtils.cpp.o 301.92 KiB 332.61 KiB +30.70 KiB (+10.17%)

716 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

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

Job report

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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant