Skip to content

Fix CANNOT_CONVERT_TYPE for folded Variant constants in distributed queries - #111136

Merged
fm4v merged 2 commits into
masterfrom
nik/fix-variant-constant-fold-distributed
Jul 21, 2026
Merged

fm4v merged 2 commits into
masterfrom
nik/fix-variant-constant-fold-distributed

Conversation

@fm4v

@fm4v fm4v commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Closes: #74366
Related: #109601

When a resolved query tree is serialized back to AST to be sent to a secondary server (parallel replicas or any distributed query), a folded constant of Variant type was emitted as _CAST(<plain literal>, '<Variant type>'). The literal does not keep the exact member type: a Point value of Geometry becomes a plain tuple whose type is re-inferred as Tuple(Float64, Float64), and a UInt64 value 42 is re-inferred as UInt8. Since conversion to Variant is allowed only for types equal by name to one of its members, the secondary server failed with CANNOT_CONVERT_TYPE:

SELECT 42::UInt64::Variant(UInt64, String) FROM remote('127.0.0.1', system.one) SETTINGS prefer_localhost_replica = 0;

Code: 70. DB::Exception: Cannot convert type UInt8 to Variant(String, UInt64). Conversion to Variant allowed only
for types from this Variant: In scope SELECT _CAST(42, 'Variant(String, UInt64)') FROM system.one AS __table1.

Now ConstantNode::toASTImpl first casts the literal to the exact member type, e.g. _CAST(_CAST((0., 0.), 'Point'), 'Geometry'), which resolves correctly on the secondary server. Constants of Variant type nested inside compound constants (e.g. Array(Variant(...))) are a rarer case with the same nature and are not covered by this fix.

The bug was exposed on master by the new test 04507_mvt_encode_state_serialize (merged today in the PR linked above), which fails flakily in Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel): https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=2592b08fdafd46c4ef82893535edb390798362de&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

This bug is also the original reason 02990_variant_where_cond was blacklisted for parallel replicas (that test has since been rewritten to assert the strict Variant comparison errors and now carries a no-parallel-replicas tag). Note: comparison of Variant values whose members have no common supertype throws NO_COMMON_TYPE by design, so the regression test uses a comparable Variant for the WHERE case.

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

Fix CANNOT_CONVERT_TYPE error for constants of Variant type (including Geometry) in distributed queries and queries with parallel replicas.

Version info

  • Merged into: 26.7.1.1272 (included in 26.7 and later)

…ueries

When a resolved query tree is serialized back to AST to be sent to a
secondary server (parallel replicas or any distributed query), a folded
constant of Variant type was emitted as `_CAST(<plain literal>, '<Variant type>')`.
The literal does not keep the exact member type: a `Point` value of
`Geometry` becomes a plain tuple re-inferred as `Tuple(Float64, Float64)`,
a `UInt64` value 42 is re-inferred as `UInt8`. Since conversion to Variant
is allowed only for types equal by name to one of its members, the
secondary server failed with CANNOT_CONVERT_TYPE.

Now the literal is first cast to the exact member type, e.g.
`_CAST(_CAST((0., 0.), 'Point'), 'Geometry')`.

Exposed by test 04507_mvt_encode_state_serialize in
"Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)":
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=2592b08fdafd46c4ef82893535edb390798362de&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7a45900]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 3/6) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue

AI Review

Summary

This PR fixes the reported Variant constant-folding failure only for the top-level Variant case by adding an inner _CAST to the exact member type before the outer Variant cast. That closes the simple distributed-query repros in the new test, but the same invariant is still broken when a Variant value is nested inside a compound constant, so I cannot approve the PR as-is.

Findings

⚠️ Majors

  • [src/Analyzer/ConstantNode.cpp:236] The new special case only wraps a top-level Variant. Nested Variant values inside Array, Tuple, or Map are still serialized through getFieldFromColumnForASTLiteralImpl as plain Fields, so the secondary server re-infers source types like UInt8 or Tuple(Float64, Float64). The recursive cast path in createArrayWrapper / createTupleWrapper then reaches createColumnToVariantWrapper, which rejects those re-inferred names and throws the same CANNOT_CONVERT_TYPE. A folded constant such as SELECT [42::UInt64::Variant(UInt64, String)] FROM remote(...) or SELECT [(0., 0.)::Point::Geometry] FROM remote(...) should still fail on this patch. Suggested fix: preserve the exact member type for nested Variant values too, and add a focused distributed-query regression for an Array(Variant(...)) or Tuple(Variant(...)) constant.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: extend the serialization fix beyond top-level Variant constants so nested Variant values in compound constants survive round-tripping to secondary servers, and add a focused distributed-query regression for that carrier.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
Comparison of `Variant(String, UInt64)` values now throws `NO_COMMON_TYPE`
under the strict comparison behavior (asserted by 02990_variant_where_cond),
so the WHERE regression case must use a Variant whose members have a common
supertype. Verified: the query returns 42 locally and on the fixed
serialization form, and fails with CANNOT_CONVERT_TYPE on unfixed master
via remote().
/// type (e.g. a `Point` value of `Geometry` becomes a plain tuple whose type is inferred back as
/// `Tuple(Float64, Float64)`, and a `UInt64` value 42 is inferred back as `UInt8`), so a secondary server
/// would fail to resolve `_CAST(<literal>, '<variant type>')`. Cast the literal to the exact member type first.
if (const auto * variant_type = typeid_cast<const DataTypeVariant *>(constant_value_type.get()))

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 repairs a top-level Variant. If the folded constant is Array(Variant(...)), Tuple(..., Variant(...)), or Map(..., Variant(...)), getFieldFromColumnForASTLiteral still erases each nested member to a plain Field, so the secondary server receives _CAST([42], 'Array(Variant(String, UInt64))') (or _CAST([(0, 0)], 'Array(Geometry)')). createArrayWrapper / createTupleWrapper then recurse into createColumnToVariantWrapper with the re-inferred source type (UInt8, Tuple(Float64, Float64), etc.) and throw the same CANNOT_CONVERT_TYPE at src/Functions/FunctionsConversion.cpp:881 and src/Functions/FunctionsConversion.cpp:2105-2112.

A minimal repro that should still fail on this patch is:

SELECT [42::UInt64::Variant(UInt64, String)] FROM remote('127.0.0.1', system.one) SETTINGS prefer_localhost_replica = 0;

@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.10% 86.20% +6.10%
Functions 90.90% 92.00% +1.10%
Branches 72.30% 78.30% +6.00%

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

Full report · Diff report

@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.1, 26.2, 26.3, 26.4, 26.5, 26.6. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 2, 2026
`Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)`
fails the new test deterministically with

    Code: 70. Cannot convert type UInt8 to Variant(Float64, Int64).
    Conversion to Variant allowed only for types from this Variant

A secondary server receives the query as text, and a folded constant is printed
as a bare literal: an `Int64` 2 becomes `2`, which re-parses as `UInt8`, and the
internal `_CAST` back to `Array(Variant(Float64, Int64))` refuses a type that is
not one of the alternatives.

This is the case ClickHouse#111136 deliberately left open. That pull request fixed the same
error for a scalar `Variant` constant, by casting the literal to the exact member
type first in `ConstantNode::toASTImpl`, and its description records that
constants of `Variant` type nested inside compound constants are not covered by
it. Measured on 26.9 through a plain distributed query, so no parallel replicas
and no table are needed:

    SELECT 42::UInt64::Variant(UInt64, String)
      FROM remote('127.0.0.1:PORT', system.one) SETTINGS prefer_localhost_replica = 0;
    -- 42

    SELECT [42::UInt64]::Array(Variant(UInt64, String))
      FROM remote('127.0.0.1:PORT', system.one) SETTINGS prefer_localhost_replica = 0;
    -- Code: 70

The arm that fails sets `optimize_redundant_comparisons = 0`, so the analysis this
pull request changes never runs on it. Against a local three-replica rig built
from the arm's own two config files, that arm serializes the identical remote
query and raises the same error on the published head and on its pristine base.

No choice of constants avoids it here. The property under test is a constant
whose discriminator cannot be recovered from its `Field`, which is exactly what
the text round trip drops, so a constant that survives the round trip is a
constant that no longer arms the test.

`no-parallel-replicas` is the existing marker for this, and 484 stateless tests
carry it, including `04628_logical_optimizer_in_rewrite_variant_type` (the sibling
test for the `IN` rewrite in this same pass) and
`04105_key_condition_nested_lc_variant`. It skips the file on the ParallelReplicas
arm and forces `enable_parallel_replicas = 0` elsewhere, so every other arm keeps
running it unchanged. Verified both directions: tagged, the arm's own invocation
reports `SKIPPED` and an ordinary run reports `OK` even against a server whose
default profile enables parallel replicas; with the tag line removed and nothing
else changed, both invocations fail with the error above.

Related: ClickHouse#111136
Related: ClickHouse#74366

Co-Authored-By: Claude Opus 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…constant-fold-distributed

Fix CANNOT_CONVERT_TYPE for folded Variant constants in distributed queries
pull Bot pushed a commit to infdahai/ClickHouse that referenced this pull request Sep 17, 2026
A folded constant whose type contains a `Variant` below the top level was
mis-serialized to every secondary server, so a query that returns a result on a
single node failed outright through parallel replicas, `remote` or `Distributed`:

    SELECT [42::UInt64]::Array(Variant(UInt64, String))
      FROM remote('127.0.0.1:9000', system.one) SETTINGS prefer_localhost_replica = 0;
    -- Code: 70. Cannot convert type UInt8 to Variant(String, UInt64).

`ConstantNode::toASTImpl` has two ways to print a constant. The exact recursive
builder `columnConstantToExactLiteralAST` already names a `Variant`'s active
member type per element, which is what the receiving `_CAST` requires, since
conversion to `Variant` is allowed only from a type equal by name to one of its
members. But the builder was reached through a predicate that asked only whether
the type had a decimal-backed leaf, so `Array(Variant(UInt64, String))` took the
plain path instead and printed a bare literal array; `[42]` re-infers as
`Array(UInt8)` on the shard and the cast throws. A decimal-carrying member such
as `Array(Variant(Decimal64(2), String))` already worked, because the decimal
dragged the whole constant onto the exact path.

Widen that predicate to the question it is really asking - can this value be
printed as a plain literal and re-parsed into the same type - and use it at all
three call sites, including the builder's own recursion guard. Without the guard
the constant enters the builder and is bounced straight back out to a plain
literal, which leaves the bug in place.

The scalar `Variant` specialization added by ClickHouse#111136 is subsumed: after the gate
change any type containing a `Variant` returns from the exact path above it, so
its `typeid_cast<const DataTypeVariant *>` can never succeed, and the exact path
emits byte-identical text for the scalar case. Confirmed unreachable by
measurement - a `chassert(false)` placed in the block never fired across 1998
stateless tests - then removed.

A `DateTime` member needed fixing as well, or naming the member type would have
turned a hard error into wrong results. The builder's recursion guard
short-circuits subtrees the plain path is believed to serialize exactly, and that
belief is wrong for `DateTime`: its text form is local date-time text, and two
UTC instants in a DST overlap share one such text, so parsing picks the earlier.
In `Europe/Berlin` the epoch 1698541800 came back as 1698538200, an hour early.
Under a named `Variant` member the value is now rendered as its raw Unix
timestamp, which is unambiguous and time-zone independent. The flag is set only
when descending into a `Variant` member, so an ordinary `DateTime` constant is
untouched, and it is deliberately not passed into the `Dynamic` branch: `Dynamic`
names no member type, so a bare number would be read back as a number.
`Date`/`Date32` text round-trips exactly and stays as text.

`tryBuildAdditionalFilterAST` never had ClickHouse#111136's special case at all, so it was
broken for scalar `Variant` constants too; the same predicate change fixes both
it and the parallel-replicas index-analysis path that shares it.

Two limits are worth naming. A `Variant` reached through an `Object`/`JSON` node
is not covered: that branch flattens the value to one JSON-text literal, and the
defect there is independent of `Variant` - `Array(JSON(a DateTime))` is equally
lossy with no `Variant` in the type. And `CAST AS Array` still refuses an
`Array(Array(T))` source against an `Array(Variant(Array(T), ...))` target on the
array-dimension count, a pre-existing local defect already reachable through a
decimal-carrying `Variant`.

Related: ClickHouse#74366

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Cannot convert type UInt8 to Variant(String, UInt64). Parallel replicas variant type conversion

3 participants