Skip to content

Serialize a Variant constant nested in an Array, Tuple or Map exactly - #117831

Merged
Avogar merged 18 commits into
ClickHouse:masterfrom
groeneai:groeneai/serialize-nested-variant-constant-exactly
Sep 17, 2026
Merged

Avogar merged 18 commits into
ClickHouse:masterfrom
groeneai:groeneai/serialize-nested-variant-constant-exactly

Conversation

@groeneai

@groeneai groeneai commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #74366

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 a constant of Variant type reached through an Array, Tuple or Map being mis-serialized to a secondary server, so a query that returned a result on a single node failed with CANNOT_CONVERT_TYPE through parallel replicas, remote or Distributed. A String member of a multi-member Variant constant, scalar or nested, arrived there as whichever member its text parsed as, and an empty Map whose key or value is a Variant was rejected outright.

Description

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).
--   In scope SELECT _CAST([42], 'Array(Variant(String, UInt64))') ...

One node returns [42].

Conversion to Variant is allowed only from a type equal by name to one of its members, so the literal has to name the active member type per element. The exact builder columnConstantToExactLiteralAST already does that, but a predicate asking only whether the type had a decimal-backed leaf gated it, so a nested Variant took the plain literal path and [42] re-inferred as Array(UInt8).

This widens the predicate to the question it is really asking, at all three call sites, and names the whole Variant on each element (array and map resolve their result type before any enclosing cast). A string-like member takes one more hop through a single-member Variant, which that text re-inference does not apply to. #111136's scalar Variant specialization then becomes unreachable and is removed. tryBuildAdditionalFilterAST, which named no member at all, is fixed too.

Reconciled with #117837, merged since: the DateTime-as-exact-instant work this branch also carried is master's now, so only the Variant half is left here, and a DateTime beside a nested Variant is exact through the merged option. Of this test's 21 arms, 14 still deviate on master, 11 by rejecting the query.

Found while reviewing that reconciliation: an empty Map whose key or value carries a Variant needs a typed empty literal, both on its own and beside a non-empty sibling in a folded parent.

Two pre-existing gaps remain, unchanged here: a Variant under an Object/JSON node stays lossy, independently of Variant (Array(JSON(a DateTime)) is lossy too), and an empty Array(Variant(...)) constant still fails, because the conversion rejects Nothing as a Variant member.


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

groeneai and others added 6 commits September 2, 2026 21:23
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]>
One arm per scenario rather than per member type: the member cast has to be
applied per element for `Array`, `Tuple` and `Map`, at nesting depth two, and
with a custom member type name (`Point` inside `Geometry`, which is why the
member cast was needed at all).

The `DateTime` arm's spelling is load-bearing. `toUnixTimestamp` has to sit
inside the `arrayMap`; indexing the constant outside it lets the whole scalar
expression fold on the initiator, and the arm then passes without the fix. Both
epochs involved format to the local text `2023-10-29 02:10:00` in the
`Europe/Berlin` DST overlap, so the text form comes back an hour early.

Co-Authored-By: Claude Opus 5 <[email protected]>
`columnConstantToExactLiteralAST` named a `Variant` element's active member type
and left restoring the `Variant` itself to the cast that wraps the whole
constant. That is too late for two containers: `array` and `map` resolve their
own result type from their arguments before any enclosing cast runs, so an
element left at its bare member type has to survive common-type resolution
against its siblings first.

Two measured consequences, both on a query that returns a result on a single
node:

    SELECT [42::UInt64::Variant(UInt64, String), 'x'::Variant(UInt64, String)]
      FROM remote('127.0.0.1:9000', system.one)
      SETTINGS prefer_localhost_replica = 0, use_variant_as_common_type = 0;
    -- Code: 386. There is no supertype for types UInt64, String

    SELECT map(NULL::Variant(UInt64, String), 'x')
      FROM remote('127.0.0.1:9000', system.one) SETTINGS prefer_localhost_replica = 0;
    -- Code: 36. Map cannot have a key of type Nullable(Nothing)

The second was a regression introduced earlier on this branch: the plain literal
path emitted the map as an array of tuples, which `_CAST` converts without
asking `FunctionMap` for a key type.

Name the whole `Variant` on every element, in the NULL arm as well. The cast
that wraps the whole constant then collapses, because `makeCastToTypeNameAST`
skips an identity cast, so a scalar `Variant` constant still emits
byte-identical text. The `Tuple` arm is unaffected either way, since `tuple`
computes no common type.

Also here, with no functional change: `typeMayContainDateTime` moves into the
file's anonymous namespace, having no caller outside it, and the exactness
comment on `columnConstantToExactLiteralAST` now enumerates the wrappers the
builder actually descends through. A scaled-decimal leaf under `LowCardinality`
reaches `default:` and keeps the plain literal form, before and after this
change alike.

Co-Authored-By: Claude Opus 5 <[email protected]>
`.claude/CLAUDE.md` asks for a new test rather than extending an existing one, so
the arms move out of `04613_variant_constant_folding_distributed`, which returns
to its state before this branch.

Two arms are new, both from the reasoning in the previous commit: a
heterogeneous `Array(Variant(UInt64, String))` under
`use_variant_as_common_type = 0`, and a `Map` with a NULL `Variant` key.

One more covers the second serialization carrier. Predicate-AST pushdown into a
distributed subquery goes through `tryBuildAdditionalFilterAST`, which named no
member type at all, not even for a scalar `Variant`. On this branch's base that
arm fails with `Code: 70` and the pushed predicate
`HAVING equals(v, _CAST(42, 'Variant(UInt64)'))` is visible in the shard's own
query text, so the arm is reached rather than passing through the outer filter.
Its sibling caller `distributedIndexAnalysis.cpp` shares the same function body.

No `no-*` tag, measured rather than assumed: the file passes with parallel
replicas enabled against a three-replica cluster, and with
`enable_analyzer = 0`. The parallel-replica rig was shown live in the same
session by a local `MergeTree` read that does take the
`ReadFromRemoteParallelReplicas` path, which none of the arms here do.

Co-Authored-By: Claude Opus 5 <[email protected]>
Naming a `Variant` element's active member type is not sufficient when that
member is string-like. `FunctionCast::createColumnToVariantWrapper` routes a
`String`, `FixedString` or `LowCardinality(String)` source into
`createStringToVariantWrapper` whenever the target `Variant` has more than one
member, and that branch runs before the name-equality lookup, so the text is
parsed and the member is re-inferred from it. The setting that enables it,
`cast_string_to_variant_use_inference`, is on by default, and it belongs to the
receiving server, not to the one that wrote the literal.

Measured on a query that returns a result on a single node, at default
settings:

    SELECT ['42'::Variant(String)::Variant(String, UInt64),
            7::UInt64::Variant(String, UInt64)] AS a,
           arrayMap(x -> variantType(x), a)
      FROM remote('127.0.0.1:9000', system.one)
      SETTINGS prefer_localhost_replica = 0;
    -- ['42',7]  ['UInt64','UInt64']   <- the String element arrives as UInt64
    -- single node: ['42',7]  ['String','UInt64']

Before the rest of this branch the same query failed with `Code: 70` instead,
so naming the member alone would have turned an error into a wrong result. The
scalar form of the shape predates this branch and is wrong there too.

A `Variant` with exactly one member is exempt from that inference, and widening
a `Variant` matches its members by name, so the value is routed through a
single-member `Variant` first and then widened. The intermediate type name comes
from a real `DataTypeVariant` rather than string concatenation, which keeps
member names that carry their own parentheses correct, and each of
`Variant(String)`, `Variant(FixedString(2))`, `Variant(LowCardinality(String))`
and `Variant(LowCardinality(FixedString(2)))` was checked to parse back and to
be accepted by `_CAST`.

`Dynamic` is deliberately left alone: `cast_string_to_dynamic_use_inference`
defaults to off, and a member type must not be named under `Dynamic` anyway. A
value whose text is not parseable as another member, and a `NULL`, are
unaffected, the latter because conversion returns early for a null-only source.

Co-Authored-By: Claude Opus 5 <[email protected]>
Two arms for the member type whose text is re-inferred on the receiving server.
Both read `variantType` there rather than on the initiator, because a
`variantType` over a constant is folded away before the query is sent and would
report the initiator's discriminator: the scalar arm needs `materialize` for
that, the nested one gets it from `arrayMap`. Their base failure modes differ,
which is why both are here. The scalar arm returns the wrong member with no
error and predates this branch; the heterogeneous arm fails with `Code: 70` on
the base of this branch, so it also guards against turning that error into a
wrong result.

Note that `'42'::Variant(String, UInt64)` cannot express either shape: the cast
runs the same text inference locally, so the constant never holds a `String`
member at all. A single-member `Variant` does not, hence the intermediate.

The pushdown arm asserted only that the result is still 2, which stays true if
the predicate never reaches the remote query at all. Assert the plan instead,
in the form used by `04278_distributed_filter_pushdown_table_function`: the
filter appears once above the outer read and once inside each shard's remote
plan. Measured, and sensitive: with
`allow_push_predicate_ast_for_distributed_subqueries = 0` the count falls to 1.

`SET enable_analyzer = 1`, as the two sibling tests for this mechanism do.
Without it the file was blind on the old-analyzer legs, where the exact
serialization is never reached: every arm, including the two new ones, returns
the expected value on the base build there.

No `no-*` tag, measured rather than assumed: the file passes with parallel
replicas enabled against a three-replica cluster, and the plan arm still counts
3 there. The rig was shown live in the same session by a local `MergeTree` read
that does take the `ReadFromRemoteParallelReplicas` path, which no arm here
does.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds)

Three rounds of independent cold review, every finding adjudicated against a measurement rather than an argument.

Fixed as a result: a nested Variant element left at its bare member type, which array and map resolve against its siblings before any enclosing cast; a string-like member re-inferred from its text on the secondary server, which would otherwise have turned CANNOT_CONVERT_TYPE into a silently different value; and a pushdown arm that asserted only the result, so it would have passed had the predicate stopped reaching the shard.

Known and not fixed here: a Variant under an Object/JSON node stays lossy, as the description says. The columnConstantToExactLiteralAST comment in src/Analyzer/Utils.h lists Object among the wrappers that carry such a leaf exactly, which holds for a decimal-backed leaf but not for a Variant.

Session id: cron:clickhouse-review-self-slot-58:20260903-072800

@clickhouse-gh clickhouse-gh Bot closed this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0431017]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR routes Variant-carrying constants through the analyzer's exact literal serializer, removes the now-redundant scalar Variant special case, and extends distributed filter-pushdown coverage. After tracing the current head through ConstantNode::toASTImpl, columnConstantToExactLiteralASTImpl, and tryBuildAdditionalFilterAST, I did not find a remaining correctness gap in the supported analyzer path, and the new stateless test covers the important carriers and edge cases (Array/Tuple/Map, string members, NULL, empty maps, predicate pushdown, and the OR-to-IN rewrite).

Missing context / blind spots
  • ⚠️ I did not run the new stateless test locally because this workspace has no existing build directory or runnable PR binary; the review is based on source inspection, the added regression coverage, and the current PR discussion.
Final Verdict

✅ No new inline findings for the current head.

LLVM Coverage Report

Measured on commit 0431017.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 47/47 (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 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @yakov-olkhovskiy, could you review this? A folded constant whose type contains a Variant below the top level was printed as a bare literal for a secondary server, so Array(Variant(UInt64, String)) re-inferred as Array(UInt8) there and the receiving _CAST threw CANNOT_CONVERT_TYPE. The exact-serialization builder in the analyzer already named the active member type per element, but was reached only when the type carried a decimal-backed leaf.

@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

I audited the head end to end and the claimed shape is solid: the per-element member naming plus whole-Variant naming covers the array/map sibling-resolution problem, the NULL discriminator is wrapped so Map keys stay valid, and the String-member hop exactly matches the receiving cast's parse trigger (the parse fires only for string-like sources with either no name match or more than one member; the single-member Variant(String) intermediate has a name match and size one, so it converts directly, and extending Variant(String) to the full set is by-name and always valid since the hop member is by construction in the set). I also checked discriminator round-trips for every non-string member kind and found no wrong-alternative re-parse, and no previously-correct case that the removed ConstantNode branch was still needed for.

One residual rides in on the same soundness condition the PR body itself states — "a DateTime member needed fixing too, or naming the member type would turn the error into wrong results" — but one structural level up. date_time_as_numbers is set only under a named Variant member and reset under Dynamic; a DateTime leaf that sits beside the Variant in the same exact-serialized compound — Tuple(DateTime, Variant(...)), a Map key next to Variant values, Array(Tuple(DateTime, Variant(...))) — reaches getFieldFromColumnForASTLiteral with the flag false and is rendered as local-time text, and the enclosing _CAST(..., '<compound type>') re-parses it. In a DST fall-back overlap two instants share one text and the parse picks the earlier. Pre-PR these shapes did not take the exact path at all and failed loudly (verified on 26.9: SELECT (toDateTime(1698541800, 'Europe/Berlin'), 42::UInt64::Variant(UInt64, String)) FROM remote(...) throws Cannot convert type UInt8 to Variant(String, UInt64)); post-PR the query succeeds and the DateTime element arrives as 1698538200 instead of 1698541800 — an error turned into a silently hour-early value, which is exactly the class the PR set out to close. The path is byte-for-byte the one an existing Decimal sibling already drags such tuples onto today, where the hour loss is reproducible end to end: SELECT toUnixTimestamp(t.1) FROM (SELECT (toDateTime(1698541800, 'Europe/Berlin'), 1.5::Decimal64(5)) AS t FROM remote('127.0.0.1', system.one)) SETTINGS prefer_localhost_replica = 0 returns 1698538200 on current master.

The fix looks cheap from where the machinery now stands: inside a compound that gets a type-asserting outer _CAST, a DateTime leaf can be the raw Unix-timestamp number (a bare number through tuple/array/map resolves numerically and the enclosing cast converts number to DateTime exactly); only the Dynamic/Object contexts, where the flag is already reset, genuinely need text. The one caveat is the add_cast_for_constants = false call site, where there is no outer cast — there the per-leaf _CAST(<number>, 'DateTime(...)') form the Variant member branch already emits is the safe rendering.

For context: the scalar form of this — a plain folded DateTime constant through remote losing the overlap hour, with wrong rows from WHERE/IN — exists on master independently of Variant and of this PR, and I filed it separately with a full repro as #117835. This PR is a natural place to close the compound-sibling instance of it, since the flag plumbing is already in hand.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 0431017317f73b6b519a6e83fdc30648662ac2c2 with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

See the job log for details.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed, both directions, on one rig. Ground truth for every arm is 1698541800; base build b92d51206057199f, this PR's head build 5b42ebd27114b3c8, each read from the running server. All arms are ... FROM remote('127.0.0.1:PORT', system.one) SETTINGS prefer_localhost_replica = 0, value read as toUnixTimestamp:

constant shape base this PR
Tuple(DateTime, Variant(UInt64, String)) Code: 70 1698538200
Map(DateTime, Variant(UInt64, String)), the DateTime being the key Code: 70 1698538200
Array(Tuple(DateTime, Variant(...))) Code: 70 1698538200
Tuple(DateTime, Decimal64(5)) 1698538200 1698538200
Tuple(DateTime, UInt64) 1698538200 1698538200

Your reading is right and the guard belongs here. Two things the last row adds: the rendering defect is not tied to the exact-serialization walker at all, since a plain Tuple(DateTime, UInt64) loses the same hour on base through the ordinary literal path, so it is generic and pre-existing. What this PR changes for the Variant-carrying shapes is a loud error into a silent value, which is the conversion it set out to prevent.

The remedy you describe is already implemented, in the form you describe, in my #117837: ConvertToASTOptions::date_time_constants_as_numbers defaults to true, both serialization walkers render a DateTime leaf as its raw Unix timestamp, and it is cleared wherever the receiving side infers the type from the literal (Dynamic, shared data, dynamic JSON paths, Variant in the plain walker) and by the external-database consumer, which is the add_cast_for_constants = false caveat you name. That PR also fixes the last row.

It does not fix the first three: its gate is still typeMayContainDecimal, so a Variant-carrying compound only reaches the exact walker with this PR. Those shapes need both, and I am not leaving a silent wrong result behind an unmerged PR, so I will carry the exact-walker half here: a DateTime leaf renders as its raw Unix timestamp wherever the caller wraps the constant in the type-asserting outer _CAST, and keeps text where there is no outer cast and under Dynamic / Object. Arms for the three shapes above. The two PRs then overlap on that hunk deliberately, and whichever merges second keeps one copy.

#117837 is also the fix for the scalar form you filed as #117835, and I will link it there.

groeneai and others added 4 commits September 3, 2026 12:52
The exact-serialization walker renders a `DateTime` leaf as local date-time
text, and two instants share one such text across a DST fall-back overlap, so
the receiving server re-parses the earlier one. Admitting `Variant` to that
walker makes compounds like `Tuple(DateTime, Variant(UInt64, String))` reach it
instead of failing with `CANNOT_CONVERT_TYPE`, which turns an error into a value
one hour early. Measured on a query that is correct on a single node:

    SELECT toUnixTimestamp(t.1)
      FROM (SELECT (toDateTime(1698541800, 'Europe/Berlin'),
                    42::UInt64::Variant(UInt64, String)) AS t
              FROM remote('127.0.0.1:9000', system.one))
      SETTINGS prefer_localhost_replica = 0;
    -- 1698538200      <- one hour early
    -- single node: 1698541800

A consumer that re-applies the constant's declared type now asks for the raw
Unix timestamp. The leaf names its own type, so the value is exact with no
enclosing cast, which is the form the `Variant` member branch already emitted. A
consumer that suppresses the cast keeps the text form, because it may parse that
text itself, as the external-database pushdown does.

`Dynamic`, shared data and `JSON` paths keep the text form for a second reason:
the value's type is inferred from the literal there, so a bare number would be
read back as a number. Both were measured identical either side of this change,
as was an ordinary `Tuple(DateTime, UInt64)`, which never reaches this walker
and still loses the hour through the plain literal path. ClickHouse#117837 fixes that path
and carries the same rendering behind a `ConvertToASTOptions` field, so whichever
of the two merges second keeps one copy.

Reported by @ zlareb1 on the pull request.

Co-Authored-By: Claude Opus 5 <[email protected]>
Three arms: the sibling in a `Tuple`, as a `Map` key, and in
`Array(Tuple(...))`. Keys and values are rendered by separate branches of the
walker, and the third arm adds a wrapper above the tuple, so all three are here.
Each returns 1698538200 instead of 1698541800 on the previous head of this
branch, where the leaf is rendered as local date-time text in the Berlin DST
fall-back hour, and the reference diff reddens on exactly those three lines.

Co-Authored-By: Claude Opus 5 <[email protected]>
The `OR`-to-`IN` rewrite builds a constant whose enclosing cast
`FunctionNode::toASTImpl` suppresses, and that AST still goes to a ClickHouse
shard, so tying the rendering to `add_cast_for_constants` left the leaf as
ambiguous local date-time text there. Measured on a
`Tuple(DateTime('Europe/Berlin'), Variant(UInt64))` column holding both instants
of a Berlin DST fall-back overlap: a three-way equality chain matches one row on
a single node and none of them through `remote`.

`ConvertToASTOptions::date_time_constants_as_numbers` carries the answer instead,
and only the external-database pushdown clears it, because that consumer parses
the text itself. The field, its comment and the pushdown hunk are byte-identical
to ClickHouse#117837, which adds the same field for the plain literal walker, so the two
merge without a conflict.

Also narrows the helper's wrapper list: an `Object` renders its subtree as JSON
text, whose tokens carry no discriminator, so a `Variant` below it keeps the
plain form rather than being named.

Co-Authored-By: Claude Opus 5 <[email protected]>
That rewrite suppresses the enclosing cast, so this arm reaches a different
carrier than the ones above it: the row is matched on a single node and missed
through a secondary server while the leaf crosses as local date-time text. It
returns 0 without the change and 1 with it, and it is the only reference line
that moves.

Co-Authored-By: Claude Opus 5 <[email protected]>
@Avogar Avogar self-assigned this Sep 3, 2026
groeneai and others added 2 commits September 3, 2026 13:44
`count()` stays 1 when the rewrite declines, because each unreplaced equality
keeps its own cast and is serialized exactly, so the arm above passes without
ever reaching the cast-suppressed carrier it exists for. Assert the query tree's
AST instead, in the form used by the pushdown arm: the generated `in` and the
leaf's numeric cast have to appear together.

Measured on the shipping build: 1 at
`optimize_min_equality_disjunction_chain_length = 3`, and 0 at 100, where the
predicate stays `or(equals(...))`. On the previous head, where the leaf crosses
as `'2023-10-29 02:10:00'`, it is 0 with the rewrite firing.

The walker's internal note drops a line that the header contract now carries.

Co-Authored-By: Claude Opus 5 <[email protected]>
Two blocks restated what this round's commit messages and the pull request
already say. The header states the parameter's contract, so the call site needs
no second copy of the reason, and the contract itself reads in three lines
rather than four.

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

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed as 24803f8. A DateTime leaf is now sent as its raw Unix timestamp named by its own type, so it is exact with no enclosing cast, and three arms cover the shapes you named plus one for the OR-to-IN carrier. Description and changelog updated.

Your add_cast_for_constants caveat was the right thing to flag. My first attempt tied the rendering to that flag, and the OR-to-IN rewrite still crossed as text, because FunctionNode::toASTImpl suppresses the cast for the set it builds: on a Tuple(DateTime('Europe/Berlin'), Variant(UInt64)) column holding both instants of the overlap, a three-way equality chain matched one row on a single node and none through remote. It now goes through ConvertToASTOptions::date_time_constants_as_numbers, which only the external-database pushdown clears, since that consumer parses the text itself. That field, its comment and the pushdown hunk are byte-identical to #117837, so whichever of the two merges second keeps one copy.

One residual, disclosed in the description and not fixed here: an empty Array(Variant(...)) constant still fails with Cannot convert type Nothing to Variant(...). It fails identically on this PR's base, and no literal spelling avoids it, _CAST([], 'Array(Variant(UInt64, String))') is rejected on its own, so the fix belongs in the conversion rather than in the serializer. An empty Map(..., Variant(...)) does not resolve on a single node either.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 24803f8

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

172 praktika nodes: 150 OK, 19 skipped, 1 failing check.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, flaky check) / setup step Start ClickHouse Server NOT a flaky new test and not PR-caused. The other four flaky-check arms ran the tests this PR adds 50 times each and report Failed: 0, Passed: 50 (amd_asan_ubsan, amd_msan, amd_debug, amd_binary), so 200 of 200 iterations are green. The amd_tsan arm never reached them: the job's own setup died with SETUP FAILURE: stateful data prep failed (exit 124) and timeout: sending signal TERM to command 'clickhouse-client' on the fixture statement INSERT INTO test.hits_s3 SELECT * FROM test.hits, which exceeded its per-statement PREP_TIMEOUT bound. The server itself started normally (Server replica 0 ready). Failures: 1/3 counts the job's sub-steps, not test runs a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)

The three merged siblings that touch this code path are all present in the tree that ran and none of them addresses the duration: #115585 introduced the PREP_TIMEOUT bound this run hit, #110185 supplies the max_insert_threads value in the failing command, and #117294 is the diagnostics change that captured the command and a full backtrace of the prep client. No open pull request targets the duration, which is why the owner here is a fix task rather than a link.

Session id: cron:our-pr-ci-monitor:20260903-193000

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

The fixing PR for the Stateless tests (amd_tsan, flaky check) row in the ledger above is up:
#117997

It stops ThreadFuzzer across the stateful fixture load in the flaky check, which of the lanes
that run functional_tests.py is the only one that arms it. At the commit in that ledger the
fuzzed amd_tsan, flaky check arm never finishes
INSERT INTO test.hits_s3 SELECT * FROM test.hits, while the unfuzzed amd_tsan lane finishes
it in 217 s on the same instance type with the same max_insert_threads=4.

@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 commented Sep 16, 2026

Copy link
Copy Markdown
Member

@groenai let's resolve conflicts and take into account #117837

…17837

ClickHouse#117837 merged the DateTime-as-exact-instant work this branch also carried, and
landed all six of the source files touched here, which is what made the branch
conflict. Its ConvertToASTOptions::date_time_constants_as_numbers option, the
plumbing through both walkers and the external-database clear are taken from
master, so IQueryTreeNode.h and transformQueryForExternalDatabaseAnalyzer.cpp are
now byte-identical to it, and the exact walker no longer needs a DateTime case or
a typeMayContainDateTime predicate of its own: a DateTime leaf inside a
Variant-carrying compound is already rendered as a raw timestamp by
getFieldFromColumnForASTLiteral.

What remains here is the nested-Variant fix. typeMayContainDecimal becomes
typeNeedsExactLiteralSerialization and answers for Variant too, so a Variant
below the top level of a constant reaches the exact walker at all; that walker
names the active member type and the whole Variant; and the top-level-only
Variant branch of ConstantNode::toASTImpl becomes redundant and is removed.

05059 keeps its 16 arms. Its OR-to-IN plan oracle now matches the rendering the
merged option produces, a raw timestamp for the DateTime sibling rather than a
per-leaf cast.
Widening the exact-serialization gate to Variant sent an empty map through the
walker too, and it emits `map()`, which is inferred as `Map(Nothing, Nothing)`:
the enclosing cast then rejects converting Nothing to a Variant, so an empty
`Map(String, Variant(...))` constant that worked through remote() before this
branch failed with CANNOT_CONVERT_TYPE. An empty container has no leaf whose
type a literal could lose, so the plain literal is already exact for it.

Measured through remote() on this head: an empty map is `{}` with the Variant in
either the key or the value position, and an empty `Array(Variant(...))` is `[]`,
which master itself rejects. Three arms added.
…ments

An empty `Map` returned as a bare empty literal is inferred as `Array(Nothing)`,
so a folded parent holding both an empty and a non-empty `Map(..., Variant(...))`
child still failed through `remote`: as `Array` elements with `Code: 53` (a
dimension mismatch), and as `Map` values with `Code: 386` (no supertype) under
`use_variant_as_common_type = 0`. Naming the declared map type on the empty
literal makes both siblings resolve as maps. Two arms.

`.claude/CLAUDE.md` asks for literal type and function names inside inline code,
so the comments this branch adds now carry backticks.
…cover

The `mapFilter` and `arrayFilter` arms did not reach the empty-container path at
all: the shard-side query keeps the function and only its non-empty input map or
array is serialized, so they were duplicates of the arms above with a misleading
comment. Measured on the shard-side text (`system.query_log`,
`is_initial_query = 0`): `mapExtractKeyLike` and `mapExtractValueLike` do ship a
folded `_CAST([], 'Map(...)')`, in the value and the key position respectively,
and so do both mixed empty/non-empty parents.

So the group is now five arms that each serialize an empty map: both positions
bare, both positions next to a non-empty sibling in an `Array` parent, and a `Map`
parent under `use_variant_as_common_type = 0`. The folded-empty-`Array(Variant)`
shape is a separate pre-existing failure (it fails on master identically) and is
not claimed here.

Also narrows the "decimal-free values" sentence in the helper's documentation,
which no longer held for a decimal-free `Variant`.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Conflicts resolved by merging master; head is now 0431017.

The conflict was with my own #117837, which landed all six of this branch's source files, so I reconciled against it instead of re-adding a parallel path: date_time_constants_as_numbers, its plumbing through both walkers and the external-database clear now come from master, IQueryTreeNode.h and transformQueryForExternalDatabaseAnalyzer.cpp are byte-identical to it again, and the exact walker no longer needs a DateTime case of its own, since getFieldFromColumnForASTLiteral already renders that leaf as a raw timestamp. Only the Variant half is left, in 4 files instead of 6.

It does not cover the nested-Variant case, though: the gate there is still typeMayContainDecimal, so a Variant below the top level of a constant never reaches the exact walker. Measured on master at 61124de, which contains #117837, with this PR's own test: 14 of its 21 arms still deviate, 11 rejecting the query (Code: 70, Code: 386) and 3 silently, [1698538200] for [1698541800] on a DateTime member, UInt64 for String on a string member, and the OR-to-IN plan oracle.

The reconciliation also exposed one defect, fixed here: widening that gate sends an empty map through the walker too, which emits an argumentless map, inferred as Map(Nothing, Nothing), so an empty Map(String, Variant(...)) constant that worked through remote before this branch began to fail with Code: 70. It keeps a typed empty literal now, with arms for both positions and for a non-empty sibling in a folded parent.

21/21 arms and 10 tests of the constant-serialization family pass on the merged head. The folded empty Array(Variant(...)) shape still fails, identically on master, and stays called out in the description.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0431017

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff infra, not caused by this PR: the CI logs cluster read raises inside has_pr_data (ci/jobs/build_profile_diff_job.py:723, reached from run_comparison at :1510), so the job aborts with a traceback instead of degrading to "no baseline" #120121 (mine, open)

PR is also red, with no independent failure of its own: it is the aggregator that rolls up the row above,
so it carries no separate owner. Every other job on this head is green or skipped, and CH Inc sync is
green, so nothing else is owed.

The failing job never executes any code from this diff: it compares build profiles by querying the CI logs
cluster, and it died on that query. So this red is not PR-caused.

Session id: cron:our-pr-ci-monitor:20260916-200109

@Avogar
Avogar added this pull request to the merge queue Sep 17, 2026
Merged via the queue into ClickHouse:master with commit 914d299 Sep 17, 2026
176 of 178 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 23, 2026
The tag was added because a `Variant` constant nested inside a container did not
survive the query-text round trip to a secondary server: the folded `Field`
printed as a bare literal, the replica re-parsed it as a different type, and the
internal `_CAST` back to the `Variant` refused it.

ClickHouse#117831 fixed exactly that case and is now merged into this branch, so the
analyzer names the member type per element. The remote query for the
`Array(Variant(Float64, Int64))` arms now reads

    _CAST(array(_CAST(_CAST(2, 'Int64'), 'Variant(Float64, Int64)')), 'Array(Variant(Float64, Int64))')

where it previously read `_CAST([2], 'Array(Variant(Float64, Int64))')`.

Measured on the failing CI arm's own cluster configuration: with the tag removed
the test passes 10/10 runs with parallel replicas enabled by the profile, and 5/5
under the runner's `--no-parallel-replicas` flag, against the unchanged
reference. Parallel replicas is engaged rather than skipped: 58 secondary
queries, the `Array(Variant)` chain itself executed on a replica, and
`ParallelReplicasUsedCount` set on 36 queries. As a positive control, the
pre-ClickHouse#117831 bare-literal form still fails `Code: 70` through the same carrier, so
the test passes because of the serialization fix and not because the remote path
went dead.

Dropping the tag puts this regression back under parallel-replica runs. The
rationale paragraph goes with it, since it describes a defect that is now fixed.

Co-Authored-By: Claude Opus 5 <[email protected]>
fm4v pushed a commit that referenced this pull request Nov 2, 2026
Resolve the cherry-pick of #118988 to 26.9.

`src/Analyzer/Utils.cpp` merges cleanly. The only conflict is the doc
comment above `columnConstantToExactLiteralAST` in `src/Analyzer/Utils.h`:
on master #117831 rewrote it before #118988 edited it, and #117831 is not
on 26.9. 26.9's comment is kept unchanged, so this commit carries
#118988's code and tests and drops only its 5-line comment edit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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