Repository navigation
Conversation
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]>
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 Known and not fixed here: a Session id: cron:clickhouse-review-self-slot-58:20260903-072800 |
|
Workflow [PR], commit [0431017] Summary: ❌
AI ReviewSummaryThis PR routes Missing context / blind spots
Final Verdict✅ No new inline findings for the current head. LLVM Coverage ReportMeasured on commit 0431017.
Changed lines: Changed C/C++ lines covered: 47/47 (100.00%) · Uncovered code |
|
cc @Avogar @yakov-olkhovskiy, could you review this? A folded constant whose type contains a |
|
I audited the head end to end and the claimed shape is solid: the per-element member naming plus whole- One residual rides in on the same soundness condition the PR body itself states — "a The fix looks cheap from where the machinery now stands: inside a compound that gets a type-asserting outer For context: the scalar form of this — a plain folded |
Build profile diff (arm_release)Comparing commit See the job log for details. |
|
Confirmed, both directions, on one rig. Ground truth for every arm is
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 The remedy you describe is already implemented, in the form you describe, in my #117837: It does not fix the first three: its gate is still #117837 is also the fix for the scalar form you filed as #117835, and I will link it there. |
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]>
`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]>
|
Pushed as Your One residual, disclosed in the description and not fixed here: an empty |
CI finish ledger - 24803f8Every 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 172 praktika nodes: 150 OK, 19 skipped, 1 failing check.
The three merged siblings that touch this code path are all present in the tree that ran and none of them addresses the duration: Session id: cron:our-pr-ci-monitor:20260903-193000 |
|
The fixing PR for the It stops |
|
@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`.
|
Conflicts resolved by merging master; head is now 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: It does not cover the nested- The reconciliation also exposed one defect, fixed here: widening that gate sends an empty map through the walker too, which emits an argumentless 21/21 arms and 10 tests of the constant-serialization family pass on the merged head. The folded empty |
CI finish ledger - 0431017Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
The failing job never executes any code from this diff: it compares build profiles by querying the CI logs Session id: cron:our-pr-ci-monitor:20260916-200109 |
914d299
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]>
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]>
Related: #74366
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a constant of
Varianttype reached through anArray,TupleorMapbeing mis-serialized to a secondary server, so a query that returned a result on a single node failed withCANNOT_CONVERT_TYPEthrough parallel replicas,remoteorDistributed. AStringmember of a multi-memberVariantconstant, scalar or nested, arrived there as whichever member its text parsed as, and an emptyMapwhose key or value is aVariantwas rejected outright.Description
One node returns
[42].Conversion to
Variantis 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 buildercolumnConstantToExactLiteralASTalready does that, but a predicate asking only whether the type had a decimal-backed leaf gated it, so a nestedVarianttook the plain literal path and[42]re-inferred asArray(UInt8).This widens the predicate to the question it is really asking, at all three call sites, and names the whole
Varianton each element (arrayandmapresolve their result type before any enclosing cast). A string-like member takes one more hop through a single-memberVariant, which that text re-inference does not apply to. #111136's scalarVariantspecialization 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 theVarianthalf is left here, and aDateTimebeside a nestedVariantis 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
Mapwhose key or value carries aVariantneeds 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
Variantunder anObject/JSONnode stays lossy, independently ofVariant(Array(JSON(a DateTime))is lossy too), and an emptyArray(Variant(...))constant still fails, because the conversion rejectsNothingas aVariantmember.Workflow [PR]
Sync PR [sync-upstream/pr/117831]