Skip to content

Fix a logical error comparing arrays whose element type is Nothing - #113609

Merged
diegomestre2 merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-array-lexicographic-nothing-cast
Aug 13, 2026
Merged

diegomestre2 merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-array-lexicographic-nothing-cast

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 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

Comparing two arrays whose element types have no least supertype aborted the server with
Bad cast from type DB::ColumnNothing to DB::ColumnVector<char8_t> when an aligned element position
held a bare Nothing, for example SELECT CAST([], 'Array(Nullable(Nothing))') > [[1]], or over
real columns of Array(Tuple(Nothing, UInt64)) and Array(Tuple(Array(UInt8), Int64)). The abort
happened during constant folding as well as at execution, so analysis alone could kill the server.

Root cause: getReturnTypeImpl's array-no-supertype branch declared a plain UInt8, while the
element comparator it later builds declares Nothing for a value-less position. Execution then
assert_cast-ed that ColumnNothing to ColumnUInt8. A bare Nothing position is genuinely
undecidable: it holds no values, a Tuple member has no null map covering it, and there is no length
to tie-break on.

The fix makes the declared type honest. A new per-side containsUndecidableNothing predicate rejects
such a pair during analysis with ILLEGAL_TYPE_OF_ARGUMENT, and compareGatheredElements keeps a
fail-closed guard for defence in depth. Each side is classified independently, because one side's
null map must never decide a position on the other side. The predicate deliberately mirrors
FunctionsNullSafeCmp::containsNothing and does not descend into Array/Map; deeper positions stay
covered because the caller recurses once per array level.

Two Nothing shapes remain decidable and keep answering, now correctly rather than crashing:
Nullable(Nothing) (decided by its own null map) and Array(Nothing) (shares a supertype with
Array(T)). Those answers were checked against the same comparison on a pair that does have a
supertype, and match exactly in both operand orders.

Introduced by #110245, which is on master only, so no released version is affected and no backport
is needed.

Tracked in #113640 (CI signature STID 1499-2747), which also collects the Equality sibling at
FunctionsComparison.h:1485.

Validation

Both directions, one command per binary (pre-fix and fixed builds of the same branch):

query pre-fix fixed
SELECT CAST([],'Array(Nullable(Nothing))') = [[1]] abort, Bad cast ... ColumnNothing ... 0
SELECT CAST([],'Array(Nullable(Nothing))') > [[1]] abort, same message 0
SELECT [NULL] = [[1]] Code: 44 0

The values the fixed build returns were compared against the supertype path ([1] in place of
[[1]]) and match exactly: 0 1 0 0 1 1 for the six operators, 0 1 1 1 0 0 for an empty aligned
prefix, 0 1 for isNotDistinctFrom/isDistinctFrom, and 0 0 in the reversed operand order.

Coverage: all eight operators the introducing PR added; Nothing direct, under Nullable, nested in
Tuple, and under 1-, 2- and 3-deep Array wrappers; Map(k, Nothing) and Array(Nothing) as
must-still-answer controls; empty and non-empty aligned prefixes. An empty range is rejected too, so
validity never depends on the data.

No existing assertion was weakened: all 47 pre-existing reference lines of
04549_array_comparison_bigger_types_nullable are unchanged. 200/200 runs pass across
--test-runs 50 --order random and --test-runs 50 --no-random-settings, and the feature's own
eight-test suite has no failures. Nine mutation arms were run against the new tests; eight are caught,
and the ninth only makes the secondary fail-closed guard unreachable, which no input can pin because
the analysis-time check rejects every such pair first.

Version info

  • Merged into: 26.8.1.1319 (included in 26.8 and later)

Comparing two arrays whose element types have no least supertype takes the
element-wise lexicographic path added by ClickHouse#110245. When a position holds a bare
`Nothing`, `getReturnTypeImpl` declared a plain `UInt8` while the executing
element comparator declared `Nothing`, so the unconditional
`assert_cast<const ColumnUInt8 &>` on the element result received a
`ColumnNothing` and killed the server:

    SELECT CAST([], 'Array(Nullable(Nothing))') > [[1]];
    Logical error: 'Bad cast from type DB::ColumnNothing to DB::ColumnVector<char8_t>'

The divergence exists because validation recurses into `getReturnTypeImpl`
directly, which has no `Nothing` handling, while execution goes through the
overload resolver, which short-circuits to `DataTypeNothing`. It is reachable
from ordinary SQL, both during constant folding and at runtime over a table,
and through `Tuple` members at any array depth.

Close it from both ends. Validation now rejects a position that nothing can
decide: a bare `Nothing`, directly or through a `Tuple` member. Two `Nothing`
shapes stay decidable and keep answering as they do today -- `Nullable(Nothing)`
is decided by its own all-set null map, and `Array(Nothing)` shares a supertype
with `Array(T)` so it never reaches this branch. Each side is classified
independently, because one side's null map never decides a position on the
other side. `Array` and `Map` are not descended, matching
`FunctionsNullSafeCmp::containsNothing`; depth is still covered because the
array branch recurses once per level and is only consulted where that level has
no supertype.

Execution answers what validation accepted and fails closed otherwise: a result
is synthesised only where a direct `Nothing` argument is paired with its own
all-set null map, and any other `Nothing` element type throws instead of
fabricating a `false`. The direct-recursion optimisation is kept.

An untyped NULL or empty array against a non-supertypable partner now answers
instead of aborting, matching the supertype path. The regression never shipped
in a release.
…erand orders

The bare equality arms are reached through the execution-side guard as well, so
they pass even when the analysis-side classifier is pairwise rather than
per-side. Asserting toTypeName in both operand orders pins the classifier
itself: a pairwise form stops at the first tuple member and accepts a pair whose
other member holds a bare Nothing.
@groeneai

groeneai commented Aug 6, 2026

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

An independent model reviewed this change cold, without access to the author's notes, and its
findings were adjudicated against the code. One finding was raised; it is answered below, together
with one I raised myself and then refuted. No finding resulted in a code change.

⚠️ The fail-closed guard in compareGatheredElements is not exercised by the new tests, so it
could be deleted with everything still green.
Disagree on the premise. The claim conflates the guard block with the guard's throw.

The block is entered by every accepted Nullable(Nothing) row, i.e. by 11 committed rows in
04549_array_comparison_bigger_types_nullable. getReturnTypeImpl tests the unstripped nested
type, and containsUndecidableNothing returns false for Nullable(Nothing), so those pairs are
accepted at analysis and do reach compareGatheredElements. There, gatherAlignedArrayElements
applies removeNullable when building the element arguments, so the resolver is handed a bare
Nothing and returns Nothing (IFunctionOverloadResolver::getReturnTypeWithoutLowCardinality,
and FunctionsNullSafeCmp::getReturnTypeImpl for the null-safe resolvers). Deleting the block sends
those rows into impl->execute and therefore into
IExecutableFunction::defaultImplementationForNothing, which throws ILLEGAL_COLUMN "Cannot create
non-empty column with type Nothing" whenever the row count is non-zero. I derived that prediction
from the source and then checked it against the pre-fix binary: SELECT [NULL] = [[1]] returns
Code: 44 there, exactly that error. So the block is load-bearing for those reference lines rather
than inert, and a mutation arm already pins it through the suite: removing only the synthesis is the
one arm that reddens both test files.

What is genuinely unpinned is only the throw, and it is unreachable by construction. Two routes can
make the element comparator declare Nothing. The first needs an element type that is a bare
Nothing after removeNullable, so the nested type must be Nothing, Nullable(Nothing), or either
under LowCardinality; analysis rejects the bare and LowCardinality(Nothing) forms, and for the two
Nullable(Nothing) forms the column is a ColumnNullable whose null map is all-set by construction,
so the masked-result branch returns first. The second route needs a Tuple containing a bare
Nothing member, and analysis descends Tuple with the identical recursion, so every such pair is
rejected before execution. Both routes are exhausted, compareGatheredElements has three call sites
and all three are reached only through the no-supertype array branch, so no input can reach the throw
today. It guards a future fourth caller. A test for it cannot exist for the same reason it cannot
fire, which is why it is documented in the source as secondary defence rather than as the fix.

💡 Stress mode rewrites the new test's Memory tables to MergeTree, raised by me then
refuted, recorded so it is not re-raised. --replace-log-memory-with-mergetree is enabled with
probability 0.3 and applies to the whole stateless suite, and replaying the replacer's own regex
matches all 17 CREATE TABLE lines in the new test. I suspected the resulting write would hit one of
IColumnDummy's unimplemented methods. It cannot via serialization info: that is only created for a
column whose type supports sparse serialization, which an Array-topped type does not, so
isDefaultAt and the default-row counters are never called. Bulk serialization of Nothing is
deliberately implemented, SerializationTuple descends per member, and ORDER BY tuple() leaves the
minmax index empty. The DDL itself is already precedented: 03034_ddls_and_merges_with_unusual_maps
creates a Map(Nothing, String) column on MergeTree today, untagged. Tagging the new test
memory-engine would skip it in that mode, losing coverage on an unmeasured hypothesis, so I left it
alone; CI measures it directly.

💡 Gitignored .stdout/.stderr files from local test runs are present in the working tree. They
cannot reach the PR and no action was taken.

Session id: cron:clickhouse-review-slot-10:20260806-015500

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT CAST([], 'Array(Nullable(Nothing))') > [[1]] aborts the pre-fix binary every time (rc=134), with the message byte-identical to the CI signature. Also reachable at runtime over real columns of Array(Tuple(Nothing, UInt64)) vs Array(Tuple(Array(UInt8), Int64)). Not a low-rate flake.
b Root cause explained? Yes. A validate-vs-execute type divergence: getReturnTypeImpl's array-no-supertype branch declared a plain UInt8, while the element comparator it later builds declares Nothing for an aligned position holding a bare Nothing. Execution reaches compareGatheredElements and assert_casts that ColumnNothing to ColumnUInt8. Such a position is genuinely undecidable: no values, no null map over a Tuple member, no length to tie-break on.
c Fix matches root cause? Yes. The declared type is made honest at the point of declaration: a per-side containsUndecidableNothing predicate rejects the pair during analysis. No widened bounds, no test-level setting pin, no data reduction. compareGatheredElements also fails closed, documented as deliberate secondary defence rather than as the fix.
d Test intent preserved / new tests added? Yes. No existing assertion weakened or removed: all 47 pre-existing reference lines of 04549_array_comparison_bigger_types_nullable are byte-identical. Added 04767_array_lexicographic_nothing_element plus 11 new rows in 04549.
e Both directions demonstrated? Yes. Same command on each binary: pre-fix aborts with Bad cast from type DB::ColumnNothing to DB::ColumnVector<char8_t>, fixed answers 0. Every server was started with SELECT lower(buildId()) asserted equal to readelf -n of the binary under test before any verdict was recorded.
f Fix is general across code paths? Yes. Both abort sites (the equality path and the less-greater path) consume the same compareGatheredElements, so the fix lands once at the shared declaration and once in the shared helper. All eight operators the introducing change added are asserted: =, !=, <, <=, >, >=, isDistinctFrom, isNotDistinctFrom. The predicate is deliberately kept in step with the sibling FunctionsNullSafeCmp::containsNothing instead of diverging from it.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nothing direct, under Nullable, nested in Tuple, and under 1-, 2- and 3-deep Array wrappers, with LowCardinality stripped; Map(k, Nothing) and Array(Nothing) included as must-still-answer controls; both operand orders; empty and non-empty aligned prefixes. Boundary case explicitly covered: an empty range is rejected too, so validity never depends on the data. The answers now returned were checked against the supertype path and match exactly.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changed, so no SettingsChangesHistory.cpp entry is owed, and no serialization format is touched. The only behaviour change is on inputs that previously aborted the server. The introducing change is on master only, so no released version is affected and no backport is needed.
i Invariants and contracts preserved? Yes. compareGatheredElements's postcondition, a full non-const UInt8 column over all gathered pairs, now holds on every path including the new early return, which is exactly what its two assert_cast callers require; the synthesised column is built at gathered.num_elements, matching the size those callers expect. The fail-closed throw is taken before any read of a value-less column. No lock or concurrency contract is involved: the change is type-level analysis plus one local column construction.

Session id: cron:clickhouse-impl-slot-4:20260806-010002

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @diegomestre2 @nihalzp, could you review this? The array-no-supertype branch of getReturnTypeImpl declared a plain UInt8 while the element comparator it later builds declares Nothing for an aligned position that holds a bare Nothing, so execution reached an assert_cast of a ColumnNothing to ColumnUInt8 and aborted debug and sanitizer builds during constant folding as well as at execution. This makes the declared type honest instead, rejecting only the positions that nothing can decide, so Nullable(Nothing) and Array(Nothing) keep answering.

@diegomestre2 diegomestre2 self-assigned this Aug 6, 2026
@nihalzp nihalzp added the can be tested Allows running workflows for external contributors label Aug 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8d4c298]

Summary: ✅


AI Review

Summary

This PR fixes the array lexicographic comparison path when a no-supertype element pair contains a bare Nothing, by rejecting genuinely undecidable shapes during type analysis and preserving the still-decidable Nullable(Nothing) cases at execution. I reviewed the current diff, tests, and prior discussion on the current head and do not see any remaining correctness, regression, or evidence gaps.

Final Verdict

✅ No remaining review findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 28/31 (90.32%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8d4c298dd with master bb1bd3074 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2e330af4c; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.05 MiB 689.06 MiB -2.99 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 68101e1

CI is fully finished on this head: 175 checks completed, 155 success, 20 skipped (each with a
recorded reason: not affected by the changed files, no build-affecting changes, not a bug-fix PR,
no integration test updates, not labeled pr-performance / ci-toolchain, reused from cache).
The praktika report top-level status is OK with 0 dropped jobs, so the run carries real coverage.

No failures. Nothing to own.

Session id: cron:our-pr-ci-monitor:20260811-223000

Comment thread src/Functions/FunctionsComparison.h Resolved
…n test

The suite asserted the rejection only where a bare `Nothing` was aligned against a side that
carries values (`Nullable(UInt64)`), so the shape where BOTH sides hold a bare `Nothing` in the
same position and differ only in the signedness of the carrying member was untested.

That shape matters because the element resolver does accept it: for
`Tuple(Nothing, UInt64)` vs `Tuple(Nothing, Int64)` the recursive `getReturnTypeImpl` answers
`Nullable(UInt8)`, which reads like a decidable comparison. It is not one.
`IFunction.cpp:872-877` returns `DataTypeNothing` as soon as any argument type is `Nothing`, so
that outer `Nullable(UInt8)` is the null-wrapping of a `Nothing` result rather than a comparison
outcome: measured over 9 populated row pairs the column is null 9 times out of 9, while the
carrying member compared on its own decides all 9. Admitting the pair on the strength of that
return type would therefore produce a comparison that cannot answer for any row.

Added rows, and what each one pins (measured against a master build without this fix):

- `toTypeName(a = b)` - master analyses it successfully, so this pins the declared type.
- `a = b` and `b = a` - master aborts with
  `Bad cast from type DB::ColumnNothing to DB::ColumnVector<char8_t>`
  (`executeArrayLexicographic` -> `assert_cast`), so these pin the crash in both operand orders.
- `a > b` and `b > a` - already `ILLEGAL_TYPE_OF_ARGUMENT` on master, because only `equals` and
  `notEquals` admit a `Nullable(UInt8)` element result there. Kept as documentation of the
  ordering half; they are not new coverage.

A `Tuple(String, ...)` pair with the same signedness difference answers `0`/`0` and stays
accepted, so the rows above pin the `Nothing` member rather than the mixed signedness.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8d4c298

CI is fully finished on this head: 176 checks completed, 155 success, 21 skipped (each with a
recorded reason: not affected by the changed files, not a bug-fix PR, no integration test updates,
no changes under src/Coordination, not labeled pr-performance / ci-toolchain, reused from
cache, no failed tests from previous runs). The praktika report top-level status is OK with 0
dropped jobs, so the run carries real coverage. CIDB reports no failing test rows for this PR.

No failures. Nothing to own.

Session id: cron:our-pr-ci-monitor:20260812-233000

@diegomestre2 diegomestre2 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should avoid the issue with Nothing type, looks good!

@diegomestre2
diegomestre2 added this pull request to the merge queue Aug 13, 2026
Merged via the queue into ClickHouse:master with commit f656ba3 Aug 13, 2026
181 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 14, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
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-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.

4 participants