Skip to content

Fix Iceberg v3 variant columns in ORC data files being read as NULL - #130116

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/orc-read-iceberg-variant
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/orc-read-iceberg-variant

Conversation

@groeneai

@groeneai groeneai commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #130031
Related: #130028

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 Iceberg v3 variant columns from ORC data files, which returned NULL for every row: an ORC struct of two binary fields metadata and value read as Dynamic or JSON is now decoded with the variant binary encoding, as for Parquet. Closes #130031.

Description

On 26.10, reading an Iceberg v3 table whose data files are ORC returns NULL for every variant value (measured on 26.10.2.103; the Parquet copy of the table is read correctly). Iceberg is not needed: file('t.orc', ORC, 'v Dynamic') over the struct<metadata: binary, value: binary> that Iceberg writes gives the same NULLs. On master the same queries return the raw metadata/value blobs instead, since #130171 casts such a struct.

Iceberg maps variant to Dynamic, and the ORC reader had no variant decoding.

Now a struct of exactly two binary fields named metadata and value (either order) requested as Dynamic, JSON or Nullable(JSON) is decoded with Parquet's decodeVariantColumn; an empty non-null blob raises INCORRECT_DATA. Any other struct is still cast to the requested type. ORCColumnToCHColumn takes the FormatSettings, and VariantEncoding.cpp is also built with ORC but without Parquet (FreeBSD). Schema inference and Tuple reads of the struct are unchanged.

Validation: 05569_orc_read_variant covers optional and required structs, swapped fields, JSON/Nullable(JSON), nesting in Array/Map/Tuple and in a nullable struct, malformed variants, and the cast of non-variant structs. It fails on master and passes 10/10, and a mutation of the binary check reddens it. The issue's table gives the values #130028's 05707_iceberg_impala_v3_variant expects. All other ORC, Iceberg ORC and variant stateless tests pass.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits November 8, 2026 09:06
Iceberg v3 stores a `variant` in ORC as a struct of two binary fields,
`metadata` and `value`, in the variant binary encoding, and Iceberg asks
the ORC reader for the column as `Dynamic`. `updateIncludeTypeIds`
selected the fields of a struct only for a `Tuple` request, so for
`Dynamic` nothing was read, the column was treated as missing and filled
with defaults: every value of such a column was NULL, with no error.

A struct requested as `Dynamic`, `JSON` or `Nullable(JSON)` is now
selected in full and decoded with `Parquet::decodeVariantColumn`, before
the `Nullable` wrapping (a `Dynamic` cannot be inside `Nullable`, and the
decoder produces the NULLs). Only a struct of exactly two binary fields
named `metadata` and `value` is accepted, in either order: Iceberg writes
binary, and Parquet likewise only reads binary leaves as a variant. Any
other struct requested as `Dynamic` or `JSON` raises TYPE_MISMATCH instead
of returning NULL or `{}`. The struct's nulls reach both fields through
`StructColumnReader`, so a non-null empty blob is a malformed file, not a
null, and raises INCORRECT_DATA; without that check the decoder would
read it as NULL.

`ORCColumnToCHColumn` takes the `FormatSettings`, which the decoder needs
(`max_parser_depth`, the JSON skip-path option), instead of five values
copied out of them. `VariantEncoding.cpp` is also compiled into `dbms`
when ORC is enabled without Parquet (the FreeBSD build).

Closes ClickHouse#130031.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the comment narrating isORCVariantTargetType, shorten the struct-selection comment, fold the readVariantFromORCStruct doc into one line.

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

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own review (4 nits, none blocking).

# Sev Finding Verdict Evidence / action
1 💡 Errors from the shared decoder say "Parquet variant" for ORC input AGREE, not changed They name the Parquet variant encoding, which Iceberg also uses in ORC; rewording means editing VariantEncoding.cpp, kept as is (#130078 also edits it)
2 💡 src/CMakeLists.txt elseif (USE_ORC) conflicts textually with #130078's elseif (USE_AVRO) AGREE, not changed Both branches append the same file; any resolution keeping either or both is correct
3 💡 ORCColumnToCHColumn keeps five members copied from the stored FormatSettings AGREE, not changed Values unchanged; no behaviour difference
4 💡 A non-variant struct read as JSON now throws, while Parquet casts it AGREE, not changed It returned {} before; stated in the description and the format docs

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-9:20261108-091100

@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [77b7f37]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR decodes Iceberg v3 variant blobs in ORC structs requested as Dynamic, JSON, or Nullable(JSON). Reviewed head 77b7f37ffc9ea56bc059fd063cfdeb60874bdbac, including all prior replies. Two correctness concerns remain after the author's dismissals: ordinary binary structs can be reinterpreted as variants, and explicit dotted schemas can still return undecoded blobs. The two findings about the reverted hint reconstruction no longer apply.

Consumer tracing covered direct chunk output, Array elements, Map values, Tuple elements, nullable parents, matchORCTupleElementsByName, insertNullAsDefaultIfNeeded, and the final cast: these retain the decoded column's declared type. NestedColumnExtractHelper receives undecoded input on the dotted-schema path described below. ORC union branch matching does not select Dynamic/JSON hints for a binary struct.

Findings

❌ Blockers

  • Ordinary binary structs lose their existing conversion semantics. NativeORCBlockInputFormat.cpp:1185 — [dismissed by author -- https://github.com/Fix Iceberg v3 variant columns in ORC data files being read as NULL #130116#discussion_r4659215524]

    isORCVariantRead identifies variants solely by two binary fields named metadata and value. An ordinary ('meta', 'payload')::Tuple(metadata String, value String), written with output_format_orc_string_as_string = 0, previously converted to an object when requested as JSON; it now throws Unsupported Parquet variant metadata version 13. Ordinary bytes that happen to form valid encoding are silently returned as a different value. The Iceberg ORC mapping supplies iceberg.struct-type=VARIANT, and Type::buildSelectedType preserves attributes.

    The author's Parquet comparison does not preserve the existing ORC behavior; the current predicate still changes the meaning of valid, unannotated ORC structs. Require the annotation or an explicit variant opt-in, retaining ordinary struct conversion otherwise.

  • Explicit dotted schemas still bypass variant decoding. NativeORCBlockInputFormat.cpp:2996, with hint construction at lines 3689–3718 — [dismissed by author -- https://github.com/Fix Iceberg v3 variant columns in ORC data files being read as NULL #130116#discussion_r4658808064]

    For the new test's nested.orc, SELECT t.v FROM file('nested.orc', ORC, 't Tuple(v Dynamic)') decodes the object, whereas SELECT * FROM file('nested.orc', ORC, '`t.v` Dynamic') wraps the raw metadata/value tuple in Dynamic. Nested::collect leaves the scalar hint as Dynamic; that hint is applied to parent t, so child v receives no hint and skips the decoder. Deeper dotted projections through lists have the same loss of hints. An explicit JSON target also receives the raw fields.

    The author intentionally retains master's behavior for flat schemas, but these remain supported requests for the same variant value and return different data depending on schema spelling. Preserve requested leaf hints through physical struct/list traversal while keeping virtual subcolumns out of tuple element names; the reverted general reconstruction is not a safe fix.

Tests
  • ⚠️ Add an unannotated binary-struct collision regression alongside an annotated Iceberg variant, proving that ordinary structs retain their values.
  • ⚠️ Compare whole-column and explicit dotted-schema reads for a struct and a list containing nested structs, with Dynamic and JSON targets. Keep the existing field/virtual-null projection working.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary/build is available, so this run verified the findings by tracing current code rather than rerunning their earlier reproductions. The current-head targeted Praktika report did not expose a per-test result for 05569_orc_read_variant; a completed focused run would close this execution-evidence gap.
Final Verdict

Status: ❌ Block

Preserve ordinary binary-struct conversion and decode explicitly requested dotted variant fields consistently, with the focused regressions above. Both remaining findings already have inline threads; no duplicate comments were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 8, 2026
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT id, p, toJSONString(v) FROM icebergLocal('iceberg_v3/iceberg_v3_variant_orc') ORDER BY id (Impala test data) returns \N in all 5 rows on master every time; file(<that .orc>, ORC, 'id Int32, v Dynamic') gives the same.
b Root cause explained? Iceberg requests variant as Dynamic; the ORC::STRUCT case of updateIncludeTypeIds selected fields only for a Tuple request, so nothing was read and the column was filled as missing (NULL). The ORC reader had no variant decoding.
c Fix matches root cause? Yes. The struct is selected in full for a Dynamic/JSON request and decoded with Parquet's decodeVariantColumn at the read site; no setting, no guard.
d Test intent preserved / new tests added? New 05569_orc_read_variant. Six mutations of the fix (no hook, no selection branch, no empty-blob check, string fields accepted, positional fields, JSON not recognised) each redden it.
e Both directions demonstrated? Yes. On master the test prints NULLs and aborts the debug clickhouse-local in the Map(String, Dynamic) arm; with the fix it matches the reference, 50/50 runs. The issue query returns 42, "hello", {"age":30,"name":"Alice"}, \N, \N.
f Fix is general across code paths? Yes. Top-level columns and Array/Map/Tuple elements all go through readColumnFromORCColumn; tested, including a variant inside a nullable struct. Parquet already decodes variants; Avro is #130078.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Dynamic, JSON, Nullable(JSON), Dynamic(max_types=1), typed JSON; NULL struct, variant null, input_format_null_as_default 0 and 1, swapped field order; string fields, other names, empty and one-sided blobs raise errors. Dictionary-encoded fields are converted from LowCardinality.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. A non-variant struct requested as Dynamic/JSON now raises TYPE_MISMATCH instead of returning NULL or {}, which were wrong results.
i Invariants and contracts preserved? Yes. One output value per row, result type equals the requested type; the Nullable wrapping is skipped only for this branch, where the decoder makes the NULLs; all other ORCColumnToCHColumn members keep their values. Builds with ORC and without Parquet compile VariantEncoding.cpp too.

Session id: cron:clickhouse-impl-slot-6:20261108-080700

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @Avogar, could you review this and add the can be tested label so CI runs? The ORC reader selected struct fields only for a Tuple request, so an Iceberg variant (requested as Dynamic) was read as missing and became NULL; it now reads the metadata/value struct whole and decodes it with the Parquet variant decoder.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). labels Nov 8, 2026
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b9a4b73

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 (amd_debug) / Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-2b00) logical error, not from this PR (it only touches the ORC reader): a server-side fuzzed ATTACH TABLE with the f | g composition inside CODEC(...) is formatted inconsistently; the same STID failed on true master on 2026-11-04 #125567 (mine, open)
Build profile diff infra, not from this PR (no ci/ file in the diff): all 8 readiness probes to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready #129675 (mine, open)
PR praktika rollup of the rows above #125567, #129675 (the owners above)

Session id: cron:our-pr-ci-monitor:20261108-143005

groeneai and others added 2 commits November 22, 2026 14:36
…ceberg-variant

Conflicts in `src/CMakeLists.txt` and `NativeORCBlockInputFormat.{cpp,h}`:
- Master builds `VariantEncoding.cpp` without Parquet for Avro too, so the
  condition is now `elseif (USE_AVRO OR USE_ORC)`.
- `ORCColumnToCHColumn` gained the data lake arguments on master; it now
  takes `FormatSettings` in place of the five settings it took from it,
  keeping the new arguments.
- `decodeVariantColumn` takes `Parquet::VariantSettings` on master.
- The `updateIncludeTypeIds` hunk that selected a struct whole for a
  `Dynamic` or `JSON` request is dropped: since ClickHouse#130171 every list, map or
  struct requested as another kind is selected whole.

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

Since ClickHouse#130171 an ORC struct requested as another kind is read whole and
cast to the requested type, so `file('t.orc', ORC, 'v JSON')` over
`struct<a:int,b:string>` returns `{"a":1,"b":"x"}` on master, as
Parquet does. The variant reader threw `TYPE_MISMATCH` for every struct
that is not exactly two binary fields `metadata` and `value`, which
after the master merge would reject such input.

Only a variant-shaped struct is decoded now; any other struct takes the
cast path. The test checks the cast for a plain struct, a struct with
other field names and a struct of `string` fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
checkStackSize();

/// Before the Nullable wrapping below: `Dynamic` cannot be inside `Nullable`, and the decoder makes NULLs itself.
if (isORCVariantRead(*orc_type, type_hint))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Blocker] Preserve the variant type hint when reading a dotted column

The new decoder is skipped for a variant requested through a dotted schema. For example, using this test's nested.orc, compare:

SELECT t.v FROM file('nested.orc', ORC, 't Tuple(v Dynamic)');
SELECT * FROM file('nested.orc', ORC, '`t.v` Dynamic');

The second request reaches orcColumnsToCHChunk's nested-column path. Nested::collect(nested_columns).front().type is just Dynamic here, since it only collects arrays into Nested. Consequently, readColumnFromORCColumn receives that hint for t, and its child v receives no hint. This condition then rejects v, and the final cast wraps the raw metadata/value tuple in Dynamic instead of decoding the object. Requesting the same value as a whole tuple or as a dotted field therefore returns different data; the analogous JSON request also exposes the blobs.

Reconstruct the parent type hint from the requested dotted fields for ordinary ORC reads too (the column_mapper path already does this), and add a stateless assertion comparing these two projections.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in f53e790: a struct read for its dotted subcolumns now gets its type hint from them in ordinary ORC reads too, and 05569 compares the two projections.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Blocker] The simple struct projection is fixed, but the same hint loss remains for a list containing nested structs.

At src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp:3709, an ordinary ORC::LIST still needs column_mapper to enter recursive hint reconstruction. For a file with a Array(Tuple(s Tuple(v Tuple(metadata String, value String)))), containing an encoded object, compare:

SELECT a.s.v
FROM file('deep_array.orc', ORC, 'a Array(Tuple(s Tuple(v Dynamic)))');

SELECT *
FROM file('deep_array.orc', ORC, '`a.s.v` Array(Dynamic)');

The first returns the decoded object array; the second returns an array of raw (metadata, value) tuples. Nested::collect gives the list element a flat s.v field hint, so its actual field s and the variant below it receive no hint. A shallow a.v projection works, which hides the deeper case.

This was reproduced with the 48997f039 PR binary; the final commit leaves this list path unchanged. Extend the recursive hint construction to list roots and compare these projections in the regression test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reverted in 77b7f37: ORC reads a query's subcolumn such as t.v through the whole column t, which decodes the variant, so only an explicit flat schema like `t.v` Dynamic reaches this path. Rebuilding the hint there broke the existing t.null projection, so that schema keeps master's behaviour for every type.

@clickhouse-gh

clickhouse-gh Bot commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 48997f039 with master 3f2770fd6 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@stresshouse

stresshouse Bot commented Nov 22, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

No query shows a performance change caused by this PR. The tested code adds Iceberg variant decoding to the native ORC reader and touches nothing else on the query path. The only flagged query, clickbench Q28 (+7.1%, 1002 ms to 1073 ms), is already inconclusive: the two tests disagree and the measurements on both sides were noisy. Q28 is a MergeTree scan with regex and GROUP BY that never runs the ORC reader, so the delta is not from this PR, and its cause was not checked.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1002 1073 +7.1% <0.0001 cpu: Q28 is +7.1% slower, but the two tests disagree and both sides were noisy. This query never runs the ORC reader this PR changes, so the delta is not from this PR.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: ed33e947-3a38-43b3-83f3-5a17711521a3
  • MIRAI run: bc30c95a-fd94-47ce-8095-eb2b57068adb
  • PR check IDs:
    • clickbench_818333_1795365000
    • clickbench_818351_1795365000
    • tpch_adapted_1_official_818375_1795365000
    • tpch_adapted_1_official_818397_1795365000

Outside the data lake schema, a dotted request such as `t.v Dynamic`
read the struct `t` with the type of its first requested subcolumn as
the hint (`Nested::collect` only builds `Nested` from arrays), so its
field `v` got no hint, the variant decoder was skipped, and the raw
`metadata`/`value` tuple was cast to `Dynamic`. `t Tuple(v Dynamic)` and
Parquet both decode it.

A struct read for its dotted subcolumns now gets the hint from them in
ordinary reads too: `makeTypeHintFromSubcolumns`, which the data lake
path already uses, takes an optional `ColumnMapper`; without one, an
element is the longest prefix of the subcolumn path that the file's
struct has as a field, so a field named `v.w` is found as well. Lists
keep the `Nested::collect` hint. Non-variant dotted reads of structs
give the same results as before (30 shapes: casts, Nullable,
LowCardinality, nested tuples, arrays and maps inside the struct,
missing and case-insensitive fields, fields with dots in their names).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// `Dynamic` or `JSON`.
static bool isORCVariantRead(const ORC::Type & orc_type, const DataTypePtr & type_hint)
{
if (orc_type.getKind() != ORC::STRUCT || orc_type.getSubtypeCount() != 2 || !type_hint)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Blocker] Distinguish an Iceberg variant from an ordinary binary struct

This treats every two-binary-field struct named metadata and value as a variant, even when it has no variant annotation. The Iceberg ORC mapping identifies variants with iceberg.struct-type=VARIANT; ORC::Type::buildSelectedType preserves that attribute.

For example, write an ordinary ('meta', 'payload')::Tuple(metadata String, value String) with output_format_orc_string_as_string=0. Reading it as v JSON or v Dynamic now throws Unsupported Parquet variant metadata version 13. Reading it as a Tuple and then casting still returns the original fields, which is the existing generic struct conversion. Ordinary data can also accidentally contain valid encoding bytes and silently become a different value.

Require the variant annotation or an explicit variant schema/opt-in before decoding, preserve the cast for ordinary structs with these names, and add a regression covering this collision.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Not changing this: it is Parquet's rule for an explicit Dynamic/JSON request, and the same ('meta', 'payload') written to Parquet with output_format_parquet_string_as_string = 0 and read as v JSON fails on master with the same Unsupported Parquet variant metadata version 13. With the default output_format_orc_string_as_string = 1 the fields are ORC string, and the struct is cast as before.

…ke schema

This reverts f53e790. Rebuilding the type hint of a struct from its
dotted subcolumns in ordinary reads turned virtual subcolumns into tuple
elements, so the existing projection `t.a Nullable(Int32), t.null UInt8`
over a nullable struct failed with BAD_ARGUMENTS (`null` is a reserved
tuple element name) where master reads it, and it still missed lists.

ORC does not read tuple elements on its own: a query's subcolumn `t.v`
is read through the whole column `t` and decoded as the variant, so a
dotted name reaches this path only from an explicit flat schema such as
`t.v Dynamic`. That request keeps master's behaviour for every type.

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

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.). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg v3: variant column in ORC data files is read as NULL

1 participant