Skip to content

Read Arrow unions with the requested Variant alternative types - #119098

Open
groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:groeneai/arrow-ipc-union-variant-hints
Open

groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:groeneai/arrow-ipc-union-variant-hints

Conversation

@groeneai

@groeneai groeneai commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110531

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 reading an Arrow or ArrowStream union column with an explicit Variant structure whose alternative types differ from the ones inferred from the Arrow schema, which failed with CANNOT_CONVERT_TYPE on a readable file. This also broke ClickHouse's own round-trip: the native Arrow writer stores IPv6 as fixed_size_binary(16), so a file written from Variant(IPv6, String) could not be read back with Variant(IPv6, String), and one written from Variant(IPv6, Int128) could not be read at all (INCORRECT_DATA).

Description

decodeUnion builds a union's Variant from the Arrow schema alone, and the outer Variant -> Variant cast can only append alternatives, never substitute one:

Cannot convert type Variant(FixedString(16), String) to Variant(IPv6, String).

On 26.8.10.6 that rejects readable files, including ClickHouse's own: it stores Enum8 as int8, IPv4/DateTime as uint32, opt-in Date as uint16, coarse Interval as int64.

This adds a Variant arm to reinterpretRawBytes, the post-decode walk that re-declares a column under the requested type. Each element takes the alternative the request forces on it, resolved as the ORC reader resolves union branch hints (#110078). An ambiguous element is left alone; two never share an alternative name. A read that succeeds today stays byte-identical.

Never substituted: a date32 branch (only the decoder's hint decides its range handling), composites (a cast between tuples with disjoint names converts positionally), and timestamp to DateTime (would wrap). So Variant(Date, String) cannot round-trip at default settings.

Children inferring one type (the writer stores IPv6 and Int128 alike) were rejected with INCORRECT_DATA before any of this ran. The writer names each child after its type family, so schema inference and decoding now tell them apart by name (IPv6, UUID, 128/256-bit integers, IPv4, DateTime, uint16 Date). Still rejected: alternatives whose parameters a name cannot carry (Enum8, DateTime64) and Date beside Date32, all needing allow_suspicious_variant_types; composites such as Variant(Array(IPv6), Array(Int128)); opaque types.

Dense children whose rows reference slots out of order or twice are now gathered too: a dictionary or filter over them returned wrong values.

Found by the review bot on #110531, raised by @ nihalzp: #110531 (comment)

New test 05141_native_arrow_ipc_union_variant_hints: 32 sections failing on master plus 8 writer round trips (Arrow and ArrowStream), 14 controls.


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

groeneai and others added 6 commits September 8, 2026 19:50
The native Arrow IPC reader maps an Arrow union to a ClickHouse Variant, but
builds that Variant from the Arrow schema alone: decodeUnion decodes every
child with no requested-type hint and types each element with fieldToCHType.
The only reconciliation left is the outer Variant -> Variant cast, which
matches alternatives by name and can only append them, never substitute one,
so it throws CANNOT_CONVERT_TYPE for any decoded alternative the requested
structure does not name. A readable file is then rejected:

  Cannot convert type Variant(FixedString(16), String) to Variant(IPv6, String).

That includes files ClickHouse wrote itself, since the native Arrow writer
stores IPv6, Int128 and UInt128 as fixed_size_binary(16), Enum8 as int8, and
IPv4 and DateTime as uint32. A file written from Variant(IPv6, String) could
not be read back with Variant(IPv6, String).

Add a Variant arm to reinterpretRawBytes, the post-decode walk that exists to
re-declare a decoded column under the requested type and already returns the
(column, type) pair its caller assigns before the cast. It pairs each decoded
element with the alternative the requested Variant forces on it, repairs the
element through the ordinary recursion (so a raw-byte element converts exactly
as the same bytes would in a plain column, including declining a wrong-width
value and leaving it to the cast), and rebuilds the column with its new type.

The pairing mirrors the native ORC reader's computeOrcUnionBranchHints, which
solves the same problem for ORC unions: Variant sorts its alternatives, so the
positional correspondence with the Arrow children is lost and has to be
reconstructed structurally. Candidate matrix, then singles elimination with
cross-element erasure, then at most one uncontested natural-pairing preference
per round. An element whose correspondence stays ambiguous is left unassigned,
so no guess is ever made, and assignments that would leave two elements on one
alternative name are dropped, which is the post-decode counterpart of the
duplicate-child check decodeUnion already performs.

Two bounds keep the blast radius provable. Decoded element names are unique, so
when the requested set merely extends the decoded one every element's exact
alternative is its unique uncontested preference and the arm is a no-op: a read
that succeeds today is byte-identical. And the arm returns the column untouched
unless every element lands on a requested alternative, so a read that fails
today fails with the byte-identical message; the only behaviour change is that
some reads rejected today now succeed.

Two element kinds deliberately get no alternative. A date32 element, because
whether a day number is copied verbatim, range-checked or saturated is decided
inside the decoder from its own hint, which this post-decode layer cannot
supply, and 05060_native_arrow_ipc_dictionary_date32_numeric pins that a
numeric target must return it verbatim. And composites, because castColumn
pairs tuple fields by name while this walk preserves the decoded names, so a
name-differing target field would be filled with defaults instead of failing.

Found by the review bot on ClickHouse#110531 and passed on by @nihalzp:
ClickHouse#110531 (comment)

Related: ClickHouse#110531

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

A dense Arrow union child keeps every slot it declares, and the Arrow spec
leaves the bytes of a slot no row selects undefined. decodeUnion gathers the
elements itself only when the union is sparse, an ancestor mask is present, the
children declare more rows in total than the union has, or some child carries a
null map; otherwise the element column reaches the Variant repair with those
unreferenced slots still in it, addressed by raw Arrow offsets.

The repair converts values, so it must not see them. The raw-byte width sniff
declines for the whole element on any row whose width does not match, dropping
it into a cast that text-parses raw bytes, and the cast itself can throw on any
row. So one unobservable byte decided whether an observable read succeeded:

  union<binary not null, int32 not null>, type ids [0,0,0,1], offsets [0,0,2,0],
  binary child ["\x00"*15+"\x01", "zz", "\x00"*15+"\x02"], int32 child [42]

read as Variant(IPv6, UInt32) threw CANNOT_PARSE_IPV6, although no row selects
the 2-byte slot and every value the query can see is a well-formed 16-byte
address. That is the class ClickHouse#110531 fixed elsewhere in this file, and the
decoder's own leaf calls pass a visibility mask for the same reason.

Gather each element down to the rows referencing it, in row order, and emit
fresh offsets before repairing. Two rows may legitimately reference one slot, so
the value is duplicated: ColumnVariant requires exactly one element value per
row that selects the element. The gather runs only on the path that repairs, so
a read that succeeds today is still returned untouched.

Also narrow what the arm claims about failures. The subset pre-check bails only
when an element is left unassigned, so a request no assignment can satisfy keeps
its exact message, but where every element is assigned the read now reaches the
values: union<binary, int32> holding an unparseable value, read as
Variant(IPv6, UInt32), reports CANNOT_PARSE_IPV6 where it reported
CANNOT_CONVERT_TYPE. The file is rejected either way and the new message names
the value that is actually wrong, so the message is pinned by a test arm rather
than suppressed.

The preference round's contested check is removed as unreachable: the preference
is name equality and decoded element names are pairwise distinct, so two
elements can never prefer one alternative.

Co-Authored-By: Claude Opus 5 <[email protected]>
An element that no conversion arm admits was never a candidate for anything, so
it left its own alternative available to a sibling, and that sibling was then
ambiguous. union<uint32, date64> read as Variant(UInt64, DateTime) was rejected
although both branch conversions are ones the flat column path performs: date64
decodes to DateTime, no arm admits a decoded DateTime, and the uint32 element
then held both DateTime and UInt64 and preferred neither, so nothing was
assigned and the outer cast rejected the read.

Admit the decoded type itself before every conversion arm, reusing
variantElementPrefersType so that preference is visibly a subset of matching. No
conversion arm is added and no exclusion is relaxed: an excluded element is still
never substituted, only reserved.

Reserving cannot change a value. The target carries the decoded name, so it
contributes nothing to the change test and the name check then skips the cast,
and the only decode in this format that depends on the requested type, date32, is
hint-sensitive only when that type differs from Date32.

Two arms pin the two halves: union<uint32, date64> as Variant(UInt64, DateTime)
for the disambiguation, and union<uint32, date32> as Variant(UInt64, Date32) for
value safety, its day numbers compared against the same days read through the
flat date32 column path. The DateTime arm pins session_timezone, which
clickhouse-test randomizes over five non-UTC zones and DateTime renders in.

Co-Authored-By: Claude Opus 5 <[email protected]>
Three alternatives a decoded Variant element could not take, although the
ordinary column path reaches all three from the same decoded type:

  - DateTime -> DateTime. Arrow date64 decodes to a zoneless DateTime
    (SchemaConverter.cpp:1047-1050), so union<uint32, date64> read as
    Variant(UInt64, DateTime('UTC')) was rejected while the flat date64 column
    returns those values as DateTime('UTC'). Relabelling to another time zone
    now joins the DateTime64 and Time64 relabel arms.
  - UInt16 -> Date, never Int16: the native Arrow writer stores Date as uint16
    under output_format_arrow_date_as_uint16 (:696-706), every UInt16 value is a
    valid day number, and castColumn maps Int16 -1 to day 65535.
  - Int64 -> Interval, never UInt64: the writer stores every Interval kind
    coarser than a second as a signed int64 (:715-731), and a large UInt64 value
    would wrap negative. All interval kinds share TypeIndex::Interval, so a
    request naming two of them leaves the element ambiguous and unassigned.

Variant(Date, String) and Variant(IntervalDay, String) therefore round-trip
through ClickHouse's own Arrow writer. Variant(Date, String) at default settings
still does not: the writer emits date[DAY], which decodes to Date32, the one
scalar kind this walk never substitutes.

The Bool/UInt8 contract comment was wrong in both halves and is rewritten. The
code does permit Bool -> UInt8, since isBool(decoded) tests which.isUInt8(), and
the bool_utf8 arm depends on it; only the reverse is blocked, and its reason is
value fidelity rather than ambiguity, because an Int8 or UInt8 value outside 0/1
would render as true.

Four arms and one control. The zoned DateTime relabel; a duration branch
claiming its own alternative against an int64 sibling that admits every interval
kind, which is what makes claiming observable at all; the two writer
round-trips; and a branch that is neither assignable nor requested, which pins
that the repair is then abandoned and the request keeps the message it reports
today.

Co-Authored-By: Claude Opus 5 <[email protected]>
Arrow date64 decodes to a zoneless DateTime and Arrow timestamp[u] decodes to
DateTime64(u*3, tz) (SchemaConverter.cpp:1047-1059), and neither decode reads
the requested-type hint: the date64 branch is data[i] = src[i] / 1000
(RecordBatchDecoder.cpp:799-807) and the Timestamp branch is a bare fillFixed
(:810-816). All the hint-driven range and scale machinery at :753-771 belongs to
date32 alone. For these two decoded types the flat column path is therefore
exactly decode-then-castColumn, which is what this post-decode walk does, so
union<uint32, date64> read as Variant(UInt64, DateTime64(3, 'UTC')) was rejected
while the flat date64 column returns those instants as DateTime64(3, 'UTC').

The reverse direction stays refused. DateTime64 -> DateTime is a narrowing: it
drops sub-second precision and silently wraps any value outside DateTime's
1970-2106 window, the same wrap the decoder's own date32 range check exists to
prevent (:747-749). The matcher already refuses every lossy narrowing on that
rule, so this is the existing rule applied rather than a new exception: a decoded
Float64 admits only Float64, variantElementWidensTo compares strictly so no
integer narrows, and a decoded FixedString(n) demands the target's n be equal.

Widening cannot un-force an element and so cannot break a read that succeeds
today, although adding a candidate normally could: a decoded DateTime offered
both DateTime and a DateTime64 prefers DateTime by name equality, so it is
assigned in the preference round rather than the singles round and lands on the
same alternative. Decoded element names are pairwise distinct, so that preference
is never contested.

Two arms cover the UInt32 -> IPv4 and UInt32 -> DateTime clause, which nothing
depended on: both existing uint32_date64 arms send the uint32 branch to UInt64
and take their DateTime value from the date64 branch, so deleting the clause
reddened no test. The new fixture puts a uint32 branch beside a utf8 branch that
can take neither special target, since rawByteWidth covers only IPv6, Int128,
UInt128, Int256 and UInt256, which forces the uint32 branch to take them itself.

Three arms and one control: the DateTime64 rescale, IPv4 and bare DateTime from
uint32, and an Arrow timestamp branch offered the narrowing DateTime, which pins
the refusal and is therefore green on master too.

Co-Authored-By: Claude Opus 5 <[email protected]>
Every other clause of the element matcher is permissive: deleting one only
removes a candidate, so an element is either left unassigned, and the read is
rejected with the message master already reports, or forced onto an alternative
that is still admissible, which by construction is one the flat column path
reaches. Two clauses are not like that, and each returns a wrong value when it is
relaxed, so each gets a control arm.

An int8 branch is never re-declared as Bool. Bool is a custom-named UInt8 and the
two compare equal, so without that clause the walk itself decides which branch
lands on Bool: on Variant(Bool, UInt8) requested over a decoded Variant(Int8,
UInt8) the uint8 branch takes its own name first and the int8 branch is then
forced onto Bool, and -8 reads back as true. The fixture carries no bool branch,
because a bool branch would claim Bool by name equality and the clause would
never be consulted; both of its values are outside 0/1 so the mode is visible.

A composite branch is never re-declared either. This walk keeps the decoded field
names, and a cast between tuples whose field names are disjoint converts
positionally, so admitting a Tuple alternative would return the decoded field
under the requested name: struct<a int32> as Tuple(b Int32) comes back as (1),
where the flat struct column read with the same requested type returns (0). Where
the names overlap the cast pairs them by name and defaults the unmatched target
field, which is what the flat path does too, so it is the disjoint case that puts
this clause outside the flat path's behaviour.

Both arms are rejections on master as well as here, so they are controls rather
than base-versus-fix arms: they pin behaviour this change does not alter.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

I reviewed the resulting code cold, had an independent model re-review it, and adjudicated both against
the recorded validation evidence. Six rounds; five returned a fix plan, and every blocker below was a
real defect the first version would have shipped.

Finding Resolution
❌ Dense-union slots that no row references reached the element repair, so an unobservable slot's bytes could decide whether an observable read succeeded. Such a slot survives the decoder's own gather when the children are non-nullable and the per-child row count still fits. Fixed: elements are gathered down to their referenced rows, in row order, before any repair. The fixture builds that layout by hand, since UnionArray.from_dense cannot express it.
❌ An element whose decoded type no conversion arm admitted did not claim the alternative that is its own type either, so it left that alternative to a sibling and the sibling stayed ambiguous: union<uint32, date64> as Variant(UInt64, DateTime) was rejected although both element conversions are ones the flat column path performs. Fixed: an element claims its own alternative before any conversion is considered. Claiming is not converting, so such an element is returned byte-identical.
❌ A decoded DateTime could not take a DateTime64 alternative, which the flat column path does reach: the date64 and timestamp decodes read no requested-type hint, so for them the flat path is exactly decode then cast. Fixed. The narrowing reverse stays refused: DateTime64 to DateTime drops sub-second precision and wraps outside 1970 to 2106, on the same rule that refuses every integer and Float64 narrowing. Pinned by a control arm.
❌ Three alternatives the ClickHouse Arrow writer's own encodings need were unreachable: another time zone for a decoded DateTime, Date from a uint16, and an interval kind from an int64. Fixed, each with a round-trip arm through the writer.
⚠️ The two matcher clauses that would return a wrong value if relaxed had no arm: an int8 element must never be re-declared as Bool (Bool is a custom-named UInt8, so the two compare equal and -8 would read back as true), and a composite element must never be re-declared. Every other clause is permissive, so relaxing it can only leave an element unassigned. Fixed: one control arm each, green on master, reddened only by deleting its own clause.
⚠️ The subset pre-check that keeps today's rejection message was unexercised, and the retained-slot arm could not fail as written. Fixed: an arm whose request no assignment can satisfy, and a retained-slot arm that reddens when the gather is skipped.
💡 Wording noted and not blocking: at the composite exclusion the diff comment names the by-name half of createTupleWrapper, while the case the new arm pins is the disjoint-name half, which converts positionally (both justify the exclusion; the description and commit d49a1167 state both halves). The uint32_date64 fixture comment predates the DateTime and DateTime64 arms it now sits beside. Noted.

One dismissal, with its measurement: a Variant(Time, ...) round-trip through the writer cannot be
repaired at this layer or any other, because no Time64 to Time cast exists, so it fails on the flat
column path too. It is disclosed in the description rather than fixed here.

Session id: cron:clickhouse-review-slot-8:20260909-194100

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

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3d6654e]

Summary: ✅


AI Review

Summary

Reviewed #119098 at 3d6654efadd54daea24eb5af69ee28632d400829, including all eight review threads and their replies. The change reconciles decoded Arrow union alternatives with requested Variant types, distinguishes colliding writer encodings, and normalizes dense-union offsets. No actionable findings remain within the stated scope. Earlier dictionary and overflow-policy findings are addressed; the author's documented conversion exclusions are accepted.

Consumers traced for the changed union representation:

  • Schema inference and batch type construction share unionElementTypes, matching the decoder's alternative types.
  • Dictionary registration and delta appends receive normalized element layouts; type repair waits until materialization.
  • Array, tuple, map, and run-end decoding preserve the normalized layout through copying, indexing, and filtering.
  • The shared buildChunk path for Arrow, ArrowStream, and Vortex reconciles the column and declared type before the final cast; repairVariantElements rebuilds the discriminator mapping by alternative name.
Missing context / blind spots
  • ⚠️ No local build was available, so tests were not rerun independently. The review used the focused regression test and the author's recorded before/after results. Current-head CI was still incomplete when inspected; its completed functional results will close that verification gap.
Final Verdict

Status: ✅ Approve

@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
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization: union<fixed_size_binary(16), utf8> read as Variant(IPv6, String) fails on master with Code: 70 CANNOT_CONVERT_TYPE. Eight shapes measured on unmodified master before any edit, including the writer round-trip INSERT INTO FUNCTION file('rt.arrow', Arrow, 'v Variant(IPv6, String)') followed by reading the same file back with the same structure.
b Root cause explained? decodeUnion (RecordBatchDecoder.cpp:1365) decodes every union child with target_hint = nullptr (:1440, :1442) and types each element from fieldToCHType (:1444), so the decoded Variant is a function of the Arrow schema alone. The only reconciliation left, castColumn at ArrowIPCBlockInputFormat.cpp:1059 -> createVariantToVariantWrapper (FunctionsConversion.cpp:1930), matches alternatives by name and can only append them, throwing at :1968-1973. reinterpretRawBytes (:670), the walk whose job is re-declaring a decoded column under the requested type, had no Variant arm.
c Fix matches root cause? Yes: the missing reconciliation is added at the only layer that can carry it, since reinterpretRawBytes already returns (column, type) and its caller assigns both before the cast. No bound widened, no tag added, no error suppressed. The same reconciliation is applied uniformly rather than per type: an element admits the alternative that is its own decoded type before any conversion arm is consulted, so an element no conversion reaches cannot strand its sibling by leaving that alternative unclaimed. A decoder-side repair cannot report a repaired element type: ColumnVariant stores no element types and decodeBatchColumn:1893 re-derives the type from the schema.
d Test intent preserved / new tests added? New 05141_native_arrow_ipc_union_variant_hints.{sh,reference}, 32 sections: 22 that fail without the change and 10 controls (the date32 substitution exclusion, the refused DateTime64 -> DateTime narrowing, the two exclusions whose relaxation returns a wrong value instead of rejecting the read (an int8 branch never re-declared as Bool, a composite branch never re-declared), the three rejection paths, whole-file schema inference, a superset request, and the flat date32 column the union Date32 branch is compared against). SQL/.sh rather than gtest. No existing test modified.
e Both directions demonstrated? Yes, arm by arm against both binaries: base 29a4d2de gives 22 of 32 sections red with all 10 controls green; the fix gives 0 of 32 red, 50 of 50 randomized runs. The whole arrow/orc selector (225 tests) was also run on both binaries and the failure name sets differ by exactly one line, 05141 itself. Each predicate added here has a mutation that reddens exactly its own arm and nothing else, and so does each of the two exclusions: deleting the Bool guard makes -8 read back as true, and admitting a Tuple alternative makes a name-differing field come back holding the neighbouring field's value.
f Fix is general across code paths? The arm sits in the shared post-decode walk, so the Array, Tuple and Map arms carry it for free (both nested shapes tested), and the top-level, nested-table and dictionary-values call sites all reach it (04417, a dictionary<dense_union>, still passes). The sibling ORC reader already has this mechanism (#110078); Parquet and the Apache Arrow library reader do not support Arrow unions at all, so they are not carriers. Read-side only: the Arrow writer is unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Tested: dense and sparse unions; Arrow and ArrowStream; a dictionary-encoded branch; a union under a struct and under a list; Arrow child order both matching and not matching the sorted Variant order; a raw-byte branch that converts and one that declines and text-parses; Bool/UInt8/Int8/Enum8/IPv6/Int128/String/UInt32 alternatives. Also probed: uint32 -> IPv4 and -> DateTime('UTC'), integer widening, a LowCardinality(String) alternative, a request with fewer alternatives than decoded, aliased and reordered child offsets. DateTime and Date32 alternatives, the latter kept unconverted and compared against the flat date32 column path. Variant cannot sit inside Nullable; a ColumnConst union column is peeled and restored by the existing caller. The DateTime arm pins session_timezone, which clickhouse-test randomizes over five non-UTC zones; proven load-bearing in both directions. Also covered: an explicitly zoned DateTime('UTC') alternative over a zoneless decoded DateTime, Date from a decoded UInt16 and IntervalDay from a decoded Int64 (both written by ClickHouse's own Arrow writer), and IntervalSecond over a decoded Arrow duration beside a competing Int64 sibling. Added since: a DateTime64(3, 'UTC') alternative over a decoded DateTime (a rescale, measured exact at every scale 0/3/6/9 including DateTime's extreme values), IPv4 and bare DateTime over a decoded UInt32 whose sibling admits neither, and a decoded DateTime64 offered the narrowing DateTime, which stays refused.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no SettingsChangesHistory.cpp entry, no format change. A read that succeeds today is byte-identical, because the arm returns the column untouched unless every element lands on a requested alternative; a request no assignment can satisfy therefore keeps its exact message. Where every element IS assigned the read reaches the values, so a value that cannot convert is now reported as that conversion failure rather than as the outer Variant mismatch (union<binary, int32> read as Variant(IPv6, UInt32) reports CANNOT_PARSE_IPV6 where master reports CANNOT_CONVERT_TYPE). The file is rejected either way and the new message names the value that is wrong.
i Invariants and contracts preserved? The rebuilt ColumnVariant keeps the original discriminators and renumbers its offsets to the gathered element positions, so every row keeps the element and value it selected; only element columns, their offsets and the declared type change. Each element is first gathered down to the rows referencing it, so a dense-union slot no row selects (whose bytes the Arrow spec leaves undefined) cannot decide whether an observable read succeeds. Element names are guaranteed distinct before the type is built, which is the post-decode counterpart of decodeUnion's own duplicate-child check, and local_to_global is rebuilt by name against the re-sorted alternatives. No path leaves a partially rebuilt column: the arm returns either the input unchanged or a fully rebuilt one.

Session id: cron:clickhouse-impl-slot-4:20260909-184000

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @alexey-milovidov, could you review this? decodeUnion types a union's Variant from the Arrow schema alone and the outer Variant -> Variant cast can only append alternatives, so an explicit structure naming a different alternative for a branch was rejected on a readable file, including one ClickHouse itself wrote (the native Arrow writer stores IPv6 as fixed_size_binary(16)). Each element now takes the alternative the request forces on it, resolved the way the native ORC reader resolves union branch hints in #110078.

@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Sep 9, 2026
The doc comment above `variantElementMatchesType` said `castColumn` pairs
tuple fields by name, so a name-differing target field would be defaulted.
That is half of it: `createTupleWrapper` pairs by name when the two named
tuples share at least one element name, and converts positionally when the
name sets are disjoint (ClickHouse#70830), so the field is filled from another field
rather than defaulted. Either way it is filled instead of rejected, which is
what the exclusion turns on, so the comment states that property and drops
the incomplete claim about how the pairing is decided.

The `uint32_date64` fixture comment and the section header above its first
arm both said a decoded `DateTime` is a type no conversion admits. That
stopped holding when a `DateTime` element was allowed to take a `DateTime64`
alternative; the arm still works because `DateTime` and `DateTime64` are its
only targets, so exactly one of them is a candidate in each of the three
requests.

Comment-only: the code token stream is unchanged.
The native Arrow writer stores `DateTime` as `uint32`, and the flat column
path reads a `uint32` column as `DateTime64` at any scale: a second count is
in range at every scale, so 7 reads as `1970-01-01 00:00:07.000` and
4294967295 as `2106-02-07 06:28:15.000000000`. The element matcher offered a
`uint32` branch only `IPv4` and `DateTime`, so a file written from
`Variant(DateTime, String)` could not be read with
`Variant(DateTime64(3, 'UTC'), String)`: the branch got no candidate, the
repair returned the decoded `Variant` unchanged and the outer cast reported
`Cannot convert type Variant(String, UInt32) to
Variant(DateTime64(3, 'UTC'), String)`.

The branch now converts through the same `castColumn` the flat path uses, so
the union arm and the flat arm of the test print the same seconds.

One request loses an assignment: where a wider integer is named beside
`DateTime64`, as in `Variant(Int64, DateTime64(3, 'UTC'), String)`, the branch
now has two admissible alternatives and prefers neither, so it takes neither
and the read is rejected. That is what `Variant(Int64, DateTime('UTC'),
String)` already does with the `DateTime` clause, and a control section pins
it. Recovering both would need the resolution to rank a value-preserving
widening above a temporal reinterpretation, which is a separate change.

Raised by the review bot on this PR:
ClickHouse#119098 (comment)
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3d6654efa with master 8b903d107 (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.

Object file sizes

5 object files changed (+39.19 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.cpp.o 605.14 KiB 622.11 KiB +16.97 KiB (+2.80%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.17 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +8.9 s (+18%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 083dfca

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
Stress test (arm_debug) / S3_ERROR No such key thrown master regression, first seen 2026-09-09 23:14Z: 05104_s3_plain_rewritable_hard_links fails to read .../__root/mutation_11.txt from a readonly s3_plain_rewritable disk whose mutation entry was concurrently removed. 10 rows on 10 PRs plus 1 true-master hit since it appeared. #119154 (mine, open)
Stress test (arm_asan_ubsan, s3) / Logical error: Shard number is greater than shard count (STID 5066-457d) trunk bug in the parallel-replicas shard scope: 95 rows on 76 PRs and 6 true-master hits in 30 days. #113589 (mine, open)
Fast test (arm_darwin) / 05076_error_trace_file_offsets pre-existing and deterministic on Darwin: since that check flavour started running (2026-09-10 02:07Z) the test has 43 failures and 0 passes across 43 PRs, with 0 master rows, because the Mach-O backtrace collector does not produce the out-of-binary frames the test asserts. #119145 (mine, open)
Mergeable Check, PR workflow-level aggregators reflecting the three rows above, no independent failure #119154, #113589 and #119145 (mine, all open)

None of the three reaches this PR's surface. The diff is
src/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.{cpp,h} plus
tests/queries/0_stateless/05141_native_arrow_ipc_union_variant_hints.{sh,reference}, and 05141
itself is green on this head: 355 OK rows across 23 check flavours, 0 failures, skipped in 3.

Session id: cron:our-pr-ci-monitor:20260910-080043

Master's opaque-column read path (ClickHouse#119519 and follow-ups) gave
reinterpretRawBytes a schema field and the format settings, so both
conflicts are one-sided additions in the same region of
ArrowIPCBlockInputFormat.cpp plus the changed declaration in the header:
keep childField and the new parameters alongside the Variant repair
helpers.

repairVariantElements takes the format settings so its own recursion into
reinterpretRawBytes can pass them on. It passes no field: an Arrow union
is decoded without consulting its children's clickhouse.opaque tags, as
master's output_format_arrow_unsupported_types description states, so no
alternative reaching the repair has a tag to act on and behaviour is
unchanged on both sides of the merge.
ClickHouse#119222 made schema inference wrap a `Tuple` read from an Arrow struct in
`Nullable`, and dropped the multi-line spelling for it, so the `nested` row of
`DESC file(..., Arrow)` now reads `Nullable(Tuple(v Variant(Bool, Int8)))`.

Measured, not assumed: the master snapshot binary (which does not carry this
branch) prints the new line for the same fixture, and the full DESC output of
that binary and of this branch is byte-identical, so nothing here touches
schema inference. The `struct_utf8` row is unaffected because ClickHouse#119222 keeps a
`Tuple` alternative of a `Variant` non-`Nullable`.
The added comments carried the reasoning that belongs in this history rather
than in the source: why each exclusion was chosen, which alternatives were
refuted, and a narration of the loop written directly beneath it. Those lines
are dropped. What stays is what the code below does not say: that the decoder
rejects a union whose children map to one ClickHouse type, so element names are
pairwise distinct; that `Bool` and `UInt8` compare equal while a value outside
0/1 renders as `true` under `Bool`; that a cast between tuples with differing
names fills the target fields instead of rejecting them; that `Date32` decoding
is hint-dependent; that `Variant` sorts its alternatives and `DataTypeVariant`
deduplicates by name; that the Arrow spec leaves an unreferenced dense-union
slot's bytes undefined; and why the duplicate-dropping loop terminates.

Comments over `src/`, per added code line: 0.268 -> 0.188. The remainder is
domain properties, which are not deleted to move a ratio.

No behaviour change: 10/10 randomized runs of
05141_native_arrow_ipc_union_variant_hints and 155/155 of the Arrow stateless
family pass on the rebuilt binary.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ac4cd2b

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
Performance Comparison (arm_release, master_head, 1/6) / read_in_reverse_order_final #0, #1 dashboard confirmed_regression, client_time +32.2% and +19.9%. On master these two FINAL queries over a ReplacingMergeTree went from 2-3 ms to 8-9 ms on both servers at the merge commit of #122073 (302e001eeb33), which stopped background merges during the measured runs, and since then they are flagged on unrelated PRs across several shards. The fixture reads no Arrow input a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollup rows, red only because of the shard above a fix task is created (the same owner as the row above)

All 173 check runs completed (154 pass, 18 not selected, 1 red), Finish Workflow is green and
CH Inc sync passed on this head.

Session id: cron:our-pr-ci-monitor:20260925-190206

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the read_in_reverse_order_final Performance Comparison rows created: #122335

The raw-byte rewrite of decoded dictionary values also rebuilt a `Variant`
under the dictionary use's hint. A top-level dictionary field takes its
declared type from the registered values, so that stayed consistent, but a
dictionary nested in a list, struct or map is declared by its Arrow type
(`fieldToCHType`). The record-batch repair then walked the materialized,
already repaired column under the stale declared `Variant`: an `Int64`
element still labelled `Int32` reached an `Int32 -> Int64` cast, and a
repair that reorders the sorted alternatives (e.g. `FixedString(16)` to
`UInt128`) paired elements with the wrong declared types. Either way the
read failed with `ILLEGAL_COLUMN`, for example
`list<dictionary<union<int32, utf8>>>` read as `Array(Variant(Int64, String))`.

Skip the `Variant` arm when rewriting dictionary values, so the dictionary
keeps the decoded `Variant` and the column is repaired exactly once, after
materialization, like an inline union. The raw-byte leaf rewrite of
dictionary values is unchanged: a `LowCardinality` built from them still
needs a consistent (values, type) pair, and a `Variant` is never inside one.

The test gains a dictionary of `union<int32, utf8>` under a list and under
a struct, read as `Variant(Int64, String)` in both `Arrow` and `ArrowStream`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Avogar Avogar self-assigned this Nov 10, 2026
@Avogar
Avogar added this pull request to the merge queue Nov 11, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 11, 2026
@Avogar

Avogar commented Nov 12, 2026

Copy link
Copy Markdown
Member

@groeneai merge into master failed, check why

groeneai and others added 2 commits November 12, 2026 20:32
Two semantic conflicts with master made the merge-queue run fail
(MergeQueueCI run 43079186130, merge commit 9948f7e):

- ClickHouse#129121 added a call to `reinterpretRawByteColumns` for native
  GeoArrow columns, while this branch gave that function a
  `repair_variants` parameter. Pass `true`, as the other materialized
  column call in `buildChunk` does; the geo target type has no
  `Variant`, so the value does not change the result.
- ClickHouse#126530 extended the `-WithMemoryTracking` container style rule to
  `src/Processors/Formats`; use `VectorWithMemoryTracking` in
  `variantElementTargets`.

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

Copy link
Copy Markdown
Collaborator Author

The merge-queue run failed on two semantic conflicts with master; GitHub saw no textual conflict:

I merged master and fixed both in 4b2c406 (5 lines). The geo call passes repair_variants=true, like the other call in buildChunk; the geo target type contains no Variant, so its result is unchanged. On the merged tree the debug build succeeds, the cpp style check and clang-tidy report nothing in the file, and 05141_native_arrow_ipc_union_variant_hints (20 runs) and 05497_geoparquet_native_encodings pass.

The native Arrow writer stores several alternatives as one Arrow type
(`IPv6`, `Int128`, `UInt128` and `UUID` as `fixed_size_binary(16)`,
`IPv4` and `DateTime` as `uint32`, `Date` as `date32` or `uint16`) and
names each union child after its type family. So a file written from
`Variant(IPv6, Int128)` had two children inferring `FixedString(16)`,
and the reader rejected it with INCORRECT_DATA, with or without an
explicit structure, before the post-decode repair could run.

`unionElementTypes` now resolves such a child to the parameterless type
its name denotes when the writer stores that type as the inferred one.
`fieldToCHType` and `decodeUnion` share it, so the declared and decoded
types agree; `decodeUnion` converts the resolved children after
gathering their selected values, so no undefined slot is converted.
`reinterpretFixedStringLeaf` moves to the decoder to be shared. Children
whose names tell nothing apart stay rejected.

Requested by the review on ClickHouse#119098:
ClickHouse#119098 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… children

`decodeUnion` kept a dense union's child columns as they are whenever the
child row count did not exceed the union's, so rows that alias one slot
(offsets `[0, 0, 2]`) or select slots out of order produced a `ColumnVariant`
whose offsets are not the per-element row sequence it requires. Anything that
copies ranges of it then returns other values: a dictionary of such a union,
materialized with `insertRangeFrom`, read `[11, 0, 22, 's']` instead of
`[11, 11, 22, 's']`, and so did a filtered read of the plain column. That was
already the case on master for the decoded `Variant`; with the per-element
repair this PR adds, a widened request such as `Variant(Int64, String)` now
reached the same wrong values instead of failing. Such a child is now gathered
like the other non-trivial layouts, so the repair no longer needs a gather of
its own.

Two `date32` children named `Date` and `Date32` were told apart by narrowing
the `Date` one with a cast after decoding, which saturates whatever
`date_time_overflow_behavior` says, while a flat `date32` read as `Date`
rejects out-of-range days by default. The pair only arises for
`Variant(Date, Date32)`, which needs `allow_suspicious_variant_types`, so it is
rejected again as on master instead; `Date` is still told apart in its
`uint16` encoding.

Both found by the review bot on ClickHouse#119098 (r4613911946, r4613911951).

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 14abb06

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
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) not from this PR (it changes the Arrow Union decoder): the upgraded server retried Code: 47 ... Unknown expression identifier b on part all_1_1_1_2 of test_3.t_stale_part_type_5, the empty DETACH PART part of 04653. The stress phase runs the previous release's tests (v26.10.6.18-stable), whose 04653 does not have the fix. Same error on 37 other PRs in 14 days #125293 (external, merged)
Mergeable Check, PR praktika rollups of the row above #125293 (external, merged)

CIDB has no other FAIL or ERROR row on this head (the Finish Workflow / Post Hooks row is the first attempt, before the review thread was resolved).

Session id: cron:our-pr-ci-monitor:20261118-183028

@Avogar

Avogar commented Nov 19, 2026

Copy link
Copy Markdown
Member

@groeneai resolve conflicts and check upgrade check failure

groeneai and others added 2 commits November 20, 2026 00:11
…union-variant-hints

# Conflicts:
#	src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp
`Variant(Date, String)` written with `output_format_arrow_date_as_uint16`
infers distinct `UInt16` and `String` children, so it never reached the
name-based resolution of a `Date` child stored as `uint16`; deleting that
clause left the test green. `Variant(Date, UInt16)` stores both children as
`uint16`, so only the child name tells them apart. With the clause removed,
the new round trip fails with `INCORRECT_DATA` in `Arrow`.

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

Copy link
Copy Markdown
Collaborator Author

Conflicts resolved: 736ec24 merges master (the one conflict, in decodeUnion against #132416, keeps both sides), and 7411531 adds a Variant(Date, UInt16) writer round trip, because no test covered the uint16 Date case.

The Upgrade check failure is not from this PR. It is 04653_mutation_rewrite_stale_part_column_type: the upgraded server retries Code: 47 ... Unknown expression identifier b on the empty part that DETACH PART leaves in t_stale_part_type_5. The check runs the tests of the previous release. The fix is #125293, and its 26.10 backport #132913 is merged but not in v26.10.7.24-stable, so the check stays red until the next 26.10 release.

@Avogar

Avogar commented Nov 23, 2026

Copy link
Copy Markdown
Member

@groeneai resolve conflicts

…union-variant-hints

# Conflicts:
#	src/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.cpp
#	src/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.h
@groeneai

Copy link
Copy Markdown
Collaborator Author

Conflicts resolved in 3d6654e (master merge). The conflict was with #131773, which turned buildChunk and reinterpretRawByteColumns into free functions shared with Vortex; the resolution keeps that structure and passes this PR's repair_variants flag through reinterpretRawByteColumnsImpl. No behaviour change: 05141 passes 10/10, and the local Arrow and Vortex tests pass (except the ones that need MinIO or an Arrow Flight port).

This branch has not been deployed

No deployments
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-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants