Skip to content

Propagate predicates across equi join - #108377

Merged
yariks5s merged 73 commits into
masterfrom
yarik/lift-predicates-accross-join
Sep 4, 2026
Merged

yariks5s merged 73 commits into
masterfrom
yarik/lift-predicates-accross-join

Conversation

@yariks5s

@yariks5s yariks5s commented Jun 24, 2026 •

Copy link
Copy Markdown
Member

Adds a query-plan optimization (query_plan_propagate_predicate_across_join) that, for an equi-join, copies filter conjuncts from one side onto the other via equi-key substitution, so that index pruning (MergeTree primary key) on the other side picks them up.

Changelog category (leave one):

  • Performance Improvement

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

Added query-plan optimization query_plan_propagate_predicate_across_join that copies equi-join filter conjuncts across MergeTree join inputs for better primary-key pruning.
Perf results show 70-80x improvement on specific queries.

image

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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5b386d8]

Summary: ✅


AI Review

Summary

This PR adds query_plan_propagate_predicate_across_join, wiring a new equi-join predicate propagation pass into second-pass query-plan optimization and covering it with focused stateless/performance tests. The main safety issues from earlier rounds are fixed, but the current primary-key usefulness gate still admits a realistic full-scan case on composite keys, the changelog text is stale after the rename/narrowing, and the final Performance Improvement claim still lacks fresh evidence for the current head.

PR Metadata

Changelog category is correct: Performance Improvement.

Changelog entry is required and is currently stale. It still names the removed setting query_plan_lift_predicate_across_join, describes a broader contract than the final implementation, and keeps the unsupported 70-80x claim even though the current head has no attached perf report.

Exact replacement:
Added query-plan optimization query_plan_propagate_predicate_across_join that copies simple equi-join key predicates across MergeTree join inputs so the opposite side can use them for primary-key pruning.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Propagate predicates across equi join #108377#discussion_r3636047915] [src/Processors/QueryPlan/Optimizations/propagatePredicateAcrossEquiJoin.cpp:97-112] The new usefulness gate only proves that each substituted column name appears somewhere in getPrimaryKey().column_names. That is not enough on composite keys: with ORDER BY (orderkey, custkey), a propagated custkey = 7 still gets accepted when the target has no orderkey constraint, but that suffix-only predicate cannot narrow the target read and survives as a post-read full-scan filter. Suggested fix: ask ReadFromMergeTree/KeyCondition whether the candidate atom together with the existing target filter actually narrows the read, or at least reject non-leading-key predicates unless the target already constrains the prefix.
Tests
  • ⚠️ The PR still lacks current performance evidence for the final head. The only benchmark note in the discussion is the 2026-06-27 cloud report for an early SHA, while the current latest CI report only exposes Build profile diff. Please attach a fresh run of tests/performance/propagate_predicate_across_equi_join.xml or a current perf-comparison report for 5b386d81.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 5b386d8.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.10% +0.10%

Changed lines: Changed C/C++ lines covered: 230/241 (95.44%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 24, 2026
yariks5s and others added 3 commits June 24, 2026 16:05
ReadFromMergeTree::applyFilters short-circuits when `indexes` is already
populated. The initial second-pass PK traversal populates it before the lift
adds new filters, so a plain re-run of `optimizePrimaryKeyConditionAndLimit`
was a no-op — the FilterStep appeared in the plan but the source still
scanned every granule. The analysis is also cached in `analyzed_result_ptr`,
so even after rebuilding `indexes`, `getAnalysisResult` (used by EXPLAIN and
range selection) returns the stale cached result.

Add a public `ReadFromMergeTree::invalidateIndexes()` that drops both
`indexes` and `analyzed_result_ptr`, and call it on the affected sources
before re-running PK condition analysis.

Move the PK re-run into the leave callback right after the lift fires,
BEFORE `convertLogicalJoinToPhysical` reorganizes the JOIN's children
(after the conversion the physical structure has back-edges that a plain
tree DFS can't cope with), and give it its own `Stack` since
`traverseQueryPlan` starts with `stack.clear()` which would corrupt the
outer walk's stack.

Verified locally on 200M+200M rows, max_threads=1:

  Point lookup k = 100000000           78 ms vs 2.08 s   ~27x
  Narrow range, ~1k matches            81 ms vs 2.16 s   ~27x
  LEFT join, ~10k matches              82 ms vs 2.32 s   ~28x
  IN list, 6 keys                      80 ms vs 2.11 s   ~26x
  Wide range (10 % of target)         3.04 s vs 7.37 s   ~2.4x
  Overhead (filter on non-equi col)   3.76 s vs 3.77 s   ~1.00x

Perf XML bumped to 200M+200M and max_threads=1 so the LIFT-OFF baseline
lands in the 1-2 s window where the speedup is visible in wall clock;
adds IN-list, wide-range, and overhead-check coverage.
@clickhouse-gh

clickhouse-gh Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 32 not_sure 1376 1304 -5.2% 0.0289

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: a5a7edc9-476e-4eaf-8412-1110801f23de
  • MIRAI run: 949c84ae-b2e5-4622-87b9-ff5b77769cbe
  • PR check IDs:
    • clickbench_1194762_1788534752
    • clickbench_1194768_1788534752
    • clickbench_1194774_1788534751
    • tpch_adapted_1_official_1194780_1788534752
    • tpch_adapted_1_official_1194797_1788534752
    • tpch_adapted_1_official_1194834_1788534751

yariks5s and others added 2 commits June 30, 2026 15:08
… INPUT

JoinStepLogical equi-keys can be expressions produced by join pre-actions
(e.g. ON l.k = r.k + 1). The substituted column ends up as an INPUT name of
the lifted FilterStep, which sits above the target child — so the name must
exist in the child's output header. Skip pairs whose target key is not a raw
INPUT in the corresponding direction.

The guard was originally added in 0f818df and removed by 09875f5 alongside
the source-filter snapshot refactor. Restore it.
yariks5s added 3 commits June 30, 2026 20:14
Add a focused EXPLAIN test for the regression shape that prompted the
target-key INPUT guard — ON o.orderkey = l.orderkey + 1, where the rhs
equi-key is a computed pre-join expression. Verify no Lifted equi-join
filter is inserted and the result matches the setting-off plan.
The previous INPUT-only guard was too strict — JoinStepLogical's equi-key
JoinActionRef can be an ALIAS or other non-INPUT wrapper even for simple
'ON l.k = r.k', so the guard rejected valid pairs and the lift stopped
firing on the existing 'inner eq' / 'left between' / 'multi-clause' cases.

Replace it with a direct check: the target column's name must exist in the
target child's output header. This is the actual invariant the FilterStep
needs (its INPUT must resolve to a column the child produces), and it
naturally rejects computed equi-keys like 'ON l.k = r.k + 1' whose rhs name
is 'plus(...)' that isn't in the right child's header.
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Jun 30, 2026
Comment thread contrib/azure Resolved
The previous merge from master accidentally rolled back contrib/azure from
20f8b46b8 to e1c250fe5, dropping the Base64Decode fix for global-buffer-overflow
and undefined left shift on malformed input. Restore the pointer to the master
revision; this submodule bump is unrelated to the lift-predicate change.

Addresses #108377 (comment)
@yariks5s yariks5s removed the submodule changed At least one submodule changed in this PR. label Jun 30, 2026
Under randomized parallel-replicas settings the plan reads through
remote-replica steps, the lift correctly bails (no local MergeTree
target), and the EXPLAIN countIf drops to 0. The test checks the local
read path, so pin the setting.
@vdimir vdimir self-assigned this Sep 3, 2026
if (propagated_dag->getOutputs().size() != 1)
return 0;

/// Drop conjuncts the target already has: equal result_name means structurally equal atom

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.

Matching by name probably does not always guarantee a result, since DAGs may in theory have arbitrary renames. However, I cannot come up with a better solution at the moment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

agree, I don't have either

@yariks5s
yariks5s requested a review from vdimir September 4, 2026 09:20
@abashkeev abashkeev added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@yariks5s
yariks5s enabled auto-merge September 4, 2026 13:45
@yariks5s
yariks5s added this pull request to the merge queue Sep 4, 2026
Merged via the queue into master with commit 3f30bb6 Sep 4, 2026
174 checks passed
@yariks5s
yariks5s deleted the yarik/lift-predicates-accross-join branch September 4, 2026 23:04
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Hi! Quick question. This doesn't seem to propagate PREWHERE predicates, although they can? Is this leftover deliberate, and am I missing something?

@vdimir

vdimir commented Sep 8, 2026

Copy link
Copy Markdown
Member

Hi! Quick question. This doesn't seem to propagate PREWHERE predicates, although they can? Is this leftover deliberate, and am I missing something?

@PedroTadim
In this PR, we propagate predicates that can be used as primary key only

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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.

6 participants