Skip to content

Name a Dynamic constant's active member type in the shard-facing literal - #118988

Merged
fm4v merged 24 commits into
ClickHouse:masterfrom
groeneai:name-dynamic-constant-active-member-type
Oct 8, 2026
Merged

fm4v merged 24 commits into
ClickHouse:masterfrom
groeneai:name-dynamic-constant-active-member-type

Conversation

@groeneai

@groeneai groeneai commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #119745
Related: #117998

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 Dynamic constant losing the type of its value when a query is sent to other servers (Distributed, remote, parallel replicas): a constant holding Enum8('7' = 3) arrived as the number 3, so IN and NOT IN matched the wrong rows and = failed with NO_COMMON_TYPE, and a UInt64, IPv4 or Map value arrived as a different type. Closes #119745.

Description

Problem. On 26.8 (26.8.10.6) and current master, SELECT ... FROM remote('127.0.0.1', currentDatabase(), t) WHERE v = CAST(CAST('7', 'Enum8(\'7\' = 3)') AS Dynamic) raises NO_COMMON_TYPE while the same query on the local table returns ['7'], and IN / NOT IN return the wrong rows.

Root cause. The Dynamic case of columnConstantToExactLiteralASTImpl sent the active member's bare literal, so the shard's _CAST(3, 'Dynamic') stored whatever the literal infers back to: UInt8 for the enum and for a UInt64, String for an IPv4, Array(Tuple(...)) for a Map, local text for a DateTime.

Change. The case now does what the Variant case above it does: it names the member type and then the Dynamic type (_CAST(_CAST(3, 'Enum8(\'7\' = 3)'), 'Dynamic')), and forwards date_time_as_numbers, so a DateTime member travels as its timestamp. This replaces the note added in #95055 that declined to name the member type. A consumer that clears date_time_as_numbers, the external-database pushdown, keeps master's literal byte for byte.

Scope. External databases are unchanged. A String member is still re-parsed on the shard under cast_string_to_dynamic_use_inference = 1, as before. A value outside its type's range (a Time tick written through RowBinary) now saturates on the shard exactly as a plain constant of that type does. Older servers parse the new literal as is.

Validation
  • 05137 (9 cells, 11 lines): pristine master fails every cell (the file stops at the first with Code: 386); the fix passes all of them, 50 randomized and 50 non-randomized runs.
  • Mutants: naming only the member fails the array cell (NO_COMMON_TYPE under use_variant_as_common_type = 0); not forwarding date_time_as_numbers fails both DateTime cells (one hour early), and not forwarding it at the shared-variant exit alone fails only the Dynamic(max_types = 0) one; leaving the shared-variant exit unnamed fails the two Dynamic(max_types = 0) cells. Dropping the external-path early return fails 05296, an IN list of Dynamic numbers read from SQLite: it pushes IN ('(3,7)') and loses both rows, where master and the fix push IN (3, 7) and match the local read (50 randomized and 50 non-randomized runs).
  • 45 faces (the ones in A Dynamic constant holding an Enum is re-emitted to a shard as its bare number: remote() reads return the wrong row and diverge from the local plan #119745 plus a sweep of member types) read locally, through remote and through parallel replicas: every read of the fix equals the local one; master differs on 38.
  • 04885_enum_empty_label_json_subcolumn_index with parallel replicas (parallel_replicas_local_plan = 0): master Code: 386, the fix passes, so it needs no no-parallel-replicas tag.
  • 314 dynamic/variant stateless tests and TransformQueryForExternalDatabase.*: no new failure, no reference change.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1852-master (included in 26.10 and later)

groeneai and others added 15 commits September 8, 2026 07:41
columnConstantToExactLiteralASTImpl's TypeIndex::Dynamic branch recursed into the
active member and emitted its bare literal without naming the member's type, so a
secondary server rebuilt the Dynamic from whatever the literal infers back to:
Enum8('7' = 3) became UInt8, Date32 became String, Array(UInt64) became
Array(UInt8). The Variant branch three cases above already names its member type,
which is why a Variant carrier survived the round trip and a Dynamic one did not.

Consequence on any Distributed / remote() / cluster() read: col = <Dynamic
constant> raised NO_COMMON_TYPE on the shard while the same predicate was correct
locally, because the comparison substitutes the active member's type
(FunctionDynamicAdaptor) and getLeastSupertype counts Enum as String-compatible
but not UInt8; and anything the shard computed from the value's own type saw a
type the initiator never held.

Name the member's own type and the Dynamic type at both value exits of the branch,
gating member naming on an allow-list, literalIdentifiesValue, whose default is
"do not name". Naming a type the literal does not determine would invent a value
rather than preserve one: a DateTime renders as local text shared by both instants
of a DST fold, an AggregateFunction state is re-read according to
aggregate_function_input_format, a JSON's dynamic paths are re-inferred from their
tokens, and a String source is re-parsed under
cast_string_to_dynamic_use_inference. Those families keep exactly today's
behaviour; an allow-list is closed under the classes nobody has audited yet,
whereas an exclusion list is not.

Naming the Dynamic type itself is required, not redundant: array and map resolve
their result type from their arguments, so a member that is itself a container of
Dynamic keeps that element type only if every element arrives named as Dynamic.

The declining comment this replaces was written deliberately, in a decimal-focused
PR; its stated reason (naming changes the stored subtype of values whose literal
infers back wider or narrower) is factually right and is precisely the intent, the
change being toward the initiator's own subtype.

Measured, remote versus a purely local read of the same constant, across 34 member
types and both code sites: 6/34 faithful before, 26/34 after, 20 rows repaired, no
new divergence, and every still-diverging row byte-identical to before. The IN leg
is NOT fixed here: it additionally needs the active-alternative hint in
convertColumnToType, so this change does not close it.

ConstantNode::toASTImpl's non-exact path needs no counterpart: typeMayContainDecimal
includes isDynamic() and is applied with forEachChild, so any type containing a
Dynamic takes the exact path first.

Co-Authored-By: Claude Opus 5 <[email protected]>
Follow-up to the previous commit on this branch, which named both the active member's type
and the Dynamic type itself, and named a member wherever it appeared. Two further rounds of
measurement narrowed that in three ways.

Stop naming the Dynamic type. Naming it at every node promotes an enclosing container's
element type to Dynamic, which routes an excluded member's bare text through the re-inferring
String -> Dynamic conversion in createColumnToDynamicWrapper. Measured: a DateTime at a DST
overlap came back at epoch 1698539400 where the initiator held 1698543000, an hour early and
with the same printed text, so a visible type mismatch became a silently different instant.
Dropping it also gives this branch the exact shape of the Variant branch three cases above,
which names its member type and not the Variant type. For a scalar constant the caller already
emits _CAST(..., 'Dynamic') and makeCastToTypeNameAST's identity dedupe collapses the pair.

Two types leave the allow-list, each because its text is not an injective carrier.

  - Floats. Two distinct Float32 NaN payloads, 0x7FC00001 and 0x7FC01234, both reach a
    secondary server as the canonical 0x7FC00000, because all four literals format as the
    single text `nan`; formatFloat says so itself ("Roundtrip may lead to loss of precision",
    FieldVisitorToString.cpp). isFloat() covers Float32, Float64 and BFloat16, so this also
    correctly excludes Point, which is a Tuple(Float64, Float64).
  - Date32. Its serializeText formats through writeDateText(ExtendedDayNum(...)), which
    saturates at DATE_LUT_MAX_EXTEND_DAY_NUM, so day 2932996 and day 2932896 share the literal
    `9999-12-31`; toDate32('9999-12-31') + 100 reaches that from plain SQL. ClickHouse already
    classifies this: ToStringMonotonicity marks Date32 -> String non-injective and Date ->
    String strict, because Date is a UInt16 whose whole domain the day LUT covers. Date stays.

A Dynamic nested inside array() or map() is no longer named at all. Those two resolve one
element type from all their arguments, so elements named as their own concrete types must
acquire a common type: Int64 and UInt64 siblings have none unless use_variant_as_common_type
builds a Variant for them, while master's unnamed literals simply widen. Measured on a mutant
without this rule: NO_COMMON_TYPE where master returns a row. tuple() is deliberately not
suppressed, because FunctionTuple keeps every argument's type independently and performs no
sibling conversion, and an IN list is serialized as a tuple.

Blast radius, measured as a value-and-type oracle over 34 member types at both code sites,
comparing a remote read against the purely local one: faithful round trips go from 6/34 to
21/34. Five families the previous commit repaired are no longer repaired, each for one of the
measured reasons above: Float32, BFloat16, Point, Date32, and the container-of-Dynamic shapes
(Array(Dynamic), Map(Dynamic, Dynamic)). All five are byte-identical to master, in value and
in reconstructed type, so nothing regresses relative to master. A Dynamic nested in a tuple
does move, from Tuple(UInt8) to Tuple(Int64), with its value unchanged.

The test grows to five cells. Cells 1 to 3 redden on pristine master. Cells 4 and 5 are
guards: each reads identically on master and here, and each fails a purpose-built mutant that
drops one of the two restrictions above, so neither restriction can be simplified away
unnoticed.

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit stops naming a `Dynamic` member that sits inside `array()` or `map()`, and
that restriction reaches the walker through three independently revertible call sites: array
elements, map keys and map values. Only the array one was covered by a cell. The existing guard
dies on a mutant that removes the restriction's single shared test, which disables all three at
once, so it could not show that the two `map()` arguments still pass the flag: reverting just
those two left the whole file green.

Add one cell over a `Dynamic`-keyed, `Dynamic`-valued map. `map()` resolves one key type from
all of its keys and one value type from all of its values, so the cell needs two entries; with
a single entry there are no siblings to reconcile and the restriction is invisible.

Measured on a mutant that reverts only the two `map()` call sites: the new cell raises
`NO_COMMON_TYPE`, because the shard receives `map(_CAST(1, 'Int64'), _CAST(3, 'Int64'),
_CAST(2, 'UInt64'), _CAST(4, 'UInt64'))` and `FunctionMap` then has to reconcile `Int64` with
`UInt64` under `use_variant_as_common_type = 0`. That mutant fails this cell alone, while the
mutant without the array rule fails the array cell alone, and the two die in different
resolvers (`FunctionArray::getReturnTypeImpl` versus `FunctionMap::getReturnTypeImpl`), so the
two arms are now pinned separately. The reference is taken from pristine master, which reads
identically here: this cell is a guard, not a repair.

Co-Authored-By: Claude Opus 5 <[email protected]>
The in-tree rulebook reached through the `AGENTS.md` symlink asks for ClickHouse names in
comments to be written as inline code. The sibling comment on `nameDynamicMemberAST` and the
pre-existing `Variant` comment further down already do, so this file disagreed with itself.

Comment text only. The stripped token stream is identical to the previous commit's, and the
recompiled object leaves the binary's build id unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
…cells

`columnConstantToExactLiteralASTImpl` suppresses member naming inside `array` and `map`, whose
element type is reconciled across all arguments, and deliberately does not suppress it inside
`tuple`, which keeps each argument's type independently. Two shipped lines carried that
distinction with no cell able to observe either: the `Tuple` case forwarding
`inside_unifying_container` unchanged, and the shared binary variant's own value exit passing the
flag separately from the regular member exit.

Cell 6 is a repair cell for the `tuple` exception. An `Int64` and a `UInt64` member of a `tuple`
both arrive named, so they coexist under `use_variant_as_common_type = 0`, where pristine master
collapses both to `UInt8`. Cell 7 is a guard for the shared exit: a `Dynamic(max_types = 0)`
inside an `array` has to stay unnamed, and its reference is taken from pristine master, which
reads identically here.

Measured on two further mutants, each one edit against this tree:

- M4 forwards `true` from the `Tuple` case. Cell 6 alone reddens, reading `UInt8` for both
  members, and the shard receives `tuple(1, 2)` instead of
  `tuple(_CAST(1, 'Int64'), _CAST(2, 'UInt64'))`.
- M5 hard-codes `false` at the shared exit's naming decision, leaving the inner recursion alone.
  Cell 7 alone reddens with `Code: 386 NO_COMMON_TYPE` from
  `FunctionArray::getReturnTypeImpl`, because the shard receives
  `array(_CAST(1, 'Int64'), _CAST(2, 'UInt64'))` where this tree sends `array(1, 2)`.

The three earlier mutants keep their single cells: the one without the value-identifies test
fails cell 8, the one without the container restriction fails cells 4, 5 and 7, and the one
reverting only the two `map()` call sites fails cell 5 in `FunctionMap::getReturnTypeImpl`. Every
arm returns the same values, `(1,2)` and `[1,2]`; only the member types differ.

Co-Authored-By: Claude Opus 5 <[email protected]>
The in-tree rulebook reached through the `AGENTS.md` symlink asks for literal ClickHouse names in
comments to be inline code spans, and the newest numbered stateless tests follow it, including the
adjacent distributed sibling `05136_view_over_distributed_ships_filter_to_shards`. An earlier
commit did this for `literalIdentifiesValue`'s comment and missed this file.

Comment text only: type names, setting names, function names and `NO_COMMON_TYPE`. Wording and
line breaks are otherwise unchanged, every executable line is byte-identical, and the
`.reference` file is untouched.

Co-Authored-By: Claude Opus 5 <[email protected]>
The comment enumerated only the value-carrying leaves, while the predicate also admits `String`
and the wrappers `Nullable`, `Array`, `Tuple`, `Map` and `LowCardinality`. A reader comparing the
two found `String` admitted here and string-like rejected a few lines below in
`nameDynamicMemberAST`, with nothing connecting the two. Name the wrappers and point at where the
top-level string-like case is decided.

Comment text only: the token stream of this file, with string literals preserved, is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
…wn cell

`nameDynamicMemberAST` declines to name a member on three independent conditions, and only two of
them had a cell: the container restriction (cells 4, 5 and 7) and the value-identifies test (cell
8). Nothing caught the third, so a contributor collapsing three conditions to two by dropping the
`isStringOrFixedString` disjunct would keep CI green while changing what a shard rebuilds, because
`literalIdentifiesValue` accepts `FixedString(3)`.

Cell 9 catches that deletion. Built against a tree with only that disjunct removed, the cell reports
`FixedString(3)` where it reports `String` here, since with
`cast_string_to_dynamic_use_inference` off the receiving cast keeps the name the initiator wrote.
The cell reads identically on pristine master and on this branch, so it is a guard, not a repair.

The `SETTINGS cast_string_to_dynamic_use_inference = 0` clause is what keeps that catch possible:
measured with the setting on, the build missing the disjunct is indistinguishable from this one,
because the receiving conversion re-parses the named `FixedString` back to the inferred type. A
plain `String` member cannot serve here at all, since naming `String` changes nothing and such a
cell reads the same on every build. The value fills the type exactly, so no padding reaches the
reference.

Cells 1 to 8 keep their numbers and their reference lines byte for byte.

Co-Authored-By: Claude Opus 5 <[email protected]>
The comment gave one reason for skipping a string-like member: that the receiving cast re-parses it
under `cast_string_to_dynamic_use_inference`. That holds only when the setting is on. With it off,
which is the default, a named `FixedString` is not re-parsed, it sticks, so the sentence did not
cover the case the new cell 9 measures. The property that does hold either way is that naming a
string-like member would make the type arriving at the shard depend on a receiving-side setting,
where leaving it unnamed gives `String` under both values.

Comment text only. The comment-stripped, whitespace-collapsed token stream of this file is
byte-identical across the edit, checked against two negative controls that do detect a one-token
code change.

Co-Authored-By: Claude Opus 5 <[email protected]>
…se AST

`getASTForExternalDatabaseFromQueryTree` lowers the query tree with `add_cast_for_constants = false`,
so a `Dynamic` constant reaches `ConstantNode::toASTImpl`'s exact-literal path and is returned as the
bare member AST that this branch now names. `ReplacingConstantExpressionsMatcherNumOrStr` then fires
on that `_CAST` function node, and for a member type `isNumber` rejects it re-serializes the folded
value as text: an `Enum8` becomes the enum's name, not its underlying value. Pushdown is only a
pre-filter, sound while the pushed predicate selects a superset of the one ClickHouse re-applies, so
pushing the name where the value was pushed before drops rows. Measured against a SQLite table
holding '7', '3' and 'x', with an `Enum8('7' = 3)` member: `IN (3)` returned row 3 and `IN ('7')`
returns nothing, `NOT IN (3)` returned 7 and x and `NOT IN ('7')` returns only x.

An external database has no `Dynamic` at all: it reads whatever literal arrives as text, so naming
the member is meaningless there by construction, the same way `_CAST` itself must not reach it. So
the external entry point is the one that declines, through a new `ConvertToASTOptions` flag threaded
into `columnConstantToExactLiteralAST`; every other caller keeps today's behaviour, `ReadFromRemote`
via the defaulted overload and the cross-replication lowering by not setting the flag.

The decimal, `DateTime64` and `Time64` carriers are deliberately left alone: master emits those on
the external path too, so suppressing them would change pre-existing decimal pushdown. The `=` shape
is restored to master's bytes as well, which means giving up an accidental repair: master's
`"field" = 3` is not a superset of `field = '7'` either, and fixing that is a separate question about
external pushdown for `Dynamic` constants, not about which literal this walker writes.

Co-Authored-By: Claude Opus 5 <[email protected]>
…e skip

`literalIdentifiesValue`'s comment said naming a string-like member "cannot help", which is true of
the value (the text is identical either way) and false of the type, which is exactly what
`nameDynamicMemberAST`'s comment three lines below says naming would change. Only the parenthetical
is rewritten, to point at the other block instead of pre-empting it.

Comment text only. The comment-stripped, whitespace-collapsed token stream of this file is
byte-identical across the edit, and a negative control that turns the same clause into one line of
code does show a difference.

Co-Authored-By: Claude Opus 5 <[email protected]>
…with its own case

`05138`'s `IN list` cell can only observe ROWS, and its local recheck repairs the fixture under every
mutation, so that cell reads `3` whether the pushed predicate is `IN (3, 4)`, `IN ('7', '3')`, or
absent altogether. The single-element cell is not blind (a named member pushes `IN ('7')`, SQLite
returns 7, the recheck rejects it and the cell goes empty), which is precisely why the multi-element
form needs an assertion of its own rather than inheriting confidence from its sibling. A
multi-element right-hand side travels as one constant `tuple`, so it is the only shape that observes
the member type being left unnamed inside `tuple` elements as well, and only the generated text can
show that.

Measured: the transformed query is `WHERE "field" IN (3, 4)`, the enum values. With the naming
opt-out ignored, the same list leaves as ONE quoted string holding the tuple's text,
`'(\'7\',\'3\')'`, which against a `TEXT` column matches no row at all; the three existing cells fail
differently, as `= '7'`, `IN ('7')` and `NOT IN ('7')`. The `TransformQueryForExternalDatabase` suite
is fully green with the new case, and red on that mutant alone.

Co-Authored-By: Claude Opus 5 <[email protected]>
`AGENTS.md` asks for `f` rather than `f()` in documentation, comments and commit messages, where the
text names the function itself rather than its application. All four sites do: `materialize`,
`dynamicType`, `array` and `map`. That is the complete set of parenthesised function names in this
branch's whole diff; `05138`, the gtest and every `src/` comment were already clean.

Comment text only. The comment-stripped, whitespace-collapsed token stream of the file is
byte-identical across the edit, with a negative control changing one executable token to show the
comparison does move, and a second control confirming a comment-text-only change does not.

Co-Authored-By: Claude Opus 5 <[email protected]>
The `Dynamic` branch of the exact literal serializer has two value exits and each
forwards `name_dynamic_member_types` on its own: the regular member exit and the
shared-binary-variant exit that decodes `Dynamic(max_types = 0)` values. Every
existing external-path case uses a default `Dynamic`, so all four of them traverse
the regular exit only, and the one test that reaches the shared exit runs on the
shard path where naming is enabled anyway.

The whole suite therefore stays green if the shared exit stops honouring the
opt-out, while an external database receives the enum's name `'7'` instead of its
value `3` and the pushed predicate silently selects the wrong rows.

The generated text was measured before the expected string was trusted: a
temporary probe printed the transformed query for every case in the file, and the
new one came out as `WHERE "field" = 3`. A single-exit mutant that hard-codes the
shared exit's flag reddens this case alone.
A constant of type `Dynamic` whose active member is `Tuple(Dynamic, ...)` is only
partly left alone. The `Tuple` branch recurses with the container flag unchanged,
so the nested `Dynamic` elements are named one level down, and then the outer
member type declines because a `Tuple` holding `Dynamic` is not a type whose
literal identifies its value.

The shard consequently rebuilds `Tuple(Int64, UInt64)` where master rebuilt
`Tuple(UInt8, UInt8)`, while the initiator held `Tuple(Dynamic, Dynamic)`. Both
arms carry the same values, so nothing a comparison can observe changes, but the
rebuilt type moved and no cell was watching it.

Both values are measured, not predicted: the statement was run on the shipped tree
and on a pristine-master server, each with `buildId()` asserted first.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change against the code; I adjudicated its findings and my own.
This was the last of six internal rounds, so the two 💡 notes at the end are recorded rather than
acted on.

❌ "Naming the member breaks external-database IN/NOT IN pushdown" - AGREED, and it did.
Naming makes the pushed literal a function node, and on the external path
ReplacingConstantExpressionsMatcherNumOrStr fires on function nodes and re-serializes anything
isNumber rejects as text, so an Enum8 member arrived as the name '7' where its value 3 used to.
Pushdown is only sound while the pushed predicate selects a superset of the one ClickHouse re-applies,
so that dropped rows: against SQLite, IN (3) returned row 3 and IN ('7') returned nothing. The
external lowering now declines the naming through one ConvertToASTOptions flag and emits master's bytes.

⚠️ Test liveness of the container rule - AGREED, fixed, three times. The rule that stops a Dynamic
member being named inside array/map reaches the walker through independently revertible arguments, so
one shared cell could not show that each is still there. Each arm is now pinned by its own cell, verified
against a mutant reverting only that arm: the two map arguments, the shared-binary-variant exit, the
deliberate tuple exception, and the string-like skip. The two external shapes the row-level test cannot
see are pinned by gtest cases on the exact pushed text: a multi-element IN, whose mutant right-hand side
becomes the single string '(\'7\',\'3\')', and Dynamic(max_types = 0), the only instrument here that
sees the shared exit forward the opt-out.

❌ "Also name Interval, Time, LowCardinality(DateTime) and FixedString" - DISAGREED. Each of
those reaches a secondary server exactly as it does today, byte for byte, so none is a regression this
introduces, and the changelog states the condition rather than promising every type. Recorded anyway:
getFieldFromColumnForASTLiteralImpl has no LowCardinality case, so a LowCardinality(DateTime) member
is emitted as a bare epoch number rather than the ambiguous local text the DateTime carve-out is about.
These are missed repairs, not defects; the predicate tests children, so it can only over-exclude.

⚠️ One composite is only partly left alone - AGREED as a disclosure, not as a regression. A Dynamic
whose active member is Tuple(Dynamic, ...) has its tuple members named one level down while the outer
member type still declines, so it arrives holding Tuple(Int64, UInt64) where master gave
Tuple(UInt8, UInt8); the initiator held Tuple(Dynamic, Dynamic), which neither reproduces. Values are
identical and no comparison that succeeds on master fails here, so it is stated in the description and
pinned by a cell rather than changed. array/map do not have it: they suppress nested naming outright.

💡 The = cell of the external-pushdown test records an answer that is wrong and stays wrong: the
external read drops the row the identical local read returns, because master's pushed "field" = 3 is not
a superset of field = '7' either. Pre-existing, restored rather than caused here, and kept because it
detects a mutation that flips it.

💡 Merge order. This carve-out matches master's pushed literal against today's local IN semantics, which
#117998 changes: when that lands, 05138's external cells move with it and the sound pushed literal
becomes the enum name, so the carve-out is worth revisiting then rather than reading as permanent.
Separately, #98938 (rewriting a single-element IN into =) would change the pushed text two gtest cases
pin - a mechanical expectation update for whichever merges second. And the Variant branch three cases
above names its member unconditionally, including inside array/map, so it carries the same exposure
this guards for Dynamic: pre-existing and untouched here, noted because it is why Variant never
appeared to need the guard.

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78150b9]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-348f) FAIL cidb

AI Review

Summary

This PR fixes the main Dynamic subtype-loss problem on distributed reads, and the added stateless coverage does a good job pinning the ordinary remote, parallel-replica, and external-SQLite paths. I still see one remaining correctness hole: the new unconditional member-naming path can change the value of a Dynamic member whose own literal does not round-trip, so the same folded Dynamic constant can still evaluate differently locally and on the shard.

Findings

⚠️ Majors

  • [src/Analyzer/Utils.cpp:1894] [dismissed by author -- https://github.com/Name a Dynamic constant's active member type in the shard-facing literal #118988#issuecomment-5915252629] name_member now re-applies the active member type for every Dynamic value, but some member literals are still non-injective. In particular, getFieldFromColumnForASTLiteralImpl renders Date32 through text at src/Analyzer/Utils.cpp:1549, which saturates out-of-range day numbers, and Time is reconstructed from raw ticks through _CAST(<number>, 'Time'), which clamps out-of-range ticks. That means a folded Dynamic(Time) / Dynamic(Date32) constant inserted through binary paths can still match locally and miss remotely after this change. I still consider this real because the contract here is local-vs-remote equivalence of the same Dynamic constant; the fact that a plain typed constant already saturates on the shard does not preserve that invariant.
  • Suggested fix: keep the old opt-out for member types whose literal is not injective, or make the naming decision value-aware for the known non-round-tripping cases instead of applying it unconditionally.
Final Verdict
  • ⚠️ Needs changes before merge: the main fix is sound, but the unconditional member naming still changes results for out-of-range Time / Date32 members.

LLVM Coverage Report

Measured on commit 78150b9.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +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 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @Avogar, could you review this? A folded Dynamic constant reached a secondary server with its active member's type dropped, so an Enum8('7' = 3) member was rebuilt as UInt8 and the shard-side comparison raised NO_COMMON_TYPE where the same predicate worked locally. @yakov-olkhovskiy, this reverses the scoping note you added in 739dbfd: I keep it for every member whose literal is not injective (floats, Date32, DateTime, JSON, AggregateFunction states, string-like) and name only the ones where the literal does identify the value, so your call on whether that is the right split.

Comment thread src/Analyzer/Utils.cpp Resolved
@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 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 78150b928 with master 41ffcf2a3 (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, 11 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bb7a383

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
Bugfix validation (unit tests) inconclusive by the job's own fail-closed guard, not a refutation of the regression test: Submodule state differs between the merge-base and the checkout (.gitmodules, contrib/bs-thread-pool, ..., contrib/usearch), so the before-worktree cannot be populated at the merge-base revisions. The base branch moved those submodules after this branch split; the diff here touches no submodule and no .gitmodules (0 of 10 changed paths). Breadth 29 rows / 22 pull requests in 7 days since a 2026-09-02 onset, 0 master runs #117948 (mine, open)
Stress test (amd_msan) / Segmentation fault (STID: 2076-288c) crash: SIGSEGV on a null AST child inside DB::InDepthNodeVisitor<...CustomizeFunctionsData...>::visitChildren (src/Interpreters/InDepthNodeVisitor.h:83) during TreeRewriter normalization, reached from children.resize(prefix_size) in ReadFromMergeTree.cpp when the read-in-order prefix outruns the sorting key. Breadth 4 rows / 4 pull requests / 0 true-master runs in 30 days across four Stress parametrizations (amd_msan, arm_msan, arm_asan_ubsan, arm_asan_ubsan, s3); the diff here touches neither MergeTree reading nor the old analyzer #116364 (mine, open)

Mergeable Check and PR are the praktika rollups of the two rows above and carry no separate
failure of their own. The rest of the run is green: 152 of 174 check runs pass, 18 skipped, and the
CI database records exactly the two non-green jobs listed above at this head.

Session id: cron:our-pr-ci-monitor:20260909-153035

@groeneai

Copy link
Copy Markdown
Collaborator Author

@yakov-olkhovskiy a follow-up on the split above, because the situation changed and I would rather have your call than force it.

This PR is now conflicting. Master has since threaded a date_time_as_numbers parameter through the same recursive columnConstantToExactLiteralASTImpl, so the two parameter sets have to be unioned across 14 conflict hunks in 5 files. More to the point, the Dynamic branch on master carries your note verbatim ("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"), so resolving the conflict means rewriting that comment. I am not going to do that as part of a merge resolution.

One result worth reporting, because it argues your way: when the review bot asked me to extend the predicate to Time, I implemented it and measured a regression rather than a fix. A raw tick outside Time's range (4000000, inserted via RowBinary, prints 999:59:59) saturates to 3599999 when its literal is cast back, so WHERE t = CAST((SELECT t FROM tt) AS Dynamic) matched 1 row without that change and 0 rows with Time named. I declined the bot's ask for that reason: #118988 (comment). So the injectivity predicate is load-bearing rather than cosmetic, and getting its membership wrong silently drops rows.

One question, then: should a Dynamic constant's active member type be named when its literal identifies the value, or does your note stand as written? If it stands, say so and I will close this PR and leave the subtype loss over remote() as a documented limitation.

Master now carries the pieces a much smaller change needs: the `Variant` case of
the exact literal serializer names both the member type and the whole `Variant`,
and `date_time_as_numbers` already marks the one consumer (the external-database
pushdown) that parses a literal itself instead of re-applying its declared type.

So this reverts the six source files to the branch's merge base and drops the
external-pushdown test. The `Dynamic` case is rewritten on top of current master
in a following commit, which also rewrites `05137`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fm4v
fm4v enabled auto-merge October 8, 2026 12:06
@fm4v
fm4v added this pull request to the merge queue Oct 8, 2026
Merged via the queue into ClickHouse:master with commit ce68860 Oct 8, 2026
150 of 152 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 10, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 13, 2026
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]>
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 removed the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 2, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Nov 3, 2026
Cherry pick #118988 to 26.9: Name a `Dynamic` constant's active member type in the shard-facing literal
robot-clickhouse added a commit that referenced this pull request Nov 3, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #118988 to 26.9: Name a `Dynamic` constant's active member type in the shard-facing literal
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Nov 3, 2026
The bugs behind their `no-parallel-replicas` / `no-replicated-database` tags are fixed on master:
- `01660_join_or_any`: ClickHouse#123683
- `04653_bloom_filter_fixed_string_constant_scalar`: ClickHouse#118988
- `04819_dynamic_aggregate_function_state_version`: ClickHouse#123649
- `04825_quantile_deterministic_alter_add_modify_column`: ClickHouse#115393, ClickHouse#123070
- `04494_atomic_populate_materialized_view_parallel_replicas`: ClickHouse#124477
- `04266_text_index_tokens_cardinality_order`: ClickHouse#124500 already disables parallel replicas for the log-checked query

Related: ClickHouse#124015
leshikus pushed a commit that referenced this pull request Nov 13, 2026
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-review-bot PR origin: review-bot finding on a groeneai PR pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A Dynamic constant holding an Enum is re-emitted to a shard as its bare number: remote() reads return the wrong row and diverge from the local plan

6 participants