Skip to content

Read an opaque Variant alternative back from Arrow - #120702

Open
yakov-olkhovskiy wants to merge 13 commits into
masterfrom
cursor/arrow-variant-opaque-alternatives-5dc0
Open

yakov-olkhovskiy wants to merge 13 commits into
masterfrom
cursor/arrow-variant-opaque-alternatives-5dc0

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Related: #120688
Related: #115250

A column whose type has no Arrow mapping is written as an opaque column tagged clickhouse.opaque with the ClickHouse type it came from, and #115250 made both readers recover that type. An opaque Variant alternative was the one shape left out: it could be written and not read back, in text and binary alike.

RecordBatchDecoder::decodeUnion decodes every child with no hint and types it with fieldToCHType, from the Arrow field alone, so an opaque child came back as String. Two of them then collapsed into a single Variant alternative and the union was rejected outright; one alongside any other type produced a Variant that would not convert to the requested one:

-- before
SELECT v FROM file('v.arrow', 'ArrowStream', 'v Variant(JSON, String)');
-- Code: 117. Arrow IPC union has multiple children mapping to the same ClickHouse type,
--            which Variant cannot represent. (INCORRECT_DATA)

SELECT v FROM file('v.arrow', 'ArrowStream', 'v Variant(JSON, UInt64)');
-- Code: 70. Cannot convert type Variant(String, UInt64) to Variant(JSON, UInt64).
--           Conversion between Variant types is allowed only when new Variant type
--           is an extension of an initial one. (CANNOT_CONVERT_TYPE)

The requested Variant is now resolved for the union, and a child's tag is looked up among its alternatives. The type therefore still comes from what the caller asked for and never from the file — the tag only confirms which alternative the child was written from, the same rule Array, Tuple, Map and Nullable already follow, and the reason nothing here needs a setting.

A tag naming a type the request does not list is not acted on, and the child keeps the type its Arrow field names. Where the request has no other child of that type, the payload arrives as the raw bytes. Where it does, the two children land on one Variant alternative and the union is rejected — which is what any two Arrow union children sharing a ClickHouse type do, a utf8 and a large_utf8 child included, with nothing opaque involved. None of that changes here: before this PR every request rejected such a file, this one included.

The Arrow type of each child states its own encoding, so a union can mix the two: Binary is serializeBinary, and Utf8 is the text form, which serializeText wrote and deserializeWholeText inverts. In text mode an AggregateFunction alternative is still Binary — its text form is the raw aggregate state, not text — and it is read correctly alongside a Utf8 sibling.

A slot that no row selects is not read. A sparse child has one per unselected row and a dense one keeps whatever slicing left behind, and per the Arrow spec their bytes are undefined, so they take the type's default — the treatment the rest of the decoder already gives an invisible row. Reading them would reject a legal file with Attempt to read after eof.

Why the decoder now reports the type it built

A union is the one field whose element types are settled while decoding rather than by fieldToCHType. decodeBatchColumn declared the column with fieldToCHType while taking the values from decodeField, so converting a child without saying so would have left the column holding types its declaration does not name — the divergence #120688 warns about, and the same one #115250 hit and solved by moving its deserialization to where column and type are set together.

decodeUnion therefore reports the Variant it built, and decodeBatchColumn declares the column with that. Where there is nowhere to report it the conversion is skipped and the child keeps the type its Arrow field names. That is what a union nested in a container still does: its type comes from fieldToCHType recursing through the container, so Array(Variant(JSON, String)) is unchanged and still fails exactly as before, loudly. Closing that needs the type derivation itself to consult the tag, which is the other half of #120688 and carries a compatibility decision this change does not.

What this does not recover

decodeUnion drops the requested type for all of its children, and only the tagged ones are recovered here. An alternative that needs that type for its own decoding still comes back as whatever its Arrow field names, so Variant(JSON, IPv6) does not round-trip even though its JSON alternative now does — the IPv6 child stays FixedString(16). The same goes for a big integer, and for a container holding an opaque leaf such as Variant(Array(JSON), UInt64).

That is not a consequence of the opaque path. Variant(IPv6, UInt64) fails identically with nothing tagged anywhere, while the same IPv6 column round-trips at top level, so this predates the change. Recovering those needs a correspondence the tag supplies and an Arrow type does not: a fixed_size_binary(16) child is FixedString(16) whether the caller asked for IPv6 or for FixedString(16). It would mean matching each requested alternative forward to the Arrow type it would have been written as — a redesign of union decoding, which would also subsume the child-collision case above. Variant(UUID, UInt64) shows the shape of what does work inside a union today: fieldToCHType recovers UUID from the arrow.uuid extension name, tag-driven exactly like this change.

Verification

05227_arrow_variant_opaque_alternatives covers Variant(JSON, String), Variant(QBit(BFloat16, 3), UInt64) and Variant(AggregateFunction(sum, UInt64), String) over three rows — one selecting the opaque alternative, one a plain alternative, one NULL — in both modes, checked against the originals. The plain-alternative row matters as much as the opaque one: Variant(JSON, String) holding a String still reports String, so the two children stay distinct.

Three further cases pin the edges: a request that omits the tagged type and gets the raw bytes; a request that omits it while listing the type the payload falls back to, which is rejected; and the two unselected-slot shapes. ClickHouse writes neither of those last two, so the test builds them with pyarrow, taking the payload out of a file ClickHouse has just written rather than hardcoding bytes, so it does not pin down the encoding.

Locally the arrow and variant suites pass: 262 tests, the one remaining failure needing a parallel-replicas server config.

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

A Variant column with an alternative whose type has no Arrow mapping (such as JSON, QBit or AggregateFunction) can now be read back from FORMAT Arrow/ArrowStream into the same Variant. Writing it already worked, but reading it failed with Arrow IPC union has multiple children mapping to the same ClickHouse type or Cannot convert type Variant(String, ...).

Open in Web Open in Cursor 

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

A `Variant` alternative whose type has no Arrow mapping is written as an opaque
union child tagged `clickhouse.opaque`. Reading it back did not work, in `text` and
`binary` alike: `decodeUnion` decodes each child with no hint and types it from the
Arrow field alone, so every opaque child came back as `String`. Two of them then
collapsed into one `Variant` alternative and the union was rejected, and one
alongside any other type produced a `Variant` that would not convert to the
requested one.

The requested `Variant` is now resolved for the union and each child's tag is looked
up among its alternatives, so the type still comes from what the caller asked for
rather than from the file, as it does for `Array`, `Tuple`, `Map` and `Nullable`.
The Arrow type of the child states its encoding, so a union can mix the two: in
`text` mode an `AggregateFunction` alternative is still `Binary`, its text form not
being text.

A union is the one field whose element types are settled while decoding rather than
by `fieldToCHType`, so `decodeUnion` reports the type it built and `decodeBatchColumn`
declares the column with it. Without somewhere to report it the conversion is skipped
and the child keeps the type its Arrow field names, which is what a union nested in a
container still does - its type comes from `fieldToCHType` recursing, and it is
unchanged here.

Related: #120688
Related: #115250

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

CLAassistant commented Sep 17, 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 Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0c55196]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb
Build profile diff ERROR

AI Review

Summary

PR #120702, reviewed at 0c55196e75f, restores opaque alternatives in top-level Variant columns read from Arrow and ArrowStream. The dictionary column/type mismatch and incorrect setting documentation reported previously are fixed. No unresolved findings remain within the documented scope.

Missing context / blind spots
  • ⚠️ Arrow-enabled stateless CI is still pending, and this checkout has no runnable ClickHouse binary. Runtime evidence comes from the author's reported runs of the committed regressions; a passing CI execution of 05227_arrow_variant_opaque_alternatives would independently confirm them.
Final Verdict

Status: ✅ Approve. No additional code changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 17, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 0c55196e75f135a91bb979b1c3109b8a251c4ef8 with master failed: LogClusterNotReady: the endpoint never became ready.

See the job log for details.

cursoragent and others added 2 commits September 18, 2026 18:46
A union child holds a slot for every row a sparse union has, and a dense one keeps
whatever slicing left behind. Those slots hold undefined bytes per the Arrow spec,
and the opaque path was reading them: a legal file whose unselected slots are not
valid payloads failed with `Attempt to read after eof` before the selected rows were
ever compacted. They now take the type's default, the treatment the rest of the
decoder already gives an invisible row.

The test builds both shapes with pyarrow, since ClickHouse writes neither, and takes
the payload from a file it has just written rather than pinning down the encoding.

It also pins what happens when a request omits the tagged type while listing the type
the payload falls back to: the two children land on one `Variant` alternative and the
union is rejected. That is what any two Arrow union children sharing a ClickHouse type
do - a `utf8` and a `large_utf8` child collide the same way, with nothing opaque
involved - so the earlier "stays the raw bytes" claim held only where the request had
no such sibling.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
…://github.com/ClickHouse/ClickHouse into cursor/arrow-variant-opaque-alternatives-5dc0

Co-authored-by: Yakov Olkhovskiy <[email protected]>
pull Bot pushed a commit to stnxo2023/ClickHouse that referenced this pull request Sep 23, 2026
…cenario

`Storage memory check` fails unrelated PRs with a byte-constant
`change=+1,056`. Since ClickHouse#120487 removed the one-time initialization offset,
9 heads had `+1,056` as their only failing scenario, on
`03_add_secondary_indexes.sql` and `04_add_projection.sql`.

A pooled thread that runs a mutation step attaches to the task's
`ThreadGroup` through `ThreadGroupSwitcher`, and that attach constructs
thread-local performance-counter state: `TasksStatsCounters`, a
`ProcfsMetricsProvider`, and two `__cxa_thread_atexit_impl` registrations
which by construction live until the thread exits. `GlobalThreadPool` keeps
its threads, so those bytes stay live once a thread has participated, and
the quantity the checkpoint diff measures is how many distinct pool threads
have ever served the scenario. Which window a thread's first participation
lands in is a scheduling draw.

It is one cluster of 7 stacks costing exactly 528 bytes per participating
thread: +384 `TasksStatsCounters::create`, -64
`ThreadGroup::SharedData::SharedData`, +64 `detachFromGroup`, +48
`make_shared<ProcfsMetricsProvider>`, +32 and +32 for the two
`__cxa_thread_atexit_impl` registrations, +32 for the query-id string copy
in `applyQuerySettings`. The gate is `absolute_change > 1024 AND
percent_change > 1.0`, so one unit passes and two clear it by 32 bytes: the
threshold sits inside the noise quantum. PR ClickHouse#120702 at `b48703670359` has
rows for `04_add_projection.sql` at both 528 and 1,056, the same commit
measured twice with different answers, so no threshold value could measure
this quantity.

Raising the threshold is the move that already failed: `150d1f2d0290b`
raised this lane from the parser lane's 100 to 1,024 for this exact
mechanism, and two units cleared it three days later. Waiting for
background tasks to quiesce cannot work either, because this state is
registered with `__cxa_thread_atexit_impl` and is not a teardown tail.
Pinning the pools to one thread would be C++-side, and the master arm
binary is downloaded from the merge base, so such a fix is asymmetric until
it reaches master.

Instead add the three thread attach/detach frames to the analyzer's
existing `EXCLUDED_STACK_FRAME_PREFIXES`, which `compute_diff` already
consults before a stack reaches the gated total. Both arms of a run are
analysed by the same script from the same checkout, so the change applies
symmetrically from the first run, and keying on the allocation site covers
every pool at once rather than enumerating pools or settings.

On the production reports for ClickHouse#118967, ClickHouse#120960, ClickHouse#121251 and ClickHouse#120702,
removing this cluster takes every failing scenario's change to exactly 0,
with the largest residual anywhere 64 bytes against the 1,024-byte
threshold. Locally, 20 repeated two-pass runs of one binary reproduce the
528-byte unit with the same 7-row composition and a multiplicity that
varies run to run; an injected 64 KiB-per-table allocation is still
reported at full size; and reverting only these three prefixes restores the
pre-fix numbers byte-for-byte.

Two consequences are deliberate. The cluster rows also leave the HTML
report, exactly as `dumpProfile` overhead already does, because a row the
check must not gate on should not be presented as a finding. And
thread-accounting regressions are no longer measured here, which the
same-commit pair above shows was never possible anyway.

`STORAGE_CHANGE_THRESHOLD_BYTES` is left at 1,024. Removing this noise is
what would make lowering it toward the parser lane's 100 possible, but that
is a calibration decision with its own data.

Related: ClickHouse#120487
Related: ClickHouse#119480

Co-Authored-By: Claude Opus 5 <[email protected]>
cursoragent and others added 2 commits October 7, 2026 23:12
One conflict, in `decodeBatchColumn`. Master hoisted the row-count check and the
subtree validation out of the non-constant branch into an earlier `if (!constant)`
block, so that a field whose nulls are undeclared can be decoded through a nullable
copy and `decoded.type` derived from it. This branch had added a `DataTypePtr
union_type` declaration to the same lines master moved away.

Resolved by taking master's structure and keeping only the declaration, which the
`decodeField` call below still fills through `&union_type`. The override that
follows now takes its type from the same `effective_field` the column was decoded
from, so the two agree as before.

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

`decodeDictionaryValues` decodes through `decodeBatchColumn`, so asking it for the
type a union settled on also applied to dictionary values. That type reaches the
declaration only when the referencing field is a batch column: a reference nested
in a container is typed by `fieldToCHType` recursing through that container, which
cannot see a type built while decoding. The dictionary's values would then carry
alternatives their declaration does not name, and the later variant-extension cast
would read a `ColumnObject` as the `String` the declaration claims.

Only the batch-column caller now asks for it. The dictionary one passes nothing,
which the existing guard in `decodeUnion` already treats as "no one can declare
this", leaving dictionary values exactly as they were before this branch.

Related: #120702 (comment)
Co-authored-by: Yakov Olkhovskiy <[email protected]>
…onary case

The setting description still said an alternative of a `Variant` never reads back,
which this branch makes false for a union the request names. It now says where the
recovery applies and keeps the limitation where it still holds: a `Variant` nested
in a container is typed from the Arrow fields alone.

The regression for a dictionary-encoded union inside a container goes with it. It
reads back as the alternative its declaration names, holding the payload as written.
Without the gate the same file segfaults, because the variant-extension cast reads a
`JSON` column as the `String` the declaration claims - a bad cast that a release
build does not check.

Related: #120702 (comment)
Co-authored-by: Yakov Olkhovskiy <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants