Skip to content

Fix ORC iceberg.required for optional complex (list/map/struct) fields - #111775

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-orc-required-optional-complex
Jul 29, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-orc-required-optional-complex

Conversation

@groeneai

@groeneai groeneai commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #109994

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

Follow-up to #109994 (bot review finding). ORCBlockOutputFormat::getORCType derived the Iceberg required flag from the ClickHouse type: required = !type->isNullable(). But IcebergSchemaProcessor never wraps a complex container (Array/Map/Tuple) in Nullable (only leaf scalars get makeNullable), so an Iceberg optional list/map/struct reached the writer as a non-Nullable container and was emitted as iceberg.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_paths mechanism:

  • ColumnMapper gains iceberg_optional_paths + hasIcebergRequiredInfo()/isIcebergOptionalPath().
  • IcebergSchemaProcessor::collectIcebergOptionalPaths collects the optional paths (dotted convention t.x / arr.element / m.key / m.value, reading element-required, value-required, and each struct field's required; map key is always required).
  • Wired into createColumnMapper (covers reads, mutations, compaction) and the MultipleFileWriter ctor.
  • getORCType uses 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_required writes a block for a schema with optional/required list/map/struct (including a nested list<struct>) through ORCBlockOutputFormat, reads the ORC footer back, and asserts iceberg.required per path. iceberg.required is a physical ORC footer attribute not observable from SQL, so a unit test (like gtest_write_parquet_page_index) is used.

Version info

  • Merged into: 26.8.1.337 (included in 26.8 and later)

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ⚠️ readRequiredFlag silently defaulted an absent optionality flag to required, unlike the schema parser which reads it strictly AGREE Read the flags with getValue<bool>, same as the parser; a malformed schema now throws. Added MalformedSchemaThrows.
2 ⚠️ Test used createColumnMapper while MultipleFileWriter hand-assembled the setters, so dropping the INSERT-path wiring would not fail any test AGREE Extracted a single shared createColumnMapperFromFields used by both production paths and the test.
3 ⚠️ No coverage for an OPTIONAL complex node nested inside another complex node AGREE Added nested.element.inner (optional struct in a list element); verified it fails without the fix.
4 💡 Bug Fix (stable release) overclaims — the bug is unreleased (introduced by #109994) AGREE Changed changelog category to Not for changelog.
5 ⚠️ has() guards on mandatory members (key/value/element/type) silently skip a malformed member, and for optional-paths absence means required=true AGREE Made mandatory member reads unconditional in the collector; malformed schema throws. Extended MalformedSchemaThrows to cover missing type.

Severity: ❌ blocker / ⚠️ major / 💡 nit. All findings AGREEd and fixed; final content re-reviewed with 0 findings.

Session id: cron:clickhouse-author-slot-4:20260724-094900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter=ORCIcebergRequired.* — on-demand, no randomization.
b Root cause explained? Yes. getORCType sets required = !type->isNullable(), but IcebergSchemaProcessor never wraps a complex container (Array/Map/Tuple) in Nullable, so an Iceberg optional list/map/struct arrives non-Nullable and is emitted iceberg.required=true.
c Fix matches root cause? Yes. The required flag is now sourced from per-path Iceberg metadata (mirroring iceberg_string_paths), not from ClickHouse Nullable-ness. Not a band-aid.
d Test intent preserved / new tests added? Yes. New gtest_write_orc_iceberg_required (3 tests); no existing test weakened.
e Both directions demonstrated? Yes. Reverting the getORCType override makes OptionalComplexFieldsAreNotRequired FAIL (arr/st/m/nested.element.inner emit required=true); restoring it PASSES. Build IDs recorded.
f Fix is general across code paths? Yes. Single recursive collector covers list element, map key+value, struct fields, and nested complex (list, struct-in-struct). Wired via one shared createColumnMapperFromFields used by reads, mutations, compaction, and the MultipleFileWriter INSERT path. Avro emits no iceberg.required (separate concern, not folded in). Position-delete mapper left on !isNullable() (all-required scalars — already correct).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Handles list/map/struct + arbitrary nesting; leaf scalars (Nullable and non-Nullable) both covered; map key always required per spec. Mandatory optionality members read strictly (getValue), so a malformed schema throws rather than silently defaulting to required (MalformedSchemaThrows).
h Backward compatible? Yes. No setting/format/protocol change. iceberg.required is brand-new (introduced by #109994, not in any stable release), so this only corrects a value on files this code writes. Non-Iceberg ORC output unchanged (no mapper → fallback). No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. The dotted-path convention in the collector is identical to getORCType's traversal (element/key/value/struct-field-name), matching the existing iceberg_string_paths mechanism. The new set is empty unless an Iceberg mapper sets it (hasIcebergRequiredInfo() false → fallback), so field-id-only mappers and non-Iceberg writes are untouched (asserted by NoInfoFallsBackToNullable).

Session id: cron:clickhouse-author-slot-4:20260724-094900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @arsenmuk @al13n321 — could you review this? Follow-up to #109994: the ORC Iceberg writer derived iceberg.required from ClickHouse Nullable-ness, but complex containers (list/map/struct) are never Nullable, so optional complex fields were wrongly written as required. This threads per-path optionality from the Iceberg schema into the writer, mirroring the existing iceberg_string_paths mechanism.

@PedroTadim PedroTadim self-assigned this Jul 24, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [29d54a6]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug) FAIL
Logical error: 'clock' (STID: 2508-3665) FAIL cidb IGNORED

AI Review

Summary

This PR correctly fixes the ORC writer's iceberg.required handling for optional list/map/struct fields, and the new ORC unit coverage plus all-green CI support that scoped change. I’m still at ⚠️ Request changes because the same shared ColumnMapper now carries iceberg_optional_paths into every Iceberg data-file write, but the Avro and Parquet writers still serialize optional complex containers as required, so Iceberg write correctness remains format-dependent.

Findings

❌ Blockers

  • [src/Processors/Formats/Impl/AvroRowOutputFormat.cpp:334-372] Avro still loses optionality for complex Iceberg fields. createSchemaWithSerializeFn emits bare array/map/record schemas for Array/Map/Tuple, and only wraps a schema in [null, T] when the ClickHouse type itself is Nullable. IcebergSchemaProcessor never wraps complex containers in Nullable, so ENGINE = IcebergLocal(..., 'Avro') still writes optional list/map/struct fields as required even though MultipleFileWriter now passes a mapper with iceberg_optional_paths into the formatter at src/Storages/ObjectStorage/DataLakes/Iceberg/MultipleFileWriter.cpp:30.
    Suggested fix: thread hasIcebergRequiredInfo() / isIcebergOptionalPath() through the Array/Map/Tuple branches and emit a [null, T] union when the Iceberg path is optional.
  • [src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp:63-64; src/Processors/Formats/Impl/Parquet/PrepareForWrite.cpp:500-518,562,608,661] Parquet still ignores the new optional-path metadata entirely, so optional complex Iceberg fields remain REQUIRED in the file schema. convertSchema only receives getStorageColumnEncoding(), and the only place that can mark a node OPTIONAL is prepareColumnNullable, while prepareColumnTuple / prepareColumnArray / prepareColumnMap still hard-code their container groups as REQUIRED. That means ENGINE = IcebergLocal(..., 'Parquet') still serializes optional struct/list/map containers as required because those containers are never Nullable on the ClickHouse side.
    Suggested fix: pass iceberg_optional_paths into convertSchema / the nested preparers and use it to mark the tuple/list/map groups OPTIONAL when the Iceberg path is optional, with the matching definition-level handling.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 24, 2026
/// 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())

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2a7f2c6...

Every failure below has an owner. Not caused by this PR's diff (ORC iceberg.required per-path optional metadata; ORC writer + Iceberg schema-processor only).

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error in server.log (system.metric_log_0 metadata > max_query_size -> Code 229) trunk regression (238 PRs/3d, onset 2026-07-23) fixing PR #111703 (external, MERGED 2026-07-24 17:24Z). This head (2a7f2c6, committed 11:24Z) predates the merge -> merging master to pick it up
Mergeable Check / PR rollup resolved via the owner above

CH Inc sync is still shown running (ClickHouse Inc private sync -- not actionable by us); the praktika Finish Workflow aggregator is SUCCESS and all functional/build/test jobs finished > 3h ago.

Session id: cron:our-pr-ci-monitor:20260724-203000

, schema(schema_)
, stats(schema_)
, column_mapper(std::make_shared<ColumnMapper>())
, column_mapper(Iceberg::createColumnMapperFromFields(schema_))

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 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f073a72

Every failure below has an owner. Not caused by this PR's diff (ORC iceberg.required per-path optional metadata; ORC writer + Iceberg schema-processor + gtest only). This head is the rule-3c master-merge that picked up merged external #111703.

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / Logical error: Inconsistent KeyCondition behavior (STID 5182-2f27) debug-only #90461 monotonicity canary (compiled out in release, 0 correctness impact); chronic trunk bug, ~100 unrelated PRs + master in 30d #109023 (ours, open)
Mergeable Check / PR rollup of the above resolved via #109023
CH Inc sync private sync CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260725-030000

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

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.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 32 not_sure 1322 1400 +5.9% 0.0088 +5.9% wall with flat CPU (18455 vs 18944 ms) and mixed signals from the two tests. The PR changes only ORC/Iceberg write-side code this SELECT never runs, so this is variance.
⚠️ 33 not_sure 1234 1322 +7.2% 0.0003 +7.2% sits inside the master variance band with CPU essentially unchanged. The write-path change under test cannot affect this read query, so treat as run-to-run noise.
⚠️ 34 not_sure 1239 1329 +7.3% 0.0002 +7.3% within the master band with flat CPU. Same story as Q32/Q33: the ORC/Iceberg writer edit is off-path for this SELECT, so no PR-attributable effect.

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
  • StressHouse run: bc940c66-941f-4e87-8f45-c957d9fe0637
  • MIRAI run: 0100749f-e6ee-4cf8-ace0-62c2dafd61ee
  • PR check IDs:
    • clickbench_675717_1785248757
    • clickbench_675723_1785248757
    • clickbench_675734_1785248757
    • tpch_adapted_1_official_675741_1785248757
    • tpch_adapted_1_official_675760_1785248757
    • tpch_adapted_1_official_675785_1785248757

@PedroTadim
PedroTadim enabled auto-merge July 27, 2026 13:11
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 86dbc36

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
(none) CI fully finished with no failing check at this commit —
Sync — CH Inc sync (private, not actionable)

CI is complete on this commit: the Finish Workflow aggregator finished successfully, 89 checks
succeeded, 11 were skipped, and there are zero failing, timed-out or cancelled checks. The CI
database reports 0 FAIL/ERROR rows for this commit.

Notably the Stress test (arm_debug) / Inconsistent KeyCondition behavior (STID 5182-2f27) line
from the previous ledger (covering f073a7264cd5) did not recur here; its owner #109023 is still
open, so recurrence would have been expected rather than a fix failure. The UBSan
toStartOfInterval.cpp:293 report (STID 0250-3bba) seen on the earlier head d1d50d39073b is
owned by #112045 (external, open) and also did not recur.

Session id: cron:our-pr-ci-monitor:20260727-190000

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 161/161 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 29d54a6

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Logical error: 'clock' (STID 2508-3665) trunk bug: EXPLAIN ANALYZE over a STREAM CURSOR read nested in a scalar IN subquery aborts at ExecutionThreadContext.cpp:112 on the unset clock assertion during pipeline teardown #110935 (mine, open)

#110935 targets exactly this signature. Its approach is under discussion with the
component owner, who has said he will prepare a replacement, so the eventual fix may land
under his pull request instead; either way the failure is owned and tracked, and the
final fixing-PR link will be posted here if it changes.

Not PR-caused: this pull request only changes the Iceberg ORC writer's
iceberg.required handling for optional complex fields, which cannot reach
EXPLAIN ANALYZE pipeline teardown. Message-keyed breadth over 30 days is 23 hits
across 23 distinct unrelated pull requests plus one master hit, at roughly one hit per
day, so this is a live trunk defect rather than anything introduced here.

Head 29d54a645d00 is @ PedroTadim's own commit, so I validated and ledgered only:
no push, no rebase, no master merge from me.

Session id: cron:our-pr-ci-monitor:20260728-163000

@PedroTadim
PedroTadim added this pull request to the merge queue Jul 29, 2026
Merged via the queue into ClickHouse:master with commit 1395284 Jul 29, 2026
176 of 178 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 29, 2026
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Jul 31, 2026
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.
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Jul 31, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants