Skip to content

Estimate an always-true x = x condition as passing every row - #126131

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/decorrelation-drop-always-true-equalities
Oct 19, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/decorrelation-drop-always-true-equalities

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122677

Changelog category (leave one):

  • Performance Improvement

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 = x condition (one non-Nullable column of an integer, Decimal, Enum, date or time, string, UUID or IP type) as selective. A correlated subquery that correlates by equality keeps such a condition for each correlation key, so a multi-key EXISTS estimated 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. With correlated_subqueries_substitute_equivalent_expressions the outer column inside the subquery is rebuilt from the inner one, so each correlated equality stays on the inner table as b.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 and HashJoin was chosen instead of ConcurrentHashJoin.

ConditionSelectivityEstimator now treats equals(x, x) of one DAG node as always true when = on its type is reflexive and never NULL, and prunesNothingAtPlanTime ignores it like a runtime filter (the estimate without statistics). Float* (NaN), Nullable and Tuple keep 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

  • Merged into: 26.11.1.179-master (included in 26.11 and later)

…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]>
@groeneai

groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Superseded: this covers the first version (07b59c26). Since 4b92a81b the PR changes the selectivity estimator instead of the decorrelation; see the description.

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

# Sev Finding Verdict Evidence / action
1 ⚠️ An always-true equality stays when a later step reads the filter column itself (PlannerCorrelatedSubqueries.cpp:1029) DISAGREE The column is kept only when a later step reads the whole WHERE expression (PlannerExpressionAnalysis.cpp:965), i.e. the subquery selects its own correlation predicate, which is 1 on every row it keeps. That plan is unchanged from master; noted, not handled.
2 💡 The test sets enable_analyzer = 1, a no-op on master AGREE Noted, not blocking.
3 💡 An equality above a UNION whose branches are correlated keeps its x = x (each branch has its own scope) AGREE Conservative, no result change; stated in the PR description.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-11:20261015-205200

@groeneai

groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Superseded: this covers the first version (07b59c26). Since 4b92a81b the PR changes the selectivity estimator instead of the decorrelation; see the description.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 5-key EXISTS over two 1M-row Int64 tables with collect_hash_table_stats_during_joins = 0: master prints t2[3913], HashJoin and Prewhere filter column: k = k AND c1 = c1 ... on every run.
b Root cause explained? The equality substitution rebuilds the correlated column from the inner column it is compared with, and the outer join enforces the correlation, but the recorded conjunct is kept and becomes x = x. It is always 1 for a non-Nullable key, yet each one is estimated at 0.33.
c Fix matches root cause? Yes. The decorrelation removes the conjunct it made redundant, where the substitution happens; the estimator is unchanged.
d Test intent preserved / new tests added? New stateless test (plan shape, results, estimate) and a performance test. Updated references change plan shape only.
e Both directions demonstrated? Yes. The new test fails on master on the removal cases and passes with the fix (50/50 with randomized settings); five mutations of the guards (Nullable, pre-filter, type allow-list, class member, and order) each make it fail.
f Fix is general across code paths? One site serves EXISTS, NOT EXISTS, scalar subqueries, LATERAL and the IN to JOIN rewrite. The CROSS JOIN fallback, UNION arms and kept filter columns are left as they are.
g Fix generalizes across inputs (params/datatypes/wrappers)? Tested: Int64, Int32 to Int64, LowCardinality(String) to String, Nullable outer (removed); Nullable inner, LowCardinality(Nullable(String)), a cast that can fail, Tuple(Float64) with NaN, Tuple(Nullable(Int64)) with NULL (kept); 1 and 5 keys; empty and partial filters.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; query results are unchanged.
i Invariants and contracts preserved? A removed conjunct is 1 on every row, so the filter keeps the same rows and the other conjuncts see the same rows in the same order. Existing DAG nodes are not modified, and the output header is unchanged.

Session id: cron:clickhouse-impl-slot-6:20261015-192700

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b94d954]

Summary: ✅


AI Review

Summary

The PR stops treating always-true x = x predicates as selective when estimating join inputs, with and without column statistics. The current diff has no actionable findings. Focused regression coverage passes in the PR's Fast test report, and the description provides before/after performance measurements.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 15, 2026
@groeneai

groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Superseded: this covers the first version (07b59c26). Since 4b92a81b the PR changes the selectivity estimator instead of the decorrelation; see the description.

cc @novikd @davenger, could you review this? With correlated_subqueries_substitute_equivalent_expressions, decorrelation rebuilt the outer key from the inner column but kept the original conjunct as b.k = b.k; each one cut the right side estimate about 3x, so 5 keys turned ConcurrentHashJoin into HashJoin (2.80 s to 0.65 s with the fix on the 10M-row query from #122677). Only non-Nullable keys with a reflexive = and no row-rejecting conversion are dropped.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 15, 2026
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]>
@groeneai groeneai changed the title Do not keep always-true x = x filters after decorrelating a correlated subquery Estimate an always-true x = x condition as passing every row Oct 16, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 16, 2026
…ion-drop-always-true-equalities

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Oct 18, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 18, 2026
Merged via the queue into ClickHouse:master with commit fbbd160 Oct 19, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #126131 to 26.10: Estimate an always-true `x = x` condition as passing every row
AdeilH pushed a commit to AdeilH/ClickHouse that referenced this pull request Nov 6, 2026
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]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... label Nov 22, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Correlated EXISTS: tautological x = x filters left by decorrelation shrink the RHS estimate 3x per key, disabling parallel hash join

5 participants