Repository navigation
Compose join-order statistics over parts surviving partition/PK pruning - #110283
Conversation
|
Workflow [PR], commit [336f5c1] Summary: ✅
AI ReviewSummaryThis PR fixes join-order estimation for Final Verdict✅ No new review findings on the current head. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 126/129 (97.67%) · Uncovered code |
|
@fkastrati The behavior has been like that forever, therefore it's not urgent. But would you take this PR for review later this week? Thanks. |
Symptom: `WHERE 0` under statistics-enabled join reordering regressed from an exact zero estimate to unknown after estimator scope moved to pruned parts. Root cause: early `selectRangesToRead` exits returned an empty `AnalysisResult` without `index_stats`; the empty-part estimator returned null and the fallback treated the pushed filter as unestimated. Fix: mark proven-empty early analysis results as exact and return zero before estimator/fallback logic. The streaming early exit remains non-exact. Verification: rebuilt `clickhouse`; `04516_join_order_estimation_pruned_parts` output matches its reference; trace reports zero rows for both sides of the `WHERE 0` join. Residual risk: full post-push CI is pending. PR: #110283
Symptom: statistics-enabled join estimation called `selectRangesToRead` before `optimizeReadInOrder`, so `ORDER BY` queries with a small `LIMIT` could fail against `max_rows_to_read` using the full-table estimate. Root cause: the estimator reused the execution analysis path, which both enforced throwing read limits and memoized the premature result before `input_order_info` existed. Fix: under throwing `max_rows_to_read` or `max_rows_to_read_leaf`, run a non-memoized estimator-only range analysis without row-limit checks. The final read analyzes again after read order is known and enforces limits unless InOrder applies. Verification: rebuilt `clickhouse`; `04516_join_order_estimation_pruned_parts` matches its reference. The InOrder probe reads approximately one row and succeeds; disabling InOrder still throws `TOO_MANY_ROWS` from final pipeline initialization. Residual risk: full post-push CI is pending. PR: #110283
@rschu1ze sure. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 120/126 (95.24%) · Uncovered code |
Symptom: with column statistics enabled (use_statistics = 1, default), the join-order optimizer estimated relation cardinalities over all active parts, ignoring partition/PK pruning that execution performs. A query pruned to a 1000-row partition of a 5M-row table was planned at 2,500,500 rows (2500x), flipping the chosen build side; identical under use_statistics_cache = 0/1. Paradoxically, use_statistics = 0 gave a better plan: the index-based fallback runs selectRangesToRead() and is pruning-aware. Issue #110281. Root cause: at optimizeJoin time analyzed_result_ptr is not set yet, so ReadFromMergeTree::getParts() falls back to prepared_parts (all parts) when building the ConditionSelectivityEstimator; the table-wide cached_estimator (populated by the background refreshStatistics() over all parts) matched that wrong scope, masking the divergence. Fix: estimateReadRowsCount() now obtains the partition/PK analysis result up front (getAnalyzedResult() or selectRangesToRead(), exactly as the fallback branch already did) and composes statistics over parts_with_ranges. MergeTreeData::getConditionSelectivityEstimator() returns the table-wide cached estimator only when the requested part set matches the set the cache was built over (reusing ConditionSelectivityEstimator::isStale); otherwise it folds statistics over the query's surviving parts. Verification: standalone reproducer (5M+1k fact / 100k dim): fact estimate 2,500,500 -> 1,000 under both cache settings; pruned-query plan cost now bit-identical to the physically-pruned counterfactual (996.86); unpruned query with warm cache still hits the cache (0 statistics loads). Stateless: new 04516_join_order_estimation_pruned_parts plus 03707_statistics_cache, 03279_join_choose_build_table_{,auto_}statistics, 03788_statistics_part_ pruning{,_nan}, 02864_statistics_*, explain-estimate suites - all green locally (macOS debug build @ 5a9528b). Residual risk: the statistics path now runs index analysis at planning time (same cost the use_statistics = 0 path already pays; result is not memoized, matching the existing fallback precedent, so execution re-runs analysis). Pruned queries bypass the table-wide estimator cache and fold per-part statistics on each query; a part-set-keyed cache is possible follow-up work.
F-1: join-order estimation memoizes the index-analysis result (selectRangesToRead() writes analyzed_result_ptr), and optimizeLazyFinal treated any non-null analysis result as an applied projection, silently disabling lazy FINAL for join relations - previously only on the no-statistics fallback path, and after the parent commit also on the default statistics path. The guard now checks readFromProjection() instead of mere presence, restoring lazy FINAL in both cases. Regression test 04517: InputSelector present for stats-enabled and stats-disabled ReplacingMergeTree FINAL under a JOIN, plus result correctness. F-4: the statistics-cache hit path allocated a DataPartsVector and copied part pointers under stats_mutex on every request. Now the cached estimator shared_ptr is copied under the lock and the part-set comparison runs outside it via a new allocation-free isStale(RangesInDataParts) overload (the estimator is immutable once published). Test coverage: - 04518 (new, sh): warm table-wide cache via background refresh (deterministic retry on LoadedStatisticsMicroseconds = 0, same oracle as 03707_statistics_cache), then: pruned query bypasses the cache AND gets pruned-scope estimates; unpruned cache hit preserved afterwards. - 04516: NDV oracle probe (f[100] = 1000 x 1/NDV(id) is derivable only from pruned column statistics; the index fallback yields f[1000], so a silently degraded statistics path now fails the test) and a PK-only pruning case (no partitioning, part fully excluded by primary key). Verification: local (macOS debug @ 5a9528b) - 04516/04517/04518 green; lazy_final suite (03990, 03991; 03988/04092/04093 skipped: no-debug), statistics and join-order suites green; reproducer behavior unchanged (fact 1000 rows both cache settings, counterfactual-identical cost, warm-cache hit preserved).
After the readFromProjection() guard fix, optimizeLazyFinal proceeded for join relations whose analysis was already memoized by join-order estimation, then unconditionally called selectRangesToRead() again - repeating the full part/PK/skip-index analysis at planning time (T3: two SelectExecutor 'Key condition' passes over the same parts in one stats-enabled ReplacingMergeTree FINAL JOIN query). Reuse the memoized result and analyze only when absent: passes drop 2 -> 1, InputSelector and result correctness unchanged. PK conditions are pushed in the first optimization pass, before both consumers, so both analyses were provably identical. tests/performance/join_planning_pruned_statistics.xml: planning-only EXPLAIN benchmarks (100/1000-part fact, selective/unselective predicate, statistics cache on/off) plus a lazy FINAL join execution query, so CI perf compares merge-base vs head on a release build for exactly the paths this PR touches.
Review findings on the previous version: - the cache-enabled query ran against tables with refresh_statistics_interval = 0, where cached_estimator is never populated (only the background refreshStatistics() task writes it) - it measured a null-cache miss, not the part-set comparison; - the lazy FINAL benchmark executed a 1.5M-row FINAL JOIN over a 2-part table, so runtime dominated and the duplicate-planning-analysis regression it was supposed to guard would drown in noise. Now: fact_1000p_cached uses refresh_statistics_interval = 1 and a trailing sleep(2) fill query so the table-wide cache is genuinely warm (verified locally: unpruned cache=1 EXPLAIN performs zero statistics loads, pruned performs the bypass fold) - the unpruned query exercises the O(parts) part-set comparison over 1000 parts, the pruned one the size-mismatch bypass. The lazy FINAL guard is a planning-only EXPLAIN over a 200-part ReplacingMergeTree (100 partitions x 2 overlapping inserts, InputSelector verified present in the plan); the end-to-end execution query is kept as a separate benchmark and no longer claimed as a planning guard.
Symptom: `WHERE 0` under statistics-enabled join reordering regressed from an exact zero estimate to unknown after estimator scope moved to pruned parts. Root cause: early `selectRangesToRead` exits returned an empty `AnalysisResult` without `index_stats`; the empty-part estimator returned null and the fallback treated the pushed filter as unestimated. Fix: mark proven-empty early analysis results as exact and return zero before estimator/fallback logic. The streaming early exit remains non-exact. Verification: rebuilt `clickhouse`; `04516_join_order_estimation_pruned_parts` output matches its reference; trace reports zero rows for both sides of the `WHERE 0` join. Residual risk: full post-push CI is pending. PR: #110283
Symptom: statistics-enabled join estimation called `selectRangesToRead` before `optimizeReadInOrder`, so `ORDER BY` queries with a small `LIMIT` could fail against `max_rows_to_read` using the full-table estimate. Root cause: the estimator reused the execution analysis path, which both enforced throwing read limits and memoized the premature result before `input_order_info` existed. Fix: under throwing `max_rows_to_read` or `max_rows_to_read_leaf`, run a non-memoized estimator-only range analysis without row-limit checks. The final read analyzes again after read order is known and enforces limits unless InOrder applies. Verification: rebuilt `clickhouse`; `04516_join_order_estimation_pruned_parts` matches its reference. The InOrder probe reads approximately one row and succeeds; disabling InOrder still throws `TOO_MANY_ROWS` from final pipeline initialization. Residual risk: full post-push CI is pending. PR: #110283
Explain that `ReadFromMergeTree` memoizes analysis-time parts and mark ranges, not runtime cardinalities, and document the throwing-row-limit and exact-empty invariants requested during review.
STREAM reads defer index analysis to execution, so an empty AnalysisResult is not an exact zero for join-order estimation. Return an explicit unknown estimate and add a focused regression. Pin the PR statistics tests to the new analyzer because their planner contract is analyzer-specific. Baseline local 26.7.1.1315 regression produced 0 for the old f[0] plan; the patched test expects f[no_stats~?]. Narrow optimizeJoin compilation was attempted but is blocked by the existing Darwin build flags' UInt64/size_t mismatch. Full CI and rebuilt-server execution remain pending.
Keep the STREAM JOIN regression on the analyzer path with parallel replicas disabled, statistics enabled, and runtime hash-table collection disabled. Require the physical equi-join to remain visible while rejecting the false zero estimate.
The fresh-master selectRangesToRead signature requires an explicit check_row_limits flag. Keep the query-condition-cache-free parallel-replica estimate on the pre-existing row-limit path while leaving the join cardinality estimator's limit-free helper unchanged. Verified with git diff --check and an audit of every static selectRangesToRead caller. Rebuilt-server and full CI gates remain unavailable.
797ef42 to
113ce6b
Compare
The test filtered EXPLAIN output to the join heading before checking the separate join-condition line, making its assertion deterministically false. Evaluate all three countIf predicates over the complete plan output.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Object file sizes10 object files changed (+23.16 KiB total), 0 added.
737 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 units126 translation units recompiled, 1728 s compile time in total, 126 of them have a recent master baseline. |
| <!-- let the background refresh warm the estimator cache of fact_1000p_cached --> | ||
| <fill_query>SELECT sleep(2) FORMAT Null</fill_query> | ||
|
|
||
| <!-- pruned predicate, cold cache: per-part statistics fold at 100 and 1000 parts --> |
There was a problem hiding this comment.
@skuznetsov-clickhouse The test itself is fine but the comments use weird terminology/language which will be hard to decipher for future readers (examples: size-mismatch bypass plus a one-part fold, pruned predicate). In future PRs, let's avoid that.
| <materialize_statistics_on_insert>1</materialize_statistics_on_insert> | ||
| </settings> | ||
|
|
||
| <create_query> |
There was a problem hiding this comment.
Please see join_planning_pruned_statistics in the performance report. Runtimes for some queries are 2 and 3 milliseconds. That could create fluctuating measurements. It would be good to make the filter (WHERE f.p = 5) less selective so that more statistics must be merged and runtimes increases to at least 50 msec. Can be done as a follow-up.
| RelationProfile estimateRelationProfile() const; | ||
|
|
||
| bool isStale(const std::vector<DataPartPtr> & data_parts) const; | ||
| /// Same check against a query's analyzed part set, without materializing a parts vector. |
There was a problem hiding this comment.
(Function isStale deserves a function-level comment that states what it is doing without making the reader study the implementation)
| cached = cached_estimator; | ||
| } | ||
|
|
||
| /// The cached estimator is built by refreshStatistics() over all active parts. |
There was a problem hiding this comment.
(Minor: "compose" is a weird term, maybe "merge"? Also "the estimator is immutable" is strangely stated.)
| /// partition/PK analysis must compose statistics over the surviving parts | ||
| /// (issue #110281). The estimator is immutable once published, so the comparison | ||
| /// can run outside the mutex. | ||
| if (cached && !cached->isStale(parts)) |
There was a problem hiding this comment.
Assume data is continuously inserted into the table and new parts are created all the time (which is the normal case).
The cached estimator was introduced in some point to avoid the overhead of reading statistics from disk for every part and every column in each query.
Before this PR, the cached estimator was used (which itself provided statistics for the parts before pruning but at least avoided reading them from disk).
Now, the normal case is that isStale (l. 930) becomes true and we can't use the cached estimator anymore. This basically renders the caching mechanism ineffective in the presence of INSERTs or other DDLs.
From a "correctness" POV, the new approach is the preferred one. Just saying ... there can be performance regressions ... and interestingly we wouldn't even notice because all our benchmarks run on static datasets.
| = (settings[Setting::read_overflow_mode] == OverflowMode::THROW && settings[Setting::max_rows_to_read]) | ||
| || (settings[Setting::read_overflow_mode_leaf] == OverflowMode::THROW && settings[Setting::max_rows_to_read_leaf]); | ||
|
|
||
| /// Join-order estimation needs these ranges before `optimizeReadInOrder` runs. Both variants |
There was a problem hiding this comment.
(General note: let's try to avoid code comments which reference functions in completely different areas of the code.)
| : reading->selectRangesToRead(); | ||
| } | ||
|
|
||
| /// `has_exact_ranges` is a deterministic index-analysis result, not a confidence estimate. |
There was a problem hiding this comment.
It's difficult to decipher the (AI-generated) code comment.
| if (!analyzed_result) | ||
| { | ||
| const auto & settings = reading->getContext()->getSettingsRef(); | ||
| const bool has_throwing_row_limit |
There was a problem hiding this comment.
It's not clear to me why we need to check the two settings prior. I don't think the row limits apply to estimation.
Document the part-set cache and estimation-only range-analysis contracts after review of ClickHouse#110283. Make the performance workload exercise 950 of 1000 parts so planning measurements are less sensitive to millisecond-scale noise.
|
@rschu1ze @fkastrati are you going to do the backports? |
|
@PedroTadim By convention, the PR author (@skuznetsov-clickhouse ) backports.
Though I honestly don't understand why we want to backport at all. It's a performance optimization, it is kind of a risky change, and there is a chance that follow-up PR will be necessary. Each of these things is a reason to decline the backport. |
|
The release board was suggesting, can close the backports. |
With parallel_replicas_min_number_of_rows_per_replica > 0 the analyzer asks ReadFromMergeTree for a row estimate to size the replica set. That estimate ran selectRangesToRead(), which analyzes with check_row_limits = true, so MergeTreeDataSelectExecutor charged the whole-granule row count of the base table against max_rows_to_read and threw TOO_MANY_ROWS at plan-build time. The projection escape hatch cannot help there: has_projections does not see the implicit _minmax_count_projection (it lives in StorageInMemoryMetadata::minmax_count_projection, not hasProjections()), and projection selection only runs later, in optimizeTreeSecondPass. So SELECT max(i) FROM x SETTINGS max_rows_to_read = 2 was rejected on a 10-row table even though _minmax_count_projection answers it without reading a single data row. Route that estimate through the non-enforcing, non-memoizing analysis whenever a throwing read row limit is set, which is what PR ClickHouse#110283 ("Defer read limits until read order is known", 5b6b32b) already established for the join cardinality estimator. Commit 113ce6b kept this call site on the pre-existing row-limit path during a conflict resolution; that pre-existing behaviour is the defect. Enforcement is unchanged for the read that executes: neither estimation entry point memoizes into analyzed_result_ptr, so the executed ReadFromMergeTree analyzes again through selectRangesToRead() and still throws when the read really exceeds the budget. The new test pins both directions, including sum() (which no implicit projection can serve) and the same query with optimize_use_implicit_projections = 0. The two estimate entry points collapse into one: selectRangesToReadForEstimation now takes allow_query_condition_cache_, so the query-condition-cache axis and the row-limit axis are independent, and estimateRangesToReadWithoutQueryConditionCache is gone. RelationStatisticsEstimator reuses the new hasThrowingReadRowLimit() predicate instead of its own inline copy (no behaviour change there). Surfaced by the randomization in ClickHouse#71028. Related: ClickHouse#71028 Co-Authored-By: Claude Opus 5 <[email protected]>

Closes: #110281
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Join-order cardinality estimation now composes column statistics over the parts surviving partition/PK pruning instead of all active parts. Previously a query pruned to a small partition was planned against table-wide statistics (observed 2500x row overestimation flipping the hash-join build side), and disabling statistics paradoxically produced a better plan. Also fixed: lazy FINAL was silently disabled for MergeTree relations under a JOIN because the join-order optimizer's memoized index-analysis result was mistaken for an applied projection.
Documentation entry for user-facing changes
Not needed: no user-visible interface changes; the fix makes existing settings (
use_statistics,use_statistics_cache,query_plan_optimize_lazy_final) behave as documented.Symptom. With
use_statistics = 1(default),estimateReadRowsCountinoptimizeJoin.cppestimated relation sizes over all active parts, ignoring partition/PK pruning. On the reproducer from #110281 (fact: 5M rows inp=1+ 1k rows inp=2, dim: 100k,WHERE p = 2): fact side estimated at 2,500,500 rows (= 5,001,000 × 1/NDV(p), a 2,500× error; NDV error 250,000×), identical underuse_statistics_cache = 0/1. With statistics disabled the index-based fallback callsselectRangesToRead()and estimates 1,000 rows exactly — i.e. enabling statistics made the plan ~100× worse by the optimizer's own cost model.Root cause. At
optimizeJointimeanalyzed_result_ptris not populated yet, soReadFromMergeTree::getParts()falls back toprepared_parts(all parts) when building theConditionSelectivityEstimator. The table-widecached_estimator(populated by the backgroundrefreshStatistics()task over all active parts) matched that wrong scope, which masked the cache/query-scope divergence.Fix.
estimateReadRowsCountobtains the partition/PK analysis result up front (getAnalyzedResult()orselectRangesToRead()— exactly what the non-statistics fallback branch already did) and passes it to a newgetConditionSelectivityEstimator(required_columns, analyzed_result)overload, so statistics are folded overparts_with_ranges.MergeTreeData::getConditionSelectivityEstimatorreturns the table-wide cached estimator only when the requested part set matches the set the cache was built over (allocation-freeisStale(RangesInDataParts)overload; the shared_ptr is copied understats_mutex, the comparison runs outside — the estimator is immutable once published). Without this, fixing (1) would make the previously-masked cache scope divergence real.optimizeLazyFinal: the "projection was applied" guard checked for a mere non-null analysis result.selectRangesToRead()memoizes its result on the reading step, so join-order estimation (the no-statistics fallback before this PR, the statistics path as well after it) made lazy FINAL silently bail for any MergeTree relation under a JOIN. The guard now checksreadFromProjection().optimizeLazyFinalalso re-ranselectRangesToRead()unconditionally after the guard, repeating the full part/PK/skip-index analysis that join-order estimation had already memoized (observed: twoSelectExecutor"Key condition" passes over the same parts in one stats-enabledReplacingMergeTree FINAL JOINquery). It now reuses the memoized result — analysis passes drop 2 → 1; PK conditions are pushed in the first optimization pass, before both consumers, so the repeated analysis was provably identical.WHERE 0:f ⋈ dbefore,f[0] ⋈ d[0]after).max_rows_to_readormax_rows_to_read_leaf, join estimation uses a non-memoized range analysis without row-limit checks. The final read repeats analysis afteroptimizeReadInOrder; it remains limited unless InOrder is selected.Scope note. Statistics are composed over surviving whole parts; mark-range granularity inside a surviving part is not used (follow-up material, see the issue). Filtering by skip indexes deferred to the scan by
use_skip_indexes_on_data_read = 1is likewise not reflected in join-order estimates: join order is fixed before those results exist. The fix relies only on partition/PK analysis remaining pre-scan.Verification (macOS arm64 debug build @
5a9528b4db5):Loading statisticsevents) — no regression from the part-set check.04516_join_order_estimation_pruned_parts(fails before the fix:f[50500]on 26.7.1.448; passes after:f[1000]), with an NDV oracle probe (f[100]= 1000 × 1/NDV(id) — derivable only from pruned column statistics, the index fallback yieldsf[1000], so a silently degraded statistics path fails the test) and a PK-only pruning case (no partitioning; a part fully excluded by the primary key).04517_lazy_final_join_with_statistics(new):InputSelectorpresent for single-table FINAL and for FINAL under a JOIN with statistics on and off, plus result correctness.04518_statistics_cache_pruned_scope(new): warms the table-wide cache via the real background refresh (deterministic retry onLoadedStatisticsMicroseconds = 0, the same oracle as03707_statistics_cache), then asserts: pruned query bypasses the cache and gets pruned-scope estimates; the unpruned cache hit is preserved afterwards.03990,03991;03988/04092/04093skipped asno-debug),03707_statistics_cache,03279_join_choose_build_table_{,auto_}statistics,03788_statistics_part_pruning*,02864_statistics_*, explain-pretty/join-order/estimate suites.Cost/risk notes.
selectRangesToRead()writesanalyzed_result_ptr), so execution reuses the analysis instead of re-running it. This matches what the no-statistics fallback already did before this PR; the new part is that the statistics path joins that behavior. Throwing read limits are the deliberate exception: estimator analysis stays local untiloptimizeReadInOrderdetermines whether the final read is exempt.Loading statistics). A part-set-keyed or per-part-decoded statistics cache is follow-up work (discussed in Join-order cardinality estimation runs before MergeTree partition/PK analysis and ignores pruned parts #110281).tests/performance/join_planning_pruned_statistics.xml(new): planning-onlyEXPLAINbenchmarks over 100- and 1000-part fact tables — per-part fold (cold cache, selective/unselective), a genuinely warm table-wide cache (refresh_statistics_interval = 1+ warm-up; verified: zero statistics loads on the unpruned hit) exercising the O(parts) part-set comparison and the pruned bypass, and a planning-only lazy FINAL join over a 200-part ReplacingMergeTree guarding the duplicate-analysis regression. An end-to-end execution query is kept as a separate benchmark. CI perf compares merge-base vs head on a Linux release build.