Repository navigation
Estimate an always-true x = x condition as passing every row - #126131
alexey-milovidov merged 3 commits into
Conversation
…ted subquery With `correlated_subqueries_substitute_equivalent_expressions`, the decorrelation of a correlated subquery that correlates by equality rebuilds the correlated column from the inner column it is compared with, and the outer join enforces the correlation. The recorded conjunct `b.k = a.k` was kept and became `b.k = b.k`. For a non-Nullable key it is always 1, but the selectivity estimator prices each one as an unknown condition (0.33), so a 5-key EXISTS over 10M rows estimated the inner table at 39135 rows and picked a single-threaded HashJoin (2.80 s vs 0.65 s, debug build). The FilterStep branch of decorrelateQueryPlan now removes such a conjunct when the correlated identifier was rebuilt at this scope's boundary from exactly that INPUT column without the null pre-filter (no accurate cast, no assumeNotNull), the column is neither Nullable nor LowCardinality(Nullable), and `=` on both types is reflexive (integers, Decimal, Enum, date and time types, String, FixedString, UUID, IPv4, IPv6). Such a conjunct is 1 on every row, so neither the rows the filter keeps nor the rows any other conjunct sees change. The predicate is rebuilt along the original `and` tree, keeping the order of the other arguments (short-circuit `and` evaluates them in order); an empty predicate turns the step into an ExpressionStep, as filter push-down does for a fully absorbed filter. Kept as before: Nullable keys (`x = x` rejects NULL), pre-filtered cross-type keys, floats (NaN) and Tuple or other composite keys (`=` is not reflexive there: dropping it would change EXISTS results), the CROSS JOIN fallback, UNION arms and filters whose column is read by the next step. The plan-reference changes are the removed filters and the resulting step merges. Closes ClickHouse#122677 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Superseded: this covers the first version ( Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (3 nits).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-11:20261015-205200 |
|
Superseded: this covers the first version ( Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261015-192700 |
|
Workflow [PR], commit [b94d954] Summary: ✅
AI ReviewSummaryThe PR stops treating always-true Final VerdictStatus: ✅ Approve |
|
Superseded: this covers the first version ( cc @novikd @davenger, could you review this? With |
A correlated subquery that correlates by equality is decorrelated with the correlated column rebuilt from the inner column, so its WHERE keeps one `b.k = b.k` per key. The selectivity estimator priced each one as an unknown condition (0.33), so a 5-key EXISTS over 10M rows estimated the inner table at 39135 rows and chose a single-threaded HashJoin. `equals(x, x)` of one DAG node whose type makes `=` reflexive and never NULL (integers, Decimal, Enum, date and time types, String, FixedString, UUID, IPv4, IPv6, also under LowCardinality) is now ALWAYS_TRUE in ConditionSelectivityEstimator, and prunesNothingAtPlanTime treats it like a runtime filter, so a filter made only of such conditions does not count for the row estimate. Floats (NaN), Nullable and Tuple keep the default estimate. This replaces the previous commit, which removed the conjunct from the plan. Without it, the join runtime filter on the correlated key was no longer grouped with a query condition on the same column, so on a table without statistics MergeTreeWhereOptimizer ordered it after the other PREWHERE conditions (ClickHouse#122452): TPC-H Q4 over Iceberg evaluated 24% more rows in PREWHERE and was 16-20% slower in the performance comparison. Keeping the conjunct leaves every plan as on master; only row estimates change. Closes ClickHouse#122677 Co-Authored-By: Claude Opus 5.5 <[email protected]>
x = x filters after decorrelating a correlated subqueryx = x condition as passing every row
…ion-drop-always-true-equalities Co-Authored-By: Claude Opus 5.5 <[email protected]>
Backport #126131 to 26.10: Estimate an always-true `x = x` condition as passing every row
A filter on a constant column of UNION ALL branches (`'s' AS sale_type` in
TPC-DS q4, q11, q74) reaches each branch as `materialize('s') = 's'`, next to
the branch's own conditions. `materialize` stops constant folding, and
`foldFilterPredicateThroughMaterialize` (ClickHouse#105987) folds only a filter that is
constant as a whole, so the conjunct stays. `ConditionSelectivityEstimator`
then priced it as a condition on an expression that is not a table column:
1% for `=` and 33% for `<`/`>`. In q74 `date_dim` was estimated at 3 rows
instead of 358, and join reordering built the hash table on the
`store_sales JOIN date_dim` side (14M rows at SF10) instead of `customer`.
`extractAtomFromTree` now decides `equals`, `notEquals`, `less`, `greater`,
`lessOrEquals`, `greaterOrEquals` of two constants with at least one behind
`materialize`, and `isNull`/`isNotNull` of such a constant, as ALWAYS_TRUE or
ALWAYS_FALSE. A constant-folded node under `materialize` counts too, since
`makeConvertingActions` puts the `_CAST` of a branch constant before
`materialize`.
Comparisons are decided with `accurateEquals`/`accurateLess`/
`accurateLessOrEqual`, only when both values have one totally ordered scalar
type after removing `LowCardinality`/`Nullable` (the type list of
`isAlwaysTrueEquality`, now shared) or are both integers. For these pairs the
`Field` comparison agrees with the comparison functions (Enum by value,
Decimal at the same scale, signed against unsigned through `accurate::lessOp`)
and cannot throw, so no try/catch is needed. Float, cross-type pairs (String
against Enum, see ClickHouse#121723), composite types and `IN` keep their default
estimate. A comparison with a NULL constant is not decided: it is NULL, not
FALSE, and ALWAYS_FALSE would turn into ALWAYS_TRUE under `NOT`.
As in ClickHouse#126131, only the estimate changes: the executed filter, results and
exceptions are the same. Removing the conjunct from the plan instead would
also move runtime filters and PREWHERE grouping (the first version of
ClickHouse#126131 slowed TPC-H Q4 over Iceberg that way, ClickHouse#122452), and would widen the
reach of ClickHouse#121723.
Analysis and original patch by snelheidai in ClickHouse#128482.
Closes ClickHouse#128482
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #122677
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The row estimate no longer treats an always-true
x = xcondition (one non-Nullablecolumn of an integer,Decimal,Enum, date or time, string,UUIDor IP type) as selective. A correlated subquery that correlates by equality keeps such a condition for each correlation key, so a multi-keyEXISTSestimated its inner table several times too small and could get a single-threaded hash join. Closes #122677.Description
A correlated
EXISTS (SELECT 1 FROM t2 AS b WHERE a.k = b.k AND a.c1 = b.c1 ...)is decorrelated into a join. Withcorrelated_subqueries_substitute_equivalent_expressionsthe outer column inside the subquery is rebuilt from the inner one, so each correlated equality stays on the inner table asb.k = b.k. The selectivity estimator priced each one as an unknown condition (0.33): with 5 keys the inner table was estimated at 0.4% of its size andHashJoinwas chosen instead ofConcurrentHashJoin.ConditionSelectivityEstimatornow treatsequals(x, x)of one DAG node as always true when=on its type is reflexive and never NULL, andprunesNothingAtPlanTimeignores it like a runtime filter (the estimate without statistics).Float*(NaN),NullableandTuplekeep the default estimate. Plans do not change, only row estimates.The first version of this PR removed the conjunct from the plan instead. That moved the join runtime filter after the other PREWHERE conditions on tables without statistics, because it was no longer grouped with a condition on the same column (#122452), and TPC-H Q4 over Iceberg became 16-20% slower in the performance comparison. With this version the Q4 plan over the CI Iceberg dataset is identical to master.
Validation (debug build): the 5-key query from the issue on two 10M-row tables,
collect_hash_table_stats_during_joins = 0,max_threads = 16, takes 0.9 s instead of 4.2 s (ConcurrentHashJoin, inner table estimated at full size). The new test covers both estimator paths (with and without statistics), a mixed condition and the excluded types; it fails on master. A performance test is added.Workflow [PR]
Sync PR [sync-upstream/pr/126131]
Version info
26.11.1.179-master(included in26.11and later)