Skip to content

Do not select a join algorithm that ignores a mixed JOIN ON condition - #112831

Merged
nickitat merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-mixed-join-condition-algorithm-selection
Aug 4, 2026
Merged

nickitat merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-mixed-join-condition-algorithm-selection

Conversation

@groeneai

@groeneai groeneai commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixes wrong results for a JOIN whose ON clause carries a mixed condition, that is a cross-side non-equi residual such as ON (t1.key = t2.key) AND (t1.a * 10 < t2.a). Only the hash family evaluates such a condition, but full_sorting_merge, partial_merge and the direct key-value join claimed they could run these joins and then silently ignored the residual, returning extra rows. They now decline, so a hash algorithm is used instead.

Description

chooseJoinAlgorithm guards a mixed join condition by checking that a hash variant is merely enabled, but the selection loop then returns the first usable algorithm in the user's list order. Only the hash family evaluates such a condition, so FullSortingMergeJoin::isSupported, MergeJoin::isSupported and tryDirectJoin claim they can run a join they then mis-execute.

The result is silently wrong, with no error and no log line. join_algorithm = 'full_sorting_merge' correctly rejects such a query with NOT_IMPLEMENTED, while adding a hash variant still selects the merge algorithm and drops the residual:

-- t1 = ('k1',1),('k1',2),('k1',3)   t2 = ('k1',10),('k1',20)
SELECT count(), sum(t2.a) FROM t1 LEFT JOIN t2
ON (t1.key = t2.key) AND (t1.a * 10 < t2.a)
SETTINGS join_algorithm = 'full_sorting_merge,hash';  -- 6, 90 ; correct 3, 20

One carrier needs no unusual configuration: join_algorithm defaults to direct,parallel_hash,hash with direct first, so a LEFT ANY JOIN onto a dictionary drops the residual under stock settings.

This makes the predicates tell the truth: they decline when a mixed expression is present. The selection loop has no break, so a list containing a hash variant falls through to hash, and a list without one keeps today's NOT_IMPLEMENTED.

Joins without a mixed expression are unaffected: the merge path is still chosen for plain equi joins and for one-sided residuals, which are pushed down instead. This is performance-visible, since an affected query moves from merge to hash, but that set is exactly the queries returning wrong results today. A sweep of 228 join-related stateless tests shows no regressions. One shape gains an error instead of a correct answer: ASOF consumes only its closest-match inequality, so a second cross-side predicate becomes a mixed condition, and the hash path rejects a non-equi condition for ASOF strictness. Teaching these algorithms to apply the residual would be the natural follow-up.

Version info

  • Merged into: 26.8.1.753 (included in 26.8 and later)
  • Backported to: 26.7.4.15

groeneai and others added 3 commits July 31, 2026 04:26
A "mixed" join condition is a cross-side non-equi residual in the ON clause,
for example ON (t1.key = t2.key) AND (t1.a * 10 < t2.a). Only the hash family
evaluates it: HashJoin passes TableJoin::getMixedJoinExpression() into
AddedColumns::additional_filter_expression and applies it while matching.

chooseJoinAlgorithm guards this with a check that a hash variant is merely
ENABLED, but the selection loop then returns the first USABLE algorithm in the
user's list order. Nothing reconciles the two, and the capability predicates of
the non-hash algorithms never consult the mixed expression, so they claim they
can run a join they then mis-execute:

  * FullSortingMergeJoin::isSupported
  * MergeJoin::isSupported(TableJoin)
  * tryDirectJoin

The result is silently wrong: join_algorithm = 'full_sorting_merge' correctly
rejects such a query with NOT_IMPLEMENTED, while adding a hash variant to the
list ('full_sorting_merge,hash') satisfies the guard, still selects the merge
algorithm, drops the residual and returns extra rows. No error, no log line.

Three carriers need no unusual configuration at all. join_algorithm defaults to
'direct,parallel_hash,hash' with DIRECT first, so a LEFT ANY join onto a
dictionary silently drops the residual under stock settings. JoinSwitcher swaps
a MergeJoin in once the right side crosses max_rows_in_join, so the same query
changes its answer as the right table grows.

Make the predicates tell the truth: decline when a mixed expression is present.
The selection loop has no break, so a list containing a hash variant falls
through to hash, and a list without one keeps today's NOT_IMPLEMENTED. Gating
MergeJoin::isSupported also covers JoinSwitcher, which is only selected when
that predicate returns true, on both the new and the legacy analyzer.

Joins without a mixed expression are unaffected: the merge path is still chosen
for plain equi joins and for one-sided residuals, which are pushed down rather
than turned into a mixed expression.
Both rows exercised only the already-correct hash arm, so they were silent
about every predicate this branch changes.

The auto,hash row passed through the spilling branch of the AUTO arm of
tryCreateJoin, which is evaluated before the JoinSwitcher branch and returns
unconditionally, so the MergeJoin::isSupported guard was never consulted.
SpillingHashJoin delegates to a HashJoin, which honours the mixed condition, so
the row read the correct answer even without the guard. That branch is live
whenever JoinSettings::getMaxBytesBeforeExternalJoin returns non-zero, and
max_bytes_ratio_before_external_join defaults to 0.5, which yields a threshold
on any server with a memory limit; the test runner also randomizes the absolute
setting to a non-zero value half the time. Both settings are now pinned on that
statement. Measured on a capped server: unpinned reads the correct 3 20 with the
guard reverted, pinned reads 6 90, and the pin also survives the runner's
randomized draw.

The LEFT SEMI and LEFT ANTI rows requested full_sorting_merge,hash, but
FullSortingMergeJoin::isSupported rejects Semi and Anti on strictness before
reaching the mixed-condition guard. They are kept and relabelled as
must-not-regress rows for that pre-existing rejection, and three discriminating
rows are added on the algorithms that do admit these strictnesses: MergeJoin
admits Left plus Semi, and tryDirectJoin admits Left plus Semi and Left plus
Anti with direct first in the default list, so the two dictionary rows need no
non-default setting at all.

Each new expected value was derived from a CROSS JOIN oracle before measuring
and cross-checked against a same-shape hash control. Per-hunk attribution
confirms the split: reverting the MergeJoin guard reddens only the partial_merge
row, reverting the direct-join guard reddens only the two dictionary rows.

No source change. Tag-free 50 of 50 runs pass with randomization on.
Review round 2: rename the test pair to 04667 (04660 and the plan's 04662 were
both claimed while the fix was in review), add an ASOF LEFT row where a second
cross-side predicate survives ASOF's own inequality erasure and was therefore
dropped by the merge algorithm, and correct the FullSortingMergeJoin comment
which claimed the merge algorithm matches on equality keys only - it also
implements the ASOF closest-match comparison.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, 5 findings adjudicated)

An independent model reviewed this change cold in each round, without access to the
implementation notes. Verdicts below; every finding was verified against the source before being
accepted or rejected.

Round 3 (final)

Finding Verdict
💡 The three new capability comments use bare MergeJoinAlgorithm, MergeJoin, DirectKeyValueJoin and a bare ON, where the repository asks for literal class and SQL names in inline code blocks ❌ Agreed, fixed. All three comments now backtick the literal names. Not enforced by any style check, so it did not gate the change
⚠️ The description never mentioned that ASOF gains an error rather than a correct answer ❌ Agreed, fixed. The description now states it. Exactly two reachable shapes convert a silently wrong answer into INVALID_JOIN_ON_EXPRESSION, ASOF INNER and ASOF LEFT with a surviving cross-side predicate, because the hash path rejects a non-equi condition for ASOF strictness
💡 The stateless test number collides with an unpublished sibling branch ✅ Disagreed, no change. Test numbers are not unique in this repository: 2165 of 3678 numeric prefixes on master already carry more than one distinct test (04653 carries 11, 04648 carries 19). check_gaps_in_tests_numbers only rejects gaps of 100 or more and reports no gap either way, no other check enforces uniqueness, and the runner never keys on the number

Earlier rounds

Finding Verdict
⚠️ The ASOF shape was dismissed as a throw-on-both-sides coverage gap in two earlier rounds ❌ Agreed, and that dismissal was wrong. ASOF consumes only its own closest-match inequality, so a second cross-side predicate survives as a mixed condition that the merge algorithm then dropped: measured 3, 30 where honouring it gives 3, 20. The test now covers it, plus a plain ASOF control asserting the merge path is still chosen when no mixed condition is built
⚠️ The auto plus max_rows_in_join assertion did not reliably reach the JoinSwitcher path ❌ Agreed, fixed. The spilling branch is evaluated first and delegates to a hash join, and max_bytes_ratio_before_external_join defaults to 0.5, so both external-join settings are now pinned. Verified load-bearing: unpinned the pre-fix arm reads the correct value, pinned it reads the wrong one
⚠️ The SEMI and ANTI assertions never reached a changed guard ❌ Agreed, fixed. FullSortingMergeJoin declines those on strictness before reaching the new guard, so they exercised only the already-correct hash path. Three rows were added on algorithms that do admit them, two of which need no non-default setting at all, and the originals were kept as must-not-regress

Also verified and unchanged: the three declining algorithms never read the mixed condition, so
declining loses no capability; the selection loop has no break, so a list containing a hash
variant falls through to hash while a list without one keeps today's NOT_IMPLEMENTED; and the
guards are inert on the old analyzer, whose planner never builds a mixed condition.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One run of the shipped test against a pristine origin/master build fails on 11 rows plus the ASOF row, which succeeds where an error is expected. No randomization involved; the fixture is 3 + 2 rows in Memory tables.
b Root cause explained? Yes. chooseJoinAlgorithm gates a mixed join condition on a hash variant being merely ENABLED (PlannerJoins.cpp:1386-1393), while the selection loop (:1428-1439) returns the first USABLE algorithm in the user's list order, with no break and no preference for hash. SettingFieldMultiEnum preserves the written order, so 'full_sorting_merge,hash' passes the gate on HASH and then selects FULL_SORTING_MERGE, whose capability predicate never reads getMixedJoinExpression and which silently drops the residual.
c Fix matches root cause? Yes. The defect is a false capability claim, so the three predicates whose job is to answer "can I run this join?" now answer truthfully. No widened bound, no no-random-* tag, no reduced dataset, no guard at the mis-execution site. The gate's own message already states the intended contract; only its reachability was wrong.
d Test intent preserved / new tests added? Yes. New test pair 04667_mixed_join_condition_algorithm_selection, 44 statements of which 5 assert a server error and 39 emit a reference line. No existing test modified or weakened. The four NOT_IMPLEMENTED rejections and the five structural EXPLAIN PIPELINE rows are must-not-regress assertions; those rows assert which transform the pipeline contains rather than a value, because 6 / 90 is ambiguous.
e Both directions demonstrated? Yes, through the real runner with buildId() asserted against readelf -n on both arms, restarting the server per arm because a .sql test reaches whichever server is listening. Pre-fix (0da1aff10fd55194): FAIL in 7.25 s, 11 rows differ and the ASOF statement succeeds where error 403 is expected. Fixed (d152407c5ee95c3b): OK in 4.24 s. Per-hunk attribution built six single-hunk binaries in total; each reddens exactly its own rows. 15d6b0652b2344f1 with the MergeJoin guard reverted reddens only the partial_merge SEMI row, abecf4fae79aec7d with the direct-join guard reverted reddens only the two dictionary rows, and d6bb619c8d797ba2 with the FullSortingMergeJoin guard reverted returns the ASOF row to its dropped-residual value with MergeJoinTransform back in the pipeline.
f Fix is general across code paths? Yes. Every concrete IJoin audited in source. Reads the mixed expression and untouched: HashJoin, ConcurrentHashJoin, SpillingHashJoin, GraceHashJoin. Does not, and now declines: FullSortingMergeJoin, MergeJoin, DirectKeyValueJoin, JoinSwitcher. Safe by construction: PasteJoin (PASTE JOIN takes no ON) and ConstantJoin (selected before any equi/residual split). StorageJoin returns before the gate and is a separate known defect, deliberately not folded in. All consumers of the two fixed predicates enumerated; optimizeJoin.cpp uses the (kind, strictness) overload, which is unchanged. The legacy analyzer rejects these queries outright, so no legacy hunk is needed.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The predicate tests presence of an ExpressionActions pointer, not any type, so no wrapper stripping is required; verified empirically anyway. Nullable (6/90 to 3/20), LowCardinality (6 to 3), Const-folded (3/60 to 3/40), multi-key equi plus residual, and disjunctive ON all now agree with their hash control. Array was never a carrier (residual pushed down) and is unchanged in both arms. Kind and strictness matrix covers INNER, LEFT, RIGHT, FULL by ALL and ANY, plus SEMI, ANTI and ASOF. ASOF is a real carrier and is now covered: it consumes only the one closest-match inequality it needs, so a second cross-side predicate still becomes a mixed condition, and the merge algorithm used to match on the closest row while ignoring it.
h Backward compatible? Yes. No new setting, no default change, no serialization change, so no SettingsChangesHistory.cpp entry. The behaviour change is a wrong answer becoming a correct one, or the NOT_IMPLEMENTED error users already get when no hash variant is listed. The feature is already gated behind allow_experimental_join_condition.
i Invariants and contracts preserved? Yes. Invariant: an IJoin implementation that does not read TableJoin::getMixedJoinExpression must never be chosen for, or switched to, a join that has one. Each hunk is a single early return false / return {} inside a predicate, before any state is inspected or mutated, so it holds on every path including error and early-return. No locking, allocation, lifetime or concurrency contract is touched. FullSortingMergeJoin::checkTypesOfKeys calls the same predicate, so its throw stays consistent with selection.

Extra verification beyond the gate: a 228-test sweep of join-related stateless tests, both arms built from one worktree with only the three source files reverted, identical selection, gives 213 OK and 13 FAIL in BOTH arms with an empty set difference in both directions, so 0 regressions and 0 improvements and nothing passing by being absent. The 13 shared failures need infrastructure the sandbox lacks. A tag-free --test-runs 50 run is 50 OK and 0 FAIL; an earlier attempt was 35 OK and 15 FAIL, which correctly caught that two structural rows are perturbed by query_plan_optimize_join_order_randomize, a pre-existing effect that 108 in-tree tests already pin, so those rows now pin it too.

Two review rounds replaced rows that could not fail, which is worth stating because it is the same defect class twice. Round 1: the auto,hash row was passing through the spilling branch of the AUTO arm, which is evaluated before the JoinSwitcher guard and delegates to a hash join, so both external-join settings are now pinned on that one statement; and the two full_sorting_merge SEMI/ANTI rows are rejected on strictness before reaching the new guard, so they were relabelled as must-not-regress and three discriminating rows added on partial_merge and on a dictionary with no non-default setting at all. Round 2: the ASOF row's first residual, t1.a != t2.a, is trivially true on this fixture, so it returned the same value with and without the predicate; it is now t1.a * 10 != t2.a, which excludes the closest matching row and therefore reads 3 / 30 pre-fix against a hand-derived oracle of 3 / 20. The real check_gaps_in_tests_numbers predicate was driven over three arms (the shipped name, a baseline with the new test removed, and the tree merged with master) and reports no new gap in any of them. After every mutation arm, all three source md5s match their pre-mutation copies and the source diff against the commit is empty, so no mutation residue ships.

Session id: cron:clickhouse-review-slot-50:20260731-223400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @yakov-olkhovskiy, could you review this? chooseJoinAlgorithm admits a mixed JOIN ON condition whenever a hash variant is merely enabled, but the selection loop then picks the first usable algorithm in list order, so full_sorting_merge,hash selected the merge algorithm and silently dropped the residual; this makes the three non-hash capability predicates decline instead.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4b41802]

Summary: ✅


AI Review

Summary

This PR makes full_sorting_merge, partial_merge, and direct key-value joins decline mixed cross-table residuals in JOIN ON so the planner falls back to hash-based execution instead of returning silently wrong results, and it adds focused stateless coverage for the affected carriers, including the ASOF shape. I did not find remaining correctness or coverage gaps in the touched selection paths, constructor invariants, or the serialized JoinStepLogical path.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 24/27 (88.89%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.70% -0.10%

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

Full report · Diff report

@PedroTadim

Copy link
Copy Markdown
Member

cc @vdimir

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 88abb61

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / Logical error: Bad cast from type DB::ColumnNullable to DB::ColumnString (STID 5793-5883) trunk bug in mutation column-type recording #112501 (external, open)
same job / Server died the abort above terminated the debug server owned via #112501

Notes: both rows are one event, same job and same start time (13:34:47Z). The stack is
MergeTreeDataPartWriterOnDisk::initColumnsSubstreamsIfNeeded -> SerializationString::serializeBinaryBulkWithSizeStream
reached from MutateTask.cpp PartMergerWriter::mutateOriginalPartAndPrepareProjections, so it is
entirely inside the MergeTree mutation write path. This PR touches only
src/Interpreters/FullSortingMergeJoin.h, src/Interpreters/MergeJoin.cpp and
src/Planner/PlannerJoins.cpp plus its own test, none of which is on that path. The signature is
pre-existing on trunk: 4 hits with pull_request_number = 0 on master between 2026-07-29 and
2026-07-30, plus 8 unrelated pull requests in 30 days. #112501 records the storage column type when
a mutation rewrites the whole part, which is the exact cause of the stale-type-versus-new-data
mismatch that throws this cast; I verified rewritesAllPartColumns is absent from MutateTask.cpp
at this head, so the failing build predates that fix rather than failing with it applied.

Session id: cron:our-pr-ci-monitor:20260801-163000

@nickitat nickitat self-assigned this Aug 3, 2026
Comment thread src/Interpreters/FullSortingMergeJoin.h Outdated
if (!isMergeAlgorithmStrictnessAndKindSupported(table_join->kind(), table_join->strictness()))
return false;

/// MergeJoinAlgorithm never evaluates a mixed (cross-side non-equi) ON condition, so

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.

How about a stronger check (assert / logical error) that none of such conditions exist in case one of those algorithms was chosen. In other words, it would be better to fail loudly rather than drop conditions implicitly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 4b41802. I added a LOGICAL_ERROR to each of the three engines that cannot evaluate the condition, next to their existing unsupported-input checks: MergeJoinAlgorithm's constructor (MergeJoinTransform.cpp), MergeJoin's constructor, and DirectKeyValueJoin's constructor. Those are the points where TableJoin is still reachable and every construction path converges.

I checked that the post-fix reachable set is genuinely empty before encoding it as an invariant, since a LOGICAL_ERROR on a live path would be a user-visible regression:

  • The only writer of mixed_join_expression is JoinStepLogical.cpp:1291, which runs before chooseJoinAlgorithm at :1405, so the value is already final when each predicate is consulted.
  • Every construction site of the three engines is gated on the corresponding predicate: FullSortingMergeJoin at PlannerJoins.cpp:1262 and ExpressionAnalyzer.cpp:1082; MergeJoin at PlannerJoins.cpp:1193, ExpressionAnalyzer.cpp:1036, and JoinSwitcher.cpp:53 (whose two construction sites are themselves gated on MergeJoin::isSupported); DirectKeyValueJoin at PlannerJoins.cpp:1150 and ExpressionAnalyzer.cpp:1251.
  • The legacy analyzer never builds a mixed expression at all - it rejects such an ON condition earlier at CollectJoinOnKeysVisitor.cpp:150 with INVALID_JOIN_ON_EXPRESSION - so the checks cannot fire for legacy-analyzer queries.
  • The ASOF path is unaffected: MergeJoinAlgorithm keeps its asof_column, and a plain ASOF join carries no mixed expression, so the check sits before nothing it could pre-empt. The 04667 row pinning ASOF to the merge path still passes.

The checks are load-bearing rather than dead code. With the three predicate guards reverted and only these three checks kept, each fires on its own carrier: full_sorting_merge,hash hits the MergeJoinAlgorithm one, partial_merge,hash the MergeJoin one, and a dictionary LEFT ANY JOIN with no non-default setting the DirectKeyValueJoin one. Restoring the guards relinked bit-identically, so nothing from that arm ships.

Validation on the shipped commit: 04667 passes byte-identically against its reference, and a 199-test sweep of everything referencing join_algorithm or a merge/direct algorithm gives 186 pass / 11 fail, with all 11 failing identically on the pre-change baseline (they need ZooKeeper, shards, or parallel replicas that the sandbox lacks). check_cpp.sh is clean.

I also folded in the backticking of the literal class and SQL names in the three comments from the first commit.

Review follow-up: the predicate-only fix relies on every capability predicate
staying truthful. This bug class is exactly predicates lying - three of them
independently accepted a mixed condition and then ignored it - and a new
consumer of those same predicates is being added elsewhere, so an invariant at
the consuming end does not have to be re-established per predicate.

Add a LOGICAL_ERROR to the three engines that cannot evaluate a mixed
(cross-side non-equi) ON condition, next to their existing unsupported-input
checks:

  - MergeJoinAlgorithm (the engine behind full_sorting_merge)
  - MergeJoin (partial_merge, and the JoinSwitcher spill path)
  - DirectKeyValueJoin (direct, first in the default join_algorithm list)

Post-fix the reachable set is empty. The single writer of mixed_join_expression
runs before algorithm selection, so the value is already final when each
predicate is consulted; every construction site of these three engines is
gated on the corresponding predicate; and the legacy analyzer rejects such an
ON condition earlier, in CollectJoinOnKeysVisitor. Verified load-bearing rather
than dead: with the three predicate guards reverted and only these checks kept,
each one fires on its own carrier.

Also wrap the literal class and SQL names in the three comments added by the
previous commit in inline code blocks, per the repo convention.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4b41802

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Join is supported only for pipelines with one output port, got 3 and 1 (STID 4488-4e11) Logical error thrown at QueryPipelineBuilder.cpp:374 in joinPipelinesYShaped, reached from JoinStep::updatePipeline; the YShaped merge-join fallback requires exactly one stream per side. Exact frame-for-frame match with the fixing PR's root cause. Not caused by this diff: 15+ distinct PRs in 30 days. #109393 (mine, open)
Build (arm_release) / Post Hooks build_profile_hook telemetry INSERT rejected with LogCluster query failed with code 500; job-level status is success (the hook carries allow_failure). 816 rows / 284 distinct PRs / 463 master hits in 7 days. a fix task is created (investigating at full effort - fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260804-043000

alexey-milovidov pushed a commit to BoloniniD/ClickHouse that referenced this pull request Aug 9, 2026
…for a dictionary

A mixed join condition is a cross-side non-equi residual in the `ON` clause, for example
`ON (t.key = d.key) AND (t.a * 10 < d.a)`. Only the hash family evaluates one: `HashJoin`
passes `TableJoin::getMixedJoinExpression` into `AddedColumns::additional_filter_expression`
and applies it while matching, resolving the right columns it needs by name against the
stored right blocks.

`buildPhysicalJoinImpl` drops the `join_use_nulls` conversion of the right columns from the
right-side expression when the right side is a prepared storage, because such a storage
delivers its columns already converted, and for a key-value storage it merges the conversion
back into the right-side DAG under the original column names. But `DirectKeyValueJoin`
declines a mixed condition, so a join onto a dictionary that carries one runs an ordinary
algorithm which reads the dictionary as a stream - and is handed a right side whose `a` is
`Nullable(UInt32)` under the very name the mixed condition declared as `UInt32`.
`buildAdditionalFilter` creates the column from the declared type and fills it with
`insertFrom` from the stored one, so a `ColumnUInt32` was filled from a `ColumnNullable`: an
aborted assertion under sanitizers, and arbitrary matching in a release build.

    CREATE TABLE dsrc (key UInt64, a UInt32) ENGINE = Memory;
    INSERT INTO dsrc VALUES (1, 100), (2, 20);
    CREATE DICTIONARY dict (key UInt64, a UInt32) PRIMARY KEY key
        SOURCE(CLICKHOUSE(TABLE 'dsrc')) LIFETIME(0) LAYOUT(FLAT());
    CREATE TABLE t (key UInt64, a UInt32) ENGINE = Memory;
    INSERT INTO t VALUES (1, 1), (2, 2), (3, 3);

    SELECT count(), sum(d.a) FROM t LEFT ANY JOIN dict AS d
        ON (t.key = d.key) AND (t.a * 10 < d.a)
    SETTINGS allow_experimental_join_condition = 1, join_use_nulls = 1, join_algorithm = 'hash';

Only key 1 satisfies the residual, so the answer is `3, 100`; the release build returned
`3, 120`, having matched key 2 as well.

Keep the conversion in the right-side expression when a key-value storage carries a mixed
condition, so the join applies `join_use_nulls` itself exactly as it does for an ordinary
table and the mixed condition keeps the non-`Nullable` columns it was built on. `StorageJoin`
is unaffected: it rejects a mixed condition outright with `INCOMPATIBLE_TYPE_OF_JOIN`.

Also compare the type and not only the name when `HashJoin` resolves the right columns the
mixed condition needs, so a future divergence throws where both types are still known instead
of reading a column through a mismatched `IColumn` interface.

The shape has been reachable with an explicit `join_algorithm = 'hash'` for as long as the
mixed condition and the prepared-storage handling have coexisted. ClickHouse#112831 made
`DirectKeyValueJoin` decline a mixed condition, which put it on the default `join_algorithm`
path and into the new `04667_mixed_join_condition_algorithm_selection` test, and the assertion
started firing in most stress runs from 2026-08-04 (STID 2508-30f6 and 2508-2e0c, which differ
only by the concurrent-hash-join wrapper in the stack).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=0f1b923e6247ef3d8409635a69738c7f3f02b84a&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_tsan%29
Related: ClickHouse#112831

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 10, 2026
Backport #112831 to 26.7: Do not select a join algorithm that ignores a mixed JOIN ON condition
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 20, 2026
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-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.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants