Skip to content

Fix crash in nested set operations over large integer literals - #112043

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-union-common-header-supertype-flag
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-union-common-header-supertype-flag

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixed a crash on nested EXCEPT, INTERSECT or UNION queries over large integer literals, where the query plan produced an Int64 column that the analyzer had typed as Variant(Int64, UInt64). Release builds could end in a segmentation fault and debug builds threw Bad cast from type DB::ColumnVector<long> to DB::ColumnVariant; aggregate functions such as groupConcat over such a column were affected too.

Description

Related: #107951, #110745

On the official 26.3.33.24 and 26.8.10.6 builds this ends in a segmentation fault at default settings:

SELECT * FROM (((SELECT 9223372036854775806 AS n) EXCEPT ALL SELECT 10 AS n)
               EXCEPT ALL SELECT -9223372036854775807 AS n)
WHERE (n = (SELECT n));

AST fuzzer reports: debug, release.

Root cause. DataTypeUInt64 carries a per-instance canUnsignedBeSigned flag that lets getLeastSupertype fold UInt64 and Int64 into Int64, but IDataType::equals ignores it. addConvertingToCommonHeaderActionsIfNeeded therefore skipped a branch that differed from the common header only by that flag, so the inner union published the flagged type and the outer one folded it to Int64, while the analyzer declared Variant(Int64, UInt64) for the same column. Every consumer built from the declared type (the Variant function adaptor, aggregate functions, variantType) then got a plain column.

Fix. When a branch column differs from its common-header type only by dropping that flag, force the conversion and the CAST that makeConvertingActions omits. The predicate never adds a flag and leaves alone a container that would need both directions; both cases are pinned by Conversion before UNION step counts in the test.

Validation. 04647_union_common_header_supertype_flag covers the query above with Nullable, LowCardinality, Array, Tuple and Map wrappers, groupConcat, any, variantType, and UNION ALL / UNION DISTINCT nested in another set operation. Each of these fails on unpatched master and returns the expected value with the fix; 67 randomized runs passed.

#110745 changes the same function for a different trigger and cannot see this flag, since type names do not encode it.


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

groeneai and others added 3 commits July 27, 2026 02:33
…ce flag

DataTypeUInt64 carries a per-instance canUnsignedBeSigned flag, set by
FieldToDataType for a UInt64 literal that also fits Int64 and consumed by
convertUInt64toInt64IfPossible so that getLeastSupertype can produce a plain
Int64 instead of a Variant. IDataType::equals compares only typeid, so a flagged
and an unflagged UInt64 are indistinguishable to every equals()-based check.

addConvertingToCommonHeaderActionsIfNeeded therefore skipped such a branch
twice over: blocksHaveEqualStructure reported equality, and even when the
converting DAG was built makeConvertingActions omitted the CAST. The branch
then published its own flagged type as the union output type. An enclosing
union folded that flagged UInt64 with an Int64 branch, convertUInt64toInt64IfPossible
fired, and the plan header collapsed to Int64 while the analyzer, whose nested
fold went through a freshly constructed unflagged instance, had already declared
Variant(Int64, UInt64) for the same node.

Every consumer built off the declared type then disagreed with the column in
the plan. IFunctionOverloadResolver::build installs FunctionBaseVariantAdaptor
whenever a declared argument type is Variant, so ExecutableFunctionVariantAdaptor
cast a ColumnVector or ColumnNullable to ColumnVariant and threw:

  Logical error: 'Bad cast from type DB::ColumnVector<long> to DB::ColumnVariant'

Force the conversion when a branch column and its common-header target compare
equal() but the branch carries the flag and the target does not, and force the
CAST that makeConvertingActions skips. The predicate is one directional: a
flagged common target is constructible through the all_equal shortcut in
getLeastSupertype, so mixed unions are order dependent and correct today, and
adding a flag is never necessary. It also refuses a container that would strip
one leaf's flag and add another's, because a CAST converts a whole column.

The same class is worked around at the consumption site twice in
src/Functions/if.cpp (issues ClickHouse#105649 and ClickHouse#70017); this fixes it one layer up so
every consumer above a union sees a consistent type.

Found by the AST fuzzer, but reachable from an ordinary SELECT at default
settings.

Co-Authored-By: Claude Fable 5 <[email protected]>
It drives remote('127.0.0.1', ...) for the distributed / WithMergeableState
control, which the runner only selects when the server has a second listen host.

Co-Authored-By: Claude Fable 5 <[email protected]>
…test

Two review findings, both about the test asserting values that cannot observe
the property the fix claims.

The aggregate state control drives two remote() queries, but the runner
randomizes prefer_localhost_replica, and with the value 1 a plain MergeTree
shard is planned entirely locally, so no secondary query plan is built while
the asserted 15 and UInt64 still match. Measured 0 secondary queries without
the pin against 4 with it, and the test passes either way, which is the
vacuity. The two queries now pin prefer_localhost_replica = 0.

The one directional restriction of the flag predicate, strips and not adds, was
pinned by nothing: a flagged and an unflagged UInt64 print the same type name
and the flag changes no value, so mutating the predicate to strips or adds, or
deleting only the mixed direction refusal, left every asserted byte identical.
The test now counts Conversion before UNION plan steps, which is the only
plan level effect the conversion has. Two of the added shapes keep every branch
non constant, because a const branch already fails blocksHaveEqualStructure and
gets a conversion step whether or not the predicate fires, which makes the count
blind to the mutation. Every expected count was derived by measurement and then
checked against a prediction written before building the mutations: strips or
adds moves three counts, strips alone moves one, and neither moves any other
line.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

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

Two review rounds. Round 0 found two majors and bounced the PR; round 1 is clean. In both rounds
the reviewer is a different model from the author, reads the resulting code before any of the
author's own evidence, and never edits source.

Round 0: two majors, both fixed

Both were raised INDEPENDENTLY by the reviewer's own cold read and by the second-model gate, so
each was twice-raised and could not be waived. Both were test-liveness defects. The C++ fix was
correct in round 0 and is byte-identical now.

❌ The only coverage of the distributed / WithMergeableState carrier was unpinned.
The control: aggregate state union block drives two remote('127.0.0.1', ...) queries, but the
test runner randomizes prefer_localhost_replica, and at value 1 SelectStreamFactory plans a
plain MergeTree shard entirely locally, so no secondary-query plan is built at all while the
asserted 15 / UInt64 still match. That block is what the verification list claims covers this
carrier, so it was a false coverage claim rather than a cosmetic gap.
Fixed: statement-level prefer_localhost_replica = 0 on both queries, reference unchanged.
Measured 0 secondary queries without the pin against 4 with it, results identical either way, and
re-checked through the real runner with a hostile --client-option prefer_localhost_replica=1.

❌ The one-directional restriction of the predicate was pinned by nothing.
strips && !adds is the fix's load-bearing safety property and the description states it twice,
but its controls asserted only toTypeName and row counts. A flagged and an unflagged UInt64
print the same type name and the flag changes no value, so mutating the predicate to
strips || adds, or deleting only the mixed-direction refusal, left every asserted byte identical.
Fixed: the test now counts Conversion before UNION plan steps, the fix's only plan-level
observable, in the SELECT ... FROM (EXPLAIN ...) form with explain_query_plan_default = 'legacy'
and optimize = 0. The reviewer deliberately narrowed the gate's suggested oracle (exact
actions = 1 cast counts) to the step count: action lists churn on unrelated planner changes and
would make this test a standing maintenance cost.

⚠️ Worth recording, because it corrects the reviewer: five of the six assertion shapes the
fix plan prescribed for that oracle cannot discriminate the mutations at all. The predicate is only
consulted where blocksHaveEqualStructure already reported equality, and a constant branch against
a non-constant common-header column already fails that comparison, so a conversion step exists
regardless and the forced cast lands inside it. The author measured this, reported it instead of
working around it, and added two shapes whose branches are all non-constant exactly where each
mutation newly fires. Those two are what discriminate.

Round 1: clean

Reviewer's own cold read: no findings. Second-model gate: 0 findings, over a diff whose
whole-PR and delta diffstats both match the intended change set. Predictions for the mutation
matrix were written before the mutation builds and match measurement in all 16 cells; widening the
predicate fails exactly three count lines, dropping only the mixed-direction refusal fails exactly
one, and neither moves any other asserted byte.

Re-derived independently rather than inherited from round 0: the invariant-carrier list; the
reference-file blast radius (swept all 25712 files under tests/queries for a set operation plus
an unsuffixed literal in the exact range the flag is set for plus a plan-level EXPLAIN, only the
new test qualifies, and the hexadecimal literal form was checked separately); and the PR metadata,
by running the actual CI parsers rather than reading headers by eye.

Noted, not blocking

💡 The added C++ comments do not backtick symbol names. The repository instruction file asks for
it, but unbackticked is the in-tree majority for C++ comments (25% of symbol-naming /// lines in
src/ use backticks; 17 of 75 in this file), so this is the prevailing convention rather than a
deviation.

💡 equals() is written with parentheses in prose. That is the established in-tree spelling for
this method in comments, and here it disambiguates the C++ method from the SQL equals function
the description also discusses.

Session id: cron:clickhouse-review-slot-49:20260727-063700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * FROM (((SELECT 9223372036854775806 AS n) EXCEPT ALL SELECT 10 AS n) EXCEPT ALL SELECT -9223372036854775807 AS n) WHERE (n = (SELECT n)); at default settings, no tables, no SET. Aborts 100 percent on the pre-fix binary, as an ordinary SELECT and as EXPLAIN PIPELINE, and with query_plan_enable_optimizations = 0.
b Root cause explained? Yes. DataTypeUInt64 carries the per-instance canUnsignedBeSigned flag (set by FieldToDataType for a UInt64 literal that fits Int64, consumed by convertUInt64toInt64IfPossible), and DataTypeNumber::equals compares only typeid. So addConvertingToCommonHeaderActionsIfNeeded skipped a flagged branch twice: blocksHaveEqualStructure reported equality, and makeConvertingActions omitted the CAST. The branch published its flagged type as the union output, the enclosing fold collapsed to Int64, while the analyzer had declared Variant(Int64, UInt64). IFunctionOverloadResolver::build then installed the Variant adaptor off the declared type and assert_cast<const ColumnVariant &> threw.
c Fix matches root cause? Yes. The conversion is forced in the function whose contract is to make each branch match the common header, so the analyzer and the planner converge naturally. No relaxation of the assert_cast at the consumption site, and no cross-stage type import into the plan header.
d Test intent preserved / new tests added? New test added: 04647_union_common_header_supertype_flag. It pins the repro, the declared type, the plan header, the wrapper matrix (Nullable, LowCardinality, Array, Tuple, Map), six controls that must be unchanged, and eight conversion-step counts. The counts exist because type names cannot see the flag, so they are the only in-test oracle for which branches the conversion fires on; each one was derived by measurement and then mutation tested. No existing test was weakened.
e Both directions demonstrated? Yes. Base binary aborts with Bad cast from type DB::ColumnVector<long> to DB::ColumnVariant and a stack matching the CI report through ActionsDAG::updateHeader; the fixed binary returns the correct row. Because the base aborts on the first offending statement and masks the rest of the file, the test was driven statement by statement against the base binary, with a fresh data path per statement. Build IDs verified distinct at every step.
f Fix is general across code paths? The fix sits in the single function shared by both buildCommonHeaderForUnion call sites (Planner.cpp and PlannerCorrelatedSubqueries.cpp), acts before the union mode is chosen so it covers all six modes, and does not depend on any plan optimization. The sibling FunctionBaseDynamicAdaptor cannot be reached the same way: getLeastSupertype only yields Dynamic when a branch is already Dynamic, and such a union rejects the correlated join earlier with ILLEGAL_COLUMN.
g Fix generalizes across inputs? The predicate compares leaf by leaf through forEachChild, so it sees the flag inside a wrapper. Verified aborting on base and passing with the fix for bare, Nullable, LowCardinality, Array, Tuple and Map, for EXCEPT ALL and INTERSECT ALL. UNION ALL, the explicit-cast form, both branch orders of a mixed flagged and unflagged union, and a mixed-direction Tuple are pinned as unchanged controls, and the conversion-step counts additionally pin a branch that would have to acquire the flag and a non constant mixed-direction Tuple, the two shapes that make the directional restriction observable.
h Backward compatible? Yes. No setting, no default, no serialization format touched. The only user-visible change is that the plan header now agrees with the type the analyzer already reports through toTypeName. A sweep of the 354 stateless tests matching union, except, intersect and variant on the fixed and the base binary produced identical failure sets apart from three tests independently confirmed flaky on the base binary; no reference file moved.
i Invariants and contracts preserved? The invariant is that a branch published to a union step carries the common-header type identity, including inference-relevant flags equals() cannot see. The forced CAST only ever targets the type buildCommonHeaderForUnion computed on the same call, so it cannot make a branch disagree with the header it is converted to. The predicate is one directional and refuses mixed-direction containers, since addCast converts a whole column; both restrictions are pinned by conversion-step counts and mutation tested. No size-mismatch bail-out was added: both computations already reject unequal branch widths, so a residual mismatch must keep propagating. Aggregate-state headers at WithMergeableState are untouched, verified through a remote() union with prefer_localhost_replica = 0 so the secondary query plan is really built (measured 4 secondary queries with the pin, 0 without it), including with serialize_query_plan = 1.

Session id: cron:clickhouse-impl-slot-40:20260727-055100 (authored), cron:clickhouse-review-slot-49:20260727-063700 (reviewed and published)

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @yakov-olkhovskiy - could you review this? It makes addConvertingToCommonHeaderActionsIfNeeded convert a union branch whose type differs from the common header only in DataTypeUInt64's per-instance canUnsignedBeSigned flag, which IDataType::equals does not compare, so the branch used to publish its own flagged type and the planner then folded a different supertype than the analyzer had already declared for the same node - ending in Bad cast ... to DB::ColumnVariant from the Variant adaptor.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3b7ca40]

Summary: ✅


AI Review

Summary

This PR fixes the planner/analyzer mismatch in nested set operations where a branch that differs from the common header only by DataTypeUInt64's hidden canUnsignedBeSigned flag can skip the cast to the common type, so downstream consumers receive a plain Int64 column where analysis declared Variant(Int64, UInt64). The src/Planner/Utils.cpp change is focused, and the new stateless test covers the original repro, wrapper carriers, function and aggregate consumers, nested set-operation shapes, and the one-direction-only safety property. I did not find a remaining code-level correctness, safety, or performance issue in the current diff.

PR Metadata
  • 💡 Changelog category is not semantically correct. This fixes a release-build segmentation fault, so it matches Critical Bug Fix, not Bug Fix.
  • 💡 The Changelog entry should be rewritten in present tense per docs/changelog_entry_guidelines.md.
  • 💡 The Related links in the PR body should be one per line, not comma-separated on a single line.
  • Exact replacement text:
### Changelog category (leave one):
- Critical Bug Fix (crash, data loss, RBAC)

### Changelog entry (a [user-readable short description](https://github.com/ClickHouse/ClickHouse/blob/master/docs/changelog_entry_guidelines.md) of the changes that goes into CHANGELOG.md):

Fixes a crash in nested `EXCEPT`, `INTERSECT`, or `UNION` queries over large integer literals, where the query plan could produce an `Int64` column that the analyzer had typed as `Variant(Int64, UInt64)`. In release builds this could end in a segmentation fault, and aggregate-function consumers such as `groupConcat` were affected too.
  • Description relationship lines should be:
Related: https://github.com/ClickHouse/ClickHouse/issues/107951
Related: https://github.com/ClickHouse/ClickHouse/pull/110745
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix the PR metadata above (Critical Bug Fix, present-tense changelog entry, and one Related: link per line). I did not find a remaining code-level blocker in the current diff.

LLVM Coverage Report

Measured on commit 3b7ca40.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 42/43 (97.67%) · Uncovered code

Full report · Diff report

The Style check rejects the phrase "new analyzer": the analyzer has been the
default since 24.3, so the wording rule in various_checks.sh asks for "the
analyzer" or "Analyzer". Only the comment text changes; the executable content
of the test is byte identical.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/112043/44bc98dfcfaff1bdc2558e913f99c4249c3fea9a/style_check/job.log
Related: ClickHouse#112043

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 42/43 (97.67%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 47b14e9

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
Stress test (arm_debug) / Logical error: Inconsistent KeyCondition behavior (STID: 5182-2f27) pre-existing debug-only monotonicity canary (#90461), widening-_CAST class #109023 (mine, open)

CI is otherwise green on this head: 174 checks, 153 success / 18 skipped / 1 failure, Finish Workflow success.

Attribution for the one failure, so it is checkable rather than asserted:

  • The mechanism is read out of the job's own clickhouse-server.err.log.zst, not inferred from the
    STID. The line preceding the throw in MergeTreeDataSelectExecutor::markRangesFromPKRange names
    the atoms: Participating conditions: key condition (useful: true) (relaxed: false): (_CAST(column 0) in ['5', '5']), (column 1 in [900, +Inf)) — three occurrences, all the same
    shape, on parts all_1_1_0, all_3_3_0, all_5_5_0. A widening _CAST on the first
    primary-key column is exactly the manifestation Fix Inconsistent KeyCondition behavior for wider-typed key comparisons #109023 fixes.
  • Not caused by this PR's diff. This PR touches src/Planner/Utils.cpp
    (addConvertingToCommonHeaderActionsIfNeeded) plus its own new test; it does not touch
    KeyCondition, key analysis, or monotonicity.
  • Not new: STID 5182-2f27 has 183 hits across 148 distinct pull requests and 12 master runs in the
    last 14 days, first seen 2026-06-15 — i.e. a trunk signature that predates this branch.

Session id: cron:our-pr-ci-monitor:20260727-160000

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@qoega

qoega commented Sep 1, 2026

Copy link
Copy Markdown
Member

@groeneai update this PR

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

@qoega Updated: merged current master in (a merge commit rather than a rebase, since the branch is already published). New head d2c2333063201f05a0e70e67d89c318f50fe5184, diff unchanged at 3 files, +265/-1. Say the word if you wanted a rebase instead.

The branch was 20319 commits behind, so I re-verified on the new base before pushing: unpatched master 38a9ca20 still aborts with Logical error: 'Bad cast from type DB::ColumnVector<long> to DB::ColumnVariant' at FunctionVariantAdaptor.cpp:87, and with this change 04647_union_common_header_supertype_flag passes and the reproducer returns the correct row. CI is running on the new head.

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3b7ca403c with master 1f578fbb5 (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, 13 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d2c2333063201f05a0e70e67d89c318f50fe5184

CI is fully finished on this head. 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) ERRORs at ci/jobs/functional_tests.py:734 with AssertionError: Could not find master builds in S3 before any server starts, so the job validated nothing and no test is attributed #117433 (mine, open)
Bugfix validation (functional tests, aarch64) same Could not find master builds in S3 abort as the row above #117433 (mine, open)
Finish Workflow / Post Hooks cascade of the two rows above: ci/jobs/scripts/workflow_hooks/new_tests_check.py reds when no per-arch bugfix job reports OK or XFAIL #117433 (mine, open)
Docs examples / Documentation examples / Function/toYYYYMM#0 the toYYYYMM documentation example pinned its output to a value derived from the current date, so it started failing at the month rollover on every pull request and on master #117459 (mine, merged 2026-09-01), absent from this tree
Stress test (arm_debug) / Logical error: Not-ready Set is passed as the second argument for function 'globalIn' (STID 0250-4e52) pre-existing trunk defect on the object-storage _path / _file prefilter, not reachable from this diff: the abort runs ReadFromObjectStorageStep::createIterator into StorageObjectStorageSource::createFileIterator, VirtualColumnUtils::getFilterByPathAndFileIndexes and FunctionIn::executeImpl (src/Functions/in.cpp:128), and carries no FutureSetFromSubquery frame #112968 (external, open)
Stress test (arm_tsan) / Logical error: Shard number is greater than shard count: shard_num=2 shard_count=1 cluster=test_cluster_one_shard_three_replicas_localhost (STID 5066-457d) pre-existing master defect: prepareClusterForParallelReplicas indexes the initiator's _shard_num into cluster_for_parallel_replicas as if both numbered the same cluster #113589 (mine, open)
Stress test (arm_tsan) / Test script failed not a separate defect: script exit code: 1 is the stress runner exiting after the server abort in the row above #113589 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

None of the rows above is caused by this pull request.

I am not merging master here purely to re-run CI. #117459 is the only merged owner, so a merge
would clear the Docs examples row and leave the Bugfix validation, Finish Workflow and two
Stress test rows red, at the cost of a full workflow cycle and a maintainer approval. One merge
once #117433 lands clears more of them at once.

Session id: cron:our-pr-ci-monitor:20260901-190000

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Another AST fuzzer report of the same divergence, this time through an aggregate function, where a release build crashes instead of throwing:

SELECT groupConcat(x) FROM ((SELECT 9223372036854775806 AS x) EXCEPT DISTINCT (SELECT 0) EXCEPT DISTINCT (SELECT -9223372036854775808 AS x));
  • AST fuzzer (amd_release, oracle): SIGSEGV (address 0x18) in SerializationVariant::serializeText called from GroupConcatData::insert (report, fatal.log).
  • On that run's amd_release binary the query above aborts at default settings with libc++ Hardening assertion __n < size() failed. A debug build of current master throws Bad cast from type DB::ColumnVector<long> to DB::ColumnVariant.
  • any(x) (an assertion in debug, ILLEGAL_COLUMN in release) and ((... UNION ALL ...) EXCEPT DISTINCT ...) hit the same divergence.

The aggregate is created for the declared Variant(Int64, UInt64), but the plan delivers a plain Int64 column. With the first branch written as 9223372036854775806::UInt64, an unflagged UInt64 like the one the forced CAST here produces, all three return the expected result on the same debug build.

So the terminology note in the description holds only for the function adaptor path: the aggregate path crashes release builds.

groeneai and others added 3 commits October 2, 2026 14:41
The same analyzer/plan type divergence is reachable through aggregate
functions created for the declared Variant type (groupConcat, any,
groupArray), through variantType, and through UNION ALL / UNION DISTINCT
nested inside another set operation. On unpatched master these fail with
`Bad cast ... to DB::ColumnVariant`, a column type assertion, `Invalid
discriminator value 254`, or ILLEGAL_TYPE_OF_ARGUMENT for variantType; on
official 26.3 and 26.8 release builds the groupConcat form and the
original repro end in SIGSEGV. All of them return the expected result
with this fix.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93833&sha=1861d9a31415622f9f5b772f915bc90558515d98&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29
Related: ClickHouse#112043

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep only the invariants a reader needs at each spot: equals(),
blocksHaveEqualStructure() and makeConvertingActions() do not see the
canUnsignedBeSigned flag, and a whole-column CAST cannot drop the flag on
one nested type while adding it on another. The rest (the one-directional
predicate, how the divergence reaches the analyzer-declared Variant) is in
the PR description and the earlier commit messages. Comment-only change:
the comment-stripped file is identical.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix logical error 'Bad cast to ColumnVariant' in set operations Fix crash in nested set operations over large integer literals Oct 2, 2026
@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to my previous comment: the function adaptor path crashes release builds too. The query in the description ends in a segmentation fault in ExecutableFunctionVariantAdaptor::executeImpl on the official 26.3.33.24 and 26.8.10.6 builds, because assert_cast is unchecked there. I updated the description accordingly.

Also merged master and added the groupConcat, any, variantType and nested UNION ALL / UNION DISTINCT cases to 04647_union_common_header_supertype_flag. Each fails on unpatched master and passes with the fix.

@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 2, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants