Repository navigation
Conversation
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]>
# Conflicts: # src/Processors/QueryPlan/Optimizations/filterPushDown.cpp
|
Workflow [PR], commit [888a3bf] Summary: ✅
AI ReviewSummaryThis PR extends analyzer-side Findings
Missing context / blind spots
Final VerdictLLVM Coverage ReportMeasured on commit 888a3bf.
Changed lines: Changed C/C++ lines covered: 88/92 (95.65%) · Uncovered code |
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.
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
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.
…-filter-pushdown-right-full
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]>
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]>
…-filter-pushdown-right-full
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 34/34 (100.00%) · Uncovered code |
@groeneai could you confirm this and create a repro? |
|
@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:
Your The refinement: the surviving case is not "the Repro, self-contained ( 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. 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. |
…ilter-pushdown-right-full
`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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes4 object files changed (+22.96 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline. |
|
Verified against the CI binary for 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 = 1the left
A matched-type The assertion at that site cannot detect it. One smaller thing: I reported three rows as not delivered, not two. The third is
|
…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 ( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
… RIGHT JOIN for cross-type USING keys
Backport #103478 to 26.8: Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys
Backport #103478 to 26.6: Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys
… RIGHT JOIN for cross-type USING keys
Backport #103478 to 26.7: Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys
…t input of RIGHT JOIN for cross-type USING keys
…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]>
…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]>
Related: #103038
For
RIGHT JOINwith aWHEREpredicate on aUSINGcolumn whose two sides have different types, the predicate was not used as a primary-key index condition on the left input, so the leftMergeTreeread every granule.buildEquialentSetsForJoinStepLogicalonly 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 theJOINoutput, 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
JOINcasts that key. The two sides are compared in their least supertype, soCAST(<opposite side>, supertype)is exactly what is behind theJOINoutput column. Requiring theJOINoutput type to be that supertype keeps the cast widening - a narrowing one would change what the predicate returns - and still rejects a column theJOINaltered for an unrelated reason, such asjoin_use_nullswidening it toNullable. The cast node is only materialized once a pushed-down filter actually references it.Reproducer from the issue:
Measured on 10M rows, before and after on the same data:
Granules read on the left
MergeTreeforRIGHT 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:USINGtypeUInt64UInt8UInt64(== left)Int64UInt32Int64(== left)Int32Int64Int64(== right)Int32UInt32Int64(wider than both)UInt32Int32Int64(wider than both)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
RIGHTandFULL JOIN, and covers both planners; this pull request only fixesRIGHT JOINunderenable_analyzer = 1.FULL JOINis not fixed, for the reasons below, and the test keeps its cases as result-only regression guards.The legacy
JoinSteppath (enable_analyzer = 0) is not fixed either. There, aUSINGkey is renamed to<table>.<key>in the right input header while theJOINoutput keeps the bare name, soequivalent_columns_to_push_downholds 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 theJOIN-output type guard that path lacks entirely, which is the guard #98167 had to add forjoin_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
JOINoutput carries, so the predicate stays above theJOIN.An earlier revision of this pull request also enabled the push-down for
FULL JOINand generalisedRIGHT/LEFT JOINfromSemistrictness to any strictness. Both were unsound and have been reverted.The reasoning behind them was that the top-level
WHEREstays above theJOINand removes any row that slips through the duplicated per-side filter. It does not:tryPushDownOverJoinStepreplaces theFilterStepwith anExpressionSteponce every conjunction has been pushed, and conjunctions routed throughequivalent_columns_to_push_downare pushed to both sides and never land inrejected_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
JOINthen 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:SEMIemits only matched rows, which is why the original restriction was there.FULL JOIN, bothSemirestrictions and both equivalence branches are now identical tomaster, and the03036_join_filter_push_down_equivalent_setsreference no longer needs the rewrite an earlier revision gave it.The test covers the granule pruning for
RIGHT JOINacross the key-type pairs above and keeps the wrong-result cases as regression guards.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Push a
WHEREcondition on aUSINGcolumn through aRIGHT JOINso the leftMergeTreeinput can use it as a primary-key index condition, also when the two join keys have different types. Applies whenenable_analyzer = 1.Workflow [PR]
Sync PR [sync-upstream/pr/103478]
Version info
26.9.1.314(included in26.9and later)26.8.1.2032,26.7.6.41,26.6.4.45