Repository navigation
Conversation
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]>
Internal second-model review (3 rounds, 5 findings adjudicated)An independent model reviewed this change cold in each round, without access to the Round 3 (final)
Earlier rounds
Also verified and unchanged: the three declining algorithms never read the mixed condition, so |
Pre-PR validation gate (click to expand)
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 Two review rounds replaced rows that could not fail, which is worth stating because it is the same defect class twice. Round 1: the Session id: cron:clickhouse-review-slot-50:20260731-223400 |
|
cc @nickitat @yakov-olkhovskiy, could you review this? |
|
Workflow [PR], commit [4b41802] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 24/27 (88.89%) · Uncovered code |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code |
|
cc @vdimir |
CI finish ledger - 88abb61Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Notes: both rows are one event, same job and same start time (13:34:47Z). The stack is Session id: cron:our-pr-ci-monitor:20260801-163000 |
| if (!isMergeAlgorithmStrictnessAndKindSupported(table_join->kind(), table_join->strictness())) | ||
| return false; | ||
|
|
||
| /// MergeJoinAlgorithm never evaluates a mixed (cross-side non-equi) ON condition, so |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_expressionisJoinStepLogical.cpp:1291, which runs beforechooseJoinAlgorithmat: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:
FullSortingMergeJoinatPlannerJoins.cpp:1262andExpressionAnalyzer.cpp:1082;MergeJoinatPlannerJoins.cpp:1193,ExpressionAnalyzer.cpp:1036, andJoinSwitcher.cpp:53(whose two construction sites are themselves gated onMergeJoin::isSupported);DirectKeyValueJoinatPlannerJoins.cpp:1150andExpressionAnalyzer.cpp:1251. - The legacy analyzer never builds a mixed expression at all - it rejects such an
ONcondition earlier atCollectJoinOnKeysVisitor.cpp:150withINVALID_JOIN_ON_EXPRESSION- so the checks cannot fire for legacy-analyzer queries. - The
ASOFpath is unaffected:MergeJoinAlgorithmkeeps itsasof_column, and a plainASOFjoin carries no mixed expression, so the check sits before nothing it could pre-empt. The04667row pinningASOFto 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.
CI finish ledger - 4b41802Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260804-043000 |
a336b18
…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]>
Backport #112831 to 26.7: Do not select a join algorithm that ignores a mixed JOIN ON condition
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes wrong results for a
JOINwhoseONclause carries a mixed condition, that is a cross-side non-equi residual such asON (t1.key = t2.key) AND (t1.a * 10 < t2.a). Only the hash family evaluates such a condition, butfull_sorting_merge,partial_mergeand 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
chooseJoinAlgorithmguards 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, soFullSortingMergeJoin::isSupported,MergeJoin::isSupportedandtryDirectJoinclaim 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 withNOT_IMPLEMENTED, while adding a hash variant still selects the merge algorithm and drops the residual:One carrier needs no unusual configuration:
join_algorithmdefaults todirect,parallel_hash,hashwithdirectfirst, so aLEFT ANY JOINonto 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'sNOT_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:
ASOFconsumes only its closest-match inequality, so a second cross-side predicate becomes a mixed condition, and the hash path rejects a non-equi condition forASOFstrictness. Teaching these algorithms to apply the residual would be the natural follow-up.Version info
26.8.1.753(included in26.8and later)26.7.4.15