Skip to content

Fix the native Arrow reader's handling of unobservable slots, dictionaries and buffer-less lengths - #110531

Merged
nihalzp merged 76 commits into
ClickHouse:masterfrom
nihalzp:fix-arrow-null-slot-validation
Sep 8, 2026
Merged

nihalzp merged 76 commits into
ClickHouse:masterfrom
nihalzp:fix-arrow-null-slot-validation

Conversation

@nihalzp

@nihalzp nihalzp commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

Related: #111996
Related: #111534
Related: #109741

The Arrow specification leaves the value bytes of unobservable slots undefined: slots that are null at their own or an ancestor level (a struct's nulls do not have to be repeated in its children's validity), slot ranges no list offset references, and union child slots not selected by their row's type id. The native Arrow IPC reader ran value-level validation — the Date32 range check, dictionary index bounds, BinaryView view checks, the raw-byte width sniff for IPv6 and the big integers — over every slot before applying null maps, so spec-valid files failed to read. It also copied those undefined bytes into the result, so they surfaced as values whenever an ancestor null map is dropped, which is what reading a nullable struct as a plain Tuple does.

ClickHouse produces such files itself: Date32 arithmetic does not clamp the stored day number and nullIf keeps the original payload under the new null mask, so the writer stores an out-of-range day number under a null slot and the reader then refuses to read it back.

INSERT INTO FUNCTION file('t.arrow', 'Arrow')
SELECT nullIf(x, x) AS d FROM (SELECT toDate32('9999-12-31') + 100 AS x);

SELECT * FROM file('t.arrow', 'Arrow');
Code: 321. DB::Exception: Arrow IPC date32 value 2932996 is out of the allowed
Date32 range [-719528, 2932896] ... (VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) -- but should work fine

The same failure occurs one level deeper with a nullable struct read as Nullable(Tuple) (with allow_experimental_nullable_tuple_type): the child of a NULL struct row can hold garbage while its own validity marks it valid, so only the composed ancestor validity reveals the value is unobservable.

The reader is now driven by one composed invisible-rows mask: value-level validation skips those rows, and every leaf decodes them as the type default instead of copying the undefined bytes — including the fixed_size_binary leaves the ClickHouse writer uses for UUID, IPv6 and the 128/256-bit integers, and the self-describing Arrow uuid extension type.

Dictionary-encoded fields get the same treatment. Dictionary values are decoded before the record batches that use them, using the requested type of each referencing field and retaining the resulting type in the registry. This fixes two more files ClickHouse writes itself with output_format_arrow_low_cardinality_as_dictionary = 1: a LowCardinality(Date32) holding an out-of-range day number could not be read under a numeric target, and LowCardinality of Int128, UInt128, Int256 or UInt256 came back as FixedString dictionaries that the cast text-parsed and rejected.

A null-typed child carries no buffers, so nothing but its parent bounds its declared FieldNode length. The decoder therefore validates every child's declared length against what its parent references before decoding it, and builds a buffer-less child only for the rows the visible slots reference: the range under a NULL list slot or the unreferenced head of a sliced list is never materialized, however large the offsets make it.

The changes also cover:

  • Nullable tuple conversion. Convert visible tuple rows and construct placeholders for NULL rows in the destination type. For example, reading a nullable struct with a string child into a tuple with an integer child must not attempt to parse an empty string underneath a NULL struct. When defaults are allowed, use the destination type’s defaults, including nonzero Enum defaults, and preserve column DEFAULT expression handling. The conversion also handles tuples nested inside arrays, maps, and dictionaries.

  • NULL dictionary entries. Store dictionary-entry null maps separately from the decoded values, including across dictionary deltas. This preserves nullness for types such as Array, Map, and plain Tuple, which cannot retain an outer nullable wrapper. A visible reference from a non-nullable field to a NULL dictionary entry is rejected instead of silently producing an empty array, empty map, or default tuple.

  • Shared dictionaries. Fields sharing a dictionary can use different target types and nullability. Compatibility checks ignore unrelated metadata and list child names while retaining distinctions that affect decoding. For example, two list fields sharing a dictionary are accepted when only their child names or unrelated metadata differ.

  • Dictionary updates. Keep decoded types and null maps consistent across dictionary deltas and enforce the uniqueness required by LowCardinality. Reject replacement dictionaries in Arrow files. File dictionaries continue to apply to every record batch, with deltas applied in footer order; their physical position does not impose stream-style ordering.

  • Bufferless fields and row counts. Check every root field’s declared length against the record batch length, including skipped columns, and validate child lengths before materialization. Avoid constructing rows from invisible or unreferenced bufferless ranges. Represent bufferless roots compactly and expand batches containing only constant results in chunks bounded by the existing max_block_size. Valid bufferless files remain readable, metadata-only counts retain their declared row count, and normal query limits apply. Ordinary materialized batches avoid an additional slicing copy.

Scope:

  • The first version of this pull request fixed the Apache Arrow library reader as well. That reader was removed from the Arrow formats in Remove the Apache Arrow library reader and writer for the Arrow formats #111996, so those changes are gone and input_format_arrow_use_native_reader no longer selects anything. ArrowColumnToCHColumn still validates the bytes of null slots the same way, but it is now reachable only through ArrowFlight and DeltaLake, so that is left for a separate change with its own coverage.

  • Reading a nullable struct as a plain Tuple drops the struct null map, and the NULL row's element values now read as type defaults rather than as the payload the producer left behind (ORC, whose null map does reach the tuple elements, shows NULLs for the same file, so the defaults are the closer of the two answers).

  • Flattened subcolumn extraction from nullable structs, such as requesting only `s.v` from s Nullable(Tuple(v Int32)), remains a separate issue addressed by Fix Arrow flattened Tuple subcolumn read from a nullable struct #109741.

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

Fix reading Arrow and ArrowStream files containing values hidden by NULLs or unused nested ranges, which could cause validation errors or expose undefined values. Fix nullable tuple conversions and destination defaults, dictionary decoding under requested types, and NULL dictionary entries for complex types. Accept compatible shared dictionaries with differing field annotations and reject replacement dictionaries in Arrow files. Validate nested row counts before allocation and read bufferless batches incrementally without materializing their entire declared row count.


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

@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0b89d2f]

Summary: ✅


AI Review

Summary

This PR hardens the native Arrow IPC reader around invisible slots, dictionary batches, bufferless nested layouts, and union null handling. Most of the earlier edge cases now look covered, but one explicit-schema gap is still open: Arrow unions still drop requested Variant branch hints, so some valid files will decode the branch to the wrong type and then fail the final Variant cast.

Findings

⚠️ Majors

  • [src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp:1440-1443] decodeUnion still decodes every child with target_hint == nullptr and resets path / list_depth, which breaks the explicit-schema contract for Arrow unions. Requests like Variant(Bool, UInt8) over union<bool, int8>, Variant(Int32, String) over a date32 branch, or Variant(IPv6, String) / Variant(Int128, String) over a fixed_size_binary(16) branch need per-branch hint-driven decoding. The later Variant -> Variant cast cannot repair those mismatches because it only supports extending the alternative set, not replacing an existing branch type.
    Suggested fix: compute Arrow union branch hints the same way the native ORC reader does and thread them through both decodeUnion and the union arm of collectDictionaryUses, so dictionary-encoded branches below unions resolve to the same requested alternative.
Tests
  • ⚠️ Add a focused native Arrow regression with an explicit union target whose branch type differs from inference and therefore must be fixed at decode time, for example union<bool, int8> read as Variant(Bool, UInt8) or union<fixed_size_binary(16), string> read as Variant(IPv6, String). That would fail on the current code and prove the new branch-hint plumbing.
Final Verdict

⚠️ Request changes.

LLVM Coverage Report

Measured on commit 0b89d2f.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 1372/1458 (94.10%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.90% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.10% 78.10% +0.00%

Changed lines: Changed C/C++ lines covered: 592/651 (90.94%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

Was it fixed by migrating to the native arrow reader?

@alexey-milovidov

Copy link
Copy Markdown
Member

No — I checked against a master binary from today (26.8.1.1436, b03544a19bc3e7046b8ac5eb6467bf444f295038).

Removing the Apache Arrow library reader (559f3d4) did not fix this, because the native IPC reader runs the same value-level validation over unobservable slots. The extended Date32 range (cb0accdedb4) only moved the threshold, and 207b5d855d3 + a7843c4a671 added more day-number validation of raw slots, so a file ClickHouse itself writes still cannot be read back:

INSERT INTO FUNCTION file('t.arrow', 'Arrow')
SELECT nullIf(x, x) AS d FROM (SELECT toDate32('9999-12-31') + 100 AS x);

SELECT * FROM file('t.arrow', 'Arrow');
Code: 321. DB::Exception: Arrow IPC date32 value 2932996 is out of the allowed Date32 range [-719528, 2932896] ... (VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE)

Running the crafted pyarrow files of 04513 against that binary, 24 cases still fail through the native reader — Arrow IPC date32 value 2147483647 is out of the allowed Date32 range, Arrow IPC dictionary index 100 out of range, Negative Arrow view length -1, Arrow union row references unknown type id 99, Arrow dense union offset 999 out of range, and the raw-byte IPv6 / Int128 hint paths. Six of them (the unions, and NULL list/map slots spanning a non-empty range) are native-only cases the library reader never reached at all. One case is worse than an error: struct_date32_garbage_under_null read as Tuple(d Int32) returns (2147483647), so the hidden bytes surface as a visible value instead of the default.

What the removal does obsolete is the ArrowColumnToCHColumn half of this pull request as far as the Arrow format is concerned — the reader is no longer selectable, so the input_format_arrow_use_native_reader = 0 loop in the test has to go. That converter is still used by ArrowFlight and DeltaLake, so the same problem exists there, just no longer reachable through file(..., 'Arrow').

I am taking over the branch: merging master, dropping the library-reader parts, and finishing the fixed_size_binary gap the review points at.

…-validation

# Conflicts:
#	src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp
#	src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp
`InvisibleRowsMask` promises that the values of unobservable slots decode as
type defaults, but only the paths that validate those bytes honored it. The
plain-copy leaves - every `ColumnVector` / `ColumnDecimal` filled by `fillFixed`,
`bool`, `date64`, `fixed_size_binary` and the value bytes of the variable-width
`binary` / `utf8` leaves - copied every slot verbatim, so the undefined bytes of
an invisible row surfaced as a value whenever an ancestor null map was dropped:
reading a struct as a plain `Tuple` turns its NULL row into a visible one.

`fixed_size_binary` is the case that matters in practice, because the ClickHouse
Arrow writer stores `UUID`, `IPv6` and the 128/256-bit integers that way and
`reinterpretFixedStringLeaf` reinterprets those bytes verbatim, so hidden bytes
came back as a value of the target type. The self-describing Arrow `uuid`
extension type is decoded into `UUID` right here, with no later rewrite that
could default the row, so it is handled in the decode loop itself.

The offsets of an invisible variable-width slot stay validated: monotonicity and
the data-buffer bound are structural properties of the offsets buffer, not
value-level checks.
@nihalzp
nihalzp force-pushed the fix-arrow-null-slot-validation branch from c7d4640 to 146a5ca Compare September 7, 2026 19:37
ColumnPtr child_column = size_determined
? buildSizeDeterminedColumn(child, selected_rows, /*target_hint=*/nullptr, /*path=*/{}, /*list_depth=*/0)
: decodeField(
child, /*allow_low_cardinality=*/false, /*target_hint=*/nullptr, /*path=*/{}, /*list_depth=*/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.

decodeUnion still drops the requested Variant alternative types completely: both branches decode each child with target_hint == nullptr and reset path / list_depth.

That leaves explicit Arrow union schemas broken whenever a branch needs hint-driven decoding instead of the inferred Arrow child type. Concrete cases are the same ones the native ORC reader already handles with per-branch hints: union<bool, int8> read as Variant(Bool, UInt8), union<date32, string> read as Variant(Int32, String), or union<fixed_size_binary(16), string> / dictionary-encoded binary read as Variant(IPv6, String) or Variant(Int128, String). In those shapes the branch is decoded as Bool / Int8 / Date32 / FixedString(16), and the later Variant cast cannot repair it because Variant -> Variant only supports extending the set of alternatives, not replacing an existing one.

This needs Arrow-side branch hint resolution analogous to computeOrcUnionBranchHints, and the same hint plumbing in the union arm of collectDictionaryUses so dictionary-encoded branches below unions keep working too.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The PR is already very big. Let's fix missing rare cases separately in a new PR. @groeneai Investigate it and open a fix covering this case if valid.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Acknowledged. I'm validating the missing per-branch Variant hints in decodeUnion (and the union arm of collectDictionaryUses) against master, and I'll follow up here with a PR, or with the measurement if a case turns out not to reproduce.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Opened #119098.

Three of the four shapes reproduced on master and are fixed there: union<bool, int8> as Variant(Bool, UInt8), union<fixed_size_binary(16), utf8> as Variant(IPv6, String) and as Variant(Int128, String), and the same branch dictionary-encoded, in both Arrow and ArrowStream. ClickHouse's own writer is affected too: it stores IPv6 as fixed_size_binary(16), so a file written from Variant(IPv6, String) could not be read back with that structure.

Two measurements narrowed the scope, both stated in the PR description:

  • union<date32, utf8> as Variant(Int32, String) stays rejected. Whether a day number is range-checked, saturated or copied verbatim is decided inside the decoder from its own hint (RecordBatchDecoder.cpp:728-771), so a Date32 element takes only its own alternative. Substituting it after the decode would make a union date32 read reject a day number the flat column path returns verbatim, which 05060_native_arrow_ipc_dictionary_date32_numeric pins.
  • The union arm of collectDictionaryUses needs no hint for this. The repair runs after the dictionary is applied, so a dictionary-encoded branch is repaired like any other, which is why the Variant(IPv6, String) read above passes with the branch dictionary-encoded in both formats.

A union whose children all infer to one ClickHouse type is also out of reach: decodeUnion rejects it with INCORRECT_DATA before any requested type is consulted, since the resulting ColumnVariant layout would not match its declared type.

@nihalzp
nihalzp added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit 24c2d3f Sep 8, 2026
175 checks passed
@nihalzp
nihalzp deleted the fix-arrow-null-slot-validation branch September 8, 2026 13:59
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
@nihalzp nihalzp changed the title Fix reading Arrow files that validate the arbitrary bytes of unobservable slots Fix the native Arrow reader's handling of unobservable slots, dictionaries and buffer-less lengths Sep 8, 2026
cursor Bot pushed a commit that referenced this pull request Nov 19, 2026
Backport only the part of #132416 that applies to 26.8: requested types are no longer looked up below an
Arrow union.

26.8 has the same lookup: the children of a union restart the dotted path, so a struct field `s` inside a
union child resolves the requested type of an unrelated header column `s`. On 26.8 a `Nullable` requested
type keeps the null map of a struct, while `decodeUnion` declares its children from the schema, so the
cast of the union read a `ColumnNullable` as a `ColumnTuple`: a `Bad cast` logical error in debug builds,
and garbage values in release builds, also on `INSERT ... FORMAT ArrowStream`. The fix sets
`decoding_below_union` in `decodeUnion` and skips the lookup in `resolveTargetHint` while it is set, as on
master. It also includes `base/scope_guard.h` for `SCOPE_EXIT`, which 26.8 does not include.

The rest of #132416 does not apply to 26.8: it changes the decode-time raw-byte conversion and the
decoding of dictionary values once per field position and requested type, which came with #110531 and
are not on 26.8 (26.8 decodes each dictionary once, without requested types). Its tests are adapted:
- `05829_arrow_ipc_union_unrelated_hint` gets a case with a `Nullable` unrelated column, the shape that
  reaches 26.8. Its other cases pass on 26.8 with or without the fix.
- `05830_arrow_ipc_union_dictionary_unrelated_hint` is kept; it passes on 26.8.
- `05816`, `05828` and `05831` are dropped: they cover the parts that are not on 26.8, and they fail on
  26.8 with or without the fix, because 26.8 does not read those raw-byte subcolumns and converts a
  dictionary-encoded `fixed_size_binary(16)` to `UUID` with a cast.

Co-authored-by: yakov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants