Repository navigation
Fix ORC iceberg.required for optional complex (list/map/struct) fields - #111775
PedroTadim merged 5 commits into
Conversation
The Iceberg ORC writer derived the Iceberg `required` flag from the ClickHouse type: `required = !type->isNullable()`. But a complex container (list/map/struct) is never wrapped in Nullable in the ClickHouse type (only leaf scalars get makeNullable in IcebergSchemaProcessor), so an Iceberg optional list/map/struct arrived as a non-Nullable Array/Map/Tuple and was wrongly emitted as iceberg.required=true, leaving the ORC footer inconsistent with the table schema. Thread per-path required/optional metadata from the Iceberg JSON schema into ColumnMapper (iceberg_optional_paths + hasIcebergRequiredInfo), collected in IcebergSchemaProcessor alongside collectIcebergStringPaths, wired through a shared createColumnMapperFromFields builder used by both createColumnMapper (reads, mutations, compaction) and the MultipleFileWriter INSERT path. ORCBlockOutputFormat::getORCType consults the per-path flag when present, else falls back to !isNullable() for non-Iceberg writes. ORC only: the Avro writer emits no iceberg.required. Follow-up to ClickHouse#109994. Co-Authored-By: Fable <[email protected]>
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 5 findings across 1 full pass + 1 fix round + 1 delta recheck; final content re-reviewed clean, 0 findings).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-4:20260724-094900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-4:20260724-094900 |
|
cc @arsenmuk @al13n321 — could you review this? Follow-up to #109994: the ORC Iceberg writer derived |
|
Workflow [PR], commit [29d54a6] Summary: ❌
AI ReviewSummaryThis PR correctly fixes the Findings❌ Blockers
Final Verdict
|
| /// optionality is not recoverable from the type: consult the per-path Iceberg metadata when | ||
| /// present, else fall back to the type (also for non-Iceberg writes and field-id-only mappers). | ||
| bool required = !type->isNullable(); | ||
| if (column_mapper && column_mapper->hasIcebergRequiredInfo()) |
There was a problem hiding this comment.
Supported Iceberg Avro tables still violate the same optional-complex invariant this patch is fixing for ORC. IcebergSchemaProcessor::getFieldType never wraps list/map/struct nodes in Nullable (SchemaProcessor.cpp:614-622), and AvroRowOutputFormat::createSchemaWithSerializeFn only emits ["null", T] unions for TypeIndex::Nullable (AvroRowOutputFormat.cpp:334-372). That means ENGINE = IcebergLocal(..., 'Avro') still serializes optional complex fields as required even though the new iceberg_optional_paths metadata is now available. Please either thread the optional-path check into Avro schema generation too, or reject Iceberg Avro writes until optional complex nullability can be preserved.
There was a problem hiding this comment.
Confirmed, this is a real sibling defect. AvroRowOutputFormat::createSchemaWithSerializeFn emits a ["null", T] union only for TypeIndex::Nullable, and Iceberg optional complex fields arrive as non-Nullable containers (only leaf scalars get makeNullable), so IcebergLocal(..., 'Avro') serializes them as required. The iceberg_optional_paths metadata this PR adds is reachable there (the Avro writer already consults the mapper for isIcebergStringPath, and column_path is threaded with the same element/value/field-name convention), so alternative (a) (thread the optional-path check into the Array/Map/Tuple schema cases) is the correct fix. I'll do (a), not (b): Avro writes work today for scalar-optional and required-complex fields, so rejecting all Iceberg Avro writes would regress existing users.
Handling it as a separate follow-up rather than expanding this PR: it is a distinct writer mechanism (Avro schema union vs ORC footer attribute), and it has the same base dependency this PR did on #109994 (iceberg_optional_paths is introduced here and absent on master), so the follow-up branches from master once this merges. Tracked; I'll link the follow-up PR on this thread when it opens.
There was a problem hiding this comment.
Follow-up opened: #112648
Alternative (a), as stated: the four sites that own a path (top-level column, tuple field, array element, map value) consult isIcebergOptionalPath and wrap the built schema in ["null", T], skipping a schema that is already a union or null so the union is added exactly once per path. The container arms are unchanged, and plain FORMAT Avro output is byte-identical since no mapper is supplied there.
One scope correction to my earlier note. getIcebergType publishes required: true for ClickHouse-authored Array/Map/Tuple columns, and Nullable(Array)/Nullable(Map) are not constructible types, so a table created purely from ClickHouse DDL has no optional-container field to get wrong. The carrier is an externally authored schema that ClickHouse then writes to, which is what the test fixture builds.
CI finish ledger — 2a7f2c6...Every failure below has an owner. Not caused by this PR's diff (ORC
Session id: cron:our-pr-ci-monitor:20260724-203000 |
…c-required-optional-complex
| , schema(schema_) | ||
| , stats(schema_) | ||
| , column_mapper(std::make_shared<ColumnMapper>()) | ||
| , column_mapper(Iceberg::createColumnMapperFromFields(schema_)) |
There was a problem hiding this comment.
The same lost-optional-complex invariant still leaks into the Iceberg Parquet writer. MultipleFileWriter now builds iceberg_optional_paths for every data-file write, but ParquetBlockOutputFormat still passes only getStorageColumnEncoding() into convertSchema (src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp:63), and prepareColumnNullable is still the only code that can make a group OPTIONAL (src/Processors/Formats/Impl/Parquet/PrepareForWrite.cpp:498-515). prepareColumnTuple / prepareColumnArray / prepareColumnMap still hard-code their container groups as REQUIRED (src/Processors/Formats/Impl/Parquet/PrepareForWrite.cpp:562, 608, 661), so ENGINE = IcebergLocal(..., 'Parquet') continues to serialize optional list/map/struct fields as required because IcebergSchemaProcessor never wraps those containers in Nullable.
Please thread the full mapper (or at least iceberg_optional_paths) into convertSchema / prepareColumnTuple / prepareColumnArray / prepareColumnMap, and use it to mark those groups OPTIONAL when the Iceberg path is optional, the same way this patch now does for ORC.
There was a problem hiding this comment.
Confirmed. Against f073a72: prepareColumnTuple/Array/Map (PrepareForWrite.cpp:562/608/661) hard-code container groups REQUIRED, only prepareColumnNullable emits OPTIONAL, and convertSchema (ParquetBlockOutputFormat.cpp:64) gets only the field-id map, so the new iceberg_optional_paths never reaches Parquet schema generation. Real, same class as the ORC fix here, distinct writer.
Taking alternative (a): thread iceberg_optional_paths into convertSchema and the Tuple/Array/Map preparers to mark those groups OPTIONAL on optional Iceberg paths (with the matching definition-level handling). Not (b) blanket-reject: Parquet writes work today for scalar-optional and required-complex, so rejecting would regress existing users.
Separate follow-up, not this PR (keeping #111775 ORC-only, matching the Avro sibling I already split off). iceberg_optional_paths reaches master only when #111775 merges, so the Parquet follow-up branches from post-#111775 master. I will link it here when it opens.
There was a problem hiding this comment.
As promised: the Parquet follow-up is #112669. It threads the iceberg_optional_paths information into convertSchema and the Tuple/Array/Map preparers, and, because the reader takes its max definition level from the schema while the writer takes the level bit width from the state built on the data path, it passes the same information to both encoder paths and adds the matching definition level below each newly OPTIONAL group.
CI finish ledger — f073a72Every failure below has an owner. Not caused by this PR's diff (ORC
Session id: cron:our-pr-ci-monitor:20260725-030000 |
…d-optional-complex
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes the ORC/Iceberg write path (deriving iceberg.required from the Iceberg schema instead of ClickHouse Nullable-ness); ClickBench is entirely read-only SELECTs that never touch that code. Across all flagged queries CPU time is flat while wall time drifts (-16.6% on Q4, +6-7% on Q32/Q33/Q34), which is the signature of shared-host variance, not a PR effect. The deterministic no_change/not_sure verdicts are correct and none of these deltas can be attributed to the change. No action needed on performance grounds. clickbenchFlagged queries (3 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…d-optional-complex
CI finish ledger — 86dbc36Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
CI is complete on this commit: the Notably the Session id: cron:our-pr-ci-monitor:20260727-190000 |
…d-optional-complex
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 161/161 (100.00%) · Uncovered code |
CI finish ledger - 29d54a6Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
#110935 targets exactly this signature. Its approach is under discussion with the Not PR-caused: this pull request only changes the Iceberg ORC writer's Head Session id: cron:our-pr-ci-monitor:20260728-163000 |
1395284
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.
An Iceberg field declared "required": false whose type is a complex container (list/map/struct) was serialized to Parquet with FieldRepetitionType::REQUIRED, so the footer contradicted the Iceberg schema published by the same commit. Spec-compliant external readers (Spark, Trino, pyiceberg) reject that. The optionality is not recoverable from the ClickHouse type: DataTypeArray and DataTypeMap both report canBeInsideNullable() == false, and the Iceberg schema builder returns a bare container while applying makeNullable only to leaf scalars. So prepareColumnArray, prepareColumnTuple and prepareColumnMap each hard-coded their group REQUIRED, and the only producer of OPTIONAL, prepareColumnNullable, is unreachable for them. ColumnMapper already carries the recovered bit as iceberg_optional_paths and the ORC writer already consumes it; the Parquet writer threaded only the field-id map. This cannot be a schema-only flip. The reader derives its max definition level purely from the schema while the writer derives the RLE level bit width from the state the data path builds, so raising the schema's OPTIONAL count alone desynchronizes them and the file becomes structurally unreadable. Both paths are now given the same IcebergOptionality: the schema path through convertSchema, and both the serial and the parallel encoder path in ParquetBlockOutputFormat. When a container's dotted Iceberg path is marked optional the group becomes OPTIONAL and one definition level is added below it, strictly after updateRepDefLevelsForArray: that function encodes an empty container as level 0, and level 0 under an OPTIONAL ancestor means "null container" to a reader, so incrementing afterwards shifts empty-but-present to 1 and leaves 0 free. A Nullable that already supplies the OPTIONAL level for the same path suppresses the extra one, since Nullable is transparent in Iceberg field naming. With no mapper, or a mapper carrying only field ids, the writer keeps its current behavior, which Iceberg position-delete writes rely on. The new stateless test asserts per-leaf definition levels through pyarrow across both encoders, with a required-container half as the control. pyarrow is the oracle rather than a ClickHouse round-trip because ClickHouse's reader normalizes a null container to an empty one, so a round-trip cannot see the ordering error the increment position guards against. Map keys, every repeated level and optional scalars are asserted unchanged and the values round-trip identically, so this only corrects metadata. No new or changed setting, so no SettingsChangesHistory.cpp entry. Files written by older versions keep their REQUIRED groups and stay readable. Related: ClickHouse#111775 Related: ClickHouse#109994 Co-Authored-By: Claude Fable 5 <[email protected]>
Related: #109994
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Description
Follow-up to #109994 (bot review finding).
ORCBlockOutputFormat::getORCTypederived the Icebergrequiredflag from the ClickHouse type:required = !type->isNullable(). ButIcebergSchemaProcessornever wraps a complex container (Array/Map/Tuple) inNullable(only leaf scalars getmakeNullable), so an Icebergoptional list/map/structreached the writer as a non-Nullable container and was emitted asiceberg.required=true.Same lossy-type class as the string-vs-binary finding on #109994: the ClickHouse type cannot recover the Iceberg optionality, so the writer must consult per-path metadata from the Iceberg schema. This mirrors the existing
iceberg_string_pathsmechanism:ColumnMappergainsiceberg_optional_paths+hasIcebergRequiredInfo()/isIcebergOptionalPath().IcebergSchemaProcessor::collectIcebergOptionalPathscollects the optional paths (dotted conventiont.x/arr.element/m.key/m.value, readingelement-required,value-required, and each struct field'srequired; map key is always required).createColumnMapper(covers reads, mutations, compaction) and theMultipleFileWriterctor.getORCTypeuses the per-path flag when the mapper has the info, else falls back to!isNullable().ORC only: the Avro writer emits no
iceberg.required. Non-Iceberg ORC output is unchanged (no column mapper supplied).Test:
gtest_write_orc_iceberg_requiredwrites a block for a schema with optional/requiredlist/map/struct(including a nestedlist<struct>) throughORCBlockOutputFormat, reads the ORC footer back, and assertsiceberg.requiredper path.iceberg.requiredis a physical ORC footer attribute not observable from SQL, so a unit test (likegtest_write_parquet_page_index) is used.Version info
26.8.1.337(included in26.8and later)