Skip to content

Refuse Iceberg data compaction until it can publish its result - #114437

Merged
arsenmuk merged 20 commits into
ClickHouse:masterfrom
groeneai:iceberg-refuse-unpublishable-data-compaction
Oct 1, 2026
Merged

arsenmuk merged 20 commits into
ClickHouse:masterfrom
groeneai:iceberg-refuse-unpublishable-data-compaction

Conversation

@groeneai

@groeneai groeneai commented Aug 12, 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):

In the open-source build, Iceberg data compaction (OPTIMIZE TABLE with allow_experimental_iceberg_compaction = 1) now reports NOT_IMPLEMENTED instead of running, because it deleted files that retained snapshots still referenced, including version-hint.text and every vN.metadata.json, which left the table unreadable and could permanently lose an acknowledged snapshot's rows. OPTIMIZE TABLE ... MANIFEST, expire_snapshots and remove_orphan_files are unaffected.

Description

Related: #114194 (the same stale-hint root reaching remove_orphan_files).

Measured on master (26.8.1.1), v2 table with position deletes: OPTIMIZE TABLE returns success silently, drops the object count 18 to 10, and deletes metadata/version-hint.text with v1..v5.metadata.json; every later read fails Code: 107 FILE_DOESNT_EXIST. No stale hint is needed. When the hint is behind the newest metadata, the rewrite is rooted at the older version, so an acknowledged snapshot's data files are not carried forward yet are still deleted: groupArray(x) returns [1] where [1,99] was committed.

Root cause: getOldFiles takes a raw listing of metadata/ and data/ with no reachability filter and no age gate, and clearOldFiles deletes all of it. Those files are reachable by the engine's own definition - collectSnapshotReferencedFiles walks every entry of the snapshots array - so deleting them is wrong at any age, under any guard.

The rewrite is also never published atomically: getPlan never calls setVersion, so it always writes v0.metadata.json, and writeMetadataFiles commits with a bare WriteMode::Rewrite, no hint and no catalog commit. Since the old files are listed before it runs, cleanup deletes the previous vN and leaves v0, so a reader resolves whichever generation survived - in the measured run, the truncated one. Publishing correctly needs the current-snapshot replacement model and catalog plumbing that do not exist here, so this refuses the path rather than repairing it, following the existing format-version 3 refusal for OPTIMIZE ... MANIFEST.

The data-compaction success contracts in the tests were deleted rather than inverted into "the feature is absent" assertions, which would have to be deleted again once publication lands. The new integration test asserts the property that holds either way: no pre-existing file is removed and the committed rows survive. A stateless test pins the refusal. OPTIMIZE ... MANIFEST coverage is untouched.


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

Version info

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

@groeneai

groeneai commented Aug 12, 2026 •

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

Two review rounds by an independent reviewer that never edits the code, plus two cold
second-model passes over the full diff. Round 1 raised 1 blocker and 2 majors; all three were
agreed and fixed. The re-review of the fix returned no findings.

Round 1: 1 blocker, 2 majors, all AGREED and fixed

❌ Do not recommend remove_orphan_files as the remedy (blocker). The refusal message and
the docs both pointed the user at remove_orphan_files. That command roots its reachable set at
a version hint, so under a stale hint it excludes newer-generation files and deletes them once
older_than passes - answering stale-hint-driven deletion with more of the same. Fixed: the
message and the docs now name only expire_snapshots. Re-derived independently before accepting
the change: expire_snapshots builds its deletion set as expired-minus-retained over the
snapshot graph rather than a raw listing, vN.metadata.json and version-hint.text are not
deletable categories there at all, and it commits through a compare-and-swap that keeps the hint
in sync. Its worst case under a stale hint is under-collecting reclaimable files, which is
conservative rather than destructive. The ### Remove Orphan Files documentation section itself
is untouched.

⚠️ The "not implemented" claim was false on the Cloud build (major). The
#if CLICKHOUSE_CLOUD branch is deliberately untouched and still succeeds, but the changelog and
docs asserted the refusal unconditionally. Fixed by scoping the claims to the open-source build
in all three places. Half of the original suggestion was declined: making the refusal
build-independent would touch a mechanism that is not present in this checkout, and a mutation
arm showed that broadening it does not compile (-Wunreachable-code). The Cloud region is
byte-identical to master.

⚠️ Nothing asserted the refusal itself (major). Reverting the source change would have left
every test arm green. Fixed by adding 04880_iceberg_optimize_data_compaction_refused.sh,
modelled on the in-tree 04293 refusal test. It passes on the fixed binary, fails on the
un-fixed one (where OPTIMIZE returns success silently), and ran 50 times under default
randomization without a failure. The suggestion to fold the assertion into the new integration
test was declined: that test deliberately asserts a property rather than an outcome, so it stays
valid if publication is ever implemented, and an outcome assert would have to be deleted then.

Re-review of the fix - no findings. Both diff scopes were checked against the intended change
set to confirm the review covered the right base.

💡 Noted, not blocking: the rewritten header of 04513 says its OPTIMIZE section was removed
"together with Iceberg data compaction"; the compaction code itself remains, only its invocation
is refused. Comment wording in a test file; the assertions are correct.

Also verified in this round, by reading the code rather than trusting the change description:
setVersion is called exactly once in Compaction.cpp and that call is on the manifest path,
confirming the data path really does emit v0; the reachability walk covers every snapshot;
the binary used for every measurement contains the final message text, so no result was taken
against a stale build; and the diff adds no source comments.

One open question for the owners, deliberately not decided here: PR #110069 (also mine, open)
adds tests to the same file asserting that data compaction succeeds. If this lands, those tests
need to be dropped or that PR needs to land first. I have not touched it.

Session id: cron:clickhouse-review-self-slot-58:20260812-074400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local on a v2 IcebergLocal table with iceberg_use_version_hint = true: INSERT 1; INSERT 2; DELETE WHERE x=2; INSERT 99; then OPTIMIZE TABLE t; with allow_experimental_iceberg_compaction=1. On master this returns rc=0 silently, drops 18 objects to 10, deletes version-hint.text and v1..v5.metadata.json, and every later read fails Code: 107. With the hint one version behind, all 18 pre-existing objects are deleted and the surviving generation returns [1] instead of the committed [1,99].
b Root cause explained? getOldFiles (Compaction.cpp:1325) takes a raw listing of metadata/ and data/ with no reachability filter and no age gate; clearOldFiles deletes all of it. collectSnapshotReferencedFiles (SnapshotFilesTraversal.cpp:31) walks every entry of the snapshots array, so those files are reachable by the engine's own definition. The rewritten generation is also never published: getPlan never calls setVersion (so it always writes v0) and writeMetadataFiles commits with a bare WriteMode::Rewrite, no version hint and no catalog commit.
c Fix matches root cause? Yes. The refusal is placed at the single entry to that path, so getOldFiles/clearOldFiles can no longer run and the whole measured impact is removed by construction. No bound was widened, no tag added, no guard placed at the crash site. Repairing publication instead needs the current-snapshot replacement model and catalog plumbing that do not exist here, and would leave the data loss in place meanwhile. Follows Compaction.cpp:1390, which already refuses OPTIMIZE ... MANIFEST on format-version 3 for unimplemented publication semantics.
d Test intent preserved / new tests added? New test_optimize_never_deletes_reachable_files (local/s3 x current/stale/absent hint) asserts the property, not the refusal: no pre-existing object removed and the committed rows still readable, tolerating either OPTIMIZE outcome so it stays valid if publication is implemented later. The data-compaction success contracts were deleted rather than inverted. 04815 was removed only after confirming its subject (tryGetAppendUpdate) is covered by gtest_iceberg_snapshot_summary.cpp's IcebergCompactionOverwriteClassification; 04513 kept its ORC-newer-than-position-delete reads, which exercise the same transform on the read path; 04230's lazy-init coverage needed no change and is green. A separate stateless test, 04880_iceberg_optimize_data_compaction_refused.sh, pins the refusal itself so reverting it cannot leave every arm green; it reads CLICKHOUSE_CLOUD from system.build_options and asserts the open-source outcome only.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (base 7361fcfe..., fix 0e9f3009...). 04880 passes on the fix binary and fails on the un-fixed one, where OPTIMIZE returns success silently, and it ran 50 times under default randomization with no failures. The new integration test fails 6/6 on the un-fixed binary with AssertionError: OPTIMIZE deleted pre-existing files: [...] naming the deleted v1..v5.metadata.json and version-hint.text, and passes 6/6 with the fix. Four mutation arms all redden: reverting the refusal, moving it into the CLICKHOUSE_CLOUD branch, broadening it into optimizeManifestFiles (that one does not even compile: -Wunreachable-code), and breaking the optional-summary-metric guard the retargeted history test covers.
f Fix is general across code paths? compactIcebergTable has exactly one caller and IcebergMetadata::optimize exactly one, so there is no sibling data-compaction path to miss. Other listFiles-then-delete sites in DataLakes/Iceberg/ were checked: RemoveOrphanFilesExecute.cpp:270 is its own command with an older_than gate, IcebergMetadata.cpp:1486 is drop deleting the table on purpose, and the remaining two are read-only resolution. OPTIMIZE ... MANIFEST, expire_snapshots, remove_orphan_files, INSERT and mutations are untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? All three iceberg_use_version_hint states (current, stale, absent) are fixed and each is a test arm; both local and s3 storage are arms; the setting-off path is asserted to keep its existing BAD_ARGUMENTS message; catalog-backed tables are refused too, which is correct since their publication was never implemented either.
h Backward compatible? (maintainer-approved exception only) No setting default, format or serialization change, so no SettingsChangesHistory.cpp entry is needed (the diff touches no src/Core/). One deliberate user-visible change: OPTIMIZE TABLE on an Iceberg table now errors where it previously reported success. It only appeared to work by deleting files retained snapshots still referenced, and its result was never published, so no reader saw it. OPTIMIZE TABLE ... MANIFEST still works and reclamation stays available via expire_snapshots. Already-damaged tables are not repaired; their files are gone.
i Invariants and contracts preserved? optimize still either returns bool or throws, which is what InterpreterOptimizeQuery expects. Throwing before getHistory and getSampleBlock builds strictly less state; the new path takes no lock, allocates nothing and performs no partial write. The CLICKHOUSE_CLOUD branch is untouched, and the mutation arm that moved the refusal into it confirms the OSS build really takes the #else.

Session id: cron:clickhouse-impl-self-slot-57:20260812-070002

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c255e8c]

Summary: ✅


AI Review

Summary

This PR makes open-source Iceberg data compaction fail closed by throwing NOT_IMPLEMENTED before any history or rewrite work, updates the source-of-truth docs/settings text to describe that split, and replaces success-based tests with refusal/property regressions. I did not find a new unresolved correctness issue in the current diff, and the previously open bot thread about the Cloud per-table gate is fixed in the current code.

Missing context / blind spots
  • ⚠️ The CLICKHOUSE_CLOUD compaction implementation is only partially verifiable from this checkout, so I could not independently execute the Cloud-only success path that 04880_iceberg_optimize_data_compaction_refused.sh now tries to pin.
Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit c255e8c.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @divanik @arsenmuk, could you review this? Iceberg data compaction deletes a raw listing of metadata/ and data/ with no reachability filter, so it removes files that retained snapshots still reference, including version-hint.text and every vN.metadata.json, and its own rewrite is never published because getPlan never calls setVersion. This refuses the path in the open-source build rather than repairing publication, which needs the current-snapshot replacement model and catalog plumbing.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 12, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c255e8c1f with master 8dc18243e (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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, and it applies to the other half of the same sentence too.

optimize() has no format-version and no catalog gate anywhere upstream
(StorageObjectStorage::optimize -> DataLakeConfiguration::optimize ->
IcebergMetadata::optimize), so a v1 or catalog-backed table does reach the refusal.
Measured on a v1 table: OPTIMIZE TABLE gives the NOT_IMPLEMENTED refusal, then
expire_snapshots gives Code: 36 BAD_ARGUMENTS, "supported only for the second version of
iceberg format". A v2 control succeeds, so the probe was live.

OPTIMIZE TABLE ... MANIFEST is conditional in the same way, which the comment did not cover:
v1 gives Code: 36, v2 succeeds, v3 gives Code: 48 for the row-lineage round-trip. So a v1
table was sent to a dead end by both prescriptions.

Took the second option and dropped the reclaim guidance from the message. Scoping it in place
would mean branching on catalog transactionality and format version inside an error string,
which would go stale as those gates move. The shape requirements went to the documentation
instead, where the expire_snapshots section already had a format-version note; its
transactional-catalog restriction was undocumented and is now stated.

Also corrected a claim of my own that the re-review caught: the message and docs said no
reader would select the rewritten generation. That is wrong. getOldFiles lists the old files
before writeMetadataFiles runs, so the cleanup deletes the previous vN and leaves the new
v0, and a reader without a hint resolves whichever generation survived. The data-loss run
depends on exactly that, so the wording contradicted its own evidence. It now says the rewrite
is not published atomically and which generation a reader resolves is undefined.

The refusal itself, its placement, the setting gate and both tokens the stateless test greps
are unchanged. 7/7 of the retained Iceberg stateless tests pass, and the refusal oracle still
reddens on a pre-fix binary.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 36d141f

CI is fully finished on this head and there are no failures to own. 177 check runs, 164 success, 13 skipped, 0 failed. The praktika report for this head is top-level OK with 0 dropped jobs, so the run has real coverage rather than a dropped matrix (every earlier head on this PR was gated out by can be tested and never produced coverage).

Check / test Reason Owner / fixing PR
(none) no failing check on this head not applicable

The only FAIL rows in the CI database at this head are the Bugfix validation (functional tests, amd64/aarch64) and Bugfix validation (integration tests, amd64/aarch64) entries for 04513_iceberg_optimize_orc_position_delete_88123 and test_iceberg_history_missing_optional_summary_metrics. Those are the expected half of the bugfix contract, which requires the new regression tests to fail without the fix, and all five Bugfix validation jobs concluded success.

CH Inc sync is a ClickHouse Inc private sync and is not actionable by me.

Session id: cron:our-pr-ci-monitor:20260813-113000

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 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: 58cbcad3-5a0a-49db-946c-59f1207b355a
  • MIRAI run: 3b6b5480-ac3e-4a50-ae3a-34dd7ffa421a
  • PR check IDs:
    • clickbench_140144_1787544910
    • clickbench_140291_1787544933
    • clickbench_140320_1787544934
    • tpch_adapted_1_official_140428_1787544936
    • tpch_adapted_1_official_140693_1787544946
    • tpch_adapted_1_official_140795_1787544970

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7d0b9e4

Every failure below has an owner: a fixing PR (ours 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
Stress test (arm_debug) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3775) pre-existing trunk abort in LimitBySortedStreamTransform; not reachable from this diff a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)

Not caused by this PR: the abort is at LimitByTransform.cpp:477
(LimitBySortedStreamTransform::transform) via ColumnDecimal::getEqualRangeEndAssumeSorted, and
this PR's diff touches none of LimitByTransform, SortCursor, ColumnDecimal or
findEqualRangeEndAssumeSorted (it changes Iceberg metadata, the object-storage table function,
Iceberg tests and one docs page). Breadth over 180 days: 9 occurrences across 9 distinct PRs plus 1
on master.

This is a new sub-signature within STID 2508-3775 rather than the already-tracked one: the other 8
carriers abort through DistinctSortedStreamTransform, which is what #110778 addresses, so that PR
is deliberately not linked as the owner here.

Session id: cron:our-pr-ci-monitor:20260825-020000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the LimitBySortedStreamTransform contiguity abort (STID 2508-3775)

The ledger above owed a fixing-PR link for this row. It is #113242 ("Do not push sorting into Merge children across an order-breaking cast"), already open.

The abort is not a distinct defect: LimitBySortedStreamTransform is a second consumer of the same upstream sort-property lie that #113242 fixes. I recovered the aborting query from the artifacts (query_log, query id 263c8fcc-62fe-497f-a236-1d06f8148ff5):

SELECT count() FROM (SELECT s FROM merge_distinct__fuzz_4 ORDER BY s ASC LIMIT 1 BY s LIMIT 100)
SETTINGS max_threads = 1, distributed_aggregation_memory_efficient = 0

merge_distinct__fuzz_4 is the stress AST fuzzer's retyped clone of the Merge table in 04870_distinct_merge_over_distributed.sql - a Decimal32 parent over a String Distributed child, which is exactly the order-breaking cast #113242 guards against.

Verified locally on master aedfbaa1cbfd51f, two-shard cluster, one fixture, two binaries differing only in #113242's src/ hunks:

build result
master SIGABRT, stack identical to this job's fatal.log
master + #113242 21 (correct), no abort

EXPLAIN PLAN shows the mechanism: on master the step above ReadFromMerge is Sorting (Merge sorted streams for ORDER BY, ...), so an order-bearing stage was delegated to children whose cast had already destroyed the order; with #113242 the children are read at FetchColumns and the initiator does a real sort. The guard sits in StorageMerge::getQueryProcessingStage, upstream of the sort-property claim, so it covers this consumer as well as DistinctSortedStreamTransform. Control: an unfuzzed String parent does not abort on master, so the mistyped cast is required.

Separately, #115839 pins ast_fuzzer_runs = 0 on 04870 and stops this wave in the stress lane without waiting on #113242.

Nothing here is caused by this PR's diff.

@groeneai

Copy link
Copy Markdown
Collaborator Author

While investigating a separate report I reproduced, on unmodified master, the failure mode this PR's refusal message describes ("no version increment ... so which generation a reader resolves is undefined"). Posting it here because it turns that sentence into a measured data-loss reproduction with no non-default settings.

Master 438a6180ae9641a3fc5dc4abe59a0c22a8c259f9, no expire_snapshots, no version hint, no cache setting. Reproduces identically in clickhouse local and on a server across separate connections.

CREATE TABLE t (id Int64, v String) ENGINE = IcebergLocal('user_files/t/', 'Parquet');
INSERT INTO t SELECT number, char(number + ascii('a')) FROM numbers(6)
  SETTINGS iceberg_insert_max_rows_in_data_file = 2, min_insert_block_size_rows = 2,
           max_insert_block_size = 2, max_block_size = 2, max_insert_threads = 1;
ALTER TABLE t DELETE WHERE id = 2 SETTINGS mutations_sync = 2;
INSERT INTO t SELECT number + 100, char(number + ascii('p')) FROM numbers(2);
OPTIMIZE TABLE t SETTINGS allow_experimental_iceberg_compaction = 1;  -- succeeds, result correct
ALTER TABLE t DELETE WHERE id = 4 SETTINGS mutations_sync = 2;        -- succeeds, no error
SELECT count(), sum(id) FROM t;   -- 0 / 0, expected 6 / 210

What metadata/ does across that run:

after *.metadata.json present SELECT count()
INSERT 6 rows v1 (empty, current-snapshot-id -1), v2 6
DELETE id = 2 v1, v2, v3 5
INSERT 2 rows v1, v2, v3, v4 7
OPTIMIZE v0 only, v1..v4 deleted 7
DELETE id = 4 v0, v1 0

The version counter restarts at 0 (getPlan never calls setVersion, and FileNamesGenerator::initial_version is 0) and clearOldFiles removes the whole prior chain, so the next writer re-issues v1.metadata.json. That path's content is already in IcebergMetadataFilesCache, cached at CREATE under table_uuid + path with no TTL and no version check, because metadata paths are assumed immutable. The reader is served the empty post-CREATE document, sees current-snapshot-id -1, and reports 0 rows with an empty system.iceberg_files.

Three probes pin that as the carrier: SYSTEM DROP ICEBERG METADATA CACHE restores 6 / 210; a fresh process over the same directory also reads 6 / 210, so the committed state is still correct at this point; and disabling the cache before CREATE prevents it outright. A per-query use_iceberg_metadata_files_cache = 0 does not help, since that flag is latched into PersistentTableComponents when the table object is built.

It stops being merely a wrong answer as soon as anything writes on top of the stale view. Continuing with ALTER TABLE t DELETE WHERE id = 100 and then INSERT INTO t VALUES (777, 'z'), the insert fails with Code: 1001 ... No such file or directory [".../data/data-4837dcdd-...parquet"], and a fresh reader afterwards finds one row (777) where six are correct. Those five rows are gone from disk.

Two bounds worth recording: a pre-existing position delete is required, since plan.need_optimize is set only when one exists and compaction is otherwise a no-op that never resets the version; and the second INSERT is not required, so the shortest form is INSERT / DELETE / OPTIMIZE / DELETE.

I am not opening a competing PR. The only reachable carrier is compactIcebergTable, which this PR makes unreachable.

@PedroTadim

Copy link
Copy Markdown
Member

@scanhex12 @SmitaRKulkarni can one of you review this?

@murphy-4o

Copy link
Copy Markdown
Member

@scanhex12 @SmitaRKulkarni looks like the data compaction does not work as expected ?
@groeneai we need to repair the compaction rather than refusing it

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, I will repair the publish path instead of refusing the command.

One measurement first, because it decides the shape of the repair: on master, with nothing pinned and the correct metadata root, a successful OPTIMIZE still leaves metadata/v0.metadata.json as the only metadata file in the table. That is not a stale-pointer edge case, it is how compactIcebergTable is built: writeMetadataFiles starts from createEmptyMetadataFile() with a fresh FileNamesGenerator (initial_version = 0), so the rewrite restarts the metadata lineage at v0 rather than committing a new version, and clearOldFiles then deletes a raw listing of metadata/ and data/ captured before the write. That is why the two per-call-site patches suggested in #120164 and #120165 (keep the pointer out of the delete list, ignore pointer overrides in getPlan / getHistory) are necessary but not sufficient.

The repair, all in Compaction.cpp, following what the manifest path in the same file already does in writeConsolidatedManifestFile:

  1. Commit on top of the current metadata: generator.setVersion(metadata_version + 1) and MetadataGenerator::generateNextMetadata over the loaded metadata object, instead of createEmptyMetadataFile.
  2. Publish through writeMetadataFileAndVersionHint (If-None-Match on the new vN.metadata.json, ETag CAS on version-hint.text) plus catalog->updateMetadata when a catalog owns the table, retrying and removing the newly written objects when the CAS is lost.
  3. Delete nothing at commit time: drop getOldFiles and clearOldFiles, and leave reclamation to expire_snapshots and remove_orphan_files, which resolve reachability.

I will rework this PR into that. If you would rather keep the refusal on master as an interim guard while the repair is reviewed, say so and I will split it into two PRs.

This is the non-cloud path only: in the CLICKHOUSE_CLOUD build IcebergMetadata::optimize goes through iceberg_compaction_metadata_generator, which I cannot see from here.

On Cloud, data compaction is allowed by the table-level
allow_experimental_iceberg_compaction setting (stored in the table definition,
or taken from the context that initializes the table metadata), and
IcebergMetadata::optimize never reads the setting sent with OPTIMIZE. The test
creates its table without that setting, so on a Cloud build the success
assertion for the first OPTIMIZE failed whenever that gate was closed, and the
setting-gate assertion for the second OPTIMIZE failed whenever it was open: no
Cloud configuration could pass both.

On Cloud, accept either outcome of that gate: OPTIMIZE succeeds, or its error
names the setting. Any other error, including the open-source refusal, still
fails there. The open-source assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The combined `UPDATE` / `MERGE` row said neither is supported, but
`ALTER TABLE ... UPDATE` is implemented for Iceberg tables:
`IcebergMetadata::checkMutationIsPossible` accepts it, it goes through the
same `IcebergMetadata::mutate` path as `DELETE` (gated by
`allow_insert_into_iceberg`), and test_writes_mutate_update.py covers it.
Measured on master 026dca3: without the setting it fails with
SUPPORT_IS_DISABLED ("Iceberg mutations is experimental"), with it the
row is updated. `MERGE` has no statement in ClickHouse (SYNTAX_ERROR).

The `UPDATE` row now mirrors the `DELETE` row; `MERGE` stays unsupported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`allow_experimental_iceberg_compaction` enables only `OPTIMIZE TABLE ... MANIFEST`
in open-source builds, because data compaction reports `NOT_IMPLEMENTED` there. The
support matrix and the Iceberg table function docs already say so; the settings
reference page, which is generated from this description, did not.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +132 to +155
started_cluster_iceberg_with_spark, instance, storage_type, table_name
)
removed = sorted(set(files_before) - set(files_after))
assert not removed, f"OPTIMIZE deleted pre-existing files: {removed}"

if hint_state == "stale":
# Point the hint back at the version it named before it went stale. Reading through a
# stale hint legitimately returns the older version, so the hint has to name the newest
# one for the row assertion below to be about `OPTIMIZE` rather than about the hint.
_write_version_hint(
started_cluster_iceberg_with_spark,
instance,
storage_type,
table_name,
newest_before,
)

# The acked third insert must still be there, and the table must still be readable
# through the version it was committed at.
assert instance.query(f"SELECT x FROM {table_name} ORDER BY x") == "1\n99\n"
assert int(instance.query(f"SELECT count() FROM {table_name}")) == 2

instance.query(f"DROP TABLE {table_name} SYNC;")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai Checking filenames and current rows does not prove a retained snapshot remains readable, and cached metadata can mask an overwrite. Please capture a pre-delete snapshot ID and verify its rows and current rows after clearing the Iceberg metadata cache.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in c5de71d: the test takes the snapshot before the DELETE from system.iceberg_history, checks that it reads [1,2] before OPTIMIZE, and after SYSTEM DROP ICEBERG METADATA CACHE checks it again together with the current rows. On a master binary with the removed-files check disabled, the absent-hint arms fail only on that snapshot read.

Comment on lines +31 to +44
if grep -qF 'Logical error' <<< "$out"; then
echo "FAIL: logical error: $out"
elif [ "$is_cloud" = 1 ]; then
if grep -qF 'Code:' <<< "$out" && ! grep -qF allow_experimental_iceberg_compaction <<< "$out"; then
echo "FAIL: expected OPTIMIZE to succeed or to name the setting: $out"
else
echo "ok"
fi
elif grep -qF NOT_IMPLEMENTED <<< "$out" \
&& grep -qF 'not yet supported for Iceberg data compaction' <<< "$out"; then
echo "ok"
else
echo "FAIL: expected a NOT_IMPLEMENTED refusal on the open-source build: $out"
fi

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai The Cloud arm accepts a disabled-table setting error as ok, so it never proves Cloud compaction works. Please use a separately initialized table with per-table compaction enabled and require its OPTIMIZE to succeed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 1463ab1: a second table created with SETTINGS allow_experimental_iceberg_compaction = 1 must compact successfully on Cloud, and the open-source build must still refuse it. I cannot build Cloud here, so I ran the test body against a stub client: a Cloud build where every OPTIMIZE names the setting passed before this change and fails now. On a real open-source server, forcing is_cloud=1 fails on the refusal.

@arsenmuk

Copy link
Copy Markdown
Member

@groeneai please update to the latest master while addressing my latests comments on this PR

groeneai and others added 5 commits September 30, 2026 10:49
…NIFEST

The table function docs listed only the format-version requirement, while
manifest compaction also rejects encrypted tables whose data files carry
per-file key_metadata with NOT_IMPLEMENTED.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The iceberg_data_file_size_*_threshold_compaction, iceberg_compaction_*,
iceberg_max_number_datafiles_to_compact and
allow_experimental_cleanup_old_data_files_compaction settings have no reader
in the open-source build, so their docs pages presented data compaction as
available there. Their descriptions now carry the in-file marker
"Only has an effect in ClickHouse Cloud", which also adds the Cloud-only
badge to the generated settings pages.

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

The stale-hint arm now points the hint at the newest metadata version after
OPTIMIZE instead of the pre-OPTIMIZE one, so a published result is what gets
read. The test also captures the snapshot before the delete and, after
dropping the Iceberg metadata cache, checks that it still reads [1, 2] next to
the current rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed in 04880

The Cloud arm accepted the table-level setting error, so it never proved that
compaction works there. A second table created with the table-level
allow_experimental_iceberg_compaction now has to compact successfully on
Cloud, and the open-source build must still refuse it.

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

Copy link
Copy Markdown
Collaborator Author

Merged master (3eda573) without conflicts and pushed 1463ab1 with the five review changes on top. Locally test_optimize.py passes 6/6, and 04880 plus the other Iceberg stateless tests pass.

The test pins issue ClickHouse#89037, which was reported through OPTIMIZE TABLE, but
the probe was dropped when data compaction started being refused. It is
back, with the open-source refusal added to the tolerated outcomes, so the
test still fails on the conversion error once compaction runs on this
fixture again. A build that calls getHistory before the refusal and reads
the two metrics unguarded now fails at the probe with the reported message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…able in 04880

With `--allow_experimental_iceberg_compaction=1` on the query, the Cloud arm
would also pass if the gate fell back to the query-level setting and the
table-level one stopped mattering. The Cloud call now relies on the
table-level setting alone. The open-source call keeps both settings, so it
still proves the refusal holds when every gate is open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@arsenmuk
arsenmuk added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit f124960 Oct 1, 2026
149 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Oct 4, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 123508 114437 Revert "Refuse Iceberg data compaction until it can publish its result"
Changelog-revert: 123789 122853 Revert "Make LLVM coverage opt-in in pull requests, run the same configurations on arm_binary"
Changelog-deleted-entry: 114437 [Improvement] [section] * In the open-source build, `Iceberg` data compaction (`OPTIMIZE TABLE` with `allow_experimental_iceberg_compaction = 1`) now reports `NOT_IMPLEMENTED` instead of running, because it deleted files that retained snapshots still referenced, including `version-hint.text` and every `vN.metadata.json`, which left the table unreadable and could permanently lose an acknowledged snapshot's rows. `OPTIMIZE TABLE ... MANIFEST`, `expire_snapshots`, and `remove_orphan_files` are unaffected. [#114437](#114437) ([Groene AI](https://github.com/groeneai)).
Changelog-deleted-entry: 122853 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Make LLVM coverage opt-in in pull requests, run the same configurations on arm_binary. [#122853](#122853) ([Nikita Fomichev](https://github.com/fm4v)).
@arsenmuk

arsenmuk commented Oct 5, 2026

Copy link
Copy Markdown
Member

@groeneai I reverted this change via #123508
We must not fail-close compaction due to lack of the proper implementation - we should implement it.

I want you to:

  • re-assess the problem
  • open a new issue with a clean repro [if such doesn't exist yet]
  • open a new PR with the necessary wiring and implementation to enable compaction + optimize; assign me as a reviewer

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm re-assessing the Iceberg OPTIMIZE compaction data loss on current master; I'll open an issue with a clean repro (if none exists yet) and a new PR that implements the missing publication wiring so compaction and OPTIMIZE work, with you as reviewer, and link both here.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

I opened #123982 with a clean repro on current master, and #124114, which makes OPTIMIZE commit one replace snapshot on top of the current one instead of rewriting the table, so catalog-backed and iceberg_use_version_hint tables can be compacted too. You are requested as reviewer there.

@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants