Skip to content

Use the active Variant/Dynamic alternative as the source type of a constant conversion - #117998

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-enum-in-variant-dynamic-in-set
Sep 13, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-enum-in-variant-dynamic-in-set

Conversation

@groeneai

@groeneai groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112647
Related: #117959

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

An Enum constant wrapped in Variant or Dynamic and compared against a String or FixedString column was 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. The active alternative's type is now used as the source type of the conversion, which also fixes LowCardinality targets, Bool under Variant, and a Date/DateTime bound wrapped in Dynamic.

Description

v IN (CAST(CAST('7', 'Enum8(''7'' = 3)') AS Dynamic)) returned the row '3' where the
equivalent v IN ('7') returns '7'. = on the same constant was already correct, which made
this a bug rather than a convention.

convertColumnToTypeOrNull materializes a Field from the constant's column and delegates to
convertFieldToType. ColumnVariant::get returns the active alternative's nested 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 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 for Dynamic, 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::getTypeAt covers both storage branches; ColumnVariant stores
no types, so its discriminator is resolved against the caller's DataTypeVariant. It also makes an
ambiguous Variant(Bool, UInt8) faithful, which the header called impossible: impossible for the
Field, not for the column.

IN, NOT IN and values() share this callee, so one change covers all three for the Variant
carrier. 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 when from != to.

Not addressed, and pre-existing: a carrier nested inside an Array/Tuple/Map, and a bare
Array(Enum8) constant. values() and a remote()/Distributed read share a cause one layer up:
the analyzer re-emits a Dynamic constant as its bare member literal, so a shard
receives _CAST(3, 'Dynamic') and filters on '3', as on master. Variant is correct on both.


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

…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author
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.
Round 1: 15 findings, 10 accepted and fixed, 4 declined with evidence, 1 dropped.
Round 2 (this tree): 0 findings from both the independent review and the gate.

❌ Accepted and fixed (round 1)

  • The set-construction cell built its right-hand side as an array literal. That parses as a call to
    array, whose legacy-analyzer branch converts each element to getLeastSupertype, an identity
    Dynamic conversion that rebuilds the value from a bare Field. The cell could only ever have
    passed under one of the two analyzers. It is now a list, whose tuple branch constructs the column
    with no conversion at all, and it is measured green in both.
  • Both analyzers are now pinned inside the test rather than left to the one job that still runs the
    legacy one.
  • Four behaviours the changelog entry promises had nothing asserting them: Enum16, a
    LowCardinality(String) target, Bool under an ambiguous Variant(Bool, UInt8), and a Date
    bound from a Dynamic-wrapped DateTime. All four are pinned, plus a cell keeping a UInt8 in
    that same ambiguous variant rendering as a number.
  • The description claimed values() and both analyzers were covered without qualification. Corrected,
    and the residual is disclosed.

⚠️ Declined, with evidence

  • "An exact-type fast path belongs here." That change is Do not lose the Variant discriminator when a constant IN set is built #117959, linked from the description.
    Adding it here would be the same diff twice and would make this pull request depend on unmerged
    work. Resolved by removing the test's dependence on that path instead.
  • "A Variant(Bool, UInt8) holding a UInt8 now becomes Bool." It does not, and that is now a
    test cell which holds both before and after the change.
  • "Preserve the active type through the query-tree to AST round-trip." Confirmed as the mechanism
    behind the values() plus Dynamic residual, but changing it would alter the stored subtype of
    every Dynamic constant that round-trips, in another subsystem and outside this changelog entry.
    Disclosed in the description; not fixed here.

💡 Noted, not blocking

  • The test number is shared with several other open pull requests. Numbers are not unique in this
    suite and nothing enforces it.

One correction to my own round-1 report: I stated the added-comment count in the source diff as 13
against 26 code lines. The true census is 24 against 27, at both revisions, so no comment lines were
added in round 2. The conclusion is unchanged.

@clickhouse-gh clickhouse-gh Bot closed this Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test 05060_enum_in_variant_dynamic_in_set fails 10 of 10 runs on a pristine build of the same base, under each analyzer (20 of 20 runs, 0 passes). Single cell: v IN (CAST(CAST('7', 'Enum8(''7'' = 3)') AS Dynamic)) returns '3' where v IN ('7') returns '7'.
b Root cause explained? Yes. convertColumnToTypeOrNull materializes a Field and delegates to convertFieldToType; ColumnVariant::get drops the discriminator (and ColumnDynamic::get delegates to it), so the Field no longer records the active alternative while the source type passed down is still the carrier's. The Enum-to-name case tests the hint with dynamic_cast<const IDataTypeEnum *>, which fails for Dynamic, so FieldVisitorToString renders the underlying number.
c Fix matches root cause? Yes. It supplies information that was present in the column and dropped by get. No widened bound, no no-random-* tag, no reduced dataset, no guard at the symptom site.
d Test intent preserved / new tests added? New 20-cell stateless test; nothing weakened or removed. It carries two control cells, so neither headline assertion can be satisfied vacuously: one stops the pruning-preserved assertion from holding when both sides read every granule, and one stops the Bool assertion from holding under a blanket Bool coercion.
e Both directions demonstrated? Yes. 18 of 20 cells return 0 on the pristine base build and all 20 return 1 with the fix, in both analyzer arms with the same per-cell list, on Build-ID-distinct binaries each asserted against its server via SELECT lower(buildId()). 100 of 100 randomized runs pass with the fix.
f Fix is general across code paths? Yes, and that is why it is one change: IN, NOT IN and values() all converge on convertColumnToTypeOrNull, in both analyzers. Both delegation points in the file are fixed, including the throwing diagnostic so its message names the real source type. For values() the covered carrier is Variant; a Dynamic one loses its alternative upstream of this helper while the analyzer resolves table-function arguments, which the description states.
g Fix generalizes across inputs? Measured across Enum8/Enum16, Nullable(Enum8), String/FixedString/LowCardinality(String)/Variant targets, Dynamic regular and shared-variant storage, unambiguous and ambiguous Variant, single-value/tuple/array right-hand sides, NULL rows, and non-Enum alternatives (Int8, Bool, UUID, Decimal, Date, DateTime, Time, IPv6). Non-carriers are excluded by mechanism: an Enum cannot get inside a JSON, LowCardinality(Enum) is not constructible, and Nullable(Variant) cannot exist.
h Backward compatible? Yes. No setting added, no default changed, no serialization format touched, so no SettingsChangesHistory.cpp entry is needed. The only behaviour change is wrong results becoming correct.
i Invariants and contracts preserved? The invariant is that the source type handed to the delegated conversion is the type a genuine value of the constant would have, not its carrier's. The resolution is total: it returns the carrier's type unchanged for a non-carrier, a NULL row, or a mismatched column and type, so the existing NULL contract is untouched. It only reads the column, changes no ownership or locking, and the ColumnVariant index is bounded by that type's own alternative count.

Session id: cron:clickhouse-impl-self-slot-57:20260903-231200

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d606e7e]

Summary: ✅


AI Review

Summary

This PR fixes the local convertColumnToType path so scalar Variant/Dynamic constants keep their active alternative when IN/NOT IN/VALUES rebuild a Field, and the new stateless coverage exercises both analyzers for that local path. I cannot approve it yet because the same Dynamic constants still lose their subtype when the query tree is serialized back to AST for remote execution, so distributed or parallel-replica plans can still return the pre-fix wrong rows.

Findings

❌ Blockers

  • [src/Interpreters/convertColumnToType.cpp:182] The new helper only fixes the local Field reconstruction path. Remote execution still rebuilds the query from query_tree->toAST() (src/Interpreters/InterpreterSelectQueryAnalyzer.cpp:342, :351), and ConstantNode::toASTImpl still serializes Dynamic members through getFieldFromColumnForASTLiteral unless the type contains a decimal. That turns Dynamic(Enum8('7' = 3)) into 3 and Dynamic(DateTime('UTC')) into a bare string / _CAST(..., 'Dynamic'), so shards still convert against the wrong source type and reproduce the original wrong-row / wrong-bound behavior.
    Suggested fix: preserve the active subtype in the AST round-trip as well, e.g. by teaching ConstantNode::toASTImpl / columnConstantToExactLiteralASTImpl to serialize Dynamic leaves exactly on IN RHS and other remote paths, then add a remote/distributed regression.
Tests
  • ⚠️ Add a focused remote regression for IN/NOT IN on Dynamic(Enum8(...)) and Dynamic(DateTime(...)) that forces a query_tree->toAST() round-trip (distributed table, remote shard, or an analyzer serialization test). The current stateless test explicitly keeps execution local.
Final Verdict
  • Status: ⚠️ Request changes
  • Fix the AST serialization of Dynamic constants for remote execution and cover it with a remote round-trip regression. After that, the local convertColumnToType fix looks sound.

LLVM Coverage Report

Measured on commit d606e7e.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 22/22 (100.00%) · Uncovered code

Full report · Diff report

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

groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @CurtizJ, could you review this? ColumnVariant::get returns the active alternative's value without recording which alternative it was, so a Dynamic-wrapped Enum constant reached convertFieldToType with the carrier as the source type and rendered as its underlying number, making v IN (CAST(CAST('7', 'Enum8(''7'' = 3)') AS Dynamic)) match the row 3 instead of 7. It reads the alternative's type back from the column and passes that as the source type, which also makes an ambiguous Variant(Bool, UInt8) faithful and so replaces the limitation note added in #112308.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d606e7e10 with master 55c256363 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... label Sep 4, 2026
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@alexey-milovidov alexey-milovidov 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.

Ok.

@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
SELECT 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.

▶ Run on ClickHouse Fiddle

Results:

  • Reproduces on: 26.8, 26.7, 26.6, 26.3
  • Does not reproduce on: master
  • Tested versions: master, 26.8, 26.7, 26.6, 26.3
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.8, 26.7, 26.6, 26.3.

Analysis metadata

comp-json-datatype · Severity P2 · Finding phase_d_pr117998

  • Verified against master build 8f68f32a0846 (aarch64)
Introducing change: not identified
  • No clean release baseline found and no lower bound established — source-build bisect is required to pin the introducing PR (not yet performed).
  • Walked 6 release(s) below the supported window: still reproduces down to 25.8.
  • Secondary components: comp-testing

@groeneai

Copy link
Copy Markdown
Collaborator Author

Checked this per branch before answering. The gap is real, and the port is two PRs rather than one.

  • None of the four active release branches inherits this fix: it merged 2026-09-13, after the cut of 26.8 (2026-08-24), 26.7 (2026-07-22), 26.6 (2026-06-23) and 26.3 (2026-03-19).
  • src/Interpreters/convertColumnToType.{cpp,h}, the only source this PR touches, arrived on master on 2026-07-18 and is present on 26.8 alone. It does not exist on 26.7, 26.6 or 26.3, so on three of the four there is no landing site for the change as written.
  • The file does exist on 26.8, but by the code on that branch, landing this change alone would still leave the reproducer returning 3. All this PR does is pass the active Variant/Dynamic alternative's type down as from_type_hint; the code that consumes that hint for an Enum source is convertFieldToType.cpp:584-586 (castToName), added by Convert an Enum constant to its name, not its number, when comparing with a String column #112647, which merged 2026-08-31, so also after the 26.8 cut and also unlabelled. On 26.8 the isStringOrFixedString() branch (:548) has no Enum case and still ends in FieldVisitorToString, so the enum comes out as its number whatever hint it is given.

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 Enum constant wrapped in Variant or Dynamic and compared against a String column is a call for whoever owns the releases. One v<X.Y>-must-backport per PR would cover it, since a version label names the oldest release to reach and expands to every newer active branch (tests/ci/cherry_pick.py:1004-1005, :1311).

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-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants