Repository navigation
Fix Iceberg Avro writer emitting optional complex fields as required - #112648
PedroTadim merged 2 commits into
Conversation
AvroSerializer::createSchemaWithSerializeFn builds an avro::UnionSchema in exactly two arms, Nullable and Variant; the Array, Tuple and Map arms build bare container schemas. Avro nullability therefore came purely from the ClickHouse type carrying a Nullable wrapper. The Iceberg read layer never puts that wrapper on a container: IcebergSchemaProcessor::getFieldType calls makeNullable only on its scalar branch, while the complex branch returns a bare Array, Map or Tuple regardless of the field's own required bit (the bit is read only to type a struct's children). So an Iceberg field declared "required": false whose type is a list, map or struct reached the writer without a Nullable and was serialized into the data file as required, contradicting the table metadata describing it and making the file non-conformant for other Iceberg readers. This is the Avro half of ClickHouse#111775, which fixed the same defect for the ORC writer and introduced the per-path iceberg_optional_paths metadata that ORC was so far the only consumer of. Add createFieldSchemaWithSerializeFn and use it at the four sites that own a field: the top-level column, a tuple field, an array element and a map value. It consults the per-path metadata and wraps the built schema in ["null", T], skipping schemas whose root is already a union or null because those carry their own optionality; that keeps the union emitted exactly once per path, so Nullable(Tuple) at an optional path stays a single union instead of becoming an invalid nested one. The three container arms are unchanged, and the three transparent same-path recursions (Nullable, LowCardinality, Variant) keep calling the raw helper so they cannot introduce a second union. Map keys deliberately stay outside this path: they never go through createSchemaWithSerializeFn, which matches collectOptionalPaths forcing a map key required per the Iceberg spec. Behaviour is unchanged without the metadata, so plain FORMAT Avro output is byte-identical, and Iceberg field ids are unaffected because setIcebergFieldIds already descends through a union without extending the path. The Parquet writer expresses optionality through FieldRepetitionType, a different mechanism, and is tracked separately.
Fix round r1. Test-only; the writer seam and the reader are unchanged. Gate B was right that the previous fixture pinned only one of the four changed call sites: every optional NESTED path in it was a primitive, so its union came from the pre-existing Nullable arm rather than from the new boundary wrapper. Add one optional COMPLEX payload per nested owner position (Array(Tuple) element, Tuple field of list type, Map value of struct type). Reverting each site individually now moves a disjoint set of reference lines, so all four are covered. Tighten the union oracle to require exactly the 2-branch null-first form, so a wrong arity or a swapped branch order fails instead of also reading as "optional", and assert Iceberg field ids at every depth rather than only at the root: not descending through the union drops four nested-id lines. Pin input_format_null_as_default for the read-back. It has to sit on the CREATE TABLE, not on the SELECT: a table engine freezes its format settings at creation and ignores the session ones afterwards, so a per-statement pin cannot reach the reader. Without it, a run that injects an old compatibility value gets the pre-21.1 default of false, under which the union an optional container now carries has no legal target, because Array and Map cannot be Nullable in ClickHouse. Add that throw as an assertion of its own, read through file() so the setting is statement-local, with a required container as the control. The trailing grep also had to stop deciding the script's exit status: a grep that matches nothing exits 1, and the runner fails a .sh test on any nonzero return code even when its output matches the reference.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 gate passes, 1 finding), plus my own
Two claims made during the rounds were corrected rather than carried forward. The first prescribed Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-51:20260730-175900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-42:20260730-164200 |
|
cc @al13n321 @scanhex12, could you review this? The Avro writer built a |
|
Workflow [PR], commit [a4f09bf] Summary: ✅
AI ReviewSummaryThis PR fixes the Iceberg Avro writer so optional complex fields ( Findings❌ Blockers
Final VerdictStatus: ❌ Block Minimum required action: avoid the new self-incompatible |
| if (schema_type == avro::AVRO_UNION || schema_type == avro::AVRO_NULL) | ||
| return mapping; | ||
|
|
||
| avro::UnionSchema union_schema; |
There was a problem hiding this comment.
This fixes the Avro schema, but it also makes Iceberg* tables created with persisted input_format_null_as_default = 0 start writing files they cannot read themselves back.
IcebergSchemaProcessor::getFieldType still materializes optional complex fields as bare Array / Map / Tuple (src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp:553-623), and the Avro reader still throws on any Union(Null, T) read into a non-nullable target when null_as_default is off (src/Processors/Formats/Impl/AvroRowInputFormat.cpp:492-534). Because object-storage tables persist format settings from CREATE TABLE (src/Storages/ObjectStorage/registerStorageObjectStorage.cpp:55-70), this is a stored regression rather than a session-only quirk: an existing IcebergLocal(..., 'Avro') table created under old compatibility or with SETTINGS input_format_null_as_default = 0 used to write/read its own optional list / map / struct columns, but after this change it will emit ["null", T] and then fail on read.
Can we either fix the reader in the same PR, or at least reject Avro writes for that persisted setting combination instead of silently producing unreadable data?
There was a problem hiding this comment.
Verified all three citations and they hold, so I agree the finding is real. I also found my own scope claim was wrong, and I have corrected the description.
I had written that ClickHouse DDL cannot author an optional container, because getIcebergType publishes required: true for Array/Map/Tuple. That misses the Nullable arm (Utils.cpp:627-631), which publishes required: false, and DataTypeTuple::canBeInsideNullable() is true. So Nullable(Tuple) is a ClickHouse-authored carrier. On a debug build, comparing this branch against its merge base with only AvroRowOutputFormat.{cpp,h} reverted:
written schema for a Nullable(Tuple(y Int64)) column |
master | this branch |
|---|---|---|
nt |
record |
["null", "record"] |
SELECT *, input_format_null_as_default = 1 (default) |
ok | ok |
SELECT *, setting persisted off at CREATE |
ok | Code: 36 |
The union does not come from my guard being bypassed. The sink serializes the Iceberg-derived type (IcebergWrites.cpp:951), so the writer receives a bare Tuple even though system.columns reports Nullable(Tuple(y Int64)); the pre-existing Nullable arm never fires, my wrapper sees a record, and the reader's target is still bare. Exposure needs enable_nullable_tuple_type = 1 (default 0) plus that column type plus the setting persisted off, and it is a loud error rather than silent corruption.
On your two options I am taking neither in this PR, for one reason: getFieldType returning a bare container is also, on unmodified master, silent data loss. A genuine NULL in that column reads back as (0) with IS NULL false, identically on both arms. Rejecting the write would leave that untouched, and fixing the reader here would mean choosing a representation for an optional Array/Map, whose targets cannot be Nullable at all, so those stay unreadable at = 0 by construction on master today. That is a different change from emitting the spec-correct marker, so a fix task is created for the derivation, covering both the NULL loss and the = 0 readability, and this PR now discloses the narrowed regression window explicitly.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 33/34 (97.06%) · Uncovered code |
|
Follow-up on the reader-derivation root cause this PR's description defers ("The reader derivation is the root cause and is tracked separately"). I investigated it and I am stopping short of a PR, because the fix turns out to need a design decision that is yours, not mine. One root site. Four measured consequences, all on unmodified master (
The Iceberg metadata is written correctly in every case ( Why I am asking instead of pushing. Three sound fixes exist with different compatibility consequences, and picking one decides how far
I tried restricting to the top level only, which is why I am not proposing it: the nested rows above are the same defect, so pinning them as expected behaviour would be wrong. I lean toward 2 if you want this small and safe, or 1 if Which do you want? I will implement whichever you pick. Note files already written keep the corrupted payload either way. @ alesapin @ scanhex12 |
|
Hi @alesapin @scanhex12, gentle ping on the design question above (#112648 (comment)): it never reached you, because the handles there were written with a space and so notified nobody. Which of the three options do you want for optional complex fields in the Iceberg writer - derive |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes an Iceberg table whose write format is
Avroserializing a field declared"required": falsewhose type is alist,maporstructas required, with no["null", T]union, so that the data file's own schema disagreed with the table metadata and other Iceberg readers saw a required field. Such a field is now written as the["null", T]union the Iceberg spec uses for an optional one.Description
AvroSerializer::createSchemaWithSerializeFnemits a["null", T]union only forNullableandVariant, so Avro nullability came purely from the type carrying aNullablewrapper. The Iceberg read layer never puts that wrapper on a container:IcebergSchemaProcessor::getFieldTypecallsmakeNullableonly on the scalar branch, while the complex branch returns a bareArray/Map/Tupleregardless of the field's ownrequiredbit. An optional container's optionality is therefore unrecoverable from the type.This is the Avro half of #111775, which fixed the same defect for ORC and added the per-path metadata this consumes.
The fix adds
createFieldSchemaWithSerializeFn, used at the four sites that own a field (top-level column, tuple field, array element, map value). It consults that metadata and wraps the built schema in["null", T], unless the schema is already a union or null, so the union is added exactly once per path.getIcebergTypepublishesrequired: truefor ClickHouse-authored containers, so the carrier is normally an externally authored schema written by ClickHouse with'Avro'. The one exception isNullable(Tuple), the only container ClickHouse DDL can declare optional. Field ids are unchanged and plainFORMAT Avrooutput is byte-identical.At the default
input_format_null_as_default = 1such a file reads back unchanged. With the setting off the read throwsCannot insert Avro Union(Null, T) into non-nullable type T, becausegetFieldTypederives a bare container for an optional complex field, the standing reader limitation Spark-written files already hit. For aNullable(Tuple)column it is a change: master wrote a bare record, readable at either value, so withenable_nullable_tuple_type = 1(default off) and the setting persisted off atCREATE, a read that worked now errors. Optional element, value and field positions are unaffected, their targets beingNullable. The reader derivation is the root cause and is tracked separately.Validation: per-field nullability in the written file's schema, master vs fix
Fixture: hand-written
v1.metadata.jsonwith optional and required containers,CREATE TABLE IF NOT EXISTS ... ENGINE = IcebergLocal(dir, 'Avro'), one INSERT. Values read out of the written file'savro.schemaheader entry.req_intrequired intopt_intoptional intopt_listoptional listopt_mapoptional mapopt_structoptional structreq_list/req_map/req_structrequiredlist_opt_elem.element,map_opt_val.value,opt_struct.syoptionallist_opt_struct_elem.elementoptional structstruct_opt_list_field.inneroptional listmap_opt_struct_val.valueoptional structEach of the four call sites is pinned separately: reverting one at a time to
createSchemaWithSerializeFnmoves a disjoint set of reference lines, the top-level site movingopt_list/opt_map/opt_struct, and the array-element, tuple-field and map-value sites moving one nested line each. All 13 Iceberg field ids are byte-identical between the arms, and the test also pins them at depth: not descending through the union drops four nested-id lines. 50/50 green, and 20/20 green undercompatibility='20.1', the regime whose pre-21.1input_format_null_as_defaultdefault the read-back pin defends.Version info
26.8.1.487(included in26.8and later)