Skip to content

Support dynamic type in parquet reader - #117106

Merged
scanhex12 merged 25 commits into
masterfrom
dynamic_parquet
Oct 9, 2026
Merged

scanhex12 merged 25 commits into
masterfrom
dynamic_parquet

Conversation

@scanhex12

@scanhex12 scanhex12 commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

Support reading columns stored in the Parquet VARIANT encoding (semi-structured data, written for example by Spark 4.0).

Detection. A column is read as a variant if it is a group annotated with the VARIANT logical type with specification version 1. Spark 4.0 writes variant columns without this annotation, so an unannotated group with exactly a metadata and a value field of type BYTE_ARRAY is also recognized as a variant. Previously such a group was read as Tuple(value String, metadata String), so this structural detection is controlled by the new setting input_format_parquet_detect_variant_by_structure (enabled by default, guarded by compatibility). Explicitly requesting Dynamic or JSON for the column reads it as a variant regardless of the setting.

Type mapping. The column is read as Dynamic, not JSON, because a top-level variant value is not necessarily an object. Values are decoded directly into the columns, without Field, and keep their own types:

  • primitive types map to the matching ClickHouse types (int32 -> Int32, decimal8 -> Decimal(18, S), timestamp -> DateTime64(6, 'UTC'), timestamp_ntz -> DateTime64(6), binary/string -> String, uuid -> UUID, etc.), and the variant null is NULL;
  • objects are read as JSON, with nested objects flattened into dot-separated paths;
  • arrays whose elements are all objects are read as Array(JSON), other arrays as Array(Dynamic).

Reading as JSON. A variant column can also be read as JSON by requesting that type explicitly. Then every value must be an object, otherwise an exception suggests using Dynamic. Typed paths and SKIP/SKIP REGEXP of the requested JSON type are respected.

Not supported yet:

  • shredded variants (a typed_value field): reading such a column throws NOT_IMPLEMENTED instead of silently losing the values stored in typed_value; the other columns of the file stay readable, and schema inference can skip the column with input_format_parquet_skip_columns_with_unsupported_types_in_schema_inference;
  • VARIANT specification versions other than 1 (NOT_IMPLEMENTED);
  • writing Dynamic or JSON columns to Parquet as VARIANT (UNKNOWN_TYPE), so such a file can't be written back.

Malformed variant data (truncated blobs, out-of-range offsets, a null in only one of metadata/value) is reported as INCORRECT_DATA, and nesting deeper than max_parser_depth as TOO_DEEP_RECURSION.

Changelog category (leave one):

  • New Feature

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

Support reading the Parquet VARIANT type (unshredded, as written for example by Spark 4.0) into the Dynamic type, with objects read as JSON. A variant column can also be read directly as JSON if all its values are objects. Shredded variants are not supported yet.


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

🤖 Generated with Claude Code

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6c7d596]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) FAIL
05316_secret_arguments_declared_by_engines FAIL cidb

AI Review

Summary

This PR teaches the Parquet reader to decode unshredded VARIANT values into Dynamic/JSON, adds structural detection for Spark 4.0 files, and wires in the compatibility setting and tests. The overall direction looks good, but two contract violations remain: explicit JSON(...) typed paths do not follow normal JSON coercion rules, and explicit Dynamic(max_types=...) requests are still decoded with the default 32-type budget before a later cast.

Findings

❌ Blockers

  • [src/Processors/Formats/Impl/Parquet/VariantEncoding.cpp:482] Reading a Parquet variant object as JSON(a T, ...) currently materializes typed paths through castColumn on a one-row column. That uses the generic non-accurate SQL cast path (src/Interpreters/castColumn.cpp:52), so narrowing conversions can wrap/truncate and settings such as type_json_skip_invalid_typed_paths are never consulted. For example, a payload with {"a":300} read as JSON(a UInt8) can silently produce 44, while the regular JSON parser would either throw or insert the default depending on the setting. Please route typed-path materialization through the same JSONExtractTree / typed-path conversion helpers used by SerializationJSON::deserializeObject (src/DataTypes/Serializations/SerializationJSON.cpp:287).
  • [src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp:827] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117106#discussion_r3896802181] The explicit-type contract for Dynamic(max_types=N) is still broken. processSubtreeDynamic always records plain Dynamic as the decode type, Reader::formOutputColumn then creates a 32-slot column from that type (src/Processors/Formats/Impl/Parquet/Reader.cpp:3775), and the later Dynamic -> Dynamic cast only raises the global limit without rehydrating rows that already spilled into the shared variant (src/Functions/FunctionsConversion.cpp:2493). As a result, file(..., Parquet, 'v Dynamic(max_types=254)') still spills everything after the 32nd distinct type instead of honoring the requested budget during decode. Please preserve the hinted DataTypeDynamic (or at least its max_types) before decoding the variant payload.
Tests
  • ⚠️ Add a focused stateless test that reads a variant object as JSON(a UInt8) with a = 300 and checks both type_json_skip_invalid_typed_paths = 0 (exception) and type_json_skip_invalid_typed_paths = 1 (default value), so this path stays aligned with regular JSON insertion.
  • ⚠️ Add an explicit-schema test for file(..., Parquet, 'v Dynamic(max_types=254)') with more than 32 distinct variant types, to prove the requested budget is honored during decode rather than only after a cast.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: switch typed-path decoding to the same coercion path that regular JSON uses, preserve requested Dynamic(max_types=...) while decoding, and add regression coverage for both cases.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Object file sizes

462 object files changed (+194.68 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/VariantEncoding.cpp.o new 181.52 KiB +181.52 KiB

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

Compile time of recompiled translation units

3257 translation units recompiled, 16989 s compile time in total, 3256 of them have a recent master baseline.

Job report

Comment thread src/Columns/ColumnMap.cpp Resolved

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I looked briefly at the implementation. Let's discuss the overall design before I go into details.

1. PR description and docs. First, let's update the PR description and the changelog entry. Right now it's unclear to a reviewer or a future reader what this feature is about. We should state what exactly we add support for here: reading the new Parquet Variant type (let's add a link to its spec as well), how we read it and how we map it to a ClickHouse Dynamic type, and the type mappings. Let's also describe clearly what is supported and what is not, including that we support only reading for now: writing a Dynamic column to Parquet throws UNKNOWN_TYPE, so such a file can't be written back. And please add documentation, we have inline documentation in the code in the ParquetV3BlockInputFormat.cpp file. A link to the Parquet Variant spec in the code where we decode it would help too, so future readers know where to look.

2. Dynamic vs JSON. If I understand correctly, Parquet Variant was added to store semi-structured JSON data. So people might ask why not use JSON instead of Dynamic here. The problem is that our JSON at top-level is always an object, while Parquet Variant can contain any value at top-level. So Dynamic is the right default type to use here, as it can contain any value. We should state it in the PR description and in the docs. But I think users will ask for reading Parquet Variant directly into JSON, so let's also support decoding into a JSON column: we can just throw if some root value isn't an object and say in the exception message to use Dynamic instead.

3. Shredded variants. A shredded group falls through to processSubtreeTuple and the user gets Tuple(metadata, value, typed_value) with raw blobs, which looks very strange to me. This is also why 04930_parquet_variant_shredded fails in all stateless jobs. Let's support shredding, it seems to be one of the main reasons people use Variant in Parquet. If it has to be a follow-up, then let's reject it here with NOT_IMPLEMENTED instead of producing a Tuple.

4. Type mapping. For objects let's use JSON, not Map(String, Dynamic): it's more natural for an unstructured object value than a Map with Dynamic values. Dynamic can hold JSON without a problem. Nested objects will flatten into dot paths. For arrays let's match what JSON does: [1, "s"] -> Array(Dynamic), an array of objects -> Array(JSON). The scalar mapping looks fine.

5. Drop Field. Right now DecodedValue uses a Field, let's try to avoid it as much as possible: fields are very inefficient and can lose the original data types (for example dates/datetimes). Let's deserialize into the column directly. For Dynamic we should use addNewVariant, look up the discriminator, getVariantByGlobalDiscriminator, insert, push the local discriminator and offset, and insertValueIntoSharedVariant if addNewVariant returned false. You can look at how we insert into Dynamic/JSON during JSON data parsing in JSONExtractTree.

6. How do we detect a Variant column? According to the spec a Variant column is a group annotated with the VARIANT logical type, and we already read this flag as logicalType.__isset.VARIANT. It also carries specification_version that we should check. But we detect it by structure instead: any group with 2 unannotated BYTE_ARRAY children named metadata and value. So an ordinary struct with such fields will silently change from Tuple(metadata String, value String) to Dynamic. Let's use the logical type. Old Spark files don't have it, but they have org.apache.spark.sql.parquet.row.metadata with the field typed as "variant" (04928_variant_spark.parquet has exactly that), so we can use it instead of guessing. If we still want the structural fallback for some writer, let's do it behind a setting.

One of the bugs Claude found that I think is worth noting here: readUnsigned does static_cast<UInt32>(data[pos + i]) and data[pos + i] is char, which is signed on x86 and unsigned on ARM. So any byte >= 0x80 sign-extends, and for example an object with more than 127 bytes of values and one-byte offsets reads offset 150 as 4294967190 and fails with Malformed Parquet variant. All test files are under 128 bytes, so we need a new test for it.

I'll review the code in detail once we agree on these.

@scanhex12

Copy link
Copy Markdown
Member Author

@Avogar

Let's do support for Dynamic type right now. The comments about JSON type and shredded parquet are reasonable, but let me add them in another PR.

5 and 6 are fixed

@scanhex12
scanhex12 requested a review from Avogar September 18, 2026 14:03
scanhex12 added a commit that referenced this pull request Sep 29, 2026
Initialize `role` in `SchemaConverter::processSubtreeDynamic` to satisfy `cppcoreguidelines-init-variables`, and describe the new `VARIANT` support in the Parquet format documentation to pass the feature docs check.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117106&sha=202738e6d60d5802a22cdc83a66524a425baaf82&name_0=PR
PR: #117106

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
const DataTypePtr type = getDataTypesCache().getType(type_name);
auto value_column = type->createColumn();
decodeValueIntoColumn(data, pos, context, depth, *value_column);
const ColumnPtr casted = castColumn({std::move(value_column), type, ""}, typed_type);

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.

This path bypasses the normal JSON typed-path coercion rules and applies a generic SQL CAST instead. castColumn does not behave like JSON(a T) insertion: it uses regular cast semantics (for example, narrowing numerics can wrap/truncate) and it never honors settings such as type_json_skip_invalid_typed_paths.

So a Parquet VARIANT object read as JSON(a UInt8) can silently materialize a different value than the same payload inserted through the regular JSON parser. Please route typed-path materialization through the same JSONExtractTree/typed-path conversion helpers that JSON uses, rather than castColumn on a one-row column.

`05299_parquet_variant_read_as_json`: add the output of the `Nullable(JSON)`
section added in e3f7c47.

`04931_parquet_variant_max_dynamic_types`: decimals of the same scale and a
different precision have the same string form, so the 68 values give 39
distinct strings, one per scale.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117106&sha=60c03e5d88d441be92f259fe177b93cc54d96ce5&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
PR: #117106

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@scanhex12
scanhex12 enabled auto-merge October 9, 2026 14:47
@scanhex12
scanhex12 disabled auto-merge October 9, 2026 16:32
@scanhex12
scanhex12 added this pull request to the merge queue Oct 9, 2026
Merged via the queue into master with commit b9f4da1 Oct 9, 2026
160 of 163 checks passed
@scanhex12
scanhex12 deleted the dynamic_parquet branch October 9, 2026 17:16
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
alexey-milovidov added a commit to rorylshanks/ClickHouse that referenced this pull request Oct 11, 2026
`master` gained an independent reader for unshredded Parquet `VARIANT`
columns into `Dynamic` (ClickHouse#117106).
Both readers are kept:

- `processSubtreeVariant` of this branch handles groups annotated with the
  `VARIANT` logical type, including shredded ones.
- `processSubtreeDynamic` from `master` runs after it, so it now only handles
  unannotated groups recognized by structure (as written by Spark 4.0,
  controlled by `input_format_parquet_detect_variant_by_structure`). It is
  adapted to the `depth` parameter of `processSubtree` of this branch.
- `VariantEncoding.h` holds both the encoding constants of this branch and
  the `decodeVariantColumn` declaration from `master`.
- `StorageFile` / `StorageURL` use `ReadFromFormatInfo::getFormatFilter` from
  `master` and still pass `format_filter_input_header`.
- `FormatFilterInfo::hasFilter` takes `top_k_filter` from `master`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit to rorylshanks/ClickHouse that referenced this pull request Oct 11, 2026
Previously this branch inferred `JSON` when `input_format_parquet_enable_json_parsing = 1`.
`master` (ClickHouse#117106) reads a variant as `Dynamic`,
because a top-level variant value is not necessarily an object. Use the same rule, so that both
readers (annotated and structure-detected variants) agree. Type-hint metadata written by
ClickHouse still restores `JSON` for files written from `JSON` columns, and `JSON` can be
requested explicitly.

Tests:
- `04848_parquet_variant_foreign_wrapper_names`, `04402_parquet_variant_malformed_wrapper_value_schema`:
  adapted to the inferred `Dynamic` (it is not allowed in `ORDER BY`).
- `04401_parquet_variant_schema_cache_json_nullable` is removed: it checked that the schema cache
  distinguishes `schema_inference_make_json_columns_nullable` for an inferred `VARIANT` `JSON`
  column, which is no longer inferred.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit to rorylshanks/ClickHouse that referenced this pull request Oct 11, 2026
After the merge, a group annotated with the `VARIANT` logical type is read by
`processSubtreeVariant` of this branch, not by `processSubtreeDynamic` from `master`, so the
behaviour pinned by the tests of ClickHouse#117106 changed:

- `05306_parquet_variant_unsupported_version`: a specification version other than 1 was
  silently decoded as version 1. `processSubtreeVariant` now throws `NOT_IMPLEMENTED` with the
  same message as `master` (or skips the column in schema inference with
  `input_format_parquet_skip_columns_with_unsupported_types_in_schema_inference`).
- `05298_parquet_variant_json_duplicate_path`: the object {"a.b": 1, "a": {"b": 2}} was rejected
  with `INCORRECT_DATA` by `master`'s reader, because the path `a.b` occurs twice once objects are
  flattened. This branch escapes the dot in the key (`a%2Eb`), so both values are kept. This is
  intended, and the test now pins the lossless result.

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

zlareb1 commented Oct 12, 2026

Copy link
Copy Markdown
Member

@groeneai is this correct?

Suggested
The Parquet reader reads VARIANT columns (e.g. written by Spark 4.0) as Dynamic, or as JSON when that type is requested. A group with exactly a metadata and a value BYTE_ARRAY field and no annotation is now read as a variant instead of Tuple; set input_format_parquet_detect_variant_by_structure = 0 or compatibility below 26.10 to keep the old behaviour.

•
Category mismatch with the actual change.
•
Change is BACKWARD-INCOMPATIBLE — must be flagged in changelog.
•
setting input_format_parquet_detect_variant_by_structure changes the inferred schema but is missing from the Parquet schema-inference cache key (ParquetV3BlockInputFormat.cpp:644-661)
•
setting input_format_parquet_detect_variant_by_structure: compatibility value (false) differs from default (true) — intentional, restores Tuple reading

@groeneai

Copy link
Copy Markdown
Collaborator

Yes, all four points hold. The suggested entry needs two precisions. I checked against master (371b23a4) and 26.9.7.6, using the Spark file from 04928_parquet_variant_read.

  1. Entry. Two precisions:

    • The structural match needs unannotated BYTE_ARRAY (binary) leaves. A STRING-annotated pair (ClickHouse's default output for Tuple(metadata String, value String)) still reads as Tuple.
    • It also matches the shredded layout (metadata + typed_value). That layout used to read as Tuple and now fails schema inference with NOT_IMPLEMENTED.

    An explicit Tuple(...) structure reads as before.

  2. and 3. Category / backward incompatibility. Correct, it should be Backward Incompatible Change. On 26.9.7.6, SELECT n, length(v.value) FROM file('04928_variant_spark.parquet') returns 5, 6. On master the inferred type is Dynamic, and the same query fails with UNKNOWN_IDENTIFIER. Schema inference default changes that compatibility restores are listed under that category (e.g. GA Nullable(Tuple(...)) #119222, Fix PostgreSQL Date32 values not being correctly read #95999).

  3. Schema cache key. Correct, the setting is missing from the Parquet key. I ran DESC file(...) with = 1 and then with = 0 in one clickhouse-local process. It returns Dynamic both times, and Tuple both times in the reverse order. With schema_inference_use_cache_for_file = 0, the second query returns the right type. This is the same class as Respect two inference-affecting settings in the schema inference cache key #113533, which added the other Parquet settings to the key. I'll send a PR that adds this one.

  4. Compatibility value. Correct and intentional. The history entry is {"26.10", false, true, ...}, and compatibility = '26.9' infers Tuple again.

Entry with these precisions:

The Parquet reader reads VARIANT columns (for example, written by Spark 4.0) as Dynamic, or as JSON when that type is requested. An unannotated group with a binary metadata field and a value or typed_value field is now read as a variant instead of Tuple (shredded variants are not supported yet and fail with NOT_IMPLEMENTED). To keep the old behavior, set input_format_parquet_detect_variant_by_structure = 0 or compatibility below 26.10.

@groeneai

Copy link
Copy Markdown
Collaborator

The schema cache key fix from point 4 is in #125408.

clickhouse-gh Bot pushed a commit that referenced this pull request Oct 13, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 125455 117198 Revert "Iceberg variant type"
Changelog-deleted-entry: 117198 [Improvement] [raw] * Support iceberg variant type. Based on parquet variant reader - #117106. [#117198](#117198) ([Konstantin Vedernikov](https://github.com/scanhex12)).
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Oct 26, 2026
Antalya 26.8: Backport of ClickHouse#117106 support dynamic type in parquet reader
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Oct 26, 2026
…arquet reader

Prerequisite for the Iceberg `variant` type backport: without the Parquet
variant reader, Spark-written variant columns are read as
`Tuple(value String, metadata String)` instead of `Dynamic`.

The new `input_format_parquet_detect_variant_by_structure` setting is
recorded in the `26.8.34.20001.altinityantalya` settings history block.
Only the variant fixtures are added to the exclude list of
`00900_long_parquet_load_2`.

Related: ClickHouse#117106
Related: #2677 (comment)
Signed-off-by: Andrey Zvonov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-parquet-reader-v3 Issues related to the native Parquet reader. pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants