Repository navigation
Conversation
… 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.
Internal second-model review: 4 rounds, no open findings
❌ blocker, fixed. The branch also carried the serialization half of this defect, which is my own 💡 declined, with evidence. A |
|
Workflow [PR], commit [ab52dd2] Summary: ✅
AI ReviewSummaryThis PR preserves type-selected Final VerdictStatus: ✅ Approve. The 52-row regression test matches its reference using the head's fast-test binary; additional probes cover multi-column sets, array collections, |
|
cc @novikd @Avogar, could you review this? A |
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units20 translation units recompiled, 121 s compile time in total, 20 of them have a recent master baseline. |
|
The defect is real, and carrying each constant as its own column at the two chain seams is the right change — that matches what For a So I would like the fix to be a column-native branch for a 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 holdsThat one branch subsumes both workarounds here. The identity fast path in 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 0One thing I would drop from the framing regardless of how the fix is written: 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); -- 0The 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:
|
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.
|
Reworked. Thanks, the column-native branch is clearly the right shape. 1. The It fixes more than the reported shape: 2. The refusal in 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
That also closes the case you named, in the other direction: 3. Framing dropped from the description, the changelog entry and the test comments. Also: One thing left unfixed on purpose: a non-identity conversion into a nested |
|
@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]>
|
Conflicts resolved in Both were in Checked on the merged tree: it differs from master by exactly this PR's 6 files, Unrelated, just noting it: |
`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]>
|
Follow-up on the merge: Fast test went red on One row moved: 16777217 = 2^24 + 1 is exact in Also corrected the description: #117831 merged this morning, so it is no longer described as open. The rest of the head is unchanged from |
`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.
`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.
CI finish ledger - 87fd111Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link
Notes on the attribution, since the report hides the real message:
Session id: cron:our-pr-ci-monitor:20260918-143348 |
Fixing PR for the
|
|
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
…inator-in-constant-set
Related: #117637
Related: #117831
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results for a set built from
Variantconstants, including where theVariantis 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 declaredUInt64was compared as aDate: it stopped matching the rows it was built for, and matched rows holding another one. At default settings theOR-to-INrewrite produces such a set, so a three-disjunctORchain dropped a row its first disjunct matches, and anANDofnotEqualskept an excluded row.Description
Reported by @ zlareb1 on #117637, reworked to @ Avogar's review. At default settings, no chain, no rewrite:
Root cause. A
Fieldcannot express aVariantresult:convertFieldToType'sVariantbranch returns the value unchanged, and the alternative is chosen only on insertion into aColumnVariant, by the first one that accepts it.The change. Convert to a
Variant-carrying target column-natively, withcastColumn, which chooses the alternative by type: an identity conversion, a source naming an alternative, and aVariantsource the target extends, element-wise underArray,Map,Tupleand a target-sideNullable. ANullablesource 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 theFieldpath, as on master. Both chain seams carry each constant into the tuple as its own column, not aField.Why the rewrite still declines a multi-alternative
Variant. No fixed set element reproduces such a comparison:equalsis 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
ORchain 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)intoVariant(Float32, Float64)landed inFloat32, rounded to 16777216; it now takesFloat64.Overlap with other open PRs
#117831 (mine) carried the serialization half of this defect: a
Variantconstant 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
convertColumnToTypeOrNullfor performance. This PR no longer has one, so the two no longer overlap textually; that fast path has to keep aVarianttarget 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]