Repository navigation
Conversation
|
Workflow [PR], commit [d5b29b2] Summary: ❌
AI ReviewSummaryThis 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 Findings
Tests
Final VerdictNeeds fixes before merge: the LLVM Coverage ReportMeasured on commit d5b29b2.
Changed lines: Changed C/C++ lines covered: 787/829 (94.93%) · Uncovered code |
9d7306d to
2c33e9d
Compare
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; |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes347 object files changed (+152.57 KiB total), 1 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units113 translation units recompiled, 847 s compile time in total, 112 of them have a recent master baseline. |
Extracted from #121647.
Prep for #96779 (MinMaxRuntimeFilter), #97501 (statistics based disabling of RuntimeFilters).
Changes extracted from this PR that need to be merged before:
RelationStatsCache#122259Relation 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:
The change set builds on a lot of insights created by #120784 (PoC: Data properties for join order cardinality cap).
Changelog category (leave one):
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]