Skip to content

Fix NOT_IMPLEMENTED for outer JOIN with full_sorting_merge when the compare chain derives a bound the join evaluates on its preserved side - #126170

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-compare-chain-outer-join-multi-table-preserved-keys
Oct 17, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-compare-chain-outer-join-multi-table-preserved-keys

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125291
Related: #124233

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed outer JOIN with join_algorithm = 'full_sorting_merge' failing with NOT_IMPLEMENTED when optimize_and_compare_chain derived a bound from ON that the join evaluates on its preserved side: for a key over several tables (for example a.number + b.number after an inner join, a FULL JOIN ... USING key, an ARRAY JOIN alias combined with a column, or a key with a lambda), for a bound derived within the other side (from r.a < r.b AND r.b < 2), and, with optimize_redundant_comparisons = 0, for a derived bound that contradicts another one or cannot hold for the column type.

Description

On 26.8.18.2, SELECT a.number, c.number FROM numbers(3) AS a INNER JOIN numbers(3) AS b ON a.number = b.number LEFT JOIN numbers(3) AS c ON a.number + b.number = c.number AND c.number < 2 SETTINGS join_algorithm = 'full_sorting_merge' fails with NOT_IMPLEMENTED; with optimize_and_compare_chain = 0 it returns three rows. Master still fails after #124233.

The compare chain appends the derived a.number + b.number < 2 to ON. It reads only the preserved side, so it cannot be pushed down, and full_sorting_merge refuses a single-side ON filter. #124233 skips such bounds, but tests getExpressionSource(expr).first, which is nullptr for a key over several tables. The same happens for a FULL JOIN ... USING key, an ARRAY JOIN alias plus a column, keys with lambdas or indexHint, a column-less key, evaluated with the left side, and keys whose other-side columns the join folds away (multiIf(1, 0, r.k), IN []). The chain's own indexHint(r.a < 2) for a bound within the other side reads no input either. The ALWAYS_FALSE branch appended a preserved-side contradiction unchecked, and a skipped bound was still recorded, so l.number < 2 (skipped) then l.number > 5 got appended; with optimize_redundant_comparisons = 0 nothing folds it.

Change: a bound is preserved-side when it reads any column of the preserved side (folding can drop the others; lambda captures count, indexHint arguments do not) or none, and it is derived only when ON already has a conjunct on that expression, to expose contradictions. No indexHint bound is added to an outer ON. A preserved-side bound that cannot hold for the type (UInt8 > 300) no longer folds ON to false; the rows are the same.

Validation: fourteen rows and two EXPLAIN rows in 05331_and_compare_chain_outer_join_on; thirteen fail on master and pass with the fix; 50 randomized runs pass.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.128-master (included in 26.11 and later)

groeneai and others added 5 commits October 15, 2026 21:49
…e keys

With `optimize_and_compare_chain`, the chain derives `expr op const` from
`expr = y AND y < 2` and appends it to the `AND`. In an outer join `ON` a
conjunct over the preserved side cannot be pushed down, so it stays in `ON`
and `full_sorting_merge` rejects the join with `NOT_IMPLEMENTED`.

ClickHouse#124233 guarded this with `getExpressionSource(expr).first`, which is
`nullptr` for an expression over several table expressions, so the guard
missed `a.number + b.number` over an inner join, the `firstNonDefault` key
of `FULL JOIN ... USING`, and an `ARRAY JOIN` alias mixed with a column.
Test every column's source against the preserved tables instead.

The `ALWAYS_FALSE` branch also appended a preserved-side contradiction
unguarded. A bound the guard skipped was still recorded, so a later bound
on the same expression conflicted with it (`l.number < 2` skipped, then
`l.number > 5` appended), and a type-impossible bound (`UInt8 > 300`) was
appended on its own; with `optimize_redundant_comparisons = 0` nothing
folds them and the join is rejected. Derive a preserved-side bound only
when the user already wrote a conjunct on that expression: the derivation
then still exposes a contradiction the next pass folds to `false`, and
that `ON` already holds a preserved-side conjunct of the user's.

Closes ClickHouse#125291

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he preserved side

The planner skips lambdas when it splits `ON` by side, but the check
rejected them as an unknown node, so a lambda key such as
`arraySum(x -> x * 2, a.arr) + b.number` still got its bound appended.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ds only the preserved side

The join's side split reads the columns a lambda captures, so a key like
`arraySum(x -> x + a.number + b.number, [0])` reads only the preserved side and its derived
bound must not be appended to ON. Lambda arguments are skipped, as they are not table columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The join evaluates a conjunct without table columns with its left side, the
preserved side of LEFT and FULL joins, so a derived `materialize(0) < 2` must
not be appended to ON. For a RIGHT JOIN this only skips a bound the user's ON
already implies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…und in outer JOIN ON

The planner builds `indexHint` with no inputs, so the join evaluates it, and
any conjunct whose columns sit only under it, with its left side: the
preserved side of LEFT and FULL joins, which full_sorting_merge refuses.

- `readsOnlyPreservedJoinTables` counted the columns under `indexHint`, so
  `l.number + indexHint(r.number < 2) < 2` was taken as reading the other side
  and appended. It now skips `indexHint` arguments.
- The `indexHint` wrapper the pass adds for a bound derived within one source
  became a left pre-filter even when the bound reads only the other side
  (`r.a < r.b AND r.b < 2` -> `indexHint(r.a < 2)`). It is no longer added
  inside an outer join ON. For a RIGHT join this also drops a hint the join
  could push to the left input; the derived bound is implied by the user's ON
  there, so the rows never change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Reviewed heads afd38c11c6967 (round 1), 9920c2792e6d (round 2), cfff70187547 (round 3), cb7f3300b74b (round 4) and 76ba5854063a (round 5, no findings).

Finding Verdict
❌ A preserved-side key containing a lambda (arraySum(x -> x, a.arr) + b.number) was still classified as not preserved, so its derived bound reached ON and full_sorting_merge failed with NOT_IMPLEMENTED. AGREE, fixed: lambda arguments are skipped; test row added.
❌ A lambda that reads the preserved side only through captured columns (arraySum(x -> x + a.number + b.number, [0])) still got its bound appended: the join splits ON by the inputs of each conjunct, which include captured columns. AGREE, fixed: the check looks inside lambda bodies and counts captured columns; test row added.
❌ A column-less key (materialize(1) < r.number AND r.number < 2) still got its bound appended: the join evaluates a conjunct with no inputs with its left side, the preserved side of a LEFT JOIN. AGREE, fixed: a column-less key counts as preserved; test row added.
❌ A preserved-side key with indexHint (l.number + indexHint(r.number < 2)) was classified as not preserved, although the join reads no column under indexHint, so its bound reached ON. AGREE, fixed: indexHint arguments are skipped; test row added.
❌ The indexHint wrapper the chain adds for a bound within the other side (r.a < r.b AND r.b < 2) reads no input, so the join evaluated it with its left side, the preserved side of a LEFT JOIN. AGREE, fixed: no indexHint bound is added to an outer ON; test row added.
⚠️ The impossible bound row only asserts rows, so reverting the guard would go unnoticed. DISAGREE: the row runs with optimize_redundant_comparisons = 0, where nothing folds the appended bound; reverting the guard makes it fail with NOT_IMPLEMENTED (measured on a mutant and on master).
💡 One reproducer row cannot tell a match from a miss for its first key (both print 0). Noted, not changed: it is the issue's own reproducer and still fails on master; the new rows use a distinguishing value.
💡 No indexHint bound is added anywhere inside an outer ON now, also where it was harmless: a RIGHT JOIN chain within the left side (the left input is not preserved there), and subqueries nested in the ON. Noted, not changed: rows are unchanged, only a derived index hint is lost in these shapes; keeping it needs join-kind and subquery-scope tracking in the visitor.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local -n --ignore-error --queries-file 05331_and_compare_chain_outer_join_on.sql: on master the ten new outer-join rows fail with Code: 48 NOT_IMPLEMENTED on every run. Shape A also fails on release 26.8.18.2.
b Root cause explained? The compare chain appends a derived expr op const to ON; a bound that reads only the preserved side stays in ON, and full_sorting_merge refuses single-side ON filters. The #124233 check uses getExpressionSource(expr).first, nullptr for an expression over several tables, and the ALWAYS_FALSE branch appended preserved-side contradictions unchecked (a skipped bound was still recorded).
c Fix matches root cause? Yes. The preserved-side test now checks every column's source, and the record/append decision is made before the bound is recorded. No tags, no widened bounds.
d Test intent preserved / new tests added? Eleven execution rows and one EXPLAIN row added to 05331_and_compare_chain_outer_join_on. Five mutants of the fix each redden at least one new row, and every row added during review fails on the head before it.
e Both directions demonstrated? Yes. Master build: ten rows NOT_IMPLEMENTED. Fix build: all rows match the reference; 50/50 randomized runs pass.
f Fix is general across code paths? Both append sites in tryOptimizeAndCompareChain (plain and ALWAYS_FALSE) are covered, and the indexHint wrapper is no longer added to an outer ON. The other rewrites in the pass only change an operand's own expression and add no new side.
g Fix generalizes across inputs (params/datatypes/wrappers)? Covered shapes: multi-table key over an inner join, FULL JOIN ... USING key, ARRAY JOIN alias plus column, a key with a lambda, a lambda that reads the preserved side only through captured columns, a column-less key (materialize(0)), a key with indexHint, a bound derived within the other side, comma and CROSS JOIN preserved side, a type-impossible bound, a contradiction through a skipped bound; full_sorting_merge, parallel_full_sorting_merge, hash; optimize_redundant_comparisons 0 and 1. Mixed-side keys are unchanged.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. The chain only adds fewer preserved-side bounds; one ON that a type-impossible bound used to fold to false is no longer folded, with the same rows.
i Invariants and contracts preserved? Every conjunct the chain adds is still implied by the user's ON; the fix only adds fewer. Chain propagation through preserved nodes to the other side is unchanged. Outside an outer ON the new check returns early, so WHERE, INNER and SEMI behave as before.

Session id: cron:clickhouse-impl-slot-4:20261015-213200

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e2974b7]

Summary: ✅


AI Review

Summary

This PR fixes outer JOIN failures with full_sorting_merge by preventing comparison-chain inference from introducing filters evaluated on the preserved input, including expressions spanning multiple tables, lambda captures, and folded dependencies. Reviewed head: e2974b7701f9dfafa852cb4fc74a1c7a8e9b091e. Both prior findings are addressed; no outstanding findings remain. The 05331_and_compare_chain_outer_join_on regression matches its reference on the PR's CI binary, and six focused cases return identical results with inference enabled and disabled.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @yakov-olkhovskiy, could you review this and add the can be tested label (I cannot add it right now, so CI has not started)? The #124233 guard looked up a single source for the derived bound, so keys over several tables, USING, ARRAY JOIN, lambda or indexHint keys still put a preserved-side filter into ON; the check now looks at every column the join reads, and no indexHint bound goes into an outer ON.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 16, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 16, 2026
…IN ON

When the join builds its ActionsDAG it folds `x IN <set>` to a constant once the
constant set turns out empty (`FunctionIn::getConstantResultForNonConstArguments`),
and with it every expression the folded value feeds, e.g. `AND`. The folded node
loses its children, so `l.number + (r.k IN [])` reads only the preserved side, and
a bound derived over it is a left pre-filter that `full_sorting_merge` refuses with
NOT_IMPLEMENTED. The query tree cannot tell whether the set will be empty: `[]`,
`()`, `(NULL)` and `(-1)` for an unsigned key all fold. So a key holding an `IN`
over a constant set now counts as preserved, which costs only the derived bound
for such keys. The walk no longer stops at the first column of another table,
because the `IN` can sit after it, as in `(r.k IN []) AND r.k > 0`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… in outer JOIN ON

The join's ActionsDAG folds calls the query tree still holds unfolded, e.g. the
`if(1, 0, r.k)` that `multiIf` rewriting leaves, an `IN` over an empty constant
set, or `and(0, ...)` over them, and a folded node loses its inputs. So the key
`l.number + multiIf(1, 0, r.k)` reads only the preserved side in the join, and the
bound derived over it becomes a left pre-filter that `full_sorting_merge` refuses
with NOT_IMPLEMENTED. Folding only drops inputs, so any key with a column of the
preserved side may end up there, and it now counts as preserved. A bound over a
mixed key gains nothing anyway: it can't leave ON, and `full_sorting_merge` rejects
mixed conditions. This subsumes the special case for `IN` over a constant set,
which is removed.

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

clickhouse-gh Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e2974b770 with master e0e91b052 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e5791b213; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

1045 object files changed (-2.75 MiB total), 4 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/TypeFunctions.cpp.o new 1.00 MiB +1.00 MiB
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 25.56 MiB 26.43 MiB +895.89 KiB (+3.42%)
src/CMakeFiles/dbms.dir/DataTypes/TypeMatchers.cpp.o new 692.78 KiB +692.78 KiB
src/CMakeFiles/dbms.dir/DataTypes/FunctionSignature.cpp.o new 417.14 KiB +417.14 KiB
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayDotProduct.cpp.o 1.75 MiB 1.55 MiB -201.52 KiB (-11.24%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl2.cpp.o 1.31 MiB 1.14 MiB -174.78 KiB (-13.07%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsBitmap.cpp.o 2.58 MiB 2.41 MiB -167.40 KiB (-6.35%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl1.cpp.o 1.12 MiB 986.07 KiB -160.78 KiB (-14.02%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/vectorFunctions.cpp.o 3.29 MiB 3.43 MiB +148.59 KiB (+4.41%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayCumSumNonNegative.cpp.o 603.16 KiB 466.82 KiB -136.34 KiB (-22.60%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayCumSum.cpp.o 673.15 KiB 538.16 KiB -134.99 KiB (-20.05%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayAggregation.cpp.o 1.29 MiB 1.16 MiB -134.86 KiB (-10.22%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsCodingIP.cpp.o 1.27 MiB 1.13 MiB -133.67 KiB (-10.32%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayDifference.cpp.o 592.61 KiB 478.04 KiB -114.56 KiB (-19.33%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsJSON.cpp.o 4.26 MiB 4.37 MiB +111.80 KiB (+2.57%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsHashingMisc.cpp.o 5.53 MiB 5.61 MiB +83.25 KiB (+1.47%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayDistance.cpp.o 10.19 MiB 10.11 MiB -78.98 KiB (-0.76%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsConversion_reg.cpp.o 6.83 MiB 6.75 MiB -78.39 KiB (-1.12%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl3.cpp.o 1.87 MiB 1.80 MiB -76.37 KiB (-3.98%)
src/CMakeFiles/dbms.dir/Functions/IFunction.cpp.o 555.11 KiB 631.16 KiB +76.05 KiB (+13.70%)

719 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

2854 translation units recompiled, 15964 s compile time in total, 2849 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 8.2 s
  • src/DataTypes/TypeFunctions.cpp: 6.4 s

Job report

@alexey-milovidov alexey-milovidov self-assigned this Oct 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 17, 2026
Merged via the queue into ClickHouse:master with commit b0b9080 Oct 17, 2026
179 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 17, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The RIGHT JOIN ON / subquery pruning loss reported in #126541 is fixed in #126551; a backport of this PR would need that one too.

alexey-milovidov pushed a commit to bacek/ClickHouse that referenced this pull request Oct 19, 2026
…s of an outer JOIN ON

ClickHouse#126170 stopped adding the within-one-source `indexHint` bound anywhere
inside an outer JOIN ON, gated on `preserved_join_tables.empty()`. The
reason for that gate is that the planner evaluates an input-less ON
conjunct with the join's left side (`concatConditions` and
`canBeEvaluatedOnSide` in JoinStepLogical.cpp), so for LEFT/FULL the hint
stays in the join and `full_sorting_merge` refuses it.

The proxy was too coarse: for RIGHT JOIN the left side is not preserved
and the hint becomes a left pre-filter (`canPushDownFromOn`), as for
INNER JOIN; and `needChildVisit` kept the outer join's state while
visiting a subquery nested in ON, which is a separate query. Both lost
primary key pruning (Granules 64/64 instead of 1/64 on the issue's
table); results were unaffected.

Track whether the current join's left side is preserved and gate the hint
on that, and visit a QueryNode/UnionNode child with the join state
cleared. LEFT/FULL keep dropping the hint, so the ClickHouse#126170 case stays
fixed. RIGHT [ALL|ANY|ANTI|SEMI] JOIN with every join algorithm gives the
same rows and refusals with the chain on and off.

Closes ClickHouse#126541

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #126170 to 26.10: Fix `NOT_IMPLEMENTED` for outer `JOIN` with `full_sorting_merge` when the compare chain derives a bound the join evaluates on its preserved side
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…h `full_sorting_merge` when the compare chain derives a bound the join evaluates on its preserved side
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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Outer JOIN ON guard misses preserved-side keys spanning several tables

6 participants