Skip to content

Do not lose the Variant discriminator when a constant IN set is built - #117959

Open
groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-variant-discriminator-in-constant-set
Open

groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:fix-variant-discriminator-in-constant-set

Conversation

@groeneai

@groeneai groeneai commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117637
Related: #117831

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 wrong results for a set built from Variant constants, including where the Variant is nested inside the constant's own type. An element was stored under the first alternative that accepted its value rather than the one its type names, so a constant declared UInt64 was compared as a Date: it stopped matching the rows it was built for, and matched rows holding another one. At default settings the OR-to-IN rewrite produces such a set, so a three-disjunct OR chain dropped a row its first disjunct matches, and an AND of notEquals kept an excluded row.

Description

Reported by @ zlareb1 on #117637, reworked to @ Avogar's review. At default settings, no chain, no rewrite:

SELECT materialize(1::UInt64::Variant(Date, UInt64)) IN (1::UInt64);  -- 0, must be 1
SELECT materialize(toDate(1)::Variant(Date, UInt64)) IN (1::UInt64);  -- 1, must be 0

Root cause. A Field cannot express a Variant result: convertFieldToType's Variant branch returns the value unchanged, and the alternative is chosen only on insertion into a ColumnVariant, by the first one that accepts it.

The change. Convert to a Variant-carrying target column-natively, with castColumn, which chooses the alternative by type: an identity conversion, a source naming an alternative, and a Variant source the target extends, element-wise under Array, Map, Tuple and a target-side Nullable. A Nullable source is followed for a non-NULL row at the top level, and deeper only where the target holds a NULL of its own; a deeper one over a target that does not keeps the Field path, as on master. Both chain seams carry each constant into the tuple as its own column, not a Field.

Why the rewrite still declines a multi-alternative Variant. No fixed set element reproduces such a comparison: equals is evaluated against each row's active alternative, so it matches a numerically equal value under a different one and throws where the two are not comparable, while a set element keys on one discriminator.

Validation. 33 of the new test's 52 labelled rows differ on the pristine base. Every OR chain is asserted un-rewritten too, five against the plan, so a decline cannot pass for a fix.

Also fixed. A directly-insertable field took the first alternative that accepted it, so toFloat64(16777217) into Variant(Float32, Float64) landed in Float32, rounded to 16777216; it now takes Float64.

Overlap with other open PRs

#117831 (mine) carried the serialization half of this defect: a Variant constant printed for a secondary server as a bare literal, which the receiver re-infers. It merged on 2026-09-17 and this branch now has its master merge, so that half is done and owned there, not here.

#117637 and #112272 (mine, open) each add a type walk beside this one, answering different questions: whether a comparison's operand order comes from the discriminator, and whether a converted constant is a semantic point. Neither subsumes this one.

#117018 independently adds an identity fast path to convertColumnToTypeOrNull for performance. This PR no longer has one, so the two no longer overlap textually; that fast path has to keep a Variant target on the branch added here, which selects the alternative rather than returning the input unchanged.

#117293 edits both chain seams, so a textual conflict there is expected; keep both changes.


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

… or serialized

`x IN (x, ...)` returned false for a value carrying its own type, with no chain and no
optimizer involved:

    SELECT materialize([1::UInt64]::Array(Variant(Date, UInt64)))
        =  [1::UInt64]::Array(Variant(Date, UInt64));   -- 1
    SELECT materialize([1::UInt64]::Array(Variant(Date, UInt64)))
        IN ([1::UInt64]::Array(Variant(Date, UInt64)),
            [5::UInt64]::Array(Variant(Date, UInt64))); -- 0, must be 1

LogicalExpressionOptimizer then turned a correct OR chain into that wrong IN, so at the
default optimize_min_equality_disjunction_chain_length of 3 a three-disjunct chain dropped
a row its first disjunct matched exactly. A top-level Variant is affected as well, and the
symmetric notEquals -> NOT IN merge returned a row that no conjunct admits.

Root cause: a Field cannot record which Variant alternative a value occupies. Rebuilding a
value from one re-selects an alternative via ColumnVariant::tryInsert, which takes the first
alternative whose column accepts the Field while DataTypeVariant sorts alternatives by type
name, so for Variant(Date, UInt64) the value 1::UInt64 was stored as Date. The value survives
as a column at every step; it was destroyed only where a Field was materialised, at three
places:

  - the two chain rewrites built the IN/NOT IN right-hand side from literal->getValue(),
    although each ConstantNode already owns a size-1 ColumnConst plus its exact type. They now
    build a ColumnTuple of the literals' own columns, as the AST path already does in
    buildCollectionColumnAndTypeFromASTFunction;

  - convertColumnToTypeOrNull round-tripped through a Field even when the conversion was the
    identity. It now returns the input column unchanged in that case. The predicate needs both
    IDataType::equals and matching type names: equals sees only the storage type, so it treats
    the custom-named UInt8 Bool as equal to UInt8 and would skip the strict validation that
    rejects a UInt8 of 10 for a Bool target, while a shared name does not pin the layout, since
    two AggregateFunction types can differ in hidden state representation;

  - a constant IN right-hand side is serialized with casts suppressed to keep the query small,
    so a shard received a bare literal and re-inferred its type. columnConstantToExactLiteralAST
    exists for exactly this problem (it was added for Decimal constants, whose literal rounds
    through Float64) and already has a Variant case, but its gate omitted isVariant, and the
    case named only the member type. The gate is widened and renamed
    typeNeedsExactLiteralSerialization, and a Variant value now names both its alternative's
    type and the Variant type. This also repairs a plain distributed comparison against an
    Array(Variant) constant, which previously failed with CANNOT_CONVERT_TYPE because the shard
    inferred Array(UInt8) from `[1]`.

No optimization is declined and no type screen is added: the rewrite becomes faithful rather
than being skipped, so the single-alternative Variant rewrite pinned by 04628 keeps firing.

A non-identity conversion into a Variant still goes through a Field, so `x IN (...)` can still
re-select an alternative when the constant's declared type differs from the column's. That is a
separate mechanism in convertFieldToType, present with no rewrite involved, and is left alone
here.

Related: ClickHouse#117637
…t` alternative

`tryConvertToColumnType` is the gate both chain seams consult before rewriting an
`OR`/`AND` chain into `IN`/`NOT IN`, and it exists to refuse a conversion that is
not lossless. It proves losslessness by converting the constant and converting it
back, comparing `Field`s - and a `Field` cannot record which `Variant` alternative
a value occupies, so the round trip lands on the same `Field` for a conversion that
changed the value, and the check passes. For `UInt8` `1` into
`Variant(Date, UInt64)` the forward conversion picks `Date`, the returned `Field`
is a bare `UInt64` `1`, and converting back to `UInt8` gives `1`.

Refuse instead when either side carries a `Variant` with more than one alternative,
or a dynamic structure, and the two types are not a named identity. This is a third
entry in the enumeration that function already carries alongside `DateTime64` scale
reduction and `DateTime` to `Date` truncation. Both operands are tested because the
erasure is symmetric: a `Variant` constant against a plain column loses its
alternative the same way, and there the rewrite admitted a row no disjunct matches,
or turned an `ILLEGAL_TYPE_OF_ARGUMENT` into an answer.

The refusal is placed before the existing `equals` early return, not after. That
return fires on bare `equals` while the coercion preserves only equals-and-name, so
a pair between the two boundaries would be admitted by the seam and not preserved
by the conversion. Writing the identity test the same way in both places gives the
two halves one definition: the seam admits a rewrite into a multi-alternative
`Variant` only for a type the coercion will preserve. An identical type still
returns earlier, so the case the previous commit fixes is unaffected, and a
single-alternative `Variant` keeps being rewritten.

Correction to the previous commit's message, which cannot be edited. It justified
comparing type names as well as types by claiming that a bare-`equals` fast path
would skip the `strict` `Bool` validation in `convertFieldToType`. That is wrong:
both entries of `convertFieldToType` short-circuit on the same `equals` test, so
the `Field` path performs no such validation either for an `equals`-true pair.

The conjunction is still required, for a different reason.
`DataTypeAggregateFunction::equals` compares normalized state types and never
compares the serialization version, which `getName` prints and which
`ColumnAggregateFunction::insert` enforces through the stamped type string. For an
`equals`-true, name-different pair of those the `Field` path therefore throws
`ILLEGAL_TYPE_OF_ARGUMENT`, while a bare-`equals` fast path would hand back a
column labelled with the other version, whose serialization is built from that
version. So `equals` answers "would the delegate change the value?" and the name
answers "are these two columns interchangeable?", and the early return needs both.
The source comment is corrected to say that.

Also scope the known-limitation paragraph in `convertColumnToType.h` to a
non-identity conversion. It promised that the legacy `Field` path had the exact
same limitation, so migrating a caller changed no behavior; after the identity
early return that is no longer true, and this helper is deliberately more faithful
than its `Field` twin for a `Variant` discriminator. The differential gtest already
records that exception, so all three places now say one thing.
Reporting `Variant` from `typeNeedsExactLiteralSerialization` made the branch below it dead.
That predicate is unconditionally true for a `DataTypeVariant`, so `toASTImpl` always returns
from the exact-serialization path above it and never reaches the member-type cast the branch
built. `columnConstantToExactLiteralASTImpl` performs that naming for every `Variant`, nested
or not, which is why the branch became redundant rather than merely unused.

The two includes the branch alone needed go with it, as does the sentence in
`columnConstantToExactLiteralASTImpl` that cross-referenced it as live code.

No behaviour change. The shard-side query text of the nine distributed shapes probed for this
fix is byte-identical before and after, including the top-level `Variant` constant, which still
carries exactly one `Variant` cast. `04613_variant_constant_folding_distributed`, which covers
this function for folded `Variant` constants, keeps its verdict.
…Variant` rewrite

`ReadFromRemote` is a second consumer of the exact literal serialization. A predicate pushed
down into a distributed subquery is rebuilt from the plan's own `ActionsDAG` rather than from
the query tree, and an `IN` never reaches that code because the `Set` node short-circuits to
its stored source AST, so a single `equals` is the only shape that exercises it. It had no
test: on the pristine base the shard receives a bare literal there and refuses the conversion
with `CANNOT_CONVERT_TYPE`.

The top-level `Variant` scenario asserted its answer only. The un-rewritten form gives the
same answer, so a change that declined the rewrite would leave the row green and silently stop
exercising the fix. The plan pin mirrors the one its `Array`-nested twin already carries, and
its oracle moves: the same `EXPLAIN` at `optimize_min_equality_disjunction_chain_length = 100`
counts zero `in` nodes.
…ant`-carrying types

This corrects the claim made by ad49bbf ("Do not lose the Variant discriminator when a
constant IN set is built or serialized"), whose message and whose header paragraph both said the
shortcut applies to any identity conversion. It does not need to, and applying it to every identity
conversion introduced a new defect of exactly the kind that commit removed.

A `Bool` is a custom-named `UInt8`, so a `Bool` column is a plain `ColumnUInt8` that can hold a byte
outside {0, 1}: `reinterpretAs` accepts `Bool` as a numeric reinterpret target and the
same-physical-type branch copies the byte through. The `Field` path clamps such a byte in
`retagBoolInField`, and the identity shortcut returned before it, so a set element built through the
shortcut kept the raw byte while the left-hand side was still normalized on its own path:

    SELECT reinterpret(toUInt8(2), 'Bool') = reinterpret(toUInt8(2), 'Bool'),                 -- 1
           reinterpret(toUInt8(2), 'Bool') IN (reinterpret(toUInt8(2), 'Bool'), false);       -- was 0

Only a type whose `Field` cannot record which `Variant` alternative a value occupies needs the
shortcut, so gate it on that. `Variant(Bool, UInt8)` is still admitted, because what the shortcut
exists to preserve there is the alternative selection and not the byte.

The three places that documented the wider scope (the header's purpose paragraph, its known-limitation
paragraph, and the differential test's contract comment) are narrowed to match.
…hey carry

Test-only. Three changes to 04628_logical_optimizer_in_rewrite_variant_type:

The direct `remote('127.0.0.1', ...)` row carried no query-level settings.
`prefer_localhost_replica` defaults to true, in which case that shard is answered by a purely
local plan and nothing is serialized, so the row degenerated into a duplicate of the plain
OR-chain row above it; and `clickhouse-test` randomizes the setting, so what the row covered
was a coin flip per run. Pin it to 0, as 04613_variant_constant_folding_distributed does on
every one of its rows.

Both shard-bound rows then asserted only a count that the initiator reproduces on its own, so
neither could tell a correctly serialized constant from no serialization at all. Read the
secondary query text out of `system.query_log` instead, following
01756_optimize_skip_unused_shards_rewrite_in. On the pristine base neither pattern matches: the
set arrives as `IN (['1970-01-02'], ...)`, the re-selected `Date` alternative rendered as text.
The assertion is therefore about the literal's content, not merely about the query succeeding.

Finally, a `Bool` row: an identity conversion of a type that carries no `Variant` keeps going
through the `Field` path, which clamps a raw byte, so `x IN (x, ...)` still agrees with `x = x`.
…line code

`.claude/CLAUDE.md` asks for literal names from the ClickHouse SQL language, classes and
functions to be wrapped in inline code blocks. Scoped to the comment lines this branch adds;
`Decimal` on the one adjacent pre-existing line is included so that the list it begins is not
left half formatted.
This branch carried two independent halves. The one that stays keeps
`tryReplaceOrEqualsChainWithIn` from rewriting a comparison chain whose constant
would re-select a different `Variant` alternative once the set element is
rebuilt from a `Field`.

The other half made a `Variant` constant nested in an `Array`, `Tuple` or `Map`
serialize exactly when it is sent to another server. My open PR ClickHouse#117831 already
does that, and does it more completely: both heads rename
`typeMayContainDecimal` to the same new `typeNeedsExactLiteralSerialization` in
the same four files, both add `isVariant` to it, and both delete the same
`DataTypeVariant` branch of `ConstantNode::toASTImpl`, so whichever merged
second would conflict on every shared file.

The copy here was also the weaker one. Three cases it got wrong and ClickHouse#117831
does not:

* a NULL alternative was written as a bare `Null` literal, so a NULL `Variant`
  `Map` key reached the receiver as `Nullable(Nothing)` and was refused;
* a numeric-looking `String` alternative was re-selected as `UInt64` on the
  receiver, because casting a string to a multi-member `Variant` infers which
  member it means;
* a `DateTime` alternative was rendered as ambiguous local text and lost the
  DST-overlap hour: 1698541800 read back as 1698538200.

`src/Analyzer/ConstantNode.cpp`, `src/Analyzer/Utils.cpp`,
`src/Analyzer/Utils.h` and `src/Processors/QueryPlan/ReadFromRemote.cpp`
therefore return to their pre-branch state byte for byte. The two shard-bound
queries in `04628` and the `system.query_log` assertion that covered them go
with them. The sixteen remaining rows still separate this fix from the pristine
base on eight of them, and every labelled control is identical on both arms.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 4 rounds, no open findings

⚠️ major, fixed. A blanket identity fast path in convertColumnToTypeOrNull also skipped the
clamp that normalizes a raw Bool byte, so reinterpret(toUInt8(2), 'Bool') IN (itself) went
false. Narrowed to Variant-carrying types, and Variant(Bool, UInt8) still takes it; the row is
committed.

⚠️ major, fixed. Two rows asserted only a count that the un-rewritten chain also produces, so a
silently declined rewrite would have passed. Both now pin the plan.

❌ blocker, fixed. The branch also carried the serialization half of this defect, which is my own
#117831 and a thinner copy of it. Withdrawn: those four files are byte-identical to the merge base
again.

💡 declined, with evidence. A notIn plan pin for the AND row: #117637 removes that merge for
a self-typed value deliberately, so the pin would assert a rewrite that is on its way out.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ab52dd2]

Summary: ✅


AI Review

Summary

This PR preserves type-selected Variant alternatives when constructing constant IN sets, carries constants as columns through comparison-chain rewrites, and declines rewrites that cannot preserve comparison semantics. No actionable findings remain at head ab52dd20e00388a8d1bfe16dff237fedf5341c4f. The documented nested Nullable limitation is an accepted scope decision.

Final Verdict

Status: ✅ Approve. The 52-row regression test matches its reference using the head's fast-test binary; additional probes cover multi-column sets, array collections, values, and optimizer boundaries. No new inline comments or thread changes are needed.

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

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @Avogar, could you review this? A Field cannot record which Variant alternative a value occupies, so the OR-to-IN rewrite's tuple and the set coercion both re-selected one by value and x IN (x, ...) went false where x = x is true; the tuple now carries each constant as its own column, and the rewrite refuses when the two types are not a named identity.

The `Variant` identity fast path this branch adds to `convertColumnToTypeOrNull`
returns the local `full` directly, and a `const` local cannot be moved from, so
that return bumps the reference count instead of moving the pointer.
`performance-no-automatic-move` reports it, `.clang-tidy` sets
`WarningsAsErrors: '*'`, and `Build (arm_tidy)` therefore failed with
`constness of 'full' prevents automatic move`.

The `const` itself predates this branch. Master never returns that local, so the
check had nothing to fire on until the fast path was added; only the new return
made the qualifier observable.

Verified with the pinned clang-tidy against the existing compile database: one
error before, none after, and the file's total diagnostic count drops by exactly
one, so no other check took its place. `misc-const-correctness` is disabled in
`.clang-tidy`, so dropping the qualifier draws no counter-diagnostic.
…comment

ClickHouse contributions use plain ASCII punctuation, and this was the only
non-ASCII character this branch adds.
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ab52dd20e with master 5a33e4237 (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

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

Job report

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

Avogar commented Sep 16, 2026

Copy link
Copy Markdown
Member

The defect is real, and carrying each constant as its own column at the two chain seams is the right change — that matches what buildCollectionColumnAndTypeFromASTFunction already does on the AST path. My concern is the other two changes: I think they can both be replaced by one, and that the replacement is strictly better.

For a Variant target a Field is not merely lossy — it cannot express the result at all. Every success path of the DataTypeVariant branch in convertFieldToType is return src;. The alternative is not chosen there; it is chosen afterwards, by ColumnVariant::tryInsert inside column->insert(converted) at the end of convertColumnToTypeOrNull, which scans alternatives in sorted order and takes the first one that accepts the value. The comment in that branch says this explicitly, and calls a lossless tryInsert selection out of scope. This is why fixing the inputs cannot work: #117998 already passes the active alternative down as the source type, and the defect survives it, because the loss is on the target side of the conversion.

So I would like the fix to be a column-native branch for a Variant target in convertColumnToTypeOrNull, next to tryConvertNumericColumnNative. castColumn needs no Context, and it selects the alternative by type rather than by value — and it selects the exact one, which is better than what the Field path does even when the discriminator happens to survive:

SELECT variantType(CAST(1::UInt64, 'Variant(Date, UInt64)'));           -- UInt64 (the Field path picks Date)
SELECT variantType(CAST(1.1::Float64, 'Variant(Float32, Float64)'));    -- Float64 (the Field path stores it lossily in Float32)
SELECT accurateCastOrNull('abc', 'Variant(Date, UInt64)') IS NULL;      -- 1, so the "not representable" contract holds

That one branch subsumes both workarounds here. The identity fast path in convertColumnToTypeOrNull becomes unnecessary, and with it typeCarriesVariantAlternative, alternativeIsNotRecoverableFromField, the from->getName() == to->getName() conjunct and the comment explaining why the two near-twin predicates are deliberately not shared. The refusal added to tryConvertToColumnType becomes unnecessary too, so the OR-to-IN rewrite keeps firing for Variant columns instead of being declined.

It also fixes a case this PR leaves wrong. The refusal stops the optimizer from producing the broken shape, but the shape is still reachable by hand, so after this PR the two spellings of one predicate disagree:

SELECT count() FROM (SELECT materialize(1::UInt64::Variant(Date, UInt64)) AS v) WHERE v = 1 OR v = 5 OR v = 7;  -- 1, rewrite now declined
SELECT count() FROM (SELECT materialize(1::UInt64::Variant(Date, UInt64)) AS v) WHERE v IN (1, 5, 7);           -- still 0

One thing I would drop from the framing regardless of how the fix is written: x IN (x, ...) agreeing with x = x is not an invariant that holds for Variant, so please don't state it as the contract being restored. = promotes both operands to a supertype, while a set keys on discriminator plus value, and those are different relations:

SET allow_suspicious_variant_types = 1;
SELECT materialize(42::UInt64::Variant(UInt8, UInt64)) = 42::UInt8::Variant(UInt8, UInt64);                      -- 1
SELECT v IN (SELECT 42::UInt8::Variant(UInt8, UInt64)) FROM (SELECT materialize(42::UInt64::Variant(UInt8, UInt64)) AS v);  -- 0

The narrow defect — an identity constant getting re-tagged to a different alternative on its way into the set — is worth fixing on its own terms, and the wording can say just that.

Smaller points, independent of the above:

  • The new check in tryConvertToColumnType is placed before the equals early return, so it also changes optimize_redundant_comparisons, which the description mentions but no test covers.
  • gtest_convert_column_to_type has no Variant case at all, so the added comment documents an exception to a contract that the table never exercises. A positive case asserting the discriminator survives would be worth more than the comment.
  • The reference file is sixteen unlabelled 0/1 rows. When one of them flips in CI there is no way to tell which shape broke; a label per row would fix that.
  • Per the repo guidance, a new test file is preferred over extending an existing one.

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

See the comment above

A `Field` cannot express a `Variant` result: every success path of
`convertFieldToType`'s `Variant` branch returns the value unchanged, and the
alternative is chosen only when the value is inserted into a `ColumnVariant`,
by the first one that accepts it. A constant stored as `UInt64` was therefore
re-tagged to `Date` on its way into the set of an `IN` over a
`Variant(Date, UInt64)` expression, and stopped matching the row it was built
from. Fixing the input side cannot help, because the loss is on the target side
of the conversion.

Convert to a `Variant`-carrying target column-natively instead, with
`castColumn`, which chooses the alternative by type and chooses the exact one.
That one branch replaces both workarounds this PR carried before: the identity
fast path in `convertColumnToTypeOrNull` with its `typeCarriesVariantAlternative`
predicate, and the near-twin predicate in `LogicalExpressionOptimizerPass`, whose
refusal now calls one shared `conversionPreservesVariantAlternative`. It also
fixes shapes the previous form left wrong: a constant that merely names an
alternative (`v IN (1::UInt64)`) now keeps `UInt64` rather than being re-tagged
to `Date`, and consequently stops matching a row that holds `Date`; so does a
`Variant` constant whose type the expression's type extends.

The `OR`-chain to `IN` rewrite still declines a multi-alternative `Variant`, and
now does so through one shared check rather than a predicate of its own. That is
not a `Field` limitation: `equals` on a `Variant` is evaluated against each row's
active alternative, so it matches a numerically equal value under a different one
and throws where the two are not comparable, while a set element keys on one
discriminator. Comparison pruning keys the constants by `Field` for the same
reason, where two alternatives collide and one of two mutually exclusive
conditions was dropped.

Tests: the cases move out of `04628_logical_optimizer_in_rewrite_variant_type`
into their own file with one label per row, and
`gtest_convert_column_to_type` gains the positive `Variant` case it had none of,
asserting the discriminator on both the column path and the `Field` twin.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Reworked. Thanks, the column-native branch is clearly the right shape.

1. The Variant branch (done). convertColumnToTypeOrNull now converts a Variant-carrying target with castColumn. The identity fast path, typeCarriesVariantAlternative, the from->getName() == to->getName() conjunct and its comment are gone. It admits an identity conversion at any depth, a source type that names an alternative, and a Variant source the target extends (createVariantToVariantWrapper's extension rule). Two details worth recording: the source has to be normalized exactly as createColumnToVariantWrapper normalizes it, or an ordinary LowCardinality constant turns a working query into CANNOT_CONVERT_TYPE; and castColumnAccurateOrNull is not usable here at all, because it wraps the target in Nullable, which Array(Variant(...)) rejects.

It fixes more than the reported shape: v IN (1::UInt64) goes 0 to 1 on a UInt64 row and 1 to 0 on a Date row, and v IN (1::UInt64::Variant(UInt64)) goes 0 to 1.

2. The refusal in tryConvertToColumnType has to stay, for the reason in your last paragraph. On the pristine base, where no refusal exists, with v = materialize(1::UInt64::Variant(Date, UInt64)):

SELECT count() FROM ... WHERE v = 1 OR v = 5 OR v = 7;  -- 0
SELECT count() FROM ... WHERE v = 1 OR v = 5 OR v = 7
SETTINGS optimize_min_equality_disjunction_chain_length = 100;  -- 1

equals is evaluated against each row's active alternative: it matches a numerically equal value under a different one (Variant(UInt8, UInt64) holding UInt8 42 matches 42::UInt64), and throws where the two are not comparable (materialize(toDate(1)::Variant(Date, UInt64)) = 1 gives Illegal types of arguments (Date, UInt8) of function equals). A set element keys on one discriminator, so a faithful conversion is not sufficient and no constant makes the rewrite equivalent. What I did instead is collapse it to ONE check, fieldCanLoseVariantAlternative, called once; alternativeIsNotRecoverableFromField is gone.

That also closes the case you named, in the other direction: v IN (1, 5, 7) still answers 0 while the chain answers 1, and I am not making the set chase equals for the reason you give. And the identity carve-out I had here was itself wrong for comparison pruning, which keys the constants by Field: WHERE v != toDate(1)::Variant(Date, UInt64) AND v != 1::UInt64::Variant(Date, UInt64) over rows (toDate(1)), (1::UInt64) dropped one condition and kept a row that both exclude. The single check covers that caller too, which answers your optimize_redundant_comparisons point with a test.

3. Framing dropped from the description, the changelog entry and the test comments.

Also: gtest_convert_column_to_type gains the positive Variant case, asserting the discriminator on the column path and on the Field twin; the reference rows are labelled (29 of them, 15 of which move); and the cases live in their own file now instead of extending 04628_....

One thing left unfixed on purpose: a non-identity conversion into a nested Variant (an Array(UInt64) constant into Array(Variant(Date, UInt64))) still goes through the Field path, since the branch would have to recurse through the structural wrappers. It is not a regression and the optimizer no longer produces that shape, but say so and I will extend it here.

@Avogar

Avogar commented Sep 17, 2026

Copy link
Copy Markdown
Member

@groeneai resolve conflicts

Two conflicts in `convertColumnToType`, both because ClickHouse#117837 landed
`resolveActiveAlternativeType` on master after this branch was cut. That change
reads the active alternative's type back from a `Variant`/`Dynamic` column and
passes it as the source type of the delegated `convertFieldToType`, so a
`Variant` SOURCE is now faithful. This branch is the other direction, a `Variant`
TARGET, and both are kept: the anonymous namespace now holds
`resolveActiveAlternativeType` alongside `carriesAmbiguousVariant`,
`variantAlternativeIsChosenByType` and `tryConvertVariantColumnNative`, and
`convertColumnToTypeOrNull` runs the column-native `Variant` path before falling
back to the `Field` path that resolves the alternative.

The header's two paragraphs conflicted for the same reason: this branch still
carried the pre-ClickHouse#117837 claim that a `Variant` source is unrecoverable, which is
now false. Master's paragraph and its `Array(Dynamic)` composite limitation are
kept, the stale claim is dropped, and the `Variant` target divergence stays.

The rewrite in `LogicalExpressionOptimizerPass` merged cleanly on top of ClickHouse#117854,
which renamed the `in` family the passes emit by `transform_null_in`; the merged
sites keep that name lookup.

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

Copy link
Copy Markdown
Collaborator Author

Conflicts resolved in af2a067, mergeable is back to MERGEABLE.

Both were in convertColumnToType, and both came from #117837 landing on master after this branch was cut. That change resolves a Variant/Dynamic source to its active alternative's type before delegating to convertFieldToType; this branch is the other direction, a Variant target whose alternative CAST picks by type. I kept both: resolveActiveAlternativeType now sits next to carriesAmbiguousVariant, variantAlternativeIsChosenByType and tryConvertVariantColumnNative, and the column-native path runs before the Field fallback that resolves the alternative. The header conflicted for the same reason, since this branch still carried the pre-#117837 claim that a Variant source is unrecoverable; I dropped that claim and kept master's paragraph and its Array(Dynamic) limitation. The LogicalExpressionOptimizerPass rewrite merged cleanly on top of #117854 and keeps its transform_null_in name lookup.

Checked on the merged tree: it differs from master by exactly this PR's 6 files, 05056_variant_discriminator_in_constant_set and 05060_enum_in_variant_dynamic_in_set pass, the 157-test variant/logical_optimizer/in_rewrite family shows 8 failures that a pristine master binary reproduces identically under the same minimal server config, and unit_tests_dbms --gtest_filter=ConvertColumnToType* is 3/3 including the differential oracle against convertFieldToType.

Unrelated, just noting it: Variant(LowCardinality(String), UInt64) rejects IN in every spelling I tried, v IN (1::UInt64) included, with Cannot convert type String to Variant(...). A master binary without this branch throws the same on all six probes, so it is pre-existing and not something this change reaches.

`04489_values_float32_conversion_and_in` pinned the pre-existing selection as a
scope limitation: a directly-insertable field went to the first alternative that
accepted it, chosen by `ColumnVariant`'s insertion order, so `toFloat64(16777217)`
into `Variant(Float32, Float64)` was stored in the sorted-first `Float32` and
rounded to 16777216. The conversion now resolves the alternative by type, so the
value stays exact in `Float64`. Measured on both arms: master answers
`16777216 Float32`, this branch answers `16777217 Float64`, and
`toFloat32(16777217) = 16777217` is 0, so `Float32` genuinely cannot hold it.

The section header and its comment described the old rule, so both name the new
one instead. Nothing else in that test moves; its single-alternative
`Variant(Float64)` TYPE_MISMATCH row and both fall-through rows are unchanged.

Also backtick `CAST` in one comment of the new test, per the repository's rule
that literal SQL names in comments are inline code.

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

Copy link
Copy Markdown
Collaborator Author

Follow-up on the merge: Fast test went red on af2a067, on 04489_values_float32_conversion_and_in, and it turned out to be this change fixing a case that test pinned as out of scope. Fixed in fb92e890.

One row moved:

SELECT x, variantType(x) FROM values('x Variant(Float32, Float64)', toFloat64(16777217))
  SETTINGS allow_suspicious_variant_types = 1;

master        16777216   Float32
this branch   16777217   Float64

16777217 = 2^24 + 1 is exact in Float64 and not in Float32 (toFloat32(16777217) = 16777217 is 0), so the old row was silently rounding. That test's own comment described it as pre-existing ColumnVariant insertion order and said reworking the selection was "outside the scope of this fix"; resolving the alternative by type is that rework for the type-named case, so I updated the row, the section header and the comment, and listed the case in the PR description.

Also corrected the description: #117831 merged this morning, so it is no longer described as open.

The rest of the head is unchanged from af2a067; both tests pass locally and check_style.py is 14/15 with only settings_changes_history, which needs the CI changed_files hook.

`variantAlternativeIsChosenByType` admitted a top-level `Variant` target only, so a constant
whose `Variant` sits under a structural wrapper kept going through the `Field` path and lost
its alternative there:

    SELECT count() FROM (SELECT materialize([1::UInt64]::Array(Variant(Date, UInt64))) AS a)
    WHERE a IN ([1::UInt64]);   -- 0, on the row the set element was built from

`CAST` converts `Array`, `Map` and `Tuple` element-wise, so the admission question applies to
each element pair, and asking it per pair admits exactly what `CAST` can place by name: a
nested source type that names no alternative throws there (`Array(String)` gives
`INCORRECT_DATA`, `Array(UInt8)` gives `CANNOT_CONVERT_TYPE`), and those keep going through
the `Field` path as before.

Two tuples that both name their elements are the one asymmetry: `CAST` pairs them by name
(dropping and default-filling what does not match) while `convertFieldToType` pairs them
positionally, so `Tuple(a UInt64, b UInt64)` into `Tuple(b Variant(Date, UInt64), a UInt64)`
would be silently reordered. Such a pair is refused, and the new differential case in
`gtest_convert_column_to_type` fails when that guard is removed.

Measured against the previous head of this branch and against master, one server per arm:
8 of the 9 new rows in `05056_variant_discriminator_in_constant_set` flip, including the two
that must go the other way (a `Date` row stops matching a `UInt64`-typed element, in an
`Array` and in a `Map`); the nested `no-such-alternative` control does not move. A 220-test
`variant|logical_optimizer|redundant_comparis|in_rewrite|or_chain|equality_disjunction` sweep
is 195 OK, and each of its 14 failures reproduces with the same reason on the arm without this
change. `ConvertColumnToType*` 4/4, and 50 randomized runs of the new test are 50 OK.

Reported at ClickHouse#117959 (comment)
`variantAlternativeIsChosenByType` asked its question only of a `Variant`, `Array`, `Map` or
`Tuple` target, so a `Nullable` wrapper on the target side kept the conversion on the `Field`
path: `Array(Tuple(UInt64))` into `Array(Nullable(Tuple(Variant(Date, UInt64))))` rebuilt the
element from a `Field`, `ColumnVariant::tryInsert` took the first alternative that accepts it
(`Date`), and the set element stopped matching the row it was built from.

A `Nullable` target adds a NULL flag over a conversion `CAST` performs unchanged, so descend
through it. Measured on the wrapper spellings, previous head versus this one:

  Array(Nullable(Tuple(Variant(Date, UInt64))))        IN   0 -> 1
  Tuple(Nullable(Tuple(Variant(Date, UInt64))))        IN   0 -> 1
  Map(String, Nullable(Tuple(Variant(Date, UInt64))))  IN   0 -> 1
  Nullable on both sides, and two Nullable layers      IN   0 -> 1
  a Date-holding row against a UInt64-spelled constant IN   1 -> 0
  a NULL element, and a constant naming no alternative IN   0 -> 0

`Nullable(Variant(...))` itself is not a reachable shape: `DataTypeVariant::canBeInsideNullable`
is false, so it is refused with ILLEGAL_TYPE_OF_ARGUMENT before any conversion runs. Only a
composite that carries a `Variant` can sit inside `Nullable`, which is what the descent reaches.

`castColumnAccurateOrNull` remains unusable on this path for the same reason as before: it wraps
the target in `Nullable`, which `Array(Variant(...))` rejects.

The same commit closes a NULL hole this native path opened earlier. The alternative lookup strips a
source `Nullable`, so a typed NULL constant such as `CAST(NULL, 'Nullable(Tuple(UInt64))')` qualified
for a `Tuple(Variant(Date, UInt64))` target, and `castColumn` answered the actual NULL with
`CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN` instead of the "not representable" the caller's contract asks
for, so an `IN` that master answers with 0 failed the whole query. A `Nullable` source position is now
followed only where the target at that position holds a NULL of its own, which is a property of the
types rather than of the row, so a NULL nested under `Array`, `Map` or `Tuple` is covered as well:

  Tuple(Variant(Date, UInt64))        IN (CAST(NULL,   'Nullable(Tuple(UInt64))'))
  Array(Tuple(Variant(Date, UInt64))) IN (CAST([NULL], 'Array(Nullable(Tuple(UInt64)))'))
  Map and Tuple spellings of the same nested shape
    master 0, previous head CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN, this head 0

A `Variant` target still takes the native path for a `Nullable` source, since it holds a NULL through
its own discriminator, which is what keeps `in-nested-nullable-element` on the column path.

Eight rows in `05056_variant_discriminator_in_constant_set`. Four answer differently without the
descent, and the two NULL-constant rows abort the file on the previous head; the `equals` row is the
ground truth for the `IN` above it, and the row holding the other alternative must not match either
way.

The two `pruning-different-alternatives` rows in the same file read their two `Variant` values
through `VALUES`, whose constants take the same `Field` path the rows are meant to pin, so both
answered 0 with and without the fix and pinned nothing. Reading them from a `UNION ALL` of two
materialized `Variant` values keeps them on `fieldCanLoseVariantAlternative`: master answers 1,
this branch 0. The header count moves with it, 29 of 46 rows now answer differently without the
fix (measured against master `bdd39260f887d`).

Comments in the non-test diff go from 49 to 38 added lines: out go a call-site paragraph that
repeated the `fieldCanLoseVariantAlternative` declaration doc, two references to the `CAST`
wrapper builders by name, a `Returns std::nullopt` sentence the signature already states, and one
sentence derivable from the recursion directly below it. What is left states properties of
`CAST`, `Field` and `Variant` that a reader cannot derive from the code.
groeneai and others added 2 commits September 18, 2026 06:07
`variantAlternativeIsChosenByType` refuses a `Nullable` source whenever the target cannot hold a
NULL of its own, because `CAST` throws `CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN` there while the
`Field` path answers "not representable". That predicate is type-level, so it cannot tell a NULL row
from a row that merely has a nullable declared type, and it refused both. A constant such as
`CAST(tuple(1::UInt64), 'Nullable(Tuple(UInt64))')` therefore went back to `convertFieldToType`,
whose tuple recursion drops the source-type hint, so the `Tuple(Variant(Date, UInt64))` element was
rebuilt under `Date`.

That lost the match against the row the constant was built from, and, because a rebuilt element
lands in the first alternative that accepts it, invented one against a row holding the other:

    SELECT count() FROM (SELECT materialize(CAST(tuple(toDate(1)), 'Tuple(Variant(Date, UInt64))')) AS t)
    WHERE t IN (CAST(tuple(1::UInt64), 'Nullable(Tuple(UInt64))'));   -- answered 1, must be 0

`tryConvertVariantColumnNative` holds the value, so the outermost `Nullable` is now decided by the
row: a non-NULL row has no NULL for `CAST` to place anywhere. The levels below it have no value
there and keep the type-level refusal, which is exactly what a purely row-level test would have
missed: deciding this from `value.isNullAt(0)` alone still threw for an
`Array(Nullable(Tuple(UInt64)))` holding `[NULL]`, since that row is not NULL at the outer level.

Six rows in 05056: the two positives, the `equals` ground truth, the other-alternative false match,
a nested NULL that the target accepts only through a `Variant` discriminator, and a plan assertion
that the `notEquals` chain above is declined, so that row's 0 cannot come from a `notIn` that merely
agrees with it. Against pristine master `bdd39260f887d`, 33 of the 52 rows now answer differently;
against the previous head exactly these three move, and the two NULL-constant contract rows added in
that head stay put.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 87fd111

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link
will be posted here when it opens.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 5/6) / iceberg_suite_tpch.query4.run0 perf-harness per-query cap, not a perf regression from this PR: TPC-H Q4 over the tpch_ice10 Iceberg dataset took 15482.017 ms against max_query_seconds = 15000 ms, so the driver raised Code: 159 and the single run-error reddened the whole shard a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)
Mergeable Check, PR aggregate roll-ups of the row above, no independent failure of their own a fix task is moved to pending (same owner)

Notes on the attribution, since the report hides the real message:

  • The report's Run Errors table shows only 10 traceback lines and the status text says 10 errors. That is the compare.sh reporting defect (a failing test falls through to head -10 of its error log), so the actual Code: 159 line sits on line 11 and never reaches the report. I read it out of iceberg_suite_tpch-err.log inside the job's logs.tar.zst.
  • The 3 too long entries (codecs_multiple_select, polymorphic_parts_m, group_by_dynamic_keys) are not what reddens the shard: green runs of this same shard carry 3 too long more than 190 times in the last two days. Only the N errors prefix reddens it.
  • Not attributable to my diff: this PR changes LogicalExpressionOptimizerPass.cpp and convertColumnToType.{cpp,h}, none of which is reachable from a TPC-H query's wall-clock over an Iceberg table. The same shard is red with the same status text on true master and on 58 other pull requests today.
  • Give the array_join String benchmark a sink so it measures replication, not its result transfer #119215 is merged and already present on this head, but it shortened only the array_join carrier query, so it does not cover this one. I am not linking it as the owner.

Session id: cron:our-pr-ci-monitor:20260918-143348

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 5/6) red

Fixing PR: #120923 (external, open). It is a plain git revert -m 1 of #120176
"Join reordering: FK->PK heuristic for equi joins without NDV statistics", which merged at
2026-09-17T21:10Z. Root cause and a repro against the public Iceberg dataset are in #120921.

This was not a harness-cap artifact, and my earlier ledger line was wrong on two counts. Query index 4
of iceberg_suite_tpch is TPC-H Q5, not Q4, and its 14-day CIDB p50 on that shard is 351 ms
with a max of 409 ms over 662 samples and zero runs over the 15 s cap. It only began timing out after
#120176 reached master, on both arches: master commit afac120af1f6 failed on amd_release 2/6 at
elapsed 15000.750 ms and on arm_release 5/6 at elapsed 15289.156 ms, same query, same frames. So
the Code: 159 reported a real >40x planner regression on relations that have no row estimate rather
than a fixture that had outgrown the cap.

One caveat for reading this shard afterwards: the bad plan needs the hash-table statistics cache to be
populated by the prewarm run first, so the failure is intermittent. On 2026-09-18 the master runs were
18 red of 27 on amd_release 2/6 and 9 red of 25 on arm_release 5/6. A single green run of the shard
is therefore not evidence the red is gone.

Nothing is needed on this PR until #120923 lands. After it lands the way to pick it up here is to merge
master into this branch; a bare re-run reuses the original merge ref and would test the unreverted tree.

@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Dear @Avogar, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

# Conflicts:
#	src/Interpreters/convertColumnToType.cpp
#	src/Interpreters/convertColumnToType.h
#	src/Interpreters/tests/gtest_convert_column_to_type.cpp
@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 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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-review-human PR origin: human review feedback on a groeneai PR 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