Skip to content

Apply Iceberg schema evolution when compacting (OPTIMIZE) - #110069

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-optimize-schema-evolution-read
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-optimize-schema-evolution-read

Conversation

@groeneai

@groeneai groeneai commented Jul 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120833
Related: #117116

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Iceberg OPTIMIZE (experimental compaction, allow_experimental_iceberg_compaction) now applies schema evolution: data files written under an older schema (for example before ALTER TABLE ... RENAME COLUMN) are read by their own schema and remapped to the current one, so the compacted files keep the original values instead of DEFAULT/NULL, and the rewritten metadata keeps the table's schemas, so the table stays readable instead of failing with ICEBERG_SPECIFICATION_VIOLATION. Into Avro or ORC such a compaction is refused.

Description

IcebergMetadata::optimize builds the compaction reader header from the table's current schema (getSampleBlock()), and Compaction.cpp read/regenerated everything against the current schema, ignoring per-file schema ids. After schema evolution this had three consequences:

  1. Data read: old data files were read by the current column names. The normal read path (StorageObjectStorageSource) handles this via getInitialSchemaByPath + getSchemaTransformer; compaction did not, so a renamed column was compacted into DEFAULT/NULL.
  2. Metadata regeneration: createEmptyMetadataFile always synthesizes schema-id 0 from the current column names with fresh field ids, rebinding schema-id 0 to different fields (ICEBERG_SPECIFICATION_VIOLATION on the next read) and losing the field ids the data files reference.
  3. Snapshots: regenerated snapshots were stamped with the current schema id while reusing the original snapshot ids, which are bound to their committed schema id on read (snapshot already registered with schema id ...).

Fix:

  • writeDataFiles reads each data file by its own schema (getClickhouseTableSchemaById) and remaps it to the current schema via getSchemaTransformationDagByIds, mirroring the normal read path. Position deletes are applied first (they reference original file row positions), then surviving rows are remapped.
  • writeMetadataFiles carries the real schemas, current-schema-id and last-column-id from the source metadata, and preserves each snapshot's originally committed schema id.
  • Schema-evolved compaction into Avro or ORC is refused (NOT_IMPLEMENTED): only the Parquet reader resolves the rewritten files' columns by field id.

Added a stateless regression (05508_iceberg_optimize_after_rename_column, over IcebergLocal and IcebergS3): INSERT, DELETE (positional delete so compaction has work), RENAME COLUMN, OPTIMIZE; it asserts the renamed column keeps its original values (no NULL/DEFAULT), the deleted row stays deleted and the position delete is compacted away. It fails before this change (ICEBERG_SPECIFICATION_VIOLATION) and passes after.

Verified locally on IcebergLocal (format-version 2): before the fix OPTIMIZE leaves the table unreadable; after it the renamed column keeps its values, and compaction without a rename is unchanged.


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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. IcebergLocal fmt-v2: INSERT 3 rows, DELETE id=2 (positional delete), RENAME COLUMN value TO label, OPTIMIZE ... allow_experimental_iceberg_compaction=1. Fails on demand pre-fix.
b Root cause explained? Yes. Compaction read old data files by current-schema names, regenerated metadata as fresh schema-id 0, and restamped snapshots with the current schema id — all ignoring per-file/committed schema ids after evolution.
c Fix matches root cause? Yes. Read each file by its own schema + apply the schema-transformation DAG (mirrors the normal read path); carry real schemas/current-schema-id/last-column-id into regenerated metadata; preserve each snapshot's committed schema id.
d Test intent preserved / new tests added? New integration test asserting the renamed column keeps original values (no NULL/DEFAULT) and the deleted row stays deleted. No existing test weakened.
e Demonstrated in both directions? Yes. Pre-fix: ICEBERG_SPECIFICATION_VIOLATION after OPTIMIZE. Post-fix: label reads hello/foo, 0 NULLs, count=2. Control run without rename unchanged.
f Fix is general, not a narrow patch? Handles any schema-id difference (not just rename); a control non-evolved compaction takes the unchanged current-schema path. Position deletes applied before remap on every file.
g Generalizes across inputs? Remap uses the general getSchemaTransformationDagByIds DAG (rename/add/type-promote), same as the normal read path; not tied to the one reproduced case.
h Backward compatible? Yes. Behavior only changes for schema-evolved compaction, which was previously broken (corruption / read failure). No setting default or on-disk format change.
i Invariants and contracts preserved? Delete transform runs first (positions reference original file order, row-preserving), then remap → output stays consistent with regenerated metadata; snapshot↔schema-id binding invariant restored.

Session id: cron:clickhouse-worker-slot-5:20260710-231500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @kssenii — could you review? This fixes Iceberg OPTIMIZE (compaction) after schema evolution: old data files were read by current-schema names and the regenerated metadata rebound schema-id 0, so a compacted table became unreadable (ICEBERG_SPECIFICATION_VIOLATION) or lost renamed-column data. Compaction now applies the same old→current schema transform as the normal read path. Found via clickhouse-gh[bot] review on #109994; scoped out of that PR per @ PedroTadim's request.

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

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fe5f360]

Summary: ❌

job_name test_name status info comment
La Casa Del Dolor (amd_debug) FAIL
Server shutdown FAIL cidb
Performance Comparison (arm_release, master_head, iceberg_local, 1/3) FAIL Performance dashboard
bloom_filter_insert #0 unstable query history
insert_statistics #2 unstable query history
insert_statistics #3 unstable query history
insert_statistics #4 unstable query history
insert_statistics #5 unstable query history
insert_statistics #6 unstable query history
merge_tree_insert #3 unstable query history
merge_tree_insert #4 unstable query history
merge_tree_insert #5 unstable query history
merge_tree_insert #12 unstable query history
7 more test cases not shown
Performance Comparison (arm_release, master_head, iceberg_s3, 1/3) FAIL Performance dashboard
insert_statistics #4 unstable query history
insert_statistics #5 unstable query history
insert_statistics #6 unstable query history
merge_tree_insert #24 unstable query history
merge_tree_simple_select #0 slower query history

AI Review

Summary

The PR makes experimental Iceberg OPTIMIZE read each file using its original schema, transform it to the current schema, preserve table metadata, and publish per-file statistics. It also retains both file generations when publication is uncertain. Reviewed head: fe5f360d24bd3d1c7000760ec0a77adf229a8cf2. The remaining findings below already have inline threads; no duplicate comments were posted. These mechanisms also exist on the base branch, so they are outstanding compaction limitations rather than newly introduced regressions.

Findings

❌ Blockers

  • Partition tuples must retain their partition specification. Compaction.cpp:1539 selects default-spec-id for every rewritten data manifest, then serializes each source file's partition tuple under that specification. An equal-arity change, such as day(ts) to month(ts), passes the arity check but assigns the old value a different meaning; partition pruning can omit live rows. Carry each source manifest's specification through the rewrite, or reject mismatched specifications before writing. [dismissed by author -- https://github.com/Apply Iceberg schema evolution when compacting (OPTIMIZE) #110069#discussion_r4078120204] The author considers this pre-existing and outside this PR; the current data-compaction writer still publishes the incorrect specification.

  • Retained snapshot IDs still change their historical row sets. Compaction.cpp:479 shares one DataFilePlan between snapshots, and the later delete-attachment pass modifies that shared plan. Thus APPEND → DELETE → OPTIMIZE makes the pre-delete snapshot return the delete-applied file. The new nested-rename test explicitly expects the historical row to disappear. Preserve separate rewrite results for distinct snapshot delete spans, or reject histories whose retained snapshots would change. [dismissed by author -- https://github.com/Apply Iceberg schema evolution when compacting (OPTIMIZE) #110069#discussion_r4240246807] The author's stated contract accepts this behavior, but reusing the same snapshot IDs still changes time-travel results.

⚠️ Majors

  • Successful cleanup can leave the metadata cache pointing at deleted files. Compaction.cpp:2120 deletes the old generation without invalidating the metadata cache populated during planning. With iceberg_metadata_staleness_ms > 0, subsequent reads can reuse the removed metadata or data paths until that window expires. Invalidate the table's metadata cache before deleting the old generation, as manifest-only compaction does. [dismissed by author -- https://github.com/Apply Iceberg schema evolution when compacting (OPTIMIZE) #110069#discussion_r3717363369] The author declined this as pre-existing; the stale-pointer failure remains on the successful-publication path. KeepEverything does not have this deletion problem.

  • Expiration can permanently prevent otherwise representable compaction. Compaction.cpp:1585 rejects a manifest first referenced by a retained delete-only snapshot, even when a later retained append also references it and is replayed. Track the first replayed reference for both attribution and sequence remapping. [dismissed by author -- https://github.com/Apply Iceberg schema evolution when compacting (OPTIMIZE) #110069#discussion_r3883551969] The author reproduced the refusal on both branches and deferred its fix; the current code still rejects that history. Keep the existing fail-closed behavior until a replacement is validated.

Tests
  • ⚠️ Add an actual equal-arity partition-evolution regression with filtered reads after data compaction. 05054 checks an arity mismatch, which cannot detect a tuple relabeled with a different same-width specification.
  • ⚠️ A historical-snapshot regression should compare the pre-delete snapshot's rows before and after OPTIMIZE; the new nested-rename assertion currently expects the changed row set.
Missing context / blind spots
  • ⚠️ No local ClickHouse build or executable was available. Runtime evidence comes from the existing regression tests, prior reproductions, and the current Praktika report, which reports no failed tests. Focused reproductions of the unresolved cases above would close the remaining runtime gap.
Final Verdict

❌ Block on the unresolved wrong-result paths: preserve or reject mismatched partition specifications, and preserve retained snapshots' row sets. The cache and expiration limitations remain separately recorded above. No new inline findings or thread replies were submitted; existing author decisions were left in their threads.

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

groeneai commented Jul 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

Addressed both review comments in 4a7b492 (per-data-file plan keying + strengthened regression test).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. IcebergLocal, fmt v2: INSERT 6 rows with iceberg_insert_max_rows_in_data_file=2 + small insert blocks (rollover to 3 data files in one manifest), DELETE WHERE id=3 (positional delete), OPTIMIZE. Pre-fix: count()=6 and only rows a,b survive (d,e,f dropped).
b Root cause explained? getPlan keyed path_to_data_file by manifest_file.manifest_file_path, which is shared by every data file in a manifest. The 2nd..Nth data files reused the first file's DataFilePlan; writeDataFiles then rewrote only the first file and writeMetadataFiles de-duplicated the shared patched_path, emitting a single replacement. So every live data file after the first in a multi-file manifest was dropped, with an inflated published row count.
c Fix matches root cause? Yes. Key path_to_data_file by the data file's own path (data_file->parsed_entry->file_path_key), so every live data file gets its own DataFilePlan and is rewritten.
d Test intent preserved / new tests added? Yes. The regression test now writes a multi-file manifest, asserts every live row survives (count()=5 + exact rows), and asserts the positional delete is gone from system.iceberg_files after OPTIMIZE. The schema-evolution (renamed column) assertions are kept.
e Both directions demonstrated? Yes. A/B on the same repro: per-manifest keying (pre-fix) fails (count()=6, rows d,e,f dropped); per-file keying (post-fix) passes (count()=5, all rows). Verified on Build-ID-checked debug binaries.
f Fix is general across code paths? Yes. This is the single point where compaction enumerates live data files into plans. The insert path (IcebergWrites) already tracks data files per file. No sibling collapse path remains.
g Fix generalizes across inputs? Multi-file manifests arise from both our own MultipleFileWriter rollover and external writers (Spark/Flink/Trino) packing many files per manifest; the key is the data file path, independent of datatype/partition. Repro exercises the rollover case; the fix is agnostic to file count and origin.
h Backward compatible? Yes. No setting, on-disk, or wire format change. Compaction is gated behind allow_experimental_iceberg_compaction; the change only makes it rewrite all live data files instead of one.
i Invariants and contracts preserved? Yes. One DataFilePlan per live data file now holds the correct data_object_info; positional-delete application (position-based, row-count-preserving) and the downstream metadata/manifest grouping are unchanged. count() after OPTIMIZE matches the pre-compaction live-row count.

Session id: cron:clickhouse-worker-slot-3:20260711-033400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. IcebergLocal fmt-v2 table (id, value, extra), INSERT 3 rows, DELETE id=2 (positional delete), ALTER ... DROP COLUMN extra, then OPTIMIZE ... allow_experimental_iceberg_compaction=1. On 4a7b492 OPTIMIZE succeeds and time travel to the pre-drop snapshot returns \N for extra; deterministic every run.
b Root cause explained? Compaction physically rewrites every historical data file into the current schema (writeDataFiles), while writeMetadataFiles preserves the original snapshot ids + committed schema-ids so old snapshots stay reachable for time travel. After a lossy evolution (DROP COLUMN / non-reversible type change) the rewritten files no longer contain the dropped/old-typed field, so reading a pre-evolution snapshot yields NULL/defaults or fails.
c Fix matches root cause? Yes. getPlan now rejects (NOT_IMPLEMENTED) when any schema-id still reachable via a snapshot has a field id missing from the current schema, or whose type differs from the current field of the same id. This directly prevents the lossy rewrite that breaks time travel.
d Test intent preserved / new tests added? New regression test_optimize_rejected_after_lossy_schema_evolution asserts OPTIMIZE is rejected after DROP COLUMN, the positional delete survives (OPTIMIZE did not run), and pre-drop time travel still returns the dropped column's original values. Existing rename + multi-file + side-effect assertions unchanged.
e Demonstrated in both directions? Yes. Buggy 4a7b492: OPTIMIZE succeeds, time travel loses extra (\N). Fixed f5d5d11: OPTIMIZE rejected Code 48; time travel returns x1/x2/x3. Build IDs verified (baseline 7cc636a8 vs fixed 5c61dd13; reapply produced byte-identical 5c61dd13).
f Fix general, not a narrow patch? Covers both lossy manifestations (dropped field id AND changed field type) across all snapshot-reachable schema-ids, not just the reported DROP COLUMN. Renames and additive evolution correctly stay allowed.
g Generalizes across inputs / types? The type check compares stringified Iceberg type JSON for the same field id, so it catches any non-identical type change (primitive widen, decimal precision/scale, struct/list/map, wrappers) as non-reversible. Renames keep type identical and pass; additive fields (present only in current) are safe and pass.
h Backward compatible? Yes. Behavior change is strictly a new fail-closed guard on an experimental feature (allow_experimental_iceberg_compaction); no on-disk/wire/metadata format change, no setting default change. Previously-succeeding cases (rename, additive, no-evolution) are unaffected.
i Invariants / contracts preserved? Yes. Pure read-only JSON inspection of initial_metadata_object before any file is written; throws before writeDataFiles/writeMetadataFiles so no partial rewrite. Upholds the time-travel contract (old snapshots stay readable after OPTIMIZE, per test_storage_iceberg_with_spark/test_optimize.py).

Session id: cron:clickhouse-worker-slot-0:20260711-041800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. IcebergLocal table with a nested struct, positional delete, metadata.json hand-edited to add a nested s.a->s.b rename schema (field id 3 preserved, type identical), current-schema-id advanced, snapshots left on the old id. OPTIMIZE is rejected on demand by the old textual guard.
b Root cause explained? The guard mapped each field id to stringifyJSON(f_type). For struct/list/map that JSON embeds child field names and ordering, so a nested rename/reorder/add changed the enclosing field's string. The cur != old check then treated it as a type change and rejected OPTIMIZE, even though getSchemaTransformationDagByIds remaps such evolution.
c Fix matches root cause? Yes. The signature is now built by a recursive field-id walk (walkTypeNode/schemaFieldTypes): each id maps to its leaf primitive type or its complex-kind marker, name/order-agnostic. Reject only field-id removals or leaf/kind type changes.
d Test intent preserved / new tests added? Yes. Added test_optimize_after_nested_rename (Spark) asserting nested rename + positional delete -> OPTIMIZE succeeds, values intact, pre-rename time travel works. Existing DROP-rejected, top-level-rename, and multi-file assertions kept.
e Both directions demonstrated? Yes, Build-ID-verified A/B on the same table: textual guard rejects (NOT_IMPLEMENTED); semantic guard allows and compacts correctly, while DROP COLUMN stays rejected and no-evolution/top-level-rename still succeed.
f Fix is general across code paths? Yes. The single guard is the only place that classifies evolution as lossy; walking recursively covers struct/list/map uniformly. No sibling code path duplicates the textual comparison.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The walk handles arbitrarily nested struct/list/map and any leaf primitive; nested renames/reorders/additions at any depth are allowed, removals/type-changes at any depth are rejected.
h Backward compatible? (maintainer-approved exception only) Yes. This only widens what OPTIMIZE accepts for an experimental feature (allow_experimental_iceberg_compaction); no setting default, on-disk/wire format, or existing-data validation changes.
i Invariants and contracts preserved? Yes. Read-only over the metadata JSON; the fail-closed contract (reject genuinely lossy evolution to keep post-compaction time travel correct) is preserved. The data-read/remap path (getSchemaTransformationDagByIds) is unchanged.

Session id: cron:clickhouse-worker-slot-0:20260711-051900

@groeneai

Copy link
Copy Markdown
Collaborator Author

Both concerns addressed in b89a011. Statistics and the partition index now live on DataFilePlan (per rewritten data file), not on ManifestFilePlan, mirroring MultipleFileWriter::getPerFileStatistics.

Comment 1 (partition values per manifest): DataFilePlan::partition_index records the file's own partition. When regenerating a manifest, compaction builds a per-file partition-values vector aligned with data_file_names and passes it to generateManifestFile, so each output entry gets its own partition tuple instead of the last-visited one.

Comment 2 (statistics unioned across files): each DataFilePlan owns a DataFileStatistics that writeDataFiles updates only from that file's rewritten chunks. Compaction passes a per-file statistics vector so each data_file record is stamped with its own bounds/null counts/column sizes.

generateManifestFile gained two optional trailing per-file vectors (per_file_partition_values, per_file_statistics); when supplied they take precedence over the single shared arguments. The normal write (IcebergStorageSink) and mutation paths pass them null and are byte-unchanged.

Regression test test_optimize_multi_partition_manifest (Spark, one INSERT writing two identity-partitioned ranges into one manifest, disjoint id ranges, positional delete in one partition). Verified in both directions: on HEAD before this commit SELECT count() WHERE part = 0 returns 0 instead of 30 (partition pruning drops live files); with the fix all rows survive with correct partition-filtered reads, each data-file entry carries its own partition value, and the two entries' lower bounds are not unioned.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks — both addressed in 3d17b02.

A. Evolution check thrown before need_optimize is known. Moved checkCompactionSupportsSchemaEvolution to run after the manifest scan, gated on plan.need_optimize (i.e. only when there are live positional deletes to rewrite). A no-op OPTIMIZE on a table with a historical DROP COLUMN / type change now stays a no-op instead of throwing NOT_IMPLEMENTED. New regression test_optimize_noop_after_lossy_schema_evolution (INSERT, DROP COLUMN, no DELETE, then OPTIMIZE) fails with NOT_IMPLEMENTED on the previous code and passes now. The existing rejection test (with a delete present) still passes.

B. Metadata object still mostly synthetic. writeMetadataFiles now starts from a deep copy of plan.initial_metadata_object instead of createEmptyMetadataFile, so table-uuid, location, partition-specs, default-spec-id, last-partition-id, sort-orders, properties and refs are all preserved. Only the snapshot-history fields (snapshots, snapshot-log, metadata-log, statistics, current-snapshot-id, last-sequence-number, refs.main pointer) are reset on the copy, since the loop regenerates them from scratch via generateNextMetadata reusing the original snapshot ids. The final metadata is written through writeMetadataFileAndVersionHint (the same helper the INSERT/mutation paths use), and the generator version is advanced to metadata_version + 1, so version-hint.text stays in sync after clearOldFiles.

New regression test_optimize_preserves_partition_spec writes a PARTITION BY part table, deletes a row, OPTIMIZEs, then INSERTs again and checks partition pruning returns exactly the live rows per partition. Before the fix the post-OPTIMIZE writes were unpartitioned (empty spec, partitioner == nullopt) and pruning dropped live rows — the test fails with '' == '1\ta\n5\te\n' on the previous code and passes now.

Report URL for the original failure and the pre-PR validation gate for this change are below.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two new integration tests reproduce both concerns deterministically: test_optimize_noop_after_lossy_schema_evolution (concern A) and test_optimize_preserves_partition_spec (concern B).
b Root cause explained? (A) checkCompactionSupportsSchemaEvolution was called in getPlan before plan.need_optimize (computed only after the manifest scan), so a no-op OPTIMIZE on a table with a historical DROP COLUMN threw NOT_IMPLEMENTED even with nothing to rewrite. (B) writeMetadataFiles bootstrapped the compacted metadata from createEmptyMetadataFile, which invents a fresh table-uuid and empty partition-specs/default-spec-id/sort-orders/properties; a subsequent INSERT read the empty spec (partitioner == nullopt) and wrote unpartitioned data into a partitioned table, and version-hint readers could lose the table.
c Fix matches root cause? Yes. (A) The guard now runs after the scan, gated on need_optimize. (B) Metadata starts from a deep copy of plan.initial_metadata_object (preserving all table-level fields), with only snapshot-history fields reset since the loop regenerates them; written via writeMetadataFileAndVersionHint.
d Test intent preserved / new tests added? Two new regression tests added. Existing test_optimize_after_rename_column and test_optimize_rejected_after_lossy_schema_evolution still pass (the rejection guard still fires when a delete is present).
e Both directions demonstrated? Yes. On the pre-fix binary: A fails with NOT_IMPLEMENTED, B fails with AssertionError: '' == '1\ta\n5\te\n'. On the fixed binary both pass. All 4 tests (2 new + 2 existing) pass on the fixed binary.
f Fix is general across code paths? Yes. The write/mutation metadata paths already start from the real metadata + use writeMetadataFileAndVersionHint; this brings the compaction path in line with them rather than diverging via a synthetic object. Guard placement is the single compaction entry point.
g Fix generalizes across inputs? Concern A covers any lossy evolution (DROP COLUMN / type change) with no deletes. Concern B preserves the spec for any partition layout; regeneration of snapshot history is independent of partition/schema shape.
h Backward compatible? Yes. No setting default, on-disk, or wire format change. The compacted metadata now retains MORE of the source metadata than before (previously it dropped uuid/specs/etc.), so it is strictly more compatible; version-hint.text is only written when iceberg_use_version_hint is set, matching the write path.
i Invariants and contracts preserved? Yes. generateNextMetadata requires the snapshot-history fields to reflect a clean starting state; the copy resets exactly those (snapshots, snapshot-log, metadata-log, statistics, current-snapshot-id, last-sequence-number, refs.main) while preserving schemas/current-schema-id and all table-level metadata. Snapshot ids and committed schema-ids are still reused as before.

Session id: cron:clickhouse-worker-slot-0:20260711-073400

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Integration tests (amd_asan_ubsan, flaky) failure was the round-8 test I added: spark.sql("ALTER TABLE t RENAME COLUMN s.a TO s.b") raised [PARSE_SYNTAX_ERROR] — Spark's Iceberg RENAME COLUMN target is the new leaf name only, not the dotted path. Fixed to RENAME COLUMN s.a TO b (matches test_tuple_evolved_simple.py/test_array_evolved_with_struct.py); the subsequent s.b/s.a reads and all assertions are unchanged. Pushed 9dd2cb6.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes — flaky-check ran the new test repeatedly; both [local] and [s3] failed every time at test_optimize.py:241 with [PARSE_SYNTAX_ERROR] Syntax error at or near '.'.
b Root cause explained? Spark Iceberg RENAME COLUMN <path> TO <name> takes the NEW LEAF NAME as target, not a dotted path. ... TO s.b is invalid DDL; the ALTER threw before the test could exercise compaction.
c Fix matches root cause? Yes — target changed from s.b to b, the leaf-name form Spark accepts.
d Test intent preserved? Yes — the field still becomes s.b; the nested-rename OPTIMIZE-succeeds + values-intact + pre-rename time-travel assertions are unchanged. DROP-rejected / top-level-rename / multi-file / side-effect assertions untouched.
e Demonstrated both directions? The invalid DDL failed 100% in CI; the leaf-name form is the exact syntax proven by the existing passing nested-rename tests (test_tuple_evolved_simple.py RENAME COLUMN b.a TO e).
f General, not narrow patch? Test-only DDL syntax correction; no product-code change.
g Generalizes across inputs? N/A (test DDL fix, not a code path).
h Backward compatible? N/A (test-only).
i Invariants/contracts preserved? N/A (test-only).

Session id: cron:clickhouse-worker-slot-0:20260711-090700

@groeneai

Copy link
Copy Markdown
Collaborator Author

Both addressed in 2ceb1b2.

1. Refs to skipped (delete-only) snapshots. After the replay loop, prune any refs entry whose snapshot id was not regenerated (delete-only DELETE / position-delete-only OVERWRITE are skipped by tryGetAppendUpdate). main is re-pointed to the last replayed snapshot by generateNextMetadata, so it stays valid; only orphaned tags/branches are dropped (logged at WARNING).

2. next-row-id (format v3). Reset next-row-id to 0 in the snapshot-state clear block, alongside snapshots / last-sequence-number / current-snapshot-id. generateNextMetadata then assigns first-row-id starting at 0 across the replayed history instead of the preserved (advanced) tail.

Regression coverage (no-Spark, local, test_writes_optimize_after_rename.py):

  • test_optimize_prunes_refs_to_delete_only_snapshot: inject a tag pinned to the delete-only snapshot, OPTIMIZE, assert the tag is gone and every surviving ref resolves to a regenerated snapshot.
  • test_optimize_resets_next_row_id_format_v3: v3 table, assert first-row-ids restart at 0 and next-row-id equals the replayed total (not old value + replay).

Verified both directions locally (IcebergLocal): pre-fix the tag survives pointing at an absent snapshot and next-row-id is inflated (old 5 + replay); with the fix the tag is pruned and lineage restarts at 0.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in cd462d2. The deep-copy metadata bootstrap now clears `partition-statistics` alongside `statistics` in the snapshot-state reset block, so a `partition-statistics` array copied from Spark/Flink source metadata no longer publishes a dangling `statistics-path` after `clearOldFiles` deletes the pre-compaction `metadata/` subtree (SnapshotFilesTraversal treats both as reachable files).

Regression: `test_optimize_clears_partition_statistics` injects a `partition-statistics` entry pointing at a metadata-side file, runs OPTIMIZE, and asserts the compacted metadata carries no `partition-statistics`. Verified both directions locally: pristine HEAD leaves the dangling entry, the fix clears it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Integration tests (amd_asan_ubsan, flaky) failure on this PR's added test test_optimize_after_nested_rename was a bug in the test's assertions, not in the compaction path. Fixed in 0a681e0.

Root cause (verified locally with IcebergLocal + a hand-crafted nested-rename metadata):

  • The post-OPTIMIZE assertion read the renamed nested leaf s.b. Iceberg subcolumn pushdown resolves a struct child by its on-disk name in ExtractColumnsTransform, so SELECT s.b throws NOT_FOUND_COLUMN_IN_BLOCK (s.b in block ... only id, s). This is a pre-existing normal-read-path limitation for renamed nested fields — it fails the same way before OPTIMIZE, i.e. it is independent of compaction. (The existing nested-rename evolution tests, e.g. test_tuple_evolved_simple.py, only ever read the whole struct via check_schema_and_data, never a renamed nested leaf.)
  • The fix reads the whole struct SELECT id, s instead, which is remapped to the current schema and correctly returns ('x',10),('z',30) — proving the values survive compaction under the renamed schema.
  • The time-travel assertion is also aligned with the sibling test_optimize contract: compaction physically rewrites the files and applies the positional delete, so an old snapshot reads the compacted delete-applied files (id=2 gone), matching how test_optimize asserts time travel returns the compacted rows.

The semantic lossy-evolution guard, per-data-file rewrite, and DROP-COLUMN rejection from the earlier rounds are unchanged and still exercised.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT id, s.b, s.n on the nested-renamed table throws NOT_FOUND_COLUMN_IN_BLOCK: s.b every time (locally reproduced with IcebergLocal + hand-crafted nested-rename metadata), both before and after OPTIMIZE.
b Root cause explained? Iceberg subcolumn pushdown (ExtractColumnsTransform) resolves a struct child by its on-disk name, so a renamed nested leaf (s.b) is unresolvable — a pre-existing normal-read-path limitation, independent of compaction. The test wrongly asserted s.b.
c Fix matches root cause? Yes. Read the whole struct SELECT id, s (remapped to current schema) instead of the renamed leaf; align time-travel assertion with the sibling test_optimize (compaction applies the positional delete).
d Test intent preserved / new tests added? Yes. The test still proves the nested rename is allowed by the semantic guard, OPTIMIZE succeeds, live values survive, and old-snapshot time travel works — just via assertions that are valid on the normal read path.
e Demonstrated in both directions? Yes (local IcebergLocal): whole-struct SELECT s returns ('x',10),('z',30) after OPTIMIZE and time-travel returns the compacted delete-applied rows; the old SELECT s.b throws before and after OPTIMIZE.
f Fix is general, not a narrow patch? N/A (test-only assertion fix). The product code (semantic guard, per-data-file rewrite, DROP rejection) is unchanged.
g Fix generalizes across inputs? N/A (test-only assertion fix).
h Backward compatible? N/A (test-only assertion fix).
i Invariants and contracts preserved? N/A (test-only assertion fix).

Session id: cron:clickhouse-worker-slot-0:20260711-103800

@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed in c246fc3.

Concern 2 (commit-conflict data loss) — fixed. writeMetadataFiles now returns the writeMetadataFileAndVersionHint result, and compactIcebergTable throws CONCURRENT_ACCESS_NOT_SUPPORTED (skipping clearOldFiles) when the commit lost the race, matching IcebergStorageSink/Mutations/ExpireSnapshotsExecute. Verified both directions on a standalone IcebergLocal server by pre-creating a valid next metadata version (the "winner") while pinning version-hint.text to the current one: pristine HEAD returned silently and clearOldFiles deleted the pre-compaction data (data files 2 -> 1); with the fix OPTIMIZE aborts and the data files survive (2 -> 3). Regression: test_optimize_aborts_on_metadata_commit_conflict.

Concern 1 (decimal precision/scale in the type signature) — already covered; added a test to pin it. In this codebase Iceberg encodes decimal and fixed as string primitives ("decimal(P, S)", "fixed[N]" — see IcebergSchemaProcessor::getSimpleType), not type objects. walkTypeNode's container->isObject(type_key) is therefore false for them, so they take the primitive-leaf branch out[id] = getValue<String>(type_key) and the full parameterized string (precision/scale, fixed length) is in the signature — the out[id] = kind collapse only fires for struct/list/map. An object-encoded decimal would throw Unknown Iceberg type on read. Confirmed empirically: injecting a reachable schema with decimal(10, 2) vs a current decimal(20, 2) makes OPTIMIZE reject with NOT_IMPLEMENTED ("field id N changed type"). Added test_optimize_rejected_after_decimal_precision_change to guard against a future regression here.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Concern 2: pre-create a valid v(N+1).metadata.json while pinning version-hint.text to vN, then OPTIMIZE -> deterministic conflict. Concern 1: inject a reachable schema with decimal(10, 2) vs current decimal(20, 2) -> deterministic NOT_IMPLEMENTED.
b Root cause explained? Concern 2: writeMetadataFileAndVersionHint returns false on commit conflict, but compaction ignored it and always ran clearOldFiles, deleting pre-compaction files while the table pointed at the winner's snapshot. Concern 1: decimal/fixed are string-encoded, so the type signature already carries precision/scale (false positive).
c Fix matches root cause? Yes. Concern 2: propagate the bool and throw CONCURRENT_ACCESS_NOT_SUPPORTED before clearOldFiles. Concern 1: no code change needed; added a test to pin the existing correct behavior.
d Test intent preserved / new tests added? Added test_optimize_aborts_on_metadata_commit_conflict and test_optimize_rejected_after_decimal_precision_change. No existing test weakened.
e Both directions demonstrated? Concern 2: pristine deletes data (files 2->1); fix aborts and preserves data (2->3). Concern 1: guard rejects on the fix build (NOT_IMPLEMENTED).
f Fix is general across code paths? Yes. The conflict-abort mirrors every other Iceberg commit path (IcebergStorageSink, Mutations, ExpireSnapshotsExecute, IcebergWrites), which all abort/retry on the false return.
g Fix generalizes across inputs (params/datatypes/wrappers)? Concern 1 test covers the parameterized-primitive family (decimal precision/scale; fixed[N] takes the same string-primitive path). Concern 2 is input-independent (metadata commit race).
h Backward compatible? (maintainer-approved exception only) Yes. Aborting a lost-race OPTIMIZE (experimental allow_experimental_iceberg_compaction) is strictly safer; no format/setting/default change.
i Invariants and contracts preserved? Yes. Upholds the reachable-file contract: clearOldFiles runs only after the compacted metadata is actually published, so the table never references deleted files.

Session id: cron:clickhouse-worker-slot-1:20260711-101900

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c246fc3

CI fully finished (Finish Workflow + Mergeable Check both green; only CH Inc sync pending, exempt). All clickhouse-gh[bot] review rounds (per-file stats/partition, evolution-check deferral + metadata deep-copy preservation, refs/next-row-id, partition-statistics dangling path, decimal-precision guard + commit-conflict abort) addressed through this head. No PR-caused failure remains.

Check / test Reason Owner
Integration tests (amd_asan_ubsan, flaky) prior test_optimize_after_nested_rename non-determinism fixed in this PR @ 0a681e0 (read whole struct, not renamed leaf) — job green on this head
Bugfix validation (integration tests, amd64 / aarch64) per-test master-fails / PR-passes demonstration rows expected (jobs passed success) — this is the bugfix-validation contract
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260711-183000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged current master (8da8054) to resolve the conflict flagged by the conflict check. Master had merged the manifest-consolidation feature (#98178) plus the ORC-position-delete fix, which reworked the same `generateManifestFile` and compaction paths this PR touches.

Reconciliation:

  • `generateManifestFile`: kept master's new params (`data_file_formats`, verbatim `per_file_statistics`, `data_file_sort_order_ids`, `per_file_entry_lineage`, `schema_to_serialize`) and appended this PR's two OPTIMIZE overrides, renamed `per_file_statistics` -> `per_file_fresh_statistics` to avoid the name collision (master carries source stats verbatim for a manifest-only rewrite; ours are freshly recomputed bounds for physically-rewritten files).
  • `writeDataFiles`: kept the schema-evolution reader-header + remap, and adopted master's now-conditional `delete_file_transform` (skipped for a data file with no attached position deletes), building it against the file's own (possibly older) schema so deletes apply before the remap.
  • OPTIMIZE manifest write keeps per-file partition/statistics accounting (drops master's per-manifest `grouped_by_manifest_files_partitions`, which assumed one partition per manifest).

All prior CR fixes preserved. Builds clean.

partition_columns,
plan.partition_encoder.getPartitionValue(grouped_by_manifest_files_partitions[manifest_entry]),
/*partition_values=*/{},
ChunkPartitioner(fields_from_partition_spec, current_schema->getArray(Iceberg::f_fields), context, sample_block_).getResultTypes(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

writeMetadataFiles still hard-codes every rewritten data manifest to the current default-spec-id, but per_file_partition_values comes from each source file's original partition_key_value. That is fine only when the table has never had partition evolution. writeConsolidatedManifestFile just above had to resolve the spec per manifest for exactly this reason.

A concrete trace is PARTITIONED BY (region), then DROP PARTITION FIELD region (or ADD PARTITION FIELD ...), DELETE, OPTIMIZE. The old files still carry the old spec's tuple, but this call serializes them under the current spec. generateManifestFile then indexes one value per current partition column in effective_partition_values (IcebergWrites.cpp:507-535), so a changed-arity spec can read past the end of the tuple; if the arity happens to match, the manifest still gets stamped with the wrong partition metadata and partition pruning goes wrong.

Can we carry the source manifest's partition_spec_id and derived partition types through ManifestFilePlan here, mirroring writeConsolidatedManifestFile, instead of unconditionally using default-spec-id?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 93987ad

Every failure below has an owner. This ledger covers the post-merge head (slot-3 duplicate-setting Style fix on top of the origin/master conflict-resolution merge). Supersedes the pre-merge ledger (issuecomment-4948318768, head c246fc3).

Check / test Reason Owner
Bugfix validation (integration tests, amd64 + aarch64) test-level FAIL rows are the expected master-side half (regression must fail on master, pass on PR) Job conclusion = SUCCESS — not a failure
Sync - CH Inc sync (private, not actionable)

Finish Workflow = SUCCESS; Style check (cpp) = SUCCESS on this head (duplicate iceberg_use_version_hint decl from the master merge removed in 93987ad). No PR-caused failure, no non-exempt red.

Session id: cron:our-pr-ci-monitor:20260717-220147

@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f824b7b9-35fc-4388-9565-ce15fdbf6581
  • MIRAI run: 11cf4e1a-4095-4be9-82de-471a2f6d7980
  • PR check IDs:
    • clickbench_949477_1791760567
    • clickbench_949490_1791760567
    • clickbench_949496_1791760567
    • tpch_adapted_1_official_949506_1791760567
    • tpch_adapted_1_official_949533_1791760567
    • tpch_adapted_1_official_949547_1791760568

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - edbcf7e

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
AST fuzzer (arm_asan_ubsan) / Logical error: Cannot call function A because is has B arguments but C columns were captured. (STID: 2458-4cb4) not from this PR (it changes Iceberg compaction only): the abort is in VirtualColumnUtils::filterBlockWithExpression <- MergeTreeDataSelectExecutor::filterPartsByVirtualColumns, where a reduced and keeps the arity of the original function. Seen on 2 master runs and 4 other PRs since 2026-10-10 21:25Z #125126 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05339_parquet_prewhere_subcolumn_read_through_column not from this PR: the test passes a session temporary table to IcebergLocal, which the replicated DDL worker cannot see (UNKNOWN_TABLE on iceberg_path). 38 PRs and 20 master runs show it since 2026-10-10 21:55Z #125121 (external, merged 00:36Z), the revert of my #124685 that added this test. The tested merge commit predates it, so I will merge master here to pick it up
Mergeable Check, PR rollups, red only because of the rows above #125126 and #125121
Sync - CH Inc sync (private, not actionable by me)

All check runs completed and Finish Workflow is green. The Bugfix validation (*) rows are the expected inversion of this PR's new tests on master (all four jobs green). CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261011-030008

@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 11, 2026
data_file_ptr = it->second;
}
plan.partitions[partition_index].push_back(data_file_ptr);
plan.snapshot_id_to_data_files[snapshot.snapshot_id].push_back(plan.partitions[partition_index].back());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

snapshot_id_to_data_files is storing the same DataFilePlan for every snapshot that still references a source file, and the delete-attachment pass below mutates that shared plan once before writeDataFiles rewrites it.

That means a later position delete is baked into the single rewritten patched_path for that file and then reused by older snapshots during history replay. A simple APPEND(F) -> DELETE some rows from F -> OPTIMIZE history will therefore make time travel to the pre-DELETE snapshot read the post-delete file.

I think this needs snapshot-specific rewrite lineage here (or, equivalently, separate rewritten files for distinct delete spans) rather than one shared rewritten file per source path.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 162eed9

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, AsyncInsert, s3 storage, sequential) / 03821_drop_workload_during_query_race flaky, not from this PR (it changes Iceberg compaction only): the INVALID_SCHEDULER_NODE stack trace of a query racing DROP WORKLOAD (RequestQueue::enqueueRequest <- CPULeaseAllocation) reaches stdout, and the runner's rerun failed 3 of 61 times. The same test failed on 42 other PRs and on master in the last 3 days #126345 (mine, open)
Mergeable Check, PR rollups, red only because of the row above #126345 (the owner of the row above)
Sync - CH Inc sync (private, not actionable by me)

All check runs completed and Finish Workflow is green. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261017-220006

@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Dear @scanhex12, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 30, 2026
`OPTIMIZE TABLE` on an Iceberg v2 table failed with

    Code: 48. DB::Exception: Position deletes are only supported for data files
    of Parquet format in Iceberg, but got ORC. (NOT_IMPLEMENTED)

on a snapshot that `SELECT` reads correctly. The carrier is a current snapshot
holding, in one partition, a non-Parquet data file whose sequence number is not
above a position delete's, where that delete references only Parquet data files.
Such a table has to be written by another engine, because ClickHouse's own
DELETE and UPDATE refuse while a non-Parquet data file is live in the current
snapshot (`validateSnapshotDataFileFormatsForMutation`).

Compaction and the read path both decide whether a position delete applies to a
data file, and compaction's decision had one term fewer. `IcebergIterator::next`
also tests the delete's `lower_reference_data_file_path` and
`upper_reference_data_file_path` against the data file's own
`data_object_file_path_key`; `getPlan` tested only the partition value and the
sequence number, so it handed a delete that provably does not name a data file to
`addPositionDeleteObject`, which rejects a non-Parquet data file. This adds that
bounds test, and only it, so the per-pair decision matches the read path's. As on
read, absent bounds mean no pruning, so a delete recording no bounds still
reports the same error a `SELECT` reports.

Results were never wrong: both delete transforms call
`filterChunkToCurrentDataFile`, so an over-attached delete could not delete
another file's rows. The change only shrinks the attachment set, and compaction's
candidate set is a superset of the read path's, so no delete the read path
applies can be lost. `writeDataFiles`' precondition still holds: a previously
over-attached non-Parquet file now takes the already-exercised no-deletes branch.

Equality deletes are unaffected. `getPlan` collects only position deletes, an
OVERWRITE snapshot carrying equality deletes is refused earlier by
`overwriteIsPositionDeleteOnly`, and `addEqualityDeleteObject` has no format
precondition.

The pass still buckets deletes by partition value without
`common_partition_specification`, so the two predicates match per pair, not as a
whole. That is left alone: data compaction resolves one default partition spec
and rewrites every manifest under it, so narrowing the bucket per spec would fix
one term of a path that then collapses all specs to one.

The regression test is an integration test because the snapshot needs an
external writer. It builds the mixed-format table with Spark and asserts the row
set is unchanged across the `OPTIMIZE`. Its arming conditions are asserted
separately, and they hold on the unfixed build, so a green run measures the fix
rather than the fixture.

Related: ClickHouse#110069, where this was reported, and ClickHouse#102508 / ClickHouse#105893, which fixed the
mutation half of the same restriction.
@fm4v

fm4v commented Nov 2, 2026

Copy link
Copy Markdown
Member

@groeneai continue the work on this PR

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master and resolved the conflicts in 4374d0f (master's per-file partition spec and position-delete bounds in Compaction.cpp, the Bool partition value in IcebergWrites.cpp, and the tests both sides appended to test_optimize.py).

On the merged build: test_storage_iceberg_with_spark/test_optimize.py 9/9 (including master's two new compaction tests), test_storage_iceberg_no_spark/test_writes_optimize_after_rename.py 19/19, and the stateless Iceberg OPTIMIZE tests pass, except three that need S3 or Azure endpoints, which CI runs. I also re-checked that the Avro refusal is still needed after master's Avro field-id changes: without it, a renamed column still fails to read and a swapped pair still exchanges values.

The PR is ready for review.

Iceberg data compaction now reads each data file with the schema it was written under and keeps
each rewritten file listed under its source schema, rejects compaction after a lossy schema
evolution, an added column or into a non-Parquet format, writes per-file partition values and
statistics, preserves table metadata on replay (committed schema ids, refs, partition statistics,
next-row-id), and treats a lost or unconfirmed metadata commit safely: the rewritten files are
removed only when the commit is certainly lost, and the version hint is kept out of the cleanup.

Squashed from ClickHouse#110069 after merging master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim
PedroTadim force-pushed the groeneai/iceberg-optimize-schema-evolution-read branch from 4374d0f to bc6c8f3 Compare November 5, 2026 17:04
groeneai and others added 3 commits November 5, 2026 18:05
The rename, dropped/added column, no-op, requiredness, partition spec and format version 3
cases of test_writes_optimize_after_rename.py run plain SQL against one table, so they move to
05508-05510, over IcebergLocal and IcebergS3 (MinIO). Each case keeps its assertions: the
compaction ran (the position delete is gone), or the refusal names its own guard and leaves the
data and time travel intact. The integration module keeps only the cases that edit the metadata
files directly or stage a version-hint failure.

On the master snapshot 39b9f2d the rename, partition spec and refusal cases fail; on this
branch they pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test built its fixture with 20 single-row INSERTs, so each run made 22
Iceberg commits and OPTIMIZE re-read every manifest of every snapshot with
the metadata cache disabled. The flaky check runner is disk-bound (about
97% iowait during the sequential runs) and every run took 183-206 s on msan,
over the 180 s limit.

One INSERT of the same 20 rows writes one data file per partition, which is
enough: compaction runs whenever a positional delete exists, and the arity
guard rejects the first rewritten file. Per run this is 3 metadata versions
instead of 22, and 64 file opens instead of 449 (local query time 2.55 s ->
0.17 s). Master still aborts on the same OPTIMIZE, and the fixed server still
reports ICEBERG_SPECIFICATION_VIOLATION and keeps all 18 rows.

Also drop `no-parallel`: every run uses its own database and table path, so
DETACH/ATTACH cannot interfere with another run (100 runs at 16 and 31 jobs).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In the ParallelReplicas job, with `optimize_trivial_count_query = 0`, the
probe's `SELECT count()` runs on two replicas, and both log the same
metadata under one query id, so the test printed `[5,5] [5,5]` instead of
`[5] [5]` (reproduced 3/3 locally with that job's profile and cluster).

Read the distinct metadata contents first, as 05509 already does: replica
duplicates collapse, while two different metadata versions would still show
as two values.

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

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fe5f360

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
La Casa Del Dolor (amd_debug) / Server shutdown shutdown hang, not from this PR (it changes Iceberg compaction only): at a scheduled restart DatabaseCatalog::shutdown waits for the table-drop task, whose MergeTreeData::dropAllData cannot get a parts-cleaning thread because 128 of them wait in DiskObjectStorageTransaction::waitBlobRemoval for Azure blob removals. Server shutdown failed on 38 PRs and 11 master runs of this check since 2026-11-02 a fix task is created (investigating at full effort, fixing-PR link to follow here)
Performance Comparison (arm_release, master_head, iceberg_local, 1/3) and (arm_release, master_head, iceberg_s3, 1/3) / prewhere_subcolumn_read_steps not from this PR: the one error of each shard is the Iceberg rewrite refusing that test's JSON column (Column j of type JSON(max_dynamic_paths = 0) has no Iceberg equivalent). The test reached master with #124553 and is not in tests/performance/iceberg_skip_list.txt; the same error failed these shards on 5 other PRs since 22:14 UTC yesterday a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above a fix task is created (the same tasks as the rows above)
Sync - CH Inc sync (private, not actionable by me)

All check runs completed and Finish Workflow is green. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261106-010008

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Iceberg rewrite error of prewhere_subcolumn_read_steps in Performance Comparison (iceberg_local/iceberg_s3, 1/3): #129658

@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

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-unknown PR origin: unclassified (legacy task) pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg compaction after a DELETE on a schema-evolved table rewrites the metadata as v0 and makes the table permanently unreadable

4 participants