Repository navigation
Embed Iceberg field IDs in Avro and ORC data files - #109994
PedroTadim merged 12 commits into
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260710-123800 |
|
cc @Avogar @scanhex12 — could you review this? It threads the existing Iceberg field-id |
|
Workflow [PR], commit [30a1245] Summary: ❌
AI ReviewSummaryThis PR correctly threads the Iceberg Findings❌ Blockers
Tests
Final Verdict
|
There was a problem hiding this comment.
@groeneai Instead of these tests, add an integration test, where Spark reads after a column rename to show the field ids being used.
|
Checked the Avro and ORC writer type mappings against the Iceberg spec (Appendix A). Summary: ORC (getORCType, ORCBlockOutputFormat.cpp): compliant for every supported type. iceberg.id/iceberg.required are attached recursively to every node, and physical types match the spec: BOOLEAN, INT (Int8/16/32, IPv4, UInt<=32), LONG (Int64/UInt64), FLOAT, DOUBLE, DATE (Date/Date32), TIMESTAMP (DateTime/DateTime64), DECIMAL(P,S) (Decimal32/64/128), STRING (String/FixedString, now forced on the Iceberg path). LIST/MAP/STRUCT recurse and carry ids on nested nodes too. Not-mappable CH types are BINARY fallbacks (IPv6, Int128/256, Decimal256) or unsupported (UUID hits the default branch and throws ILLEGAL_COLUMN, so no invalid file is produced). Avro (createSchemaWithSerializeFn): compliant for boolean, int (Int8/16/32, IPv4, UInt8/16), long (Int64/UInt64), float, double, string, date (int+date), decimal (bytes+decimal). Remaining gaps, in decreasing importance:
The struct/list/map field-id gap (1) is the direct extension of this fix and I can take it in a follow-up once the avro-cpp side supports element/key/value-id. (2)-(4) are pre-existing Avro type-mapping issues independent of field-ids. Want me to fold the UUID and DateTime64-scale fixes into this PR, or keep this PR scoped to field-ids and track the type-mapping gaps separately? |
|
@groeneai Don't fix anything else related to type mapping in this PR. |
|
Both done in the next push:
|
Data files ClickHouse writes into Iceberg tables violated the Iceberg spec for Avro and ORC (Parquet was already correct). Avro files carried no field-id, so after a column rename spec-compliant readers (Spark/iceberg-java) fall back to name matching and silently return NULLs for ClickHouse-written rows. ORC files carried no iceberg.id/iceberg.required type attributes, so a single ClickHouse INSERT made the table unreadable by such readers. The Iceberg write path already builds a column-name to field-id map (ColumnMapper from IcebergSchemaProcessor::traverseSchema) and passes it to every output format via FormatFilterInfo; only Parquet consumed it. Thread it into the Avro and ORC writers too: - Avro: set field-id on each record field, recursively into nested Tuple records (the vendored avro-cpp already emits field-id from NodeRecord). - ORC: set iceberg.id and iceberg.required type attributes on every node recursively, and force String columns to ORC string (not binary) for Iceberg writes so output_format_orc_string_as_string=0 cannot produce files that spec-compliant readers reject. Non-Iceberg Avro/ORC output is unchanged (no column mapper). Closes: ClickHouse#109988 Co-Authored-By: Claude Opus 4.8 <[email protected]>
1a9436e to
a10d171
Compare
|
Pushed a10d171. Replaced the stateless test with tests/integration/test_storage_iceberg_with_spark/test_writes_field_ids_spark_read.py: for both Avro and ORC, ClickHouse creates the Iceberg table, writes the data files, does ALTER TABLE ... RENAME COLUMN, and Spark then reads the renamed column and gets the ClickHouse-written values. Passes locally (2/2). No other type-mapping changes in the diff. |
…ope FixedString Address bot review on ClickHouse#109994: - Avro setIcebergFieldIds now descends through union (Nullable/Variant), array and map wrapper nodes, so records nested in Nullable(Tuple(...)) or Array(Tuple(...)) carry field-ids. Dotted paths mirror IcebergSchemaProcessor's traversal. - Drive the ORC String -> string normalization off the column mapper inside getORCType instead of forcing output_format_orc_string_as_string in MultipleFileWriter, so compaction/mutation ORC rewrites (which already pass a mapper) also emit ORC string. - Scope the Iceberg String -> string override to TypeIndex::String only; FixedString stays on the setting-driven binary/fixed path so fixed[L] columns keep their logical type. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed all three findings in 61eea2e. 1. Avro recursion through wrappers. 2. Compaction / mutation rewrite paths. Instead of forcing 3. FixedString scoping. Split Verified non-Iceberg ORC/Avro output is unchanged (no mapper), and the Iceberg path is covered by the Spark rename integration test. Kept within the "no other type-mapping changes" scope. |
output_format_orc_string_as_string defaults to true, so leaving Iceberg fixed[L] (FixedString(L)) on the setting-driven path emitted ORC STRING and lost the fixed logical type. On the Iceberg write path (column_mapper) force BINARY regardless of the setting; keep setting-driven behavior otherwise. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Fixed in a8c77e3. On the Iceberg write path (`column_mapper != nullptr`) `TypeIndex::FixedString` now forces ORC `binary` regardless of `output_format_orc_string_as_string` (which defaults to `true`), so `fixed[N]` (exposed as `DataTypeFixedString(N)`) keeps its ORC `binary` logical type. `TypeIndex::String` stays forced to ORC `string` on the Iceberg path. Non-Iceberg ORC output is unchanged (setting-driven), verified: with the setting on/off the written files still differ. This closes the tension between the two review rounds: on Iceberg, String -> ORC `string`, FixedString -> ORC `binary`; off Iceberg, both remain setting-driven. |
… regressions Cover the two behaviors the earlier patches added but the flat Spark-read test did not exercise: Avro field-id recursion through array/union wrappers (Array(Tuple)) and the mapper-driven ORC String->string rule on the compaction (OPTIMIZE) rewrite path with output_format_orc_string_as_string=0. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Added the two focused regressions to
Note on the |
Iceberg string and binary both read as ClickHouse DataTypeString (getSimpleType), so keying the ORC String -> ORC string override on column_mapper presence corrupted Iceberg binary columns into ORC string. Thread the per-path Iceberg string set into ColumnMapper and force ORC string only for genuine Iceberg string fields; Iceberg binary stays ORC binary. Add a Spark-created binary+string regression. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Fixed in 98c245c. You are right: The writer now consults the per-path source Iceberg logical type instead of just the field-id map:
Regression |
…-file mapper marks file_path as string The Avro writer picked string vs bytes from output_format_avro_string_column_pattern, which cannot tell Iceberg string from binary (both read as DataTypeString). On the Iceberg path the writer now selects from the per-path source logical type via the column mapper, mirroring the ORC fix; the regex still drives the non-Iceberg path. The position-delete-file column mapper (Mutations.cpp) now marks file_path as an Iceberg string path, and ColumnMapper distinguishes no-string-info from known-binary so a bare field-id mapper falls back to the setting instead of forcing binary. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed both round-5 findings in 7a43a4c. Avro string vs binary (per-path, not regex). New regression Position-delete mapper. The Note on the ALTER DELETE/UPDATE regression you suggested: ORC-backed Iceberg mutate is not reachable end-to-end. On this branch Full test file (6 tests) passes locally. |
| # Compaction rewrites the ClickHouse-written ORC data files (applying the | ||
| # delete). The rewrite runs with output_format_orc_string_as_string=0 to | ||
| # prove the String -> ORC string forcing is mapper-driven, not setting-driven. | ||
| instance.query( |
There was a problem hiding this comment.
OPTIMIZE here runs before the rename, so it only exercises the easy rewrite case where the file's field names still match the current sample block. The schema-evolution case on the compaction path is still missing, and the current code looks wrong there.
Concrete trace from the current branch:
IcebergMetadata::optimizepassesmetadata_snapshot->getSampleBlock()(current schema names) intocompactIcebergTable(IcebergMetadata.cpp:467-476).Compaction.cpp:274-282then builds the reader with that header andFormatFilterInfo(..., column_mapper = nullptr, ...).- The normal Iceberg read path does not do this:
StorageObjectStorageSourceswitches togetInitialSchemaByPathand appliesgetSchemaTransformerwhen the file schema id differs (StorageObjectStorageSource.cpp:953-1002,IcebergMetadata.cpp:582-602).
So after RENAME COLUMN, an OPTIMIZE still reads old files by the new column names instead of the file schema id, and can fail or rewrite default/NULL values into the compacted file. I think compaction needs the same old-schema header + schema-transformer flow as the regular Iceberg source, and this regression should rename before OPTIMIZE to cover it.
The Avro field-id writer already descends into a map's value schema (the vendored avro-cpp MapSchema builds key+value leaves, value at leafAt(1)), so Map(String, Tuple(...)) value subfields get field-ids. This adds the missing regression covering that path. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Added the On the vendored avro-cpp ( Verified both directions with the new test:
So the map path was correct but untested; the regression now covers it. |
test_writes_field_ids_orc_compaction_rewrite cannot run on current master: compaction rewrites data files only when position deletes are present (Compaction.cpp need_optimize), but ClickHouse cannot read ORC Iceberg tables that have position deletes (IcebergDataObjectInfo.cpp: position deletes are only supported for Parquet). A copy-on-write DELETE instead produces an OVERWRITE snapshot with added_files != 0, which compaction now rejects (tryGetAppendUpdate: NOT_IMPLEMENTED). So there is no reachable end-to-end ORC rewrite path to exercise. The mapper-driven ORC String -> string / FixedString -> binary rules the rewrite paths rely on live in the shared getORCType + createColumnMapper code and stay covered by test_writes_field_ids_orc_binary_vs_string. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
The Two independent blocks make an ORC compaction rewrite with deletes impossible:
The original copy-on-write The mapper-driven ORC Remaining 6 tests in the file pass locally (39.66s). |
CI finish ledger — 49da71cEvery failure below has an owner (a fixing PR, ours). Only
Session id: cron:our-pr-ci-monitor:20260711-060000 |
Condense the comments added across the field-id/logical-type writer changes to the essential invariant at each site, per review feedback. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Done in 80c6f70. Trimmed the comments across the 8 changed files (net -28 comment lines), keeping only the non-obvious invariant at each site: the string-vs-binary logical-type distinction (both read as DataTypeString), the dotted-path convention, and why FixedString stays ORC binary on the Iceberg path. Comment-only, no code changes. |
| { | ||
| switch (type->getTypeId()) | ||
| /// Nullable(T) maps to the same ORC node as T; only the Iceberg `required` flag differs. | ||
| const bool required = !type->isNullable(); |
There was a problem hiding this comment.
iceberg.required is now derived from !type->isNullable(), but the Iceberg schema layer already drops optionality for object-typed fields. IcebergSchemaProcessor::getFieldType returns getComplexTypeFromObject(...) immediately for any object type at src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp:451-452, so top-level Iceberg list / map / even optional struct fields are represented as Array(...), Map(...), and Tuple(...) instead of Nullable(...). The existing schema inference expectation in tests/integration/test_storage_iceberg_with_spark/test_schema_inference.py:68-70 confirms that loss.
That means a field like optional list<int> or optional struct<...> will still be rewritten with iceberg.required=true here even though the Iceberg schema says it is optional. The new ORC footer is therefore inconsistent with the table schema on any optional complex field. I think this needs per-path required/optional metadata from the Iceberg JSON schema (similar to iceberg_string_paths) instead of inferring required from the lossy ClickHouse type.
There was a problem hiding this comment.
Confirmed, and it affects this PR's own iceberg.required (ORCBlockOutputFormat.cpp:220): getComplexTypeFromObject (SchemaProcessor.cpp:451-452) returns Array/Map/Tuple without a surrounding Nullable, so an optional list/struct reaches the writer non-Nullable and !type->isNullable() emits iceberg.required=true for it. Same lossy-CH-type class as the string-vs-binary fix (Iceberg string and binary both collapse to DataTypeString).
The correct fix mirrors iceberg_string_paths: thread per-path required/optional from the Iceberg JSON schema into ColumnMapper and consult it here, falling back to !isNullable() only when absent.
That is a new per-path metadata mechanism, so it is a scope call under the "no other type-mapping changes" limit on this PR. @PedroTadim in #109994, or a follow-up? I have filed a tracked task and can implement either way; defaulting to follow-up so this PR is not expanded further without your call.
There was a problem hiding this comment.
Will do. I'll open a separate follow-up PR for the optional-complex-field iceberg.required fix once #109994 merges (the iceberg.required code only exists on this branch, so there is no master base for a standalone PR yet), and link it back here.
There was a problem hiding this comment.
Follow-up PR opened: #111775 — it threads per-path required/optional metadata from the Iceberg schema into the ORC writer (mirroring iceberg_string_paths), so optional list/map/struct fields are no longer emitted as iceberg.required=true.
CI finish ledger — 80c6f70Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260722-183000 |
…ro-orc-field-ids-109988
…ro-orc-field-ids-109988
|
📊 Cloud Performance Report ✅ AI verdict: This PR changes only the Iceberg Avro/ORC output-format writers (embedding field IDs and preserving the string-vs-binary logical-type distinction). That code runs solely on Iceberg data-lake writes and is never touched by the ClickBench SELECT read path. The flagged deltas on Q15 (-12.0%) and Q17 (+13.7%), plus the borderline Q18, therefore cannot be attributed to this change and are consistent with run-to-run variance, so all three are marked not_sure. The private and public diffs are identical, so this reasoning applies to both. 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
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 261/276 (94.57%) · Uncovered code |
f2a9f42
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]>
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]>
|
Fixing PR for the The row was not a part-move defect. The archived TSAN halts the Keeper process, which expires the server's ZooKeeper session, so the in-flight read of #112695 suppresses that report at its The test is healthy. Filtering No further work is tracked on my side for this line. |
…ope FixedString Address bot review on ClickHouse#109994: - Avro setIcebergFieldIds now descends through union (Nullable/Variant), array and map wrapper nodes, so records nested in Nullable(Tuple(...)) or Array(Tuple(...)) carry field-ids. Dotted paths mirror IcebergSchemaProcessor's traversal. - Drive the ORC String -> string normalization off the column mapper inside getORCType instead of forcing output_format_orc_string_as_string in MultipleFileWriter, so compaction/mutation ORC rewrites (which already pass a mapper) also emit ORC string. - Scope the Iceberg String -> string override to TypeIndex::String only; FixedString stays on the setting-driven binary/fixed path so fixed[L] columns keep their logical type. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…vro-orc-field-ids-109988 Embed Iceberg field IDs in Avro and ORC data files
Closes: #109988
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Data files written by ClickHouse into Iceberg tables now embed Iceberg field IDs for the Avro (
field-id) and ORC (iceberg.id/iceberg.requiredtype attributes) formats, and ORCStringcolumns are written as ORCstringinstead of binary. Previously only Parquet embedded field IDs, so spec-compliant readers (e.g. Spark/iceberg-java) silently returned NULLs from ClickHouse-written Avro rows after a column rename, and could not read ClickHouse-written ORC files at all.Description
The Iceberg write path already builds a column-name to field-id map (
ColumnMapperfromIcebergSchemaProcessor::traverseSchema) and passes it to every output format viaFormatFilterInfo; only the Parquet writer consumed it. This threads the same map into the Avro and ORC writers:field-idon each record field, recursing into nestedTuplerecords. The vendored avro-cpp already emitsfield-idfromNodeRecord.iceberg.idandiceberg.requiredtype attributes recursively on every node, and forceStringcolumns to ORCstringfor Iceberg writes so a user settingoutput_format_orc_string_as_string=0cannot produce files that spec-compliant readers reject (binary to string is not an allowed promotion).Non-Iceberg Avro/ORC output is unchanged (no column mapper is supplied).
Verified end-to-end: ClickHouse-written Avro files now carry
field-idon top-level and nested struct fields, and ORC files carryiceberg.id/iceberg.requiredon all fields withStringwritten as ORCstring. Test:04401_iceberg_avro_orc_field_ids_109988.Follow-up (not in this PR): Avro
element-id/key-id/value-idfor list/map require finishing the emission in the avro-cpp submodule (NodeArray/NodeMapdo not yet print them). ORC already covers list/map/struct element ids since attributes attach to every type node.Version info
26.8.1.70(included in26.8and later)