Skip to content

Read Iceberg tables whose optional schema-id and sort-orders fields are absent - #130071

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:iceberg-optional-schema-id-129991
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:iceberg-optional-schema-id-129991

Conversation

@groeneai

@groeneai groeneai commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #129991
Related: #100304
Related: #130028
Related: #117112

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

Fixed reading Iceberg tables written by Iceberg older than 0.12 (for example by Spark 2.4) and tables whose snapshots have no schema-id: a format version 1 schema or manifest header schema without schema-id, a snapshot without (or with a null) schema-id, and format version 1 metadata without sort-orders were rejected with BAD_ARGUMENTS or POCO_EXCEPTION.

Description

On 26.10.2.103 (also 26.3 LTS), SELECT count() FROM icebergLocal('iceberg_partitioned') on Apache Impala's Spark 2.4 test table fails with Cannot parse Iceberg table schema: 'schema-id' field is missing in schema. (BAD_ARGUMENTS); Impala returns 20. A snapshot without schema-id gives POCO_EXCEPTION (#100304).

Root cause: these fields are optional for old writers, but the readers require them.

Change, with the defaults of the Java reader:

  • parseCurrentTableSchema picks schemas + current-schema-id, else the legacy schema, whose missing id is 0 (on a copy). Also used for the sort key; the Glue catalog reads the legacy schema the same way.
  • A snapshot without schema-id is not bound to a schema: its data files keep the schema of their manifest, and its table schema (time travel) is the current one, as SnapshotUtil.schemaFor.
  • A format version 1 manifest header schema without schema-id takes the header schema-id key, else 0 if it matches the metadata.json schema 0, else an internal id derived from its fields: files written before a rename or a drop and re-add of a column are read with their own schema (ORC reads by name). Cluster function workers register it from the manifests.
  • Format version 1 metadata without sort-orders is unsorted.

The open #117112 overlaps this, but sets schema-id on the cached metadata object and still requires sort-orders.

Writes and maintenance commands still require v2-shaped metadata.

Validation: 05569_iceberg_optional_schema_id (Impala's iceberg_partitioned, the same files as in #130028, an ORC copy of three of them, and modified copies of the PyIceberg corpus table, also through icebergLocalCluster) fails on master and passes with the fix. In #130028's 05700, 5 of 15 tables now pass; the other 10 stop at #129989.


Workflow [PR]
Sync PR [sync-upstream/pr/130071]

groeneai and others added 3 commits November 8, 2026 02:01
…absent

Iceberg writers older than 0.12 (e.g. Spark 2.4, the Apache Impala test
tables) write format version 1 metadata with only the legacy `schema`, which
has no `schema-id`, manifest headers whose `schema` has no `schema-id`,
snapshots without `schema-id`, and no `sort-orders`. Snapshots without
`schema-id` are also legal in format version 2. All of these are optional in
the spec, but `parseTableSchemaV1Method`,
`traverseMetadataAndFindNecessarySnapshotObject`,
`createIcebergDataSnapshotFromSnapshotJSON`, `ManifestFileIterator::create`
and `IcebergMetadata::getSortingKey` required them, so such tables failed with
BAD_ARGUMENTS or POCO_EXCEPTION.

Use the defaults of the Java reader:
- `parseCurrentTableSchema` returns `schemas` + `current-schema-id` when
  `schemas` exists (or format version >= 2), else the legacy `schema`; a
  missing id means schema 0 (`SchemaParser`). The id is set on a copy because
  the parsed metadata object is shared through the metadata files cache.
  The helper also serves the sort key and `GlueCatalog`'s timestamp lookup.
- A snapshot without `schema-id` (absent or null) is not registered in the
  schema processor: a fabricated binding would be persistent and would throw
  on re-binding after a schema evolution, while unregistered snapshots already
  read their data files with the schema of their manifest. The snapshot's own
  table schema (time travel, manifest list pruning) is the current schema, as
  `SnapshotUtil.schemaFor`.
- A format version 1 manifest header schema without `schema-id` takes the
  header `schema-id` key, else 0. Format version 2/3 still require it.
- Format version 1 metadata without `sort-orders` is unsorted
  (`SortOrder.unsorted()`).
- `system.iceberg_metadata_log_entries` treats a null snapshot `schema-id`
  as absent.

Writes and maintenance commands are unchanged: they support only
v2-shaped metadata and keep failing closed on legacy metadata.

The test vendors Impala's `iceberg_partitioned` table unmodified (the same
25 files as ClickHouse#130028) and modifies copies of the PyIceberg corpus table.

Closes ClickHouse#129991

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test now checks three things that it did not observe before:
- for snapshots whose `schema-id` is absent or null, the per-file
  `schema_id` of `system.iceberg_files` (the data files keep the schema of
  their manifest, ids 0, 1 and 2, the same as for the unmodified table);
- for the legacy `schema` with a sort order, `system.tables.sorting_key`
  (`id`; the table without `sort-orders` has none). One read of each table
  is needed first, because the Iceberg sort order reaches the table metadata
  on a read;
- in the Glue gtest, that the legacy `schema` of the input metadata is not
  given a `schema-id` (the id is set on a copy).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove two comments that restate the code below them, shorten the manifest schema-id comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, head d9b5f40)
Finding Verdict
⚠️ Snapshot test cannot tell manifest schema ids from current-schema binding AGREE, fixed: system.iceberg_files.schema_id assertion
⚠️ Legacy sorted case does not assert the sort key AGREE, fixed: system.tables.sorting_key assertion
⚠️ Glue gtest does not prove the cached metadata is unmodified AGREE, fixed: assert the original schema has no schema-id
⚠️ Header-only manifest schema-id branch untested DISAGREE: no writer emits it (Java and PyIceberg write no header schema-id; ClickHouse writes it equal to the embedded id)
💡 v2/v3 manifest with neither id still fails with POCO_EXCEPTION noted: the spec requires the id there
💡 INSERT into v1 metadata without sort-orders noted: writes still require v2-shaped metadata
💡 A legacy schema evolved by a pre-0.12 writer is schema 0 in every metadata version, so a long-lived table that sees two such versions gets the existing ICEBERG_SPECIFICATION_VIOLATION noted: master rejects these tables on every read

Round 2 re-review of the fix: no findings.

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? SELECT count() FROM icebergLocal('<Impala iceberg_partitioned>'): BAD_ARGUMENTS on master, 26.10.2.103 and 26.3.60.2; 20 with the fix.
b Root cause explained? Optional fields of old writers (v1 schema id, v1 manifest header schema id, snapshot schema-id, v1 sort-orders) are read as required by readers that bypass the v1/v2 dispatch.
c Fix matches root cause? Each reader treats the field as optional with the Java default (id 0, current schema for the snapshot, unsorted); the cached metadata object is not modified.
d Test intent preserved / new tests added? New 05569_iceberg_optional_schema_id (real Spark 2.4 table; legacy schema with a sort order, asserting system.tables.sorting_key; v2 snapshots with absent/null schema-id incl. time travel, asserting the per-file schema_id of system.iceberg_files; system.iceberg_metadata_log_entries) and a Glue gtest case that also asserts the input metadata is not modified; existing tests unchanged.
e Both directions demonstrated? Fails on master, passes with the fix; 16 mutation arms each fail their case (reverting any one edit, binding id-less snapshots to the current schema, dropping the sort order of every v1 table). 50/50 randomized runs pass.
f Fix is general across code paths? All readers of these fields: table schema, snapshot traversal (incl. time travel), snapshot state, manifest open, sort key (also the write caller), system.iceberg_metadata_log_entries, Glue timestamp lookup. Write/maintenance paths stay v2-only.
g Fix generalizes across inputs (params/datatypes/wrappers)? Absent and JSON null ids; v1 manifest with and without the header schema-id key (v2/v3 manifests still need it, as the spec requires); empty, non-empty and absent sort orders.
h Backward compatible? (maintainer-approved exception only) Yes: metadata that carries the fields takes the unchanged paths; no setting or format change.
i Invariants and contracts preserved? The shared cached metadata JSON stays immutable (copy before set); no fabricated snapshot-to-schema binding, so no re-binding error across metadata versions.

Session id: cron:clickhouse-impl-slot-5:20261108-024800

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @SmitaRKulkarni @arsenmuk, could you review this and add the can be tested label so CI runs? The Iceberg readers now treat schema-id (legacy v1 schema, v1 manifest header schema, snapshots) and v1 sort-orders as optional with the Java defaults (schema 0, current schema, unsorted) instead of failing with BAD_ARGUMENTS or POCO_EXCEPTION, without modifying the cached metadata object.

@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0abfd7c]

Summary: ✅


AI Review

Summary

Reviewed #130071 at 0abfd7c92b9da49f678c8ea2afaefcaaa458a354. The change reads legacy Iceberg schemas and snapshots without schema-id, preserves distinct manifest schemas, and treats missing v1 sort-orders as unsorted. The previous ordinary-read and cluster-worker findings are addressed. Two compaction findings remain, including a data-corruption path; approval is blocked. Both already have inline threads, so no duplicate comments were posted.

Findings

❌ Blockers

  • Compaction.cpp:365, reached through the new registration at ManifestFileIterator.cpp:476: Data compaction does not preserve the file schema. [dismissed by author -- https://github.com/Read Iceberg tables whose optional schema-id and sort-orders fields are absent #130071#discussion_r4505733866] The thread was silently resolved, but writeDataFiles still passes the current schema and mapper to every input reader, without applying the per-file schema transformation. An upgraded v2 table retaining an id-less legacy ORC manifest with a renamed top-level column therefore writes default values instead of its stored values. With the added ORC fixture, dropping and re-adding the same name can instead copy the dropped field's values into the new field. A position-delete file targeting a separate Parquet file activates the rewrite of every collected data file; successful commitment then deletes the originals at Compaction.cpp:1720. This remains real because v2-shaped metadata passes the guards and the ORC top-level reader still matches names. Apply the file schema and transformation during compaction, or reject files requiring evolution before writing.

⚠️ Majors

  • Compaction.cpp:707, reached through ManifestFileIterator.cpp:476: Manifest compaction cannot resolve synthesized schema identities. Existing unresolved finding. A valid v2 table can retain legacy v1 manifests whose id-less schemas differ from metadata schema 0. They now receive negative IDs, and consolidation groups files by those IDs, but get_schema_object_by_id searches only the metadata schemas array. Any actual consolidation of such a group throws ICEBERG_SPECIFICATION_VIOLATION. Preserve the registered manifest schema through the rewrite and give it a valid external identity; substituting the current schema would lose the evolution distinction.
Tests
  • ⚠️ Add a stateless regression using an upgraded legacy ORC table with a renamed column and a position delete confined to a separate Parquet file. Verify identical values before and after OPTIMIZE TABLE, or verify a safe rejection with unchanged files. Include the fixture's dropped-and-re-added column case.
  • ⚠️ Add a manifest-compaction regression with two retained id-less manifests sharing an old schema, v2 metadata, and iceberg_insert_single_manifest_for_all_partitions = 1. Run OPTIMIZE TABLE ... MANIFEST with a threshold that forces consolidation, then verify the rows. The new test covers reads but neither compaction path.
Performance & Safety

The negative schema-ID representation was traced through these consumers:

  • IcebergIterator, initial-schema lookup, schema transformation, column mapping, and cluster-task serialization: IDs remain signed; workers register unknown negative IDs from manifests before reading. The earlier cluster finding is addressed.
  • Partition/min-max/runtime-filter pruning, identity-partition projection, and ManifestColumnStatistics: lookups use the registered file schema. Lazy materialization rejects files whose schema differs from the table schema.
  • system.iceberg_files: internal negative IDs are exposed as the legacy default 0. Snapshot traversal leaves absent/null snapshot IDs unbound; time travel selects the current table schema.
  • Mutation validation, partition deletion, snapshot expiry, and orphan-file traversal consume manifest handles and retain file paths. Manifest consolidation and data-file rewriting require the fixes above; handling the new representation only in read hooks does not cover these writers.
Final Verdict

Status: ❌ Block

Preserve per-file schema semantics during data compaction, support synthesized schemas during manifest consolidation, and add the two focused regressions above.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. can be tested Allows running workflows for external contributors labels Nov 8, 2026
…wn id

A format version 1 manifest written before Iceberg 0.12 has no `schema-id`
in its header schema, and that schema is the one its data files were written
with. Defaulting it to 0 made a manifest written before a rename (or before a
drop and re-add of a column with the same name) share the id 0 of the current
legacy `schema`; the conflict tolerance then kept the metadata.json schema, so
no schema transformation was applied. Parquet still read correctly through
the field ids, but ORC is read by name: a renamed column came back empty and
a re-added column showed the values of the dropped one.

Such a schema now keeps 0 only if metadata.json binds 0 to the same fields,
and otherwise gets a negative internal id, one per distinct schema, so the
files are read with their own schema and transformed to the table schema.
The choice and the registration happen under one mutex, so concurrent reads
of the same table agree on the ids. The ids stay internal to the reader:
`system.iceberg_files.schema_id` shows 0 for them, the default of a schema
without an id, and cluster reads are unaffected because the initiator ships
the schema transformation to the workers.

The ORC fixture is three data files of the vendored Impala table rewritten as
ORC with the same manifest layout (pyarrow + avro); the test renames `user`
and drops and re-adds it in a copy of both tables.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
if (header_schema_id.has_value())
schema_object->set(f_schema_id, *header_schema_id);
else if (manifest_format_version == 1)
schema_processor.addIcebergTableSchemaWithoutId(schema_object);

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.

[Major] Handle synthesized schema IDs in manifest compaction as well.

A table upgraded from an old writer to format version 2 can retain v1 manifests without schema-id, while its metadata has valid schemas, current-schema-id, partition specs, and sort orders. If a retained manifest schema differs from metadata schema 0, this call now assigns it a negative ID. writeConsolidatedManifestFile groups data files by that resolved_schema_id, but its get_schema_object_by_id searches only the metadata's schemas array. When compaction actually consolidates such a group, it therefore throws Iceberg metadata does not contain a schema entry matching schema-id -1 at Compaction.cpp:949.

This also affects v2-shaped metadata, so the stated restriction on writing legacy metadata does not exclude it. Please preserve the manifest schema through the rewrite and serialize it with a valid external schema identity; substituting the current schema would reintroduce the rename/drop-and-readd problem. A focused test can upgrade an evolved legacy fixture to v2 metadata, retain two manifests with the same old schema, and run OPTIMIZE TABLE ... MANIFEST with iceberg_insert_single_manifest_for_all_partitions = 1 before checking the rows again.

@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0abfd7c92 with master ffc535ce4 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

9 object files changed (+69.90 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFileIterator.cpp.o 559.10 KiB 593.56 KiB +34.46 KiB (+6.16%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp.o 905.66 KiB 935.46 KiB +29.80 KiB (+3.29%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

53 translation units recompiled, 422 s compile time in total, 53 of them have a recent master baseline.

Job report

… `schema-id`

The internal negative id of an id-less format version 1 manifest schema
was a counter, known only to the server that read the manifest. A
cluster function worker does not read the manifests, so a column read
of such a file failed there with `Schema with id -1 is unknown` (or, on
a worker that had walked the manifests for lazy materialization in
another order, could bind the id to another schema).

The id is now derived from the fields of the schema, so every server
gives a schema the same id, and a server that meets an unknown negative
id walks the manifests of the snapshot it reads to register it, as lazy
materialization does. Reading with the table schema 0 instead is not
enough: ORC and Avro files, and Parquet files without field ids, are
read by column name.

05569 reads the evolved Parquet and ORC copies through
`icebergLocalCluster` with lazy materialization disabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bbca130

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
Upgrade check (amd_release) / Unknown job error infra, not from this PR: during a GitHub outage the previous-release tag lookup (get_gh_api on api.github.com/repos/ClickHouse/ClickHouse/releases) got a 503 and then read timeouts, and gave up after about one minute of retries, so the check stopped before any test ran #112974 (mine, open)
PR praktika rollup of the row above #112974 (the owner above)

Session id: cron:our-pr-ci-monitor:20261108-123006

@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 19, 2026
…hema-id-129991

Conflicts resolved:
- `GlueCatalog.cpp`: master removed the timestamp type lookup through
  metadata.json (`getCurrentSchemaFieldTypes`) and now reads the current
  schema with `getCurrentSchema` + `loadCurrentSchema`. The legacy v1
  `schema` without `schema-id` now goes through `parseTableSchemaV1Method`
  there, so `loadCurrentSchema` gets schema 0 instead of a POCO exception.
- `gtest_glue_timestamp_type.cpp` was deleted on master; its legacy v1 case
  moved to `gtest_glue_schema_columns.cpp`.
- `IcebergMetadata.cpp`: master dropped `updateLastColumnId`; kept the
  optional `schemas` handling.
- `gtest_iceberg_schema_processor.cpp`: kept the tests of both sides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
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 comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg: optional schema-id is required: v1 metadata without schema-id and snapshots without schema-id cannot be read (POCO_EXCEPTION)

1 participant