Repository navigation
Added Parquet Shredded VARIANT Support to ParquetReaderv3 - #102499
rorylshanks wants to merge 179 commits into
Conversation
|
Workflow [PR], commit [fee9f2b] Summary: ❌
|
|
Thanks for the contribution. Really cool. |
|
(I didn't review much, but two standard problems stand out.) There needs to be a more coherent and explicit story for how parquet data types are mapped to CH data types (inside ColumnObject/ColumnDynamic/ColumnVariant). This PR seems to rely on Field::Types for that, which loses information; e.g. Field doesn't distinguish timestamps from ints, so parquet TIMESTAMP would be reported as something like Int64, IIUC. Current code does something like: look at data type in parquet, dispatch to per-type parsing code, put the result into a discriminated union, pass it to ColumnObject, which does a dispatch by type again but slightly differently and calls into per-type column append code. This double dispatch seems counterproductive. I'd try to make parquet parser be in charge of keeping track of the different data types the column/subcolumn contains. Maintain some state for each (E.g. in current PR Current code seems too row-oriented and relies on Or maybe we can just wait for mythos and hope it one shots this :) |
|
Hi Michael, thanks for the review! I'll take a look at making the whole to-typed-column approach simpler and avoiding the double-dispatch. You are right, this is AI and I was kind of at the stage of 'I just want these dang tests to pass' hence the somewhat strange logic. I'll do another pass and try to clean it up! |
|
The fix is in progress: #127761 (open, no review yet). This PR does not cause it. Query #7 is #127761 inlines |
| } | ||
|
|
||
| auto [shared_data_paths, shared_data_values] = object_column.getSharedDataPathsAndValues(); | ||
| ColumnObject::serializePathAndValueIntoSharedData(shared_data_paths, shared_data_values, path, dynamic_value, 0); |
There was a problem hiding this comment.
[P1] Sort flattened JSON paths before appending shared data
The recursive walk preserves sibling object-key order, which is not the order of the flattened, escaped paths required by ColumnObject shared data. For example, an unshredded VARIANT containing {"a":{"z":1},"a-":2} read as JSON(max_dynamic_paths=0) appends a.z followed by a-, although a- sorts first. serializePathAndValueIntoSharedData only appends; the completed row is never sorted.
ColumnObject::fillPathColumnFromSharedData subsequently uses std::lower_bound, so extracting either field from the materialized parent can return NULL instead of its stored value. Escaping literal dotted keys can also change their sort order. Please collect the flattened paths and append shared entries in their final lexicographic order, with a regression covering extraction after a whole-column read with shared data.
| if (!has_values[row] && !tuple_type->getElements().empty()) | ||
| continue; |
There was a problem hiding this comment.
[P1] Preserve a present shredded object with no present children
A non-null object typed_value still represents {} when all its shredded fields are missing; the object shredding rules distinguish the group's presence from its children's presence. This condition discards that distinction before finalizeConvertedContainer can preserve the empty object. The nullable conversion above only removes absent groups, so it cannot restore the discarded value.
For example, a Dynamic column containing JSON values {} and {"a":1} selects object shredding with field a. The writer emits a present typed_value with no present child and no residual for the first row; this branch then marks it absent, and VariantReader::formOutputColumn inserts a default Dynamic value (NULL) instead of {}. Please preserve object-group presence independently of child values and cover the two-row round trip, including an actually absent group as a control.
|
🕵 Merged the latest CI failures on the previous head (60fd4d3) are unrelated, and both have fixes in progress:
@groeneai, thanks for the The three open review threads ask whether to split the |
| out.clear(); | ||
| WriteBufferFromString buffer(out); | ||
| VariantValue json_value = value; | ||
| if (auto nested_value = tryNestVariantJSONPaths(std::move(json_value), format_settings, 1)) |
There was a problem hiding this comment.
[P1] Preserve literal object keys when rendering a VARIANT as String
decodeValue builds object entries with the raw dictionary keys, but this unconditional call treats those entries as flattened ClickHouse JSON paths. For an annotated, unshredded VARIANT containing {"a.b":1}, reading the whole column as String therefore produces {"a":{"b":1}}. Literal %2E sequences are also decoded as path escapes. These are valid object names, so rendering changes the value's structure.
Please preserve the hierarchy of decoded binary objects here. Unflatten only representations explicitly known to contain internal JSON paths, before merging them with raw decoded keys. A fixture with a single literal dotted key, read both as JSON and as String, would expose this independently of subcolumn projection.
|
|
||
| bool array_is_empty = values.empty(); | ||
| DataTypePtr exact_array_type = tryBuildExactArrayType(values); | ||
| result[row] = finalizeConvertedContainer( |
There was a problem hiding this comment.
[P1] Retain optional list presence when merging shredded values
This marks every array row present, although a null optional typed_value (LIST) has already been normalized to empty offsets by Reader::decodePrimitiveColumn. In a valid external shredded object with field a, rows {"a":[1]} and {} can have the same schema; the second row has both a.value and a.typed_value null. Conversion nevertheless produces a present [], and the wrapper's preservation flag keeps it, changing the second row into {"a":[]}.
The shredding rules distinguish a missing field from a present empty array. Please carry the optional list group's presence separately from its offsets and use it here. An external fixture should distinguish absent, present-empty, and explicit-null values; disabling empty-container preservation would break valid empty arrays instead.
| case Field::Types::Tuple: | ||
| { | ||
| const auto & tuple = field.safeGet<Tuple>(); | ||
| for (const auto & child : tuple) |
There was a problem hiding this comment.
[P2] Collect named tuple keys from the source type
Converting a named Tuple to a Field loses its element names, so this traversal collects its values' keys but omits the names required by the residual encoder. With output_format_parquet_json_as_variant=1, writing CAST('{"a":1,"t":{"x":{"k":2}}}', 'JSON(max_dynamic_paths=0, a UInt64, t Tuple(x Map(String, UInt64)))') takes the declared-path fast path: a is shredded, t remains residual, and the dictionary contains a, k, and t. emitVariantColumnarNamedTupleChildren then needs x and throws Missing Parquet VARIANT dictionary entry for key x.
Please collect residual keys using the source column and type, so named tuple elements are retained. The earlier Array(JSON) fix covers its original example, but this named-tuple carrier still cannot be written. A focused write/read test with the schema above would cover the missing case.
|
🕵 Merged The other red check, The three open review threads (splitting |
# Conflicts: # src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
| if (common_exact_type->equals(*output_info.output_type)) | ||
| return materialized_column; | ||
|
|
||
| auto casted = castColumn({std::move(materialized_column), common_exact_type, output_info.name}, output_info.output_type); |
There was a problem hiding this comment.
[P1] Preserve unsigned Variant conversion in the exact fast path
This whole-column cast bypasses tryCastToUnsignedVariantArm, which the general insertion path uses to restore unsigned destination arms from the signed VARIANT encoding. For an unshredded j JSON(max_dynamic_paths=0) containing {"a":7}, reading only j.a with structure j JSON(a Variant(UInt64, String)) reaches this branch with common_exact_type = Int64. FunctionCast::createColumnToVariantWrapper requires an exact source arm, so it throws CANNOT_CONVERT_TYPE instead of producing unsigned 7.
Adding a row {"a":"x"} makes the exact scan decline the optimization; the general path converts the integer to UInt64 and succeeds. The all-null-residual scalar shredded fast path also calls this helper. Please retain the general path's unsigned-arm conversion here, or decline this optimization for affected Variant destinations, and compare homogeneous and heterogeneous inputs in a regression test.
| variant_columns[variant_discr] = std::move(materialized_column); | ||
|
|
||
| auto variant_column = ColumnVariant::create(std::move(discriminators), variant_columns); | ||
| return ColumnDynamic::create( |
There was a problem hiding this comment.
[P2] Honor Dynamic(max_types=0) in exact materialization
This builder always adds common_exact_type as a regular variant, even when both limits passed here are zero. ColumnDynamic's constructor retains that layout without moving values into shared storage, violating the documented invariant that max_types=0 stores every non-null value in the shared variant.
A homogeneous annotated scalar read with explicit type Dynamic(max_types=0) reaches this through finalizeExactOutputColumn, so isDynamicElementInSharedData returns 0; the ordinary insertion path honors the same limit and returns 1. Direct homogeneous subcolumn reads have the same problem. Please handle the zero limit by inserting into shared storage, or decline this explicit-arm shortcut. A regression comparing homogeneous and heterogeneous reads with isDynamicElementInSharedData would cover the difference.
| throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "Cannot encode `DateTime64` value as `Parquet` `VARIANT` timestamp"); | ||
|
|
||
| const VariantPrimitiveType primitive_type = target_scale == 6 | ||
| ? (date_time_type.hasExplicitTimeZone() ? VariantPrimitiveType::TimestampMicros : VariantPrimitiveType::TimestampNtzMicros) |
There was a problem hiding this comment.
[P1] Preserve instant semantics for default-timezone timestamps
hasExplicitTimeZone being false means the type uses the default timezone; its raw DateTime64 value is still UTC epoch time. This branch labels that unchanged value as timezone-naive. With the default timezone Europe/Berlin, toDateTime64('2024-01-01 12:00:00', 6) contains the epoch for 11:00 UTC. Force that Dynamic row into the residual by mixing it with more string rows, and this writes naive 11:00; the homogeneous shredded path instead writes the adjusted timestamp for the original instant.
The encoding specification distinguishes adjusted timestamp primitives from naive timestamp primitives. DateTime has the same issue above. Please preserve adjusted timestamp semantics for default timezones, or translate to actual local wall time before emitting a naive timestamp. A non-UTC regression comparing homogeneous and residual DateTime/DateTime64 values would catch this.
# Conflicts: # src/Columns/ColumnDynamic.h # src/Processors/Formats/Impl/Parquet/Reader.cpp # src/Storages/ObjectStorage/StorageObjectStorageSource.cpp
`CLICKHOUSE_LOCAL` now carries arguments (`clickhouse-local --tmp`), so the quoted form is treated as a single program name and the tests failed with "No such file or directory". CI report: ClickHouse#102499 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Finalize the `WriteBufferFromString` before inserting a nested object rendered as `String`, so no buffer padding is copied into the value. - Give up on the exact array type in `VariantShreddedConversion` when the element type cannot be inside `Nullable` (like the decoder's builders), instead of building `Array` of a null type. - Keep an empty JSON key as the path component `""` of an object leaf, and check the number of path components before indexing it during write analysis. - Do not infer a `FILE` group from tuples inside `VARIANT`, whose element names are object keys. - Check that an integer fits the selected shredded leaf type (not only its `Field` carrier); otherwise keep it in the residual. `256` stored next to `UInt8` values was written as `0`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Update for this pass:
Still open and not addressed in this pass: the other automated findings from 2026-10-19 to 2026-11-03 (in |
# Conflicts: # src/Processors/Formats/Impl/Parquet/SchemaConverter.cpp # src/Processors/Formats/Impl/ParquetBlockOutputFormat.h
| std::vector<String> segments; | ||
| while (!path.empty()) | ||
| { | ||
| auto [head, tail] = Nested::splitName(path); |
There was a problem hiding this comment.
[P1] Preserve empty components when splitting JSON paths
Nested::splitName deliberately refuses splits at leading or trailing dots, but those delimiters represent valid empty JSON keys. For example, {"":{"":{"":42}}} has flattened path ..; this turns it into one literal .. key when writing Parquet VARIANT, changing the object's hierarchy. Likewise, {"a":{"":1}} is written with the literal key a.. The new empty-root-key special case does not cover these nonempty paths.
Please use a splitter that preserves every empty component, including in metadata-key collection, and add round trips for nested empty keys in both dynamic and shared paths.
| if (!has_typed_value_child) | ||
| return false; |
There was a problem hiding this comment.
[P1] Recognize residual-only shredded field wrappers
The object shredding rules permit omitting a field's typed_value child. For a valid j.typed_value.a group containing only binary value, this guard declines the wrapper. Reading only j.a with structure j JSON(a UInt64) then reaches processSubtreeTuple with a UInt64 hint and throws TYPE_MISMATCH, although materializing the parent decodes the same wrapper through tryGetVariantWrapperLayout.
Please recognize residual-only wrappers and decode them using the enclosing metadata. Cover direct-versus-whole-column reads of an external file with an omitted typed_value.
…-variant-support Resolve the conflict in `updateFormatPrewhereInfo` by keeping the PR's construction: it retains all `PREWHERE` inputs in `format_header` and builds `source_header` from the requested columns, which covers the case fixed on master in ClickHouse#128326 (`05339_parquet_prewhere_subcolumn_read_through_column`).
…-variant-support Conflict resolutions: - Parquet reader, schema converter and writer: keep the shredded `VARIANT` changes of this branch, using the `-WithMemoryTracking` containers that master now requires in `src/Processors/Formats` (also converted the containers this branch adds there, for the style check). - `Parquet::Write.h` / `PrepareForWrite.cpp`: keep the extra `FormatSettings` and variant arguments, with master's `ColumnNameToFieldId` type for the field ids. - `Reader::decodePrimitiveColumn`: port master's "compact the dictionary only when the last `PREWHERE` step can throw" into this branch's `finalize_subchunk`. - `VariantEncoding.h`: keep both the variant encoding constants of this branch and master's `VariantValueDecoder`. - `ReadFromObjectStorageStep`: take master's `make_format_filter_info` and pass `format_filter_input_header` as this branch does. - `StorageObjectStorageSource`: keep master's handling of files read under their own names, and treat their filters as fallback filters when deciding whether the count-only path may be used. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Update for this pass:
The three open threads by @scanhex12 ask whether to split the |
…raversal `collectSchemaElementPaths`, `schemaIdxAfterSubtree` and `skipSchemaSubtree` relied on `checkSchemaReadDepth`, which does nothing with `max_parser_depth = 0`. Call `checkStackSize` from that shared helper so a deep chain of REQUIRED groups raises `TOO_DEEP_RECURSION`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…`Dynamic` variants
`IDataType::equals` ignores the timezone of `DateTime`/`DateTime64` and custom names such as
`Bool`. The compatibility checks used to share a stored `Dynamic` variant and to read a `Dynamic`
subcolumn accepted such pairs, so `DateTime('Europe/Paris')` was merged into a `DateTime('UTC')`
variant and `dynamicElement(true::Dynamic, 'UInt8')` returned `1`. Require the type names of
equal leaves to match as well.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…writer - Accept object field offsets that follow field-name order while the values are stored in another physical order: each child spans up to the next greater offset, the last offset is the total size. - Choose a decimal carrier wide enough for the encoded scale: the specification allows scales up to 38 for `DECIMAL4` and `DECIMAL8` too, which threw `ARGUMENT_OUT_OF_BOUND` before. - Keep the raw bytes of the `binary` primitive in the decoded `String` instead of Base64, like the structure-detected reader does. - Write a residual `String` as the `binary` primitive with `output_format_parquet_string_as_string = 0`. - A projected path that is absent in a row reads as missing instead of falling back to the whole parent value. This also fixes a `LOGICAL_ERROR` exception when such a parent was materialized as the requested scalar type of another directly read subcolumn. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lossless conversion A `Field` loses part of a value's type: `Float32` and `Float64` share a carrier, as do `String` and `FixedString(N)`, decimals and `DateTime64` of any scale, and enums are plain integers. The writer accepted such values into the selected shredded leaf and discarded the residual, so a `Float64` was narrowed to `Float32`, a scale-3 decimal was stored as raw digits of a scale-2 one, and an enum value was written with the name of another enum. Pass the resolved source type into `tryConvertVariantScalarToShreddedField` and keep incompatible values in the residual `value`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…domain Two out-of-bounds reads on the rows of a `Parquet` `VARIANT` inside an array: - `PREWHERE` applied the row filter to every `VARIANT` metadata and source state, including the states of an `Array(Dynamic)` that have a row per array element. Drop such states after the enclosing output is formed, like the outputs formed inside an `Array`. - The shared metadata state was sized from the consuming output's row count, which is the element count for a directly read nested path such as `j.arr.a`, so it read past the end of the `metadata` column. Size it from the `metadata` column itself; the parent-to-element mapping is applied by `buildNestedMetadataByRow`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ped_value` `formOutputColumn` propagated `skip_cast` to the children of arrays, tuples and maps, so they kept their physical types while the compound `input_type` is built from the children's output types. A shredded `INT64` array read as `Array(UInt8)` formed `ColumnArray(ColumnInt64)` labelled `Array(UInt8)`, and its bytes were reinterpreted (`[1,0]` instead of `[1,2]`). Cast the children. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/DataTypes/Serializations/SerializationDynamicHelpers.cpp # src/Processors/Formats/Impl/Parquet/ReadManager.cpp # src/Processors/Formats/Impl/Parquet/Reader.cpp # src/Processors/Formats/Impl/Parquet/Reader.h
# Conflicts: # src/Processors/Formats/Impl/Parquet/Write.cpp # src/Storages/prepareReadingFromFormat.h
| case TypeIndex::Time64: | ||
| break; | ||
| default: | ||
| return true; |
There was a problem hiding this comment.
[P1] Keep temporal values separate from integral shredded leaves
This accepts any source type for Date, Date32, DateTime, and integer targets. A Dynamic column containing toDate('1970-01-02'), toDate('1970-01-03'), and toUInt64(42) selects a Date leaf. The last row passes the UInt16 range check, is written as day number 42, and has its residual discarded, so it reads back as the date 1970-02-12 instead of numeric 42. Integer-majority inputs similarly turn temporal values into raw numbers.
Please check source and target semantic types in this common gate before allowing integral conversion, retaining incompatible values in value. Cover both the scalar preparer and nested shredded encoder with temporal/integer mixtures.
| } | ||
| case TypeIndex::FixedString: | ||
| { | ||
| sink.writeString(assert_cast<const ColumnFixedString &>(column).getDataAt(row)); |
There was a problem hiding this comment.
[P2] Apply binary encoding to residual FixedString values too
This sibling of the corrected String branch still always emits a string primitive. For example, with output_format_parquet_string_as_string = 0, a Dynamic column containing two integer rows and toFixedString(unhex('FF'), 1) chooses an integer shredded leaf and sends the FixedString row here. It writes 0xFF under a string tag even though binary output was requested; VARIANT strings must contain UTF-8. The ordinary/shredded FixedString mapping writes binary data.
Please centralize the binary-versus-string choice for all supported string carriers, including size measurement, and add a forced-residual FixedString case with arbitrary bytes. Otherwise the same value changes encoding validity according to which other rows share the file.
Conflict resolutions: - `Reader.cpp`: apply master's `levels_only_arrays` handling inside the PR's `finalize_subchunk` lambda; hash both `preserve_unexpanded_nullable` and `levels_only_arrays` for the columns cache. - `SchemaConverter.cpp`: keep the PR's variant name suppression and deferred `requested` check, plus master's `not_in_datalake_schema` and `leaves_in_arrays` bookkeeping. - `ReadFromObjectStorageStep.h`: both `format_settings` (master) and `need_only_count` (PR) are non-const. - `prepareReadingFromFormat.cpp`: keep the PR's copy of `info`, which already carries `columns_read_under_other_names`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This PR introduces the parquet Shredded VARIANT standard to CLickHouse. duckdb has this already and the main benefit is that it can read less bytes from disk. This is of course critical for a main parquet use case, which is remote reads from S3.
Benchmark results for JSONBench reading from file() on NVME on the final binary are below.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add Parquet shredded VARIANT read/write support, including direct reads for declared JSON typed paths and row-group/page pruning for filters on VARIANT subcolumns.
Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/102499]