Repository navigation
Do not treat a non-Nullable CAST as null-propagating in the join order optimizer - #119512
Conversation
…r optimizer isNullPropagatingFunction in optimizeJoin.cpp decided null propagation from the function name alone and listed CAST / _CAST unconditionally. For a cast that is a property of the target type, not of the name: casting NULL to a non-Nullable type raises CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN instead of returning NULL. So strictOnRelations reported a relation as "evaluates to NULL when all of R's columns are NULL" where the runtime actually raises. That claim flows through predicateNullRejectingRelations to cda_nr_rels (gated by trust_null_rejection = join_use_nulls) to ConflictJoinOp::nr_rels, where a set bit turns a null-rejection-dependent assoc matrix entry from a conflict into a permitted reordering. Observable effect, with join_use_nulls = 1 and the LEFT/LEFT shape t1 LEFT JOIN t2 ON t1.a = t2.a LEFT JOIN t3 ON CAST(t2.k AS Int64) = t3.k: every configuration raises Code 349 except dpsub with conflict detector A or C, which reassociate into t1 LEFT JOIN (t2 LEFT JOIN t3) and thereby skip the throwing evaluation. This is a consistency hardening rather than a bug fix: there is no wrong result in either direction, because a non-Nullable cast never yields a value that could make a null-extended row match, and both experimental settings default to false while the default solver is greedy, so nothing reads nr_rels in a default build. The gate uses isNullableOrLowCardinalityNullable(node.result_type), which is the same predicate ClickHouse#119305 adds on FunctionConvert / ExecutableFunctionCast, so the analysis and the runtime agree by construction. Once that PR lands, the cast branch here can delegate to IFunction::isNullPropagating. Only CAST is gated on its result type: the INPUT leaf and the comparison and arithmetic names must not be, because under join_use_nulls = 1 a non-Nullable base column becomes Nullable in the join output while the DAG node keeps its pre-join type, so gating those would drop relations that are correctly reported today. The new test asserts the Join/Read plan skeleton per arm at query_plan_optimize_join_order_limit > 0, since the reordering under test is only reachable with dpsub plus a conflict detector. It carries two non-vacuity controls: a CAST(... AS Nullable(Int64)) arm that must still reassociate, which reddens if every cast is rejected instead of only the non-Nullable ones, and a plain-predicate arm proving the detector is what moves the plan. It asserts the plan rather than the exception because coupling a test to error preservation across plan shapes would assert a guarantee ClickHouse does not make. It is also the first stateless coverage of the trust_null_rejection = true branch, as no existing test combines a conflict detector with join_use_nulls = 1. Requested by @ m-selmi at ClickHouse#119305 (comment) Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review (1 round, 2 findings, both dismissed with evidence)
💡 💡 Also dismissed: changing |
|
cc @KochetovNicolai @vdimir, could you review this? The join reorderer classified null propagation by function name and listed |
|
Workflow [PR], commit [d6784f0] Summary: ✅
AI ReviewSummaryThis PR narrows the join-order optimizer's null-rejection inference so non- Final Verdict✅ No new findings on the current head. LLVM Coverage ReportMeasured on commit d6784f0.
Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code |
…n test A review comment asked for the predicate to be widened from isNullableOrLowCardinalityNullable to canContainNull, so that a cast to Variant or Dynamic keeps contributing to strictOnRelations. Measured, that widening is unsound: a Variant or Dynamic join key matches NULL to NULL (an INNER JOIN with one NULL key per side returns the NULL-NULL pair, where a Nullable(Int64) key returns nothing), so an equality over such a key does not reject a null-extended row and carries no null-rejection for the reorderer, even though the cast itself returns NULL on NULL input. The same distinction is already drawn for these two families by hasIEJoinIncompatibleComparison in JoinStepLogical.cpp. Built the proposed predicate to confirm the direction: with canContainNull the LEFT/LEFT pair reassociates under CD-A and the null-extended row loses its match through t3's NULL key, which is the result master produces today because it accepts every cast unconditionally. The shipped predicate keeps the plan and the result unchanged. So this adds the arms that pin it rather than the widening: a Variant-keyed fixture whose CD-A and reordering-off results must agree. The arms pass here and fail on master, so they redden if the predicate is ever widened to canContainNull. Also state the Variant/Dynamic property in the comment at the predicate, which previously justified only the non-Nullable case. 50/50 runs with randomization on; style 14/15 (local-only settings_changes_history fail-closed branch).
The previous wording claimed that only the `Nullable` wrappers reject a null-extended row in this analysis. That is the rule this predicate applies to a cast, but it is not enforced for every operand shape: a direct `Variant` equality key reaches `strictOnRelations` as an input and still contributes its relation, which is a separate defect on the same invariant and is not in the scope of this change. Say only what the predicate decides.
…-order CAST test The two cast-int64 arms read the Join/Read skeleton of the plan. That pins the reorderer's decision but not the behaviour the decision exists to keep: a change that preserved the left-deep shape and stopped evaluating the raising cast on the null-extended row would leave both arms green. So assert the executed query as well, expecting CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN with reordering off and under each conflict detector. Measured on the PR's base binary and on this branch: arm base this branch limit = 0 Code: 349 Code: 349 greedy, limit = 10 Code: 349 Code: 349 dpsub + detector A 2 9 9 Code: 349 dpsub + detector C 2 9 9 Code: 349 The reordering-off arm is the reference rather than an assertion of its own: the exception is pre-existing there, so the two detector arms assert agreement with the unoptimized query, not a newly expected error. Base returns rows for both, so they redden without the change. This corrects the reasoning given with the first commit, that asserting the exception would pin a guarantee ClickHouse does not make. Error preservation across arbitrary plan shapes is indeed not guaranteed, which is why the over-approximation was reported as a hardening rather than a soundness bug; but these arms do not claim it. With the settings pinned they claim only that the reorderer must not take this one reassociation, and the reordering-off arm is what supplies the expected behaviour they compare against. 50/50 runs with randomization on, 50 passed; style 14/15 (local-only settings_changes_history fail-closed branch). Requested at ClickHouse#119512 (comment) Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 20 s compile time in total, 7 of them have a recent master baseline. |
The join-order conflict detectors relax the assoc/asscom reordering rules when
the ON condition rejects nulls on the null-supplying relation. That premise
requires an unmatched outer-join row to be padded with a top-level SQL NULL.
optimizeJoin.cpp already checks exactly that, but only at setting granularity
(join_use_nulls, via the trust_null_rejection flag), never per column, so the
INPUT/PLACEHOLDER leaf of strictOnRelations claimed null-rejection for every key
type.
Two padding routes defeat it:
- Array, Map, Variant, Dynamic and AggregateFunction have
canBeInsideNullable() == false, so JoinCommon::convertTypeToNullable returns
the type unchanged, silently, and the padding is a plain insertDefault: []
for Array, map() for Map. A default-valued key matches another
default-valued key.
- Variant and Dynamic do pad with Null(), but as a
ColumnVariant::NULL_DISCRIMINATOR, and extractNestedColumnsAndNullMap only
inspects ColumnNullable, so the value stays an ordinary hash key and matches
another internal NULL. JoinUtils.cpp documents the same failure mode for a
NULL nested inside a Tuple.
Either way the ON condition rejects nothing, the reassociation DPsub licenses
through nr_rels is invalid, and rows are lost.
Gate the leaf on isNullableOrLowCardinalityNullable(t) ||
JoinCommon::canBecomeNullable(t), which is
isNullableOrLowCardinalityNullable(convertTypeToNullable(t)) written without
allocating. Reusing the executor's own decision procedure, the one TableJoin
uses to pick the padding, is the point: the analysis and the execution cannot
drift apart. The predicate deliberately differs from the CAST-node gate in
ClickHouse#119512, which uses isNullableOrLowCardinalityNullable alone. For a computed
value the type IS the value's type, but for a leaf the outer join has yet to
convert it, so the question is whether the operand will be NULL-carrying AFTER
the conversion. canContainNull is wrong in both places because it admits Variant
and Dynamic.
The change only ever removes bits from nr_rels, so it cannot admit a reordering
that was previously rejected, and it is unreachable unless join_use_nulls = 1
and the 'dpsub' solver runs with a conflict detector enabled, all off by
default.
Wrappable-but-unwrapped key types (Int64, Tuple, LowCardinality(String), JSON,
QBit, Interval) never reach this leaf: their ON condition carries a
toNullable/CAST wrapper, which makes JoinStepLogical::typeChangingSides()
non-empty and keeps that child join out of the reorderable graph. That is why
the defect looks type-specific, and why a Nullable(Int64) key is the right
non-vacuity control in the new test.
The test asserts the ON condition of each join step, root first, rather than the
Join/Read step sequence: query_plan_join_swap_table is randomized and swaps the
printed order of a join's two children without changing the association, which
made a step-sequence oracle fail on an unchanged plan.
The same oracle also pins CD-C against the Nullable control key, not only CD-A.
Plain DPsub cannot reassociate a LeftOuter/LeftOuter pair at all (measured: with
no detector, both the dpsub and the greedy solver leave k = k at the root), so
a = a at the root additionally witnesses that the detector is engaged. Without
that arm a silent CD-C fallback, or an over-restriction reaching CD-C alone,
would keep the file green behind the CD-A arms.
Co-Authored-By: Claude Opus 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Related: #119305
Requested by @ m-selmi at #119305 (comment)
isNullPropagatingFunctioninoptimizeJoin.cppdecided null propagation from the function name,listing
CAST/_CASTunconditionally. For a cast it is a property of the target type: castingNULLto a non-Nullabletype raisesCANNOT_INSERT_NULL_IN_ORDINARY_COLUMNinstead of returningNULL, sostrictOnRelationsreported a relation as null-rejected where the runtime raises and theDPsub conflict detectors reassociated on that basis. This gates the two cast
names on
isNullableOrLowCardinalityNullable(node.result_type), the predicate #119305 adds onFunctionConvert/ExecutableFunctionCast, so the two agree by construction.All columns
Nullable(Int64),t1(a) = {1,2},t2(a,k) = {(1,10)},t3(k) = {10}:'dpsub'+..._use_conflict_detector_a = 11 10 10/2 \N \NCode: 349'dpsub'+..._use_conflict_detector_c = 11 10 10/2 \N \NCode: 349Code: 349Code: 349A hardening for the cast above; a correctness fix for one other shape. For an
Int64target aquery that returned rows now raises
Code: 349. A target that padswith a matchable value gave a wrong result: with
t3.k Variant(Int64)holding a NULL key,CAST(t2.k AS Variant(Int64)) = t3.kloses that match under CD-A before and keeps it after. AVariant/Dynamicjoin key matches NULL to NULL, so a cast to one carries no null-rejection;hence
isNullableOrLowCardinalityNullable, notcanContainNull. Both detectors default off, withgreedythe default solver.The new test pins the Join/Read plan skeleton per arm at
..._join_order_limit > 0, with twonon-vacuity controls, two
Variant-keyed result arms that must agree, and executed arms expectingCANNOT_INSERT_NULL_IN_ORDINARY_COLUMNwith reordering off and under each detector. Five arms failon master. First stateless coverage of
trust_null_rejection = true; 50/50 with randomization on;14 neighbour tests unchanged.
Query plans, before and after (click to expand)
'dpsub'+..._use_conflict_detector_a = 1, before. The cast counts as null-propagating, so thepair is reassociated and the raising evaluation is skipped:
After this change, identical to the
..._join_order_limit = 0plan:The analyzer nests the cast as
_CAST(CAST(t2.k, 'Int64'), 'Nullable(Int64)'). The outer alignmentcast is
Nullableand still passes; recursion descends into the inner non-Nullablecast, which isnow rejected, and that is what stops
t2from being contributed.Workflow [PR]
Sync PR [sync-upstream/pr/119512]