Skip to content

Fix Iceberg schema-drift write abort and OPTIMIZE metadata loss - #109838

Open
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-iceberg-insert-column-count-oob-109835
Open

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-iceberg-insert-column-count-oob-109835

Conversation

@groeneai

@groeneai groeneai commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

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 a server abort (out-of-bounds read) when writing into an Iceberg table whose cached structure has more columns than its current Iceberg schema. INSERT, UPDATE, DELETE and OPTIMIZE now reject a write whose columns no longer fit the current schema (a dropped, renamed or retyped column) with BAD_ARGUMENTS. Fixed OPTIMIZE of an Iceberg table committing a renumbered schema, an empty partition spec and a new table UUID and dropping the refresh cursor, which made the table fail with schema-id 0 is bound to two different schemas, a later DELETE on a partitioned table leave rows visible, a table attached by iceberg_metadata_table_uuid unreadable, and an incremental refreshable materialized view re-append its source. OPTIMIZE now rejects live equality deletes, branches and tags, and rolled-back or out-of-order snapshots instead of resurrecting deleted rows, erasing the refs or making an older snapshot current. It also rejects live data files written under an older schema id or another partition spec, and UPDATE and DELETE reject a live data file whose partition spec id is not the default one.

Description

Closes: #109835

On 26.7.1.644 IcebergStorageSink mapped the input block's columns positionally onto the current schema's fields when it wrote per-column statistics, so an input block wider than the schema read past the end of field_ids and the server aborted. The fix validates the input header against the current schema: by name for INSERT, which may omit fields added after it was planned; positionally for UPDATE, DELETE and OPTIMIZE, which build statistics by position. Master's INSERT refuses such a block with INCORRECT_DATA since #126768; this check runs first, so test_writes_stale_insert_after_alter.py expects BAD_ARGUMENTS.

Also fixed here, each with a test:

  • OPTIMIZE keeps the table-level metadata (schemas, partition specs, table UUID, location, sort orders, properties, main's retention policy) and the refresh cursor, and rebuilds only the snapshot state.
  • OPTIMIZE refuses a table with a live data file written under an older schema id or another partition spec, since compaction rewrites every file under the current schema and default spec; on master a pruned SELECT then misses rows of another spec. test_optimize_position_delete_other_partition_spec now expects it.
  • UPDATE and DELETE refuse a live data file whose spec id is not the default one: readers apply position deletes only to data files of the same spec id.
  • OPTIMIZE refuses live equality deletes, refs other than main, and snapshots outside the current history or out of commit order, which its replay cannot rebuild.

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

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. On current master (git c1edd5f, build 743d4c86), the reporter's sequence aborts the server every run: Avro IcebergLocal t(3 cols) + MV(3 cols); a sibling IcebergLocal on the same path ALTER ... DROP COLUMN c2 shrinks t's on-disk schema to 2 fields; INSERT INTO src -> MV pushes a 3-col block into the 2-field sink -> abort.
b Root cause explained? DataFileStatistics sizes field_ids from the current on-disk schema but column_sizes from the written chunk. getColumnSizes() (DataFileStatistics.cpp:97) indexes field_ids[i] for i < column_sizes.size(). When the input block is wider than the schema, field_ids[i] reads past the end -> libc++ hardening vector[] OOB -> abort. An MV's output block is fixed at MV-creation and is pushed into the target sink without re-resolving against the target's (shrunk) current schema; AVRO data files bypass the Parquet-only write-time field-id guard.
c Fix matches root cause? Yes. The mapping is only valid when input column count == current schema field count. The fix validates exactly that invariant in the sink constructor (where both the input block and the resolved current schema are available) and rejects a mismatch, so field_ids is never indexed out of range.
d Test intent preserved / new test added? New regression test 04365_iceberg_insert_column_count_mismatch_109835.sh: without the fix it aborts the server; with the fix it asserts a clean BAD_ARGUMENTS and that the server is still alive.
e Demonstrated in both directions? Yes. Reverted only IcebergWrites.cpp, rebuilt (743d4c86): INSERT aborts, stack matches the report frame-for-frame (DataFileStatistics.cpp:97 -> generateManifestFile IcebergWrites.cpp:381 -> IcebergStorageSink::initializeMetadata). Re-applied fix, rebuilt (8b9cec63): BAD_ARGUMENTS, server ALIVE.
f Fix is general, not a narrow patch? The guard sits in the single sink constructor that all Iceberg write paths (direct INSERT, MV, table function) flow through, so every entry point is covered. The added if (!current_schema) also closes a null-deref path (current_schema was dereferenced later at IcebergWrites.cpp:736 without a prior null check).
g Fix generalizes across inputs? The check is on column count (schema fields vs input columns), independent of column types/wrappers. Any width mismatch (wider or narrower input) is caught; the too-narrow case is also rejected rather than silently writing partial stats.
h Backward compatible? Yes. Previously this input aborted the server; now it is a clean query error. No setting default, on-disk/wire format, or metadata format changes. Valid inserts (matching column count) are unaffected.
i Invariants and contracts preserved? Yes. Upholds the DataFileStatistics contract that field_ids is indexed only within [0, field_ids.size()). The sink now guarantees sample_block->columns() == current_schema fields before any positional mapping (statistics field ids, per-column dumps, partitioner).

Session id: cron:clickhouse-worker-slot-2:20260708-192900

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @alesapin — could you review? Fixes the Iceberg write-path OOB abort from #109835: DataFileStatistics::getColumnSizes() indexed field_ids[] (sized from the on-disk schema) up to the written-chunk column count, so a block wider than the current schema (e.g. an MV whose output block outlives an out-of-band DROP COLUMN on the target) read past the end and aborted the server. The sink now rejects the column-count mismatch with BAD_ARGUMENTS.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [db91824]


AI Review

Summary

The PR validates Iceberg write headers against the current schema, rejects compaction inputs the rewrite cannot safely handle, and preserves table metadata, the retention policy of main, and the incremental refresh cursor. Reviewed head: db918245701d984ea487aac1c7c3b7e3997fd707. No new inline findings. The previously dismissed compaction defects below remain in the current code; I accept the decision to address the pre-existing rewrite problems in the separate, still-open compaction rework.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary is available. The current-head targeted integration report contains 499 passing Iceberg cases, including the modified stale-insert and partition-evolution cases. The current stateless report supplies no results yet; completed CI results are still needed for the cursor and commit-retry shell regressions. This review does not claim those tests passed.
Findings

❌ Blockers — previously dismissed; retained for visibility, without reopening threads

Final Verdict

Status: ✅ Approve

Approve the scoped fixes, accepting the existing decision to defer the pre-existing experimental-compaction defects to #124114. Normal CI gates still apply. No new inline comments or thread-state changes are needed.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4b88ce4 (superseded by master-merge 64cd00a)

Every failure below has an owner. CI on 4b88ce4 finished (Finish Workflow success); the only red checks were the ThreadPoolCallbackRunner unit test across all sanitizers, whose fix (revert #109851) was on master but not yet on this branch. I merged master (64cd00a) to pick it up, so CI re-runs with the fix.

Check / test Reason Owner / fixing PR
Unit tests (asan_ubsan / tsan / msan / amd_llvm_coverage) — ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup (+ AllTests) trunk (branch predated the revert) #109851 (merged) — merged master into this branch @ 64cd00a to pick it up
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260709-033000

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch. Fixed in 7d1a8d6: the sink now compares the full current-schema-id ClickHouse schema (names + types) against sample_block, not just size().

The check reuses the shared IcebergSchemaProcessor (getClickhouseTableSchemaById, the same converter that produced the cached ClickHouse columns at attach time), so it is apples-to-apples and does not false-positive on converter quirks (nullability, geo, nested types). A same-width RENAME COLUMN / MODIFY COLUMN drift is now rejected with BAD_ARGUMENTS naming the mismatched column, before any Avro data file is committed under the new schema id.

Verified both directions locally with a same-width RENAME regression added to the test: on the count-only guard the RENAME insert silently succeeds (test fails), with the full-schema guard it is rejected (test passes, 5/5 with randomized settings).

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A sibling IcebergLocal table on the same path does ALTER ... RENAME COLUMN c1 TO c1_renamed; the original table's cached structure stays (c0, c1). INSERT through an MV into the stale table triggers it every time.
b Root cause explained? The sink guard only compared column COUNT. A same-width RENAME/MODIFY COLUMN keeps the count but changes names/types, so a stale table passes the guard and reaches the writer. AvroRowOutputFormat builds the file schema from the stale sample_block header (it ignores the ColumnMapper), so it would commit data files with old names/types under the new schema id.
c Fix matches root cause? Yes. The guard now compares the full current-schema-id ClickHouse schema (names + types) against sample_block, using the shared IcebergSchemaProcessor converter. The count check is kept as the first gate.
d Test intent preserved / new tests added? Original count-mismatch case unchanged. Added a same-width RENAME case to the regression test that only the full-schema check can catch.
e Both directions demonstrated? Yes. On the count-only guard the RENAME insert silently succeeds (test FAILS, second BAD_ARGUMENTS missing). With the fix it is rejected (test PASSES, 5/5 under randomized settings). Distinct Build IDs verified for each binary.
f Fix is general across code paths? Yes. The guard is at the single sink-construction site all write paths flow through; the same converter output is used, so the check covers every column type the converter emits.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Uses IDataType::equals, which compares Nullable/LowCardinality/Array/Map/nested wrappers exactly. RENAME (name change) and MODIFY (type change) are both covered by the name-or-type comparison.
h Backward compatible? Yes. No setting/format/on-disk change. It only converts a previously-silent corruption (or an OOB abort) into a clear BAD_ARGUMENTS error; a correctly-refreshed table is unaffected.
i Invariants and contracts preserved? Yes. addIcebergTableSchema is idempotent for an already-registered identical schema id (throws only on a re-bound schema id, per spec). The input_columns.empty() guard skips the degenerate empty-schema case. The positional-mapping invariant the writer relies on is now enforced, not just assumed.

Session id: cron:clickhouse-worker-slot-0:20260709-043300

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed c047079: reconcile 04329_iceberg_insert_stale_schema_field_id_107268 with the strengthened guard.

The full-schema (names + types) sink guard now rejects a stale-schema INSERT up front with BAD_ARGUMENTS, before the old writer-path INCORRECT_DATA. Verified locally (Build ID 43dae094) that both stale-schema INSERTs in 04329 are still rejected with no rows written and the server alive; only the error code moves earlier:

  • top-level rename c0->c9: BAD_ARGUMENTS naming the c0 vs c9 mismatch
  • nested rename t.a->t.b (same top-level field id): BAD_ARGUMENTS naming Tuple(a Int32) vs Tuple(b Int32)

Updated 04329's two assertions and reference from INCORRECT_DATA to BAD_ARGUMENTS. 04329 and 04365 both pass 5/5 and 3/3 under randomized settings.

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim Good question. I checked the two mutation write paths in Mutations.cpp and reproduced both locally.

DELETE: not affected. A pure delete only emits position-delete files. writeDataFiles' delete branch builds DataFileStatistics(IcebergPositionDeleteTransform::getSchemaFields()) and writes a fixed two-field block (file_path, pos) from getPositionDeleteFileSampleBlock(). That schema is a constant, independent of the user/table columns, so no user-widened block ever feeds the positional field-id mapping. No OOB, and no data file is committed with stale user names/types. (A delete against a stale-cached table just fails cleanly at the interpreter with NOT_FOUND_COLUMN_IN_BLOCK when the read column set no longer matches.)

UPDATE: yes, it shares the same class. writeDataFiles' UPDATE branch writes new data files through the exact same machinery as the INSERT sink: DataFileStatistics(data_schema->getArray(f_fields)) (fresh current_schema field ids) fed a data_block derived from the table's cached structure, serialized by the same output format that ignores the ColumnMapper for Avro. There is no guard in the mutate path equivalent to the one added to IcebergStorageSink. Reproduced on a v2 IcebergLocal table whose current on-disk schema was narrowed by a sibling DROP COLUMN while this table's cached structure stayed wide: the ALTER ... UPDATE committed a new snapshot against the narrowed schema id with the stale wide block, rather than being rejected.

Fix: I will extract the sink's full-schema (names + types) check into a shared helper and apply it in the mutate path for UPDATE, so INSERT and UPDATE stay in sync, and leave DELETE as-is with a source comment explaining why it is inherently safe. Regression will cover a same-width RENAME and a DROP COLUMN drift on UPDATE for Avro.

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Implemented in 622d5a1. The UPDATE path now runs the same full-schema guard as the sink (extracted into validateInputSchemaMatchesCurrentIcebergSchema), and DELETE is left as-is with a source comment explaining why it is safe.

Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. v2 IcebergLocal table, warm the metadata cache with schema {c0,c1}, publish a newer metadata version renaming c0->c9, then ALTER ... UPDATE. On the pristine mutate path the UPDATE commits a new snapshot against the renamed schema id; with the fix it is rejected with BAD_ARGUMENTS.
b Root cause explained? The UPDATE branch of writeDataFiles writes new data files via the same positional block->field mapping as the INSERT sink: DataFileStatistics(current_schema field ids) fed a block shaped by the stale cached structure, serialized by an output format that ignores the ColumnMapper (Avro). No guard existed on the mutate path, so a stale attached table committed files with old names/types under the new schema id.
c Fix matches root cause? Yes. The sink's full-schema (names + types) check is extracted into a shared helper and invoked for UPDATE. It rejects the drift before any data file is written.
d Test intent preserved? / New tests added? New test 04367_iceberg_update_stale_schema_drift_109838 (same-width RENAME drift on UPDATE + a normal UPDATE sanity). Existing 04329/04365 unchanged and still pass.
e Demonstrated in both directions? Yes. Pristine mutate path (Build ID 37a3a26c): new test FAILS (UPDATE not rejected). With fix (Build ID 4ed4557a): passes 5/5; 04329+04365 pass 5/5 each.
f Fix general, not a narrow patch? Checked both mutation write paths. UPDATE shares the sink machinery -> guarded. DELETE writes only fixed-schema position-delete files (getPositionDeleteFileSampleBlock / IcebergPositionDeleteTransform::getSchemaFields), independent of user columns -> inherently safe, excluded with a comment.
g Generalizes across inputs? The shared helper compares names + types positionally via the same IcebergSchemaProcessor used at attach time, so it handles Nullable/LowCardinality/nested wrappers apples-to-apples; covers add/drop (count) and same-width RENAME/MODIFY drift.
h Backward compatible? Yes. Only converts a previously-silent stale-schema commit (or crash) into a clean BAD_ARGUMENTS; normal INSERT/UPDATE unaffected. No format/setting/default change.
i Invariants preserved? Yes. The write path's invariant (input header matches current schema for positional field mapping) is now enforced for UPDATE too; no data structure or concurrency contract touched.

Session id: cron:clickhouse-worker-slot-2:20260709-073400

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim good catch, UPDATE was not the only additional path. I enumerated every Iceberg path that writes data files through the positional block->field mapping + DataFileStatistics + the Avro/Parquet output that ignores the ColumnMapper, and there are four:

  1. INSERT (IcebergStorageSink, IcebergWrites.cpp) - guarded.

  2. UPDATE (Mutations.cpp writeDataFiles UPDATE branch) - guarded.

  3. OPTIMIZE / compaction (Compaction.cpp writeDataFiles) - was NOT guarded, now fixed in this push. It reads the fresh on-disk current schema for the manifest / DataFileStatistics but shapes the rewritten file from sample_block_ (the cached, possibly-stale structure). Reproduced locally (IcebergLocal, format_version 2, a position delete so need_optimize fires): with a sibling same-width MODIFY c0 Int32 -> Int64 published under a new schema id while the cache still serves the old one, pristine OPTIMIZE committed a rewritten Parquet data file with the stale Int32 under the new schema id silently (no error). RENAME happens to be rejected by the name-based ColumnMapper (INCORRECT_DATA), but a MODIFY type change is not - same silent-corruption shape you flagged for Avro. After the fix OPTIMIZE rejects it with BAD_ARGUMENTS naming the mismatched column, server alive.

  4. DELETE (Mutations.cpp writeDataFiles DELETE branch) - safe, no guard needed. Pure delete only emits position-delete files, built from the fixed two-field schema getPositionDeleteFileSampleBlock() / IcebergPositionDeleteTransform::getSchemaFields() = {file_path, pos}, independent of the user columns. It never feeds a user-shaped block into the positional mapping.

No other mutation kind can reach writeDataFiles: IcebergMetadata::checkMutationIsPossible (IcebergMetadata.cpp) throws NOT_IMPLEMENTED for anything other than DELETE / UPDATE, so MATERIALIZE, APPLY DELETED MASK, etc. cannot get there. No backup / partition-attach path reaches the Iceberg data-file writer either.

I refactored the check into the shared validateInputSchemaMatchesCurrentIcebergSchema and now call it from all three writing paths (INSERT sink, UPDATE, OPTIMIZE), plus moved the null-current_schema rejection into that one helper so a malformed table (current-schema-id resolves to no schema) is rejected consistently instead of null-dereferencing. New regression 04368_iceberg_optimize_stale_schema_drift_109838 covers the OPTIMIZE MODIFY drift + a normal-OPTIMIZE sanity; 04367 also gained the malformed-metadata case. Verified both directions with distinct Build IDs.

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. IcebergLocal fmt v2, INSERT, ALTER ... DELETE (creates a position delete so need_optimize fires), warm cache, external writer publishes MODIFY c0 Int32 -> Int64 under a new schema id, then OPTIMIZE TABLE with iceberg_metadata_staleness_ms=600000. Fails on demand pre-fix.
b Root cause explained? Compaction.cpp::writeDataFiles builds the manifest / DataFileStatistics from the fresh on-disk current schema but shapes the rewritten data file from sample_block_ (the stale cached structure). A same-width MODIFY keeps the field count and the column name, so the name-based ColumnMapper does not catch it and the file is committed with the stale type under the new schema id.
c Fix matches root cause? Yes. Runs the same full-schema (names + types) validateInputSchemaMatchesCurrentIcebergSchema check for the compaction path, comparing sample_block_ against the fresh current_schema, before any file is rewritten.
d Test intent preserved / new tests added? New 04368_iceberg_optimize_stale_schema_drift_109838 (OPTIMIZE MODIFY drift rejected + normal-OPTIMIZE sanity). 04367 extended with a malformed-metadata (current-schema-id resolves to no schema) case. No existing test weakened.
e Demonstrated both directions? Yes. Pristine (Build ID 4ed4557a): OPTIMIZE commits the stale-type file silently. Fix (Build ID 97f56a6c): OPTIMIZE rejected with BAD_ARGUMENTS naming the column, server alive; normal OPTIMIZE still compacts.
f Fix is general, not a narrow patch? Yes. Audited all four data-file writers (INSERT / UPDATE / OPTIMIZE / DELETE); guarded the three that feed the positional mapping, confirmed DELETE is inherently safe (fixed two-field position-delete schema), and confirmed checkMutationIsPossible blocks every other mutation kind from reaching the writer. Consolidated the null-schema rejection into the shared helper so all paths behave identically.
g Generalizes across inputs / datatypes / wrappers? Repro uses a MODIFY type change (Int32 -> Int64); the full names+types comparison via the shared schema processor also covers RENAME and add/drop, and reuses the same converter that produced the cached ClickHouse columns so it does not false-positive on Nullable / LowCardinality / nested wrappers.
h Backward compatible? Yes. No format, setting-default, or on-disk change. Only adds an up-front rejection of an already-broken (stale-cache) write that otherwise produced silent corruption.
i Invariants / contracts preserved? Yes. The Iceberg contract that a committed data file's names/types match the schema id it is advertised under is now upheld for compaction as well. The helper's precondition (non-null current_schema) is enforced in one place; error/early-return paths reject before any file is written.

Session id: cron:clickhouse-worker-slot-3:20260709-083800

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. IcebergLocal fmt v2, INSERT, warm cache, rewrite metadata so current-schema-id points at an absent schema id, then UPDATE. Fails on demand.
b Root cause explained? The mutation path resolves current-schema-id against the schemas array; if nothing matches, current_schema stays null. Mutations.cpp then calls validateInputSchemaMatchesCurrentIcebergSchema (and later chunk_partitioner / writeDataFiles) which dereference the null Poco::JSON::Object::Ptr. The INSERT sink already guarded this; UPDATE/OPTIMIZE did not.
c Fix matches root cause? Yes. The null check moves into the shared helper (single choke point for INSERT/UPDATE/OPTIMIZE), plus an explicit guard right after schema resolution in Mutations.cpp so DELETE (does not call the helper but dereferences current_schema) is covered.
d Test intent preserved? / New tests added? Preserved: 04329/04365/04368 still pass. New: 04367 gains a malformed-table UPDATE case asserting ICEBERG_SPECIFICATION_VIOLATION.
e Demonstrated in both directions? Yes. Without guard (Build ID 58e6e4d7): Poco::NullPointerException. With guard (Build ID 97f56a6c): clean ICEBERG_SPECIFICATION_VIOLATION, server alive. 04367 passes 3/3 repeats.
f Fix general, not a narrow patch? Yes. Hardened the shared helper so all three write paths (INSERT sink, UPDATE mutation, OPTIMIZE compaction) reject a null schema at one place; also removed the now-redundant if (current_schema) skip in Compaction.cpp.
g Generalizes across inputs? The malformed condition (unresolved current-schema-id) is independent of column types; the guard fires before any type/positional logic.
h Backward compatible? Yes. No format/setting change. A malformed table that previously null-deref'd now gets a clear error; a well-formed table is unaffected.
i Invariants and contracts preserved? Yes. The helper's precondition (non-null schema) is now enforced at entry, so all callers can rely on it. No change to well-formed write behavior.

Session id: cron:clickhouse-worker-slot-0:20260709-090400

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate — compaction schema-id-reuse guard (click to expand)
# Question Answer
a Deterministic repro? Yes. 04369: DROP c0 + ADD c0 Nullable(Int32) then OPTIMIZE deterministically corrupts silently on pristine, rejected with BAD_ARGUMENTS with the fix.
b Root cause explained? Compaction reads each historical data file into the cached header with a null FormatFilterInfo (no per-file getSchemaTransformationDagByIds/input ColumnMapper), then rewrites under the current schema field ids. DROP c0 + ADD c0 keeps names/types but advances the Iceberg field id, so the name+type guard passes while the on-disk file (older underlying_format_read_schema_id) gets re-tagged under the new field id: silent corruption.
c Fix matches root cause? Yes. After the name+type check, reject when any data file's underlying_format_read_schema_id differs from the current schema id (option 1, reject), directly targeting the field-id mismatch.
d Test intent preserved / new tests added? New test 04369; existing 04329/04365/04367/04368 unchanged and still pass.
e Both directions demonstrated? Yes. Pristine (Build ID 97f56a6c): OPTIMIZE silently rewrites the schema-id-0 file, 04369 FAILS. Fix (Build ID 09d9da61): rejected, 04369 passes 5/5 randomized.
f Fix is general across code paths? Yes. Sibling data-file writers already guarded: INSERT sink + UPDATE mutation (name+type via shared helper), OPTIMIZE now also field-id; DELETE emits only fixed-schema position-delete files (safe). No other MutationCommand kind reaches writeDataFiles (checkMutationIsPossible throws NOT_IMPLEMENTED for others).
g Fix generalizes across inputs? Yes. The check is on schema id, independent of column type/wrapper; the guard fires for any file whose read schema id differs from the current schema id (add/drop/rename/modify/field-id reuse).
h Backward compatible? Yes. Turns a previously-silent-corruption path into a clear error; no format/setting/default change. Compacting across a schema evolution was never correct here.
i Invariants and contracts preserved? Yes. Compaction's contract is that rewritten files carry the current schema's field ids; the guard enforces exactly that every input file already belongs to the current schema id before rewrite, upholding the manifest/DataFileStatistics field-id consistency invariant.

Session id: cron:clickhouse-worker-slot-1:20260709-095400

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Pin the table to a stale iceberg_metadata_file_path=metadata/v1.metadata.json, INSERT (writes v2), externally publish a v3 with the drift + SYSTEM DROP ICEBERG METADATA CACHE, then INSERT again: it targets v2 (present), enters cleanup(true), and re-reads v3. Deterministic; scripted in .scratch/repro_retry.sh and in test 04370.
b Root cause explained? The sink validates schema only on the first attempt (before data files exist). On a metadata-conflict retry, cleanup(true) keeps the buffered writers/DataFileStatistics and only checked new_schema_id != current_schema_id. So a same-schema-id default-spec-id change re-partitions buffered tuples under the new spec, and a same-schema-id content rebind never gets re-validated -> stale data committed under the new definition (silent corruption).
c Fix matches root cause? Yes. On the retry path only: reject a default-spec-id change (NOT_IMPLEMENTED) before reusing the buffered files, and re-run validateInputSchemaMatchesCurrentIcebergSchema against the refreshed current_schema (rejects a same-id rebind via the schema processor's immutable-id check, and null refreshed schema). No band-aids.
d Test intent preserved / new tests added? New test 04370_iceberg_insert_retry_metadata_drift_109838 (spec-id change, same-id rebind, no-drift-retry-succeeds sanity). Existing 04329/04365/04367/04368/04369 unchanged and still pass 3x each.
e Both directions demonstrated? Yes, distinct Build IDs. Pristine (09d9da61): both drifts silently commit; 04370 FAILS (both error lines missing). Fixed (8908d758): both rejected, server alive; 04370 passes 5/5 under randomized settings.
f Fix is general across code paths? Yes. IcebergStorageSink::initializeMetadata is the only writer with a buffer-reusing cleanup(true) retry. The UPDATE/OPTIMIZE mutation retries (Mutations.cpp) restart from scratch each iteration (re-read metadata, re-derive sample_block, re-validate, re-writeDataFiles), so they have no equivalent hole; DELETE emits only fixed-schema position-delete files.
g Fix generalizes across inputs? N/A (metadata-consistency guard on the retry path, not an input-type code bug). Both semantics-affecting metadata deltas (partition spec, schema rebind) are covered; a schema-id change was already rejected.
h Backward compatible? Yes. Only rejects a semantics-affecting metadata change observed mid-write (a rare conflict-retry race) that would otherwise silently corrupt. No format/setting/default change; no SettingsChangesHistory impact. The prior behavior already threw NOT_IMPLEMENTED for a schema-id change.
i Invariants and contracts preserved? Yes. The reused buffered DataFileStatistics/partition-key tuples must match the metadata they are committed under; the fix enforces exactly that invariant before reuse. current_schema is cleared before the re-lookup so a stale non-null pointer cannot survive, and the shared helper rejects null.

Session id: cron:clickhouse-worker-slot-1:20260709-105100

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Partitioned UPDATE: PARTITION BY c1 (constant) then evolve default spec to PARTITION BY c0 so one pulled block partitions into 3 chunks; SELECT count() = 9 pre-fix, 3 post-fix. Spec rebind: pin table to iceberg_metadata_file_path=v1, publish v3 that rebinds spec-id 0 (identity c0 -> bucket[4] c0), drop cache, retry INSERT -> silently commits pre-fix, NOT_IMPLEMENTED post-fix.
b Root cause explained? (1) The UPDATE loop wrote the full data_block/chunk to every per-partition file and updated every partition's DataFileStatistics from the full block, so a block spanning N partitions duplicated its rows across N files. (2) The cleanup(true) retry only checked default-spec-id change; a same-spec-id structural rebind reused writers keyed by old-spec tuples, mislabeling partitions (a wider rebind also overruns partition_values[i]).
c Fix matches root cause? Yes. (1) Build a partition-local block from partition_chunk; write/total_rows/stats.update all use it. (2) Compare the refreshed same-spec-id spec object structurally against the buffered spec and reject any change.
d Test intent preserved / new tests added? Existing tests unchanged and green (04061, 04329, 04365, 04367, 04368, 04369). New: 04371 (partitioned-UPDATE duplication), 04370 extended with the same-spec-id rebind scenario.
e Demonstrated both directions? Yes, distinct Build IDs. 04371: FAILs pristine (count 9) / passes fix (count 3). 04370 rebind: FAILs pristine (line missing) / passes fix (NOT_IMPLEMENTED). Full suite 21/21 (7 tests x 3 runs).
f Fix general, not a narrow patch? Yes. (1) is the general per-partition write fix for the UPDATE path (DELETE already uses partition-local chunks; INSERT sink already partitions correctly). (2) closes the last same-id metadata-rebind hole on the retry alongside the existing schema-id and default-spec-id checks.
g Generalizes across inputs? (1) covered for 1..N partitions and multi-partition single block. (2) covers transform/name/order/field-count rebinds via whole-spec comparison.
h Backward compatible? Yes. No format/setting change. Rejections only fire on genuinely stale/malformed metadata that would otherwise corrupt data.
i Invariants preserved? Yes. Per-partition manifest entry now carries exactly its partition's rows and statistics; buffered files are only committed under a spec structurally identical to the one they were partitioned under.

Session id: cron:clickhouse-worker-slot-6:20260709-115800

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 04370 Scenario 1c: INSERT pinned to a stale metadata version, then publish a v3 that drops the partition-specs entry for the current default-spec-id + DROP ICEBERG METADATA CACHE; the retry deterministically hits cleanup(true) with no matching spec.
b Root cause explained? The cleanup(true) retry loop searched partitions_specs for the current default-spec-id. If the refreshed metadata dropped that entry, the loop body never ran, so partititon_spec/partitioner stayed cached from attempt 1 and generateManifestFile published buffered tuples under a stale layout.
c Fix matches root cause? Yes. Track found_partition_spec in the loop and throw ICEBERG_SPECIFICATION_VIOLATION before reusing buffered files when the entry is missing. Directly targets the "loop never ran" gap.
d Test intent preserved / new tests added? 04370 extended with Scenario 1c (dropped partition-specs entry on retry). Existing scenarios unchanged.
e Both directions demonstrated? Yes. Pristine (Build ID 93152e3b): 04370 FAILS (missing ICEBERG_SPECIFICATION_VIOLATION line). Fix (Build ID fff083a7): 04370 passes 5/5; full Iceberg suite 04365/04367/04368/04369/04370/04371/04329 passes 14/14.
f Fix is general across code paths? UPDATE/OPTIMIZE mutation retries restart from scratch each iteration (no equivalent reuse-of-buffered-spec hole); DELETE emits only fixed-schema position-delete files. The gap is specific to the INSERT sink cleanup(true) reuse path, which is where the guard lives.
g Fix generalizes across inputs? The check keys on the found/not-found of the default-spec-id entry, independent of column types/wrappers. Applies to partitioned and unpartitioned tables (an unpartitioned table has its spec-id 0 entry present, so found stays true).
h Backward compatible? Yes. Only adds a rejection for malformed refreshed metadata (dropped spec entry) on a conflict retry; no format/setting/default change.
i Invariants and contracts preserved? Upholds the retry-reuse invariant: buffered DataFileStatistics/writers may only be committed under a partition spec identical to the one they were partitioned under. The new throw closes the one path where that invariant was assumed but not checked.

Session id: cron:clickhouse-worker-slot-1:20260709-125100

@PedroTadim PedroTadim added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Jul 9, 2026
`OPTIMIZE` built the committed metadata from `createEmptyMetadataFile` and
copied back only the schema and partition-spec keys. So it replaced
`table-uuid` with a fresh one, rewrote `location` to the bare table path, and
dropped `properties` and the sort orders, while the rewritten data files keep
their `sort_order_id`. A table attached with `iceberg_metadata_table_uuid` then
fails with `FILE_DOESNT_EXIST` once the old metadata files are removed.

Copy every key of the original metadata except the snapshot state
(snapshots, refs, logs, sequence number, statistics), which compaction
rebuilds from the plan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/SchemaProcessor.h
@PedroTadim PedroTadim removed their assignment Nov 10, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 13, 2026
…ioned table

Data compaction (writeMetadataFiles) built the metadata it commits from
createEmptyMetadataFile(..., partition_by = nullptr, ...), so it committed an
empty spec 0 (no fields, last-partition-id 999) while every rewritten manifest
and the manifest list kept the source table's default spec and its partition
tuples. Every later writer reads the committed spec: INSERT and ALTER ... DELETE
wrote `[]` tuples, so the position deletes never matched the compacted files and
the deleted rows stayed visible, and the next OPTIMIZE read 0 partition columns
from the committed spec while the old files still carried 1-value tuples, which
generateManifestFile reports as LOGICAL_ERROR "Iceberg manifest partition arity
mismatch: 0 partition columns but 1 values" (aborts debug builds). Any second
data OPTIMIZE on a partitioned table hits it; the emptied partition in the issue
is not needed.

writeMetadataFiles now copies partition-specs, default-spec-id and
last-partition-id from the source metadata, so the committed metadata defines
the spec (id, field ids, transforms) the rewritten manifests are written under.
Only the partition keys are copied: schema preservation interacts with how the
rewritten snapshots are stamped with the current schema id and is handled with
its own refusal in ClickHouse#109838.

Data compaction rewrites every data file under the default spec, so a tuple of
another arity cannot be written (a table whose spec another engine changed to a
different number of fields, or a table already compacted by an earlier version).
compactIcebergTable now checks every data file's tuple against the default spec
before writing anything and refuses with NOT_IMPLEMENTED; a missing default spec
is ICEBERG_SPECIFICATION_VIOLATION (master dereferenced a null spec there).
generateManifestFile keeps its LOGICAL_ERROR guards, since its other callers
compute tuples from the spec they pass.

Tests: a stateless test with the issue's two symptoms (a DELETE after OPTIMIZE,
then a second OPTIMIZE), and a Spark integration case (DROP PARTITION FIELD) that
checks the error, the rows, and that the refused OPTIMIZE writes no file.

Closes ClickHouse#129498

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Nov 16, 2026
…g-insert-column-count-oob-109835

Conflicts with ClickHouse#129564 (keep schema and partition spec in Iceberg `OPTIMIZE TABLE`):
- `compactIcebergTable`: keep master's partition-tuple arity check (`NOT_IMPLEMENTED`) first, then this PR's stricter schema-id and partition-spec guards, sharing one lookup of the default spec.
- `writeMetadataFiles`: this PR copies all table-level keys, which subsumes master's list of keys; keep master's `last-column-id` recomputation after the copy.
- `test_optimize_position_delete_other_partition_spec`: keep this PR's expectation that `OPTIMIZE` is refused, and check that the metadata is unchanged; keep master's new tests.

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

Copy link
Copy Markdown
Member

🕵 Merged master (8026058). It conflicted with #129564 (keep the schema and partition spec in Iceberg OPTIMIZE TABLE). How I resolved it:

  • compactIcebergTable: master's partition-tuple arity check (NOT_IMPLEMENTED, pinned by the new test_optimize_refuses_partition_tuple_of_another_arity) runs first. This PR's stricter schema-id and partition-spec guards (BAD_ARGUMENTS) run after it, and both now use one lookup of the default spec.
  • writeMetadataFiles: this PR's copy of all table-level keys covers master's narrower list of keys, so the narrower copy is gone. Master's last-column-id recomputation (getLastAssignedFieldId) still runs after the copy.
  • test_optimize_position_delete_other_partition_spec: kept this PR's expectation that OPTIMIZE is refused. Master's post-OPTIMIZE assertions are replaced with a check that the metadata is unchanged. Master's two new tests are kept.

Design question for reviewers: on master, OPTIMIZE rewrites data files from a different spec of the same arity (here identity(region) vs truncate(1, region)). This PR refuses that case. I kept the refusal because rewriting re-labels the partition values under the wrong transform.

Local checks: the changed translation units and the clickhouse binary build, and the 7 stateless tests of this PR pass on a local server. I did not run the integration tests locally.

Compaction applies only position deletes and regenerates only the
history of the current snapshot under `main`. Three table shapes passed
the existing checks and were silently corrupted:

- live equality deletes: the rewritten files drop them, so rows removed
  by an equality delete come back (copy of the
  `data_minio/deletes_db/eq_deletes_table` fixture: 881 rows before,
  980 after OPTIMIZE);
- a ref other than `main` (tag or branch): the rebuilt metadata has only
  `main`, and `clearOldFiles` deletes the files the ref kept;
- a snapshot outside the current snapshot's history (a branch, or main
  rolled back): every append is replayed in order, so the last one
  becomes current (main read [2] before OPTIMIZE and [2,3] after).

All three are now rejected with NOT_IMPLEMENTED before any file is
written. Master behaves the same (the equality-delete table becomes
unreadable there instead).

Found by clickhouse-gh[bot] review 5968980783 on ClickHouse#109838.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The stale INSERTs of this test (after DROP COLUMN, DROP + ADD COLUMN,
RENAME COLUMN and a nested field rename) are now refused by the input
header check in the `IcebergStorageSink` constructor with BAD_ARGUMENTS,
before `MultipleFileWriter` would refuse them with INCORRECT_DATA. The
test still checks that no file is written and that the table keeps its
rows; only the expected error changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rebuilt metadata starts from empty `refs`, and `generateNextMetadata`
recreates `main` with only `type` and `snapshot-id`, so OPTIMIZE dropped
`min-snapshots-to-keep`, `max-snapshot-age-ms` and `max-ref-age-ms` from
`main`. A later `expire_snapshots` then falls back to the table policy and
deletes snapshots the branch policy protected (measured: two manifest lists
deleted with `min-snapshots-to-keep = 10` on `main`, none with the fix).
Copy every field of the original `main` except its snapshot id onto the
rebuilt one. Other references are already refused before any file is written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The history rebuild replays `snapshots` in array order and makes the last
replayed append current, but the Iceberg spec does not tie that order to
the parent chain (iceberg-rust, for one, serializes it from a hash map).
With two appends listed out of order, OPTIMIZE committed the older append
as current and `clearOldFiles` removed the originals (measured: rows
[2, 3] became [2]). Every snapshot is already required to be an ancestor
of the current one, so they form one chain; refuse unless each snapshot's
parent is the snapshot listed before it.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4118ec4

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
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05829_autopr_skip_index_on_read_in_subquery not from this PR (it changes only Iceberg compaction and schema handling): a deterministic red of this test under the plan-based parallel replicas job: automatic parallel replicas collects no statistics for its queries there (#131450). Same red on 14 master commits since 2026-11-19 00:41Z (master report) and on 87 other PRs. The fix merged at 11:58Z, after this run started #132867 (mine, merged)
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05137_join_fixed_string_zero_bytes_runtime_filter not from this PR: the EXPLAIN check gets an extra BuildRuntimeFilter row under plan-based parallel replicas when the randomizer draws enable_parallel_blocks_marshalling = 0 (the runner's own diagnosis on this run). Same red on master (master report) and on 5 other PRs #132869 (mine, open)
PR praktika rollup of the rows above #132867 (mine, merged), #132869 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

The other CIDB FAIL rows on this head are the Iceberg cases of Bugfix validation (integration tests, *), which must fail on master; both checks are green. Mergeable Check is red only because of the rows above.

Session id: cron:our-pr-ci-monitor:20261119-120019

@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
PedroTadim and others added 2 commits November 20, 2026 17:22
# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp
…g-insert-column-count-oob-109835

Conflicts with the NDV statistics writer and the ORC timestamp fix:
- `writeDataFiles` in `Compaction.cpp`: keep this PR's order (data file statistics are
  collected after the deleted rows are removed), with master's
  `ORC::replaceTimestampsStoredAsEpoch` before it and the `column_sketches` update after it.
- `compactIcebergTable`: keep this PR's schema-id and partition-spec guards, then create
  master's `column_sketches`.
- `IcebergStorageSink` constructor: keep both the partition spec check and `column_sketches`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (1c255df). It conflicted with the NDV statistics writer (#118500 area, iceberg_write_table_statistics_ndv) and the ORC timestamp fix (#132657). How I resolved it:

  • writeDataFiles in Compaction.cpp: kept this PR's order, where the data file statistics are collected after the deleted rows are removed. Master's ORC::replaceTimestampsStoredAsEpoch runs before it and the column_sketches update after it.
  • compactIcebergTable: this PR's schema-id and partition-spec guards run first, then master's column_sketches are created.
  • IcebergStorageSink constructor: kept both the partition spec check and master's column_sketches.

The only CI failure on the previous head was 05042_crash_handler_without_global_context in Fast test (arm_darwin) (#133246). Its fix, #133270, is on master and is included in this merge.

Local checks: the clickhouse binary builds, and the 6 stateless tests of this PR plus 04329_iceberg_insert_stale_schema_field_id_107268 pass on a local server. I did not run the integration tests locally.

…g-insert-column-count-oob-109835

Conflicts:
- `IcebergWrites.cpp`: master moved the reads of the latest metadata into `IcebergStorageSink::readLatestMetadata`.
  The `validateInputSchemaMatchesCurrentIcebergSchema` call of the first read now follows master's `checkFieldIdsKept`,
  and the checks of the retry (the schema and the partition spec redefined under the same id) moved into the retry branch
  of `readLatestMetadata`.
- `Compaction.cpp`: kept the copy of all table-level metadata keys in `writeMetadataFiles`, which covers
  the keys master copies, including `properties`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (c93b930). It conflicted with the rework of the Iceberg insert commit (#133240: IcebergStorageSink::readLatestMetadata, the commit retry backoff) and with #128702 (metadata-log limit). How I resolved it:

  • IcebergStorageSink::readLatestMetadata, first read: master's checkFieldIdsKept (the insert was planned with another schema and a name now denotes another field, NOT_IMPLEMENTED) runs first, then this PR's validateInputSchemaMatchesCurrentIcebergSchema.
  • Commit retry: master moved the re-read of the metadata out of initializeMetadata into the retry branch of readLatestMetadata. This PR's retry checks moved there too: the schema is validated again under the same schema id, and a partition spec that was redefined under the same spec id or that disappeared is rejected. A rejected retry still removes its data files and manifests, in the destructor of the sink, like master's own schema-id check.
  • writeMetadataFiles in Compaction.cpp: kept this PR's copy of all table-level keys. It covers the keys master copies, including properties that Bound the metadata-log of Iceberg tables on write #128702 added.

The only red check was CH Inc sync, and the PR was conflicting with master. I compiled IcebergWrites.cpp, Compaction.cpp and Mutations.cpp on the merged tree. I could not link a server binary on this machine in time, so the stateless and integration tests of this PR have not been run on the merge; CI will run them.

OPTIMIZE rebuilds every snapshot through `generateNextMetadata` without a
refresh cursor, and `carryForwardRefreshCursor` only inherits from rebuilt
parents, so `clickhouse.refresh-cursor` disappears from the table. The next
APPEND INCREMENTAL refresh of a materialized view targeting the table then
finds no cursor (`RefreshTask` keeps no Keeper copy for a transactional target)
and reads its source from the beginning, appending every row again.

Measured: refresh (1), (2) into an IcebergLocal target, DELETE 1, OPTIMIZE,
insert 3, refresh: the target held [1,2,2,3] instead of [2,3] (also on the
master build 9f7ed31). Copy the cursor of the original current snapshot
onto the rebuilt current one, next to the `refs.main` copy; the carried
value is byte-identical.

Reported by clickhouse-gh[bot] in
ClickHouse#109838 (comment)

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... groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg out-of-bounds with a materialized view

3 participants