Skip to content

Fix cardinality underestimation when join column NDVs are unknown - #101398

Open
davenger wants to merge 42 commits into
masterfrom
restore_join_step_estimation
Open

davenger wants to merge 42 commits into
masterfrom
restore_join_step_estimation

Conversation

@davenger

@davenger davenger commented Mar 31, 2026 •

Copy link
Copy Markdown
Member

Restore the join-step row count estimation (originally #97114, reverted in #99957 because of regressions reported) and add a trust-propagation mechanism that prevents fabricated estimates from leaking into decisions where they cause regressions.

Trust-propagated cardinality

  • DPJoinEntry / RelationStats carry a rows_estimate_trusted flag. It is true only when every NDV along the DP path came from real column statistics.
  • The NDV-unknown fallback in computeSelectivity (1 / max(rows) for both direct and transitive predicates) still gives the DP a usable estimate, but marks the entry untrusted.
  • JoinStepLogical exposes two accessors:
    • getResultRowsEstimation — raw DP estimate; used by EXPLAIN for visibility.
    • getTrustedResultRowsEstimation — returns nullopt when untrusted, so outer-scope estimateReadRowsCount does not feed a fabricated number upstream (equivalent to master's behavior for join steps).

Guards against fabricated estimates

  • Build-side swap (swap_on_sizes) is gated by sides_trustworthy so a fabricated smaller side cannot flip HashJoin onto a huge relation.
  • When HashTablesStatistics returns a source_rows below the current estimate, trust is demoted (used in the swap gate) but estimated_rows is not clamped. Clamping made the DP read different leaf sizes on cold vs warm runs, which flipped greedy ordering and caused degradation in some cases; keeping source upper bounds keeps the plan shape stable across runs.

Regression tests

  • 04103_join_build_side_no_stats — without stats the 100-row dim still builds, fact probes, outer ResultRows: unknown.
  • 04104_join_trust_boundary_propagation — nested JoinStepLogical exposes its result estimate only when trusted.
  • 04105_plan_stability_hash_table_stats_cache — cold and warm EXPLAINs of the same query are identical both with and without stats.
  • 04106_join_plan_stats_toggle — same 3-table star-join run twice with SETTINGS use_statistics = 0 and = 1; contrasts the left-deep fallback plan against the right-deep pre-joined-dimensions plan.

Changelog category (leave one):

  • Improvement

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

Restore join-step row count estimation with trust propagation: when column NDVs are available, join cardinality and column stats flow through the DP and to the outer optimizer, enabling better build-side and multi-join ordering decisions; when NDVs are unavailable, an untrusted fallback keeps the DP working but does not drive structural decisions or propagate to upstream joins.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

High Risk
Changes core join-order optimization cardinality/selectivity estimation and build-side swapping logic, which can alter query plans and performance across many workloads despite added safeguards and tests.

Overview
Restores and extends join cardinality estimation in the join-order optimizer, adding end-to-end trust propagation so only estimates derived from real table/column statistics influence upstream optimizers and structural decisions.

When join key NDVs are missing, selectivity now falls back to a row-count-based heuristic but marks the result untrusted; untrusted estimates are hidden via JoinStepLogical::getTrustedResultRowsEstimation() and are prevented from driving hash-join build-side swapping, while still being usable internally for DP cost comparisons.

Also adjusts handling of hash-table statistics cache hints to demote trust (instead of clamping row counts) to keep join plans stable between cold and warm runs, and adds several stateless tests covering trust boundaries, build-side choice without stats, and plan stability/statistics toggling.

Reviewed by Cursor Bugbot for commit 255b598. Bugbot is set up for automated code reviews on this repo. Configure here.

@clickhouse-gh

clickhouse-gh Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4e7ac9c]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
04277_parallel_replicas_join_dp_reorder FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
04277_parallel_replicas_join_dp_reorder FAIL cidb
04277_parallel_replicas_join_dp_reorder FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_tsan, flaky check) FAIL
04277_parallel_replicas_join_dp_reorder FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
04277_parallel_replicas_join_dp_reorder FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_msan, flaky check) FAIL
04277_parallel_replicas_join_dp_reorder FAIL cidb
04277_parallel_replicas_join_dp_reorder FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
04277_parallel_replicas_join_dp_reorder FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
04277_parallel_replicas_join_dp_reorder FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
04277_parallel_replicas_join_dp_reorder FAIL cidb
04277_parallel_replicas_join_dp_reorder FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
03960_join_order_dphyp_hyperedge FAIL cidb
04277_parallel_replicas_join_dp_reorder FAIL cidb
03545_analyzer_correlated_subquery_exists_asterisk FAIL cidb
00184_parallel_hash_returns_same_res_as_hash FAIL cidb
01391_limit_overflow FAIL cidb
04033_tpc_ds_q78 FAIL cidb
04060_coalescing_merge_tree_array_tuple_with_column_param FAIL cidb
00377_shard_group_uniq_array_of_string_array FAIL cidb
04033_tpc_ds_q74 FAIL cidb
01626_cnf_fuzz_long FAIL cidb
133 more test cases not shown
Stateless tests (amd_debug, parallel) FAIL
04277_parallel_replicas_join_dp_reorder FAIL cidb
03545_analyzer_correlated_subquery_exists_asterisk FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
Stateless tests (amd_tsan, parallel) FAIL
04277_parallel_replicas_join_dp_reorder FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
04277_parallel_replicas_join_dp_reorder FAIL cidb
03545_analyzer_correlated_subquery_exists_asterisk FAIL cidb
03960_join_order_dphyp_hyperedge FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED

AI Review

Summary

This PR restores join-step row estimates and re-integrates the trust boundary across greedy, dpsize, dphyp, and the newer dpsub path. The main remaining problems are both in the new dpsub integration: its native-mask transitive-selectivity path does not apply the no-stats row fallback used by the other solvers, and solveDPsub still shares stale selectivity / DP caches with earlier failed solvers in a fallback chain. I would not merge it yet.

Missing context / blind spots
  • ⚠️ The current head has no fresh performance-comparison evidence: the available PR report skipped all Performance Comparison shards, so the earlier Q7 / Q8 / Q20 swap-gate regression discussion is still unclosed. A current pr-performance / TPC-H run on 4e7ac9c6 would close this gap.
Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/joinOrder.cpp:1092] computeSelectivityMask demotes trust for transitive equivalence classes with unknown NDVs, but unlike computeSelectivity(edges, left, right) it never applies the 1 / max(lhs_rows, rhs_rows) fallback when all NDVs in the class are unknown. In dpsub, a transitive-only candidate such as A.k = B.k AND B.k = C.k can therefore keep selectivity = 1.0 and be costed near lhs_rows * rhs_rows, diverging from the other solvers and skewing join-order selection.
    Suggested fix: mirror the max_rows fallback branch from the BitSet overload and add a focused dpsub regression for a no-stats transitive chain.
  • [src/Processors/QueryPlan/Optimizations/joinOrder.cpp:1276] solveDPsub does not clear the shared dp_table / expression_selectivity state before starting, even though computeSelectivityMask still routes through the shared per-edge cache. In a fallback chain like dphyp,dpsub or dpsize,dpsub, a failed earlier solver can leave cached selectivity or intermediate-subset state behind, making the dpsub fallback order-dependent.
    Suggested fix: reset the shared caches at the top of solveDPsub (same pattern as solveGreedy, solveDPsize, and solveDPhyp) and add a regression that forces an earlier algorithm to bail out before dpsub runs.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Fix the missing transitive no-stats fallback in computeSelectivityMask and add dpsub coverage.
  2. Reset the shared optimizer caches before solveDPsub runs and add a fallback-chain regression.
  3. Re-run current performance validation on the mergeable head, because the available PR report skipped the performance jobs.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Mar 31, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

}
else
{
/// Both NDVs unknown — use containment assumption: 1 / min(left_rows, right_rows).

@hanfei1991 hanfei1991 Apr 8, 2026 •

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.

Just out of curious in which case the NDV is unknown when we have statistics.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@hanfei1991 it's for the case when column statistics are not enabled. Also currently we might not have NDV-s of columns that were computed by a subquery with joins and aggregations.

@alexey-milovidov

Copy link
Copy Markdown
Member

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

@hanfei1991

Copy link
Copy Markdown
Member

Looks like the failure of 04040_tpc_h_q08 is related

davenger and others added 3 commits April 18, 2026 12:02
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
davenger and others added 7 commits April 18, 2026 14:41
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

This comment was marked as low quality.

if (!all_ndvs_known)
info.trusted = false;

if (max_ndv > 0)

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.

computeSelectivityMask demotes trust here, but it never applies the same 1 / max(lhs_rows, rhs_rows) fallback that computeSelectivity(edges, left, right) uses when the whole transitive equivalence class has unknown NDVs.

That reintroduces the transitive-only overestimation bug in the new dpsub path: for a chain like A.k = B.k AND B.k = C.k with query_plan_optimize_join_order_algorithm = 'dpsub' and no stats, the A ⋈ C candidate keeps selectivity = 1.0, so the compact DP costs it near lhs_rows * rhs_rows instead of using the same conservative fallback as greedy / dpsize / dphyp.

Can we mirror the max_rows branch from computeSelectivity(edges, left, right) here and add a focused dpsub regression for a transitive-only / no-stats chain?

double sel{.0};
/// See DPJoinEntry::rows_estimate_trusted; false by default so an entry that
/// never went through the acceptor cannot leak a trusted estimate.
bool rows_estimate_trusted{false};

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.

solveDPsub is now the only solver that does not reset dp_table and expression_selectivity before it starts. The other three do this because computeSelectivity* memoizes per-edge results and consults the shared dp_table for multi-relation sources / NDV fallbacks.

In a fallback chain like dphyp,dpsub or dpsize,dpsub, a failed earlier solver can therefore leave cached SelectivityInfo or intermediate stats behind, and dpsub will reuse them instead of recomputing against its own run. That makes the fallback order-dependent.

Please clear the shared caches at the top of solveDPsub as well (same pattern as solveGreedy, solveDPsize, and solveDPhyp) and add a chain test where an earlier algorithm bails out before dpsub runs.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Dear @fkastrati, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@abashkeev abashkeev added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`computeSelectivity` previously kept `info.trusted = true` whenever
`max(lhs_ndv, rhs_ndv) > 0`, so the mixed case (one NDV known, the
other unknown) still produced a usable denominator from the known
side while crossing the trust boundary as if fully stats-backed.
Per the design contract - `rows_estimate_trusted` is true only when
every NDV along the DP path came from real column statistics - the
flag must be demoted whenever any participating NDV is missing.

The same rule now applies to the transitive-equivalence branch:
track `all_ndvs_known` across the class and demote trust if any
participating column lacks NDV stats.

Adds `04266_04107_join_mixed_ndv_trust` covering a nested join where
one key has `uniq` stats and the other does not - the partially-
fabricated cardinality must stay inside the DP and the outer
optimizer must read `ResultRows: unknown` for the inner join.

Addresses AI Review on commit `255b598d`:
ClickHouse#101398 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`estimateAggregatingStepStats` previously copied
`rows_estimate_trusted` from the input even when one or more grouping-
key NDVs were missing. In that case `total_number_of_distinct_values`
gets reset and the function falls back to `input_stats.estimated_rows`
instead of a product of NDVs, so the aggregate cardinality is
partially fabricated. Per the design contract -
`rows_estimate_trusted` is true only when every NDV along the DP path
came from real column statistics - the flag must be demoted when any
grouping-key NDV is absent, otherwise the fabricated estimate can
cross the trust boundary via `getTrustedResultRowsEstimation` and
influence upstream `swap_on_sizes` and join ordering as if it were
fully stats-backed.

Track `all_group_key_ndvs_known` across the keys (treating
`num_distinct_values == 0` as "unknown" for symmetry with the
direct-edge path in `computeSelectivity`) and require it together
with `input_stats.rows_estimate_trusted` before marking the aggregate
trusted.

Adds `04267_aggregate_mixed_ndv_trust` covering an aggregation whose
result feeds an inner join: one grouping key has `uniq` stats and the
other does not, so the inner join is untrusted and the outer
optimizer reads `ResultRows: unknown` for the wrapping join.

Addresses AI Review on commit `ba14c5ec`:
ClickHouse#101398 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test exercises `dpsize` join ordering with statistics across a
correlated-subquery rewrite, plus four invocations of two views with
and without join-order optimization. Peak duration in this PR's
flaky check is 239s and several runs of `Stateless tests (amd_debug,
flaky check)` hit the 180s ceiling under randomized debug settings,
producing 6 "Test runs too long" failures over 30 days, all on
PR ClickHouse#101398. The cardinality work in this PR exercises additional
NDV-trust paths and the test was already in the borderline range, so
the 180s cap is no longer realistic. `-- Tags: long` lifts the cap
without changing semantics.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101398&sha=f8ee1d4049f0599bdad1591de9aecb089852dda4&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`computeSelectivity(const JoinActionRef &)` returned a default-constructed
`SelectivityInfo{}` for non-equality predicates, i.e. `{value = 1.0, trusted
= true}`. Such predicates (e.g. `a.v < b.v`) are handled as residual/post-join
filters, so the DP never estimates their selectivity, yet the equi-join
cardinality stayed trusted and could cross the trust boundary via
`getTrustedResultRowsEstimation` - influencing upstream join ordering and
build-side decisions as if the join were fully stats-backed even though a
semantics-affecting predicate was silently ignored.

Per the design contract - `rows_estimate_trusted` is true only when the DP
estimate accounts for every selectivity factor from real statistics - the
flag must be demoted whenever a non-equality predicate participates. The
combined trust in `computeSelectivity(edges)` already ANDs per-edge trust, so
demoting the single non-equality edge propagates correctly.

Adds `04268_join_residual_inequality_trust` covering a nested join where the
inner `ON a.k = b.k AND a.v < b.v` has fully-stats-backed keys but an
unestimated inequality: the inner estimate must stay inside the DP and the
outer optimizer must read `ResultRows: unknown`. Verified the test fails
without the fix (the inner join leaks `1000` upstream and the outer join is
estimated and reordered).

Addresses AI Review on commit `6599701b`:
ClickHouse#101398

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
fkastrati added a commit that referenced this pull request Sep 22, 2026
A join the optimizer has already settled enters its parent's graph as a single
relation, and the row count it arrived at is the only estimate that relation
has. `estimateReadRowsCount` returned early for any node with two children, so
the parent saw nothing and `computeJoinCost` read the missing count as one row
through `value_or(1)` - the largest input in the query looked like the cheapest
thing to join. Read the estimate before that check.

On TPC-DS q72 the boundary is real: the non-equi predicate
`inv_quantity_on_hand < cs_quantity` splits `inventory` and `catalog_sales` into
their own graph, which estimates itself at 945,072,914 rows against a true
944,916,882 - 0.02% off - and the parent then planned eight relations around it
as if it returned one row. With column statistics the query goes from 11.6s to
0.8s, and under `dpsub` with the CD-C conflict detector from 72.7s to 1.0s: the
detector widens the search space, so a wrong estimate buys more wrong plans.

Measured over the full 99-query TPC-DS suite at scale factor 1 with column
statistics, no other query changes.

The relation name of such a sub-join is a chain that already carries its own
inputs' estimates, so it is marked composite and `EXPLAIN` no longer appends a
second estimate to it.

This restores #97114, reverted in #99957 for a suspected performance
regression. On tables without column statistics the estimate it propagates is
itself unreliable, and there the change is a wash across TPC-DS - 18 queries
faster, 11 slower. #101398 proposes gating propagation on a trust flag.

Related: #97114
Related: #99957
Related: #101398
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Dear @fkastrati, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Nov 5, 2026
Base-table NDV can exceed the row count of a multi-relation join input, so `1 / max(NDV)` underestimates the output of the join above it and the optimizer picks a worse order. Cap each join key NDV and NDV upper bound by the estimated rows of its input subtree when that side contains more than one relation.

`SelectivityCache` stores context-independent `JoinKeyStats` instead of a finished `SelectivityEstimate`: the same edge can join different subtrees in another candidate plan, so the row cap is applied after the cache lookup. Both direct predicates and transitive equivalence classes are covered in `dpsub`, `dphyp`, `dpsize`, and `greedy`.

Tests: `05493_join_order_subtree_ndv` checks corrected estimates, cache contexts, and bushy plans. `05494_join_order_subtree_ndv_stable` uses independent tables per algorithm to verify cold and warm `EXPLAIN` plans are identical with hash table statistics enabled.

Historical benchmark (7 runs, discard the first, median of the remaining 6; result hashes identical): TPC-DS Q72 0.1725s -> 0.0835s. TPC-H Q02 unchanged at 0.034s. These figures come from the original benchmark logs and were not rerun for this commit.

Related: ClickHouse#128102

Related: ClickHouse#114614

Related: ClickHouse#101398
@cv4g cv4g self-assigned this Nov 18, 2026
@clickhouse-gh clickhouse-gh Bot added comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... hold Skip for auto-updating. pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants