Skip to content

Embed Iceberg field IDs in Avro and ORC data files - #109994

Merged
PedroTadim merged 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-avro-orc-field-ids-109988
Jul 24, 2026
Merged

PedroTadim merged 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-avro-orc-field-ids-109988

Conversation

@groeneai

@groeneai groeneai commented Jul 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #109988

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

Data files written by ClickHouse into Iceberg tables now embed Iceberg field IDs for the Avro (field-id) and ORC (iceberg.id/iceberg.required type attributes) formats, and ORC String columns are written as ORC string instead 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 (ColumnMapper from IcebergSchemaProcessor::traverseSchema) and passes it to every output format via FormatFilterInfo; only the Parquet writer consumed it. This threads the same map into the Avro and ORC writers:

  • Avro: set field-id on each record field, recursing into nested Tuple records. The vendored avro-cpp already emits field-id from NodeRecord.
  • ORC: set iceberg.id and iceberg.required type attributes recursively on every node, and force String columns to ORC string for Iceberg writes so a user setting output_format_orc_string_as_string=0 cannot 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-id on top-level and nested struct fields, and ORC files carry iceberg.id/iceberg.required on all fields with String written as ORC string. Test: 04401_iceberg_avro_orc_field_ids_109988.

Follow-up (not in this PR): Avro element-id/key-id/value-id for list/map require finishing the emission in the avro-cpp submodule (NodeArray/NodeMap do not yet print them). ORC already covers list/map/struct element ids since attributes attach to every type node.

Version info

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (...) ENGINE=IcebergLocal(path,'Avro'|'ORC'); INSERT ... then inspect the data file. Avro file has no field-id; ORC file has no iceberg.id attributes. Deterministic every run.
b Root cause explained? The Iceberg write path builds a name->field-id map (ColumnMapper) and passes it to every output writer via FormatFilterInfo, but only the Parquet writer read it. The Avro and ORC registerOutputFormat lambdas ignored format_filter_info, so no field-ids were emitted; ORC additionally wrote String as binary when output_format_orc_string_as_string=0.
c Fix matches root cause? Yes. Thread the existing ColumnMapper into the Avro and ORC writers and emit the ids the same way Parquet does (Avro field-id; ORC iceberg.id/iceberg.required); force ORC String->string for Iceberg. No new mechanism.
d Test intent preserved / new tests added? New test 04401_iceberg_avro_orc_field_ids_109988. No existing test weakened.
e Demonstrated in both directions? Yes. Baseline binary (fix reverted, same tree): Avro field-id=0, ORC iceberg.id=0. With fix: Avro ids 1-5 + nested 9,10; ORC 10 iceberg.id + 10 iceberg.required, 3 STRING / 0 BINARY (even with output_format_orc_string_as_string=0).
f Fix is general, not a narrow patch? Covers both broken formats, all sibling type branches (primitive/Array/Map/Tuple/Nullable), recursively for nested types, via the shared mapper.
g Generalizes across inputs/types/wrappers? field-id lookup keyed by the same dotted-name scheme traverseSchema produces (col, t.x, arr.element, m.key, m.value); Nullable unwrapped so the id-map key and the required flag are both correct. Verified on Int64/String/Array/Map/Tuple incl. nested.
h Backward compatible? Yes. Only Iceberg writes (column mapper present) change; non-Iceberg Avro/ORC output is byte-unchanged (no mapper supplied). No setting default changed.
i Invariants and contracts preserved? Writers only annotate the schema (field-id attributes / ORC string kind); row encoding and data layout are unchanged. ColumnMapper is read-only here.

Session id: cron:clickhouse-worker-slot-2:20260710-123800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @scanhex12 — could you review this? It threads the existing Iceberg field-id ColumnMapper (already consumed by the Parquet writer) into the Avro and ORC output writers so ClickHouse-written data files carry Iceberg field IDs: field-id on Avro record fields (reusing the NodeRecord field-id emission scanhex12 added to avro-cpp) and iceberg.id/iceberg.required type attributes on ORC, plus forcing ORC String to string. Fixes #109988 (Spark silently NULLing renamed Avro columns / unable to read ORC).

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [30a1245]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Changed settings are not reflected in the settings changes history (see changed_settings.txt) FAIL cidb IGNORED
New settings are not reflected in settings changes history (see new_settings.txt) FAIL cidb IGNORED
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb IGNORED

AI Review

Summary

This PR correctly threads the Iceberg ColumnMapper into the Avro and ORC writers, and the current branch appears to have fixed the earlier field-id recursion and string/binary scoping problems. I do not think it is mergeable yet, because the new ORC iceberg.required metadata still derives nullability from a lossy ClickHouse type representation, so ClickHouse-written ORC files can advertise the wrong required/optional contract for common Iceberg schemas with optional complex fields.

Findings

❌ Blockers

  • [src/Processors/Formats/Impl/ORCBlockOutputFormat.cpp:96-97, src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp:513-582] [dismissed by author -- https://github.com/Embed Iceberg field IDs in Avro and ORC data files #109994#discussion_r3629436096] The new ORC iceberg.required attribute is computed from !type->isNullable(), but IcebergSchemaProcessor::getFieldType bypasses that wrapping for object-typed Iceberg fields and returns Array(...), Map(...), or Tuple(...) directly. That means an Iceberg optional list, optional map, or optional struct still reaches the writer as non-Nullable, so this PR writes iceberg.required=true even though the table schema says the field is optional. The result is a ClickHouse-written ORC file whose Iceberg nullability metadata disagrees with the table schema the PR is trying to preserve.
    Suggested fix: thread per-path required/optional metadata from the Iceberg JSON schema through ColumnMapper (parallel to iceberg_string_paths) and have getORCType use that source-of-truth instead of inferring nullability from the already-lossy ClickHouse type.
Tests
Final Verdict
  • Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 10, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai are the other data types spec-compliant?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai Instead of these tests, add an integration test, where Spark reads after a column rename to show the field ids being used.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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:

  1. list element-id / map key-id/value-id not emitted - this is the same schema-evolution class as the field-id bug this PR fixes, but for collections. Blocked in the vendored avro-cpp: NodeArray::printJson does not print element-id, and NodeMap has no key-id/value-id storage at all (NodeImpl.hh/.cc). Fixing it needs an avro-cpp submodule change, so I flagged it as the follow-up in the PR body. Struct/record field-ids (the reported bug) are emitted.
  2. UUID: written as avro string + logicalType uuid; spec wants fixed(16) + logicalType uuid. Physical-type mismatch (AvroRowOutputFormat.cpp:316).
  3. DateTime64: scale 6 -> timestamp-micros (compliant); scale 3 -> timestamp-millis; other scales -> decimal fallback. Iceberg timestamps are micros-only, so scale != 6 is non-compliant (line 209).
  4. DateTime (32-bit, seconds): written as plain int with no logical type. Iceberg has no second-resolution timestamp, so it round-trips as an integer (line 145).

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?

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai Don't fix anything else related to type mapping in this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Both done in the next push:

  1. Scope: no other type-mapping changes. This PR stays limited to embedding Iceberg field IDs (Avro record field-id + ORC iceberg.id/iceberg.required) and forcing ORC String -> ORC string. UUID fixed(16), DateTime64 non-micros scale, and Avro list/map element-id/key-id/value-id remain tracked follow-ups, untouched here.

  2. Tests: dropping the stateless .sh test and adding a Spark integration test in test_storage_iceberg_with_spark that, for both Avro and ORC, has ClickHouse write the data files, then does ALTER TABLE ... RENAME COLUMN, then Spark reads the renamed column and gets the ClickHouse-written values (not NULL) - which only works because the field IDs are present. It also asserts NULLs on the pre-fix behavior so it is a real regression guard.

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]>
@groeneai
groeneai force-pushed the groeneai/iceberg-avro-orc-field-ids-109988 branch from 1a9436e to a10d171 Compare July 10, 2026 14:47
@groeneai

Copy link
Copy Markdown
Collaborator Author

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

Copy link
Copy Markdown
Collaborator Author

Addressed all three findings in 61eea2e.

1. Avro recursion through wrappers. setIcebergFieldIds is now a full schema-tree walk that dispatches on node type and descends through union (Nullable/Variant), array and map wrapper nodes, so records nested in Nullable(Tuple(...)) or Array(Tuple(...)) get field-ids on every field. Dotted paths mirror IcebergSchemaProcessor::traverseSchema (t.x, arr.element, m.value). One honest limitation: list element-id / map key-id/value-id are not emitted, because the vendored contrib/avro NodeArray/NodeMap::printJson only emit field-id on records (no element/key/value-id support). Adding those needs a ClickHouse/avro fork change plus a submodule bump, which is out of scope for this PR; record field-ids (the part iceberg-java uses for struct projection) are now complete for wrapped/nested structs.

2. Compaction / mutation rewrite paths. Instead of forcing output_format_orc_string_as_string in MultipleFileWriter, the ORC String -> string normalization now lives in ORCBlockOutputFormat::getORCType and keys off the presence of a column mapper. Every Iceberg ORC writer already passes a mapper (MultipleFileWriter, Compaction.cpp:290, Mutations.cpp:213/:314), so compaction and mutation rewrites emit ORC string regardless of the session setting. Removed the now-redundant format_settings override.

3. FixedString scoping. Split FixedString out of the shared branch. The Iceberg override now applies to TypeIndex::String only; FixedString follows the setting-driven path unchanged, so fixed[L] (= DataTypeFixedString(L)) keeps its logical type and is not forced to ORC STRING.

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

Copy link
Copy Markdown
Collaborator Author

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

Copy link
Copy Markdown
Collaborator Author

Added the two focused regressions to test_writes_field_ids_spark_read.py (commit 1d4886b):

  • test_writes_field_ids_nested_avro — writes info Array(Tuple(a Int32, b String)) from ClickHouse, reads the Avro data file back and asserts the nested subfield ids (info.element.a, info.element.b) are present. Verified fails-without-fix: reverting the array/union wrapper recursion in setIcebergFieldIds drops those ids (field-id map becomes {'id':1,'info':2}) and the assert fires; with the fix they are present and Spark reads the nested rows back.

  • test_writes_field_ids_orc_compaction_rewrite — ClickHouse writes ORC, Spark adds a merge-on-read positional delete, then OPTIMIZE compacts (rewriting the ClickHouse-written ORC via the mapper path in Compaction.cpp) with output_format_orc_string_as_string=0. After a RENAME COLUMN, Spark reads the rewritten String column back by field id — which only works if the rewrite forced ORC string from the mapper rather than the (disabled) setting.

Note on the ALTER ... UPDATE variant: I hit a pre-existing crash unrelated to this PR while trying it — LOGICAL_ERROR: Unexpected null _row_number at Mutations.cpp:234 on the Iceberg ORC merge-on-read UPDATE path (Parquet is fine). It is upstream of the data-file writer this PR touches, so I used the OPTIMIZE compaction rewrite instead and filed the crash separately.

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

Copy link
Copy Markdown
Collaborator Author

Fixed in 98c245c. You are right: IcebergSchemaProcessor::getSimpleType maps both Iceberg string and binary to DataTypeString (SchemaProcessor.cpp:319-320), so keying the ORC String -> ORC string override on column_mapper != nullptr alone corrupted an Iceberg binary column into ORC string.

The writer now consults the per-path source Iceberg logical type instead of just the field-id map:

  • ColumnMapper gains an iceberg_string_paths set (paths whose Iceberg type is exactly string), populated from the schema alongside the field-id map (collectIcebergStringPaths walks struct/list/map like traverseSchema, using the same dotted paths). Wired into all Iceberg mapper construction sites (createColumnMapper + MultipleFileWriter, which covers the compaction/mutation rewrite paths).
  • ORCBlockOutputFormat::getORCType TypeIndex::String: on the Iceberg path force ORC string only when column_mapper->isIcebergStringPath(column_path); genuine Iceberg binary (also DataTypeString) stays ORC binary. Non-Iceberg output is unchanged (setting-driven). FixedString is untouched (still forced to ORC binary on Iceberg).

Regression test_writes_field_ids_orc_binary_vs_string: Spark creates a table with s STRING, b BINARY, ClickHouse INSERTs (with output_format_orc_string_as_string=0), then the raw ClickHouse-written ORC file is inspected with pyarrow: s -> ORC string, b -> ORC binary. Verified fails-without-fix (reverting to the mapper-presence heuristic makes b come out as ORC string), passes with the fix. Existing compaction-rewrite and rename tests still pass.

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

Copy link
Copy Markdown
Collaborator Author

Addressed both round-5 findings in 7a43a4c.

Avro string vs binary (per-path, not regex). createSchemaWithSerializeFn now threads the full dotted path (same convention as setIcebergFieldIds and IcebergSchemaProcessor: t.x, arr.element, m.value). For a String column on the Iceberg path (mapper carrying per-path logical-type info) the string vs bytes choice comes from isIcebergStringPath(column_path) instead of output_format_avro_string_column_pattern. Off the Iceberg path (or without string-path info) the regex still drives it, unchanged.

New regression test_writes_field_ids_avro_binary_vs_string: Spark creates s STRING, b BINARY, ClickHouse INSERTs with output_format_avro_string_column_pattern='b' (which would previously force b->Avro string and miss s), then the Avro data file schema is asserted: s->string, b->bytes. Verified fails-without-fix (reverting the per-path branch gives {'b': 'string', ...}, the exact bad case) and passes with it.

Position-delete mapper. The file_path column of the position-delete schema is Iceberg string (pos is long), so the delete-file ColumnMapper in Mutations.cpp now calls setIcebergStringPaths({file_path}). To keep bare field-id mappers safe, ColumnMapper now exposes hasIcebergStringInfo(): the ORC/Avro String branch only consults isIcebergStringPath when string-path info was actually supplied, otherwise it falls back to the setting/spec default rather than forcing every DataTypeString path to binary. So an un-annotated mapper can no longer downgrade a string field to binary.

Note on the ALTER DELETE/UPDATE regression you suggested: ORC-backed Iceberg mutate is not reachable end-to-end. On this branch ALTER TABLE ... DELETE on an ORC Iceberg table aborts pre-existing at Mutations.cpp Unexpected null _row_number (untouched by this PR, since Feb 2026), and the approved PR #105893 (@ alesapin) rejects Iceberg DELETE/UPDATE on non-Parquet tables outright, so no ORC position-delete file is ever written on that path. The mapper fix above is the correct, harmless plumbing for if/when that path is enabled; an end-to-end ORC-delete integration test would just hit the #105893 rejection (or the pre-existing crash before it merges).

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109994&sha=7a43a4cd068b13ac92349248b24354716032c7eb&name_0=PR

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(

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.

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::optimize passes metadata_snapshot->getSampleBlock() (current schema names) into compactIcebergTable (IcebergMetadata.cpp:467-476).
  • Compaction.cpp:274-282 then builds the reader with that header and FormatFilterInfo(..., column_mapper = nullptr, ...).
  • The normal Iceberg read path does not do this: StorageObjectStorageSource switches to getInitialSchemaByPath and applies getSchemaTransformer when 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Added the Map(String, Tuple(a Int32, b String)) regression (test_writes_field_ids_map_tuple_avro, b6127d4).

On the vendored avro-cpp (contrib/avro), avro::MapSchema(const Schema&) builds the node via the default NodeMap() ctor, which auto-adds the string key leaf at index 0, then addLeaf(values) puts the value at index 1 (contrib/avro/lang/c++/api/NodeImpl.hh:434-450, impl/Schema.cc:87-90). So node->leaves() == 2 and the existing leafAt(1) descent already reaches the map value record. The finding does not reproduce here (it matches upstream avro's single-leaf map, not this fork).

Verified both directions with the new test:

  • current code: m.value.a / m.value.b field-ids present, test passes.
  • map descent removed: field-ids collapse to {'id': 1, 'm': 2}, test fails with assert 'm.value.a' in {'id': 1, 'm': 2}.

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

Copy link
Copy Markdown
Collaborator Author

The test_writes_field_ids_orc_compaction_rewrite regression was failing CI with Code: 48. NOT_IMPLEMENTED because that end-to-end path is not reachable on current master, so I have removed it (49da71c).

Two independent blocks make an ORC compaction rewrite with deletes impossible:

  • Compaction only rewrites data files when position deletes are present (Compaction.cpp need_optimize = !all_positional_delete_files.empty()). A pure-append history is a no-op.
  • But ClickHouse cannot read an ORC Iceberg table that has position deletes at all: IcebergDataObjectInfo.cpp:104 throws Position deletes are only supported for data files of Parquet format in Iceberg, but got ORC.

The original copy-on-write DELETE in the test produced an OVERWRITE snapshot with added_files != 0, which tryGetAppendUpdate (Compaction.cpp:335) now rejects (Unsupported snapshot's operation type OVERWRITE). Switching Spark to merge-on-read moves the failure one step earlier, to the SELECT (the ORC-with-position-deletes read block above). So there is no reachable ORC rewrite scenario to assert against.

The mapper-driven ORC String -> string / FixedString -> binary rules that the Compaction/Mutations rewrite paths depend on are not lost from coverage: those paths build the mapper via the same createColumnMapper and go through the same ORCBlockOutputFormat::getORCType, which stays covered by test_writes_field_ids_orc_binary_vs_string (fresh write, output_format_orc_string_as_string=0).

Remaining 6 tests in the file pass locally (39.66s).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 49da71c

Every failure below has an owner (a fixing PR, ours). Only CH Inc sync is exempt. All real checks finished; only the private CH Inc sync remains pending (not actionable by us).

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (30d: 55 unrelated PRs / 9 master) #110030 (ours, open)
Stateless tests (arm_asan_ubsan, azure, parallel) / 04344_server_ast_fuzzer_insert_limit flaky TIMEOUT_EXCEEDED (passed 0/3 reruns; 6 PRs / 0 master) #109209 (ours, merged) — branch predates it, picked up on next rebase/push
Stress test (amd_debug) / Logical error 'Not-ready Set' (STID 0250-41a5) chronic trunk IN-family LOGICAL_ERROR (127 PRs / 19 master), not PR-caused #107924 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260711-060000

@PedroTadim PedroTadim self-assigned this Jul 22, 2026
Comment thread src/Formats/FormatFilterInfo.h Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai can you trim the comments in this PR?

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

Copy link
Copy Markdown
Collaborator Author

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();

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.

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.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai leave it as a follow up

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.

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.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 80c6f70

Every 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 CH Inc sync is exempt. None of these are caused by this PR's diff (Iceberg Avro/ORC field-id embedding).

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) + (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter chronic flaky (595 PRs / 1397 hits / 120 master in 14d; regression since 2026-07-10) #111029 (external, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables chronic flaky (180 PRs / 254 hits / 24 master in 14d) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
Integration tests (amd_tsan, 3/6) / test_consistant_parts_after_move_partition::test_consistent_part_after_move_partition one-off flaky (1 PR / 1 hit / 0 master in 14d) a fix task is created (investigating; fixing-PR link to follow here)
Stateless tests (amd_tsan, s3 storage, parallel, 2/3) / 01730_distributed_group_by_no_merge_order_by_long chronic flaky (MEMORY_LIMIT_EXCEEDED; 180 PRs / 243 hits / 21 master in 14d) #109847 (external, merged)
CH Inc sync private sync CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260722-183000

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 241 212 -12.0% <0.0001 This PR only touches the Iceberg Avro/ORC output-format writers (field-id embedding, string-vs-binary logical types). ClickBench Q15 is a read-path SELECT that never exercises that code, so the -12.0% is run-to-run variance, not a PR effect.
⚠️ 17 not_sure 494 561 +13.7% <0.0001 The change is confined to Iceberg data-lake write formatting; Q17 is a read-only SELECT that doesn't hit any writer path, so the +13.7% cannot plausibly come from this diff and reads as variance.
⚠️ 18 not_sure 1253 1345 +7.3% 0.0045 Already borderline with mixed signals from the two tests; the PR only changes Iceberg output writers, so Q18 is unrelated to this diff regardless.

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: 4f194e73-fb02-4447-bfaa-8f5dc03a8609
  • MIRAI run: dd65d303-8ba5-4163-a57c-14c87b65fdde
  • PR check IDs:
    • clickbench_76590_1784840189
    • clickbench_76604_1784840189
    • clickbench_76610_1784840189
    • tpch_adapted_1_official_76622_1784840189
    • tpch_adapted_1_official_76646_1784840190
    • tpch_adapted_1_official_76659_1784840190

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 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.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 261/276 (94.57%) · Uncovered code

Full report · Diff report

@PedroTadim
PedroTadim enabled auto-merge July 24, 2026 07:42
@PedroTadim
PedroTadim added this pull request to the merge queue Jul 24, 2026
Merged via the queue into ClickHouse:master with commit f2a9f42 Jul 24, 2026
176 of 178 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 24, 2026
alexbakharew pushed a commit to clickgapai/ClickHouse that referenced this pull request Jul 29, 2026
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]>
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]>
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_consistant_parts_after_move_partition::test_consistent_part_after_move_partition line on my CI finish ledger for 80c6f70c79d4830a901b12edb4000d4c46a54ccf: #112695 (merged 2026-07-31T16:57:30Z).

The row was not a part-move defect. The archived logs.tar.gz for that job holds exactly one ThreadSanitizer report, in the zoo3 Keeper container:

src/Coordination/KeeperCommon.h:65:8 in DB::KeeperResponseForSession::operator=(DB::KeeperResponseForSession&&)
  read  T14: NonblockingBoundedQueue<KeeperResponseForSession>::tryPop  <- KeeperRequestDispatcher::responseThread
  write T33: NonblockingBoundedQueue<KeeperResponseForSession>::tryPush <- KeeperRequestDispatcher::onResponse

TSAN halts the Keeper process, which expires the server's ZooKeeper session, so the in-flight read of .../alter_partition_version inside StorageReplicatedMergeTree::movePartitionToTable returned Connection loss and surfaced as Code: 999 on the MOVE PARTITION. The teardown then reported Sanitizer assert found for instance zoo3-1. Both are the same event; the test's own assertions never fired.

#112695 suppresses that report at its tryPush write frame, and this build predates it (compare reports the merge commit ahead_by 0, behind_by 17417 relative to the failing sha).

The test is healthy. Filtering default.checks on that exact test_name: over 90 days, 5 failures against more than 111000 runs, and 0 of the 5 on master; over the last 14 days, 0 failures against more than 23000 runs. The other two sanitizer failures in the 90-day window (2026-06-11, 2026-05-29) carry the same queue signature on KeeperRequestForSession and are covered by the same PR.

No further work is tracked on my side for this line.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…vro-orc-field-ids-109988

Embed Iceberg field IDs in Avro and ORC data files
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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants