Repository navigation
Fix the native Arrow reader's handling of unobservable slots, dictionaries and buffer-less lengths - #110531
Conversation
|
Workflow [PR], commit [0b89d2f] Summary: ✅
AI ReviewSummaryThis 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 Findings
Tests
Final VerdictLLVM Coverage ReportMeasured on commit 0b89d2f.
Changed lines: Changed C/C++ lines covered: 1372/1458 (94.10%) · Uncovered code |
…r view and JSON decoders
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 592/651 (90.94%) · Uncovered code |
|
Was it fixed by migrating to the native arrow reader? |
|
No — I checked against a master binary from today ( 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 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');Running the crafted What the removal does obsolete is the I am taking over the branch: merging |
…-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.
c7d4640 to
146a5ca
Compare
| 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, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>asVariant(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 aDate32element takes only its own alternative. Substituting it after the decode would make a uniondate32read reject a day number the flat column path returns verbatim, which05060_native_arrow_ipc_dictionary_date32_numericpins.- The union arm of
collectDictionaryUsesneeds 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 theVariant(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.
Arrow files that validate the arbitrary bytes of unobservable slotsArrow reader's handling of unobservable slots, dictionaries and buffer-less lengths
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]>
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
ArrowIPC reader ran value-level validation — theDate32range check, dictionary index bounds,BinaryViewview checks, the raw-byte width sniff forIPv6and 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 plainTupledoes.ClickHouse produces such files itself:
Date32arithmetic does not clamp the stored day number andnullIfkeeps 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.The same failure occurs one level deeper with a nullable struct read as
Nullable(Tuple)(withallow_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_binaryleaves the ClickHouse writer uses forUUID,IPv6and the 128/256-bit integers, and the self-describing Arrowuuidextension 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: aLowCardinality(Date32)holding an out-of-range day number could not be read under a numeric target, andLowCardinalityofInt128,UInt128,Int256orUInt256came back asFixedStringdictionaries that the cast text-parsed and rejected.A
null-typed child carries no buffers, so nothing but its parent bounds its declaredFieldNodelength. 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
Enumdefaults, and preserve columnDEFAULTexpression 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 plainTuple, 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 inArrowfiles. 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
Arrowformats in Remove the Apache Arrow library reader and writer for the Arrow formats #111996, so those changes are gone andinput_format_arrow_use_native_readerno longer selects anything.ArrowColumnToCHColumnstill validates the bytes of null slots the same way, but it is now reachable only throughArrowFlightand DeltaLake, so that is left for a separate change with its own coverage.Reading a nullable struct as a plain
Tupledrops 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, showsNULLs 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`froms 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix reading
ArrowandArrowStreamfiles 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 inArrowfiles. 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]