Skip to content

Keep an Iceberg INSERT working when a column is added after it was planned - #121821

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:iceberg-insert-column-added-after-planning
Oct 10, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:iceberg-insert-column-added-after-planning

Conversation

@groeneai

@groeneai groeneai commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121392
Related: #109838

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 an INSERT into a Parquet Iceberg table failing with Logical error: 'Iceberg data file has 1 columns while its schema has 2 fields' when ALTER TABLE ... ADD COLUMN committed while the INSERT was running.

Description

An INSERT into an Iceberg table written as Parquet fails when a column is added between the
query's analysis and its sink's construction:

Logical error: 'Iceberg data file has 1 columns while its schema has 2 fields'

Where abort_on_logical_error is on (debug, sanitizer, stress) it aborts instead. CI found it
running 04615_iceberg_prewhere_mixed_schema_delete_update's INSERT and its ADD COLUMN
concurrently:
https://github.com/ClickHouse/ClickHouse/actions/runs/35808380550/job/107184782953

Root cause. DataFileStatistics keys column_sizes, null_counts and the bounds by schema
position
but fills them from the written block, read at different moments: the block when the
query is analysed, the schema in the sink's constructor. Reachable since #121392 added these
statistics. The narrower file is valid Iceberg: these maps are field-id keyed, and an absent id means
unknown.

Change. Key the statistics to the columns actually written, taking the ids from the ColumnMapper
the writer already uses for the Parquet footer, so the two cannot drift.
addColumnSizesOnDisk is untouched; its guard stops being reachable here. OPTIMIZE and
mutations keep today's behaviour deliberately: compaction rebuilds the table metadata from its block,
so accepting a narrower block there would republish a schema without the added column.

Validation. 05241_iceberg_insert_column_added_after_planning pins a table to the pre-ADD COLUMN
metadata, reproducing the divergence with no race; it fails on master, passes here, and leaves the
Iceberg write tests and 50/50 randomized runs green. A written column with no field id is
still refused with INCORRECT_DATA.

On v26.9.13.15-stable the new test's steps fail with this LOGICAL_ERROR (Code: 49) and the
INSERT writes nothing. 26.8 and 26.9 got the assertion through the robot backports of #121392, so
both need a backport.

#109838 fixes a different site, but its new guard rejects any column-count difference, so it would
reject this INSERT instead; that guard needs to become one-sided before it lands.


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

Version info

  • Merged into: 26.10.1.2044-master (included in 26.10 and later)

groeneai and others added 2 commits September 23, 2026 17:00
An INSERT into an Iceberg table written in Parquet aborted the server when a
column was added between the moment the INSERT was analysed and the moment its
sink was constructed:

  Logical error: 'Iceberg data file has 1 columns while its schema has 2 fields'
  DB::DataFileStatistics::addColumnSizesOnDisk <- DB::MultipleFileWriter::finalize
                                              <- DB::IcebergStorageSink::onFinish

Found by CI, in Stress test (arm_release) on an unrelated PR, where the fuzzer
ran 04615_iceberg_prewhere_mixed_schema_delete_update's INSERT concurrently with
its own ALTER TABLE ... ADD COLUMN:
https://github.com/ClickHouse/ClickHouse/actions/runs/35808380550/job/107184782953

DataFileStatistics keys column_sizes, null_counts and the bounds by schema
position, but fills them from the written block, and the two sides come from
independent reads of the table: the block is the sample block captured when the
INSERT was analysed, while the schema is re-read from the latest metadata file in
IcebergStorageSink's constructor, which deliberately ignores any metadata pointer
override. An ADD COLUMN that commits between those two moments leaves the sink
with two fields and the in-flight INSERT with a one-column block, so
addColumnSizesOnDisk walks the schema's field count while indexing the block.

That narrower state is legitimate Iceberg rather than an internal inconsistency,
which is why the count check is the wrong place to answer it: a data file need not
carry fields appended after it was written, these maps are field-id keyed, the
manifest writer emits whatever pairs it is given, and the read and pruning side
already returns nullopt for an id a file does not mention.

So the ids are taken from the ColumnMapper that MultipleFileWriter already builds
from the same schema and already hands to the output format. Reading that mapper
rather than re-parsing the schema keeps one source of truth for the
name-to-field-id mapping: the Parquet footer and the statistics keys now move
together if traverseSchema's naming ever changes, instead of desynchronising.
This also corrects null_counts and the bounds on this path, which relaxing the
count check to allow a narrower block would not have done, and would in fact have
made worse on a DROP COLUMN history, where the narrower block is not a positional
prefix and the statistics would have been stamped with the wrong field ids.

addColumnSizesOnDisk keeps today's diagnostics byte for byte. Mutations and
compaction keep the one-argument constructor on purpose: compaction rebuilds the
whole table metadata from its block, so accepting a narrower block there would
republish a schema without the concurrently added column, and that count check is
currently the only thing preventing it. Binding each rewrite path's plan, block
and metadata rewrite to a single metadata version is the real fix there, and it
is a separate change.

A written column that has no field of that name is still refused, recursively, by
validateIcebergFieldIds with INCORRECT_DATA during the format's schema
preparation, which happens before finalize. The new helper returning an empty
vector is what preserves that ownership: an unresolvable column leaves the
schema's ids in place, and no statistic is ever read from that writer because the
write is refused first. Verified byte-identical to master on that path, including
the DROP COLUMN history where the column counts match but the mapping does not.

The regression test pins a table to the pre-ADD COLUMN metadata so the divergence
is deterministic and needs no race: the sink resolves the latest metadata while
the table's structure honours the pin. It must use Parquet, because that is the
only output format that reports per-column on-disk sizes, and it runs in
clickhouse-local, because before this change the write terminated the process,
which in the long-running test server trips the hung check instead of failing the
test.

Co-Authored-By: Claude Opus 5 <[email protected]>
Remove the fieldIdsOfWrittenColumns comment: its first clause restates the lookup below, its second duplicates the DataFileStatistics constructor contract, and its claim that the format layer refuses an unmapped column holds for Parquet only.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 23, 2026
@groeneai

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 an independent cold
read of the diff; 1 full pass, no fix round needed.

# Sev Finding Verdict Evidence / action
1 ❌ The missing-field-id fallback is safe only for Parquet; ORC and Avro accept such a write and commit statistics keyed by schema ids DISAGREE for this PR, hazard conceded When the lookup fails the schema ids are left exactly as before (DataFileStatistics.cpp:32), and update, addColumnSizesOnDisk, merge and all four getters are byte-identical to master, so that behaviour is unchanged by this PR and not newly reachable. The proposed remedy (throw before format dispatch) would take over the refusal owned by validateIcebergFieldIds (PrepareForWrite.cpp:919), whose INCORRECT_DATA code 04329_iceberg_insert_stale_schema_field_id_107268.reference asserts for a top-level rename; measured on both binaries: Code: 117, identical post-state. The ORC/Avro surface is carried on the #109838 work, which already owns the same-width rename case
2 ⚠️ The new test never reaches the changed writer, because clickhouse-local rejects its absolute user-files path DISAGREE In CI that root is inside the runner cwd: ci/jobs/scripts/clickhouse_proc.py:81,126 puts it at <repo>/ci/tmp/run_r0/user_files and exports CLICKHOUSE_USER_FILES to it, and the stateless job runs clickhouse-test from the repository root (ci/jobs/functional_tests.py:39-42). 04628_delta_lake_partition_special_values.sh has the same shape through the same access check and reports 55514 OK / 0 FAIL over 14 days; this test ran 50 consecutive times green under the real harness. The Code: 481 seen is the local-runner cwd trap
3 💡 The helper's comment claimed the format layer refuses an unmapped column "before any statistic is read", which holds for Parquet only AGREE, comment removed ORC omits the iceberg.id attribute without throwing (ORCBlockOutputFormat.cpp:308-316), so the claim was not universal. The comment is gone from the diff; the code is unchanged
4 💡 column_mapper's relocated comment still names only startNewFile, though the constructor now reads it too AGREE, left as master wrote it The member moved with its comment text unchanged, so that line is not one this PR adds or rewrites, and I do not edit comments outside my own diff

Sibling-surface matrix for the fixed path, measured: Parquet is the only format that reports
per-column on-disk sizes (IOutputFormat.h:90 returns {} for every other format), so it is the
only one that reached the count check at all; ORC and Avro write no such sizes and are untouched
by this change. OPTIMIZE and mutations keep their existing guard on purpose, for the reason given
in the description.

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

Session id: cron:clickhouse-review-slot-9:20260923-170500

@clickhouse-gh clickhouse-gh Bot closed this Sep 23, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [734e6a3]

Summary: ✅


AI Review

Summary

This PR fixes the Iceberg INSERT path when the table is widened after analysis but before sink construction by deriving DataFileStatistics field ids from the writer's actual column mapping instead of schema position. The change is consistent with the current manifest-writing path, and the new deterministic regression test covers the LOGICAL_ERROR that originally terminated the write; I did not find a remaining correctness or coverage gap in the changed code.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 734e6a3.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed: the Stress test (arm_release) failure on #116577 (report) is the case this PR fixes. From that job's server log, job.log and query_log (server time):

  • 06:51:58.937 INSERT INTO t_del_test_x5u6q4r9t0v1_27660 SELECT toInt32(number + 10) FROM numbers(10) (line 28 of 04615_iceberg_prewhere_mixed_schema_delete_update.sh) starts and is planned against the one-column schema (metadata v1..v6).
  • 06:51:59.072 the stress disruptor kills a random client (Killing random client process: 136453); the test's stderr starts with Terminated, and the script moves on to line 29 while the server is still running the INSERT.
  • 06:51:59.231...415 ALTER TABLE ... ADD COLUMN note Nullable(String) commits v7.metadata.json.
  • 06:51:59.469 the INSERT's IcebergStorageSink reads v7 (2 fields); its block still has the planned single column.
  • 06:51:59.812 DataFileStatistics::addColumnSizesOnDisk <- MultipleFileWriter::finalize <- IcebergStorageSink::onFinish: Iceberg data file has 1 columns while its schema has 2 fields.

05241_iceberg_insert_column_added_after_planning here reproduces it without the race by pinning the table to the pre-ADD COLUMN metadata. The assertion and the sink's two sample_block uses are unchanged on master today (c873902b8273), and the PR still merges cleanly.

Since 2026-09-23 the same message (STIDs 4224-3b20, 4224-3ae3, 4224-3f73) failed 29 Stress runs: 27 PRs, one master run (ef037e60fc7f) and one 26.8 run (9988f3b92a40). The assertion is also in v26.8.21.10-lts and v26.9.13.15-stable, so this needs a backport to 26.8 and 26.9.

@alexey-milovidov alexey-milovidov self-assigned this Oct 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into ClickHouse:master with commit 0b2e86d Oct 10, 2026
177 of 349 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 31, 2026
An INSERT planned before `ALTER TABLE ... ADD COLUMN` commits its data file
under the widened schema (accepted since ClickHouse#121821), so the file lacks an
optional field of the schema its manifest names. The Iceberg spec reads such
a field as null, but whether the format reader tolerated it was left to the
generic `input_format_avro_allow_missing_fields` (default 0) and
`input_format_{parquet,orc}_allow_missing_columns` settings: every Avro query
reading the column failed with `Field d not found in Avro schema`, and
Parquet/ORC failed the same way when a user set those settings to 0.

Pin the three settings in `IcebergMetadata::modifyFormatSettings`, as
`DeltaLakeMetadataDeltaKernel::modifyFormatSettings` already does for
Parquet, and for the compaction reader in `IcebergMetadata::optimize`, which
reads data files with the storage's own format settings.

Compaction rewrites data files only when position deletes exist, and only
Parquet tables accept DELETE, so the test covers it with a Parquet DELETE
before OPTIMIZE.

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

Copy link
Copy Markdown
Collaborator Author

This fix is not on the 26.8 and 26.9 release branches, and their CI keeps hitting the same Logical error: 'Iceberg data file has 1 columns while its schema has 2 fields' (4 times since this merged, 0 on master and 26.10):

  • 26.8, Stress test (arm_release), 2026-11-18: report
  • 26.9, Stress test (arm_release), 2026-11-16: report
  • a 26.9 backport PR, Stress test (amd_tsan), 2026-11-17: report

The change applies to both branches without conflicts: three of the four src/ files are identical to this PR's base on both branches, MultipleFileWriter.cpp merges cleanly, and ColumnMapper::getStorageColumnEncoding() exists on both. 26.10 already has the fix and 26.3 does not have the affected code, so v26.8-must-backport would cover it. Could that label be added?

@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... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants