Skip to content

Fix Iceberg duplicate field ids after ADD COLUMN on nested-field table - #110884

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-nested-field-id-reuse-110877
Jul 21, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-nested-field-id-reuse-110877

Conversation

@groeneai

@groeneai groeneai commented Jul 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #110877

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 Iceberg tables producing duplicate field IDs after ALTER TABLE ... ADD COLUMN when the initial schema contains nested fields (Tuple/Array/Map). last-column-id now records the maximum assigned field ID including nested children, so a subsequently added column no longer reuses a nested field ID and reads no longer fail with ICEBERG_SPECIFICATION_VIOLATION (Duplicate field id).

Description

createEmptyMetadataFile initialized last-column-id to the number of top-level columns, ignoring the nested field IDs that tuple/array/map children consume. For (id Int64, t Tuple(a Int64, b Int64)) the assigned field IDs are id=1, t=2, t.a=3, t.b=4, but last-column-id was written as 2. A subsequent ADD COLUMN c then reused id 3 (already held by t.a): the ALTER succeeded and published invalid metadata, and the next SELECT failed with Code: 743 ... Duplicate field id 3 (ICEBERG_SPECIFICATION_VIOLATION).

The fix records the max assigned field ID (counting nested children) as last-column-id, both on initial table creation (createEmptyMetadataFile) and in generateAddColumnMetadata when the added column is itself complex, so every newly added field ID is globally unique.

Repro from the issue (https://fiddle.clickhouse.com/e0c313b0-fcad-41b4-a7a1-4c27e0e8bc90); regression test 04545_iceberg_add_column_nested_field_id_reuse_110877 covers initial nested schema + scalar ADD COLUMN + complex ADD COLUMN + read-back.

Version info

  • Merged into: 26.7.1.1264 (included in 26.7 and later)

createEmptyMetadataFile initialized last-column-id to the number of
top-level columns, ignoring the nested field ids that tuple/array/map
children consume. For (id Int64, t Tuple(a, b)) the field ids are
id=1, t=2, t.a=3, t.b=4, but last-column-id was written as 2. A later
ADD COLUMN then reused id 3 (already held by t.a), publishing metadata
with a duplicate field id: the ALTER succeeded but the next SELECT
failed with Code 743 Duplicate field id 3 (ICEBERG_SPECIFICATION_VIOLATION).

Record the max assigned field id (counting nested children) as
last-column-id, both on initial table creation and in
generateAddColumnMetadata, so every newly added field id (including the
children of a newly added complex column) is globally unique.

Closes: ClickHouse#110877

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE ice (id Int64, t Tuple(a Int64,b Int64)) ENGINE=IcebergLocal(...); INSERT; ALTER TABLE ice ADD COLUMN c Nullable(Int64); SELECT fails every time with Code: 743 Duplicate field id 3 on master.
b Root cause explained? createEmptyMetadataFile set last-column-id = columns.size() (top-level count = 2), but getIcebergType recursively assigns nested child ids via a shared iter (t.a=3, t.b=4). ADD COLUMN reads last-column-id=2, assigns id 3, colliding with t.a → duplicate field id.
c Fix matches root cause? Yes. last-column-id is now set to the final iter (max assigned id, incl. nested children) after schema construction; the ADD COLUMN path allocates the top field id + any nested child ids via iter and records the max.
d Test intent preserved / new tests added? New regression test 04545_iceberg_add_column_nested_field_id_reuse_110877 (initial nested schema + scalar ADD COLUMN + complex nested ADD COLUMN + read-back). No existing tests weakened.
e Demonstrated in both directions? Yes. Baseline (build 742f9e95): initial last-column-id: 2, ADD COLUMN → Code 743. Fixed (build 4989ef36): initial last-column-id: 4, scalar ADD COLUMN → id 5 + SELECT OK; complex ADD COLUMN s Nullable(Tuple(x,y)) → ids 5,6,7, last-column-id: 7, all unique, SELECT OK.
f Fix is general, not a narrow patch? Yes. Both field-id allocation sites are fixed: createEmptyMetadataFile (Utils.cpp) and generateAddColumnMetadata (MetadataGenerator.cpp). The recursive allocator getIcebergType already handles Tuple/Array/Map/Nullable via the shared iter; both sites now record the max id it reaches.
g Generalizes across inputs/wrappers? Verified with scalar and complex (Nullable(Tuple)) added columns; nested children (Tuple/Array/Map) all get unique ids since getIcebergType walks every wrapper. Initial-schema nesting and added-column nesting both covered.
h Backward compatible? Yes. Only corrects metadata newly written by ClickHouse Iceberg writes; no on-disk format change, no setting change, no read-path change. Previously-written (already-broken) tables are unaffected by this change.
i Invariants/contracts preserved? Yes. Upholds the Iceberg spec invariant that field ids are globally unique and last-column-id >= every assigned id. Top-level ids 1..N unchanged; only nested/added ids are now counted.

Session id: cron:clickhouse-worker-slot-5:20260717-150900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim — as offered on #110877. Fixes the duplicate-field-id-after-ADD-COLUMN bug by recording the max assigned field id (counting nested tuple/array/map children) as last-column-id, in both the initial-metadata and ADD COLUMN paths.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5af3640]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
04507_mvt_encode_state_serialize FAIL cidb IGNORED
02499_monotonicity_toUnixTimestamp64 NOT_FAILED cidb IGNORED
03707_statistics_cache NOT_FAILED cidb IGNORED
02345_implicit_transaction NOT_FAILED cidb IGNORED
01010_partial_merge_join NOT_FAILED cidb IGNORED
01147_partial_merge_full_join NOT_FAILED cidb IGNORED

AI Review

Summary

This PR fixes last-column-id tracking for freshly created Iceberg tables and for complex columns added after the fix, and the new stateless regression now covers the fresh-table path plus non-reuse after DROP COLUMN. I did not find any new diff-only issues to post inline, but one previously raised blocker still remains in the current head: tables whose metadata was already written by the buggy build are still left on the duplicate-field-id path.

Findings

❌ Blockers

  • [src/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.cpp:470-478] [dismissed by author -- https://github.com/Fix Iceberg duplicate field ids after ADD COLUMN on nested-field table #110884#discussion_r3604633465] generateAddColumnMetadata still allocates from the persisted last-column-id without reconciling it against the field IDs actually present in the current schema. For a table created by the buggy build, (id Int64, t Tuple(a Int64, b Int64)) still stores last-column-id = 2; after upgrade, ALTER TABLE ... ADD COLUMN c Nullable(Int64) here still chooses field id 3, collides with t.a, commits another invalid metadata version, and the next read still fails with ICEBERG_SPECIFICATION_VIOLATION. That means the PR closes #110877 only for tables created after the fix, not for existing affected tables.
  • Suggested fix: restore the maxAssignedFieldId(current_schema) reconciliation (or an equivalent uniqueness validation before commit) so ADD COLUMN starts from max(persisted last-column-id, max field id already present).
Final Verdict

Not ready: the fresh-table regression is fixed, but the upgrade path for metadata already written by the buggy build still publishes duplicate field ids.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 17, 2026
generateAddColumnMetadata trusted the persisted last-column-id when
allocating the next field id. A table written by an older buggy build
recorded last-column-id too small (top-level column count, ignoring nested
tuple/array/map children), so after upgrade ADD COLUMN still reused a nested
child id and published metadata with a duplicate field id.

Derive the starting id from max(persisted last-column-id, max field id
assigned in the current schema) so upgraded tables also get unique ids.

Extend the regression test: a second ADD COLUMN after a complex column
exercises the nested half of the fix, an assertion on last-column-id guards
the recorded value, and an upgrade-path scenario (metadata with a too-small
last-column-id) reproduces the original duplicate-field-id failure.

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

Copy link
Copy Markdown
Collaborator Author

Both addressed in 42800d7.

  1. Upgrade path: generateAddColumnMetadata no longer trusts the persisted last-column-id. It now starts from max(persisted last-column-id, max field id assigned in the current schema), where the max is computed by walking the schema (struct fields, list element-id, map key-id/value-id, recursively). A table written by the old buggy build has last-column-id=2 for (id, t Tuple(a,b)); ADD COLUMN now derives max=4 and assigns id 5, so no collision with t.a=3. Verified on a metadata file with last-column-id manually set to 2: before the fix the follow-up SELECT fails with Code 743 Duplicate field id 3; after, it reads back cleanly and last-column-id becomes 5.

  2. Test now exercises the nested half: a second ADD COLUMN (d) after the complex column s would reuse a child id of s if the storage regressed, and the final SELECT would fail. It also asserts last-column-id in the emitted metadata JSON (9 for the fresh table, 5 for the upgrade path), plus a dedicated upgrade-path scenario that rewrites last-column-id to the buggy value before ADD COLUMN.

@PedroTadim PedroTadim self-assigned this Jul 17, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai fix the merge conflict

Resolve conflict in MetadataGenerator.cpp by dropping the maxAssignedFieldId
recompute (and its recursive collectMaxFieldId walker): per reviewer, do not
handle tables written before this patch, so the recursion (and thus a
stack-overflow guard for it) is no longer needed.

Keep the new-table fix: createEmptyMetadataFile records the max assigned field
id (counting nested children) as last-column-id, and generateAddColumnMetadata
assigns nested children of a newly added complex column their own ids.

Strengthen the regression test: SELECT after each ALTER (surfaces a duplicate
id immediately) and a SELECT after two consecutive ALTERs (s then d) so the
nested-child half of the fix is exercised.

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

Copy link
Copy Markdown
Collaborator Author

Pushed b7bc8b8.

  1. Merge conflict resolved (merged master).
    2/4. Per "forget about tables before this patch": dropped the max(persisted last-column-id, maxAssignedFieldId) upgrade-path recompute and its recursive collectMaxFieldId walker. With the recursion gone there is nothing left to guard, so no stack-overflow check is needed. What remains is only the new-table fix: createEmptyMetadataFile records the max assigned field id (counting nested children) as last-column-id, and generateAddColumnMetadata assigns the nested children of a newly added complex column their own ids.
  2. Test now SELECTs after each ALTER (a duplicate id surfaces on the immediate SELECT) and SELECTs after two consecutive ALTERs (s then d), which exercises the nested-child half. Verified: fails on the pre-fix binary (Code 743 Duplicate field id 3 at the first SELECT), passes with the fix (last-column-id=9).

@PedroTadim
PedroTadim enabled auto-merge July 17, 2026 18:05
The merge-conflict resolution in the previous commit dropped the
Utils.cpp initializer fix, so last-column-id was written as the top-level
column count again. For (id Int64, t Tuple(a, b)) that is 2, ignoring the
nested ids t.a=3 t.b=4, so the first ADD COLUMN reused id 3 and ClickHouse#110877
still reproduced on newly created tables.

Set last-column-id after the field loop to iter, which getIcebergType
advances past every nested tuple/array/map child, so it records the real
max assigned field id.
auto-merge was automatically disabled July 17, 2026 19:55

Head branch was pushed to by a user without write access

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2d76d8e

CI finished on this head. Every failure below has an owner (a fixing PR); none are caused by this PR's diff (this is an Iceberg metadata change, unrelated to stress/hung-check).

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Hung check failed, possible deadlock found deadlock (chronic; 104 hits / 79 PRs / 20 master in 30d) #108212 (ours, merged) / #105905 (ours, merged)
Stress test (arm_debug) / Cannot start clickhouse-server + Check failed server-restart flake (64 hits / 61 PRs / 3 master in 30d) #110906 (ours, open) in-flight fix for the server-abort-on-restart family
Sync - CH Inc sync (private, not actionable)

Reports:

Session id: cron:our-pr-ci-monitor:20260718-020000

# would reuse a child id of `s` and that SELECT would fail with a duplicate id.
TABLE_DIR="${WORK_DIR}/t0"
mkdir -p "${TABLE_DIR}"
${CLICKHOUSE_LOCAL} \

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, why are you testing with clickhouse local? You can also remove a column, then add another one to check that last_column_id is still right.

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.

Good point, switched to clickhouse-client in 5af3640. clickhouse-local was only for convenience here; the isolation reason other Iceberg tests use it (e.g. 04214, whose bug SIGABRTs and must be contained to a subprocess) does not apply, since this bug is a caught ICEBERG_SPECIFICATION_VIOLATION exception, not a crash. Kept it parallel-safe with a unique table name and ${USER_FILES_PATH} path.

Also added the drop-then-add check you suggested: after ADD c/s/d, DROP COLUMN d (id 9) then ADD COLUMN e, asserting last-column-id stays monotonic at 10 (e takes a fresh id, the dropped 9 is not reused). SELECT after each ALTER, plus a SELECT after the two consecutive ALTERs (s then d).

Verified both directions on a server: baseline fails at the first SELECT with Code: 743 Duplicate field id 3 (last-column-id=2); with the fix all SELECTs are clean (last-column-id=10). 50/50 runs pass.

Per review, run the regression via clickhouse-client instead of
clickhouse-local (the bug is a caught exception, not a crash, so it does
not need the subprocess isolation clickhouse-local gives). Add SELECTs
between the ALTERs so a duplicate field id surfaces immediately, and a
DROP COLUMN d then ADD COLUMN e step asserting last-column-id stays
monotonic (dropped id 9 is not reused, e takes 10).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5af3640

CI fully finished (Finish Workflow pass, 0 checks queued/in-progress, >20min buffer). This head is the test-only update addressing @PedroTadim's 2026-07-20 review (server-based test + drop-then-add-column last-column-id check). One failure, non-PR-caused (this PR only touches Iceberg MetadataGenerator.cpp / Utils.cpp + the 04545 test), with an owner:

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04507_mvt_encode_state_serialize trunk bug, unrelated to this Iceberg change; lossy AST-serialization of a folded Geometry/Variant constant under parallel replicas (Code 70), spiked across master + 18+ unrelated PRs on this one config on 2026-07-20 #111136 (external, open)

Mergeable Check / PR are aggregators reflecting the single stateless red above.

Session id: cron:our-pr-ci-monitor:20260720-210000

@PedroTadim
PedroTadim added this pull request to the merge queue Jul 21, 2026
Merged via the queue into ClickHouse:master with commit fa0b31f Jul 21, 2026
176 of 178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 21, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-field-id-reuse-110877

Fix Iceberg duplicate field ids after ADD COLUMN on nested-field table
Blargian pushed a commit to Blargian/ClickHouse that referenced this pull request Nov 3, 2026
…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]>
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

Development

Successfully merging this pull request may close these issues.

Iceberg tables generate duplicate field IDs after adding a column to a table with nested fields

4 participants