Skip to content

Make the result nullability of arrayIntersect follow its declared return type - #117577

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-array-intersect-nullable-argument-mix
Sep 2, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-array-intersect-nullable-argument-mix

Conversation

@groeneai

@groeneai groeneai commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #114587

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 arrayIntersect when only some of its arguments are Nullable. Such a call could fail with Unexpected return type from arrayIntersect over Array(Nullable(Date32)) and Array(Date32), return a spurious default-valued element for UUID, IPv4, IPv6, Time, Time64, Interval, JSON and QBit, or fail with Unexpected value 0 in enum for Enum8 and Enum16. An intersection that has a not Nullable argument cannot contain NULL, so the result now follows the declared return type; arrayUnion and arraySymmetricDifference are not affected.

Description

getReturnTypeImpl declares Array(getMostSubtype(nested_types, true)), which is Nullable only when every argument is. executeImpl separately computes the cast target with force_support_conversion = true, which makes it Nullable as soon as one argument is. castColumns preserves each argument's own nullability only for the types in a hand-written list (numbers, Date, DateTime, DateTime64, String/FixedString); every other type is cast to that common type, so all arguments become Nullable. execute then derived the result's nullability from those cast arguments, wrapping the result in ColumnNullable although the declared type was not Nullable, and emitting a NULL the intersection cannot contain.

The fix records the declared nullability once on UnpackedArrays and uses it for the wrap, the null-map flag and the NULL-emission gate. No cast is changed, no type list extended and no type check loosened, so every affected nested type is covered at once, not only the reported one.

Hence two symptoms. Date32 has its own dispatch branch, so the mismatch surfaces as an exception; the other types take the generic branch, where castRemoveNullable strips the wrap and discards the null map, so the emitted NULL silently becomes a default-valued element instead. Both are reachable on the ordinary execution path, not only under constant folding.

Found by FunctionsStress in Unit tests (tsan, function_prop_fuzzer): report. Validated in both directions from a deterministic one-query repro and over 23 nested types in both argument positions: exactly the 14 defective probes change, across 11 nested types, and every control is byte-identical. #114587 is a different defect in the same function and stays untouched: this change alters no cast and no overflow mask.


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


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

Version info

  • Merged into: 26.9.1.523 (included in 26.9 and later)

…eturn type

`getReturnTypeImpl` declares `Array(getMostSubtype(nested_types, true))`, which is
`Nullable` only when every argument is. `executeImpl` separately computes the cast
target as `getMostSubtype(data_types, true, force_support_conversion = true)`, and
that third flag makes the common type `Nullable` as soon as one argument is.
`castColumns` preserves each argument's own nullability only for the types in a
hand-written list (`isNumber`, `isDate`, `isDateTime`, `isDateTime64`,
`isStringOrFixedString`); every other nested type is cast to that common type, so
all arguments become `Nullable`. `execute` then derived `all_nullable` from those
cast arguments and used it for the `ColumnNullable` wrap, the `use_null_map` flag
and the `NULL`-emission gate. For an intersection with some-but-not-all `Nullable`
arguments that produced a `Nullable` column against a not `Nullable` declaration,
and emitted a `NULL` that an intersection with a not `Nullable` argument cannot
contain.

Record the declared nullability once on `UnpackedArrays` and use it at those sites
instead. No cast is changed, no type list extended and no type check loosened, so
this covers every affected nested type at once rather than only the one that was
reported.

There are two symptoms, because `castRemoveNullable` discards the null map when it
strips a wrap. `Date32` has its own dispatch branch and never reaches that stripper,
so the mismatch surfaces as an `Unexpected return type from arrayIntersect`
exception, thrown from any of the six `columnMatchesType` guards
(`Analyzer/Utils.cpp`, `resolveFunction.cpp`, `ColumnFunction.cpp`, `ActionsDAG.cpp`
twice, `ExpressionActions.cpp`). `UUID`, `IPv4`, `IPv6`, `Time`, `Time64`,
`Interval`, `JSON` and `QBit` take the generic branch, where the stripper hides the
mismatch and the emitted `NULL` silently becomes a default-valued element; for
`Enum8` and `Enum16` that element is not a valid enum value, so it throws
`Unexpected value 0 in enum` instead.

`arrayUnion` and `arraySymmetricDifference` declare `getLeastSupertype`, which is
`Nullable` exactly when the cast makes all arguments `Nullable`, so their declared
nullability and the old derivation always agreed. They are unaffected, and measured
unchanged across the whole type matrix.

Introduced by 3ba2d11, which added the `isDate32` dispatch branch without
adding `isDate32` to the `castColumns` list.

Found by `FunctionsStress` in `Unit tests (tsan, function_prop_fuzzer)`. Validated
in both directions from a deterministic single-query repro and over 23 nested types
in both argument positions, with and without an actual `NULL`: exactly the 14
defective probes change, across 11 nested types, and every control is byte-identical.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Round 1 of an independent cold review plus a second-model gate, adjudicated against the recorded
validation. Kept here for the record; nothing below needs action from a reviewer.

Blocker raised and refuted

❌ arrayIntersect becomes order-dependent when every argument is typed Nullable but only some
contain a NULL: disagreed, with evidence. The observation is real but pre-existing, and this
change provably does not touch it. Renaming the removed all_nullable and the new
nullable_result to one identifier makes the parent commit and this commit byte-identical at
every read site of the flag, including the per-element reset the finding cites; the only
differences are where the flag gets its value and the deleted derivation. In the scenario named,
every argument's nested type is DataTypeNullable, so getMostSubtype declares a Nullable
result and every cast argument carries a null map, so both flags are true and the two revisions
behave identically. It is also outside what this change claims: the fix is scoped to calls where
only some arguments are Nullable, and there the declared type is not Nullable. The proposed
remedy would change results for existing all-Nullable callers, which needs its own decision and
its own entry.

Agreed and fixed

⚠️ The new comment claimed that the arguments are cast to a Nullable common type as soon as one
argument is Nullable. That is not true of the hand-written-list branch, which preserves each
argument's own nullability, which is exactly why numbers, Date, DateTime, DateTime64,
String and FixedString are not affected. Reworded, since as written it invited a future reader
to widen the cast list back into the bug.

⚠️ The regression test did not pin the reproducer that was reported: the reported query has an
empty first argument, and the swapped argument order was also a measured defect. Both added.

⚠️ A countable claim was wrong: the type matrix changes 14 probes over 11 nested types, not 12.
Corrected here and in the commit message.

Notes, not blocking

💡 The overflow-mask guard in the same function tests isInteger on a still-Nullable type
(#114587). A different defect; this change alters no cast and no mask, so it is left alone.

💡 arrayUnion and arraySymmetricDifference share every line of the execution loop, so they were
checked rather than assumed. They declare getLeastSupertype, which is Nullable exactly when the
cast makes all arguments Nullable, so the declared value and the removed derivation always agreed.
The one shape that looks like a counterexample is not one: getLeastSupertype can return
LowCardinality(Nullable(T)), whose isNullable() is false, but prepareArrays takes a null map
only from a ColumnNullable and a ColumnLowCardinality is not one, so the removed derivation was
already false there as well. Measured unchanged across the whole matrix, LowCardinality rows
included.

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6ed4ec7]

Summary: ✅


AI Review

Summary

This PR makes arrayIntersect derive its result nullability from the declared return type instead of the post-cast argument columns, which fixes the mixed-Nullable cases where Date32 raised an exception and several generic types could emit a spurious default-valued element. I did not find a new correctness or regression issue in the current diff, and the new stateless test covers both the fast-path exception case and the generic wrong-result case.

Missing context / blind spots
  • ⚠️ The full CI matrix for commit 6ed4ec7d575666433c32dfd6b69790340dc67953 was still in progress while I reviewed. Style check and Fast test were green, but completed build/stateless coverage would close the remaining validation gap.
Final Verdict

✅ No review findings.

LLVM Coverage Report

⚠️ No coverage measurement for commit 6ed4ec7: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

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

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One query, no randomization: SELECT arrayIntersect(CAST([toDate32('2000-01-01')] AS Array(Nullable(Date32))), [toDate32('2000-01-01')]); fails every time before the fix. The reported fuzzer query (ARRAY JOIN over Array(Array(Date32))) reproduces too. Note a LOGICAL_ERROR in clickhouse local prints nothing without --logger.console=1.
b Root cause explained? Yes. getReturnTypeImpl declares getMostSubtype(nested_types, true), Nullable only if every argument is; executeImpl recomputes the cast target with force_support_conversion = true, Nullable if one is; castColumns preserves per-argument nullability only for a hand-written type list, casting all other types to that Nullable common type; execute then derived the result nullability from those cast arguments, so it wrapped in ColumnNullable against a not Nullable declaration and emitted a NULL the intersection cannot contain.
c Fix matches root cause? Yes. The violated contract is the declaration, so the result nullability is taken from the declared return type. No cast changed, no type list extended, no type check loosened. Rejected: adding isDate32 to the list (fixes only the reported symptom, leaves the silent-wrong-results sibling); wrapping the fast branches in castRemoveNullable (converts a caught error into the same wrong result).
d Test intent preserved / new tests added? Yes. New SQL test 05055_array_intersect_nullable_argument_mix, 6 SELECTs, one per scenario, no existing test touched or weakened. It pins the reported reproducer (an empty Array(Nullable(Date32)) first argument) and the swapped argument order. Two complementary mutations prove every line load-bearing: restoring the old derivation reddens lines 1-4 and leaves 5-6 green; forcing the new flag to false reddens lines 5-6 and leaves 1-4 green.
e Both directions demonstrated? Yes. Date32: exception -> ['2000-01-01']. UUID with NULL in the first argument: ['00000000-0000-0000-0000-000000000000'] -> []. Both shown on clickhouse local and on a running server whose buildId() was asserted against the binary's ELF Build-ID.
f Fix is general across code paths? Yes. The fix keys on the declaration rather than on a type, so all 11 measured carriers and any nullable-capable type added later are covered by the same assignment. All 11 result-producing carriers enumerated and each measured (14 changed probe rows: Date32 x4, ten other types x1). arrayIntersect.cpp is the only function-level getMostSubtype caller (JoinUtils.cpp is join-key conversion, no result-nullability decision), so no sibling function carries this idiom.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 23 nested types x both argument positions x empty/non-empty x with/without an actual NULL x all three modes. Carriers fixed: Date32, UUID, IPv4, IPv6, Enum8, Enum16, Time, Time64, Interval, JSON, QBit. Unchanged: numbers, Date, DateTime, DateTime64, Decimal, String, FixedString, LowCardinality(Nullable(T)), and every arrayUnion/arraySymmetricDifference row. Not constructible: Array/Map nested (canBeInsideNullable is false), Tuple (getMostSubtype rejects the mixed pair with NO_COMMON_TYPE). Boundaries covered: 0000-01-01, 9999-12-31, empty arrays, 3 arguments.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default, no serialization format, so no SettingsChangesHistory.cpp change. Behaviour changes only for the mixed-nullability intersection shapes, from an exception or a spurious element to the correct intersection; nothing that previously returned a correct result moves.
i Invariants and contracts preserved? Yes. Restored invariant: the nullability of the column executeImpl returns equals the nullability getReturnTypeImpl declared. When the flag is true, every cast argument still carries a null map, so nothing downstream loses a guarantee; null_map and the result column stay the same length on every path because the wrap and the null-map flag now read the same value. When it is false while an argument does carry a null map, that argument's NULLs are filtered out of both the map and the lookups, which is the correct semantics. has_nullable is untouched for arrayUnion/arraySymmetricDifference. No lock, allocation or error path changed.

Session id: cron:clickhouse-impl-slot-6:20260901-173800, cron:clickhouse-impl-slot-5:20260901-191600

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @george-larionov @KochetovNicolai, could you review this? arrayIntersect derived its result nullability from the cast arguments rather than from its declared return type, so with some-but-not-all Nullable arguments it returned a Nullable column against a not Nullable declaration: a logical error for Date32, and a silent spurious default-valued element for the types whose null map castRemoveNullable discards. It now reads the declared type, which covers every affected nested type at once without changing any cast.

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6ed4ec7d5 with master fc9bebf58 (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, 10 s compile time in total, 7 of them have a recent master baseline.

Job report

Picks up ClickHouse#117580, which repairs the bugfix-validation master-build S3 lookup.
Without it `Bugfix validation (functional tests, amd64/aarch64)` aborts before
running any test and reds the Workflow Post Hook.
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c5e46b7

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
Bugfix validation (functional tests, amd64), Bugfix validation (functional tests, aarch64), Finish Workflow / Post Hooks harness abort before any test ran: AssertionError: Could not find master builds in S3 at ci/jobs/functional_tests.py:734. Master build artifacts moved under a normalized workflow-name prefix, so find_master_builds probes the old key and matches nothing. new_tests_check.py then reds the post hook because neither per-arch arm reported a result. This is not the inverted-semantics pass either: check_status is failure, not success or skipped. My diff touches no ci/ file #117580 (external, merged 2026-09-01T22:06:23Z), rule 3c: absent from the tree that ran (probed at the failing head with both controls firing). Picked it up by merging master, pushed as 6ed4ec7d575666433c32dfd6b69790340dc67953, so CI re-runs with the fix

The rest of the run is green: 148 of 170 check runs success, no other failure, no cancellation, Style check 0/15 failures, Config Workflow success.

Session id: cron:our-pr-ci-monitor:20260902-023000

@PedroTadim PedroTadim self-assigned this Sep 2, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Sep 2, 2026
Merged via the queue into ClickHouse:master with commit b305d8c Sep 2, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 2, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 8, 2026
…sk tests

castColumns narrows every argument to the most subtype of the element types, so
a wider argument can be truncated (257 to 1 as UInt8). prepareArrays stops the
truncated values from matching by building an overflow mask: it re-compares the
cast column against the original with notEquals and skips every element where
they differ. The mask is built only for integer-like element types.

Both element types feeding that test came from

    typeid_cast<const DataTypeArray &>(*removeNullable(<arg>.type)).getNestedType()

where removeNullable strips the wrapper off the array type, which is never
Nullable here so it is a no-op, and not off the element type. For
Array(Nullable(UInt16)) the element type therefore stayed Nullable(UInt16),
WhichDataType reported TypeIndex::Nullable, and isInteger, isDate, isDateTime
and isDateTime64 all returned false. The whole mask block was skipped and
arrayIntersect([toNullable(1)], [toNullable(257)]) returned [1] while the not
Nullable spelling arrayIntersect([1], [257]) has always returned [].

The condition reads the initial argument's type, so the guard was lost only
when the overflowing argument was itself Array(Nullable(...)); one Nullable
argument on the non-overflowing side left it working.

Stripping Nullable at the single declaration site fixes all four arms at once
and covers Array(LowCardinality(Nullable(T))) too, since IExecutableFunction
materializes a nested LowCardinality away before executeImpl runs. Both types
are stripped, not only the ones in the condition: arg.nested_column and
initial_column are already unwrapped out of ColumnNullable above, so leaving
the types Nullable makes each ColumnWithTypeAndName describe a column it does
not hold, which reaches columnGetNested via defaultImplementationForNulls and
throws ILLEGAL_COLUMN. That variant was built and measured rather than assumed.

The same shape already exists in this function, where castColumns feeds
isNumber/isDate/isDateTime/isDateTime64/isStringOrFixedString from
removeNullable(type_nested). No cast, result type, type list or NULL handling
changes.

arrayUnion and arraySymmetricDifference share prepareArrays, and there the
strip also removes an error. Their common element type comes from
getLeastSupertype, so it is Nullable as soon as one argument is, and a not
Nullable argument of a different width is cast to Array(Nullable(T)) while its
own initial column stays unwrapped. Pre-fix the guard therefore saw a plain
initial element type, fired, and handed callFunctionNotEquals a still Nullable
cast type against that unwrapped column: arrayUnion([1], [toNullable(257)])
and arraySymmetricDifference([1], [toNullable(257)]) failed with
ILLEGAL_COLUMN. Both now return [1,257], which is what each has always
returned without toNullable, and the arrayUnion case is one of the test lines.
arrayIntersect never reaches that state because getMostSubtype keeps Nullable
only when every argument has it, so its not Nullable argument is not cast at
all.

The mask stays unconditional. It is redundant for the sibling modes, whose
common element type comes from getLeastSupertype, which covers all values of
its inputs and throws NO_COMMON_TYPE rather than returning a lossy type, so
their masks are all zero. That redundancy is already there on master for a not
Nullable argument of a differing width, so it is not introduced here, and
gating construction on the set mode would make those two functions depend on
that property holding for every present and future type pair, with a silently
wrong result rather than a dead comparison if it ever stops holding. Narrowing
the guard is a separate change to two functions this fix is not about.

Verified in both directions from a deterministic one-query repro and across 46
probes over mixed widths, LowCardinality(Nullable), const and materialized
paths, NULL elements, boundary values, decimals, strings, tuples, mixed
nullability and all three set functions: no input gains a new exception, one
loses the ILLEGAL_COLUMN above, and every case whose result moves now returns
what the not Nullable spelling has always returned. Date32 stays outside the
guard's type list and is unchanged.

Closes: ClickHouse#114587
Related: ClickHouse#117577

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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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