Skip to content

Fix Arrow export of JSON, Dynamic, QBit and AggregateFunction - #115250

Merged
yakov-olkhovskiy merged 50 commits into
masterfrom
cursor/fix-arrow-unsupported-types-fallback-5dc0
Sep 17, 2026
Merged

yakov-olkhovskiy merged 50 commits into
masterfrom
cursor/fix-arrow-unsupported-types-fallback-5dc0

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Closes: #115023
Caused by: #91170

The output_format_arrow_unsupported_types_as_binary fallback wrote a column with no first-class Arrow mapping by calling IColumn::getDataAt per row. That method exposes a column's contiguous in-memory bytes, which most of the types reaching the fallback do not have:

  • ColumnObject (JSON), ColumnVariant (hence ColumnDynamic) and ColumnQBit throw Method getDataAt is not supported, so SELECT ... FORMAT Arrow failed on them — after the schema message had already been written, leaving the client with a truncated stream;
  • ColumnAggregateFunction::getDataAt returns the AggregateDataPtr itself, so exporting an aggregate state silently wrote raw heap addresses instead of the state, both corrupting the data and disclosing server addresses.

Before the fallback existed these types were rejected with a clear UNKNOWN_TYPE, so both are regressions introduced together with the setting:

-- 26.4, before #91170
SELECT '{"a":1}'::JSON FORMAT Arrow;
-- Code: 50. The type 'JSON' of a column 'j' is not supported for conversion into Arrow data format. (UNKNOWN_TYPE)
SELECT sumState(number) FROM numbers(3) FORMAT Arrow;
-- Code: 50. The type 'AggregateFunction(sum, UInt64)' ... (UNKNOWN_TYPE)

-- 26.5 .. 26.8
SELECT '{"a":1}'::JSON FORMAT Arrow;
-- Code: 48. Method getDataAt is not supported for Object(max_dynamic_paths=1024, max_dynamic_types=32). (NOT_IMPLEMENTED)
SELECT sumState(number) FROM numbers(3) FORMAT Arrow;
-- succeeds, writes 00D0A9C9D37F0000

The fallback now serializes each value through ISerialization, whose serializeText/serializeBinary are pure virtual and therefore defined for every type, so the "do not fail a SELECT *" property that motivated the setting holds by construction instead of depending on an unrelated method's implementation status.

output_format_arrow_unsupported_types (throw / text / binary) replaces the boolean, adding a text mode that writes what CAST(col AS String) would produce — useful for the BI clients that drive SELECT * over Arrow Flight SQL, and the workaround users had to apply by hand for JSON. Its default, binary, is the previous behavior, and its SettingsChangesHistory entry has identical previous and new values so compatibility never marks it changed. The boolean keeps working with full effect (0 means throw, 1 means binary) and is only consulted while the new setting is left at its default, so an explicit mode wins whichever order the two are set in.

The Arrow type states the encoding

An opaque column is tagged with the clickhouse.opaque Arrow extension name and the original ClickHouse type name in ARROW:extension:metadata, so a consumer can tell it apart from a genuine string or binary column. Per the Arrow extension-type convention a reader that does not know the extension name ignores the metadata and sees the plain storage type, so no existing consumer changes behavior. Nested children are tagged on their own field, including an Array(JSON) element, a Tuple member, a Variant alternative, and both the key and the value of a Map(JSON, ...).

Alongside the name, the Arrow type says which of the two encodings the payload is: Utf8 is the text form and Binary is serializeBinary. output_format_arrow_string_as_string deliberately does not apply to these columns — it governs only real String and FixedString ones, as its description says — because letting it move an opaque column would park a text payload in a Binary column and leave a reader unable to tell the two apart.

That is what lets both readers recover the original type. They used to turn such a column into a String and leave the caller to CAST it, which is the text parser, so only the text form ever survived: with binary — the default — JSON and QBit failed to parse, and a Dynamic came back silently wrong, holding the encoding's own type tag and length prefix inside its value (42::Dynamic wrote 3432 and read back as 15023432, still reporting String and still printing 42, because the two extra bytes are not printable). Each reader now checks for a Binary column tagged with the type being asked for, and deserializes it with deserializeBinary. Everything else takes the route it took before — an untagged column, a tag naming a different type, or a read that asks for String and gets the raw bytes.

Both readers walk the schema fields alongside the requested type, so a leaf reads the tag on the field that owns it rather than one belonging to an enclosing container: a Nullable root, an Array element, a Tuple member and a Map value all recover their type. In the native reader this is the post-decode rewrite that already descends through those shapes, and in the Apache-Arrow-library one the container branches pass each child's own arrow::Field down. A row whose bytes Arrow leaves undefined, because it is null at the leaf or at any enclosing level, decodes as the type's default instead of being fed to deserializeBinary.

An alternative of a Variant is the one shape that does not read back, and the setting description says so. The Arrow union its alternatives form is decoded without consulting the tags, so such a Variant fails on read — identically in text and in binary, and loudly rather than silently. It is not a regression, since before this change the write side could not produce such a file at all: the getDataAt fallback threw on the union's child. Closing it means threading the requested alternatives through the native decoder's decodeUnion and implementing union decoding in the Apache-Arrow-library reader, which has none today, so it belongs in its own change rather than here.

Text and UTF-8

An AggregateFunction column stays an Arrow Binary column even in text mode: its serializeText writes the raw aggregate state, which is not valid UTF-8, and an Arrow Utf8 column must hold valid UTF-8. The schema is written before any data, so this cannot be decided per value.

For the same reason, a value written into a Utf8 column has each invalid UTF-8 sequence replaced by U+FFFD. Only a payload that is already not valid text changes — a Dynamic holding a String of arbitrary bytes, for example. A JSON column cannot reach this at all: its parser rejects invalid UTF-8 on every input path, so CAST(map('k', unhex('FF')), 'JSON') and the equivalent JSONEachRow insert both fail with INCORRECT_DATA. Real String and FixedString columns are untouched and keep writing raw bytes into Utf8 exactly as before — this affects only the types whose representation the setting invents, which today either throw or emit heap addresses.

The substitution goes through writeValidUTF8, which is why src/Functions/toValidUTF8.cpp appears in the diff. WriteBufferValidUTF8 is a streaming filter and stages into 4 KiB of its own memory so that a multi-byte sequence split across two writes can be carried to the next one; a caller holding the whole value has no such sequence, so that allocation was pure overhead — one per value, to replace a byte or two. toValidUTF8 already contained a one-shot form of the same algorithm that allocates nothing, so it moved to src/IO/writeValidUTF8.{h,cpp} and both use it. Writing 5M invalid one-byte values through FORMAT ArrowStream, against a 0.250 s baseline where every value is valid: 0.770 s with the 4 KiB buffer, 0.701 s sized to the value, 0.343 s with no buffer at all.

One consequence is worth stating explicitly: an aggregate state held in a Dynamic is lossy in text mode. The carve-out above reads the column's declared type, and Dynamic says nothing about what its rows hold, so the state cannot be given a Binary column of its own. binary mode keeps it whole, and a Variant is unaffected because it lists its alternatives, so an AggregateFunction among them gets its own Binary child.

Both writers

The native Arrow IPC writer behind FORMAT Arrow/ArrowStream and the Apache-Arrow-library one behind Arrow Flight SQL both make the accept/reject decision in the schema converter, before the schema message is written, so a rejected type can no longer abort a stream whose schema the reader has already accepted. Both serialize the values with the query's own FormatSettings, so a setting the serialization depends on (output_format_binary_write_json_as_string, output_format_json_quote_64bit_integers, …) produces the same payload whichever writer serves the query. When a type is rejected, the exception names the column the query used rather than the Arrow field name a container gives its child (item, key, value), and says which setting accepts it.

Parquet and ORC are unaffected. CHColumnToArrowColumn::Settings::output_unsupported_types defaults to THROW and Arrow Flight is its only caller, so neither format writes an opaque column and Parquet still rejects QBit with UNKNOWN_TYPE exactly as before.

Arrow Flight otherwise pins the canonical Arrow mapping and deliberately does not follow the remaining output_format_arrow_* settings, because the same conversion builds the Flight SQL metadata responses whose schemas the specification fixes, and because a Flight client fetches the schema and the data in separate calls. That is now stated on arrowConversionSettings and documented on the Arrow Flight interface page, along with the fact that CreatePreparedStatement's dataset_schema is a best guess — the specification says clients must not assume it is accurate, and in ClickHouse it can differ both because inference substitutes NULL for each ? and because the Arrow mode is resolved per call.

StorageArrowFlight::ArrowFlightSink built its converter settings from scratch and never consulted the setting, so it always used the rejecting struct default. It now resolves the mode from the query context like the other Arrow Flight call sites.

Verified against a local ClickHouse Arrow Flight server as well as FORMAT Arrow. A QBit column in an ENGINE = ArrowFlight table now round-trips in the default binary mode, where the insert previously failed; JSON, Dynamic, QBit and AggregateFunction all read back byte-identical to the originals through an ArrowStream file in both modes; a Dynamic holding ok\xc3(tail arrives as ok\ufffd(tail in a string column while binary keeps the original bytes; and reading an opaque column without a requested type still yields the raw bytes as String. Nested and nullable shapes round-trip as their exact types: Nullable(JSON), Nullable(QBit), Array(JSON), Tuple(x JSON) and Map(String, JSON) through an ArrowStream file, with JSON subcolumn access working on the result, and QBit inside Array, Tuple and Nullable over Arrow Flight.

The reader change was diffed against the pre-change binary over the arrow, parquet, orc and utf8 suites: the same 48 of 456 fail either way, none of them Arrow. Because the library reader also serves Parquet, where the field metadata it now threads through containers is what JSON and UUID detection reads, that part was diffed separately against a baseline binary over nested JSON and UUID Parquet round trips, with schema inference and with explicit types — byte-identical.

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

Fixed SELECT ... FORMAT Arrow failing with Method getDataAt is not supported for JSON, Dynamic and QBit columns, and silently exporting heap addresses instead of the aggregate state for AggregateFunction columns. Added the output_format_arrow_unsupported_types setting (throw / text / binary, default binary) which supersedes output_format_arrow_unsupported_types_as_binary. Such columns can now also be read back into their original type, which previously failed or silently corrupted the value. INSERT INTO ... ENGINE = ArrowFlight now follows this setting too; it previously rejected such columns unconditionally, so an insert that used to fail may now write an opaque column — set output_format_arrow_unsupported_types = 'throw' to keep rejecting it.

Open in Web Open in Cursor 

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

Version info

  • Merged into: 26.10.1.54 (included in 26.10 and later)

The `output_format_arrow_unsupported_types_as_binary` fallback wrote a column
with no first-class Arrow mapping by calling `IColumn::getDataAt` per row.
That method exposes a column's contiguous in-memory bytes, which most of the
types reaching the fallback do not have:

- `ColumnObject` (`JSON`), `ColumnVariant` (hence `ColumnDynamic`) and
  `ColumnQBit` throw `Method getDataAt is not supported`, so `SELECT ... FORMAT
  Arrow` failed on them - after the schema message had already been written,
  leaving the client with a truncated stream;
- `ColumnAggregateFunction::getDataAt` returns the `AggregateDataPtr` itself,
  so exporting an aggregate state silently wrote raw heap addresses instead of
  the state, both corrupting the data and disclosing server addresses.

Before the fallback existed these types were rejected with a clear
`UNKNOWN_TYPE`, so both are regressions introduced together with the setting.

The fallback now serializes each value through `ISerialization`, whose
`serializeText`/`serializeBinary` are pure virtual and therefore defined for
every type, so the "do not fail a `SELECT *`" property holds by construction
instead of depending on an unrelated method's implementation status. The
aggregate state written in binary mode is the `RowBinary` encoding and
deserializes back into the original `AggregateFunction` type.

`output_format_arrow_unsupported_types` (`throw`/`text`/`binary`) replaces the
boolean, adding a `text` mode that writes what `CAST(col AS String)` would
produce - useful for the BI clients that drive `SELECT *` over Arrow Flight
SQL, and the workaround users had to apply by hand for `JSON`. The default,
`binary`, is the previous behavior, so `compatibility` must not change it. The
boolean keeps working with full effect (`0` means `throw`, `1` means `binary`)
and is only consulted while the new setting is left at its default, so an
explicit mode wins whichever order the two are set in.

Both writers now decide in the schema converter, before the schema message is
written, so a rejected type can no longer abort a stream whose schema the
reader has already accepted. An opaque column is tagged with the
`clickhouse.opaque` Arrow extension name and the original ClickHouse type
name, so a consumer can tell it apart from a genuine string or binary column;
a reader that does not know the extension name sees the plain storage type.

Closes: #115023
Caused by: #91170

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@CLAassistant

CLAassistant commented Aug 18, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ alexey-milovidov
❌ cursoragent
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [93eb366]

Summary: ✅


AI Review

Summary

This PR correctly replaces the old getDataAt fallback with serialization-based Arrow export, threads clickhouse.opaque metadata through both writers and readers, and fixes the opaque binary round-trip regressions for JSON, Dynamic, QBit, and AggregateFunction. I would still keep it open because the ordinary Arrow Utf8 paths for plain String / FixedString are unchanged: they still advertise Utf8 while writing raw bytes, so strict Arrow clients can reject the result as invalid Arrow data.

Findings

❌ Blockers

  • [src/Processors/Formats/Impl/ArrowIPC/SchemaConverter.cpp:643-666, src/Processors/Formats/Impl/ArrowIPC/RecordBatchEncoder.cpp:358-445, src/Processors/Formats/Impl/CHColumnToArrowColumn.cpp:1101-1137, 1452-1465] The new UTF-8 repair only runs on the opaque fallback path. Ordinary String columns, and FixedString when output_format_arrow_fixed_string_as_fixed_byte_array = 0, are still declared as Arrow Utf8 whenever output_format_arrow_string_as_string = 1, but both writers append the raw bytes verbatim. A query like SELECT unhex('80') FORMAT ArrowStream therefore still emits an Arrow Utf8 column with invalid payload, which strict readers are allowed to reject. Suggested fix: either route the Utf8 string branches through the same writeValidUTF8 repair path, or stop declaring unvalidated byte strings as Arrow Utf8.
Tests
  • ⚠️ There is still no automated end-to-end regression for the Apache-Arrow-library readback path against a real ClickHouse Flight server that preserves declared types. The native ArrowStream round-trip test exercises the same tag matching logic, but ENGINE = ArrowFlight typed readback remains manual-only because the mock Flight server casts incoming data to strings.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 93eb366.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 511/587 (87.05%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 18, 2026
A new setting field type has to be listed in every `*_SUPPORTED_TYPES` macro
that carries format settings, otherwise `Settings::operator[]` has no overload
for it. Follows `ArrowCompression` everywhere it appears.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 93eb36619 with master e02a452a9 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

464 object files changed (+378.97 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/CHColumnToArrowColumn.cpp.o 649.73 KiB 694.54 KiB +44.81 KiB (+6.90%)
src/CMakeFiles/dbms.dir/Core/SettingsEnums.cpp.o 2.09 MiB 2.12 MiB +23.59 KiB (+1.10%)
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ArrowIPC/RecordBatchEncoder.cpp.o 102.43 KiB 123.67 KiB +21.23 KiB (+20.73%)
src/CMakeFiles/dbms.dir/Storages/StorageArrowFlight.cpp.o 443.62 KiB 463.09 KiB +19.46 KiB (+4.39%)
src/CMakeFiles/dbms.dir/Core/Settings.cpp.o 3.51 MiB 3.53 MiB +19.33 KiB (+0.54%)
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp.o 561.14 KiB 578.12 KiB +16.97 KiB (+3.02%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3194 translation units recompiled, 16711 s compile time in total, 3193 of them have a recent master baseline.

Job report

Covers all three values of `output_format_arrow_unsupported_types` for
`JSON`, `Dynamic`, `Array(Dynamic)` and `AggregateFunction`, the precedence
between the new setting and `output_format_arrow_unsupported_types_as_binary`
in both orders, the `AggregateFunction` binary round-trip through
`finalizeAggregation`, and the `clickhouse.opaque` extension tag as seen by
`pyarrow`.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review August 18, 2026 13:45
cursoragent and others added 2 commits August 18, 2026 16:19
…ting in the Flight sink

`CHColumnToArrowColumn`, which serves Arrow Flight, only switched the storage
type to `utf8`/`binary` for a column with no Arrow mapping, so a Flight client
could not tell such a column from a genuine `String`/`Binary` one - the
`clickhouse.opaque` extension tag existed only in the native IPC writer.
`getArrowType` now reports the ClickHouse type name of an opaque column through
an out parameter and `calculateArrowSchema` attaches the same extension
metadata. Only the pass-through wrappers (`Nullable`, `LowCardinality`) forward
it, so it describes the field itself, matching how this writer already tags
`UUID` at the root.

The extension name moves to `FormatSettings` next to the enum, so both writers
share one definition (`SchemaConverter.h` is `USE_ARROW`-only, while
`CHColumnToArrowColumn` also builds for `USE_PARQUET`).

`StorageArrowFlight::ArrowFlightSink::consume` built its converter settings
from scratch and so never consulted the setting at all, leaving it on the
struct default. It now resolves the mode from the query context like the other
Arrow Flight call sites, which makes `INSERT INTO ... ENGINE = ArrowFlight` of
an `AggregateFunction` column follow `output_format_arrow_unsupported_types`
(`throw` reproduces the struct default). `JSON` and `Dynamic` cannot reach this
sink: the storage rejects a dynamic-structure column when the table is created,
and through the table function the header comes from the remote schema.

Verified against a local ClickHouse Arrow Flight server: `SELECT *` over a
table with `JSON` and `AggregateFunction` columns returns them as
`clickhouse.opaque`-tagged `binary` fields carrying the ClickHouse type name,
with a neighbouring `String` column left untagged, and
`output_format_arrow_unsupported_types = 'text'` in the command switches them
to tagged `string` fields holding the text.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
cursoragent and others added 3 commits August 19, 2026 00:23
`CHColumnToArrowColumn` materialized a default `FormatSettings` to serialize a
column with no Arrow mapping, so the payload ignored every setting the value's
serialization depends on. The native Arrow IPC writer passes the query's own
settings, so the two writers could encode the same value differently:
`output_format_binary_write_json_as_string = 1` produced the length-prefixed
`RowBinary` string in `FORMAT Arrow` and the plain binary `JSON` encoding over
Arrow Flight. `text` mode diverged the same way, for instance on
`output_format_json_quote_64bit_integers`.

The settings now travel with the conversion settings, and the Arrow Flight call
sites build both through one `arrowConversionSettings` helper instead of
repeating the initializer. `getFormatSettings` reads the whole profile, so the
per-block loop in `DoGet` resolves it once rather than once per block.

Verified against a local ClickHouse Arrow Flight server that both writers now
emit identical bytes:

    output_format_binary_write_json_as_string = 0 -> 0101610A0100000000000000
    output_format_binary_write_json_as_string = 1 -> 077B2261223A317D
    output_format_json_quote_64bit_integers = 1   -> {"n":"12345678901234567890"}

Co-authored-by: Yakov Olkhovskiy <[email protected]>
`calculateArrowSchema` attached the `clickhouse.opaque` extension type only to
the top-level field, while the container branches of `getArrowType` built their
children with no metadata. `Array(JSON)`, `Tuple(j JSON)`, `Map(String, JSON)`
and `Variant(..., JSON)` therefore reached an Arrow Flight client as plain
`list<item: binary>` / `struct<j: binary>` / ... , where the native Arrow IPC
writer tags those children, so a nested opaque value was indistinguishable from
a genuine string or binary child on this path only.

The container branches now build their children through `getArrowChildField`,
which carries the tag when the child's ClickHouse type has no Arrow mapping.
Arrow type equality ignores child field metadata, so the builder path that
shares `getArrowType` is unaffected.

Verified against a local ClickHouse Arrow Flight server that the two writers
now produce the same schema for `Array(JSON)`, `Tuple(JSON)`, `Map(String, JSON)`
and `Variant(String, JSON)`, down to the tag on `item`, `j`, `value` and the
variant's `Object` alternative.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
The interface page still described the superseded boolean. It now covers the
three values of `output_format_arrow_unsupported_types`, the `clickhouse.opaque`
extension tag that lets a client tell such a column from a genuine
`Utf8`/`Binary` one, and how the boolean maps onto the new setting.

The rest of the user-facing documentation is generated: the per-setting page
under `docs/reference/settings/formats/` comes from the `DECLARE` doc strings in
`FormatFactorySettings.h`, and the settings tables on the `Arrow` and
`ArrowStream` pages come from `setDocumentation` in
`ArrowIPCBlockInputFormat.cpp`, both of which this branch already updates.
Regenerating the docs tree against this build confirms those sources produce
the intended pages, so the generated regions are left to the docs
autogeneration workflow.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@mintlify

mintlify Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 17, 2026, 3:56 AM

@dgieselaar

Copy link
Copy Markdown

@yakov-olkhovskiy I'm running into this now - I'm using FORMAT ArrowStream everywhere and it basically breaks my product for anyone that is using JSON columns. It seems like a pretty bad bug to me but perhaps I either A) missed a workaround (?), B) no one is using ArrowStream. Any chance of moving this forward?

cursoragent and others added 3 commits September 9, 2026 12:49
…k-5dc0

Master opened a 26.9 settings-changes block while this branch was open, so the
`output_format_arrow_unsupported_types` entry moves there - that is the release
it now ships in.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
`format_settings` was the only member of `CHColumnToArrowColumn::Settings`
without one, so `-Wmissing-field-initializers` fired on the positional
aggregate initialization in `DeltaLake/WriteTransaction.cpp`, which lists only
the leading fields and relies on the rest defaulting. That is an error under
`-Werror` in the `arm_tidy` build:

    WriteTransaction.cpp:121:9: error: missing field 'format_settings' initializer
    [clang-diagnostic-missing-field-initializers,-warnings-as-errors]

Clang skips the diagnostic for a field that has an initializer, so spelling one
here also keeps any future field addition from breaking that caller.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
…ed anchor

The `output_format_arrow_unsupported_types` heading is emitted into the
autogenerated region of `reference/settings/formats/output-format`, which this
branch deliberately leaves to the docs autogeneration workflow. Until that runs
the anchor does not exist in the committed tree, so `lychee --include-fragments`
rejected the link:

    [ERROR] reference/settings/formats/output-format#output_format_arrow_unsupported_types
    (at 399:198) | Cannot find fragment

Linking the page instead is stable regardless of when the reference pages are
regenerated, and the setting is already named in the sentence.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@yakov-olkhovskiy

Copy link
Copy Markdown
Member Author

@dgieselaar not a workaround you missed, and not that nobody uses ArrowStream - it's a genuine gap - JSON has never been exportable over Arrow/ArrowStream. Before 26.5 you'd get a clean UNKNOWN_TYPE - 'JSON' is not supported for conversion into Arrow data format, and from 26.5 you get the much less obvious Method getDataAt is not supported for Object(...). Same outcome either way, so downgrading won't help you.

output_format_arrow_unsupported_types_as_binary = 0 isn't a workaround either - it only replaces one exception with a clearer one.

What does work today is casting the column in the query, since String maps to Arrow fine:

SELECT id, toJSONString(j) AS j FROM t FORMAT ArrowStream

If you're doing SELECT * and don't want to enumerate columns, REPLACE keeps the shape:

SELECT * REPLACE (toJSONString(j) AS j) FROM t FORMAT ArrowStream

On this PR: once it lands, a JSON column goes out without any query changes. The default (output_format_arrow_unsupported_types = 'binary') writes the RowBinary encoding, but for a product consuming ArrowStream you probably want:

SETTINGS output_format_arrow_unsupported_types = 'text'

which gives you the JSON text in an Arrow Utf8 column - the same thing toJSONString produces, without the cast. Either way the field is tagged with the clickhouse.opaque Arrow extension name and the original ClickHouse type name, so your client can tell it apart from a genuine string column.

Two problems with how an opaque column is declared.

`text` mode advertised every opaque column as Arrow `Utf8`, but
`SerializationAggregateFunction::serializeText` writes the raw state bytes
rather than text, so `sumState(toUInt64(128))` produced a `Utf8` column whose
payload starts with `0x80` and is not valid UTF-8. The schema is written before
any data, so this cannot be decided per value: an aggregate state now goes into
a `Binary` column in either mode, in both writers. Every other type reaching
this path (`JSON`, `Dynamic`, `QBit`, `BFloat16`) has a genuine text form and
still gets `Utf8` in `text` mode.

`DataTypeMap::isValidKeyType` rejects only nullable keys, so `Map(JSON, UInt8)`
is a legal type, but the Arrow-library writer passed the key to `arrow::map` as
a bare type and only the value went through `getArrowChildField`. The key field
therefore carried no `clickhouse.opaque` tag, while the native IPC writer tags
both children. The key is now built as a field too, via the `MapType` overload
that takes both, which reproduces the previous layout - an `entries` struct of
a non-nullable `key` and a `value` - with the tag added.

The new coverage is a high-bit aggregate state and a `Map(JSON, UInt8)` in the
stateless test for the native writer, and the same two over Arrow Flight in the
integration test for the library-backed one.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
cursoragent and others added 2 commits September 17, 2026 02:17
A column whose type has no Arrow mapping is written as an opaque column tagged
`clickhouse.opaque`, and reading it back into that type has to undo the encoding
the Arrow type names. That undo reached only a non-nullable column sitting at the
top level of the batch.

On the native reader it moves out of `decodeBatchColumn` into `reinterpretRawBytes`,
the post-decode rewrite that already walks `Nullable`, `Array`, `Tuple` and `Map`
alongside the requested type. `DecodedColumn` carries the schema field it was
decoded from and the recursion threads each child's own field down, so a leaf reads
the tag that belongs to it. A `Nullable` root and a constant column, both excluded
before, are covered by the same move.

On the Apache-Arrow-library reader the `LIST`, `MAP` and `STRUCT` branches passed
the parent `arrow::Field` into the child read, where the child's metadata never is.
They now pass the child's own field.

Parquet and ORC are unaffected: `output_unsupported_types` defaults to `THROW` and
only Arrow Flight sets it, so neither writes an opaque column in the first place.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
…o cursor/fix-arrow-unsupported-types-fallback-5dc0

# Conflicts:
#	src/Core/SettingsChangesHistory.cpp

Co-authored-by: Yakov Olkhovskiy <[email protected]>
std::string field_name = column_variant_type.getVariant(i)->getFamilyName();
fields.push_back(std::make_shared<arrow::Field>(field_name, arrow_type, is_column_nullable));
fields.push_back(getArrowChildField(
field_name, column_name, column_variant_type.getVariant(i), variant, format_name, settings, for_builder));

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.

The write side now tags opaque Variant alternatives distinctly, but the native IPC reader still never consumes that information inside unions. RecordBatchDecoder::decodeUnion decodes every child with target_hint = nullptr and fieldToCHType(child, ...) (src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp:1479-1509), so an alternative tagged clickhouse.opaque = JSON is still treated as plain String.

That makes valid round-trips fail today. The simplest repro is Variant(JSON, String): in either mode, both union children map to String, DataTypeVariant deduplicates them, and read-back fails with Arrow IPC union has multiple children mapping to the same ClickHouse type. Even when the other alternatives are distinct, binary mode still falls back to the old String -> CAST route because the post-pass never descends through ColumnVariant.

Could we thread the requested Variant alternatives through decodeUnion (or add an equivalent post-pass for ColumnVariant) before treating Variant as covered by the new opaque round-trip support?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Both repros are real — I reproduced them exactly, including the Variant(JSON, String) deduplication error. The last sentence is the right ask, and I have taken it as written down rather than papered over: d949874 states the limitation in the setting description, so Variant is no longer implied to be covered.

What the measurements say about where the gap is. It is not specific to binary, and not specific to this PR's reader work — text fails identically:

type binary text
Variant(JSON, String) INCORRECT_DATA, union deduplication same
Variant(JSON, UInt64) CANNOT_CONVERT_TYPE, Variant(String, UInt64) -> Variant(JSON, UInt64) same
Variant(QBit(BFloat16, 3), UInt64) CANNOT_CONVERT_TYPE same
Variant(String, UInt64) round-trips round-trips

So a Variant with an alternative that has no Arrow mapping does not round-trip in any mode, and it fails loudly in every case — there is no silent corruption of the kind this PR fixes for inline columns, where a Dynamic absorbed the encoding's tag and length bytes into its value. It is also not a regression: before this PR the write side could not produce such a file at all, because the getDataAt fallback threw on the union's JSON child.

On fixing it here rather than following up. decodeUnion derives each child's type from fieldToCHType with no hint, so a tagged child would need the requested Variant's alternatives threaded in, and the type has to be settled inside decodeUnion — the deduplication check runs there, before any post-pass could descend through ColumnVariant. That part is tractable. The problem is symmetry: ArrowColumnToCHColumn has no union handling at all, so an Arrow union never becomes a Variant over Arrow Flight in the first place. Making Variant round-trip properly therefore means implementing union decoding in the library reader too, which is a feature in its own right and unrelated to what this PR is fixing. Doing it only in the native reader would leave the two readers disagreeing about Variant, which seems worse than a documented gap.

Happy to open a follow-up issue for union decoding across both readers if you would like it tracked.

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.

Yes, please track this separately. The docs now narrow the promise enough that I would not block this PR on Variant, but Variant(..., JSON/QBit/...) is still a user-visible gap that will be easy to rediscover without a follow-up issue.

An Arrow union is decoded without consulting the `clickhouse.opaque` tags its
children carry, so a `Variant` with an alternative that has no Arrow mapping
writes fine but does not read back into the same `Variant`. It fails the same way
in `text` and in `binary`, so this is a property of union decoding rather than of
either encoding, and the data written stays well formed for other Arrow readers.
Say so in the setting description instead of leaving it to be discovered.

Also record why the dictionary rewrite passes no field: a dictionary is how a
`LowCardinality` is written, and that wraps only numbers, strings, `Date` and
`DateTime`, each of which has an Arrow type of its own, so a dictionary's values
are never an opaque column.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Comment thread src/Core/FormatFactorySettings.h Resolved
cursoragent and others added 2 commits September 17, 2026 13:49
`StorageArrowFlight.cpp` already included it, so the one added for
`getArrowUnsupportedTypesMode` was a second copy and `readability-duplicate-include`
failed the tidy build.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115250&sha=d9498748a0eb5a6e47c32e03e2b222dcc8a7ee59&name_0=PR&name_1=Build%20%28arm_tidy%29
#115250

Co-authored-by: Yakov Olkhovskiy <[email protected]>
The previous wording read as though the tag alone were enough. It is not: neither
schema-inference path consults it, so a column read without a type named for it
arrives as `String` holding the raw payload, unchanged from before. Only a read
that already knows the type - from a table's declaration or from a structure
argument - recovers it.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@yakov-olkhovskiy
yakov-olkhovskiy added this pull request to the merge queue Sep 17, 2026
Merged via the queue into master with commit bf669b9 Sep 17, 2026
178 checks passed
@yakov-olkhovskiy
yakov-olkhovskiy deleted the cursor/fix-arrow-unsupported-types-fallback-5dc0 branch September 17, 2026 20:10
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
alexey-milovidov pushed a commit to jh0x/ClickHouse that referenced this pull request Sep 19, 2026
alexey-milovidov pushed a commit that referenced this pull request Nov 7, 2026
Resolve the conflicts in ArrowFlightServer.cpp: 26.9 does not have #115250,
#125534 and #125553, which changed the same lines (conversion settings,
the `block.empty()` check in `DoGet`, `removeSpecialColumnRepresentations`),
so their changes are left out and only #129193's lines are kept.

Leave out 05497_arrowflight_exception_on_query_finish: 26.9 has no Arrow
Flight port in the stateless test config (#125517 is master-only), so the
test cannot connect there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 7, 2026
Resolve the conflicts in ArrowFlightServer.cpp: 26.8 does not have #115250,
#125534 and #125553, which changed the same lines (conversion settings,
the `block.empty()` check in `DoGet`, `removeSpecialColumnRepresentations`),
so their changes are left out and only #129193's lines are kept.

Leave out 05497_arrowflight_exception_on_query_finish: 26.8 has no Arrow
Flight port in the stateless test config (#125517 is master-only), so the
test cannot connect there.

Co-Authored-By: Claude Opus 5.5 <[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.

Arrow: unsupported-types-as-binary fallback crashes on JSON/Dynamic columns

7 participants