Skip to content

Join on the implied equalities also at join steps that already have a condition - #122445

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/join-transitive-equality-with-direct-predicate
Sep 27, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/join-transitive-equality-with-direct-predicate

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122396
Related: #112630
Related: #120110
Related: #120784

Changelog category (leave one):

  • Performance Improvement

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

A join step that has a condition of its own now also joins on the equalities implied through other tables (for a.x = b.x AND b.x = c.x, joining a with c also uses a.x = c.x), as the join order was costed with them. With query_plan_optimize_join_order_algorithm = 'dpsize' this makes TPC-H Q02 join its correlated subquery to partsupp on the part key instead of on the supply cost alone. Closes #122396.

Description

With dpsize (also dphyp,greedy, dpsub,greedy), TPC-H Q02 joins the decorrelated subquery R0 (min(ps_supplycost) per part) to partsupp on min(ps_supplycost) = ps_supplycost only. Each R0 row then matches about |partsupp| / NDV(ps_supplycost) rows; the part key is applied three joins later.

The cost model already counts every equivalence class that spans a join step, so that step is costed with the part key. But the transitive equalities were only added to a step without a condition of its own. Since #112630 (26.9) the supply cost equality from WHERE is a join condition, so the part key was never added. 26.8 joins this step on the part key.

Now every inner step gets one equality per class spanning its two sides that its conditions do not connect yet. A step with conditions skips classes whose members differ in type beyond Nullable/LowCardinality (String = FixedString is not transitive) and a prepared storage side (Join engine, key-value), which is looked up by its own key. A step without conditions behaves as before. The join order does not change.

R0 has no row estimate, which is why dpsize puts it first. #120110 (open) passes that estimate on; this PR does not change it.

Validation: new test for all five algorithm settings (red on master). Of 1357 join and plan tests only 03836_tpch_join_order_plans Q02 changes: same join order, and partsupp and R0 are shuffled by ps_partkey instead of broadcasting R0. On a synthetic SF10 subset with runtime filters off, dpsize produces 5.1M join rows instead of 309M (greedy: 1.6M), with identical results. TPC-H and TPC-DS SF1 results are unchanged.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/122445]

Version info

  • Merged into: 26.10.1.796-master (included in 26.10 and later)

… condition

The join cost model counts every column equivalence class that spans a join
step (`computeSelectivity`), but `cleanupJoinPredicates` added the transitive
equality only to a step without a condition of its own. A step with an
unrelated condition was costed with the class and executed without it.

TPC-H Q02 hits this since ClickHouse#112630: the `WHERE` equality on the minimal supply
cost is merged into the join, so with `dpsize` (and `dphyp,greedy`,
`dpsub,greedy`) the decorrelated subquery is joined to `partsupp` on the
supply cost alone, and every subquery row matches about
|partsupp| / NDV(ps_supplycost) rows until the part key is applied three
joins later. 26.8 joined this step on the part key.

Phase 2 now runs at every inner step and adds one equality per class that
spans both sides and is not connected by the step's own conditions yet. With
conditions present it skips classes whose members differ in type beyond
Nullable/LowCardinality (`String = FixedString` is not transitive) and steps
with a prepared-storage side (`Join` engine, key-value storage), which is
looked up by its declared key only (an extra key fails with `Code: 264`).
The join order is unchanged, and Phase 1 still removes the later duplicate.

In 03836 only Q02 changes: `partsupp` and the subquery are now shuffled by
`ps_partkey` instead of broadcasting the subquery.

Closes ClickHouse#122396

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Before publication, an independent model reviewed this PR (engine: codex; 2 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck). My own review found 1 more item worth showing.

# Sev Finding Verdict Evidence / action
1 ❌ A step without a condition still gets a String equality derived through a FixedString member, because the type check applies only to steps with a condition (joinOrder.cpp, cleanupJoinPredicates) DISAGREE That path is unchanged: without a condition both new checks are skipped, so the loop is the same as on master. Today the added equality is implied by the keys the join executes. Both String sides are compared with the same cast value (r_key = CAST(p_key AS String) in EXPLAIN). The check keeps the new case out of #118561, which trims the String side of that comparison. Once #118561 lands, the unchanged path would need the same check.
2 ❌ A Join engine table joined without a direct condition can get a non-key equality and fail with Code: 264 under dpsize DISAGREE This already happens on master: that step has no condition, so its path is unchanged, and the join order is chosen before this cleanup runs. A 3-table variant already fails on master with dpsize (Key 'k' not found in JOIN ON section). The check added here keeps the new equalities off a Join engine step. Without it, the default greedy plan of that query fails with Code: 264. A fix for the dpsize case belongs in join order selection.
3 💡 When one side holds two members of a class, which of them the added equality uses follows hash map order over plan nodes, so EXPLAIN text can differ between runs noted, not blocking The no-condition path already works this way, and the result is not affected. The new test and 03836 do not depend on which member is used.

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

Session id: cron:clickhouse-review-slot-11:20260926-150300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: EXPLAIN actions = 1 of a 3-table query with row count hints and one unestimated table; dpsize, dphyp,greedy, dpsub,greedy join it on r_min = s_cost alone on master, every time.
b Root cause explained? The cost model counts every equivalence class spanning a step, but the transitive equality was only added to a step without its own condition. Since #112630 the Q02 supply cost equality is a join condition, so the part key was never added.
c Fix matches root cause? Yes: the executed step now carries the equality it was costed with. No order, bound or setting change.
d Test intent preserved / new tests added? New 05258_join_transitive_equality_with_direct_predicate (plan and result arms); 03836 Q02 reference updated, only that section changes.
e Both directions demonstrated? New test: master 20/20 FAIL, fix 300/300 OK with randomized settings. Removing either guard reds its arm.
f Fix is general across code paths? One synthesis site, used by greedy, dpsize, dphyp and dpsub; the cost side already assumes the invariant.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable and LowCardinality classes get the equality, String/FixedString does not, Join engine sides are excluded; checked over 20 randomized join orders.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change; results identical (TPC-H/TPC-DS SF1, SF10 Q02, 1357 join tests).
i Invariants and contracts preserved? An inner join can only shrink by an implied conjunct; redundant duplicates are still removed; outer joins untouched.

Session id: cron:clickhouse-impl-slot-5:20260926-085800

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c591327]

Summary: ✅


AI Review

Summary

This PR teaches cleanupJoinPredicates to synthesize missing transitive equi-predicates for inner join steps that already have their own condition, while explicitly skipping mixed-type chains and prepared lookup storages. I reviewed the optimizer changes, the new prepared-storage tracking, the updated plan reference, and the added stateless coverage, and I did not find an actionable correctness, safety, or regression issue in the current head.

Final Verdict

✅ No actionable findings.

LLVM Coverage Report

Measured on commit c591327.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 50/50 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR changes only join reordering: after reordering, it adds predicates implied by chains of equal columns at inner joins, limited to columns of the same type and skipping Join-engine lookups. All flagged queries are ClickBench queries on the single hits table with no joins, so the changed code never runs for them. The three regressions (Q18 +16.5%, Q30 +23.1%, Q31 +21.8%) are downgraded to not_sure, and the five rows inside master's normal range were checked and match the diff. TPC-H, where the new predicates actually apply (Q02's plan changes in the updated test reference), shows no flagged changes.

clickbench

⚠️ 8 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 543 605 +11.4% <0.0001 ClickBench reads only the single hits table and has no joins, so the join-order predicate cleanup in this PR never runs for this query. The +11.4% stays inside master's normal range.
⚠️ 18 not_sure 884 1030 +16.5% <0.0001 This is a GROUP BY on the single hits table with no join, so the transitive-predicate change in the join-order code is never reached. The +16.5% shift, noisy on both sides, cannot come from this diff.
⚠️ 28 not_sure 1059 1120 +5.8% <0.0001 This query reads one table and has no join, so the changed join-order path does not run. The +5.8% stays inside master's normal range and the PR measurements were noisy.
⚠️ 30 not_sure 229 282 +23.1% <0.0001 This query reads one table with no joins, and the PR only changes how join predicates are synthesized after join reordering. CPU time is flat, so the +23.1% is not extra work done by the query.
⚠️ 31 not_sure 271 330 +21.8% <0.0001 This single-table aggregation never builds a join graph, so the changed cleanup code is off its path. The +21.8% median shift cannot be attributed to this diff.
⚠️ 32 not_sure 730 811 +11.0% <0.0001 This query has no join, so the join-order change does not apply. The +11.0% stays inside master's normal range, with noisy measurements on both sides.
⚠️ 33 not_sure 1132 1230 +8.7% <0.0001 This single-table GROUP BY has no join, so the changed code path is not executed. The +8.7% stays inside master's normal range.
⚠️ 34 not_sure 1138 1233 +8.4% <0.0001 This single-table GROUP BY has no join, so the changed code path is not executed. The +8.4% stays inside master's normal range.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 6c100dbf-6d44-468c-9327-773e409476a7
  • MIRAI run: 7d82f6db-4c9c-48e5-950d-9e4d598434aa
  • PR check IDs:
    • clickbench_1976031_1790447245
    • clickbench_1976044_1790447245
    • clickbench_1976051_1790447244
    • tpch_adapted_1_official_1976057_1790447244
    • tpch_adapted_1_official_1976067_1790447244
    • tpch_adapted_1_official_1976103_1790447245

@alexey-milovidov alexey-milovidov self-assigned this Sep 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
Merged via the queue into ClickHouse:master with commit 7a4586f Sep 27, 2026
172 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 27, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 2, 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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TPC-H q02: dpsize joins min(ps_supplycost) to partsupp on the cost value alone

3 participants