Skip to content

Fix Iceberg ADD COLUMN reusing a nested field id when last-column-id is too small - #128525

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-add-column-too-small-last-column-id
Nov 3, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-add-column-too-small-last-column-id

Conversation

@groeneai

@groeneai groeneai commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128455
Related: #110884

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 ALTER TABLE ... ADD COLUMN on Iceberg tables created by ClickHouse 26.6 or older: the new column could get the field id of an existing nested field (an Array element, a Map key or value, a Tuple element), and the table could no longer be read (Duplicate field id). New field ids now start after the largest id used by any schema of the table. Closes #128455.

Description

On 26.8.34.13 (also 26.7.22.4, 26.9.25.15, 26.10.2.103), ALTER TABLE ... ADD COLUMN on an Iceberg table created by 26.3 or 26.6 gives the new column an id that a nested field already has, and every later read fails with Duplicate field id 3. (ICEBERG_SPECIFICATION_VIOLATION). Measured with the official images: (id Int64, arr Array(Int64)) created on 26.6.8.7 or 26.3.42.3, then ADD COLUMN on each newer version.

26.3 and 26.6 wrote last-column-id as the number of top-level columns (2 here, while arr.element has id 3). #110884 fixed that for new tables, but generateAddColumnMetadata still allocates from the stored value.

New ids now start after max(last-column-id, largest field id of every schema in schemas, nested ids included), and last-column-id is updated to the new largest id. All schemas, not only the current one, because a dropped column keeps its ids in older schemas and in old data files. IcebergSchemaProcessor::getMaxFieldId collects only the ids, reusing the time field id walk (now a shared visitor with checkStackSize), so a top-level column named a.b cannot hide the id of field b of a tuple a.

The first version of #110884 had this upgrade path for the current schema; it was dropped in review (#110884 (comment)). This issue is the upgrade case that needs it.

Validation:

  • The new test writes a metadata version with the 26.6 last-column-id, as the issue asks (same technique as 04337_iceberg_schema_id_reuse_across_versions), and reads it through a second table. Its Array, Map, dropped-Tuple and a.b cases all reuse an id on master (Duplicate field id 3) and pass with the fix, 50/50 with random settings. A walk over the current schema only fails the dropped case; a path-keyed one fails a.b.
  • Tables created by the official 26.6 and 26.3 images are readable after ADD COLUMN on the fixed build.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1203-master (included in 26.11 and later)

…small

ClickHouse 26.3 and 26.6 wrote `last-column-id` as the number of top-level
columns, ignoring the ids of nested fields (list element, map key/value,
struct children). `generateAddColumnMetadata` took the next id from that
value, so the first `ALTER TABLE ... ADD COLUMN` on a newer version gave the
new column an id that a nested field already had, and every later read
failed with `Duplicate field id N (ICEBERG_SPECIFICATION_VIOLATION)`.
Measured with official images: a table created by 26.6.8.7 or 26.3.42.3,
then altered by 26.8.34.13.

New ids now start after max(`last-column-id`, the largest field id of every
schema in `schemas`, nested ids included). All schemas, not only the current
one, because a dropped column keeps its ids in older schemas and in old data
files. The walk reuses `IcebergSchemaProcessor::traverseSchema`, the same
walk the reader uses to map field ids, and `traverseComplexType` gets a
stack-size check because it now also runs over historical schemas that no
read has parsed.

ClickHouse#110884 fixed `last-column-id` for new tables; its first version also had
this upgrade path for the current schema, which was dropped during review
(ClickHouse#110884 (comment)).
Issue ClickHouse#128455 is the measured upgrade case that needs it.

Closes ClickHouse#128455.

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

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 ❌ The path-keyed traverseSchema map can hide an id when a literal a.b column collides with nested a.b (MetadataGenerator.cpp:146) DISAGREE Such a schema is invalid Iceberg: Iceberg Java IndexByName and pyiceberg reject "multiple fields for name a.b", and ClickHouse's reader already fails SELECT * on it before any ALTER. Master allocates the same id, so nothing regresses.
2 ❌ No check that new ids stay below the reserved bound 2147483447 (MetadataGenerator.cpp:530) DISAGREE The spec forbids such ids in table schemas, and ids are allocated sequentially from 1, so the bound needs about 2.1e9 assigned ids. The unchecked increment is unchanged from master.
3 💡 The test has no Map case DISAGREE The change has no per-shape branch; Map measured locally both ways (master reuses m.key id 3, fix assigns 6).
4 💡 The reader's last-column-id bound still reads the stored value DISAGREE Each data file is mapped with its own manifest schema, so the bound is not consulted there (the test's SELECT after DROP passes); the first fixed ADD COLUMN also repairs the value.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261101-213800

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's two-process reproducer with last-column-id lowered to 2 fails every time on master (Duplicate field id 3), and so does the real upgrade with the official images: created on 26.6.8.7 or 26.3.42.3, ADD COLUMN on 26.7.22.4, 26.8.34.13, 26.9.25.15 or 26.10.2.103.
b Root cause explained? 26.3/26.6 wrote last-column-id as the top-level column count; generateAddColumnMetadata allocates the next id from it, so the new column takes an id a nested field already has, and the reader rejects the duplicate on every read.
c Fix matches root cause? Yes. The allocator starts after the largest id of every schema (nested ids included) and updates last-column-id, which also repairs the table for later writers. Nothing changes on the read side.
d Test intent preserved / new tests added? New stateless test: the issue's reproducer plus a dropped-Tuple case. No existing test touched.
e Both directions demonstrated? Yes. The new test fails on master and passes with the fix (50/50 with random settings). A walk over the current schema only fails the dropped-column case, so that case is what requires all schemas.
f Fix is general across code paths? generateAddColumnMetadata is the only place that assigns ids for an existing table. Table creation already records the max nested id, MODIFY only allows primitive promotions (no new ids), DROP/RENAME assign nothing, and the catalog path sends the same generated schema.
g Fix generalizes across inputs (params/datatypes/wrappers)? Array element, Map key/value and Tuple fields at any depth come from the same walk the reader uses. Test: Array and Tuple; Map(String, Array(Int64)) checked separately (master reuses the key id 3; the fix assigns 6).
h Backward compatible? (maintainer-approved exception only) Yes. For tables with a correct last-column-id the ids are unchanged. No setting, no format change.
i Invariants and contracts preserved? A new field id is now larger than every id the table ever assigned, and last-column-id stays the largest assigned id. The added checkStackSize only turns a stack overflow on a pathologically deep schema into TOO_DEEP_RECURSION.

Session id: cron:clickhouse-impl-slot-7:20261101-210900

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @SmitaRKulkarni, could you review this and add the can be tested label so CI runs? New Iceberg field ids now start after the largest id of every schema instead of the stored last-column-id, which 26.3/26.6 wrote without nested ids, so ADD COLUMN on 26.8+ made those tables unreadable (#128455); this brings back the upgrade path I dropped from #110884 in review.

@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e5f9b02]

Summary: ✅


AI Review

Summary

Reviewed PR #128525 at e5f9b02504989923e941b9b7587c40024f986550. It fixes ALTER TABLE ... ADD COLUMN on legacy Iceberg tables by allocating beyond both last-column-id and all retained schemas' field IDs, including nested fields. No actionable findings remain after reviewing the current code and prior discussion. The regression test passed 50/50 in targeted CI at df5838bdb; the subsequent shared-walker refactor was reviewed from source. Tests were not run locally because this checkout has no ClickHouse binary or build directory.

Final Verdict

Status: ✅ Approve. No new inline findings.

@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. labels Nov 1, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e5f9b0250 with master f27411a0a (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of ab781ea76; 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

5 object files changed (+23.20 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.cpp.o 532.48 KiB 554.27 KiB +21.79 KiB (+4.09%)

719 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

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

Job report

@PedroTadim PedroTadim self-assigned this Nov 2, 2026
@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai two things on the new getLastAssignedFieldId:

1. Ids can still be lost when a column name contains a dot. The helper takes the max over IcebergSchemaProcessor::traverseSchema. That function returns a map keyed by the dotted field path, so two fields with the same path end up in one entry. traverseSchema writes the nested ids first and then result[cur_name] = field_id for the top-level field, so a top-level column literally named t.a overwrites the id of a inside a Tuple t:

t     Tuple(a Int64)    -> id 1, nested t.a -> id 3
`t.a` Nullable(Int64)   -> id 2
last-column-id = 2

result["t.a"] ends up as 2, so the max is 2. ADD COLUMN then assigns 3, which t.a inside t already uses. That's the duplicate id this PR is meant to prevent. Spark and other writers accept dotted names, so such tables can show up. A small recursive walker that only collects ids (for example a getMaxFieldId next to traverseComplexType) avoids the collision. It also avoids building path strings for every field of every historical schema on each ALTER.

2. The test doesn't reproduce an upgraded table. It lowers last-column-id on a server that has already loaded the correct value for this table, and the in-memory last column id only grows. So the server never runs with the too-small value a fresh server would read from a real old table. Re-loading the table after the rewrite, with a DETACH/ATTACH or a second table over the same path, would cover that.

A related question: the read path still passes the stored last-column-id to the Parquet field-id bound check. Could a fresh server reading old data files of a dropped nested column hit ICEBERG_SPECIFICATION_VIOLATION there? If so, taking the max once when the metadata is parsed would fix reads and ADD COLUMN together.

`getLastAssignedFieldId` took the max over `traverseSchema`, which keys ids
by dotted path, so a top-level column named `a.b` overwrote the id of field
`b` of a tuple `a` and that id could be assigned again. A small recursive
walk now collects only the ids, without building a path for every field of
every schema. The stack-size check moves to it from `traverseComplexType`.

The test now reads the lowered `last-column-id` through a second table over
the same path, as a newer server opening an old table does, and covers a
`Map` column and the dotted-name case.

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

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, both changed in df5838b.

  1. Confirmed on the previous head: with a Tuple(b Int64) (id 1, its b id 3), a top-level `a.b` Int64 (id 2) and last-column-id 2, ADD COLUMN got id 3. getMaxFieldId, next to traverseComplexType, now collects only the ids (it has the checkStackSize now), and the test covers this case.
  2. After lowering last-column-id, the test now creates a second table over the same path and runs the ALTER and the reads there. I also added a Map(String, Array(Int64)) case. All four cases reuse an id on master and pass with the fix, 50/50 with random settings.

On the read path: no. I measured it with this PR's release build, a fresh clickhouse local per step. The data files do carry field ids above the stored value (arr.element 3, or m.key/m.value/m.value.element 3/4/5, with last-column-id 2), and after DROP COLUMN they read fine (SELECT *, INSERT + SELECT), also with last-column-id lowered to 1, below the dropped column's own id. Each file is mapped with the schema of its manifest entry, which still has the dropped column, so the bound only sees ids missing from that schema. As a control, also removing arr from that schema makes the same read fail with ICEBERG_SPECIFICATION_VIOLATION for field_id 2. So I left the read path as is.

}
}

Int64 getMaxFieldIdOfType(Poco::JSON::Object::Ptr type)

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 you sure you can't reuse a function from somewhere to do this?

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.

Yes, there was one: collectTimeFieldIds already walked every field, list element and map key/value id. In e5f9b02 I turned it into a forEachFieldId visitor (with checkStackSize) used by both collectIcebergTimeFieldIds and getMaxFieldId, and removed getMaxFieldIdOfType.

The other walkers don't fit: traverseSchema is keyed by path (the a.b collision), and the REST catalog's collectAndValidateNestedFields throws on duplicate ids and on types getSimpleType rejects, which an old schema may still contain.

Checked: the test passes 50/50 with random settings, and a table with time at the top level, in a tuple, as a list element and as a map key reads the same values as before the change.

`collectTimeFieldIds` already walked every field, list element and map
key/value id of a schema. Turn it into a `forEachFieldId` visitor (with
`checkStackSize`) and use it both for the `time` field ids and for
`getMaxFieldId`, instead of a second recursive walker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit 87addeb Nov 3, 2026
179 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 Nov 3, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
robot-clickhouse added a commit that referenced this pull request Nov 3, 2026
…ield id when `last-column-id` is too small
robot-clickhouse added a commit that referenced this pull request Nov 3, 2026
…ield id when `last-column-id` is too small
robot-clickhouse added a commit that referenced this pull request Nov 3, 2026
…field id when `last-column-id` is too small
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #128525 to 26.10: Fix Iceberg `ADD COLUMN` reusing a nested field id when `last-column-id` is too small
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #128525 to 26.9: Fix Iceberg `ADD COLUMN` reusing a nested field id when `last-column-id` is too small
PedroTadim added a commit that referenced this pull request Nov 3, 2026
Backport #128525 to 26.8: Fix Iceberg `ADD COLUMN` reusing a nested field id when `last-column-id` is too small
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…ield id when `last-column-id` is too small
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…ield id when `last-column-id` is too small
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…field id when `last-column-id` is too small
@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 22, 2026
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg: tables created by 26.6 become unreadable after ADD COLUMN on 26.8+ (last-column-id ignores nested field ids, Duplicate field id)

6 participants