Skip to content

Iceberg OPTIMIZE TABLE commits a new snapshot instead of rewriting the table - #124114

Open
groeneai wants to merge 26 commits into
ClickHouse:masterfrom
groeneai:iceberg-compaction-publish-repair
Open

groeneai wants to merge 26 commits into
ClickHouse:masterfrom
groeneai:iceberg-compaction-publish-repair

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

OPTIMIZE TABLE on an Iceberg table (allow_experimental_iceberg_compaction) now commits one replace snapshot on top of the current one, merging position deletes into the data files they apply to. Earlier snapshots, the table UUID, partition specs and properties stay as they were, nothing is deleted at commit time (expire_snapshots reclaims the replaced files), and tables in catalogs that ClickHouse can INSERT into and tables read through iceberg_use_version_hint can now be compacted.

Description

Closes #123982. Data compaction rebuilt the table: it replayed every retained snapshot into a new metadata file, always named v0.metadata.json, and then deleted a listing of metadata/ and data/ taken before the write. So a second OPTIMIZE left no metadata file, time travel to a committed snapshot returned other rows, and a catalog could not express the commit.

Now compaction plans over the current snapshot only. Each data file with applicable position deletes is rewritten into the current schema with SELECT's read chain; the replaced files stay as DELETED entries for writers that validate concurrent commits. Other manifests are carried forward, and the snapshot is committed like OPTIMIZE ... MANIFEST: metadata-file CAS plus version hint, or the catalog. Glue cannot reject a concurrent commit, so its pointer is re-read just before the swap; if it moved, compaction retries. A lost race is retried on top of the winner; after a failed metadata write the file is read back, and another writer's bytes mean a lost race. Any other failure keeps every file and throws UNKNOWN_STATUS_OF_TRANSACTION, for OPTIMIZE ... MANIFEST too (it used to delete the manifests of a commit that may have landed). A null current-snapshot-id now means no current snapshot, as for SELECT.

The diff is big because a catalog can only add a snapshot on top of the current one, so no patch of the rewrite could reach catalogs.

Overlaps: merged #122833, #116941 and #128759 patched the removed rewrite, and their cases hold here; #110069 and #121500 patch it too. #115390 reconciles failed writes for every writer; this PR adds only the lost-race case.

Tests: new 05325_iceberg_optimize_replace_snapshot (every arm fails on master, including the reproducers of #123282 and #123909); 05483 and 05401 now expect the earlier snapshots to keep their totals and files; integration and unit tests.


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

groeneai and others added 9 commits October 5, 2026 12:24
Data compaction used to rebuild the whole table: it rewrote every snapshot of
the history from an empty metadata file and then deleted a raw listing of the
table's files. That lost the table uuid, partition specs and properties,
changed the content of committed snapshots, could not be committed through a
catalog, and a second OPTIMIZE deleted the only metadata file.

Now OPTIMIZE plans over the current snapshot only: every live data file with an
applicable position delete (the rule SELECT uses) is rewritten without the
deleted rows into the current schema, its untouched siblings in the same
manifest are kept as EXISTING entries, unaffected manifests are carried
forward, and the delete manifests are dropped. The result is committed as one
replace snapshot through the catalog or as the next metadata file plus the
version hint. Nothing is deleted at commit; expire_snapshots and
remove_orphan_files reclaim the replaced files.

The commit helper of manifest compaction is shared and now distinguishes a
lost race (retry) from an unknown outcome (keep the files, throw
UNKNOWN_STATUS_OF_TRANSACTION).

Closes ClickHouse#123982

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The REST catalog test now expects OPTIMIZE to commit a replace snapshot through
the catalog. New arms: a commit race retried on top of the winning INSERT
(failpoint), an identity-partition column materialized into the rewritten file,
and rewritten files written to write.data.path. test_optimize's time travel
now expects the rows the earlier snapshot committed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…outcome

Two writers racing for the same `vN.metadata.json` usually both pass the
existence check, so the loser's create-only write is rejected (S3/MinIO
`PreconditionFailed`, local `FILE_ALREADY_EXISTS` from `link`, the Azure
condition error) and the primitive reported `WriteFailed`. Compaction maps
`WriteFailed` to an unknown outcome and throws `UNKNOWN_STATUS_OF_TRANSACTION`,
so concurrent `OPTIMIZE ... MANIFEST` on S3 failed instead of retrying
(`test_optimize_manifest_files_partitioned_concurrent[s3]`: 5 of 8 runs).

`writeMetadataFileAndVersionHintWithOutcome` now reads the target back once,
bypassing caches, after a failed write. Bytes other than ours prove a lost race
(`TargetExisted`): the write is create-only, so no request of ours can land on
that name any more, and another writer's bytes never equal ours because they
carry a different snapshot id. An absent or unreadable target, or our own bytes
(an unproven replay of a write that landed), stay `WriteFailed`, so the files of
a commit that may be published are never removed.

The `bool` wrapper used by INSERT, mutations, DROP PARTITION and
`expire_snapshots` does not read back, so their results and I/O are unchanged.

Both compactions now initialize their commit outcome to `Unknown`, the value that
keeps the files (clang-tidy `cppcoreguidelines-init-variables`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…keep row order

A REST catalog's 409 does not prove that none of our requests applied:
`ReadWriteBufferFromHTTP` re-sends the commit POST after a network error and
after any 5xx, and when the first POST landed and its answer was lost, the
re-sent one fails `assert-ref-snapshot-id`. Both compactions treated the 409
as a conflict and removed the files of the snapshot that had just been
committed. A rejection is now checked against the catalog's current metadata:
our snapshot present -> committed; main moved past our parent -> conflict
(every request of ours asserts `main == parent`, so none can apply any more);
anything else, or a failure of the check itself -> unknown, files kept.

Glue's `UpdateTable` is unconditional and the file CAS only guards our own
`vN+1` name, so a writer that names metadata differently could commit during
the rewrite and be overwritten. The catalog pointer is now compared with the
one the attempt was planned on right before anything is written.

The source of a rewrite is read with `parquet.preserve_order`, since the new
data file keeps the source's `sort_order_id` and read-in-order trusts it.

Smaller: `UNSUPPORTED_METHOD` from the metadata write (raised before anything
is written) is rethrown with this OPTIMIZE's files removed instead of being
reported as an unknown outcome; the rewrite reuse key is a tuple instead of a
joined string that two delete sets could collide in; the rewritten file's size
lookup runs inside the scope that removes the file on failure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…roof

After a REST 409 the catalog's current metadata was read as "not applied"
whenever our snapshot was absent and main had moved. An applied snapshot can
already be expired by then while a descendant built on it is retained, and
the cleanup that follows a conflict then deletes files that descendant reads.

Now the rejection is resolved against the retained snapshots: ours, or a
snapshot whose parent is ours, means some attempt was applied (Committed);
a conflict is reported only when main's retained lineage reaches our parent
through another snapshot; anything else (an expired link in the chain, no
current snapshot) stays Unknown and keeps every file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… numbers

After a REST 409, a rejection whose snapshot is absent was still read as a
conflict when main's retained lineage reached our parent through another
snapshot. That is not proof: if the first POST was applied, another writer
can build a child and a grandchild on ours, keep the grandchild on a branch
or tag, reset main through a foreign child of our parent and expire ours and
the child. The verifier then saw a conflict and the cleanup deleted files the
retained grandchild still reads.

Iceberg snapshot sequence numbers increase monotonically ("a monotonically
increasing long that tracks the order of changes to a table"), so every
descendant of ours has a sequence number greater than ours, and a snapshot
with a sequence number at or below ours is not one. The verifier now walks
each retained snapshot towards its root while its sequence number is above
ours; if the walk meets a parent that is not retained, that snapshot may
descend from ours and the outcome is Unknown, every file kept. Lineages that
lose a link at or below our sequence number do not block the conflict check,
which is otherwise unchanged. This holds for any interleaving of ref resets,
branches and expiries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…snapshot sequence number as 0

Data compaction drops the delete manifests of the current snapshot, so the
equality-delete refusal is the only thing that keeps equality-deleted rows
from coming back. 05325 now runs OPTIMIZE on the shared
`deletes_db/eq_deletes_table` fixture and checks NOT_IMPLEMENTED, an unchanged
history and the 881 live rows.

After a rejected REST commit the verifier read every retained snapshot's
`sequence-number` with `getValue`. A table upgraded from v1 keeps snapshots
without it, so the read threw and every rejection became UNKNOWN_STATUS. Such
snapshots now read as 0, the value Iceberg readers default to: they are older
than ours, and a descendant of ours is a v2 snapshot that carries the field.

Comments in 04815 and the history-summary integration test no longer describe
the removed history replay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The history-summary integration test explained its fixture with checkIfIcebergHistorySupported, which this branch removes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Compaction.cpp: drop the narration of the manifest regrouping loop and shorten the totals comment to its invariant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 6, 2026
@groeneai

groeneai commented Oct 6, 2026

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

Pre-publication review by an independent model plus my own review (engine: codex; 5 rounds, 21 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ A REST 409 is read as "not applied", but the HTTP client re-sends the commit POST after a timeout or 5xx, so a commit that landed could have its files removed (Compaction.cpp commitCompactedMetadata) AGREE, fixed @ 0279684 a rejection is checked against the catalog's snapshots; a "409 after an applied POST" control deletes the committed files before the fix, keeps them after
2 ⚠️ Glue updates the table pointer unconditionally, so a foreign commit during a long compaction could be overwritten AGREE, fixed @ 0279684 the pointer is re-read right before the commit and a moved pointer retries; Glue's own update stays unconditional, as for INSERT
3 ⚠️ A rewritten file keeps sort_order_id, but the Parquet read may reorder row groups AGREE, fixed @ 0279684 source read with parquet.preserve_order = 1
4 ⚠️ The unknown-outcome leg has no caller-level proof (raised twice) AGREE, fixed @ 0279684 control: a landed write reported as failed gives UNKNOWN_STATUS_OF_TRANSACTION, every file kept, table readable, for both compactions
5 💡 Rewrite reuse key is not injective for paths containing , or | AGREE, fixed @ 0279684 structured key
6 💡 A failing size lookup after finalize leaves an orphan file AGREE, fixed @ 0279684 result assembled inside the cleanup scope
7 💡 UNSUPPORTED_METHOD from the metadata write is reported as an unknown commit AGREE, fixed @ 0279684 rethrown after cleanup, as before
8 ⚠️ A relative write.data.path is not resolved under the table location DISAGREE INSERT passes the property to FileNamesGenerator::setDataLocation verbatim (IcebergWrites.cpp:1171-1176); compaction writes where INSERT writes
9 💡 Catalogs without updateMetadata (Hive, Unity v1) now fail after the rewrite, not upfront AGREE, not changed same as INSERT and OPTIMIZE ... MANIFEST there; every file is kept
10 💡 The Cloud half of the old 05291 stale-hint arm is no longer asserted AGREE, not changed the open-source half moved to 05325; the Cloud branch is untouched
11 ⚠️ After a 409, "the commit's snapshot is absent and main moved" is not proof of a conflict: the snapshot may have landed and been expired under a descendant AGREE, fixed @ a2e916e conflict only when main's retained lineage reaches the commit's parent through another snapshot; the commit's snapshot or a child of it means applied; anything else is unknown, every file kept
12 💡 An error from the Glue pointer re-read, before anything is written, is reported as an unknown commit AGREE, not changed no loss; the files are kept for remove_orphan_files
13 💡 INSERT handles a REST 409 after a re-sent POST the same way AGREE, not changed outside this PR, which does not change INSERT
14 ⚠️ A retained branch can keep a grandchild of the compaction snapshot after main was reset through another child of its parent and the snapshots in between were expired; that still reads as a conflict AGREE, fixed @ 0df4502 sequence numbers only grow, so a retained snapshot whose lineage loses a link above the commit's may descend from it: now an unknown outcome, every file kept
15 ⚠️ A rewritten file of an old partition spec whose source column was dropped gets the current schema in its manifest header DISAGREE the spec defines the header as the table schema at write time, and the file is written in the current schema; the unresolved spec field keys a column the table no longer has
16 💡 The rejection warning says the snapshot is in the table when only a child of it is AGREE, fixed @ 0df4502 message names both cases
17 ⚠️ Data compaction drops every delete manifest, and the refusal of equality deletes that makes this safe has no test (the PR removed the old ones) AGREE, fixed @ 212217d arm in 05325 on the shared deletes_db/eq_deletes_table fixture: NOT_IMPLEMENTED, no new snapshot, 881 rows; removing the guard turns it red
18 💡 The history-summary integration test still explains its OPTIMIZE probe with the removed history replay AGREE, fixed @ 212217d comments rewritten; the probe stays
19 💡 A retained snapshot without sequence-number (v1-era snapshots of an upgraded table) makes the rejection check report an unknown outcome, even when the commit's snapshot is listed AGREE, fixed @ 212217d a missing sequence number reads as 0, as Iceberg readers do
20 ❌ A standalone table whose metadata files are named <N>-<uuid> gets a v<N+1> commit, which a concurrent writer of the uuid scheme does not collide with DISAGREE every standalone writer names its commit this way (INSERT IcebergWrites.cpp:1165-1167, mutations, DROP PARTITION, expire_snapshots, OPTIMIZE ... MANIFEST); such a table commits through its catalog
21 💡 The history-summary integration test still gives the removed checkIfIcebergHistorySupported as the reason for its fixture (raised twice) AGREE, fixed @ 936b487 comment rewritten; the assertion stays

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

Bounce cap reached, published as-is: the last fix round (936b487, one test comment) was checked by my own review only, without another independent-model run. Rows 9, 10, 12 and 13 are noted, not blocking.

Session id: cron:clickhouse-review-slot-11:20261006-001900

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master, a second OPTIMIZE after INSERT + DELETE leaves no metadata file (Code: 107), and time travel to the pre-DELETE snapshot returns [2,3] instead of [1,2,3] (#123982). The commit race is reproduced by test_optimize_manifest_files_partitioned_concurrent[s3] and by a unit test that drives the window between the existence check and the write.
b Root cause explained? Compaction rebuilt the table from an empty metadata file, always as v0, with a plain overwrite, then deleted a pre-write listing of metadata/ and data/. A catalog cannot commit re-created snapshot ids.
c Fix matches root cause? Yes. The commit model is replaced at its source: one replace snapshot on top of the current one, committed through the helper OPTIMIZE ... MANIFEST uses, nothing deleted at commit.
d Test intent preserved / new tests added? New 05325 (each arm fails on master; it also checks that tables with equality deletes are still refused), 05218/05291 updated to the new semantics, integration arms for a REST catalog, a commit race, identity partitions and write.data.path, two unit tests.
e Both directions demonstrated? Yes: every 05325 arm and the probes fail on master and pass with the fix; the lost-race unit test fails before the read-back and passes after; concurrent OPTIMIZE ... MANIFEST on S3 went from 5/8 failed to 20/20 passed. With a REST catalog answering 409 to a commit that landed, both compactions deleted the committed snapshot's files before and keep them now, also when that snapshot was already expired under a retained child, or when main was reset while a branch kept a snapshot that may descend from it. Removing the equality-delete refusal makes 05325 fail (99 deleted rows come back), and a 409 on a table with snapshots from before a v1 to v2 upgrade is no longer reported as unknown.
f Fix is general across code paths? Yes. Both compactions share one commit helper and one outcome primitive; SELECT's delete matching, identity-partition substitution and schema transform are reused, not copied. Other writers keep the unchanged bool wrapper.
g Fix generalizes across inputs (params/datatypes/wrappers)? Partition specs, schema evolution, identity columns not stored in files, ORC/Avro survivors, write.data.path, catalog / no catalog / version hint, compressed metadata, local and S3 storage.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Visible changes are the intended ones: time travel no longer shows deletes applied retroactively, replaced files stay until expire_snapshots.
i Invariants and contracts preserved? One snapshot whose parent is the current one; earlier snapshots and table fields untouched; files removed only when the commit provably did not land (after a catalog rejection, files are removed only when no retained snapshot above the commit's sequence number has a missing ancestor and main's retained lineage reaches the commit's parent through another snapshot; a Glue pointer that moved since planning means nothing is written); the commit's own bytes after a failed write are never treated as a lost race; a snapshot without a sequence number counts as 0; tables with equality deletes are refused.

Session id: cron:clickhouse-impl-slot-40:20261005-215800

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cf80b1d]

Summary: ✅


AI Review

Summary

PR #124114, reviewed at cf80b1d405a81df37589818822d1ce46ad7ab2c4, replaces Iceberg table reconstruction with a single replace snapshot, preserving historical snapshots and recording replaced files as DELETED. The earlier inline findings are addressed; the null-snapshot thread was resolved. No new inline findings were posted. The previously discussed Glue commit race remains a data-loss concern.

Consumers of the new DELETED entries were traced: IcebergIterator, file listings, row counts and estimates exclude them; subsequent inserts and mutations carry manifests forward; manifest compaction collects live entries; snapshot expiration and orphan-file traversal protect historical live references. Java concurrent-writer validation consumes the deletion entries through MergingSnapshotProducer.validateDataFilesExist.

Missing context / blind spots
  • ⚠️ No local build or runtime tests were run; this checkout has no built ClickHouse binary. Storage-specific CI results for the current head were still pending. Completed regression-suite results would close this verification gap.
Findings

❌ Blockers

  • Compaction.cpp:584–617: Glue publication can overwrite a successful concurrent commit. [dismissed by author -- https://github.com/Iceberg OPTIMIZE TABLE commits a new snapshot instead of rewriting the table #124114#issuecomment-6006701008] The author explicitly accepts the unconditional Glue update as matching INSERT; the pointer re-read narrows the race but does not make publication atomic.

    Concrete interleaving: compaction reads pointer M0 at line 584; a Spark writer publishes M1 under its own metadata filename; compaction creates its different metadata filename and then calls GlueCatalog::updateMetadata. That method sends an unconditional UpdateTable request, replacing M1 with a snapshot planned from M0. The Spark writer's committed rows disappear. The metadata-file conditional write cannot detect a writer using another filename. Both compaction modes use this helper.

    Require a catalog version check in the atomic update, or reject compaction through catalogs without that guarantee. Glue supports optimistic locking with a table version ID. This concern is retained here only, respecting the author's recorded decision.

Tests
  • ⚠️ If Glue compaction remains enabled, cover an external commit between the pointer re-read and UpdateTable, using a different metadata filename. Verify that compaction retries or rejects publication and preserves the external writer's rows.
Final Verdict

Status: ❌ Block

Minimum action: make Glue publication conditional on the planned catalog version, or keep Glue compaction unsupported. The existing discussion was not reopened.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Oct 6, 2026
The compaction section claimed support for Iceberg tables without naming
the refusals in the data-compaction path: any format-version other than 2
(BAD_ARGUMENTS; this also covers deletion vectors, a v3 feature), equality
delete files in the current snapshot, and per-file key_metadata in a data
manifest that has to be rewritten (both NOT_IMPLEMENTED).

"Catalog-backed" is narrowed to catalogs ClickHouse can INSERT into: the
commit goes through ICatalog::updateMetadata like INSERT, and only the
REST-derived, Glue and Unity v2 catalogs implement it.

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

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cf80b1d40 with master 1d4ff1539 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

27 object files changed (+33.87 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/MetadataGenerator.cpp.o 540.71 KiB 580.38 KiB +39.67 KiB (+7.34%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp.o 1.00 MiB 1005.49 KiB -23.43 KiB (-2.28%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.60, programs/clickhouse-keeper ×0.65 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 10.8 s +7.0 s (+185%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.3 s +5.1 s (+238%)
Compile time of recompiled translation units

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse DB::Iceberg::compactIcebergTable(DB::Iceberg::PersistentTableComponents const&, std::__1::shared_pt… new 92.54 KiB +92.54 KiB

Job report

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cd2a1b1

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_asan_ubsan, azure, sequential) not from this PR: the job hit its 9000 s timeout at test 1165 of 1167 and uploaded no test results. The job ended the same way, in error with no test results, on 36 other runs (7 of them on master) in the last 3 days #123849 (mine, open)
PR rollup of the row above #123849 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

CIDB has no FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261006-073316

groeneai and others added 3 commits October 20, 2026 12:05
…publish-repair

Conflicts resolved:
- Compaction.cpp: this branch's version. Master's changes there (the
  next-version commit, the version-hint retention and the field-id read
  mapper of data compaction) sit in code this branch replaces; the rewrite
  already reads through `getColumnMapperById`, which carries the time field
  ids and the last assigned field id.
- MetadataGenerator: `generateNextMetadata` takes master's `removals`, then
  `precomputed_summary`; compaction passes no removals.
- Utils: `writeMetadataFileAndVersionHintWithOutcome` is built on master's
  `writeMetadataFile` / `tryWriteVersionHintFile` split and keeps the
  refused-write rule.
- gtest_iceberg_commit_propagation.cpp: master's stub, extended so a failed
  write can leave content that `readObject` serves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tion test

`OPTIMIZE TABLE` now rewrites only the data files that position deletes
apply to and keeps the others. With one deleted row, two of the three
pyiceberg files were kept, so the check that every row is read from a
file written by `OPTIMIZE` failed. Deleting one row from each file keeps
that check. With the compaction read stripped of its field-id mapper the
test fails on every row (seconds instead of microseconds).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ummary

The `replace` snapshot of data compaction copied every extra field of
the parent's summary, so compacting a snapshot written by Spark kept
Spark's `engine-name`, `engine-version`, `app-id` and `spark.app.id`.
Those fields describe the write that produced the parent. The refresh
cursor is the only extra field every snapshot must carry forward (the
rule `generateNextMetadata` applies), so only it is kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 3 commits October 20, 2026 13:17
An incremental refreshable materialized view resumes from the cursor in
the latest snapshot's summary. Compact the target after the first
refresh and check that the `replace` snapshot carries the cursor and
that the refresh after a restart appends only the new rows. With the
cursor dropped by compaction the new arm fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…snapshot

The Iceberg spec allows JSON null for a table without a current
snapshot, and SELECT, INSERT and mutations already read it that way.
The compaction planner called `getValue<Int64>` on the null and failed
with `Invalid access: Can not convert empty value`; it now takes the
no-snapshot path and commits nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits October 22, 2026 03:26
The replace snapshot listed only the rewritten files, so the data files
it replaced and the position delete files it applied vanished from the
manifests. Iceberg's Java writer validates a concurrent commit against
the DELETED entries of the snapshots committed since it planned
(MergingSnapshotProducer.validateDataFilesExist), so a position delete
planned against a file that OPTIMIZE then replaced still committed, and
was lost: its rows live on in the rewritten file. Incremental snapshot
expiration relies on the same entries to reclaim the replaced files.

Every replaced source, including one with no surviving rows, and every
removed position delete file is now a DELETED entry of the new snapshot
that keeps its data and file sequence numbers, and the manifest list
carries the matching deleted_files_count and deleted_rows_count.
ClickHouse readers skip DELETED entries, so SELECT, expire_snapshots and
remove_orphan_files see the same files as before.

Measured with Spark 4.0 and Iceberg 1.11: a RowDelta staged against a
replaced file before OPTIMIZE committed on the previous head, and is
now rejected with "Cannot commit, missing data files".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 11, 2026 12:46
…publish-repair

Conflicts:
- Compaction.cpp: the PR's version, with master's changes to the code it keeps:
  the rewrite read asks the format for row numbers (the position delete transform
  needs them, formats attach them only on request now); the metadata object is
  deep-copied before MetadataGenerator mutates it (metadata.json is cached and
  shared now); a group keeps one partition tuple per file and the manifest list
  gets a ManifestPartitionSummary, and OPTIMIZE ... MANIFEST groups by partition
  value only without iceberg_insert_single_manifest_for_all_partitions; the
  existing-entry statistics carry NaN counts (master's getColumnStatisticsForRewrite
  and getEntryLineageForRewrite are reused). Master's changes to the code this PR
  replaces (getPlan, writeDataFiles, writeMetadataFiles, getOldFiles) are dropped.
- IcebergIterator.{h,cpp}: DataFileEntriesStream is gone on master and
  defineDeletesSpan moved to ManifestFile.h; only positionDeleteMayReferenceDataFile
  stays here.
- IcebergMetadata.cpp: updateLastColumnId is gone on master.
- Utils.cpp: master's concurrent-write debug log in writeMetadataFileWithOutcome.
- StorageObjectStorageSource.h, test_optimize.py: both sides kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
05325 gets the reproducers of ClickHouse#123282 (an earlier schema must not become the
schema of the rewritten files) and ClickHouse#123909 (rows of a dropped partition must
not come back). Both fail on master: `-1294967296 Int32`, and `[2,3]` with the
dropped row back.

05483 (from master) expected master's OPTIMIZE, which rewrites every snapshot.
Here the earlier snapshots keep their totals and the one `replace` snapshot has
the totals of its live files, so the expected arrays list them all; the trivial
count, the size check and the reads per delete file are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 3 commits November 11, 2026 15:02
A manifest group checked for a duplicate path with a linear scan of the
paths already in the group, which makes collecting n files O(n^2). Master's
OPTIMIZE ... MANIFEST used a per-group unordered_set before the groups were
shared with data compaction; restore it for both the existing-entry and the
rewritten-file insertions. Same equality as before: IcebergPathFromMetadata
compares and hashes its raw path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
05401 (from master) asserted master's OPTIMIZE, which deletes a listing of
data/ after rewriting the table. Here OPTIMIZE commits a replace snapshot and
deletes nothing: the earlier snapshots still reference the replaced files and
expire_snapshots reclaims them. The OPTIMIZE section now checks that every
data file listed before OPTIMIZE is still there; it prints 0 on master (the
files are deleted) and 1 here. The strays outside the table directories are
still checked to survive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 3 commits November 12, 2026 21:44
Since ClickHouse#128600 a metadata file of a catalog-backed table is named
`<N>-<uuid>.metadata.json` with the UUID derived from the base metadata
file, and `FileNamesGenerator` throws LOGICAL_ERROR when that base is not
set. The data compaction commit still called `setVersion`, so OPTIMIZE on
a table in a REST catalog aborted the server (test_database_iceberg in
Integration tests (amd_asan_ubsan, flaky)).

Use the same generator setup as the other writers after ClickHouse#128600: UUID
names for every catalog-backed table and `setBaseMetadataFile` with the
metadata file the plan was read from. A non-transactional catalog (Glue)
now also gets the deterministic name, so two writers committing on the
same base collide on it and the loser retries, as for INSERT.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Data compaction already reads `"current-snapshot-id": null` as "no current
snapshot", but the manifest compaction pre-check and
`writeConsolidatedManifestFile` still called `getValue<Int64>` on it, so
`OPTIMIZE TABLE t MANIFEST` on such a table failed with POCO_EXCEPTION
`Invalid access: Can not convert empty value` (also on master, where data
compaction fails the same way). All three sites now share one null-aware
lookup, and the 05325 null case also runs the MANIFEST mode and checks that
no metadata is published.

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-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg OPTIMIZE TABLE rewrites the table instead of committing a snapshot: a second OPTIMIZE leaves no metadata file

2 participants