Skip to content

Support the ORC union type in the native ORC reader (map to Variant) - #110078

Merged
alexey-milovidov merged 34 commits into
masterfrom
orc-native-union
Jul 29, 2026
Merged

alexey-milovidov merged 34 commits into
masterfrom
orc-native-union

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 11, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

The native ORC reader now supports ORC's uniontype, mapping it to the ClickHouse Variant type (previously such columns were rejected with Unsupported ORC type).

Documentation entry for user-facing changes

ORC uniontype columns can now be read; each is exposed as a Variant over the union's branch types.


Maps ORC union → ClickHouse Variant:

  • parseORCType: ORC UNION → DataTypeVariant over the branch types.
  • ORCColumnToCHColumn::readColumnFromORCColumn: builds a ColumnVariant from the ORC UnionVectorBatch (tags → discriminators, offsets → offsets, one branch column per child).
  • updateIncludeTypeIds: includes the union's branches in the ORC read set - a branch with a forced type hint (see below) is included by recursing into the hint, so a STRUCT branch keeps the named-tuple field pruning; a branch without one is included in full. The union's own tag stream is picked up automatically as the parent of the included branches.

Variant and ORC union don't line up 1:1, so:

  • Variant sorts and de-duplicates its branch types, so ORC branches are placed at their sorted position and the ORC tags are remapped to the sorted (global) discriminators.
  • A union-level NULL — and a non-null union row that selects a branch whose payload is null (possible for any branch kind, including LIST/MAP/STRUCT and dictionary-encoded strings) — is represented by the Variant NULL discriminator. Branch null maps are taken directly from the ORC batches, because complex branches never come back as Nullable columns. Because such rows are never read, the per-branch repair cast never inspects their placeholder values: they are replaced with a valid row before the cast, so a value-checking cast (e.g. Int8 → Enum8, or the same on a nested Tuple/STRUCT field) cannot reject a null-payload placeholder.
  • Per-branch type hints: an explicit (or inferred) Variant schema is matched structurally against the ORC branches, and a hint is propagated to a branch when the correspondence is unambiguous. This enables the explicit-schema conversions inside unions — the unsigned and Enum integer targets of the matching width (e.g. int → UInt32, tinyint → Enum8, boolean → Enum8, recursively for nested leaves such as Array(UInt32) or Map(String, Enum8(...))), binary → IPv6/Int128/UInt128/Int256/UInt256/Decimal256, int → IPv4 — and keeps complex branch types aligned with schema inference (e.g. Array(Nullable(Int32))). The matching is custom-type-name aware: Bool (which the ORC writer maps to boolean) is kept distinct from a plain UInt8 (mapped to tinyint), so e.g. Variant(Bool, UInt8) over uniontype<boolean,tinyint> resolves one-to-one, and a boolean branch hinted as plain UInt8 is cast accordingly. A branch whose correspondence stays ambiguous is read without a hint, so no guess is ever made. STRUCT branches follow the same named-tuple rules as the non-union ORC struct path: a target tuple with explicit field names is matched by name, so it may project (drop) and reorder the ORC struct's fields (e.g. Variant(Tuple(b String), String) or Variant(Tuple(b String, a Int32), String) over uniontype<struct<a:int,b:string>,string>); the repair cast then projects/reorders the read tuple to exactly the target. This field pruning also applies to the include set computed before the read (updateIncludeTypeIds), not just to the values materialized afterwards: a dropped field is never selected from the ORC file at all, so e.g. an unsupported or corrupt field inside a struct branch (such as a nested uniontype) does not prevent reading the fields the target tuple does reference.
  • Widening numeric conversions inside a branch. The ordinary (non-union) ORC column path gets them for free from the final cast, but a union column's final cast is a Variant -> Variant cast, which only extends the set of alternatives by exact type name and cannot widen one of them, so the widening has to be requested as a per-branch hint. An ORC integer branch therefore also matches a strictly wider integer target and a float that represents its width exactly (e.g. Variant(Int64, String) or Variant(Float64, String) over uniontype<int,string>), and a FLOAT branch matches Float64 - recursively for nested leaves such as Array(Int64). Numeric branches that become ambiguous with each other this way (uniontype<tinyint,bigint> with Variant(Int8, Int64): both match Int64) are tie-broken by their natural inference pairing, like the string-like kinds below, so the exact-width alternative stays with its own branch and the wider one goes to the branch that needs it.
  • Dictionary-encoded string branches are read as non-nullable LowCardinality(String) under the default input_format_orc_dictionary_as_low_cardinality = 1.
  • String-like branches are matched by their logical kind, not the stripe's physical encoding. CHAR and STRING/VARCHAR can all be read as either FixedString or String targets, so e.g. uniontype<char(1),string> over Variant(FixedString(1), String) leaves both branches with two candidates; a tie-break pairs each branch with its natural inference type (CHAR ↔ FixedString of the same length, STRING/VARCHAR ↔ String, with LowCardinality wrappers stripped for the comparison), applied only when the forced-assignment elimination is stuck and only when uncontested. Without it, each ambiguous branch materialized per the current stripe's encoding (dictionary-encoded → LowCardinality), so a supported schema could fail depending on per-stripe encoding choices. For the same reason both duplicate-branch checks compare branch types with LowCardinality stripped, so uniontype<string,string> is rejected even when its branches happen to be encoded differently.
  • The two ORC timestamp kinds both read back physically as DateTime64(9) but are inferred differently — TIMESTAMP as DateTime64(9) and TIMESTAMP_INSTANT as DateTime64(9, 'UTC') — so TIMESTAMP_INSTANT is matched only by an explicitly time-zoned target (any timezone, not only UTC) while TIMESTAMP stays permissive, and the singles-elimination step decides whether the correspondence is forced. This lets a uniontype<timestamp,timestamp with local timezone> resolve to Variant(DateTime64(9), DateTime64(9, 'UTC')) — and an explicit schema such as Variant(DateTime64(9), DateTime64(9, 'Europe/Berlin')) be accepted — instead of being wrongly rejected as duplicate branches (the TIMESTAMP_INSTANT branch is repair-cast from DateTime64(9) to the target timezone, a value-preserving relabel).
  • Unions with duplicate branch types (e.g. uniontype<int,int>) cannot be represented as a Variant (which would squash them into one branch with a single physical stream), so they are rejected with a clear error.
  • Nested unions (a union branch that is itself a union, e.g. uniontype<uniontype<int,string>,double>) would map to a Variant nested inside another Variant, which Variant forbids. They are rejected explicitly through the normal unsupported-type path (as UNKNOWN_TYPE), before the outer Variant is constructed, so the error is clear instead of a BAD_ARGUMENTS from the Variant constructor and input_format_orc_skip_columns_with_unsupported_types_in_schema_inference can skip such a column and still read the remaining ones.
  • Unions with more branches than Variant can hold (more than 255, still valid ORC since union tags are a byte) are rejected through the same explicit unsupported-type path — checked before any branch is parsed, so the column is skippable during schema inference and the explicit-structure read path reports a clear UNKNOWN_TYPE as well.
  • An out-of-range union tag is rejected with INCORRECT_DATA. This is also the malformed input that crashed the Apache Arrow-based ORC reader with a heap-buffer-overflow; the native reader handles it safely. The vendored ORC library (contrib/orc) is hardened accordingly: decoding a union tag stream validates every tag against the number of branches, and getColumnEncoding validates the column id against the stripe footer, both throwing ParseError (surfaced as INCORRECT_DATA) instead of writing or reading out of bounds.

This is one of a series that lets the native ORC reader fully replace the Arrow-based one:

  1. Remove the Apache Arrow-based ORC reader #110074 — remove the Arrow-based ORC reader (merged; its embedded ORC format documentation now lives in NativeORCBlockInputFormat.cpp, where this pull request adds the Union row)
  2. this PR — union support in the native reader
  3. union support in the native ORC writer (Variant → ORC union)
  4. port the Hive engine off the Arrow ORC adapter

Verification

Built locally and exercised end-to-end with union ORC files written by pyarrow:

  • sparse & dense union<int32,string> → Variant(Int32, String) with values 10, x, 30, z;
  • union<string,int32,double> → Variant(Float64, Int32, String) with the tags correctly remapped to the sorted discriminators;
  • union<list<int32>,string>, union<map<string,int32>,int32>, union<struct<a:int32>,string> with null branch payloads → Variant NULLs;
  • an explicit Variant(Tuple(b String), String) (projecting away the struct's a field) and Variant(Tuple(b String, a Int32), String) (reordering the struct's fields) over union<struct<a:int,b:string>,string>;
  • an explicit Variant(Tuple(a Enum8(...)), String) over union<struct<a:tinyint>,string> with a null struct payload (a value-checking Tuple field cast that must skip the null-payload placeholder), including the all-null-branch case;
  • a dictionary-encoded string branch under both values of input_format_orc_dictionary_as_low_cardinality;
  • explicit Variant(IPv6, String) and Variant(Int128, String) schemas over a union<binary,string> file;
  • explicit Variant(UInt32, String), Variant(Enum8(...), String) (with a null payload in the enum branch), Variant(Enum16(...), UInt64), Variant(Array(UInt32), String) and Variant(Int32, Map(String, Enum8(...))) schemas over the corresponding integer-branch unions;
  • explicit Variant(Bool, UInt8) and Variant(UInt8, String) schemas over union<boolean,tinyint> and union<boolean,string> files (plus the inferred Variant(Bool, Int8) for the former);
  • explicit Variant(Enum8('false' = 0, 'true' = 1), String) over union<boolean,string> and Variant(Enum8(...), Int8) over union<boolean,tinyint> (the boolean branch takes the Enum8 alternative; the latter with a null payload in the boolean branch);
  • explicit Variant(Int64, String), Variant(Float64, String), Variant(Float32, String) and Variant(Array(Int64), String) widening schemas over uniontype<int,string>, uniontype<float,string> and uniontype<array<int>,string> files, plus Variant(Int8, Int64) and Variant(Int64, Int128) over uniontype<tinyint,bigint> (the exact-width pairing decides which branch takes the shared alternative);
  • a union<timestamp,timestamp with local timezone> file → inferred Variant(DateTime64(9), DateTime64(9, 'UTC')), with a null payload in each branch, the explicit schema in both branch orders, and an explicit Variant(DateTime64(9), DateTime64(9, 'Europe/Berlin')) (non-UTC) schema;
  • a uniontype<char(1),string> file in a dictionary-encoded and a direct-encoded variant, each read with the inferred schema and with explicit Variant(FixedString(1), String) / Variant(LowCardinality(FixedString(1)), LowCardinality(String)) schemas (the encoding/schema cross-pairings fail without the string-kind tie-break), plus a two-stripe variant with a null payload in each branch;
  • uniontype<int,int> → clean error (duplicate branch types), and uniontype<string,string> with one dictionary-encoded and one direct branch → the same clean error on both the schema-inference and the explicit-structure read paths (previously the encoding difference let it slip past the duplicate check);
  • uniontype<uniontype<int,string>,double> → clean UNKNOWN_TYPE (nested union), skippable with input_format_orc_skip_columns_with_unsupported_types_in_schema_inference (keeping a supported id column), and the same rejection on the explicit-structure read path;
  • a 256-branch union of distinct types (char(1)..char(255) plus int, written by pyorc) → clean UNKNOWN_TYPE (more branches than Variant supports), skippable in schema inference, and the same rejection on the explicit-structure read path;
  • the original crash-repro ORC (out-of-range tag 255) → INCORRECT_DATA: Invalid ORC union tag 255 for union with 2 branches, no crash;
  • uniontype<struct<a:uniontype<int,int>,b:string>,string> (the struct branch's own field a is an unsupported nested union) read with an explicit Variant(Tuple(b String), String) schema that projects away a → succeeds, a is never selected or inspected; the same file with a schema that references a (or with schema inference, which always inspects every field) → fails the same way 04602's nested-union case does.

Covered by the stateless tests 04511_orc_native_union_type, 04512_orc_native_union_branch_hints, 04513_orc_native_union_integer_targets, 04515_orc_native_union_bool_targets, 04516_orc_native_union_struct_branch_null, 04600_orc_native_union_timestamp_kinds, 04601_orc_native_union_struct_projection, 04602_orc_native_union_nested, 04603_orc_native_union_oversized, 04604_orc_native_union_string_kinds, 04605_orc_native_union_struct_branch_pruning 04635_orc_native_union_boolean_enum and 04636_orc_native_union_numeric_widening (inline unhex() ORC data, so no binary test files).

Version info

  • Merged into: 26.8.1.331 (included in 26.8 and later)

alexey-milovidov and others added 2 commits July 11, 2026 04:53
The native ORC reader previously rejected ORC's uniontype with UNKNOWN_TYPE.
Map it to the ClickHouse Variant type instead:

* parseORCType: ORC UNION -> DataTypeVariant over the branch types.
* ORCColumnToCHColumn::readColumnFromORCColumn: build a ColumnVariant from the
  ORC UnionVectorBatch (tags -> discriminators, offsets -> offsets, one branch
  column per child).

Variant sorts and de-duplicates its nested types and forbids Nullable/Variant
branches, while ORC union is positional and keeps one physical stream per
branch, so:
* branches are placed at their sorted (global) position and tags remapped to
  global discriminators (identity local-to-global);
* a branch column read back as Nullable is unwrapped (a union-level NULL is
  the Variant NULL discriminator, not a Nullable wrapper);
* unions with duplicate branch types are rejected with a clear error, since
  they cannot be represented as a Variant;
* an out-of-range union tag is rejected with INCORRECT_DATA (this also removes
  the crash surface that the Arrow-based reader had on malformed union tags).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c695543]

Summary: ✅


AI Review

Summary

This PR adds native ORC uniontype -> Variant support in the native reader, including schema inference, explicit-structure branch hinting, null-payload handling, malformed-input hardening via the updated contrib/orc submodule, documentation updates, and focused stateless coverage. I reviewed the current diff and the full prior discussion against the latest head and did not find any remaining correctness, compatibility, or documentation issues that still reproduce in the current code.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 11, 2026
alexey-milovidov and others added 3 commits July 11, 2026 07:09
`updateIncludeTypeIds` had no case for `orc::UNION`, so it fell through to
`default: return;` and added neither the union's own column id nor any of its
child streams to the ORC read set. With `RowReaderOptions::includeTypes`, the
children of a type are not auto-selected (only ancestors are), so the union's
tag stream and branch columns were never decoded: every union value was read
back as `NULL`, and the out-of-range-tag validation in
`readColumnFromORCColumn` was never reached (so a malformed union tag did not
raise `INCORRECT_DATA`).

This surfaced as a failure of `04511_orc_native_union_type` in the
`arm_asan_ubsan` runs: the union values came back as `\N` and the malformed-tag
query succeeded instead of throwing. It passed in the local `RelWithDebInfo`
run only because the manual pyarrow files were exercised through a different
read path.

Add a `case orc::UNION:` that inserts the union's own column id. Selecting the
union's type id makes the ORC reader select the union together with all of its
descendant columns (see `ColumnSelector::selectChildren`), which is exactly the
set that `readColumnFromORCColumn` reads (it reads every branch, since `Variant`
reorders its branch types and there is no per-branch pruning).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110078&sha=1a21ffb3571bec15cfe415357153b0b741460e21&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
An ORC union row can be non-null while the branch it selects holds a null
payload (for example a `string` branch round-tripped from Arrow with `None`,
where the union array keeps `null_count == 0`). The previous code unwrapped the
branch's `Nullable` wrapper and dropped the null map, so such a row was written
as the branch's nested default (`''`, `0`, ...) while staying non-null - it
silently changed data.

`Variant` branches are non-nullable, so there is no way to represent a "branch
selected, but null" row other than as a `Variant` `NULL`. Keep each branch's
null map and, when a non-null union row selects a null branch value, emit the
`ColumnVariant::NULL_DISCRIMINATOR` instead of the branch value.

This also required building the `Variant` sub-columns compactly: skipping a
branch value leaves an entry unreferenced, and `ColumnVariant::validateState`
requires every sub-column to contain exactly the values its discriminator
references. The sub-columns are now cloned empty from the ORC branch columns and
filled row by row (`insertFrom`) with sequential offsets, which is also robust
to any ORC offset ordering.

Extends `04511_orc_native_union_type` with a `union<int32,string>` whose string
branch payload is null on a non-null row: it now reads back as a `Variant`
`NULL` rather than an empty string.

Addresses review feedback on the pull request.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The compact `Variant` construction reads each selected branch value at the ORC
offset (`insertFrom`, and the branch null-map lookup). A malformed file can
point past the branch's decoded values, so bound-check the offset against the
branch column size and raise `INCORRECT_DATA` rather than reading out of bounds
- matching how an out-of-range union tag is already handled.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
An out-of-range union tag in a corrupt ORC file made the ORC library's
`UnionColumnReader` index `childrenCounts_` (and the branch children) out of
bounds while decoding the stripe - a heap-buffer-overflow caught by ASan (the
`04511_orc_native_union_type` malformed-tag case in the arm_asan_ubsan run).
The ClickHouse-side tag bounds check in `readColumnFromORCColumn` ran too late,
after the ORC library had already decoded the batch and overflowed.

Fix it in the ORC library (`contrib/orc`), which now validates each union tag
against the number of branches and throws `ParseError`, matching the existing
footer type-nesting-depth guard. Surface that read-time `ParseError` as
`INCORRECT_DATA` rather than letting it propagate as a generic `std::exception`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110078&sha=dd7e558f3919c7424c2323991c8614e9d9856b07&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Jul 11, 2026
…thout a crash

An AST-fuzzer run on this PR found that reading a corrupt ORC file could abort the
process (signal 6) inside `orc::StripeInformationImpl::getColumnEncoding`. During
schema inference `parseORCType` calls `isDictionaryEncoded`, which consults the
stripe footer's per-column encoding via the type's column id. When a corrupt file
declares a type (here a union branch) whose column id has no matching stripe-footer
encoding, the ORC library indexed its repeated `ColumnEncoding` field out of bounds,
which is a hard abort in debug builds and undefined behavior otherwise. The new
union support made such trees reachable for the fuzzer, but the underlying defect is
independent of unions.

Fix it in the ORC library (submodule bump) by bounds-checking the column id in
`getColumnEncoding` and `getDictionarySize` and throwing `ParseError`, matching the
existing union-tag and type-nesting-depth guards. On the ClickHouse side,
`NativeORCSchemaReader::readSchema` now catches `orc::ParseError` and rethrows it as
`INCORRECT_DATA` instead of letting it surface as a generic exception, mirroring the
existing wrapper around `stripe_reader->next`.

The malformed file is added to `04511_orc_native_union_type`; it now fails cleanly
during schema inference instead of crashing.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110078&sha=97818f010231a40f18bd6f50f03affdee9f702e9&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ality normalization for ORC union branches

Fixes the three union-read gaps from the review of the native ORC reader's
union support:

1. A non-null union row selecting a null complex branch payload (LIST, MAP,
   STRUCT) was read as the branch's default value ([], {}, tuple of defaults),
   because the branch null map was only harvested when the branch came back as
   `ColumnNullable`, which complex branches never do. The null map is now taken
   directly from the ORC batch (`notNull`), and branches are read with
   `inside_nullable` set (a STRUCT branch could not be wrapped in `Nullable`
   anyway, because `Tuple` cannot be inside `Nullable`).

2. The explicit type hint was not propagated to union branches, so the special
   explicit-schema conversions (binary -> `IPv6`/`Int128`/`UInt128`/`Int256`/
   `UInt256`/`Decimal256`, int -> `IPv4`) never ran inside a union, and complex
   branches produced types misaligned with the inferred schema (e.g.
   `Array(Int32)` instead of the inferred `Array(Nullable(Int32))`), failing
   with `CANNOT_CONVERT_TYPE`. `Variant` sorts its nested types, so the
   positional correspondence between ORC branches and Variant alternatives is
   lost; it is now reconstructed structurally, and a hint is propagated only
   when the assignment is forced - a branch whose correspondence stays
   ambiguous is still read without a hint, so no guess is ever made.

3. A dictionary-encoded string branch read under the default
   `input_format_orc_dictionary_as_low_cardinality = 1` came back as
   `LowCardinality(Nullable(String))`, which `removeNullable` left unchanged,
   so `DataTypeVariant` rejected it with `BAD_ARGUMENTS`. Such branches are now
   normalized to non-nullable `LowCardinality` (nulls are tracked by the batch
   null map), and with the inferred `Variant(..., LowCardinality(String))` hint
   they are read directly as non-nullable `LowCardinality(String)`.

The new test `04512_orc_native_union_branch_hints` covers null list/map/struct
payloads, dictionary-encoded string branches under both values of the setting,
and explicit `Variant(IPv6, String)` / `Variant(Int128, String)` schemas over a
binary branch.

Co-Authored-By: Claude Fable 5 <[email protected]>
… union branch hints

The ordinary (non-union) ORC column path accepts UInt8/UInt16/UInt32/UInt64,
Enum8 and Enum16 for the ORC integer types through the final cast (they are
also exactly what the ORC writer maps to those types), but
orcUnionBranchMatchesType only matched the signed storage types, so an
explicit schema such as Variant(UInt32, String) over uniontype<int,string>
never received a per-branch hint. The final cast cannot repair that, because
a Variant -> Variant conversion only accepts an extension by exact nested
type names. Extend the matcher with the unsigned and Enum targets of the
matching width, recursively for nested leaves (Array(UInt32),
Map(String, Enum8(...)), ...).

The branch cast is routed through Nullable when the branch has a null map: a
value-checking cast such as Int8 -> Enum8 must not inspect the placeholder
values at null-payload positions (such rows become the Variant NULL
discriminator and are never read), e.g. an Enum8 without a value 0 would
otherwise reject a valid file.

Covered by the new stateless test 04513_orc_native_union_integer_targets.

Co-Authored-By: Claude Fable 5 <[email protected]>
@mintlify

mintlify Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 11, 2026, 8:03 PM

…ints

The union branch-hint matcher used `WhichDataType`, which strips custom
type names, so `Bool` (a custom-named `UInt8`) and plain `UInt8` were
indistinguishable: for `uniontype<boolean,tinyint>` read with an explicit
`Variant(Bool, UInt8)` schema, both branches matched both alternatives,
no hint was assigned, and the final `Variant(Bool, Int8)` ->
`Variant(Bool, UInt8)` conversion failed - even though the ordinary
(non-union) column path already accepts `UInt8` for `BYTE`.

Two custom-name-blind spots fixed:
- the BYTE case of `orcUnionBranchMatchesType` no longer accepts `Bool`
  (the writer maps `Bool` to BOOLEAN, never to BYTE), so the forced
  assignments become one-to-one again;
- the per-branch repair cast is gated on type-name inequality instead of
  `equals` (which also cannot tell `Bool` from `UInt8`), because Variant
  identity is name-based; otherwise a BOOLEAN branch hinted as a plain
  `UInt8` alternative skipped the `Bool` -> `UInt8` cast and produced
  `Variant(Bool, ...)` instead of the hinted type.

Adds the test `04515_orc_native_union_bool_targets`:
`union<boolean,tinyint>` as `Variant(Bool, UInt8)` (the reviewed case,
with a null boolean payload), the inferred and explicit
`Variant(Bool, Int8)` schemas, and `union<boolean,string>` as both
`Variant(UInt8, String)` and `Variant(Bool, String)`.
…r cast

A non-null ORC union row can select a branch whose payload is null; such rows
are mapped to the `Variant` NULL discriminator and are never read. The
branch-repair cast previously routed only `Nullable`-wrappable branches through
`Nullable` to skip these placeholders. `Tuple`/`STRUCT` branches report
`canBeInsideNullable() == true`, so they took that path too, but wrapping the
tuple in `Nullable` does not stop the cast from descending into a nested field
and rejecting its null placeholder - a value-checking `Int8` -> `Enum8` field
cast, or a plain `Int8` field, then failed with `UNKNOWN_ELEMENT_OF_ENUM` /
`CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN`.

Replace every null-payload row with a copy of a valid row before the cast
instead (the copied values are discarded when the row becomes a `Variant` NULL),
and fall back to a default-valued column of the target type when the whole
branch is a null payload. This unifies the null-safe cast path for scalar and
complex branches alike.

Adds test `04516_orc_native_union_struct_branch_null`.
… branches

A `uniontype<timestamp, timestamp with local timezone>` is inferred as
`Variant(DateTime64(9), DateTime64(9, 'UTC'))`, but both ORC timestamp kinds
read back physically as `DateTime64(9)`. In `orcUnionBranchMatchesType` both
kinds matched any `DateTime`/`DateTime64` alternative, so neither branch got a
per-branch hint, both branches collapsed to `DateTime64(9)`, and the
duplicate-branch check rejected the valid file.

Match `TIMESTAMP_INSTANT` only against a UTC-timezoned target (the type schema
inference produces for it) while keeping `TIMESTAMP` permissive, so
singles-elimination resolves the two branches to distinct alternatives. The
`TIMESTAMP_INSTANT` branch is then repair-cast from `DateTime64(9)` to the UTC
variant (a value-preserving relabel) before deduplication.

Add test `04600_orc_native_union_timestamp_kinds`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 22, 2026 11:54
The ordinary (non-union) ORC path can cast a boolean column to `Enum8`
through the final cast, but `orcUnionBranchMatchesType` accepted only
`UInt8` for a BOOLEAN branch, so an explicit schema like
`Variant(Enum8('false' = 0, 'true' = 1), String)` over
`uniontype<boolean,string>` left the boolean arm unhinted, built
`Variant(Bool, String)`, and failed the final `Variant` -> `Variant`
cast (`Enum8(...)` is not an extension of `Bool`).

Accept `which.isEnum8()` in the BOOLEAN arm. Add the regression test
`04635_orc_native_union_boolean_enum` covering the reported case and
`Variant(Enum8(...), Int8)` over `uniontype<boolean,tinyint>`, where
singles-elimination now assigns `Enum8` to the boolean branch and
`Int8` to the tinyint branch (with a null payload in the boolean
branch exercising the masked value-checking cast).

Co-Authored-By: Claude Fable 5 <[email protected]>
An explicit schema such as `Variant(Int64, String)` over `uniontype<int,string>`
was rejected: the ordinary (non-union) ORC column path gets numeric widening for
free from the final cast in `orcColumnsToCHChunk`, but a union column's final
cast is a `Variant` -> `Variant` cast, which can only extend the set of
alternatives by exact type name and cannot widen one of them. The branch had to
request the widening as a per-branch type hint, and `orcUnionBranchMatchesType`
matched only exact-width numeric targets, so the branch stayed unhinted, was
materialized as `Int32`, and the read failed after the union had already been
built into the wrong `Variant` shape. The same gap applied recursively to the
numeric leaves of `Array`/`Map`/`Tuple` alternatives.

Now an ORC integer branch also matches a strictly wider integer target and a
float that represents every value of its width exactly (`Float32` for BOOLEAN,
BYTE and SHORT, `Float64` also for INT), and a `FLOAT` branch matches `Float64`.
Because a widening match makes numeric branches ambiguous with each other
(`uniontype<tinyint,bigint>` with `Variant(Int8, Int64)`: both branches match
`Int64`), the numeric kinds are tie-broken by their natural inference pairing in
`orcUnionBranchPrefersType`, exactly like the string-like kinds: the exact-width
alternative stays with its own branch and the wider one goes to the branch that
needs it. A branch whose correspondence remains ambiguous is still left without
a hint, so no guess is ever made.

Test `04636_orc_native_union_numeric_widening`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110078&sha=313fc1d0d79bd8d2e2e4cc1cf1ba9354d10c624c&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%202%2F2%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

04327_runtime_filter_nested_variant fails with result differs with reference, and it is unrelated to this pull request (it only adds ORC union support). The CI diagnosis says the failure is caused by randomized settings (it passes without randomization); on #111721 the same test was minimized to the culprit setting query_plan_optimize_join_order_randomize 6. It also failed on unrelated pull requests in the last two weeks (#110886, #111721, #109071, #106373, #109620), and I could not find an open issue for it.

The other red, Logical error: Inconsistent KeyCondition behavior in Stress test (arm_debug), is a MergeTree KeyCondition failure with no ORC involvement, already tracked by #111421.

# Conflicts:
#	src/Processors/Formats/Impl/ORCBlockInputFormat.cpp
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #111691 (yours) adds SET join_runtime_filter_min_probe_rows = 0 to this test, and that pin alone resolves it. I am not opening a duplicate PR.

One correction to the diagnosis: the culprit is not query_plan_optimize_join_order_randomize by itself. The failing line is the SELECT count() > 0 FROM (EXPLAIN actions = 1 ...) WHERE explain ILIKE '%BuildRuntimeFilter%' assertion, which is why the diff is -1 +0. join_runtime_filter_min_probe_rows (default 1000) makes joinRuntimeFilter.cpp:251-256 skip building the filter when the probe-side row estimate is at or below the threshold:

auto probe_size = join_step->getInputRowsEstimation(JoinTableSide::Left);
if (probe_size && *probe_size <= optimization_settings.join_runtime_filter_min_probe_rows)
    return false;

query_plan_optimize_join_order_randomize replaces real statistics with random cardinalities, so that probe estimate becomes random and can land under the threshold. Both settings have to line up, and pinning either one is sufficient. Verified locally on 693a303 (debug), using seed 951826 from the run you linked:

settings result
randomize=0, min_probe_rows=default pass
randomize=0, min_probe_rows=100000 pass
randomize=951826, min_probe_rows=default fail, reproduces the -1 +0 diff
randomize=951826, min_probe_rows=0 pass

With #111691's min_probe_rows = 0 pin in place, an 18-seed sweep of query_plan_optimize_join_order_randomize (including 951826, 610415 and 6) passes 18/18, so #111691 covers this test completely.

Worth noting the per-query query_plan_join_swap_table = false already in those statements does not help, because the suppression is the probe-size guard rather than a side swap.

…widening`

The test reads ORC data through `format(ORC, ...)`, but the fasttest build
does not include the ORC input format, so every query failed there with
`Unknown format ORC` (`UNKNOWN_FORMAT`) and the whole `Fast test` job went
red, dropping the rest of the CI workflow.

All the other ORC union tests of this pull request already carry
`-- Tags: no-fasttest`; only the one added last was missing it.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110078&sha=cbb9daa1efb714b49e673608f109ba063bd5aef8&name_0=PR&name_1=Fast%20test
Related: #110078
… unions

The test asserted that a plain ORC `uniontype` column is an *unsupported* type,
which is no longer true in this branch: it is now mapped to `Variant`. So the
second `DESC` no longer threw and the test failed reproducibly in every
`Stateless tests` flavor, e.g.

    -UNKNOWN_TYPE
    +Nullable(Int32)

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110078&sha=57530b8bc8ed291ce067673534a852f2ca92f293&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29

The test itself is about the schema-inference cache key including
`input_format_orc_skip_columns_with_unsupported_types_in_schema_inference`, so
it only needs *some* unsupported ORC type. Switch it to a *nested* union
(a union branch that is itself a union), which stays unsupported, because
`Variant` cannot be nested in `Variant` - the same file shape as before: one
unsupported column plus one supported `Int32` column. The reference is
unchanged.

The new data file `data_orc/orc_nested_union_type.orc` is the same blob already
used inline by `04602_orc_native_union_nested`.
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.40% 86.20% +5.80%
Functions 91.40% 92.00% +0.60%
Branches 72.30% 78.40% +6.10%

Changed lines: Changed C/C++ lines covered: 330/374 (88.24%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic is a little-bit overdone, but it looks thorough and correct.

@alexey-milovidov alexey-milovidov self-assigned this Jul 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 29, 2026
Merged via the queue into master with commit efb26ec Jul 29, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the orc-native-union branch July 29, 2026 01:15
alexey-milovidov added a commit that referenced this pull request Jul 29, 2026
The reader-side prerequisite (#110078) is merged, so this branch no longer
needs to be stacked on `orc-native-union`.

Conflict resolution: `contrib/orc` diverged. Master points at
`orc-union-tag-bounds-2` (the union tag bounds check re-done on top of the
updated `ClickHouse/2.1.2`, which meanwhile picked up the
`getColumnEncoding` fix through upstream pull request #24), while this
branch pointed at the older `orc-union-tag-bounds` line carrying one extra
writer-side commit: "Do not count null rows into union children lengths
when writing".

The old and new union-tag-bounds commits are byte-identical patches, so the
only change unique to this branch is the writer fix. It is cherry-picked
onto master's ORC commit as `ClickHouse/orc` branch
`orc-union-write-null-rows` (80427af091c3d09d4634f74756f2498b60675233), and
`contrib/orc` now points there.
alexey-milovidov added a commit that referenced this pull request Jul 29, 2026
…rted

The data-types matching table and the note below it were written when only
reading an ORC `Union` was implemented (#110078). Now that a `Variant`
column is written as an ORC `Union`, fill in the `SELECT` side of the
`Union` row and drop the "not supported yet" sentence.
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants