Skip to content

Do not treat a non-Nullable CAST as null-propagating in the join order optimizer - #119512

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/optimizejoin-cast-null-propagation-result-type
Sep 12, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/optimizejoin-cast-null-propagation-result-type

Conversation

@groeneai

@groeneai groeneai commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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)

isNullPropagatingFunction in optimizeJoin.cpp decided null propagation from the function name,
listing CAST / _CAST unconditionally. For a cast it is a property of the target type: casting
NULL to a non-Nullable type raises CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN instead of returning
NULL, so strictOnRelations reported a relation as null-rejected where the runtime raises and the
DPsub conflict detectors reassociated on that basis. This gates the two cast
names on isNullableOrLowCardinalityNullable(node.result_type), the predicate #119305 adds on
FunctionConvert / ExecutableFunctionCast, so the two agree by construction.

All columns Nullable(Int64), t1(a) = {1,2}, t2(a,k) = {(1,10)}, t3(k) = {10}:

SELECT t1.a, t2.k, t3.k FROM t1 LEFT JOIN t2 ON t1.a = t2.a
LEFT JOIN t3 ON CAST(t2.k AS Int64) = t3.k ORDER BY ALL SETTINGS join_use_nulls = 1;
added settings before after
'dpsub' + ..._use_conflict_detector_a = 1 1 10 10 / 2 \N \N Code: 349
'dpsub' + ..._use_conflict_detector_c = 1 1 10 10 / 2 \N \N Code: 349
anything else (defaults included) Code: 349 Code: 349

A hardening for the cast above; a correctness fix for one other shape. For an Int64 target a
query that returned rows now raises Code: 349. A target that pads
with a matchable value gave a wrong result: with t3.k Variant(Int64) holding a NULL key,
CAST(t2.k AS Variant(Int64)) = t3.k loses that match under CD-A before and keeps it after. A
Variant / Dynamic join key matches NULL to NULL, so a cast to one carries no null-rejection;
hence isNullableOrLowCardinalityNullable, not canContainNull. Both detectors default off, with
greedy the default solver.

The new test pins the Join/Read plan skeleton per arm at ..._join_order_limit > 0, with two
non-vacuity controls, two Variant-keyed result arms that must agree, and executed arms expecting
CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN with reordering off and under each detector. Five arms fail
on 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 the
pair is reassociated and the raising evaluation is skipped:

└──Join (JOIN FillRightFirst)
   │  t1[2] ⟕ (t2[1] ⟕ t3[1])
   │  Join conditions: a = a
   ├──ReadFromMergeTree (t1)
   └──Join (JOIN FillRightFirst)
      │  t2[1] ⟕ t3[1]
      │  Join conditions: CAST(CAST(k AS Int64) AS Nullable(Int64)) = k
      ├──ReadFromMergeTree (t2)
      └──ReadFromMergeTree (t3)

After this change, identical to the ..._join_order_limit = 0 plan:

└──Join (JOIN FillRightFirst)
   │  t1[2] ⟕ t2[1] ⟕ t3[1]
   │  Join conditions: CAST(CAST(k AS Int64) AS Nullable(Int64)) = k
   ├──Join (JOIN FillRightFirst)
   │  │  t1[2] ⟕ t2[1]
   │  │  Join conditions: a = a
   │  ├──ReadFromMergeTree (t1)
   │  └──ReadFromMergeTree (t2)
   └──ReadFromMergeTree (t3)

The analyzer nests the cast as _CAST(CAST(t2.k, 'Int64'), 'Nullable(Int64)'). The outer alignment
cast is Nullable and still passes; recursion descends into the inner non-Nullable cast, which is
now rejected, and that is what stops t2 from being contributed.


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

…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 round, 2 findings, both dismissed with evidence)

⚠️ CAST to Dynamic is rejected by the new gate although Dynamic can hold NULL - suggested
switching to canContainNull. Not adopted. A join key of Dynamic type is refused by the planner
outright (PlannerJoins.cpp, TableJoin.cpp: "JOIN on keys with Dynamic type is not supported ...
you should cast it to any other type"
), and allow_dynamic_type_in_join_keys is off by default and
documented as not recommended, so the reassociation is unreachable. Rejecting a node is also the
conservative direction: nr_rels is read only inside the constraint-relaxing tests in assocHolds /
lAsscomHolds / rAsscomHolds, so clearing a bit can only remove a reordering, never add one.
canContainNull would additionally diverge from isNullableOrLowCardinalityNullable, the predicate
#119305 adds on FunctionConvert / ExecutableFunctionCast, which is the agreement this PR exists
to establish.

💡 Related: must be a full GitHub URL - agreed and fixed in the description.

💡 Also dismissed: changing @ m-selmi to a live mention in the body (deliberate, to avoid a second
notification on top of the thread reply), and pinning query_plan_join_swap_table /
enable_parallel_replicas in the new test. On the latter I checked CIDB before dismissing it:
03836_tpch_join_order_plans pins full plan text with 102 ReadFromMergeTree lines and has zero
failures in 30 days over 819 runs of the ParallelReplicas arm and 935 of the distributed plan
arm.

@clickhouse-gh clickhouse-gh Bot closed this Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @vdimir, could you review this? The join reorderer classified null propagation by function name and listed CAST / _CAST unconditionally, but a cast to a non-Nullable type raises CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN rather than returning NULL, so the DPsub conflict detectors were given a null-rejection claim the runtime does not honour. This gates the two cast names on the result type instead. Requested by @ m-selmi on #119305.

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d6784f0]

Summary: ✅


AI Review

Summary

This PR narrows the join-order optimizer's null-rejection inference so non-Nullable CAST / _CAST no longer count as null-propagating for the conflict detectors. I reviewed the current head, the full changed logic in optimizeJoin.cpp, the new stateless coverage, the prior inline discussion, and the current CI state; I did not find any remaining blockers or majors.

Final Verdict

✅ No new findings on the current head.

LLVM Coverage Report

Measured on commit d6784f0.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Sep 11, 2026
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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.

Compile time of recompiled translation units

7 translation units recompiled, 20 s compile time in total, 7 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov left a comment

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.

Nice.

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit 5a73f82 Sep 12, 2026
174 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 Sep 12, 2026
protomn pushed a commit to protomn/ClickHouse that referenced this pull request Sep 12, 2026
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]>
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-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants