Repository navigation
Conversation
|
Workflow [PR], commit [4e7ac9c] Summary: ❌
AI ReviewSummaryThis PR restores join-step row estimates and re-integrates the trust boundary across Missing context / blind spots
Findings
Final VerdictStatus:
|
…e_join_step_estimation
|
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). |
There was a problem hiding this comment.
Just out of curious in which case the NDV is unknown when we have statistics.
There was a problem hiding this comment.
@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.
|
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 |
|
Looks like the failure of 04040_tpc_h_q08 is related |
…e_join_step_estimation
…e_join_step_estimation
…e_join_step_estimation
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]>
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]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This comment was marked as low quality.
This comment was marked as low quality.
| if (!all_ndvs_known) | ||
| info.trusted = false; | ||
|
|
||
| if (max_ndv > 0) |
There was a problem hiding this comment.
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}; |
There was a problem hiding this comment.
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.
|
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. |
`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]>
`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]>
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
`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]>
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
|
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. |
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
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/RelationStatscarry arows_estimate_trustedflag. It istrueonly when every NDV along the DP path came from real column statistics.computeSelectivity(1 / max(rows)for both direct and transitive predicates) still gives the DP a usable estimate, but marks the entry untrusted.JoinStepLogicalexposes two accessors:getResultRowsEstimation— raw DP estimate; used byEXPLAINfor visibility.getTrustedResultRowsEstimation— returnsnulloptwhen untrusted, so outer-scopeestimateReadRowsCountdoes not feed a fabricated number upstream (equivalent to master's behavior for join steps).Guards against fabricated estimates
swap_on_sizes) is gated bysides_trustworthyso a fabricated smaller side cannot flipHashJoinonto a huge relation.HashTablesStatisticsreturns asource_rowsbelow the current estimate, trust is demoted (used in the swap gate) butestimated_rowsis 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, outerResultRows: unknown.04104_join_trust_boundary_propagation— nestedJoinStepLogicalexposes 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 withSETTINGS use_statistics = 0and= 1; contrasts the left-deep fallback plan against the right-deep pre-joined-dimensions plan.Changelog category (leave one):
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
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.