Skip to content

Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys - #103478

Merged
fm4v merged 17 commits into
ClickHouse:masterfrom
raimannma:fix-join-equi-key-filter-pushdown-right-full
Aug 29, 2026
Merged

fm4v merged 17 commits into
ClickHouse:masterfrom
raimannma:fix-join-equi-key-filter-pushdown-right-full

Conversation

@raimannma

@raimannma raimannma commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Related: #103038

For RIGHT JOIN with a WHERE predicate on a USING column whose two sides have different types, the predicate was not used as a primary-key index condition on the left input, so the left MergeTree read every granule.

buildEquialentSetsForJoinStepLogical only returns equi-key pairs whose two sides have equal types, because those pairs feed a Union-Find equivalence class. Plain column-name substitution does not need that. It does need two other things: the replacement must carry the type the replaced name has in the JOIN output, because that is what the filter's nodes were typed against, and it must evaluate to the value that output column holds, because the filter's semantics are defined on that value.

A cross-type equi-key gives both once the replacement is cast the way the JOIN casts that key. The two sides are compared in their least supertype, so CAST(<opposite side>, supertype) is exactly what is behind the JOIN output column. Requiring the JOIN output type to be that supertype keeps the cast widening - a narrowing one would change what the predicate returns - and still rejects a column the JOIN altered for an unrelated reason, such as join_use_nulls widening it to Nullable. The cast node is only materialized once a pushed-down filter actually references it.

Reproducer from the issue:

CREATE TABLE mt (k UInt64) ENGINE = MergeTree ORDER BY k
  AS SELECT number FROM numbers(10000000);

SELECT k FROM mt AS l RIGHT JOIN (SELECT 1 AS k) AS r USING (k) WHERE k = 1;

Measured on 10M rows, before and after on the same data:

rows read bytes read time
before 10,000,001 76.29 MiB 0.050 s
after 8,193 64.00 KiB 0.021 s

Granules read on the left MergeTree for RIGHT JOIN ... USING (k) WHERE k = 1, 1M rows, by key type pair. The first two rows are what an earlier revision already delivered; the last three are what this revision adds:

left right USING type before after
UInt64 UInt8 UInt64 (== left) 122/122 1/122
Int64 UInt32 Int64 (== left) 122/122 1/122
Int32 Int64 Int64 (== right) 122/122 1/122
Int32 UInt32 Int64 (wider than both) 122/122 1/122
UInt32 Int32 Int64 (wider than both) 122/122 1/122

The pushed-down condition is the JOIN's own cast, so the index still applies: Condition: (_CAST(k, 'Int64') in [1, 1]).

Scope

This does not close #103038. The issue asks for RIGHT and FULL JOIN, and covers both planners; this pull request only fixes RIGHT JOIN under enable_analyzer = 1.

FULL JOIN is not fixed, for the reasons below, and the test keeps its cases as result-only regression guards.

The legacy JoinStep path (enable_analyzer = 0) is not fixed either. There, a USING key is renamed to <table>.<key> in the right input header while the JOIN output keeps the bare name, so equivalent_columns_to_push_down holds a name the filter never references and nothing is pushed - the type check this pull request relaxes is not what blocks it. Making it work would additionally require the JOIN-output type guard that path lacks entirely, which is the guard #98167 had to add for join_use_nulls. That is out of scope here.

The substitution is also not registered in the opposite direction when it would need a narrowing cast, for example a predicate on the wider of the two keys: the narrower side cannot reproduce the value the JOIN output carries, so the predicate stays above the JOIN.

An earlier revision of this pull request also enabled the push-down for FULL JOIN and generalised RIGHT / LEFT JOIN from Semi strictness to any strictness. Both were unsound and have been reverted.

The reasoning behind them was that the top-level WHERE stays above the JOIN and removes any row that slips through the duplicated per-side filter. It does not: tryPushDownOverJoinStep replaces the FilterStep with an ExpressionStep once every conjunction has been pushed, and conjunctions routed through equivalent_columns_to_push_down are pushed to both sides and never land in rejected_conjunctions, which is exactly what triggers the removal.

Keeping the post-join filter would not have been sufficient either. Pushing an equivalence-derived predicate to the opposite input changes which rows match, and an outer JOIN then emits a defaulted unmatched row whose columns differ from the original, so a predicate evaluated on that default both admits rows belonging to neither input and discards rows that should survive:

-- returned 3 rows instead of 1
SELECT * FROM t1 AS lhs FULL JOIN t2 AS rhs ON lhs.id = rhs.id
WHERE lhs.id != 0 AND rhs.id != 0;

-- lost the unmatched (5, 0) row
SELECT lhs.id, rhs.id FROM s1 AS lhs FULL JOIN s2 AS rhs ON lhs.id = rhs.id
WHERE rhs.id != 5;

-- returned a jt.x = 5 row, against a filled join where the right-side push is disabled
SELECT lt.x, jt.x FROM lt RIGHT JOIN jt ON lt.x = jt.x WHERE jt.x = 1;

SEMI emits only matched rows, which is why the original restriction was there. FULL JOIN, both Semi restrictions and both equivalence branches are now identical to master, and the 03036_join_filter_push_down_equivalent_sets reference no longer needs the rewrite an earlier revision gave it.

The test covers the granule pruning for RIGHT JOIN across the key-type pairs above and keeps the wrong-result cases as regression guards.

Changelog category (leave one):

  • Performance Improvement

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

Push a WHERE condition on a USING column through a RIGHT JOIN so the left MergeTree input can use it as a primary-key index condition, also when the two join keys have different types. Applies when enable_analyzer = 1.


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

Version info

  • Merged into: 26.9.1.314 (included in 26.9 and later)
  • Backported to: 26.8.1.2032, 26.7.6.41, 26.6.4.45

raimannma and others added 2 commits April 23, 2026 23:40
For `RIGHT` / `FULL JOIN` with a `WHERE` predicate on the `USING` / equi-join
column, the predicate was not used as a primary-key index condition on the
left input. The left `MergeTree` scan read every granule even when the
predicate was highly selective. `INNER` / `LEFT JOIN` already optimised
correctly.

Reproducer:

    CREATE TABLE mt (k UInt64) ENGINE = MergeTree ORDER BY k
      AS SELECT number FROM numbers(100000000) ORDER BY rand();

    EXPLAIN PLAN indexes = 1
    SELECT k FROM mt AS l RIGHT JOIN (SELECT 1 AS k) AS r USING (k) WHERE k = 1;
    -- Before: Granules: 120/120    After: Granules: 2/2

`tryPushDownOverJoinStep` in `filterPushDown.cpp` rejected `FULL JOIN`
outright and, for `RIGHT JOIN`, only allowed the equi-key bridge when the
strictness was `Semi`. Generalising it for any strictness is safe for every
outer-JOIN shape (All / Any / Semi / Anti) because the top-level `WHERE`
stays in place and filters out any rows that would slip through the
duplicated per-side filter.

Additionally, `buildEquialentSetsForJoinStepLogical` skips equi-key pairs
whose two sides share different types (because the equivalence class it
feeds relies on type equality). That meant the `UInt8`-vs-`UInt64` `USING`
case in the reproducer never reached the equi-key pushdown path. Register
every Equals predicate from `join_operator.expression` directly as a
column-name substitution entry, ignoring the type check -- type mismatch
is handled by ClickHouse's cross-type comparison in `KeyCondition`. Gated
on at least one side being restricted so `INNER JOIN` (both sides freely
pushable) is unaffected.

`FULL JOIN` output `k` is wrapped in `firstNonDefault(l.k, r.k)` which
`KeyCondition` cannot currently reduce to `k = c`, so granule pruning does
not kick in for `FULL JOIN`. The filter is still pushed to both inputs,
which is the groundwork for a future KeyCondition / DAG simplification.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- Pull the equi-key predicate walker out of `getJoiningKeysForJoinStep` into
  `forEachEquiJoinKey` so both it and the new outer-join equivalence-map
  population use the same normalisation logic instead of duplicating the
  `asBinaryPredicate` / `fromLeft` / `fromRight` / `swap` pattern.
- Call `lhs.getColumn()` / `rhs.getColumn()` only when the insert will
  happen; the prior code copied both `ColumnWithTypeAndName` unconditionally.
- Trim the verbose WHY/HOW comments in the `else if` branches that paraphrased
  the downstream mechanism.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@rschu1ze

Copy link
Copy Markdown
Member

@vdimir

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/filterPushDown.cpp
@vdimir vdimir self-assigned this Jul 21, 2026
@vdimir vdimir added the can be tested Allows running workflows for external contributors label Jul 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [888a3bf]

Summary: ✅


AI Review

Summary

This PR extends analyzer-side RIGHT JOIN filter pushdown to cross-type equi-keys by materializing the same widening cast the join output uses, so the left MergeTree side can still derive a primary-key condition. The core implementation and the newer coverage around widened supertypes and session_timezone look coherent, but one regression guard is still too weak to prove the advertised "no narrowing substitution" boundary.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04117_join_equi_key_filter_pushdown_right_full.sql:148] The RIGHT JOIN ON, predicate on the wider side: no narrowing substitution case still only checks count() = 1. With the default query_plan_convert_outer_join_to_inner_join = 1, WHERE l.k = 1 makes unmatched right rows impossible, so the optimizer can legally rewrite this RIGHT JOIN to INNER and apply ordinary left-side pushdown. That means the test stays green even if the narrowing-direction substitution is broken, so it does not actually protect the boundary described in the comment above it.
    Suggested fix: pin query_plan_convert_outer_join_to_inner_join = 0 for this case and assert on the plan (no Granules: 1/% / no pushed PK condition) instead of only on the final row count.
Missing context / blind spots
  • ⚠️ I could not execute the changed queries locally because this workspace does not contain a built clickhouse binary. A local repro of the narrowing-direction case would fully close the remaining evidence gap.
Final Verdict

⚠️ Needs changes: the implementation looks plausible on the current head, but the narrowing-direction regression guard is still not strong enough to prove the intended behavior.

LLVM Coverage Report

Measured on commit 888a3bf.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 88/92 (95.65%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 21, 2026
The equi-key push-down generalisation was unsound for `FULL JOIN`. The reasoning
was that the top-level `WHERE` stays above the join and removes any row that
slips through, but `tryPushDownOverJoinStep` replaces the `FilterStep` with an
`ExpressionStep` once every conjunction has been pushed, so the `WHERE` is gone.
Conjunctions routed through `equivalent_columns_to_push_down` are pushed to both
sides and never land in `rejected_conjunctions`, which is exactly what triggers
the removal.

Keeping the post-join filter would not have been enough either. Pushing an
equivalence-derived predicate to the opposite input changes which rows match, and
`FULL JOIN` then fabricates a defaulted unmatched row whose columns differ from
the original. A predicate evaluated on that default both admits rows belonging to
neither input and discards rows that should survive:

    SELECT * FROM t1 AS lhs FULL JOIN t2 AS rhs ON lhs.id = rhs.id
    WHERE lhs.id != 0 AND rhs.id != 0;   -- returned 3 rows instead of 1

    SELECT lhs.id, rhs.id FROM s1 AS lhs FULL JOIN s2 AS rhs ON lhs.id = rhs.id
    WHERE rhs.id != 5;                   -- lost the unmatched (5, 0) row

Restore the `FULL JOIN` early return, so that path is unchanged from `master`.

`RIGHT` / `LEFT` keep the generalisation from `Semi` to any strictness, which is
sound: those equi-key names are also pushed to the preserved side natively, so
the copy on the opposite input is a pure narrowing. A surviving row keeps exactly
the partners it had, and a dropped one is rejected by the post-join filter
whether or not it found a match.

Both wrong-result cases are added to the test as regression guards.
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 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: 197036cb-035f-4ce0-8dd2-414c45fdcebb
  • MIRAI run: 582b6a1d-62ab-4593-b816-275e06105a14
  • PR check IDs:
    • clickbench_277323_1787973757
    • clickbench_277329_1787973757
    • clickbench_277336_1787973756
    • tpch_adapted_1_official_277347_1787973756
    • tpch_adapted_1_official_277356_1787973756
    • tpch_adapted_1_official_277393_1787973757

Revert the `Semi` -> any-strictness generalisation and the swapped equivalence
maps: both were unsound. Pushing an equivalence-derived predicate to the opposite
input changes which rows match, and an outer JOIN then emits a defaulted
unmatched row whose columns differ from the original, so a predicate evaluated on
that default admits and discards rows incorrectly. `SEMI` emits only matched rows,
which is why the original restriction was there.

    -- RIGHT JOIN against a filled join, WHERE on the right key
    SELECT lt.x, jt.x FROM lt RIGHT JOIN jt ON lt.x = jt.x WHERE jt.x = 1;
    -- returned a jt.x = 5 row

What remains is registering the equi-key pairs that
`buildEquialentSetsForJoinStepLogical` skips: its Union-Find needs the two input
types to be equal, plain name substitution does not. Substitution instead needs
the replacement column to carry the type the replaced name has in the JOIN output,
since that is what the filter nodes were typed against. That is weaker than input
type equality, so a cross-type `USING` still reaches the opposite `MergeTree` as an
index condition, and stronger where it matters, so a column widened by
`join_use_nulls` no longer contradicts the predicate's result type.

`FULL JOIN`, both `Semi` restrictions and both equivalence branches are now
identical to `master`, so the `03036` reference no longer needs its rewrite.
@raimannma raimannma changed the title Push equi-key filter into the left input of RIGHT / FULL JOIN Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys Jul 21, 2026
raimannma and others added 2 commits July 21, 2026 19:25
Under `enable_analyzer = 0` a `USING` key is renamed to `<table>.<key>` in
the right input header while the `JOIN` output keeps the bare name, so the
equivalence maps are keyed by a name the filter never references and nothing
is pushed. The relaxed type check is not what blocks that path, and making it
work would also require the `JOIN`-output type guard it lacks entirely.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
raimannma and others added 2 commits July 22, 2026 15:22
The substitution added by `tryPushDownOverJoinStep` only fires when the replacement
column already carries the type the replaced name has in the JOIN output header, which
is the header the filter above the JOIN was typed against. Pin that with `join_use_nulls`
enabled, where the output is widened: the cross-type `USING` key still reaches the left
`MergeTree` as an index condition, and an unmatched right row keeps its `NULL` left side.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.70% +0.20%

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

Full report · Diff report

@vdimir
vdimir added this pull request to the merge queue Jul 31, 2026
@vdimir
vdimir removed this pull request from the merge queue due to a manual request Jul 31, 2026
@vdimir

vdimir commented Aug 3, 2026

Copy link
Copy Markdown
Member

buildJoinUsingCondition keeps join_operator.expression on the raw input nodes and stores the cast-to-common-type aliases only in changed_types, so replacement.type here is still the original input type. That means this recovery only works when the USING output type happens to equal one side already (the new UInt8/UInt64 test), but it still misses legitimate cross-type USING keys whose common type is wider than both inputs. For example, Int32 joined to UInt32 produces an Int64 USING column; both substitutable(...) checks fail, equivalent_columns_to_push_down stays empty for the left side of a RIGHT JOIN, and the left MergeTree still full-scans. To actually deliver cross-type USING support, this needs to substitute through the logical join's output-typed alias (or cast the replacement to the USING output type) instead of comparing against the raw input column type.

#103478 (comment)

@groeneai could you confirm this and create a repro?

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

@vdimir Confirmed, with one refinement to the characterisation.

I measured it on the two official CI binaries rather than a local build, so the arms are exact:
PR head build_amd_release for 4b904ba1 (its GIT_HASH 5ec8976e is "Merge 4b904ba into a90a5c2"),
against REFs/master/a90a5c2f.../build_amd_release, which is that same merge base. RIGHT JOIN ... USING (k) WHERE k = 1, granules on the left MergeTree, 1M rows:

left right USING type master PR head rows read (PR)
UInt64 UInt8 UInt64 (== left) 122/122 1/122 8,193
Int64 UInt32 Int64 (== left) 122/122 1/122 8,193
Int32 Int64 Int64 (== right) 122/122 122/122 1,000,001
Int32 UInt32 Int64 (wider than both) 122/122 122/122 1,000,001
UInt32 Int32 Int64 (wider than both) 122/122 122/122 1,000,001

Your Int32/UInt32 example behaves exactly as you predicted: nothing is pushed and the left input still full-scans. Results are identical on both arms in every row, so this is a scope gap, not a regression.

The refinement: the surviving case is not "the USING output type happens to equal one side". It is specifically "the output type equals the left input type". Row 3 has the output type equal to the right raw input type and still does not prune, because the substitution that would help the left side is the one keyed on the left name, and that is the comparison that fails. So the set the current diff delivers is just "the left side is not cast by the USING supertype" - which is why the new UInt8/UInt64 test passes: there the left side is already UInt64.

Repro, self-contained (1 / 0 / 0 on the PR head, 0 / 0 / 0 on master):

SET enable_analyzer = 1;
SET query_plan_filter_push_down = 1;
SET query_plan_join_swap_table = 'false';
SET enable_join_runtime_filters = 0;

CREATE TABLE mt_i32 (k Int32) ENGINE = MergeTree ORDER BY k
    SETTINGS index_granularity = 8192, index_granularity_bytes = '10Mi';
INSERT INTO mt_i32 SELECT number FROM numbers(1000000);
CREATE TABLE mt_i64 (k Int64) ENGINE = MergeTree ORDER BY k
    SETTINGS index_granularity = 8192, index_granularity_bytes = '10Mi';
INSERT INTO mt_i64 SELECT number FROM numbers(1000000);

-- delivered: USING type == left input type
SELECT count() > 0 FROM (
    EXPLAIN PLAN indexes = 1
    SELECT k FROM mt_i64 AS l RIGHT JOIN (SELECT 1::UInt32 AS k) AS r USING (k) WHERE k = 1
) WHERE explain ILIKE '%Condition: (k in [1, 1])%';

-- not delivered: USING type wider than both inputs
SELECT count() > 0 FROM (
    EXPLAIN PLAN indexes = 1
    SELECT k FROM mt_i32 AS l RIGHT JOIN (SELECT 1::UInt32 AS k) AS r USING (k) WHERE k = 1
) WHERE explain ILIKE '%Condition: (k in [1, 1])%';

-- not delivered either: USING type == right input type
SELECT count() > 0 FROM (
    EXPLAIN PLAN indexes = 1
    SELECT k FROM mt_i32 AS l RIGHT JOIN (SELECT 1::Int64 AS k) AS r USING (k) WHERE k = 1
) WHERE explain ILIKE '%Condition: (k in [1, 1])%';

The mechanism matches your reading. cast_to_super (src/Planner/PlannerJoinsLogical.cpp:220-226) adds the cast plus an alias into changed_types and then returns the uncast argument, which is what lands in join_operator.expression. EXPLAIN PLAN shows this directly in the join condition: k = CAST(k AS Int64) when only the right side is cast (prunes), versus CAST(k AS Int64) = CAST(k AS Int64) when both are (does not prune). So substitutable in filterPushDown.cpp is handed the pre-cast column and its type comparison against the join output header fails on any side the supertype touched.

I have not pushed anything - this is @raimannma's branch. If a fix here is wanted from me rather than from him, say so and I will open a separate pull request referencing this one.

`buildEquialentSetsForJoinStepLogical` only keeps equi-key pairs whose two
sides have equal types, because those pairs feed a Union-Find equivalence
class. Plain column-name substitution does not need that, but it does need
two other things: the replacement must carry the type the replaced name has
in the `JOIN` output, because that is what the filter's nodes were typed
against, and it must evaluate to the value that output column holds, because
the filter's semantics are defined on that value.

The previous revision asked for both by demanding that the opposite side's
raw input column already have the `JOIN` output type. That only holds when
the `USING` supertype happens to equal the left input type, so an
`Int32` / `UInt32` key pair widened to `Int64`, or an `Int32` / `Int64` pair
whose supertype equals the right side, still left the left `MergeTree`
reading every granule.

Cast the replacement the way the `JOIN` casts that key instead: the two sides
are compared in their least supertype, so `CAST(<opposite side>, supertype)`
is exactly what is behind the `JOIN` output column. Requiring the `JOIN`
output type to be that supertype keeps the cast widening - a narrowing one
would change what the predicate returns - and still rejects a column the
`JOIN` altered for an unrelated reason, such as `join_use_nulls` widening it
to `Nullable`. The cast node is only materialized once a pushed-down filter
actually references it.

Reported by `clickhouse-gh` in
ClickHouse#103478 (comment)
and confirmed with measurements by @groeneai.
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 888a3bf8b with master 6c5b5aa32 (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 710.10 MiB 707.05 MiB -3.05 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.

Object file sizes

4 object files changed (+22.96 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/filterPushDown.cpp.o 315.04 KiB 337.97 KiB +22.94 KiB (+7.28%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator

Verified against the CI binary for 578e519d (GIT_HASH 94d63bd1, parents d09da182 + 578e519d). The current head has no build on S3 yet, but it is test-only over that commit and the add_replacement block is byte-identical, so it stands in for the pushdown behaviour. The test passes verbatim against its reference, and both rows you name do prune, 1/122 each.

Two things do not hold as written.

The direction described as still not delivered prunes under default settings. For

SELECT l.k FROM mt_i32 AS l RIGHT JOIN (SELECT 1::Int64 AS k) AS r ON l.k = r.k WHERE l.k = 1

the left MergeTree reads Granules: 1/122 with Condition: (k in [1, 1]), and the plan shows Type: inner. Isolating it (both settings default 1):

query_plan_convert_outer_join_to_inner_join enable_join_runtime_filters granules
0 0 122/122
1 0 1/122
0 1 122/122

A matched-type Int64/Int64 control behaves the same way, so this is query_plan_convert_outer_join_to_inner_join: a predicate on the left side makes unmatched rows unsatisfiable, the RIGHT JOIN becomes INNER, and ordinary pushdown applies. Your narrowing-CAST reasoning is intact and the substitution indeed does not fire there, but "the predicate stays above the JOIN" is not what happens. The three delivered cross-type cells prune with both of those optimizations off, so their pruning is unambiguously the substitution.

The assertion at that site cannot detect it. SELECT count() FROM (...) returns 1 with the conversion on and 1 with it off, so it passes either way; the granule form separates them (1/ vs not). That is the failure mode you flagged in the join_use_nulls thread, in the opposite direction.

One smaller thing: I reported three rows as not delivered, not two. The third is UInt32 left / Int32 right, the signedness mirror of the Int32/UInt32 cell. It prunes now as well, but it is unasserted, since mt_u32 appears only as the right input of the FULL JOIN. Whether that earns a line is your call.

#114919 is an ancestor of the head, so that red is genuinely carried in. It merged on 2026-08-18, not 2026-08-15, which changes nothing.

…mezone case with a test

There is no `JOIN` cast of the substituted key to reuse: the logical join
actions only keep the cast behind the `JOIN` output column, which converts
the opposite side, and the key matching casts are built later - also without
a context - by the conversion to the physical join. Nor can a context change
the conversion for any type pair that has a least supertype: the
context-dependent conversion settings concern parsing from `String` and
serialization to `String`, which never appear as a supertype cast, and
`createInternalCast` pins the date-time overflow behavior whether or not a
context is given. `session_timezone` acts through the query thread at
execution time, identically for the `JOIN` output column and the pushed-down
predicate. Documented at the cast site.

The new test pins the reviewed scenario: a `Date` key joined to a `DateTime`
key under `session_timezone = 'Pacific/Apia'` still prunes the left input
granules, keeps the matched row matched, and preserves the unmatched right
row. The test's `Date` range stays below 2106, where the unrelated
statistics-based part pruning defect of
ClickHouse#111759 takes over.

Co-Authored-By: Claude Fable 5 <[email protected]>
-- The opposite direction would need a narrowing `CAST`, which is not a substitution, so the predicate
-- stays above the `JOIN` and the wider key value survives it.
SELECT 'RIGHT JOIN ON, predicate on the wider side: no narrowing substitution';
SELECT count() FROM (

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 assertion does not actually pin the "no narrowing substitution" boundary it describes.

With the default query_plan_convert_outer_join_to_inner_join = 1, WHERE l.k = 1 makes this RIGHT JOIN unsatisfiable for unmatched right rows, so the optimizer can legally convert it to INNER and apply the ordinary left-side pushdown. In that shape the query still returns count() = 1 even when the narrowing-direction substitution is absent, so this test would keep passing if a later refactor broke the intended "predicate stays above the JOIN" invariant.

Please pin query_plan_convert_outer_join_to_inner_join = 0 here and assert on the plan (no Granules: 1/ / no pushed PK condition) instead of the final row count.

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.

tests/queries/0_stateless/04117_join_equi_key_filter_pushdown_right_full.sql:148 is still only checking count() = 1, so it does not distinguish "no narrowing substitution" from the ordinary RIGHT-to-INNER rewrite.

That rewrite is still enabled by default (src/Core/Settings.cpp:6718), it still runs after pushDownFilter (src/Processors/QueryPlan/Optimizations/Optimizations.h:244-246), and the optimizer revisits the node after a rewrite (src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:143-182). With WHERE l.k = 1, unmatched right rows are unsatisfiable once l.k is defaulted, so query_plan_convert_outer_join_to_inner_join can still fire and give the same final count() even if the narrowing-direction substitution never happens.

So the current test still does not pin the boundary described in the comment above it. It needs SET query_plan_convert_outer_join_to_inner_join = 0 and a plan assertion such as no Granules: 1/% / no pushed PK condition.

@fm4v
fm4v enabled auto-merge August 28, 2026 21:59
@fm4v
fm4v added this pull request to the merge queue Aug 29, 2026
Merged via the queue into ClickHouse:master with commit 9adeb11 Aug 29, 2026
177 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 29, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 29, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #103478 to 26.8: Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys
fm4v added a commit that referenced this pull request Aug 29, 2026
Backport #103478 to 26.6: Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #103478 to 26.7: Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
…t input of RIGHT JOIN for cross-type USING keys
pull Bot pushed a commit to stnxo2023/ClickHouse that referenced this pull request Sep 15, 2026
…shes

`tryPushDownOverJoinStep` substitutes the opposite side of a cross-type equi key into a predicate it
pushes below the join, and keeps that key's own name whenever it already carries the two sides' least
supertype, on the grounds that such a key is not cast by the join either.

That name is not unambiguous. `join_use_nulls` makes the join null-extend one side before the join and
alias the widened column back to the original name, so the expression DAG deliberately holds two nodes
called `__tableN.id` with different types: the pre-join input, and the post-join output action. The
pushed-down predicate's inputs are matched to the join's output actions by name alone, and merging the
two DAGs re-points the children of nodes that were already built. A `_CAST` in the predicate therefore
ended up with a `Nullable(UInt16)` child while keeping `result_type = UInt64`, and executing it raised
`LOGICAL_ERROR: Unexpected return type from _CAST. Expected UInt64. Got Nullable(UInt64)`. Release
builds return that to the client for a query with a well-defined answer; debug and sanitizer builds
abort, which is how it was found (`Stress test (arm_tsan)`).

Take the bare name only while it denotes a single type at that point in the plan, and otherwise fall
through to the uniquely named replacement this function already builds for the cast case. The sibling
equal-typed substitution above solves the same problem the same way, by renaming to
`__filterpushdown_src<name>`. The replacement's materializer now adds an alias rather than a cast when
the types already agree, so plans that need only the fresh name do not carry an identity `_CAST`.

`ActionsDAG::mergeInplace`'s name-based binding is left alone on purpose: its contract is name-based
and shared by many callers, so the ambiguous name is corrected where it is created rather than guarded
where it bites.

The substitution was added in ClickHouse#103478. My own ClickHouse#117973 lists this case under "Not fixed here" and leaves
the shortcut untouched.

Co-Authored-By: Claude Opus 5 <[email protected]>
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Sep 15, 2026
…INNER JOIN

A `WHERE` predicate on one join key of a plain `INNER JOIN` did not reach the
other table as an index condition when the two join keys had different types,
so that table was read in full. The same query with matching key types used the
other table's primary key. Results were always correct; only the plan lost the
condition. Reported in
ClickHouse#116395, whose body notes that
`INNER JOIN` behaves the same as the `RIGHT`/`LEFT` shape fixed in ClickHouse#103478.

`tryPushDownOverJoinStep` has exactly one producer of equi-key equivalence
entries for keys whose two sides differ in type, because the ordinary producer
`buildEquialentSetsForJoinStepLogical` needs equal input types for its
Union-Find. That producer was gated on at least one side being unavailable for
push-down, and a plain `INNER JOIN` clears neither availability flag: one flag
is cleared only for `JoinKind::Left`/`Right`, both only for `isAnyInnerJoin`
(`Inner` with strictness `Any`/`RightAny`, while a plain `INNER JOIN` has
`All`), and the right one only for ASOF and `JoinStepLogicalLookup`. So both
equivalence maps stayed empty for such keys,
`splitActionsForJOINFilterPushDown` had nothing to substitute, and the opposite
input was read with `Condition: true`. `ANY INNER JOIN` already worked,
precisely because clearing both flags turned the gate on, which means the
feature was granted to the more delicate kind and withheld from the simpler
one.

The gate was redundant rather than a soundness condition, so it is deleted.
Availability is already applied per map further down, where the equivalence
lists are built, so a pair registered for a side that cannot take the filter is
inert. Soundness comes from the per-substitution guard, which is untouched: it
requires the replaced name's JOIN output type to be the two keys' least
supertype, which rejects a narrowing cast and a column the join widened for an
unrelated reason such as `join_use_nulls`. A plain `INNER JOIN` emits a row
only where the two keys are equal in that supertype, so a predicate on one key
implies the same predicate on the cast of the other, and pushing it can only
drop rows that could not have survived the join.

Measured on 1M rows per side, `Date32` against `Date`, with the predicate on
the wider key: the other table goes from `Condition: true` and 122/122 granules
to the join's own `_CAST(b, 'Date32')` range and 1/122 granules, 1008282 rows
read down to 16471, identical result. Every other join kind is bit-identical
before and after, including `ANY`/`RightAny INNER`, `LEFT`, `RIGHT`, `LEFT`
converted to `INNER`, key pairs with no least supertype, and a predicate on the
narrower key.

Four arms are appended to
`04117_join_equi_key_filter_pushdown_right_full`: both cross-type key
orientations, an equal-type control, and a result assertion. They compare the
two granule counts of a read rather than matching a literal total, because a
total pins the part layout that CI randomizes; the side carrying the predicate
is ordered by `tuple()` so it can never prune, which is what identifies the
pruning read as the opposite input.

Co-Authored-By: Claude Opus 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-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.6-must-backport

Projects

None yet

8 participants