Skip to content

Compose join-order statistics over parts surviving partition/PK pruning - #110283

Merged
rschu1ze merged 11 commits into
masterfrom
fix-join-estimation-pruned-parts
Aug 12, 2026
Merged

rschu1ze merged 11 commits into
masterfrom
fix-join-estimation-pruned-parts

Conversation

@skuznetsov-clickhouse

@skuznetsov-clickhouse skuznetsov-clickhouse commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #110281

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):

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), estimateReadRowsCount in optimizeJoin.cpp estimated relation sizes over all active parts, ignoring partition/PK pruning. On the reproducer from #110281 (fact: 5M rows in p=1 + 1k rows in p=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 under use_statistics_cache = 0/1. With statistics disabled the index-based fallback calls selectRangesToRead() 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 optimizeJoin time analyzed_result_ptr is not populated 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() task over all active parts) matched that wrong scope, which masked the cache/query-scope divergence.

Fix.

  1. estimateReadRowsCount obtains the partition/PK analysis result up front (getAnalyzedResult() or selectRangesToRead() — exactly what the non-statistics fallback branch already did) and passes it to a new getConditionSelectivityEstimator(required_columns, analyzed_result) overload, so statistics are folded over parts_with_ranges.
  2. MergeTreeData::getConditionSelectivityEstimator returns the table-wide cached estimator only when the requested part set matches the set the cache was built over (allocation-free isStale(RangesInDataParts) overload; the shared_ptr is copied under stats_mutex, the comparison runs outside — the estimator is immutable once published). Without this, fixing (1) would make the previously-masked cache scope divergence real.
  3. 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 checks readFromProjection().
  4. optimizeLazyFinal also re-ran selectRangesToRead() unconditionally after the guard, repeating the full part/PK/skip-index analysis that join-order estimation had already memoized (observed: two SelectExecutor "Key condition" passes over the same parts in one stats-enabled ReplacingMergeTree FINAL JOIN query). 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.
  5. Early index-analysis exits that prove the read empty now preserve the exact-zero invariant; join ordering short-circuits to zero rather than degrading to unknown when no estimator exists (WHERE 0: f ⋈ d before, f[0] ⋈ d[0] after).
  6. With throwing max_rows_to_read or max_rows_to_read_leaf, join estimation uses a non-memoized range analysis without row-limit checks. The final read repeats analysis after optimizeReadInOrder; 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 = 1 is 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):

  • Reproducer from the issue: fact estimate 2,500,500 → 1,000 rows under both cache settings; the pruned query's plan cost becomes bit-identical (996.86) to the physically-pruned counterfactual table; build side flips to the small side.
  • Unpruned query with a warm cache still hits the cache (0 Loading statistics events) — 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 yields f[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): InputSelector present 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 on LoadedStatisticsMicroseconds = 0, the same oracle as 03707_statistics_cache), then asserts: pruned query bypasses the cache and gets pruned-scope estimates; the unpruned cache hit is preserved afterwards.
  • Locally green: lazy_final suite (03990, 03991; 03988/04092/04093 skipped as no-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.

  • The statistics path normally runs index analysis at planning time and memoizes it on the reading step (selectRangesToRead() writes analyzed_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 until optimizeReadInOrder determines whether the final read is exempt.
  • Pruned queries bypass the table-wide estimator cache and fold per-part statistics per query (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-only EXPLAIN benchmarks 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.
  • If the pre-analysis pass ordering was a deliberate trade-off, happy to hear maintainer context — the issue discusses this explicitly.

@skuznetsov-clickhouse skuznetsov-clickhouse self-assigned this Jul 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [336f5c1]

Summary: ✅


AI Review

Summary

This PR fixes join-order estimation for MergeTree reads by composing statistics over the part set that survives partition / PK pruning, adds a cache-scope check so the table-wide statistics cache is only reused for the exact full-part set it was built for, and preserves lazy FINAL after join-order analysis memoizes read analysis on the step. I did not find a remaining correctness or performance regression in the current head; the previously open STREAM-estimate regression is fixed in code and covered by a focused stateless test.

Final Verdict

✅ No new review findings on the current head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 126/129 (97.67%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 13, 2026
@rschu1ze

Copy link
Copy Markdown
Member

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

skuznetsov-clickhouse added a commit that referenced this pull request Jul 13, 2026
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
skuznetsov-clickhouse added a commit that referenced this pull request Jul 13, 2026
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
@fkastrati

Copy link
Copy Markdown
Contributor

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

@rschu1ze sure.

@fkastrati fkastrati left a comment •

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.

I approve this PR but some parts require more comments. See below the exact portions of code in question.

@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 82.30% 86.10% +3.80%
Functions 91.60% 92.00% +0.40%
Branches 74.40% 78.10% +3.70%

Changed lines: Changed C/C++ lines covered: 120/126 (95.24%) · Uncovered code

Full report · Diff report

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.
@skuznetsov-clickhouse
skuznetsov-clickhouse force-pushed the fix-join-estimation-pruned-parts branch from 797ef42 to 113ce6b Compare August 12, 2026 00:36
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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 336f5c17e with master 86e654b84 (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
Binary Master PR Δ
programs/clickhouse-stripped 691.19 MiB 688.19 MiB -2.99 MiB (-0.43%)

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 sizes

10 object files changed (+23.16 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeLazyFinal.cpp.o 339.00 KiB 356.13 KiB +17.13 KiB (+5.05%)

737 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

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

Job report

<!-- 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 -->

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.

@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>

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.

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.

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.

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

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.

(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))

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.

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

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.

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

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.

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

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.

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.

@rschu1ze
rschu1ze added this pull request to the merge queue Aug 12, 2026
Merged via the queue into master with commit 6a217c8 Aug 12, 2026
181 checks passed
@rschu1ze
rschu1ze deleted the fix-join-estimation-pruned-parts branch August 12, 2026 22:51
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 12, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Aug 17, 2026
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.
@PedroTadim

Copy link
Copy Markdown
Member

@rschu1ze @fkastrati are you going to do the backports?

@rschu1ze

rschu1ze commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

@PedroTadim By convention, the PR author (@skuznetsov-clickhouse ) backports.

image

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.

@PedroTadim

Copy link
Copy Markdown
Member

The release board was suggesting, can close the backports.

@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 18, 2026
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 8, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Join-order cardinality estimation runs before MergeTree partition/PK analysis and ignores pruned parts

7 participants