Skip to content

Fix arrayIntersect matching values that overflow the common element type when the arguments are Nullable - #118485

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-114587-arrayintersect-nullable-overflow-mask
Sep 8, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-114587-arrayintersect-nullable-overflow-mask

Conversation

@groeneai

@groeneai groeneai commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #114587
Related: #117577

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 returning elements that do not survive the cast to the common element type when the overflowing argument is Nullable: arrayIntersect([toNullable(1)], [toNullable(257)]) returned [1] where arrayIntersect([1], [257]) correctly returned []. The guard that drops such elements tested the element type without removing Nullable, so it never fired for a Nullable or LowCardinality(Nullable) argument, in any of its integer, Date, DateTime and DateTime64 arms. arrayUnion and arraySymmetricDifference share that guard, where one not Nullable argument of a different width failed with ILLEGAL_COLUMN instead: arrayUnion([1], [toNullable(257)]) now returns [1,257], like arrayUnion([1], [257]).

Description

prepareArrays builds an overflow mask so elements that do not survive the narrowing cast cannot match, by re-comparing the cast column against the original with notEquals (:400-419, consumed at :714) for integer-like element types only. Both types feeding that test came from removeNullable(<arg>.type), which strips the wrapper off the array type, never Nullable here, and not off the element type. So the element type of Array(Nullable(UInt8)) stays Nullable(UInt8), WhichDataType reports TypeIndex::Nullable, all four predicates return false, the mask block is skipped, and the truncated 257 -> 1 matches 1.

The fix removes Nullable from both element types at their single declaration site, covering all four arms. Both are needed, not only the condition: the nested columns are already unwrapped out of ColumnNullable above, so leaving the types Nullable makes callFunctionNotEquals describe a column it does not hold and throw ILLEGAL_COLUMN. No cast, result type, type list or NULL handling changes; the same shape already exists at :281.

arrayUnion and arraySymmetricDifference share this code, and there the strip also removes an error: with one not Nullable argument of a different width the guard compared a Nullable type against a plain column, so arrayUnion([1], [toNullable(257)]) failed with ILLEGAL_COLUMN. It now returns [1,257], as it always has without toNullable; arraySymmetricDifference is the same.

Validated in both directions from a deterministic one-query repro and 46 probes over mixed widths, type wrappers, const and materialized paths, NULL elements, boundary values and all three set functions: no input gains a new exception, and every changed case returns what the not Nullable spelling has always returned.


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

…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]>
@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 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 gate findings plus 6 from my own
cold reads; 3 review passes and 2 fix rounds, then a clean delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The change also alters arrayUnion and arraySymmetricDifference, contradicting the scope this PR originally claimed (src/Functions/array/arrayIntersect.cpp:400-419) AGREE, fixed @ 8bff83f Correct, and I reached it independently before the gate did. prepareArrays is shared by all three set modes and the mask is consumed at :714 for each. Measured on both binaries: arrayUnion([1], [toNullable(257)]) and arraySymmetricDifference([1], [toNullable(257)]) returned Code: 44 ILLEGAL_COLUMN before, [1,257] after, which is what each already returns without toNullable. The changelog entry, description, commit message and validation comment were all corrected, and the arrayUnion case is now a test line
2 ⚠️ Restrict mask construction to ArraySetMode::Intersect: the sibling modes resolve through getLeastSupertype, so their mask can never hold a set bit AGREE on the observation, DISAGREE on the remedy Both load-bearing steps are true (:210-213, :471-474 select getLeastSupertype; getLeastSupertype.h:22-26 defines it as value-covering and .cpp:145-166 throws NO_COMMON_TYPE rather than returning a lossy type). What does not follow is "adds": the siblings build that same all-zero mask on master today for a not Nullable argument of differing width, so this change routes Nullable arguments into a pre-existing path rather than creating redundancy. Adopting it would make both functions newly depend on that property holding for every future type pair, with a wrong result rather than a dead comparison if it stops. Raised twice, so it is not silently overridden: the observation and this reasoning are in the commit message, and one comment from you overrules it
3 ⚠️ Coverage gaps: LowCardinality(Nullable) is claimed but untested, no sibling mode is covered, and the per-arm temporal, reversed-order and const/materialized matrices are missing AGREE in part, fixed @ 8bff83f and d4c8854 Three lines added: the LowCardinality(Nullable) carrier, the arrayUnion case, and the reversed spelling. The rest is DISAGREEd with evidence: one declaration site feeds all four predicates, so there is no partial implementation to pin per arm, and the changed lines read only .type, which is identical for const and materialized columns (ColumnConst is unwrapped at :369-374, upstream of the change)
4 💡 The reversed spelling is a distinct case, not a duplicate of the repro AGREE, fixed @ d4c8854 My earlier reason for treating it as the same case was unsound and I corrected it: the guard loop runs once per argument, so reversing changes which argument carries the truncated element, and argument 0 both seeds the lookup map and drives the result pass. Measured [1] before, [] after, and the reference line was written from the fixed binary's own output
5 💡 The new comment's "already unwrapped out of ColumnNullable" is unconditional only for the cast side DISAGREE Exhausting castColumns: a Nullable-element argument is only ever cast to a Nullable-element target (:310-317, :324-328, and return_type_with_nulls is Nullable whenever any argument is, since :472 passes force_support_conversion). Every remaining case leaves the two columns identical, which skips the guard, so both are plain where the comment sits
6 💡 Line references in my own validation comment mixed pre-fix and post-fix numbering, and its provenance line named the wrong session AGREE, fixed before posting Claims were all correct, pointers were loose; normalized to master numbering (:513, :708-715) so they line up with the numbering used in the description

Also checked and clean, so you do not have to re-derive it: getMostSubtype and getLeastSupertype
both distribute Nullable outward over the element computation, so after the strip the guard sees
exactly the element type pair the not Nullable spelling already produces, which is why no
comparison can newly fail to build and no mask bit can differ; isInteger is exactly
isInt() || isUInt(), so the guard's admitted set is precisely {Int*, UInt*, Date, DateTime, DateTime64} and no other element type gains a path; the reverse pairing of a plain type over a
still-Nullable column is unreachable; null_map is tested before the mask at :708-715, so a
NULL can never be dropped by it; removeNullable(overflow_mask) at :417 degrades to a no-op;
and the idiom appears nowhere else in src/.

One pre-existing behavior I noticed and deliberately left alone: the intersect result pass consults
null_map but not overflow_mask, so a truncated element in the first argument is still emitted
when its cast value collides with a genuinely present one. arrayIntersect([257, 1], [1]) already
returns [1] on master without any Nullable, so both spellings agree there and it is outside
this fix.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-10:20260906-223800

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

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT arrayIntersect([toNullable(1)], [toNullable(257)]) returns [1] on a pristine build and [] with the fix. One query, no settings, no table, 100% deterministic.
b Root cause explained? Yes. The overflow-mask guard derived its element types as typeid_cast<const DataTypeArray &>(*removeNullable(arg.type)).getNestedType(), so removeNullable stripped the wrapper off the array type, which is never Nullable here, and not off the element type. For Array(Nullable(UInt8)) the element type stayed Nullable(UInt8), WhichDataType reported TypeIndex::Nullable, and isInteger, isDate, isDateTime and isDateTime64 all returned false, so the whole mask block was skipped and the truncated 257 -> 1 matched 1.
c Fix matches root cause? Yes. The type test is corrected at its single declaration site, which is the mechanism in (b). Not a widened bound, not a no-random-* tag, not a data-size reduction, not a defensive check: the guard already existed and was already correct, it was simply asked the wrong question. The same shape already exists in this function at :281.
d Test intent preserved / new tests added? Yes. New stateless test 05104_array_intersect_nullable_overflow: the not Nullable control, the issue's repro, the reversed spelling (which carries the truncated element in argument 0, the argument that seeds the lookup map and whose overflow_mask the result pass does not consult), a two-element oracle expecting [2] that rejects both a fix which keeps too much ([1,2]) and one which drops everything ([]), the LowCardinality(Nullable) carrier, and the arrayUnion case that used to raise ILLEGAL_COLUMN. No existing test or reference file was modified.
e Both directions demonstrated? Yes. Against the pristine binary the test reports Having 1 errors!: four lines redden ([]/[]/[2]/[] becoming [1]/[1]/[1,2]/[1]) and the arrayUnion line raises Code: 44. ILLEGAL_COLUMN, while the control line stays green. Against the fixed binary all six pass. Server and binary identity were asserted with SELECT lower(buildId()) before each verdict.
f Fix is general across code paths? Yes. One declaration feeds all four guard arms, so all four are fixed at once, and the DateTime64 arm is measured to move. arrayUnion and arraySymmetricDifference share this code and are measured to change too: arrayUnion([1], [toNullable(257)]) and arraySymmetricDifference([1], [toNullable(257)]) raised Code: 44. ILLEGAL_COLUMN on the pristine binary and return [1,257] with the fix, which is what each of them returns without toNullable on the pristine binary. The arrayUnion case is one of the new test lines. arrayUnion([toNullable(1)], [257]) and the all-Nullable spellings are measured unchanged. Fixed at the source rather than guarded at the consumer. grep -rl overflow_mask src/ and grep -rl callFunctionNotEquals src/ return only this file, so there is no sibling site to widen to.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 46 probes on both binaries: Nullable, LowCardinality(Nullable) (a carrier, fixed by the same two lines, now a test line), const and materialize paths, NULL elements, integer widths including the Int64/UInt64 and Int8/UInt8 boundaries, 0/256, -128/128, DateTime/DateTime64, Date32 (outside the guard's list, unchanged), decimals, String/FixedString, tuples, empty arrays, multi-row, Float, Bool, IPv4, and mixed nullability across all three set functions. No input gains a new exception, and one is removed: the ILLEGAL_COLUMN that arrayUnion and arraySymmetricDifference raised when a not Nullable argument met a Nullable argument of a different width. Each changed case now returns what the not Nullable spelling has always returned.
h Backward compatible? (maintainer-approved exception only) Deliberate and consistent. Two kinds of change, both measured: Array(Nullable(T)) narrowing intersections move from a wrong result to what the not Nullable spelling has always returned (12 of 12 controls agree on the pristine binary), and the arrayUnion/arraySymmetricDifference calls that raised ILLEGAL_COLUMN for a not Nullable argument of a different width now return that same value. Nothing that returned a correct result before returns a different one. No setting is added or changed, so no SettingsChangesHistory.cpp entry is owed; no format or serialization change, so no versioning is involved.
i Invariants and contracts preserved? Yes. The invariant is that an element type handed to the guard, and to callFunctionNotEquals, describes the column actually passed. It holds in lockstep with the two column unwraps: castRemoveNullable is never applied to an argument cast (only to the result at :513), and every castColumns branch that casts a Nullable element targets a Nullable element. removeNullable(overflow_mask) at :417 becomes a no-op and the typeid_cast<const ColumnUInt8 &> there still holds. null_map is consulted before overflow_mask at :708-715, so NULL handling is unchanged. The guard sits inside if (arg.nested_column != initial_column) and the only other exit from that block is an untouched LOGICAL_ERROR. Pure function, no serialization and no restart re-entry path.

Session id: cron:clickhouse-impl-slot-5:20260906-221800

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a0cd55e]

Summary: ✅


AI Review

Summary

This PR fixes prepareArrays so the overflow mask compares unwrapped element types for Array(Nullable(T)), which restores the intended arrayIntersect behavior and also removes the shared ILLEGAL_COLUMN failure in arrayUnion and arraySymmetricDifference. I reviewed the current diff, the surrounding implementation, the new regression coverage, and the prior discussion, and I did not find any remaining correctness, test, or PR-metadata issues that warrant an inline comment.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit a0cd55e.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.20% +0.10%

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

Full report · Diff report

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

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Ergus, could you review this? The overflow guard in prepareArrays applied removeNullable to the array type rather than the element type, so for Array(Nullable(UInt8)) the element type stayed Nullable(UInt8), isInteger and the three temporal predicates all returned false, and values truncated by the narrowing cast (257 to 1) matched. Worth knowing before you look: arrayUnion and arraySymmetricDifference share that code, where the same defect surfaced as an ILLEGAL_COLUMN error rather than a wrong result, and @ PedroTadim offered to review this on the issue too.

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a0cd55e87 with master 275379f80 (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, 12 s compile time in total, 7 of them have a recent master baseline.

Job report

@PedroTadim PedroTadim self-assigned this Sep 7, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit bd6150f Sep 8, 2026
175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @PedroTadim — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

The finding is real and is fixed in #118966: stripping Nullable from both declared element types here is correct, but the initial element column keeps its ColumnNullable wrapper when the common element type is Dynamic, because that unwrap sits inside the if testing the cast column. Nothing to close on this PR.

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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

arrayIntersect overflow guard tests isInteger on a Nullable type, so it never fires

4 participants