Skip to content

Added Parquet Shredded VARIANT Support to ParquetReaderv3 - #102499

Open
rorylshanks wants to merge 179 commits into
ClickHouse:masterfrom
rorylshanks:feature/add-parquet-variant-support
Open

rorylshanks wants to merge 179 commits into
ClickHouse:masterfrom
rorylshanks:feature/add-parquet-variant-support

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor

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.

query method wall s user CPU s OSReadBytes
q1_collection_counts parquet_variant_shredded 0.330 0.08 4.1 MB
parquet_variant_unshredded 0.620 0.69 133.9 MB
parquet_string 0.750 1.25 133.6 MB
parquet_json 4.830 4.57 131.8 MB
q2_collection_users parquet_variant_shredded 0.420 0.22 17.4 MB
parquet_variant_unshredded 0.660 0.83 133.7 MB
parquet_string 0.830 2.08 133.3 MB
parquet_json 4.910 5.26 131.2 MB
q3_hourly_events parquet_variant_shredded 0.370 0.13 9.4 MB
parquet_variant_unshredded 0.640 0.78 133.7 MB
parquet_string 0.810 1.93 133.3 MB
parquet_json 4.730 4.64 131.2 MB
q4_first_posts parquet_variant_shredded 0.400 0.13 19.2 MB
parquet_variant_unshredded 0.670 1.13 133.3 MB
parquet_string 0.800 1.93 133.0 MB
parquet_json 4.910 5.23 130.9 MB
q5_activity_span parquet_variant_shredded 0.400 0.15 19.7 MB
parquet_variant_unshredded 0.670 1.06 133.6 MB
parquet_string 0.780 1.92 133.4 MB
parquet_json 4.840 5.00 131.2 MB

Changelog category (leave one):

  • New Feature

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

  • Documentation is written (mandatory for new features)

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

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fee9f2b]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
03548_parquet_missing_tuple_elements FAIL cidb
Build (arm_tidy, 2/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Apr 12, 2026
Comment thread src/Columns/ColumnObject.cpp Resolved
@melvynator

Copy link
Copy Markdown
Member

Thanks for the contribution. Really cool.

Comment thread src/Storages/prepareReadingFromFormat.h Resolved
@al13n321

Copy link
Copy Markdown
Contributor

(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 basic type + primitive type pair from parquet metadata; maybe there would be an IColumn per such type (into which we can directly decode), and a discriminator column for all types; then a ColumnDynamic/ColumnVariant can be directly constructed from those. (+ likely with something separate and recursive for Array and Object basic types.) Sometimes multiple parquet types would map to the same CH column, e.g. IIRC our JSON type widens all signed ints to Int64 instead of storing Int8/Int16/Int32 separately. I'm not super sure this would work, maybe I missed something, but that would be the first approach to try.

(E.g. in current PR tryInsertConvertedFieldIntoColumn implementation looks like the author doesn't care at all about what they're doing and are just trying to stop tests from reporting errors. I assume the author is an AI, and its supervisor needs to do a more careful review with a deeper understanding of the code?)


Current code seems too row-oriented and relies on Fields a lot. Even shredded values are turned into Fields. Sounds slow. I guess this is largely parquet's fault; if I'm reading https://parquet.apache.org/docs/file-format/types/variantshredding/ correctly, the format is very strange and requires some heroic optimizations to parse efficiently. But surely we can do better than this? Hopefully the per-primitive type column approach from above can help?


Or maybe we can just wait for mythos and hope it one shots this :)

@rorylshanks

Copy link
Copy Markdown
Contributor Author

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!

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Apr 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress: #127761 (open, no review yet). This PR does not cause it.

Query #7 is intDiv on signed Int256. On arm_release the out-of-line signed operator/ calls the out-of-line divide<256> with its operands on the stack, so the timing follows stack placement, which shifts with unrelated changes: each binary lands at about 150 ms or about 195 ms. On d11ffb2 the reference is 151 ms and this PR's binary 193 ms; the previous head f2f2b7b got the same verdict (149 vs 191 ms).

#127761 inlines divide into the signed operators. In its own run of this job, query #7 went from 152 ms to 114 ms. Until it is merged, the verdict will keep appearing on unrelated PRs: 29 slower runs on arm_release since 2026-10-22, on 14 PRs and once on master.

}

auto [shared_data_paths, shared_data_values] = object_column.getSharedDataPathsAndValues();
ColumnObject::serializePathAndValueIntoSharedData(shared_data_paths, shared_data_values, path, dynamic_value, 0);

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.

[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.

Comment on lines +598 to +599
if (!has_values[row] && !tuple_type->getElements().empty())
continue;

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.

[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.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (89663e8, no conflicts). clickhouse builds, and a few of this PR's Parquet VARIANT tests pass locally.

CI failures on the previous head (60fd4d3) are unrelated, and both have fixes in progress:

@groeneai, thanks for the bigint_arithm analysis and for linking #127761.

The three open review threads ask whether to split the LowCardinality, UUID and PREWHERE changes into separate PRs. They are still a scope decision for the author and the reviewer.

out.clear();
WriteBufferFromString buffer(out);
VariantValue json_value = value;
if (auto nested_value = tryNestVariantJSONPaths(std::move(json_value), format_settings, 1))

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.

[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(

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.

[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)

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.

[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.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master to pick up the fix for the flaky 05055_format_schema_source_query_background_access (#127797), which was missing from this branch.

The other red check, Logical error: Trying to deserialize data into Variant column with not global variants order (and the resulting Server liveness check failed), comes from SerializationObjectTypedSharedData reading JSON SHARED paths in MergeTree with use_columns_cache = 1. It is unrelated to this PR, also fails on master and many other PRs, and is being fixed in #127867.

The three open review threads (splitting LowCardinality, the UUID utilities and PREWHERE into separate PRs) are scope decisions for the author and reviewer.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
# 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);

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.

[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(

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.

[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)

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.

[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.

alexey-milovidov and others added 3 commits November 4, 2026 21:55
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Update for this pass:

  • Merged the latest master (conflicts in ColumnDynamic.h: kept dynamic_structure_is_fixed and added master's checkStackSize calls; Parquet/Reader.cpp: kept the VARIANT source setup and used master's new RowGroupSelection/selectRowGroups; StorageObjectStorageSource.cpp: combined the filtered-count guard with master's new file_bucket_info check).
  • Fixed the CI failures of 04141, 04241, 04310, 04402: CLICKHOUSE_LOCAL now carries arguments (clickhouse-local --tmp), so it must not be quoted.
  • Fixed and resolved five automated review findings (d3b7e18), covered by 05507_parquet_variant_review_regressions.

Still open and not addressed in this pass: the other automated findings from 2026-10-19 to 2026-11-03 (in VariantBinaryDecoder.cpp, VariantReader.cpp, VariantWrite.cpp, VariantShreddedConversion.cpp, SchemaConverter.cpp, Reader.cpp, VariantUtils.cpp, and the Dynamic type-identity ones in SerializationDynamicHelpers.cpp, ColumnDynamic.cpp, DataTypeDynamic.cpp). Most of them need real changes to the decoder or writer design (object offsets in field-name order, non-unique dictionary strings, decimal carriers by scale, unsigned shredded leaves, timezone and custom-name identity in Dynamic). The three scope questions from @scanhex12 still need a decision from the author or reviewer.

# 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);

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.

[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.

Comment on lines +1583 to +1584
if (!has_typed_value_child)
return false;

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.

[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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Update for this pass:

  • Merged the latest master (1d607cb) and resolved the conflicts in the Parquet reader, schema converter and writer, VariantEncoding.h, ReadFromObjectStorageStep.cpp and StorageObjectStorageSource.cpp:
    • Reader::decodePrimitiveColumn: ported master's change into this branch's finalize_subchunk. The dictionary is now compacted only when the last PREWHERE step can throw.
    • Write.h / PrepareForWrite.cpp: the field ids now use master's ColumnNameToFieldId type.
    • StorageObjectStorageSource: kept master's handling of files read under their own names. For such files the filters are applied after the schema transform, so they also count as fallback filters when deciding whether the count-only path can be used.
  • master now requires -WithMemoryTracking containers in src/Processors/Formats (style check), so I converted the std:: containers that this PR adds there.
  • clickhouse builds. Locally I ran 532 stateless tests that match parquet or variant: 456 passed. The other 76 failures all come from the bare local environment (no MinIO, a different user_files path, no test clusters), not from the code.

The three open threads by @scanhex12 ask whether to split the LowCardinality, UUID and PREWHERE parts into separate PRs. That is a scope decision for the author and reviewer, so I left them open.

alexey-milovidov and others added 8 commits November 10, 2026 07:30
…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;

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.

[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));

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.

[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 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-parquet-reader-v3 Issues related to the native Parquet reader. external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants