Skip to content

One rule for converting read columns to the requested type in the input format readers - #130259

Open
groeneai wants to merge 43 commits into
ClickHouse:masterfrom
groeneai:parquet-keep-array-sizes-of-missing-elements
Open

groeneai wants to merge 43 commits into
ClickHouse:masterfrom
groeneai:parquet-keep-array-sizes-of-missing-elements

Conversation

@groeneai

@groeneai groeneai commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #130279
Related: #131125

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

With input_format_null_as_default, a NULL read from Parquet, ORC, Arrow, Native or Vortex as a non-Nullable column of another type gets the default of the requested type: Nullable(String) read as Int32 failed with Cannot parse Int32 from String, and Nullable(Int8) read as an Enum without 0 stored the invalid value 0. A Tuple element or column the file lacks gets the default of its type, and ORC, Arrow and Vortex match named Tuple elements by name with one rule. With case-insensitive matching, a name that matches several fields only by case fails with AMBIGUOUS_COLUMN_NAME in ORC and Arrow instead of reading one of them.

Description

On 26.10.2.103, a NULL of Nullable(Int8) read from Parquet or ORC as Enum8('a' = 1, 'b' = 2) returns the invalid value 0, and a NULL of Nullable(String) read as Int32 fails with Cannot parse Int32 from String.

Every columnar reader cast the zero of the file's type stored in a NULL row. castColumnToRequestedType now has one rule: the value of a NULL row is never converted, the row gets the default of the requested type. NativeReader and Parquet's leaf cast call it; every columnar reader shares it, ORC dictionary strings included; Parquet pruning assumes the same value. NativeReader keeps CAST's positional pairing of named tuples with no common name (#70830). ORC pairs struct fields, union branches, hints and pushed-down predicates with DataTypeTuple::matchElementsByName, as the cast does. The tuple-only NULL shortcut and insertNullAsDefaultIfNeeded are deleted.

src: 28 files +982/-1068 vs master.

Case-insensitive matching (#130259 (comment)): a name binds to the field spelled the same, else to the only one differing by case, else fails with AMBIGUOUS_COLUMN_NAME, for tuples, subcolumns and columns. ArrowIPC and Vortex bind each hint to the field the name reads, so `s.a` Int32, `s.A` DateTime from Tuple(A Date32, a Date32) no longer returns 49709 for s.a. ORC pairs Iceberg struct fields by field id first; a field absent by id reads as its default next to namesakes.

Native without conversion rejects a tuple of another size (TYPE_MISMATCH, was LOGICAL_ERROR).

Not changed: CAST of a Nullable(Tuple) still converts the elements under NULL rows.

Validation: 05618 reads the same files in all five formats; its new lines fail on master, except the Native positional guard. Debug, 10M rows: ORC Nullable(Int64) as Int32 0.13 s to 0.21 s; ORC dictionary strings with NULLs as String 0.1-0.5 s to 0.8-1.5 s, as Arrow on master; others the same or faster.


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

groeneai and others added 3 commits November 9, 2026 03:35
…re not in the file

Parquet stores the sizes of arrays (repetition/definition levels) only in leaf
columns, and SchemaConverter requested a leaf only for requested elements that
exist in the file. When none did, nothing under the array was read: a whole
column like `l Array(Tuple(d ...))` got zero offsets in formOutputColumn, and a
flattened subcolumn like `l.d` matched no schema element and was filled as a
top-level missing column. Both read as `[]` for every row, so ARRAY JOIN and
filters on the size lost rows, and inserting the subcolumns into a Nested column
failed with SIZES_OF_ARRAYS_DONT_MATCH. Iceberg reaches this when a data file is
read under a schema whose list element struct gained or replaced fields.

SchemaConverter::addLevelsOnlyPrimitive now adds one leaf under such an array,
read only for its levels: before the REPEATED node's make_array and before the
`arr.elem` wrap arrays when the output has no leaf, and, for `arr.missing`
columns that match no schema element, after the traversal from the recorded
tuples inside arrays (not a Map's key_value tuple: `keys` and `values` name the
subcolumns of a Map). It picks the cheapest leaf: one not read for another
column, without arrays of its own, of fixed width. If the subtree has leaves but
none can be decoded, the error is raised as for a requested leaf, unless
input_format_parquet_skip_columns_with_unsupported_types_in_schema_inference.

The leaf has no output. Its values and the offsets of arrays below it are dropped
right after decoding, because a row subgroup keeps its columns until the end of
the read. PrimitiveColumnInfo::levels_only_arrays is part of the columns cache
identity, so such a column is never served the entry of a column that reads the
same leaf as values.

03548_parquet_missing_tuple_elements pinned the empty arrays: its two such
expectations change, and it is extended with ARRAY JOIN, WHERE, PREWHERE, nested
arrays and tuples inside the element.

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

A requested column like `x.z` that matches no schema element used to be an
is_missing_column output, and formOutputColumn set its bits in the block
missing values, so AddingDefaultsTransform applied an explicit DEFAULT of it.
addMissingElementsOfTuplesInArrays now builds it as an array output sized by a
leaf of the file, so it lost those bits and its DEFAULT was replaced by type
defaults. OutputColumnInfo::report_as_missing restores the report for that
output. Such a column is not served from the columns cache either: a cached
column gets no missing values, so it would lose the DEFAULT on a cache hit.

03548_parquet_missing_tuple_elements checks a DEFAULT of such a column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop two comments that narrate the new code in addLevelsOnlyPrimitive and shorten the report_as_missing doc to one line.

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

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 1 issue fixed, 1 out of scope, 2 notes
Finding Verdict
⚠️ A flattened column such as x.z that is not in the file stopped being reported as missing, so an explicit DEFAULT of it was ignored AGREE, fixed: it is reported as missing again and is not cached
⚠️ Array(Nullable(Tuple(...))) whose requested elements are all missing is still rejected with TYPE_MISMATCH DISAGREE, out of scope: the same deliberate error on master (the tuple null map has no leaf); supporting it is a separate change
💡 A carrier leaf inferred as a geo type is not Nullable, so input_format_null_as_default = 0 could reject its nulls noted, not reproduced
💡 Iceberg: only the whole-column case is fixed for list elements; subcolumns there are #130023 description corrected

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. File written as l Array(Tuple(a Int32, c String)), read with l Array(Tuple(a Nullable(Int32), c Nullable(String), d Nullable(Int32))): on master l.d is [], ARRAY JOIN l.d gives 0 rows, WHERE length(l.d) > 0 0 rows, the Nested insert fails with Code 190, and l Array(Tuple(d Nullable(Int32))) is [], every run.
b Root cause explained? Parquet stores array sizes only in leaf columns. SchemaConverter requested a leaf only for requested elements present in the file, so with none present nothing under the array was read, and the reader emitted zero offsets (whole column) or a top-level missing column (l.d).
c Fix matches root cause? Yes: one leaf under the array is read for its levels only, and the existing per-element default fill produces sized arrays. No guard or tolerance change.
d Test intent preserved / new tests added? 03548_parquet_missing_tuple_elements is extended; its two [] expectations change on purpose, all other lines are kept. Removing each of the three call sites alone reddens only its own lines. A new line checks that an explicit DEFAULT of a flattened column not in the file still applies; it passes on master, and removing the missing-values report reddens it.
e Both directions demonstrated? Master binary: 03548 fails in exactly the changed and added lines; fix binary: passes, 50/50 randomized. Same split on the repro queries and on an Iceberg Parquet table read under a schema whose list element fields were replaced (l: [] vs [(NULL),(NULL)]).
f Fix is general across code paths? All repeated kinds go through one make_array site (3-level and legacy lists, repeated groups, a Map read as Array(Tuple)); plus the arr.elem path and flattened subcolumns, at any array depth and for tuples inside the element. ORC is not changed here; Arrow is already correct.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked: Nullable and non-Nullable elements, NULL lists and NULL structs, empty arrays, nested arrays, string-only leaves, a leaf only under an inner array, every leaf already read, case-insensitive matching, input_format_parquet_allow_missing_columns = 0 (still an error), input_format_null_as_default = 0, PREWHERE, the columns cache, an explicit DEFAULT of a flattened column (also on a second, cached read). Debug and ASan builds.
h Backward compatible? (maintainer-approved exception only) Read side only, no format or setting change. Arrays that were read as [] now have the file's sizes with default elements, which is what the whole-column read and the Arrow format already return.
i Invariants and contracts preserved? Each primitive still belongs to exactly one top-level output, and all leaves of an array output have the same offsets. The extra leaf is never output: its values are dropped after decoding, and the columns cache key distinguishes it. A flattened column that is not in the file is still reported in the block missing values, so its DEFAULT applies, and it is not written to the columns cache, whose entries carry no missing values. Schema inference is unchanged.

Session id: cron:clickhouse-impl-self-slot-57:20261109-042300

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [332bd9e]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) FAIL
Server died FAIL cidb
UndefinedBehaviorSanitizer: undefined behavior (STID: 0993-9a84) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

This PR shares requested-type conversion across the columnar readers, defaults NULL rows using the requested type, and aligns tuple matching, decoder hints, and ORC predicate binding. Reviewed head 332bd9edaa836650f4f9e23aadb2976bdf83e4af, the complete diff, surrounding callers, regression coverage, and every prior discussion reply. No new findings. The four remaining findings below predate this PR and have tracking issues, satisfying the maintainer's accepted follow-up policy.

Missing context / blind spots
  • ⚠️ No ClickHouse binary or build is available locally, so this review did not independently rerun the regression tests. Runtime evidence comes from the prior reproductions and author's validation; the current implementation and test cases were inspected directly.
Findings

❌ Blockers — previously reported; accepted as a tracked follow-up

  • src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp:1149 — [dismissed by author -- https://github.com/One rule for converting read columns to the requested type in the input format readers #130259#discussion_r4638844677] A literal ORC column a.x still loses to an earlier struct a, returning its child or a default instead of the literal column. The exact pass still accepts the first prefix. Give complete field names precedence over descent. Tracked in #133146; accepted deferral, not a new merge requirement.

⚠️ Majors — previously reported; accepted as tracked follow-ups

  • src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp:2810 — ORC union bindings are recomputed after pruning, which can remove a previously unique alternative and fail a valid projection with CANNOT_CONVERT_TYPE. Preserve the binding from the original schema. Tracked in #132878; existing thread.
  • src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp:3078 — [dismissed by author -- https://github.com/One rule for converting read columns to the requested type in the input format readers #130259#discussion_r4638198156] A single physical field serving differently cased requests still receives one decode hint, so one request can observe another's clamping or interpretation. Arrow and Vortex share this path. Preserve per-request decoding semantics. Tracked in #132784.
  • src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp:3573 — [dismissed by author -- https://github.com/One rule for converting read columns to the requested type in the input format readers #130259#discussion_r4638198161] Top-level Iceberg renames still materialize by name and can silently return defaults for an existing field. Carry field-id resolution into materialization. Tracked in #132785.
Final Verdict

Status: ✅ Approve

No additional changes required for this PR under the accepted follow-up policy. Existing threads were left unchanged because the tracked issues still hold in the current code; no duplicate inline findings were posted.

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

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @scanhex12, could you review this and add the can be tested label so CI runs? When none of the requested elements of a tuple inside an array is in the Parquet file, the reader now reads one leaf under the array only for its repetition/definition levels, so the array keeps its sizes instead of reading as []; this changes two expectations of 03548_parquet_missing_tuple_elements.

@clickhouse-gh clickhouse-gh Bot added comp-parquet-reader-v3 Issues related to the native Parquet reader. can be tested Allows running workflows for external contributors labels Nov 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit c4a651708947dcdcb54e340e1ad59aeac9f16b4a was not compared: the CI logs cluster did not answer (the endpoint never became ready: the readiness probe timed out: HTTPSConnectionPool(host='t6h0zvqlg…).

See the job log for details.

groeneai and others added 2 commits November 9, 2026 08:43
A tuple inside an array was recorded for addMissingElementsOfTuplesInArrays
under its physical name even when it, or an ancestor, has a field id that the
column mapper does not know (a column dropped from the Iceberg schema). After
`x` is dropped and added again with new field ids, an old data file still has
the old `x`, so a request for `x.new` took the sizes of the old list and read
`[NULL]` instead of `[]`, and `ARRAY JOIN x.new` produced rows. The traversal
now carries TraversalNode::not_in_datalake_schema down from such an element,
and those tuples are not recorded.

A leaf read only for the array sizes can have NULL values while its type cannot
be Nullable (`Geometry`, which addLevelsOnlyPrimitive infers for a `GEOMETRY`
leaf, is a Variant). With input_format_null_as_default = 0, decodePrimitiveColumn
rejected them before the values were dropped, so a valid array of requested
missing elements failed with CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN. The check is
skipped for such a leaf, as nothing reads its values.

With input_format_parquet_case_insensitive_column_matching, a column like `x.z`
can match two recorded tuples (`X` and `x`), and the sizes were taken from the
first one. The same file read as `x.a` or `x` fails with DUPLICATE_COLUMN, and
now `x.z` fails with it too, whichever of them is checked first.

addLevelsOnlyPrimitive preferred a leaf not read for another column over a
fixed-width one, so with `x.id` requested beside a missing `x.z` it decoded a long
string `x.payload` only to drop it (1,000,164 decompressed bytes instead of 204 in
the test). Variable width now costs the most and being read for another column
the least, so the already read `x.id` is used.

03548_parquet_missing_tuple_elements covers each case: a `GEOMETRY` leaf with a
NULL, an Iceberg list replaced with a new list of the same name (read as a whole,
as `x.new` and with ARRAY JOIN), arrays named `X` and `x`, and the decompressed
bytes of the string case. It also reads one Iceberg file under two schemas with
the columns cache, where the same leaf is a requested element in one and only
gives the sizes in the other: without levels_only_arrays in the cache identity,
the second read returns the values of the first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sizes-of-missing-elements

Resolve the include conflict in SchemaConverter.cpp and use the
-WithMemoryTracking containers that master now requires in
src/Processors/Formats for the containers this PR adds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano Algunenano self-assigned this Nov 10, 2026
@Algunenano

Copy link
Copy Markdown
Member

🕵 A note on how the readers should be unified later, from fixing the same shape for ORC in #130279 (kept ORC-local there because it needs a backport).

The Arrow reader (the by-name block in the struct read of ArrowColumnToCHColumn.cpp), the ORC reader (matchORCTupleElementsByName in #130279) and the Parquet SchemaConverter each implement the same rule: named tuple elements are matched by name, requested elements that are not in the file get defaults, and the others are dropped. The copies exist only because CAST (FunctionCast::createTupleWrapper) converts named tuples that have no element names in common by position.

Suggested unification:

  • An internal flag in FunctionConvertSettings (not a user setting, included in updateHash) that disables that positional fallback for named tuples, passed through castColumn and createInternalCast, and always set by castColumnToRequestedType, which Arrow, ORC and DWARF use.
  • Then delete the Arrow and ORC copies, and use the same cast for the conversions inside the readers: ORC map keys, Variant branches, and the Nested element before createNested.
  • What stays per format is keeping the sizes of lists and maps whose element struct has none of the requested fields: levels-only columns here, and in ORC its narrowest field read without converting its values.
  • Choose the defaults for missing elements once: CAST uses createColumn()->cloneResized, which gives an Enum the invalid value 0, while Fix reading ORC lists and maps whose element struct has none of the requested fields #130279 uses insertManyDefaultsInto, which gives its first value.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Two things I measured on master (41a73dec) that bear on this:

  • Arrow and ArrowStream are no longer read through ArrowColumnToCHColumn (the library reader was removed in 26.8, input_format_arrow_use_native_reader is obsolete). The native ArrowIPCBlockInputFormat has its own copy of the rule in prepareArrowColumnForCast: it matches by name whenever both tuples are named, without the positional fallback, and then calls castColumn directly, not castColumnToRequestedType. The ArrowColumnToCHColumn block is now reached through Vortex, Arrow Flight and the Delta Lake change feed.
  • The defaults already differ between the readers. A file with t Tuple(a Int32) read as t Tuple(a Int32, e Enum8('x' = 5, 'y' = 7)), z Enum8('x' = 5, 'y' = 7): t.e is 'x' in Arrow (createColumnConstWithDefaultValue) and 0 in Parquet and ORC, so SELECT t fails there with UNKNOWN_ELEMENT_OF_ENUM. The whole missing column z is 0 in all three, so SELECT z fails in all three. Choosing the default once would need to cover each reader's missing-column fill as well, not only CAST.

This PR keeps the existing Parquet fill for the elements it adds. If you want, I can do the unification as a follow-up PR once #130279 and this one are merged.

groeneai and others added 5 commits November 10, 2026 17:39
…none of the requested fields)

The unification of the by-name rule for named tuples across the format readers
deletes matchORCTupleElementsByName, which exists only in ClickHouse#130279, so this PR
builds on it until it merges.
Requested in ClickHouse#130279 (comment)

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

The Arrow, ORC and Parquet readers each realigned a requested named tuple
to the read one by name, because CAST converts named tuples without common
element names positionally and insertNullAsDefaultIfNeeded pairs tuple
elements by position. The copies chose different defaults for a missing
element: the first value of an Enum in Arrow, the invalid value 0 in the
others and in CAST.

CAST gets an internal flag (not a user setting, part of updateHash) that
matches named tuples by name also when they have no element name in common,
used by castColumnToRequestedType and the reader casts through
castColumnMatchingTupleElementsByName. insertNullAsDefaultIfNeeded gets the
same flag to pair named tuple elements by name. A missing element or column
is filled with the default of its type (insertManyDefaultsInto) in CAST and
in every reader. The legacy Arrow by-name block and the ORC
matchORCTupleElementsByName are deleted; ArrowIPC keeps only the recursion
into requested elements.

Requested in ClickHouse#130279 (comment)
Design note: ClickHouse#130259 (comment)

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

ORC lost case-insensitive matching on the extracted-subcolumn path once its
own by-name realignment was removed: `c0.up Tuple(b UInt32)` over a file
`UP Tuple(B UInt32)` read `(0)` instead of `(70)` (04401), because the
subcolumn hint never reaches `UP` and the exact by-name cast then filled `b`.

ArrowIPC's alignStructFieldNamesCaseInsensitive moves to
src/Formats/castColumnToRequestedType and ORC calls it at the same point as
ArrowIPC: after the read, before null-as-default and the cast. Its named
tuple branch now uses the exact-first rule of the ORC struct read: an element
spelled exactly keeps its name, and a requested element is taken by at most
one case-folded element. The previous first-occurrence lookup renamed both
fields of `c0 Tuple(A ..., a ...)` to the same name, so ArrowIPC failed with
"Names of tuple elements must be unique", where ORC reads the struct.

createColumnWithDefaults (DataTypes/Utils) replaces the per-row
insertManyDefaultsInto at the five default-fill sites (CAST, Parquet, legacy
Arrow, ArrowIPC, ORC): a bulk cloneResized when the type's default insert is
trivial, as before, else one default row replicated with insertManyFrom.

Requested in ClickHouse#130279 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
One template over Parquet, ORC, Arrow and Vortex with the same expected
blocks: requested named tuples with none, some or all elements in the file
(top level, arrays, map values and keys, Nested), a missing Enum element and
column read as the first Enum value, NULL-as-default paired by name,
case-insensitive column and element names, and, for ORC and Arrow,
fields whose names differ only by case. Then CAST and ALTER MODIFY COLUMN of
a tuple that gains an Enum element.

Parquet is left out of the `input_format_null_as_default = 0` map key query:
it does not read the null map of a nullable struct none of whose requested
fields is in the file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the positional-descent comment in alignStructFieldNamesCaseInsensitive; createColumnWithDefaults: an Enum's default is its smallest value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix Parquet arrays of tuples read as empty when the requested elements are not in the file One by-name rule for requested named tuples in the input format readers Nov 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review of the repurposed PR (1 round): 2 out of scope, 1 note
Finding Verdict
⚠️ A Variant tuple alternative with an added or renamed element is still rejected (CANNOT_CONVERT_TYPE) in ORC and Arrow DISAGREE, out of scope: the same error on master; it comes from choosing the alternative (ORC maps a struct branch only to a tuple whose elements are all in the file, Arrow decodes unions without hints), not from matching elements; the branch conversions themselves now use the by-name cast
⚠️ The ORC count-only carrier can read a large string field because it ties with a fixed-width one and comes first DISAGREE here: real cost, but it is #130279's code (in this diff through the merge); reported on #130279
💡 The new test's header says "every input format reader"; it covers Parquet, ORC, Arrow and Vortex noted

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT CAST(CAST(tuple(1), 'Tuple(a Int32)'), 'Tuple(a Int32, e Enum8(''x'' = 5))') fails with UNKNOWN_ELEMENT_OF_ENUM on 26.3.42.3, 26.8.18.2, 26.10.2.103 and master; the new test 05618 fails on the pre-change tree every run (first at Parquet t.e).
b Root cause explained? CAST matches named tuples with no common element names by position and fills an added element with cloneResized zeros (invalid for Enum), and insertNullAsDefaultIfNeeded pairs tuple elements by position, so Arrow, ORC and Parquet each realigned by name themselves, each with its own default and case rule.
c Fix matches root cause? Yes. The by-name rule moves into CAST (an internal flag set only by the readers) and into the null-as-default pairing; one default helper serves CAST and every reader; the reader copies are deleted.
d Test intent preserved / new tests added? New 05618 (same queries over Parquet, ORC, Arrow, Vortex, plus CAST and ALTER MODIFY COLUMN); 03548 extended earlier in this PR; 04401 and 05617 unchanged and passing.
e Both directions demonstrated? 05618: pre-change binary FAIL, fix OK (50/50 randomized). 04401: the intermediate head without the shared case-insensitive alignment FAIL at c0.up, fix OK. Seven mutations each redden their own lines.
f Fix is general across code paths? Covered: legacy Arrow, ArrowIPC, ORC, Parquet, Vortex (legacy Arrow); top level, map keys and values, arrays, Nested, the extracted-subcolumn path, missing columns. DWARF unnamed tuples stay positional.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable, Array, Map keys and values, Nested, Enum, nested tuples, unnamed tuples, input_format_null_as_default 0 and 1, case-insensitive on and off, fields differing only by case.
h Backward compatible? (maintainer-approved exception only) No new setting. Plain CAST keeps its positional fallback (05026); only the value of an added element changes, to the type default (an Enum8('neg' = -1, 'zero' = 0) element becomes 'neg', as ADD COLUMN gives), stated in the changelog. ArrowIPC case collisions read instead of failing.
i Invariants and contracts preserved? Output column = requested type, elements by name, missing = type default; the alignment changes only types and never produces duplicate names (exact first, each requested element taken once); the default fill keeps the bulk cloneResized for trivial defaults (cost measured equal or lower).

Session id: cron:clickhouse-impl-slot-7:20261110-200400

@clickhouse-gh clickhouse-gh Bot added comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). and removed comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Nov 11, 2026
addLevelsOnlyPrimitive set up the leaf with processPrimitiveColumn, so its values
went through the conversion of the leaf's logical type before they were
dropped. That conversion rejects valid values: an INT96 timestamp after
2262-04-11 does not fit DateTime64(9) (Int96Converter throws
VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE), and a DATE outside the Date32 range is
rejected by the date range check. A list whose struct has only such a leaf,
read as `x Array(Tuple(q Int32))` or as `x.q Array(Int32)`, failed with code 321
although none of those values is requested.

The leaf now decodes its physical values only: FixedString of the physical
width for INT32, INT64, INT96, FLOAT, DOUBLE and FIXED_LEN_BYTE_ARRAY, String for
BYTE_ARRAY and UInt8 for BOOLEAN, the same trivial converters as the
FixedString escape hatch of processPrimitiveColumn. Such a type is always
Nullable outside an array, so the NULL check exemption for this leaf in
decodePrimitiveColumn is not needed any more and is removed. A NULL GEOMETRY
leaf is now read as a String.

Checked locally for every physical type with PLAIN, dictionary, RLE,
DELTA_BINARY_PACKED, DELTA_LENGTH_BYTE_ARRAY, DELTA_BYTE_ARRAY,
BYTE_STREAM_SPLIT and ALP pages, three row groups and 512-byte pages: the
sizes of all 3000 lists match the file in each case. 03548 gets the INT96 and
DATE cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A field of the Iceberg schema that no field of the file has by field id is absent, even if fields of the file have its
name. With case-insensitive matching, a field `Ab` added next to the file's fields `AB` and `ab` was still matched by
name, so its reads failed with AMBIGUOUS_COLUMN_NAME (and read `AB`'s values on master):

- prepareFileReader checks the namesakes of an absent column without throwing, an ambiguous name counts as one: the
  column is not selected and the filter push-down is disabled;
- orcColumnsToCHChunk does not look up an absent column by its own name, only as an element of its parent;
- the struct reader gives an absent element its type's default when it has no `initial-default`, instead of leaving it
  to the cast to the requested type, which pairs elements by name. This also keeps the sizes of a list for an added
  element of its struct: `l.Ab` read `[]` instead of `[NULL]`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 19, 2026 00:29
computeOrcUnionBranchHints tests every union branch against every
alternative of the requested Variant. Since a name that matches several
struct fields only case-insensitively throws AMBIGUOUS_COLUMN_NAME, such
a test against an unrelated alternative made a valid file unreadable:
union<struct<AB int, ab int>, struct<Ab string>> read as
Variant(Tuple(AB Int32, ab Int32), Tuple(Ab String)) with
input_format_orc_case_insensitive_column_matching = 1 failed, also with
schema inference, although every field it reads has an exact match.

The test now treats such a name as no match (matchElementsByName and
matchORCStructFieldsByName report it through `ambiguous`, as
traverseDownORCTypeByName does). A branch that no alternative fits and
that met an ambiguous name still fails with AMBIGUOUS_COLUMN_NAME, as a
struct read does, instead of the later Variant conversion error.

Reported by the AI review:
ClickHouse#130259 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The branch is in conflict with master. Conflicts in the ArrowIPC reader only: master (ClickHouse#132416) keys the
dictionary uses and the registry by position and requested hint (`DictionaryUse::operator==`,
`DictionaryRegistry::useKey`, `dictionaryUse`), as this branch did with `DictionaryUse::key`; master's code
is kept and the branch's copy dropped. Master's `below_union` position (ClickHouse#132550) is kept with this
branch's exact-name hint lookup (`resolveHint` with case-insensitive matching), the per-struct
`structFieldHints` and the top-level field name as the starting path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bool ambiguous = false;
for (size_t a = 0; a < alternatives.size(); ++a)
if (orcUnionBranchMatchesType(orc_type->getSubtype(i), alternatives[a], case_insensitive_matching))
if (orcUnionBranchMatchesType(orc_type->getSubtype(i), alternatives[a], case_insensitive_matching, &ambiguous))

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.

[Major] Keep the original ORC union binding across field pruning

The candidates computed here depend on which struct fields are present. updateIncludeTypeIds computes them against the complete file schema, then readColumnFromORCColumn recomputes them against getSelectedType. Removing an unrequested field can change ambiguity and invalidate the previously selected branch hint.

Reproduced with the PR-head binary:

SET allow_suspicious_variant_types = 1;
INSERT INTO FUNCTION file('union_projection.orc', ORC)
SELECT CAST(CAST((11, 'x'), 'Tuple(AB Int32, ab String)'),
    'Variant(Tuple(AB Int32, ab String), Tuple(Ab Int64))') AS v;

SELECT v FROM file('union_projection.orc', ORC,
    'v Variant(Tuple(AB Int64), Tuple(Ab Int64))')
SETTINGS input_format_orc_case_insensitive_column_matching = 1;

Expected: (11), as with case-insensitive matching disabled. Actual: CANNOT_CONVERT_TYPE from Variant(Tuple(AB Int32), Tuple(Ab Int64)). Initially the first branch matches only Tuple(AB Int64): Ab is ambiguous against AB/ab. Pruning removes ab, after which both alternatives match both branches; their hints disappear and the required Int32 widening never runs. Keeping the original tuple's two fields in the request also succeeds.

Retain the binding derived from the original schema through decoding, keyed by the original ORC column identity, and cover projection plus widening. This also fails on base bc6d347; a linked follow-up issue is an alternative under the maintainer's stated policy for pre-existing bugs. I found no existing tracking issue.

…ype conversion

With `input_format_orc_dictionary_as_low_cardinality = 1` (the default), the
dictionary decoding picked the column's nullability from the requested type,
so for a non-Nullable request a NULL row became the empty string before the
shared conversion ran. Reading the same file with dictionary encoding then
behaved differently from reading it without:

- `e Int32` failed with ATTEMPT_TO_READ_AFTER_EOF parsing '' (expected 0),
- `e String DEFAULT 'fallback'` returned '' for NULL (expected 'fallback'),
- `e String` with `input_format_null_as_default = 0` accepted NULL as ''
  (expected CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN),
- an `Enum8` request failed with UNKNOWN_ELEMENT_OF_ENUM.

The same happened on master. Now a batch with NULLs is decoded as
`LowCardinality(Nullable(...))`, and `castColumnToRequestedType` gives the NULL
rows the requested type's default, sets their missing-value bits, or rejects
them, as it does for every other column. This applies to STRING, VARCHAR and
CHAR, at the top level and inside tuples, arrays and maps; a batch without
NULLs is decoded as before.

Cost: a batch with NULLs requested as non-Nullable `String` or
`LowCardinality(String)` now pays the per-row default fill of
`ColumnLowCardinality::cloneWithDefaultOnNull`, the cost Arrow dictionaries
with NULLs already pay on master. Debug build, 10M rows, 10% NULLs,
1000 distinct values, max_threads = 1: ORC 0.10-0.30 s -> 0.8-1.5 s,
Arrow 0.7-1.7 s on master and with this change.

Reported by clickhouse-gh in
ClickHouse#130259 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With case-insensitive matching, the push-down looked the predicate column up
in the header with `Block::findByName(name, true)`, which returns the first
column whose name matches case-folded, and since this PR it resolves the file
field through that header column's name. With both `AB` and `ab` requested, a
predicate on `ab` read the statistics of `AB` and dropped a matching stripe:

- `SELECT AB, ab ... WHERE ab = 22` and `SELECT ab, AB ... WHERE AB = 11`
  returned no rows instead of `11, 22` with input_format_orc_filter_push_down = 1,
- the same for tuple roots `T` and `t` (`WHERE t.a = 22` read `T.a`).

Master was not affected: it resolved the file field from the predicate name.
Now the header column is found as the fields of a struct are: the one with the
same name, else the only one whose name differs only by case (no push-down when
several do). `05618` covers both requested orders and the tuple roots, and asserts
that the push-down still prunes the stripe for them (read_rows 0).

Reported by clickhouse-gh in
ClickHouse#130259 (comment)

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3761c4b

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
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05829_autopr_skip_index_on_read_in_subquery fails on master too; the test was pinned after this build started #132867 (ours, merged)
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 02346_text_index_transform_access fails on other PRs too: the remote replica of plan-based parallel replicas refuses the read #132916 (ours, open)
Upgrade check (amd_release) / Logical error: Cannot finalize buffer after cancellation. (STID: 2341-1787), and the 5 follow-up checks that could not connect to the aborted server logical error in TCPHandler after a failed log send, not in this PR's code #113438 (ours, open)
Docker keeper image / clickhouse/clickhouse-keeper:head-distroless-amd64 infra: apt mirrors unreachable during the distroless build (12:11-12:32 UTC, 6 PRs) a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20261119-130022

With input_format_arrow_case_insensitive_column_matching, a decoded field whose
path no requested name spells took the type of the only requested name that
differed from the whole path only by case. That ignored which field the reader
actually extracts for the name, so:

- with roots `S` and `s` and the requests `S.a`, `s.A`, the field `s.a` matched
  both names and got no hint (a date32 of 3000000 read as Int32 became 2932896,
  and a value outside the DateTime range no longer threw, unlike the whole tuple);
- an unrequested case variant of a requested field took its hint (`c1.A` alone
  from `Tuple(A Date32, a Date32)`, or `A` next to a top-level `a`), so its own
  value could fail the hint's range check.

bindRequestedTypes now keys the requested types by the field each column reads,
resolved like buildChunk extracts it (the whole name as a top-level field, else
the first component as a top-level field and the rest below it, each spelled
exactly, else the only case-insensitive match). The decoder looks hints up
exactly again, as on master. A field read by several case variants still gets
no hint.

Found by the AI review of ClickHouse#130259 (r4630484011).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
if (const auto [table, rest] = Nested::splitName(std::string_view(column.name)); !path && !rest.empty())
if (const auto root = find(top_level_fields, "", table))
path = find(nested_fields, *root + ".", rest);
if (path && !types.contains(*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.

[Major] A field that serves two case-insensitive requests still gets only one decode hint

bindRequestedTypes drops the folded binding when the resolved physical path already exists in types. With a file that contains only A Date32, the header a Int32, A DateTime resolves both requests to physical A. The exact A request keeps the DateTime hint, while a contributes nothing here, so the field is decoded once through DateTime's range checks and both result columns reuse that decoded data. The later cast cannot recover a's own Int32 semantics after clamping or raw-byte reinterpretation has already happened.

Please either carry per-request uses through decoding (for example by distinguishing (physical field, requested type) the way the shared-dictionary fix distinguishes dictionary uses), or link the follow-up issue if you want to defer this pre-existing wrong-result case.

ColumnWithTypeAndName column;
auto orc_column_it = find_orc_column(header_column.name);
/// A column absent by field id is not read from a field that has its name, only as an element of its parent.
auto orc_column_it = absent_columns.contains(header_column.name) ? name_to_column_ptr.end() : find_orc_column(header_column.name);

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.

[Major] Top-level Iceberg renames still materialize as missing columns

The new Iceberg-aware selection path resolves a renamed top-level field by field id in prepareFileReader, but orcColumnsToCHChunk still materializes top-level columns only by header_column.name here. If the current schema renames top-level old (field id 1) to new, an ORC file that still stores old with field id 1 is selected earlier via resolveORCFieldByIcebergId, then dropped here because name_to_column_ptr only has old; new falls through to the missing-column path and gets defaults.

Please carry the resolved top-level file field (or its field id) into materialization instead of re-resolving by name only, or link the follow-up issue if this pre-existing Iceberg rename bug is being deferred.

{
return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)};
if (!fold)
return {target_copy.size() == field_name.size() ? "" : target_.substr(field_name.size() + 1), type_->getSubtype(i)};

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] Resolve a complete dotted field name before accepting a path prefix

The exact pass returns the first matching prefix, so a physical field named a.x loses to an earlier struct named a. prepareFileReader then selects the struct's child and prunes the actual top-level a.x; materialization takes the nested value instead. This silently reads another field even with case-insensitive matching disabled.

Reproduced with the PR-head binary:

INSERT INTO FUNCTION file('dotted.orc', ORC)
SELECT tuple(11)::Tuple(x Int32) AS a, toInt32(22) AS `a.x`;

SELECT * FROM file('dotted.orc', ORC, '`a.x` Int32');
-- Actual: 11. Expected: 22.

Requesting both a Tuple(x Int32) and the literal a.x Int32 also returns (11), 11. Please give a complete field-name match precedence over descent through a shorter prefix, consistently for selection and predicate binding, and cover both file orders. The same prefix selection is present in base 0e212e6ce6fd; under the maintainer's follow-up policy, linking a tracking issue is an alternative to extending this PR. I found no existing issue for this case.

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.

Same on master ec475edd5e3d (a.x reads 11, and 0 when a has no field x), so following the follow-up policy I opened #133146 for it instead of extending this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the La Casa Del Dolor (amd_debug) failure on ec0f52f7 (Logical error: 'Cannot alter table t27 metadata doesn't have structure', STID 3623-3a50): #133156. It is not caused by this PR: StorageObjectStorage kept its table id from before EXCHANGE TABLES.

@Algunenano

Copy link
Copy Markdown
Member

@groeneai Please fix conflicts

@groeneai

Copy link
Copy Markdown
Collaborator Author

Working on it: I'm merging master and resolving the conflicts now, and will push once it builds and the affected tests pass.

groeneai and others added 2 commits November 23, 2026 21:52
…sizes-of-missing-elements

Conflicts:
- `ArrowIPCBlockInputFormat.cpp`: master made `buildChunk` the free function `ArrowIPC::buildChunk`
  (also used by `Vortex`) with an `allow_missing_columns` argument; kept this branch's body
  (`createMissingColumn` with that argument, `castColumnToRequestedType`, `reinterpretRawByteColumnsImpl`).
- `RecordBatchDecoder.h`: master's per-batch node state (`setBatchNodes`) with this branch's comment.
- `FunctionsConversion.cpp`: includes of both sides.

Also: master's nested-conversion copy constructor of `FunctionConvertSettings` copies `tuple_elements_matching`
from its base, as it copies the other settings it does not override.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This branch made the Arrow IPC decoder look requested types up by the exact field path, keyed by
`RecordBatchDecoder::bindRequestedTypes`. `Vortex`, which master moved onto the same decoder, still keyed them by
the lower-cased header name, and master's `decodeExternalBatch` seeded the lower-cased field name, so with
`input_format_arrow_case_insensitive_column_matching = 1` a subcolumn of a struct lost its hint: `S.A DateTime`
from a `Date32` of 2200-01-01 returned 2106-02-06 instead of the `VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE` that master
and the whole-tuple read give. Both now follow the Arrow reader; a line in 05618 covers it.

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

Copy link
Copy Markdown
Collaborator Author

Done: merged master in 6a8f934 (conflicts in ArrowIPCBlockInputFormat.cpp, where master made buildChunk the free ArrowIPC::buildChunk that Vortex now uses too, plus RecordBatchDecoder.h and FunctionsConversion.cpp).

One semantic conflict needed a separate commit, 332bd9e: Vortex reads through the Arrow decoder but keyed its type hints by the lower-cased name, which this branch no longer uses, so with case-insensitive matching S.A DateTime from a Date32 of 2200-01-01 returned 2106-02-06 instead of throwing as on master. It now binds hints like the Arrow reader; a line in 05618 covers it.

@Algunenano
Algunenano enabled auto-merge November 24, 2026 16:12

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.

2 participants