Skip to content

Allow equality filters with common super type to be merged into joins - #112630

Merged
novikd merged 15 commits into
ClickHouse:masterfrom
m-selmi:relax-rules-for-merge-filter-into-join-condition
Aug 24, 2026
Merged

novikd merged 15 commits into
ClickHouse:masterfrom
m-selmi:relax-rules-for-merge-filter-into-join-condition

Conversation

@m-selmi

@m-selmi m-selmi commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Currently mergeFilterIntoJoinCondition only applies when both sides of the condition have the same type.
This PR relaxes the condition to be consistent with predicateOperandsToCommonType:

  • excludes Dynamic type unless allow_dynamic_type_in_join_keys is true
  • allow types that have a common supertype

This is especially useful for the case where one side is nullable and the other isn't.

image

Changelog category (leave one):

  • Performance Improvement

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

A WHERE equality is now merged into the JOIN condition when its operands have different types but a common supertype, such as Int32 and Nullable(Int32). This allows a CROSS join to be converted to an INNER Join.


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

Version info

  • Merged into: 26.9.1.23 (included in 26.9 and later)

@m-selmi m-selmi added the can be tested Allows running workflows for external contributors label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [68726c9]

Summary: ✅


AI Review

Summary

This PR extends mergeFilterIntoJoinCondition so a cross-table equality can be absorbed into the JOIN clause when the operands have a common supertype, and it adds guards/tests around Dynamic keys and prepared lookup storages. The common-supertype rewrite itself looks reasonable, but the final prepared-lookup guard is too broad: it also disables existing keyed dictionary/direct lookup plans, so I cannot approve the change as-is.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/mergeFilterIntoJoinCondition.cpp:281-285] The new early return is keyed on JoinStepLogicalLookup, which covers dictionaries and other IKeyValueEntity lookups in addition to StorageJoin. For an existing equal-type query such as INNER JOIN dict ON 1 WHERE lhs.pk = rhs.pk, this pass currently extracts the equality so buildPhysicalJoinImpl can produce one join key and tryDirectJoin can still select DirectKeyValueJoin. With the unconditional return, the query keeps ON 1, no join keys are discovered, and the planner falls back to the constant/cross path instead of a keyed lookup join. That is a real regression for prepared key-value joins, not just a loss of the unsafe StorageJoin case.
    Suggested fix: narrow the guard to the unsafe prepared-storage cases (at least StorageJoin), or otherwise preserve the single-primary-key lookup case for dictionaries / other IKeyValueEntity storages.
Tests
  • ⚠️ The new regression coverage only exercises the Join table engine. Please add one focused dictionary/EmbeddedRocksDB case shaped as ON 1 WHERE lhs.pk = rhs.pk (ideally with join_algorithm = 'direct' and an EXPLAIN assertion) to prove the safe direct-lookup path still survives.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.90% +0.10%
Functions 91.90% 92.00% +0.10%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 29/31 (93.55%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 30, 2026
@m-selmi
m-selmi marked this pull request as ready for review July 31, 2026 19:09
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: b1847902-5015-445d-b89a-ef772ff36b62
  • MIRAI run: 5f2cf1b7-1cc0-4a08-896f-543a623cd9a9
  • PR check IDs:
    • clickbench_113925_1787145279
    • clickbench_113938_1787145279
    • clickbench_113946_1787145279
    • tpch_adapted_1_official_113956_1787145279
    • tpch_adapted_1_official_113981_1787145279
    • tpch_adapted_1_official_113995_1787145280

@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 62/64 (96.88%) · Uncovered code

Full report · Diff report

@novikd novikd self-assigned this Aug 10, 2026
Comment on lines +312 to +315
/// Merging a condition whose operands have different types adds a cast that makes the key `_CAST(key, ...)`.
/// This can make prepared join storage fail because it no longer recognizes the key.
const bool require_equal_types = child_node->children.size() == 2
&& typeid_cast<JoinStepLogicalLookup *>(child_node->children.back()->step.get()) != nullptr;

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.

We can reject joins with StorageJoin on the right side in the beggining of functions. We should not merge condition into the JOIN in such a case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I allowed StorageJoin with equal types here because otherwise the following query shape that works now will start failing.
But I'm not sure if such a query is intended usage, WDT?

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.

I think it is not intended and we should not allow this optimisation for StorageJoin. There is another example:

SELECT * FROM left l JOIN right r ON 1 WHERE l.id = r.id AND l.tag = r.tag SETTINGS query_plan_merge_filter_into_join_condition = 1;

If tag columns will have different types, it will fail with too many keys. It is impossible to implement it consistent for StorageJoin, so we should not allow it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

that makes sense, I switched to rejecting JoinStepLogicalLookup at the start.


/// Merging a condition can make a prepared join storage fail because it no longer recognizes the key.
auto is_storage_join = child_node->children.size() == 2
&& typeid_cast<JoinStepLogicalLookup *>(child_node->children.back()->step.get()) != nullptr;

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.

This guard now disables mergeFilterIntoJoinCondition for every JoinStepLogicalLookup, not only for StorageJoin. That is broader than the bug it is fixing: dictionaries and other IKeyValueEntity lookups also arrive here via JoinStepLogicalLookup, and master already relies on this pass for valid equal-type queries of the form ... INNER JOIN dict ON 1 WHERE lhs.pk = rhs.pk.

Before this return, the WHERE equality was extracted here, buildPhysicalJoinImpl could still discover one join key, and tryDirectJoin was able to pick DirectKeyValueJoin (src/Processors/QueryPlan/JoinStepLogical.cpp:1430-1464, src/Planner/PlannerJoins.cpp:1048-1121). With the unconditional early exit, the same query keeps ON 1, no keys are found, and the planner falls through to the constant/cross path instead of a keyed lookup join. That regresses an existing direct/dictionary plan into a full-scan ConstantJoin.

Can we narrow this guard to the unsafe prepared-storage cases (at least prepared_join_storage.storage_join) and add a focused regression test for a dictionary/EmbeddedRocksDB query shaped as ON 1 WHERE lhs.pk = rhs.pk?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

the same discussion in #112630 (comment) applies to this.

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 68726c917 with master 747e52eb5 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.05 MiB 699.02 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

14 translation units recompiled, 76 s compile time in total, 14 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.13 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +6.6 s (+9%) in total before that adjustment.

Job report

@novikd
novikd added this pull request to the merge queue Aug 24, 2026
Merged via the queue into ClickHouse:master with commit ef23be3 Aug 24, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
novikd added a commit that referenced this pull request Aug 25, 2026
…ack cases

Review feedback pointed out that under the default
`query_plan_merge_filter_into_join_condition = 1` the guarded float cases'
fallback loses the `-0.0` matches, so pinning the setting looked like hiding
a gap. The divergence reproduces with the substitution disabled — it is
master's own decorrelation fallback interacting with the common-supertype
condition merging, now tracked as issue #116358 (caused by PR #112630, the
fix belongs in `tryMergeFilterIntoJoinCondition`, not in the decorrelation).
The pin stays for test determinism; the pin comment and the case 12/24
headers now reference the tracked issue instead of implying the `equals`
fallback semantics are the production default.

Related: #116358
Related: #115493

Co-Authored-By: Claude Fable 5 <[email protected]>
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Aug 26, 2026
pull Bot pushed a commit to Dream-hu/ClickHouse that referenced this pull request Sep 27, 2026
… 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]>
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 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.

4 participants