Repository navigation
Use the active Variant/Dynamic alternative as the source type of a constant conversion - #117998
Conversation
…nstant conversion An Enum8/Enum16 constant wrapped in Variant or Dynamic and compared against a String or FixedString column converted to the enum's underlying number instead of its name, so `IN` matched the wrong row, `NOT IN` was inverted, and key analysis pruned on the wrong value. `=` on the same constant was already correct, which is what showed this to be a bug rather than a convention. `convertColumnToTypeOrNull` reconstructs a Field from the constant's column and delegates to `convertFieldToType`. `ColumnVariant::get` returns the nested column's value and drops the discriminator, and `ColumnDynamic::get` delegates to it, so the Field no longer records which alternative was active while the source-type argument handed down is still the carrier's type. Every conversion in `convertFieldToType` that is keyed on the source type therefore took the wrong branch: the Enum-to-name case added by ClickHouse#112647 tests the hint with `dynamic_cast<const IDataTypeEnum *>`, which fails for `Dynamic`, so the value was rendered as its number. Read the alternative's type back from the column, which still records it, and pass that as the source type at both delegation points. `ColumnDynamic` exposes `getTypeAt`, covering the regular and the shared-variant storage; `ColumnVariant` stores no types of its own, so its global discriminator is resolved against the `DataTypeVariant` the caller already supplies. That also makes an ambiguous variant such as `Variant(Bool, UInt8)` faithful, which the header previously documented as impossible: it is impossible for the Field, not for the column. Fixed by the same change, each verified against the equivalent String-literal result: `NOT IN`, a set built from a collection element, a `FixedString` target, the shared-variant storage of `Dynamic`, `Bool` under `Variant`, and a `Date`/`DateTime` bound wrapped in `Dynamic`, which previously matched nothing at all. Pruning is preserved rather than traded for correctness.
…sed carriers The set-construction cell built its right-hand side as an array literal, `v IN ([CAST(... AS Dynamic)])`. That parses as a call to `array` rather than as a collection of literals, so the legacy analyzer routes it to `buildCollectionColumnAndTypeFromASTFunction`, whose `array` branch takes `getLeastSupertype` of the element types - `Dynamic` for a single `Dynamic` element - and converts each element to it. That identity conversion rebuilds the value from a bare `Field`, and `ColumnDynamic` re-infers `Int8` from it, so the alternative is gone before the set is built. Measured: with the fix the array form returns `'7'` under the new analyzer and still `'3'` under the legacy one, so the cell could only ever have passed in one of the two jobs. The `tuple` branch of the same helper constructs the column directly with no conversion, so building the right-hand side as a list holds in both. Pin both analyzers inside the test rather than relying on the one job that still runs the legacy one, and pin the four behaviours the changelog entry promises but nothing asserted: `Enum16`, a `LowCardinality(String)` target, `Bool` under an ambiguous `Variant(Bool, UInt8)`, and a `Date` bound from a `Dynamic`-wrapped `DateTime`. A further cell keeps a `UInt8` in that same ambiguous variant rendering as a number, so the conversion is shown to follow the active alternative rather than to coerce every `Bool`-shaped value. Correct one claim from the previous commit. It described `values` with a `Dynamic` argument as beyond reach because a `Field` round trip somewhere upstream re-infers the type. The round trip is specifically the new analyzer's re-emission of resolved table-function arguments, where the `Dynamic` branch of `columnConstantToExactLiteralASTImpl` deliberately emits the active member's bare literal without naming its type. Under the legacy analyzer there is no such re-emission and the same query is fixed, which is what tells the two explanations apart. The description now scopes the claim accordingly. The header's known limitation named `Array(Dynamic)` as the unfaithful shape, which reads as contradicting the array cell above; it names the entry condition instead, a conversion whose source is itself a composite over the carrier. No behaviour change here: `resolveActiveAlternativeType`, both of its call sites and the `retagBoolInField` argument are untouched, and the only source edits are comment text, so the linked binary is byte-identical to the previous commit's.
Internal second-model review (2 rounds, 2 independent gate runs; click to expand)Reviewed cold by a second model before publication, then re-reviewed after one fix round. ❌ Accepted and fixed (round 1)
💡 Noted, not blocking
One correction to my own round-1 report: I stated the added-comment count in the source diff as 13 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260903-231200 |
|
Workflow [PR], commit [d606e7e] Summary: ✅
AI ReviewSummaryThis PR fixes the local Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit d606e7e.
Changed lines: Changed C/C++ lines covered: 22/22 (100.00%) · Uncovered code |
|
cc @yakov-olkhovskiy @CurtizJ, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 6 s compile time in total, 7 of them have a recent master baseline. |
| retagBoolInField(field, from); | ||
| /// `get` keeps neither the `Bool` tag nor the active `Variant`/`Dynamic` alternative; restore both so | ||
| /// the delegated `convertFieldToType` behaves as it would for a genuine value of the constant. | ||
| const DataTypePtr source = resolveActiveAlternativeType(unwrapped, from); |
There was a problem hiding this comment.
This only fixes the local Field reconstruction path. Remote execution still round-trips the same Dynamic constant through query_tree->toAST() (src/Interpreters/InterpreterSelectQueryAnalyzer.cpp:342, :351), and that serialization still drops the active subtype: ConstantNode::toASTImpl falls back to getFieldFromColumnForASTLiteral, so Dynamic(Enum8('7' = 3)) becomes 3, and Dynamic(DateTime('UTC')) becomes a bare string / _CAST(..., 'Dynamic') instead of a DateTime. Shards then build the IN set from the wrong source type and reproduce the old wrong-row / wrong-bound behavior on distributed or parallel-replica plans.
This needs the AST round-trip fixed as well, plus a remote/distributed regression that exercises query_tree->toAST() instead of keeping the read local.
There was a problem hiding this comment.
Confirmed for Dynamic, refuted for Variant. Measured on this head (d606e7e, build a8dc16c5) against pristine master e568d262 (build 0ccba595), with prefer_localhost_replica = 0 so the shard query is really serialized and re-parsed.
Shard-facing text, read from the secondary executeQuery line under --send_logs_level=trace:
Dynamic + Enum8: IN _CAST(3, 'Dynamic')
Variant + Enum8: IN _CAST(_CAST(3, 'Enum8(\'7\' = 3)'), 'Variant(Array(UInt8), Enum8(\'7\' = 3))')
Dynamic + DateTime: IN _CAST('2020-01-02 05:00:00', 'Dynamic')
Dynamic in a list: IN _CAST(tuple(3, 'zz'), 'Tuple(Dynamic, String)')
Over remote() on this branch: IN returns ['3'] where the oracle is ['7'], NOT IN is inverted, the list form gives ['3','zz'], the Date bound raises Code: 53 Cannot convert string '2020-01-02 05:00:00' to type Date, and = raises Code: 386 NO_COMMON_TYPE ... _CAST(UInt8_3_Dynamic, 'Dynamic'). Each is identical on the pristine-master arm, so nothing here regresses. Variant over remote() goes from ['3'] on master to ['7'] here, which is the control that separates the two defects.
One correction to the mechanism: this does not fall back to getFieldFromColumnForASTLiteral. A Dynamic constant already takes the exact-literal path (typeMayContainDecimal includes isDynamic()), and columnConstantToExactLiteralASTImpl already recurses to the active member. The single missing step is naming that member's type, which Analyzer/Utils.cpp:1746-1756 declines on purpose: "Dynamic accepts a value of any type, so its member type must not be named, and doing so would change the stored subtype of values whose literal is inferred back as a wider or narrower type than the initiator's" (#95055).
So the remedy is to overturn that trade-off in Analyzer/Utils.cpp, on the initiator, one layer above this PR's callee, and it changes the stored subtype of every Dynamic constant that crosses to a shard. #117831 is already restructuring that same function for the Variant half and leaves the Dynamic branch unnamed by design, so this is sequenced behind it rather than folded into a PR that cannot observe the loss. The regression test you ask for only turns red together with that change, so it ships there. A fix task owns it with this transcript, and the PR body now names the limitation.
ReproducerSELECT v FROM (SELECT arrayJoin(['7', '3']) AS v)
WHERE v IN (CAST(CAST('7' AS Enum8('7' = 3)) AS Dynamic));
-- 26.8 / 26.7 / 26.6 / 26.3 return '3' (the enum's underlying number).
-- Expected '7' (its name) -- both `v IN ('7')` and `v = CAST(CAST('7' AS Enum8('7' = 3)) AS Dynamic)` return '7'.
-- Same wrong answer for Variant: CAST(CAST('7' AS Enum8('7' = 3)) AS Variant(Array(UInt8), Enum8('7' = 3))).
-- NOT IN is inverted the same way; MergeTree key analysis prunes on the wrong value.Results:
Backport the fix to Analysis metadata
Introducing change: not identified
|
|
Checked this per branch before answering. The gap is real, and the port is two PRs rather than one.
So if this is wanted, the order is #112647 first and this PR second. I am not asking for labels on either: I do not apply backport labels or open release-branch PRs, and whether a two-PR port across four branches is worth it for a defect that needs an |
Related: #112647
Related: #117959
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
An
Enumconstant wrapped inVariantorDynamicand compared against aStringorFixedStringcolumn was converted to the enum's underlying number instead of its name, soINmatched the wrong row,NOT INwas inverted, and key analysis pruned on the wrong value. The active alternative's type is now used as the source type of the conversion, which also fixesLowCardinalitytargets,BoolunderVariant, and aDate/DateTimebound wrapped inDynamic.Description
v IN (CAST(CAST('7', 'Enum8(''7'' = 3)') AS Dynamic))returned the row'3'where theequivalent
v IN ('7')returns'7'.=on the same constant was already correct, which madethis a bug rather than a convention.
convertColumnToTypeOrNullmaterializes aFieldfrom the constant's column and delegates toconvertFieldToType.ColumnVariant::getreturns the active alternative's nested value and dropsthe discriminator, and
ColumnDynamic::getdelegates to it, so theFieldno longer records whichalternative was active while the source type handed down is still the carrier's. Conversions keyed
on the source type then take the wrong branch: the Enum-to-name case tests the hint with
dynamic_cast<const IDataTypeEnum *>, which fails forDynamic, so the number is rendered.The alternative's type is read back from the column and passed as the source type at both
delegation points.
ColumnDynamic::getTypeAtcovers both storage branches;ColumnVariantstoresno types, so its discriminator is resolved against the caller's
DataTypeVariant. It also makes anambiguous
Variant(Bool, UInt8)faithful, which the header called impossible: impossible for theField, not for the column.IN,NOT INandvalues()share this callee, so one change covers all three for theVariantcarrier. The new test pins both analyzers and reddens 18 of its 20 cells on master in
each; pruning is asserted to be preserved rather than traded for correctness.
#117959 is the complement here: it keeps the column when the conversion is an identity
(
from->equals(*to)); this one supplies the alternative's type whenfrom != to.Not addressed, and pre-existing: a carrier nested inside an
Array/Tuple/Map, and a bareArray(Enum8)constant.values()and aremote()/Distributedread share a cause one layer up:the analyzer re-emits a
Dynamicconstant as its bare member literal, so a shardreceives
_CAST(3, 'Dynamic')and filters on'3', as on master.Variantis correct on both.Workflow [PR]
Sync PR [sync-upstream/pr/117998]