Skip to content

Merge cross-side range predicates from WHERE into the JOIN condition - #128140

Open
zoomxi wants to merge 15 commits into
ClickHouse:masterfrom
zoomxi:filter-into-join
Open

zoomxi wants to merge 15 commits into
ClickHouse:masterfrom
zoomxi:filter-into-join

Conversation

@zoomxi

@zoomxi zoomxi commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

A cross-side range comparison written in WHERE (<, <=, >, >=) used to stay in a FilterStep above the join. The join-order optimizer walks through JoinStepLogical, and stops at that filter, so the join underneath is one relation. Equalities were already pulled into the join by query_plan_merge_filter_into_join_condition; ranges were not.

a and c are 3 rows each, and b is 10 000 rows. With the ranges stuck above the joins, the plan joins b first and applies a.x < c.x AND a.y > c.y only after both joins. After the ranges become join conditions, reordering joins a and c first and then joins b to that result.

Example SQL and Plan Change

  CREATE TABLE a (id UInt32, k Int64, x Int64, y Int64) ENGINE = Memory;
  CREATE TABLE b (id UInt32, ak Int64, ck Int64) ENGINE = Memory;
  CREATE TABLE c (id UInt32, k Int64, x Int64, y Int64) ENGINE = Memory;

  -- a: 3 rows, b: 10 000 rows, c: 3 rows
  INSERT INTO a VALUES (1, 1, 10, 100), (2, 2, 20, 200), (3, 3, 30, 300);
  INSERT INTO c VALUES (1, 1, 15, 50), (2, 2, 25, 150), (3, 3, 5, 400);
  INSERT INTO b SELECT number, number % 3 + 1, (number * 7) % 3 + 1 FROM numbers(10000);
  EXPLAIN
  SELECT a.id, b.id, c.id
  FROM a
  JOIN b ON a.k = b.ak
  JOIN c ON b.ck = c.k
  WHERE a.x < c.x AND a.y > c.y
  SETTINGS join_algorithm = 'direct,parallel_hash,hash,ie_join',
           query_plan_optimize_join_order_algorithm = 'dpsub',
           query_plan_optimize_join_order_limit = 3,
           query_plan_merge_filter_into_join_condition = 0;

Before:

Filter (WHERE: x < x AND y > y)
└──Join b[10000] ⋈ c[3] ⋈ a[3]   HashJoin, ak = k
   │  Output rows: estimated 10.00 thousand
   │  Cost: estimated 20.00 thousand
   ├──Join b[10000] ⋈ c[3]   HashJoin, ck = k
   │  ├──ReadFromMemoryStorage (b)
   │  └──ReadFromMemoryStorage (c)
   └──ReadFromMemoryStorage (a)

After:

Join b[10000] ⋈ (a[3] ⋈ c[3])   HashJoin, ak = k AND ck = k
│  Output rows: estimated 10.00 thousand
│  Cost: estimated 10.01 thousand
├──ReadFromMemoryStorage (b)
└──IEJoin
   │  Conditions: a.y > c.y AND a.x < c.x
   ├──ReadFromMemoryStorage (a)
   └──ReadFromMemoryStorage (c)

Changelog category (leave one):

  • Performance Improvement

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

Cross-side range comparisons (<, <=, >, >=) in WHERE are merged into an INNER or CROSS join when query_plan_merge_filter_into_join_condition is enabled, so the join-order optimizer can reorder across them.


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

Let `tryMergeFilterIntoJoinCondition` extract cross-side range
comparisons (`<`, `<=`, `>`, `>=`) when `hash` is enabled, guarding each
conjunct against evaluation-count sensitivity and `ARRAY_JOIN`.

Also let `isIEJoinPreferred` yield to another runnable algorithm when a
cross-side equality key matches values `equals` rejects (`NaN`, `NULL`s
inside tuples) and all equality keys have a valid common type.
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Oct 29, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e382871]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
01763_filter_push_down_bugs FAIL cidb
02346_text_index_transform_access FAIL cidb
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
05234_promql_result_timestamp_scale FAIL cidb
01710_projection_with_mixed_pipeline NOT_FAILED cidb
04353_text_index_explicit_tokenizer_argument NOT_FAILED cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
Performance Comparison (arm_release, master_head, iceberg_local, 1/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_local, 2/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_local, 3/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_s3, 1/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_s3, 2/3) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, iceberg_s3, 3/3) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

The PR promotes safe cross-side range predicates from WHERE into INNER/CROSS JOIN conditions so join reordering can cross the former filter boundary. Reviewed head: e382871ec8669ecca1e09ac6f9c068be6dd75a91. The earlier correctness findings are addressed, and the new regression test passes in the current head's Fast test report. One existing performance validation concern remains; no new inline findings.

Findings

⚠️ Majors

  • mergeFilterIntoJoinCondition.cpp:381: Recheck TPC-DS Q72 on the current head (existing thread). ARM tpcds, query index 71, slows down by 11.3%, 9.7%, 9.0%, and 10.0% across the four completed comparisons. The newest measured run increases client_time from 0.1148 s to 0.1263 s. Raw Sample Evidence, Quantile Shift, History Adaptive Threshold, and Recent Master Variation support the slowdown; multimodal fleet history adds uncertainty. The query executes the modified optimizer and includes outer joins absent from the focused benchmark. These measurements cover 9806d0140620 and earlier commits, so they do not establish a regression at the current head. The performance claim still needs this existing workload accounted for after the master merge.
Performance & Safety

All changed client_time rows in the latest available comparison, dated 2026-11-03 (34064ae5afdd → 9806d0140620):

Workload Architecture Before → after Change Evidence
TPC-DS Q72 ARM 0.1148 → 0.1263 s +10.0% Supported slowdown; needs current-head rerun
TPC-DS Q72 AMD 0.1342 → 0.1567 s +16.7% Confidence analysis classifies as noise
Focused range-merge benchmark, query 0 ARM 0.5399 → 0.0404 s −92.5% Supported improvement
Focused range-merge benchmark, query 0 AMD 0.5218 → 0.0394 s −92.5% Supported improvement
Tests
  • ⚠️ Compare ARM TPC-DS Q72 (tpcds/71) at e382871ec866 against its current base, 92fdcb78e3a9. If the slowdown persists, compare plans/profiles and address or explicitly justify the tradeoff. No performance run for the current head is available in the dashboard.
Final Verdict

⚠️ Request changes — close the existing current-head performance validation gap. No additional inline comments or thread replies are needed.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements external Author is not a member of the ClickHouse organization labels Oct 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e382871ec with master 92fdcb78e (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

A range such as `toInt64` or a `Decimal` compared with `Float64` can throw, and a residual `rowNumberInAllBlocks` changes when rows are removed first. Pin `query_plan_merge_filter_into_join_condition` where an EXPLAIN reference depends on it.
`canBeMovedToTheFrontOfAndChain` already decides that an `and` atom can run on more rows, and `isSensitiveToEvaluationCount` with `hasArrayJoin` already guards a step that changes the row set.
A single top-level `or` is the hash-key form for disjunctive `ON`.
Appending another conjunct would turn those keys into scalar `equals`.
Treat nested Variant, Dynamic and JSON types as potentially throwing in comparisonCanThrow, so a promoted comparison cannot run before its guarding conjunct.

Do not extract range predicates when the existing JOIN expression is sensitive to evaluation count. Add regression coverage for both cases to 05454.
…er-into-join test.

`less` is cheap, so when the flaky check disables `query_plan_merge_filters` it runs before a false guard and throws `NO_COMMON_TYPE`.
Those checks apply to conditions already written in `ON`, so they belong with the standalone `ie_join` fix. Range merging still keeps Tuple and Float equalities in the residual filter.
…o filter-into-join

Take master's  from  and its  handling in  instead of the copies in this branch.
ClickHouse#129219 concluded that `ie_join` should not yield to another algorithm when a residual `equals` differs from a join key: the remaining differences (`NaN`, `NULL` inside tuples) are documented per algorithm in ClickHouse#129361, and ClickHouse#118561 makes `String`/`FixedString` keys, including `ie_join` range keys, compare like the scalar functions.

The `hash` requirement for merging ranges now states its actual reason: a merged range is a non-equi `ON` condition. Add the `String`/`FixedString` regressions from the review of ClickHouse#128140, and drop the `parallel_hash` case: `parallel_hash` is now the same algorithm as `hash`.

Related: ClickHouse#129219
Related: ClickHouse#128140
Drop the `String`/`FixedString` cases (fixed in master by ClickHouse#118561), the `NaN`/`Tuple(Nullable)` key cases (documented per algorithm in ClickHouse#129361), and the reorder cases that repeat one query under other join or reorder algorithms. Shorten the comment of the performance test.
|| conjunct->function_base->getName() == "greater"
|| conjunct->function_base->getName() == "greaterOrEquals")
&& conjunct->children.size() == 2;
if (!block_range_predicates && is_range && is_cross_side(conjunct->children[0], conjunct->children[1])

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.

[Major] Recheck the repeatable TPC-DS Q72 slowdown on the current head

The existing tpcds query index 71 (Q72) exercises these cross-side ranges together with additional outer joins. It slows down on ARM in all four completed PR comparisons: +11.3%, +9.7%, +9.0%, and +10.0%. In the latest measured run, client_time rises from 0.1148 s to 0.1263 s; repeated samples and recent master variation support a slowdown signal. The new focused benchmark shows a substantial improvement, but its join graph omits these outer joins.

These measurements cover 9806d0140620 and earlier commits, so they do not establish a regression at the current head. Please rerun this query on e382871ec866 against its current base and compare the plans/profiles if the slowdown persists. The performance claim needs this existing workload accounted for before approval.

This branch has not been deployed

No deployments
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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants