Skip to content

Native reader and writer for the Arrow and ArrowStream formats - #106522

Merged
alexey-milovidov merged 125 commits into
masterfrom
native-arrow-ipc-format
Jul 9, 2026
Merged

alexey-milovidov merged 125 commits into
masterfrom
native-arrow-ipc-format

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

Implement a native ClickHouse reader and writer for the Arrow and ArrowStream formats that does not use the Apache Arrow C++ library. It parses the Arrow IPC metadata (FlatBuffers) directly and decodes/encodes record-batch buffers straight to and from ClickHouse columns, eliminating the extra full materialization into Arrow's array layer (builders, memory pool, codec stack) on each side of the conversion. Parquet and ORC keep using the Apache Arrow library.

The native implementation is now the default, controlled by the new settings input_format_arrow_use_native_reader and output_format_arrow_use_native_writer; setting them to 0 selects the previous Apache-Arrow-library path. It has full type parity with the library path — including Nullable, Array/Tuple/Map, LowCardinality ↔ Arrow dictionary (incl. dictionary-encoded output with deltas), UUID/IPv4/IPv6/big integers/Interval, Variant ↔ Arrow union, Nested flattening / case-insensitive matching, input_format_null_as_default, GeoParquet (WKB/WKT), and LZ4_FRAME / ZSTD body compression — and there is no library fallback.

Motivation: remove excess copies and conversions and make these formats faster. Benchmarked against the Apache Arrow library across numeric / string / nullable / LowCardinality / array data, both formats, and none/lz4_frame/zstd compression: native is faster for reading in every case and for writing in every case except raw fixed-width numeric bulk writes, which are at parity. Output stays byte-compatible — native-written LZ4/ZSTD data is read correctly by the Apache Arrow library and by pyarrow, and native reads the library's output.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Implemented a native reader and writer for the Arrow and ArrowStream formats that does not use the Apache Arrow library, avoiding extra data copies and conversions. It is now the default (settings input_format_arrow_use_native_reader and output_format_arrow_use_native_writer) and is faster for both reading and writing.

Version info

  • Merged into: 26.7.1.695 (included in 26.7 and later)

alexey-milovidov and others added 15 commits June 4, 2026 07:45
First step towards a native ClickHouse reader and writer for the `Arrow` and
`ArrowStream` formats that does not use the Apache Arrow C++ library.

This commit adds only the scaffolding:
- New directory `src/Processors/Formats/Impl/ArrowIPC` with stub classes
  `ArrowIPCBlockInputFormat`, `ArrowIPCBlockOutputFormat`, `ArrowIPCSchemaReader`
  (currently throwing `NOT_IMPLEMENTED`) and `FlatBuffersCommon.h`, which is the
  single place that includes the FlatBuffers-generated Arrow IPC metadata headers.
- A CMake interface target `ch_contrib::arrow_ipc_metadata` exposing those generated
  headers plus the FlatBuffers library, linking `_flatbuffers` and never the Arrow
  runtime. `_flatbuffers` headers are now `SYSTEM` so they do not trip `-Werror`.
- New settings `input_format_arrow_use_native_reader` and
  `output_format_arrow_use_native_writer` (default `false` for now). The format
  registration dispatches to the native or the library implementation based on them;
  the schema-cache key includes the reader choice.

The native code is gated by `USE_ARROW` and decodes/encodes IPC buffers directly
to/from ClickHouse columns; only the FlatBuffers metadata layer is shared with Arrow.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Implements the native ClickHouse reader for the `ArrowStream` format for flat
(non-nested), uncompressed types, selected with `input_format_arrow_use_native_reader`.
No Apache Arrow C++ library is used: the IPC metadata is parsed with the
FlatBuffers-generated headers and record-batch buffers are decoded directly into
ClickHouse columns.

New modules under `src/Processors/Formats/Impl/ArrowIPC`:
- `MessageReader` — encapsulated-message framing (continuation token, little-endian
  metadata length, FlatBuffer `Message`, body) with the same anti-DoS guard on the
  first bytes as the library-based reader.
- `SchemaConverter` — parses the IPC `Schema` FlatBuffer into an Arrow-free type tree
  and maps fields to ClickHouse types (integers, floats, `Bool`, decimals, `Date32`,
  `DateTime`, `DateTime64`/time, `String`/`FixedString`).
- `RecordBatchDecoder` — walks the pre-ordered flattened `nodes`/`buffers`, slicing the
  single message body with bounds checks on every access. Handles the LSB-first
  validity bitmap (inverted relative to the ClickHouse null map), `i32`/`i64` string
  offsets with the trailing-terminator difference, and decimals stored wider in Arrow
  than in ClickHouse (low-bytes-per-row copy).
- `ArrowIPCBlockInputFormat` / `ArrowIPCSchemaReader` — wire the decoder into
  `IInputFormat`/`ISchemaReader`: name matching, `castColumn` to the output header,
  missing-column handling, `need_only_count` (metadata-only), the `eof` keepalive, and
  `schema_inference_make_columns_nullable` parity (0/1/auto) with the library reader.

The native reader produces output identical to the Arrow-library reader on flat types,
verified by the new test `04314_native_arrow_ipc_reader_flat`. The file format, nested
types, dictionaries and body compression are added in later steps.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Extends the native `ArrowStream` reader to nested and dictionary-encoded types:
- `Array`/`LargeList`/`FixedSizeList` -> `Array`, `Struct` -> `Tuple`, `Map` -> `Map`,
  decoded recursively from the flattened nodes/buffers with offset bounds checks and a
  child-size consistency check.
- Dictionary-encoded fields -> `LowCardinality`. A new `DictionaryRegistry` stores the
  values decoded from `DictionaryBatch` messages (replacement and delta); the record-batch
  decoder gathers the indices via `IColumn::index`, combining index-validity nulls with
  null entries inside the dictionary (so both the pyarrow and ClickHouse-writer null
  conventions round-trip). The schema reader infers `LowCardinality(value type)` for
  dictionary columns, matching the Apache Arrow library reader.

Verified identical to the library reader (schema and data) on Array/Tuple/Map/nested-Array
and LowCardinality including LowCardinality(Nullable) by the new test
`04315_native_arrow_ipc_reader_nested`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds support for the `Arrow` (file) format to the native reader. The file format keeps a
footer (schema plus the locations of all dictionary and record batches as `Block`s) at the
end of the file and is read with random access:
- `readArrowFileFooter` (shared by the input format and the schema reader) verifies the
  leading and trailing `ARROW1` magic, reads the footer FlatBuffer, and returns the schema
  plus the dictionary and record-batch block offsets. The input size is obtained via
  `getFileSizeFromReadBuffer` rather than `SEEK_END`, which mmap-backed buffers reject.
- The input format seeks to each block to read record batches on demand (so `need_only_count`
  reads just the batch metadata); all dictionary batches are decoded up front. When the input
  is not seekable it is loaded into memory and wrapped in a `ReadBufferFromMemory`, matching
  the Apache Arrow library's behaviour.

Verified identical to the library reader (schema, data, and count) on a multi-record-batch
file containing a dictionary column, via the new test `04316_native_arrow_ipc_reader_file`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Implements the native ClickHouse writer for the `Arrow` and `ArrowStream` formats, selected
with `output_format_arrow_use_native_writer`. No Apache Arrow C++ library is used: ClickHouse
columns are encoded directly into Arrow IPC record-batch buffers and the FlatBuffers metadata
is built natively.

New modules under `src/Processors/Formats/Impl/ArrowIPC`:
- `MessageWriter` — encapsulated-message framing with the metadata zero-padded so each body
  starts 8-byte aligned, the end-of-stream marker, and raw writes (file magic). Returns each
  message's location so the file writer can record footer `Block`s.
- `RecordBatchEncoder` — walks ClickHouse columns into the flattened FieldNode/Buffer lists and a
  single 8-byte-aligned body: bit-packed validity (1 = valid) and bit-packed `Bool`, `i32` string
  offsets (this `ColumnString` stores no trailing `\0`), decimals sign-extended to Arrow's 16/32-byte
  width, `DateTime64` rescaled to the nearest Arrow time unit, `Date` widened to `date32`, and
  recursion for Array/Tuple/Map. `Const` is materialized; `LowCardinality` is written as its full
  column (matching `output_format_arrow_low_cardinality_as_dictionary=false`).
- `SchemaConverter::buildSchemaMessage` / `buildFooter` build the IPC `Schema` message and the file
  `Footer` FlatBuffers, mirroring the encoder's type choices.
- `ArrowIPCBlockOutputFormat` — writes the schema, one record-batch message per chunk, then the
  end-of-stream marker (stream) or the footer + length + trailing magic (file).

Native-written data reads back identically to data written by the Apache Arrow library writer, for
both formats and a wide type matrix, verified by the new test `04317_native_arrow_ipc_writer`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds per-buffer body compression to the native reader and writer. Arrow IPC compresses each body
buffer independently as an 8-byte little-endian uncompressed length followed by the compressed
bytes (or, when the length is -1, the bytes stored uncompressed); the `RecordBatch` carries a
`BodyCompression{codec, BUFFER}` and the schema advertises the `COMPRESSED_BODY` feature.

- `BufferCompression` wraps the LZ4 frame (`lz4frame.h`) and ZSTD (`zstd.h`) codecs, whose frame
  formats match Arrow's `LZ4_FRAME` and `ZSTD`.
- The reader decompresses all buffers of a compressed batch up front into a private body and then
  decodes as usual; the writer compresses each buffer, falling back to storing it uncompressed
  (prefix -1) when compression does not shrink it, driven by `output_format_arrow_compression_method`.

Verified that LZ4_FRAME and ZSTD round-trip through every writer/reader combination, including
native-write -> library-read and library-write -> native-read, by the new test
`04318_native_arrow_ipc_compression`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Extends the native reader/writer to more ClickHouse types:
- UUID round-trips as the self-describing Arrow extension type: written as fixed_size_binary(16)
  with the two 64-bit halves byte-reversed and an `ARROW:extension:name = arrow.uuid` field
  metadata; the reader recognises that metadata and reverses the swap. Cross-compatible with the
  Apache Arrow library (type and value preserved).
- The writer now supports IPv4 (uint32), IPv6 and big integers (fixed_size_binary 16/32) and
  Interval (Arrow duration for sub-second kinds, int64 otherwise), so those columns no longer throw.
- The reader handles half-float (-> Float32) and Arrow duration (-> Interval).

On schema inference IPv4/IPv6/big integers map to UInt32/FixedString exactly as the Apache Arrow
library reader does. Verified by the new test `04319_native_arrow_ipc_extra_types`.

Variant<->Union, BinaryView/Utf8View reading, GeoParquet metadata and JSON-as-string remain on the
library path for now; the native formats stay opt-in via the settings.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Records `input_format_arrow_use_native_reader` and `output_format_arrow_use_native_writer` in the
settings changes history for the current release.

The settings remain opt-in (default false) for now: the native reader/writer cover the common type
set and are fully cross-compatible with the Apache Arrow library, but a few types (Variant/Union,
BinaryView/Utf8View reading, GeoParquet metadata, JSON-as-string) still require the library path, so
making native the default safely needs either that remaining coverage or a transparent library
fallback. Until then the formats are selected explicitly via the settings.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rectness fixes (P8)

Substantially extends the native reader/writer's coverage and correctness, found by running it
against the full existing Arrow test suite. The settings stay opt-in (default false).

Reader:
- BinaryView/Utf8View read into String (handles `variadicBufferCounts` and inline vs out-of-line views).
- Type-hint conversions when the requested column type differs from the natural Arrow type: big integers
  and UUID reinterpreted from fixed_size_binary (castColumn cannot), and `input_format_null_as_default`
  honoured when a nullable Arrow column is read into a non-nullable ClickHouse column (looking through
  LowCardinality, which can hold nulls without being Nullable itself).
- Do not wrap Array/Map/Tuple in Nullable (illegal in ClickHouse) — drop the outer validity, matching
  the library reader; empty Tuple() and zero-length / placeholder-offset (-1) buffers are handled.
- The Arrow file format over a non-seekable input (e.g. INSERT from a pipe) is loaded into memory; the
  size is taken from `tryGetFileSizeFromReadBuffer` rather than a `SEEK_END` that pipes reject.
- Duplicate column names are rejected with DUPLICATE_COLUMN.

Writer:
- Honour `output_format_arrow_date_as_uint16`.
- Fall back to the Apache Arrow library writer (via the format registration) for types the native
  encoder does not support (e.g. Variant) and for dictionary-encoded LowCardinality output
  (`output_format_arrow_low_cardinality_as_dictionary`).

With the settings enabled, the native reader/writer now produce results identical to the Apache Arrow
library across the common type matrix; the new 04314-04319 tests cover this. Making native the default
still needs Variant<->Union, GeoParquet metadata, nested null_as_default and a few dictionary edge
cases, so the formats remain selectable via the settings for now.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…_size_binary (P9)

When reading a fixed_size_binary(16) column into a UUID column via a type hint (e.g. a pyarrow
file that stores a UUID as plain binary(16) without the arrow.uuid extension), the value must be
reinterpreted with the same 64-bit-half reversal the Apache Arrow library import uses. The
reinterpret branch was being shadowed by the input_format_null_as_default branch (the field is
nullable), so it fell through to a plain castColumn that produced byte-swapped garbage. Reorder so
the UUID and big-integer reinterpret branches run before the null_as_default handling.

Verified by 04042_arrow_uuid_import and 04039_arrow_uuid passing under the native reader.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Makes `input_format_arrow_use_native_reader` and `output_format_arrow_use_native_writer` default to
true, so the native reader/writer handle the `Arrow` and `ArrowStream` formats by default, and add a
transparent fallback to the Apache Arrow library reader for the cases the native reader does not
reproduce faithfully, so existing behaviour is preserved everywhere.

`ArrowIPCBlockInputFormat` (and `ArrowIPCSchemaReader`) delegate to `ArrowBlockInputFormat` /
`ArrowSchemaReader` when, after parsing the schema, they detect:
- GeoParquet geometry columns (schema-level `geo` metadata),
- union columns (Variant),
- `import_nested` Nested flattening (a dotted header column backed by a List/Struct/Map field, which
  also covers case-insensitive nested matching),
- a nullable Arrow column read into a non-nullable ClickHouse column under
  `input_format_null_as_default` (the library applies the column's DEFAULT expression).

The stream is rewound for the fallback with a `PeekableReadBuffer` (checkpoint around the schema
read); the file format re-seeks to the start. Also: reject non-unique LowCardinality dictionaries
with INCORRECT_DATA, matching the library.

With native as the default, the full existing Arrow stateless test suite passes (the only remaining
failures are pre-existing, environment-specific issues unrelated to this change: a parquet test
timeout, a `user_files` permission error, and a wasm test).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e library fallback (P11)

The native `Arrow`/`ArrowStream` reader and writer previously delegated to the Apache
Arrow C++ library for a few cases (`ArrowBlockInputFormat`/`ArrowSchemaReader` and the
output format). Implement all of those natively and remove the fallback entirely:

- Variant <-> Union: decode an Arrow dense/sparse union into `ColumnVariant` and encode
  `ColumnVariant` as an Arrow dense union (a types and an offsets buffer plus a trailing
  single-element `null` child for NULL rows; no validity buffer). `fieldToCHType` and the
  schema writer now map `Union` <-> `Variant`. The library never read unions, so this also
  adds union reading. `RecordBatchEncoder::canNativelyEncode` accepts `Variant`.
- GeoParquet: parse the schema-level `geo` metadata and decode WKB/WKT binary columns into
  the geo types via `parseGeoMetadataEncoding` / `parseWKBFormat` / `appendObjectToGeoColumn`,
  gated by `input_format_parquet_allow_geoparquet_parser`. Corrupted offsets are rejected with
  `INCORRECT_DATA` by the existing string-buffer bounds checks.
- `import_nested` and case-insensitive matching: mirror the library's column-matching driver
  in `buildChunk` using `Nested::extractTableName` / `Nested::collect` /
  `NestedColumnExtractHelper`, reshaping the decoded `Array(Tuple(...))` to the collected
  `Nested` type so it can be flattened into dotted subcolumns.
- `input_format_null_as_default`: call the shared `insertNullAsDefaultIfNeeded` (handles
  nested narrowing and records `BlockMissingValues` so the engine applies column DEFAULTs).
- Dictionary-encoded output (`output_format_arrow_low_cardinality_as_dictionary`): accumulate
  one dictionary per id across record batches (extending it via Arrow dictionary deltas),
  write `DictionaryBatch` messages, record dictionary blocks in the file footer, and write the
  record batch with the integer index column. The index type honours
  `output_format_arrow_use_signed_indexes_for_dictionary` /
  `output_format_arrow_use_64_bit_indexes_for_dictionary`.

The only remaining use of the library writer is for column types the native encoder does not
support at all (e.g. `Dynamic`/`JSON`), which is a capability guard rather than a fallback for
the features above. Removed `needsLibraryFallback`, the schema-reader fallback, the
`PeekableReadBuffer`/`fallback` members, and the `friend class ArrowIPCBlockInputFormat`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…library (P12)

Benchmarking the native reader/writer against the Apache Arrow library revealed several cases
where native was slower; fix them so native is faster (or at parity for raw bulk writes) everywhere.

- Dictionary write (`output_format_arrow_low_cardinality_as_dictionary`): deduplicate at the
  dictionary level (a handful of values) via the LowCardinality column's existing dictionary, instead
  of materializing the full column and hashing every row. ~12x faster for that case (now faster than
  the library).
- Dictionary read: build the `LowCardinality` column directly from (keys, indexes) via
  `insertRangeFromDictionaryEncodedColumn` — no full-column gather and no re-deduplication. ~5x faster
  (now faster than the library).
- Body (de)compression: like the Apache Arrow writer (whose codec is multi-threaded), compress and
  decompress the record-batch buffers in parallel across the shared format thread pool, and reuse one
  codec context across all buffers (LZ4 frame via `LZ4F_compressBegin/Update/End` with a 4 MB block
  size, ZSTD via a reused `ZSTD_CCtx`/`ZSTD_DCtx`) instead of allocating a context per buffer. Turns a
  ~4x compression slowdown into a win for everything except raw numeric bulk write (at parity).
- Fixed-width encoding: append the column's contiguous data straight into the body, removing a
  redundant per-buffer copy.

Output remains byte-compatible: native-written LZ4/ZSTD is read correctly by the Apache Arrow library
and by pyarrow, and native reads the library's output (cross-checked across the full type matrix and
both formats).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Resolve the conflict in `ArrowBlockOutputFormat.cpp`: keep the native
`canNativelyEncodeBlock` capability check alongside master's added forward
declaration of `registerOutputFormatArrow`. Sync the `NuRaft` and
`mariadb-connector-c` submodules bumped on master.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…elines-init-variables

Master's `.clang-tidy` enables `cppcoreguidelines-init-variables` (warnings as errors). Initialize
the local scalars that are subsequently filled via `memcpy`/`readStrict` in the native Arrow IPC
reader/writer so the `ClangTidy` CI check passes; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5e5bbdc]

Summary: ✅


AI Review

Summary

This PR replaces the Apache Arrow C++ conversion path for Arrow and ArrowStream with a native IPC reader/writer, makes that path the default behind the new format settings, and adds broad coverage for schema inference, dictionaries, compression, Variant, raw-byte hints, and malformed-input handling. After reviewing the current code, prior discussion, and the remaining open thread, I did not find an unresolved correctness, compatibility, or evidence gap.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels Jun 5, 2026
CI report: #106522

- Style check: use Allman braces for the `make_int` lambda in `SchemaConverter.cpp`; remove the now-unused
  `NOT_IMPLEMENTED` `ErrorCodes` declaration from `ArrowIPCBlockInputFormat.cpp` (left over after removing
  the library fallback).
- ClangTidy (`cppcoreguidelines-init-variables`): initialize `make_nullable` in `ArrowIPCSchemaReader.cpp`.
- Fast test: tag the new `04314`-`04319` Arrow IPC tests with `# Tags: no-fasttest`, matching the existing
  Arrow tests (the Fast test build has no Arrow support, so the formats are unavailable there).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ase value

A delta dictionary batch appends to the existing dictionary, but it was only checked
for internal duplicate values per incoming batch. A unique base dictionary plus a
unique delta can still produce a duplicate merged value (e.g. base `['a', 'b']`
followed by a delta `['b']`), which violates the `LowCardinality` dictionary
uniqueness invariant the non-delta path enforces and differs from the Apache Arrow
library reader.

Both dictionary-batch sites (the file reader and the stream reader) now re-validate the
merged dictionary with `checkDictionaryUnique` after a delta is applied, so a delta that
repeats a base value is rejected with the same `Arrow dictionary contains duplicate
values` error as the non-delta path.

Addresses the second Major of the AI review on
#106522.

New test `04497_native_arrow_ipc_delta_dictionary_duplicate`: a base dictionary
`['AAA', 'BBB']` followed by a delta whose only value is patched from `'CCC'` to `'AAA'`
(the test asserts a delta — not a replacement — was emitted) makes the merged dictionary
repeat `'AAA'`; the read is now rejected.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed f27b935ab0d..5d9447cb8ce — merged the latest master and addressed all three Majors of the AI-review Request changes verdict, each with targeted regression coverage.

Merge

The CONFLICTING state was stale (as before): the master merge applied with no conflicts and touched no ArrowIPC code.

Major 1 — record-batch layout exactness on the non-pruned path (RecordBatchDecoder.cpp) — da41ef055a8

The exact FieldNode/buffer-consumption check only ran when columns were pruned. It now runs unconditionally and also covers the variadic buffer counts (matching validateBatchLayout), so a fully-decoded batch declaring surplus/interposed field nodes or buffers is rejected instead of reading a column from an injected buffer. The dead pruned flag is removed. Test 04498_native_arrow_ipc_surplus_buffers.

Major 2 — delta dictionary that duplicates a base value (ArrowIPCBlockInputFormat.cpp) — 5d9447cb8ce

Both dictionary-batch sites now re-validate the merged dictionary with checkDictionaryUnique after a delta is applied, rejecting a delta that repeats a base value with the same Arrow dictionary contains duplicate values error as the non-delta path. Test 04497_native_arrow_ipc_delta_dictionary_duplicate (asserts a delta — not a replacement — was emitted, so it exercises the merged-dictionary check).

Major 3 — nullable FixedString variable-width null payload (RecordBatchEncoder.cpp) — ffe502d964c

With output_format_arrow_fixed_string_as_fixed_byte_array = 0, the FixedString branch now honors the null map like the String/binary paths fixed in 6ef80636cb2: a NULL row emits a zero-length slot, so its nested bytes never reach the IPC body. The fixed-size-binary path (= 1) is unchanged on purpose — that Arrow type stores N bytes per row including NULLs, exactly as the library writer. Test 04496_native_arrow_ipc_fixed_string_null_payload.

Validation: the full native Arrow IPC suite (31 tests) and the broader Arrow reader / OOB-hardening tests pass locally on the rebuilt binary, confirming the stricter layout check produces no false positives on conformant files written by ClickHouse or pyarrow. The three inline threads are resolved.

The two remaining unresolved threads are the Variant-as-dictionary-boundary design question, which is left for your maintainer decision as noted above.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage (head 5d9447cb8ce)

Human-approved by @Algunenano, and the latest AI Review verdict on this head is ✅ Approve with all inline review threads resolved. mergeStateStatus is BLOCKED only because Mergeable Check is red from the flaky/unrelated failures below. This change touches only the native Arrow/ArrowStream code and src/CMakeLists.txt — no distributed, protocol, or SQL-execution code — so none of these can be caused by it.

  • 03794_global_in_nullable_type_mismatch (Stateless amd_asan_ubsan) — UNEXPECTED_PACKET_FROM_SERVER desync (expected TablesStatusResponse, got ProfileInfo) inside getTablesStatus on a hedged remote() connection. A distributed connection-establishment flake: 3 failures in the last 30 days, never on master (PR=0); the other two were on the unrelated More settings to randomize #106734. Re-ran the job (in progress).
  • Hung check failed, possible deadlock found (Stress arm_msan) — chronic flake Hung check failed, possible deadlock found #107941; the stack trace contains no Arrow/RecordBatch/ArrowIPC frames. Non-required.
  • Performance Comparison (amd 3/6, arm 6/6) — the flagged queries (re2_regex_caching, decimal_aggregates, file_table_function, number_formatting_formats) are slower/unstable measurement noise and none use the Arrow format. The native-Arrow perf tests improved substantially on this run: formats_columns_sampling −83%, arrow_format −57%/−55%, formats_columns_nullable −78%/−46%.

CH Inc sync is PENDING (private #59877), not failed.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage update (head 5d9447cb8ce)

State since the 06:32 triage:

  • CH Inc sync → SUCCESS (was PENDING); Style check → SUCCESS.

  • 03794_global_in_nullable_type_mismatch re-ran and passed — gone from the current failures.

  • mergeStateStatus is BLOCKED only because Mergeable Check/PR aggregate three flaky/unrelated check-runs, none of which is reachable from a native-Arrow-only change (this PR touches only the ArrowIPC code and src/CMakeLists.txt — no mutation, distributed, or SQL-execution code):

    • Upgrade check (amd_release) — Error message in clickhouse-server.log (new since the last triage, logged at 10:28). The message is a background-mutation retry logging FUNCTION_THROW_IF_VALUE_IS_NON_ZERO for if(1, _CAST(plus(x, throwIf(1)), 'UInt64'), x) in MutatePlainMergeTreeTask — a throwIf mutation from an unrelated stateless test, not Arrow. It is a chronic master-wide upgrade-check log-hygiene flake: over the last 90 days it fires on unrelated PRs every day, incl. 8 distinct unrelated PRs on 2026-07-01 and 19 on 2026-06-30 (CIDB: test_name = 'Error message in clickhouse-server.log …', test_context_raw LIKE '%THROW_IF%', base_ref = 'master').
    • Performance Comparison (amd 3/6, arm 6/6) — the slower/unstable queries (hash_table_sizes_stats, round_methods, array_distance, insert_select_squashing_dynamic, file_table_function) are on GROUP BY/arithmetic/file() paths that never touch the Arrow format and pattern as binary-layout / measurement noise. The native-Arrow perf tests improved on this run: arrow_format −62%, formats_columns_sampling −83%, formats_columns_nullable −45%.

Human-approved by @Algunenano, AI Review ✅ Approve, all inline threads resolved. No code change or master re-merge needed (merge-base is <1 day old and the branch is MERGEABLE; the reds are flakes, not staleness).

@groeneai — there is no open tracking issue for the Upgrade check throwIf Error message in clickhouse-server.log flake, yet it recurs across many unrelated PRs daily and is independent of this change; could you open/track one?

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov This upgrade-check throwIf flake is already owned by an approved fix in flight: #108651 ("Match benign mutation parse errors by class in the Upgrade check"), which you approved on 2026-06-28.

#108651 replaces the old per-literal Cannot parse string ... allow-list in tests/docker_scripts/upgrade_runner.sh with an error-CLASS regex on the background-mutation executors, and it folds in exactly this signature:

(MutatePlainMergeTreeTask|MutateFromLogEntryTask|MergeTreeBackgroundExecutor).*(Cannot parse string .* as .*CANNOT_PARSE_TEXT|FUNCTION_THROW_IF_VALUE_IS_NON_ZERO)

So the FUNCTION_THROW_IF_VALUE_IS_NON_ZERO line from if(1, _CAST(plus(x, throwIf(1)), 'UInt64'), x) on MutatePlainMergeTreeTask is filtered by class, independent of the fuzzer-generated literal/type. It is the #39174 family (intentionally-broken mutations replay after the upgrade restart); that umbrella issue is closed. The current source is the stateless test 04341_broken_mutation_part_log_flush (t_failed_mutation_part_log), whose deliberate ALTER ... UPDATE x = x + throwIf(1) was added in 189f8023c72 (2026-06-19). It is independent of the native Arrow reader/writer and reproduces on master, so it cannot be caused by this PR.

On a tracking issue: we chose the allow-list fix (#108651) over a standalone issue. Opening a GitHub issue on our side needs human approval, so I have not filed one. If you would prefer a tracked issue in addition to the fix, say so and I will open one. #108651 is approved and MERGEABLE.

The new `native_arrow_ipc` performance test failed the `Performance Comparison`
job (`amd_release` 3/6 and `arm_release` 6/6), which made `Mergeable Check` and
the overall `PR` check red. Two independent problems, both self-contained in the
test:

1. The write benchmark used `SELECT * FROM na_src FORMAT Arrow`, which does not
   measure Arrow encoding at all. The perf runner drives queries over the native
   TCP protocol (`clickhouse_driver`), which ignores the query's `FORMAT` clause
   and sends `Native` blocks back to the client, so the query really measured
   client-side row deserialization of 20M rows (~58s) instead of the encoder.
   That blew past the 15s `max_execution_time` of a measured run
   (`Code: 159 Timeout exceeded`) and aborted the whole test. Verified with
   `clickhouse_driver`: `FORMAT Arrow` (2.71s) is identical to a plain
   `SELECT *` (2.69s) and unlike `FORMAT Null` (0.018s). The encode is now
   measured by `INSERT INTO na_arrow_out SELECT * FROM na_src` where
   `na_arrow_out` is `File(Arrow, '/dev/null')` — the encoder runs server-side
   and the output is discarded — the same idiom used by `select_format.xml`.

2. Every query pinned `input_format_arrow_use_native_reader` /
   `output_format_arrow_use_native_writer`, which are added by this pull request
   and therefore do not exist on the compared master server. The prewarm on that
   server failed with `Code: 115 ... is neither a builtin setting`, and any
   non-empty per-test `*-err.log` is folded into `run-errors.tsv`, which
   `report.py` counts unconditionally as an error and fails the job. The queries
   now run on the default path (native on this branch, the Apache Arrow library
   on master), so nothing errors on the reference server and the comparison
   directly measures the speedup of this change.

Validated end to end through `tests/performance/scripts/perf.py`: exit code 0,
empty `err.log`, write ~1.70s and read ~1.10s per run for 20M rows on the
library path, both far under the limit (native is faster still).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106522&sha=5d9447cb8cea70d101d8e3f1683402b07ec84440&name_0=PR
PR: #106522

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 2, 2026 15:16
Two recently-added stateless tests exercise Arrow behavior that the
Apache-Arrow-library path gained on `master` but the native reader/writer
(now the default) did not yet implement, so they failed once the native
path became the default after the latest `master` merge:

- `04209_arrow_time_import_export` (issue #104038): mapping between
  ClickHouse `Time`/`Time64` and Arrow `time32`/`time64`.
- `03926_arrow_fixed_offset_timezone` (issue #73261): reading Arrow
  timestamps whose timezone is a fixed numeric UTC offset (`+05:30`,
  `-08:00`) or the non-IANA `fixed` marker.

`Time`/`Time64` support (writer and reader), mirroring the library path:

- Writer schema (`SchemaConverter::buildField`): `Time` maps to Arrow
  `time32[s]`; `Time64(scale)` maps to `time32` (SECOND/MILLISECOND) for
  scale <= 3, else `time64` (MICROSECOND/NANOSECOND).
- Writer values (`RecordBatchEncoder::encodeValues`): `Time` writes the
  Int32 seconds directly; `Time64` rescales the value up to the Arrow
  unit's scale and range-checks the 32-bit path, raising `DECIMAL_OVERFLOW`
  on overflow, matching `fillArrowArrayWithTime64ColumnData`.
- Reader type (`SchemaConverter::fieldToCHType`): Arrow `time32`/`time64`
  maps to `Time64(unit * 3)` (previously `DateTime64`, which is wrong --
  `Time` carries no timezone, so a non-UTC session timezone must not shift
  the stored value on import).
- Reader values (`RecordBatchDecoder`): a `Time` field now fills a
  `ColumnDecimal<Time64>` (`time32` = 4-byte, `time64` = 8-byte).

Fixed-offset timezone support (reader): `fieldToCHType` normalizes an
Arrow timestamp's timezone with `normalizeArrowTimezone` before building
`DataTypeDateTime64` -- a full `[+|-]HH:MM[:SS]` offset becomes cctz's
canonical `Fixed/UTC+HH:MM:SS`, `fixed` becomes `UTC`, and anything else
is passed through unchanged so a genuinely-malformed zone still raises
`Cannot load time zone`. This mirrors the helper of the same name in the
library reader (`ArrowColumnToCHColumn.cpp`).

Both tests pass locally with the native reader/writer as the default, and
the full native Arrow IPC suite (32 tests) still passes.

Related: #104038
Related: #73261

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Algunenano and others added 2 commits July 7, 2026 13:18
…ormat

# Conflicts:
#	src/Processors/Formats/Impl/ArrowBlockInputFormat.cpp
…IPC reader

The native reader only reinterpreted a top-level fixed_size_binary column as
UUID / big integer. It now recognises the same raw-byte conversions the Apache
Arrow library reader does, closing two gaps:

- Variable-width `Binary` (not just `fixed_size_binary`) is reinterpreted as
  `IPv6` / `Int128` / `UInt128` / `Int256` / `UInt256`, matching
  `readIPv6ColumnFromBinaryData` / `readColumnWithBigNumberFromBinaryData`: null
  rows are skipped in the width check, and if any non-null row is not exactly the
  target width the column is left as `String` for the cast (rather than failing).

- The conversions are applied recursively through `Nullable`, `Array`, `Tuple`
  and `Map`, so nested shapes such as `Array(Int128)` (from
  `list<fixed_size_binary[16]>`) and `Tuple(ip IPv6)` (from `struct<ip: binary>`)
  are reinterpreted instead of being decoded as `FixedString`/`String` children
  and text-parsed by the cast.

`IPv6` is also handled from `fixed_size_binary(16)`, which the ClickHouse writer
emits, so that round-trip no longer relies on text parsing.

Also adapts the geo call site to the merged `parseWKTFormat` signature
(`precise_float_parsing`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 7, 2026, 12:25 PM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

This is real!

Screenshot_20260707_151629

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The master merge in this branch (62520f0a819) pulled in the new master test 04493_nullable_tuple_schema_inference_arrow_formats (from #109185), and it now fails deterministically on the native Arrow/ArrowStream reader across every stateless shard (it appeared after the 12:41 approval, so flagging in case it isn't on your radar yet):

  • DESCRIBE of an optional (nullable) Arrow struct returns Nullable(Tuple(...)), but with schema_inference_allow_nullable_tuple_type off (the default) it must be a plain Tuple(...) — otherwise CREATE TABLE from the inferred schema is rejected — and SELECT * returns \N where the struct null map should be propagated into the tuple elements.

Root cause: in the native reader, fieldToCHType (src/Processors/Formats/Impl/ArrowIPC/SchemaConverter.cpp:1158) wraps any nullable field in Nullable unconditionally, so a nullable Struct becomes Nullable(Tuple). #109185 changed the library path (src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp:2440, commit 21f96114f74) to gate struct-into-Nullable behind allow_nullable_struct = schema_inference_allow_nullable_tuple_type || (type_hint && type_hint->isNullable()). The native fieldToCHType needs the same gate for the Struct case, plus the matching null-map-into-elements handling in the decode path (RecordBatchDecoder) so that a nullable struct read as a plain Tuple populates the elements instead of NULLing the whole row.

I did not push anything — leaving the fix to you since it touches the decode path you are iterating on. The new raw-byte test 04419 passes.

…ive Arrow IPC reader

Schema inference and decoding of a nullable Arrow `Struct` wrapped it in
`Nullable(Tuple(...))` unconditionally, so with the default settings `DESCRIBE`
returned a type that `CREATE TABLE` rejects and `SELECT *` produced `NULL` for
null-struct rows.

Wrap a `Struct` (`Tuple`) in `Nullable` only when
`allow_experimental_nullable_tuple_type` is enabled (via
`schema_inference_allow_nullable_tuple_type`), matching the Apache Arrow library
reader's `allow_nullable_struct` gate. Otherwise the struct is read as a plain
`Tuple` with the struct-level null map dropped (its element values are kept), as
it worked before `Nullable(Tuple)` was supported. `fieldToCHType` and
`decodeField` apply the same gate so the inferred type and the decoded column
stay consistent.

Fixes 04493_nullable_tuple_schema_inference_arrow_formats on the native reader.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

Confirmed the two-part root cause and validated the fix in ed9e76b locally (debug build).

Root cause, as you described:

  1. SchemaConverter.cpp fieldToCHType wrapped any nullable field in Nullable unconditionally, so a nullable Arrow Struct became Nullable(Tuple). With allow_experimental_nullable_tuple_type off (the default), DESCRIBE then returns a type CREATE TABLE rejects.
  2. RecordBatchDecoder propagated the struct null map onto the whole tuple, so SELECT * produced \N for null-struct rows.

ed9e76b gates both the schema (!isTuple() || schema_inference_allow_nullable_tuple_type) and the decode path (struct_not_allowed_nullable) on the same setting, matching the library reader's allow_nullable_struct. So with the gate off the struct is read as a plain Tuple with the struct-level null map dropped (element values kept), and with it on Nullable(Tuple) still works.

Local validation (both directions):

  • 04493 FAILS on the parent commit (native reader infers Nullable(Tuple), SELECT * shows \N, CREATE TABLE rejected with ILLEGAL_COLUMN 44).
  • 04493 PASSES with ed9e76b; 04419_native_arrow_ipc_raw_byte_hints still passes.

Session id: cron:clickhouse-worker-slot-3:20260707-150700

Algunenano and others added 2 commits July 8, 2026 12:41
…ve Arrow IPC reader

The struct-into-Nullable gate only checked `allow_experimental_nullable_tuple_type`,
but the library reader also enables `Nullable(Tuple(...))` when the requested target
type is already nullable. So reading Arrow data with the setting off into an existing
`Nullable(Tuple)` column (or nested `Array(Nullable(Tuple))`) dropped the struct-level
null map and decoded the child payload as a real value row instead of `NULL`.

`decodeField` now wraps a struct in Nullable when the setting is on OR the effective
target hint at this field is nullable (matching the library's `allow_nullable_struct`),
resolving the hint via `resolveTargetHint` so both top-level and nested fields honor it.

`decodeColumns` reconciles the reported type with the decoded column via
`matchColumnNullability`, so the column/type pair stays consistent when `decodeField`
wraps a struct that `fieldToCHType` (setting-only) left as a plain Tuple.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.80% -0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 77.90% -0.10%

Changed lines: Changed C/C++ lines covered: 2859/3219 (88.82%) · Uncovered code

Full report · Diff report

This branch was successfully deployed

1 active deployment
staging - docs — 5e5bbdc6 Deployed Jul 8, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants