Repository navigation
Support the ORC union type in the native ORC reader (map to Variant) - #110078
Conversation
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]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [c695543] Summary: ✅
AI ReviewSummaryThis PR adds native Final Verdict
|
`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]>
…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]>
…ORC format and schema inference docs
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
…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]>
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]>
# Conflicts: # contrib/orc
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`.
|
@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.
The other red, |
# Conflicts: # src/Processors/Formats/Impl/ORCBlockInputFormat.cpp
|
The fix is already in progress: #111691 (yours) adds One correction to the diagnosis: the culprit is not auto probe_size = join_step->getInputRowsEstimation(JoinTableSide::Left);
if (probe_size && *probe_size <= optimization_settings.join_runtime_filter_min_probe_rows)
return false;
With #111691's Worth noting the per-query |
…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`.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 330/374 (88.24%) · Uncovered code |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The logic is a little-bit overdone, but it looks thorough and correct.
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.
…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.
Changelog category (leave one):
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 ClickHouseVarianttype (previously such columns were rejected withUnsupported ORC type).Documentation entry for user-facing changes
ORC
uniontypecolumns can now be read; each is exposed as aVariantover the union's branch types.Maps ORC
union→ ClickHouseVariant:parseORCType: ORCUNION→DataTypeVariantover the branch types.ORCColumnToCHColumn::readColumnFromORCColumn: builds aColumnVariantfrom the ORCUnionVectorBatch(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 aSTRUCTbranch 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.Variantand ORCuniondon't line up 1:1, so:Variantsorts 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.NULL— and a non-null union row that selects a branch whose payload is null (possible for any branch kind, includingLIST/MAP/STRUCTand dictionary-encoded strings) — is represented by theVariantNULLdiscriminator. Branch null maps are taken directly from the ORC batches, because complex branches never come back asNullablecolumns. 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 nestedTuple/STRUCTfield) cannot reject a null-payload placeholder.Variantschema 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 andEnuminteger targets of the matching width (e.g. int →UInt32, tinyint →Enum8, boolean →Enum8, recursively for nested leaves such asArray(UInt32)orMap(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 plainUInt8(mapped to tinyint), so e.g.Variant(Bool, UInt8)overuniontype<boolean,tinyint>resolves one-to-one, and a boolean branch hinted as plainUInt8is cast accordingly. A branch whose correspondence stays ambiguous is read without a hint, so no guess is ever made.STRUCTbranches 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)orVariant(Tuple(b String, a Int32), String)overuniontype<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 nesteduniontype) does not prevent reading the fields the target tuple does reference.Variant->Variantcast, 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)orVariant(Float64, String)overuniontype<int,string>), and aFLOATbranch matchesFloat64- recursively for nested leaves such asArray(Int64). Numeric branches that become ambiguous with each other this way (uniontype<tinyint,bigint>withVariant(Int8, Int64): both matchInt64) 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.LowCardinality(String)under the defaultinput_format_orc_dictionary_as_low_cardinality = 1.CHARandSTRING/VARCHARcan all be read as eitherFixedStringorStringtargets, so e.g.uniontype<char(1),string>overVariant(FixedString(1), String)leaves both branches with two candidates; a tie-break pairs each branch with its natural inference type (CHAR↔FixedStringof the same length,STRING/VARCHAR↔String, withLowCardinalitywrappers 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 withLowCardinalitystripped, souniontype<string,string>is rejected even when its branches happen to be encoded differently.DateTime64(9)but are inferred differently —TIMESTAMPasDateTime64(9)andTIMESTAMP_INSTANTasDateTime64(9, 'UTC')— soTIMESTAMP_INSTANTis matched only by an explicitly time-zoned target (any timezone, not onlyUTC) whileTIMESTAMPstays permissive, and the singles-elimination step decides whether the correspondence is forced. This lets auniontype<timestamp,timestamp with local timezone>resolve toVariant(DateTime64(9), DateTime64(9, 'UTC'))— and an explicit schema such asVariant(DateTime64(9), DateTime64(9, 'Europe/Berlin'))be accepted — instead of being wrongly rejected as duplicate branches (theTIMESTAMP_INSTANTbranch is repair-cast fromDateTime64(9)to the target timezone, a value-preserving relabel).uniontype<int,int>) cannot be represented as aVariant(which would squash them into one branch with a single physical stream), so they are rejected with a clear error.uniontype<uniontype<int,string>,double>) would map to aVariantnested inside anotherVariant, whichVariantforbids. They are rejected explicitly through the normal unsupported-type path (asUNKNOWN_TYPE), before the outerVariantis constructed, so the error is clear instead of aBAD_ARGUMENTSfrom theVariantconstructor andinput_format_orc_skip_columns_with_unsupported_types_in_schema_inferencecan skip such a column and still read the remaining ones.Variantcan 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 clearUNKNOWN_TYPEas well.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, andgetColumnEncodingvalidates the column id against the stripe footer, both throwingParseError(surfaced asINCORRECT_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:
NativeORCBlockInputFormat.cpp, where this pull request adds theUnionrow)Verification
Built locally and exercised end-to-end with union ORC files written by pyarrow:
union<int32,string>→Variant(Int32, String)with values10, 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 →VariantNULLs;Variant(Tuple(b String), String)(projecting away the struct'safield) andVariant(Tuple(b String, a Int32), String)(reordering the struct's fields) overunion<struct<a:int,b:string>,string>;Variant(Tuple(a Enum8(...)), String)overunion<struct<a:tinyint>,string>with a null struct payload (a value-checkingTuplefield cast that must skip the null-payload placeholder), including the all-null-branch case;input_format_orc_dictionary_as_low_cardinality;Variant(IPv6, String)andVariant(Int128, String)schemas over aunion<binary,string>file;Variant(UInt32, String),Variant(Enum8(...), String)(with a null payload in the enum branch),Variant(Enum16(...), UInt64),Variant(Array(UInt32), String)andVariant(Int32, Map(String, Enum8(...)))schemas over the corresponding integer-branch unions;Variant(Bool, UInt8)andVariant(UInt8, String)schemas overunion<boolean,tinyint>andunion<boolean,string>files (plus the inferredVariant(Bool, Int8)for the former);Variant(Enum8('false' = 0, 'true' = 1), String)overunion<boolean,string>andVariant(Enum8(...), Int8)overunion<boolean,tinyint>(the boolean branch takes theEnum8alternative; the latter with a null payload in the boolean branch);Variant(Int64, String),Variant(Float64, String),Variant(Float32, String)andVariant(Array(Int64), String)widening schemas overuniontype<int,string>,uniontype<float,string>anduniontype<array<int>,string>files, plusVariant(Int8, Int64)andVariant(Int64, Int128)overuniontype<tinyint,bigint>(the exact-width pairing decides which branch takes the shared alternative);union<timestamp,timestamp with local timezone>file → inferredVariant(DateTime64(9), DateTime64(9, 'UTC')), with a null payload in each branch, the explicit schema in both branch orders, and an explicitVariant(DateTime64(9), DateTime64(9, 'Europe/Berlin'))(non-UTC) schema;uniontype<char(1),string>file in a dictionary-encoded and a direct-encoded variant, each read with the inferred schema and with explicitVariant(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), anduniontype<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>→ cleanUNKNOWN_TYPE(nested union), skippable withinput_format_orc_skip_columns_with_unsupported_types_in_schema_inference(keeping a supportedidcolumn), and the same rejection on the explicit-structure read path;char(1)..char(255)plusint, written by pyorc) → cleanUNKNOWN_TYPE(more branches thanVariantsupports), skippable in schema inference, and the same rejection on the explicit-structure read path;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 fieldais an unsupported nested union) read with an explicitVariant(Tuple(b String), String)schema that projects awaya→ succeeds,ais never selected or inspected; the same file with a schema that referencesa(or with schema inference, which always inspects every field) → fails the same way04602'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_pruning04635_orc_native_union_boolean_enumand04636_orc_native_union_numeric_widening(inlineunhex()ORC data, so no binary test files).Version info
26.8.1.331(included in26.8and later)