Skip to content

Do not compact an Iceberg history that retains snapshots off the current chain - #118951

Open
tiandiwonder wants to merge 4 commits into
masterfrom
fix-iceberg-compaction-rollback-replay
Open

tiandiwonder wants to merge 4 commits into
masterfrom
fix-iceberg-compaction-rollback-replay

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Related: #114465

Problem

A rollback makes an older snapshot current again and leaves the newer, abandoned snapshots retained in
snapshots. On such a table a plain OPTIMIZE TABLE succeeded quietly, and afterwards the table read
as the abandoned branch tip again — the rollback was silently undone. Measured on a local build, with
history append s1, position-delete s2, append s3, rolled back to s1:

stage current-snapshot-id refs.main SELECT v
tip of the append branch s3 s3 1,3,4
after the rollback s1 s1 1,2,3
after plain OPTIMIZE s3 s3 1,3,4

Row v=2 disappears (the abandoned delete is applied) and v=4 appears (the abandoned append is
republished). The row count is 3 in both states, so a count-only check cannot see it.

Root cause

getPlan iterates every record of the history it is handed with no is_current_ancestor filter,
collecting each snapshot's manifests, data files and position deletes; writeMetadataFiles then
replays the snapshots in order, publishing each one and moving current-snapshot-id and refs.main as
it goes. So a snapshot that is not on the current chain is folded into the rewrite and the last one
replayed becomes current.

IcebergMetadata::getHistory already computes the fact that was missing: it walks the parent chain
from current-snapshot-id and marks each record is_current_ancestor. Nothing in the compaction path
consulted it.

Solution

Refuse the rewrite, in checkIfIcebergHistorySupported — where compaction already forces the history
shapes its experimental implementation supports — naming the offending snapshot and leaving the table
untouched.

Dropping the non-current snapshots and compacting the rest is not a safe alternative: their data files
can still be referenced from another branch or tag, and compaction deletes the files it did not carry
over, so filtering would trade a wrong-result bug for a data-loss bug.

New test 05153_iceberg_optimize_rollback_replay asserts the row values before and after OPTIMIZE,
plus the refusal itself on an open-source build (a cloud build gates OPTIMIZE on
IcebergCompactionMetadataGenerator and throws before reaching this check, so only the row assertions
apply there). With the check reverted and rebuilt, both of its assertions flip. The four existing
compaction tests — 04230, 04513, 04614, 04815 — pass either way.

Compaction is behind the off-by-default allow_experimental_iceberg_compaction, so no backport.

#114465 guards the degenerate case of this defect — a table with no current snapshot at all — in
IcebergMetadata::optimize, before compactIcebergTable. The two changes do not collide: with both
in, a snapshotless table stays a quiet no-op and a rollbacked table is refused.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed OPTIMIZE TABLE on an Iceberg table silently moving the table off the snapshot it had been rolled back to, republishing the abandoned snapshots and changing the rows a SELECT returns.


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

A rollback makes an older snapshot current again and leaves the newer, abandoned snapshots retained in
`snapshots`. On such a table a plain `OPTIMIZE TABLE` succeeded quietly and afterwards the table read
as the abandoned branch tip again - the rollback was silently undone.

`getPlan` iterates every record of the history it is handed with no `is_current_ancestor` filter,
collecting each snapshot's manifests, data files and position deletes, and `writeMetadataFiles` then
replays the snapshots in order, publishing each one and moving `current-snapshot-id` and `refs.main` as
it goes. So a snapshot that is not on the current chain is folded into the rewrite and the last one
replayed becomes current. `getHistory` already computes the missing fact - it walks the parent chain
from `current-snapshot-id` and marks each record `is_current_ancestor` - and nothing in the compaction
path looked at it.

Refuse the rewrite instead, in `checkIfIcebergHistorySupported`, where compaction already forces the
history shapes its experimental implementation supports. Dropping the non-current snapshots and
compacting the rest is not a safe alternative: their data files can still be referenced from another
branch or tag, and compaction deletes the files it did not carry over, so filtering would trade a
wrong-result bug for a data-loss bug.

Measured on a local build, with history append `s1`, position-delete `s2`, append `s3`, rolled back to
`s1`:

    after the rollback           current-snapshot-id=s1  refs.main=s1  SELECT v = 1,2,3
    after plain OPTIMIZE, before  current-snapshot-id=s3  refs.main=s3  SELECT v = 1,3,4
    after plain OPTIMIZE, after   refused, table untouched, SELECT v = 1,2,3

The row count is 3 in both states, so the new test asserts the values rather than the count. With the
check reverted and rebuilt, both of its assertions flip, and the four existing compaction tests
(`04230`, `04513`, `04614`, `04815`) pass either way.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a503b5b]

Summary: ✅


AI Review

Summary

This PR refuses OPTIMIZE TABLE for Iceberg tables whose retained history is not a single current-snapshot ancestor chain, and adds stateless coverage for rollbacked histories plus ref/retention metadata that the rewrite cannot round-trip. The rollback and retention checks close one real corruption path, but the patch still leaves one previously reported metadata-loss hole open and introduces a new false-positive rejection path for no-op OPTIMIZEs, so I would not merge it yet.

Findings
  • ⚠️ Major: [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:221-275] and [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1088-1101] add new unsupported-history checks before [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:368], where plan.need_optimize is decided. OPTIMIZE only rewrites metadata when a position delete is present, so an append-only table with a rollbacked history, extra refs, or these retention settings is currently a no-op. After this patch the same table starts throwing BAD_ARGUMENTS even though nothing would be rewritten. Move these refusals behind the "will rewrite" decision, or add an earlier cheap pre-check for position deletes.
  • ⚠️ Major: [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:198], [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:262-275], [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1113], and [src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp:1107-1111] show that the rewrite still does not round-trip write.data.path. Normal Iceberg writes copy that property into FileNamesGenerator, but compaction builds plan.generator from table_location only and later rebuilds metadata from createEmptyMetadataFile(...), which drops the entire properties map. A table that sets write.data.path therefore still passes the new allow-list, writes compacted files under the default ${table_location}/data/ prefix, and loses the property from the rewritten metadata so later writes switch prefixes too. Either preserve write.data.path in both the data-file generator and rewritten metadata, or refuse compaction on tables that set it until the rewrite can round-trip it.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit a503b5b.

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

Changed lines: Changed C/C++ lines covered: 39/41 (95.12%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit a503b5b54e4a98bd9c0b4918a4beb2bc1f2f8cdf was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@maxknv maxknv removed the external Author is not a member of the ClickHouse organization label Sep 11, 2026
tiandiwonder and others added 2 commits September 21, 2026 02:58
…e cannot reproduce

Review found the guard of this pull request incomplete, in three related ways, each measured on this
branch with a plain `OPTIMIZE` returning `rc=0` and saying nothing. Compaction rebuilds the metadata
from `createEmptyMetadataFile`, and `MetadataGenerator` then writes a `refs` map holding one `main`
branch with a snapshot id and a type - so anything else a table kept is simply not in the result:

    before  refs = {main, audit_tag, audit_branch}          after  refs = {main}
    before  refs.main = {snapshot-id, type, min-snapshots-to-keep, max-snapshot-age-ms}
    after   refs.main = {snapshot-id, type}
    before  properties = {..., history.expire.min-snapshots-to-keep: 5}
    after   properties = <absent>

A branch or tag that names an ancestor of the current snapshot passes the current-ancestor check, so
none of these shapes was refused. All three weaken retention the same way: `ALTER TABLE ... EXECUTE
expire_snapshots` reads `min-snapshots-to-keep`, `max-snapshot-age-ms` and `max-ref-age-ms` off both
the references and the table properties (`ExpireSnapshotsExecute.cpp`), so history the table asked to
keep can be expired after a compaction that never mentioned dropping anything.

Carrying them over is not a fix by itself: the rewrite does not retain every source snapshot - the
same run drops the count from 3 to 2 - so a reference or a retention floor can outlive the snapshots
it protects and there is nothing correct to remap it to. Refuse instead, next to the
`format_version` check in `getPlan` that already refuses for the same rebuild-from-scratch reason,
and leave the table as it is.

The rewrite drops the *whole* `properties` map, not only the retention keys - a ClickHouse-written
table always carries `write.delete.mode` and friends, so refusing on any property would refuse every
such table. Only the retention floor is refused here; the rest is a defect of the rewrite itself,
which has to carry `properties` across, and is tracked separately.

`05153_iceberg_optimize_non_main_ref` covers the three shapes and asserts both the refusal and that
the references, the retention fields and the rows survive. With the check reverted and rebuilt, the
tag is gone after `OPTIMIZE` and the test fails on both of its first-scenario lines; `04230`,
`04513`, `04614`, `04815` and `05153_iceberg_optimize_rollback_replay` pass either way, because a
table ClickHouse wrote carries only a bare `main` and no retention floor.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
/// dropped by the rewrite too, which is a defect of its own and not something a guard here can
/// fix - refusing on any property would refuse every table ClickHouse writes, since it always
/// sets `write.*.mode` - so only the retention floor is refused.
if (initial_metadata_object->has(Iceberg::f_properties) && !initial_metadata_object->isNull(Iceberg::f_properties))

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.

properties is still an incomplete allow-list here. writeMetadataFiles rebuilds the table from createEmptyMetadataFile(...), and plan.generator never inherits write.data.path, even though IcebergStorageSink uses that property to decide where data files belong. A table that sets write.data.path therefore still passes this check, then OPTIMIZE writes the compacted files under the default ${table_location}/data/ prefix and drops the property from metadata, so later writes switch prefixes too.

Please either preserve write.data.path in both plan.generator and the rewritten metadata, or fail closed on tables that set it until the rewrite can round-trip it.

/// Carrying the refs over instead is not a fix on its own: the rewrite does not retain every
/// source snapshot, so a ref can name one the new metadata no longer has. Refuse the rewrite
/// and leave the table as it is.
if (initial_metadata_object->has(Iceberg::f_refs) && !initial_metadata_object->isNull(Iceberg::f_refs))

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.

These new unsupported-shape checks run before we know whether this OPTIMIZE will rewrite anything. plan.need_optimize is only set after scanning the manifests and finding at least one position delete (!all_positional_delete_files.empty() at line 368), and when it stays false we exit without touching metadata.

That means an append-only table with a rollbacked history, an extra ref, or one of these retention settings now starts throwing BAD_ARGUMENTS even though the command would have been a pure no-op. The same regression applies to the later is_current_ancestor guard. Please gate these refusals on actually needing a rewrite, or add an earlier cheap "has position deletes" pre-check, otherwise we turn harmless no-op OPTIMIZEs into hard failures.

@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

comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants