Skip to content

Skip Iceberg compaction on a table with no current snapshot - #121500

Open
groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:iceberg-optimize-no-current-snapshot-guard
Open

groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:iceberg-optimize-no-current-snapshot-guard

Conversation

@groeneai

@groeneai groeneai commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121134
Related: #121460

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 with no current snapshot is now a no-op instead of rewriting the table from its append history, which brought back rows that SELECT reads as gone, and it now fails like SELECT when current-snapshot-id names a snapshot missing from the table metadata. Requires allow_experimental_iceberg_compaction.

Description

Asked for by @ alexey-milovidov on #121134: private meta in keeper lanes aborted on
Logical error: Background compaction is not initialized from IcebergMetadata::optimize
(job).
@ Algunenano reverted #114465 in #121443 over it.

Cause. Compaction never checks for a current snapshot: getPlan sets
need_optimize from any historical position delete and republishes a chain from append history, so a
table that SELECT reads as empty gets its old rows back. @ tiandiwonder's check for that in #114465
was #else-only, so his tests still hit the #if CLICKHOUSE_CLOUD arm's
IcebergCompactionMetadataGenerator assertion.

Change. Before the #if, optimize reads current-snapshot-id from the latest metadata and
skips compaction when it is absent, null or negative (ClickHouse writes -1 for a new table), so
neither arm reaches that assertion from such a table, and on cloud it also stops
waiting on the generator. The open-source arm passes that metadata to the compaction plan, so OPTIMIZE
lists metadata/ once. An id missing from snapshots now fails like SELECT
(ICEBERG_SPECIFICATION_VIOLATION): compacting the rest would lose or resurrect its rows. A table that
has a current snapshot and no generator still asserts. Only the private sync tests that arm.

Overlap with #121460: it re-lands the #114465 check #else-only, plus readers accepting a null
current-snapshot-id, so its test skips OPTIMIZE on cloud, where this one asserts on both builds.
Happy to reduce or drop this once it lands; the test derives from his.

Validation. With the check removed, -1 and absent return after=3 and null raises a Poco
conversion error. Removing any one of the < 0, isNull or snapshots-lookup clauses fails its own
variant. With it, 100 runs green and other Iceberg OPTIMIZE tests unchanged.


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

groeneai and others added 6 commits September 21, 2026 23:29
…h build arms

A table whose `current-snapshot-id` says "no current snapshot" reads as empty, but
`OPTIMIZE TABLE` brought its historical rows back. `getHistory` marks no record a
current ancestor when there is no current snapshot; compaction never consulted
that, so `getPlan` set `need_optimize` from a historical position delete and the
rewrite republished a snapshot chain built from append history, restoring the old
`current-snapshot-id` and every row with it. Measured on post-revert master
(be9434c): a table that `SELECT` reads as 0 rows comes back with 3 after
`OPTIMIZE`, for `current-snapshot-id` spelled `-1` and for the key absent alike.

`IcebergMetadata::optimize` splits on `#if CLICKHOUSE_CLOUD`, and the two arms fail
differently on that one state. The open-source arm rewrites and resurrects. The
cloud arm never looks at the snapshot state at all: it asserts that the background
compaction generator exists, which for such a table it does not, so a
`LOGICAL_ERROR` aborts the server under a sanitizer build.

So the refusal goes above the `#if`, where the state `getHistory` already computed
is available to both arms, and the setting check keeps its place ahead of it: a
user who forgot `allow_experimental_iceberg_compaction` still gets `BAD_ARGUMENTS`
rather than a silent success. Deriving the condition from `is_current_ancestor`
instead of re-reading `current-snapshot-id` covers every spelling of the absence
with one check, and a `current-snapshot-id` naming a snapshot missing from
`snapshots` lands in the same branch - that metadata is corrupt, and refusing the
rewrite is the fail-close answer for it too. The `LOGICAL_ERROR` is left exactly as
it is for every other state, so a cloud table that does have a current snapshot and
no generator yet still reports the bug it is.

The guard and the test are deliberately independent of the `has`-versus-`isNull`
reader normalization: the JSON `null` spelling still raises a Poco conversion error
inside `getHistory` (measured: `Code: 1000 ... Can not convert empty value`), which
is ClickHouse#114465's reader fix and not re-landed here, so the test covers `-1` and the
absent key only. `OPTIMIZE TABLE ... MANIFEST` goes through the separate
`optimizeManifestFiles` and is untouched.

Requested in ClickHouse#121134 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
Hoisting the no-current-ancestor refusal above the `#if CLICKHOUSE_CLOUD` split
routed the cloud arm through `IcebergMetadata::getHistory` for the first time.
That reader extracted the optional `snapshots` key without checking for it, so a
table whose metadata omits the key answered `OPTIMIZE` with
`Code: 1000 ... Can not extract empty value` instead of the refusal. `snapshots`
is optional in the Iceberg spec, and three sibling readers already treat an
absent key as an ordinary empty state rather than as corruption, so the guard
goes at the reader, once, for both of its callers.  `system.iceberg_history`
already reported zero rows for such a table through its catch-all, so its output
is unchanged.

Measured on three binaries of one tree: with neither change the two original
variants resurrect rows; with the hoist alone the new `no_snapshots` variant
fails inside `getHistory`; with both, all four variants leave the table empty.

The test also stops excusing the background-compaction assertion.  It tolerated
any nonzero status on a cloud build, so on a release cloud build, where the
retained `LOGICAL_ERROR` is an ordinary exception rather than an abort, the one
regression it exists to prevent would have passed.  The captured message is now
rejected on every build, while unrelated cloud exceptions stay tolerated.
…etHistory

`current-snapshot-id` spelled JSON `null` is the same state this change makes a
quiet no-op, but `IcebergMetadata::getHistory` tested the key with `has()` alone.
Poco's `has()` is true for an explicit null, so `getValue<Int64>` raised
`Code: 1000 ... Can not convert empty value` before the refusal could run.

Hoisting the refusal above the `#if CLICKHOUSE_CLOUD` split is what puts that
error on the cloud arm, which never called `getHistory` before, so the spelling
belongs to this change rather than to the reader normalization it was previously
deferred to. The state itself is ordinary and the tree already says so: 400 lines
above, the same file maps a null `current-snapshot-id` to `-1` and reads such a
table as empty, and `Mutations.cpp` and `IcebergWrites.cpp` pair `has` with
`isNull` on the same key. One line brings the history reader in line with them.

It also makes the refusal's own comment true. That comment states that
`getHistory` marks no record a current ancestor when a table has no current
snapshot; for the null spelling `getHistory` threw instead of marking, and now it
skips the ancestor walk exactly as it already did for an absent key.

Measured on binaries of one tree, one guard at a time: with the hoist and the
`snapshots` guard but not this one, the new `null` variant fails inside
`getHistory` (`Code: 1000`), while the other four variants are unaffected; with
it, all five leave the table empty. `system.iceberg_history` on such a table
reported that conversion error before and now reports its records with
`is_current_ancestor` false throughout, which is what it already did for an
absent key. No stateless test reads that table, and the one integration test
mentioning the error strips optional summary metrics rather than
`current-snapshot-id`.

`OPTIMIZE TABLE ... MANIFEST` keeps its own `has`-only reads of the key. It is
reached through `optimizeManifestFiles`, a separate entry point this change
neither touches nor newly routes, so its behavior is unchanged.

The test gains the `null` variant as its first arm and an `EXIT` trap, so an
interrupted or failing run no longer leaves a fixture directory behind under
`user_files`. The trap expands at exit to whichever variant was in flight, and is
a no-op before the first iteration.

Requested in ClickHouse#121134 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
`IcebergMetadata::getHistory` opened by asserting that the `format_version`
cached in `persistent_components` equals the one in the metadata file it had just
read. Those are not the same value. `PersistentTableComponents` documents the
cached one as the value observed when the table was opened, and says the
authoritative version for parsing a specific manifest list or manifest file is
taken from that file's own Avro metadata, "so an external upgrade (e.g. Spark
v1 -> v2) between queries does not corrupt this cache". An external upgrade is
therefore expected to make the two differ, and
`test_storage_iceberg_with_spark/test_format_version_upgrade.py`, the regression
test for ClickHouse#86776, makes that path a supported one whose stated contract is that
reading "should succeed rather than triggering a logical error".

The assertion also guarded nothing in this function. `getHistory` reads the
metadata JSON's `snapshots` and `snapshot-log` and never parses a manifest list or
a manifest file, so the cached version is not an input to anything it does. Every
other reader in the file takes the version from the file it is parsing
(`initializePersistentTableComponents`, `parseTableSchema`) instead of comparing
it against the cache.

Left in place it would fire more often, not less: hoisting the
no-current-snapshot refusal above the `#if CLICKHOUSE_CLOUD` split routes the
cloud arm of `OPTIMIZE` through `getHistory` for the first time, and `chassert`
aborts the server in every `DEBUG_OR_SANITIZER_BUILD`, which is the build class
of the lanes this change exists to quiet.

Measured on two debug binaries of this tree differing only in that line, using the
new `format_upgrade` variant of
`05237_iceberg_optimize_snapshotless_position_delete`: with the assertion (build
id 43e0a1f88f823acbf015b0803913ccaa114ee113) `OPTIMIZE` aborts the server at
`IcebergMetadata.cpp:998` inside `getHistory`, reached from `optimize`; without it
(735fa7c5fcb78ff5b11d799647a83a547b69464b) the test passes, and 50 randomized
plus 50 non-randomized runs are green. `system.iceberg_history`, the function's
other caller, still reports an ordinary table's snapshots with their ancestry.

That variant cannot share the loop above it. The cached version is fixed when the
table is opened, so the loop's `DETACH`/`ATTACH` would re-read the upgraded file
and leave nothing to exercise, and a v1 table refuses the loop's position delete
("Mutations are supported only for the second version of iceberg format"). It
creates a v1 table with `iceberg_format_version = 1`, keeps it open, upgrades the
newest metadata file to v2 as an external tool would, and drops
`current-snapshot-id` so the refusal under test is still the path taken. The
metadata files cache is off from the `CREATE` on, because a cache captured at open
time answers every later read from memory and the on-disk upgrade would be
invisible.

Requested in ClickHouse#121134 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
On a cloud build `IcebergMetadata::optimize` refuses on `compaction_enabled` before
the hoisted `getHistory` guard, so a table whose flag is false never reaches the code
this PR changes and the test could pass without exercising it.

`DataLakeStorageSettings.h` documents a per-table `allow_experimental_iceberg_compaction`
and states that when it is not set explicitly in the table definition, the query-level
setting of the context that initializes the table metadata is used instead. The fixture
set only the query-level setting, and only on the `OPTIMIZE` invocation, so the context
that initialized the metadata never carried it and neither table definition asked for
compaction. Both `CREATE TABLE`s now set it per table.

Nothing in `src/` reads the per-table setting outside the cloud overlay, so it is inert
on the open-source build: the six reference lines are unchanged, byte for byte, and 50
randomized plus 50 non-randomized runs are green.

The classification now fails on any cloud error other than a refusal naming that
setting. That one outcome stays tolerated because `compaction_enabled` is declared
outside this repository, and an unconditional "must succeed on cloud" could redden the
private lanes for a cause this repository cannot fix.

Requested in ClickHouse#121134 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
A count of zero cannot tell "the guard refused compaction" from "there was nothing to
rewrite", so the fixture could stay green without ever executing the code this PR adds.
Two paths reach a zero count with the guard never running. On a cloud build `optimize`
refuses on `compaction_enabled` before the guard, and the classification tolerated that
refusal, so the table was left untouched and all six lines printed unchanged. On any
build the `empty_snapshots` variant has no position delete to collect, so
`plan.need_optimize` stays false (`Compaction.cpp:312`) and the rewrite is a no-op
whether or not the guard is compiled in.

`OPTIMIZE` is now additionally held to logging the refusal it is supposed to take.
`LOG_INFO(log, "No snapshot is a current ancestor, skipping compaction")` sits above the
`#if CLICKHOUSE_CLOUD` split, so requiring it proves the changed code executed on the
open-source arm and on the cloud arm alike. The line is delivered by raising
`send_logs_level` to `information` on the `OPTIMIZE` invocation only, the same mechanism
this file already uses to lower it elsewhere.

Requiring that line subsumes the tolerated cloud refusal: if `OPTIMIZE` was refused
before the guard then the line is absent and the test fails. The tolerance is therefore
retired rather than narrowed, no branch accepts a nonzero status any more, and the
`IS_CLOUD` probe that fed only that branch is dead and removed.

Measured with only the guard hunk toggled out of an otherwise identical tree, every
variant now reddens with `FAIL: OPTIMIZE did not reach the snapshotless guard`,
including the two a row count could never move:

  variant          guarded 735fa7c5   guardless b44572e1
  null             before=0 after=0   FAIL (guard not reached)
  negative         before=0 after=0   FAIL (guard not reached)
  absent           before=0 after=0   FAIL (guard not reached)
  empty_snapshots  before=0 after=0   FAIL (guard not reached)
  no_snapshots     before=0 after=0   FAIL (guard not reached)
  format_upgrade   before=0 after=0   FAIL (guard not reached)

The `.reference` file is unchanged, byte for byte, and 50 randomized plus 50
non-randomized runs are green.

Requested in ClickHouse#121134 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent cold read of the diff plus a second-model pass on every head, adjudicated against the
recorded validation. Accepted and fixed before publication:

Finding Verdict
❌ On a Cloud build OPTIMIZE is refused on compaction_enabled before the hoisted guard, and neither fixture asked for compaction per table, so the test could pass whether or not the guard existed, on the one build class this change exists for. AGREE, fixed: both CREATE TABLEs set the per-table allow_experimental_iceberg_compaction, and no branch tolerates a nonzero status any more.
❌ getHistory opened by asserting that the format-version cached when the table was opened equals the current file's. PersistentTableComponents documents the opposite as intended, an external Spark v1 to v2 upgrade is supported (#86776), and the assertion aborts debug and sanitizer builds. AGREE, fixed: deleted. getHistory parses no manifest, so the cached version is not an input to it.
❌ The hoist routes the Cloud arm through getHistory, which read the optional snapshots key unguarded, so a table with no snapshot set failed there instead of reaching the refusal. Three sibling readers guard that key. AGREE, fixed: one guard at the reader, in the siblings' shape.
❌ current-snapshot-id spelled JSON null is the same state this change makes a no-op, but getHistory checked only has before converting to Int64, so it raised Can not convert empty value first. AGREE, fixed: isNull handled at that reader, with the null variant and a measured necessity arm.
❌ A row count of zero cannot tell "the guard refused" from "there was nothing to rewrite", so two variants were green for a reason unrelated to the guard. AGREE, fixed: OPTIMIZE must now log the refusal it is supposed to take, which happens above the #if CLICKHOUSE_CLOUD split, so all six variants redden when the guard is removed.
⚠️ isCurrentManifestListAboveThreshold and writeConsolidatedManifestFile keep the same has-only read, so OPTIMIZE ... MANIFEST throws on a null table. DISAGREE on placement, not on the defect: both are reached only from optimizeManifestFiles, which this change neither touches nor newly routes, and #121460 guards those two exact lines. Named in the description.
⚠️ optimize reads the history and then rewrites without binding the commit to the version it read. DISAGREE: byte-for-byte pre-existing (the base tree already read the history then called compactIcebergTable, and getPlan already re-fetched), there is no version predicate to bind to, and the contract here is a table state rather than a concurrency model.
⚠️ The fixture rewrites an Iceberg metadata JSON directly, against the rule that stateless tests must not hand-modify data. DISAGREE: that rule's subject is MergeTree parts. An Iceberg metadata JSON is the multi-writer surface ClickHouse exists to read, test_format_version_upgrade.py simulates this upgrade with Spark, and 04230_iceberg_optimize_metadata_not_initialized_104711 overwrites every *.metadata.json in a merged stateless test. ClickHouse never writes the state under test.
💡 getHistory's iceberg_history local is declared one line above the new early return, so it is dead on that path. DISAGREE, noted not blocking: moving it enlarges the diff without changing behaviour.

Verified independently rather than taken from the validation notes: plan.need_optimize comes from
any historical position delete with no ancestry filter, and the only readers of is_current_ancestor
are the history builder, system.iceberg_history and the new refusal; the refusal precedes both
#if CLICKHOUSE_CLOUD blocks, which is what lets the test issue OPTIMIZE on a Cloud build at all;
the existing plain OPTIMIZE coverage, 04230 and 04513 included, passes on both binaries, so the
refusal is not refusing every table; and each of the six variants fails for a distinct mechanism when
its own guard is removed.

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2bb61f2]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Reviewed head 2bb61f29835ffde0a09fe6b29eb54287e1b3fa29. The PR makes plain OPTIMIZE TABLE skip snapshotless Iceberg tables, reject dangling snapshot ids, and use one metadata object for validation, history and planning. Two existing concerns remain in OPTIMIZE TABLE ... MANIFEST; request changes. The separate, pre-existing rollback-replay defect is tracked by #118951.

Findings

⚠️ Majors

  • Compaction.cpp:164, also line 531: OPTIMIZE TABLE ... MANIFEST still throws a Poco conversion exception for current-snapshot-id: null. Both isCurrentManifestListAboveThreshold and writeConsolidatedManifestFile check only key presence before converting it. This is the same ordinary snapshotless state that plain OPTIMIZE now accepts, leaving equivalent empty-table representations with different results. Add the isNull check at both sites, or land the corresponding change from Fix an error reading an Iceberg table whose current-snapshot-id is JSON null #121460 first. [dismissed by author -- https://github.com/Skip Iceberg compaction on a table with no current snapshot #121500#discussion_r4078047324] The author assigns this to that separate PR; it remains open, and the conversion is still present in the reviewed head. The earlier thread's absent-snapshots allegation is dropped: snapshotless inputs return before that access.

  • Compaction.cpp:179, also line 554: a non-negative current-snapshot-id absent from snapshots makes manifest compaction report success as though no work were needed. SELECT and the new plain-OPTIMIZE guard reject the same metadata with ICEBERG_SPECIFICATION_VIOLATION. Validate snapshot resolution before the threshold early return and preserve the same distinction between an empty table and a dangling pointer in writeConsolidatedManifestFile. Existing thread.

Missing context / blind spots
  • ⚠️ The private Cloud compaction generator is unavailable in this checkout, and the current head's Iceberg test results were not available in the fetched Praktika report. A passing Cloud run of 05237_iceberg_optimize_snapshotless_position_delete would validate the original private-build failure path. No local server binary or build was available for runtime verification.
Tests
  • ⚠️ Add focused stateless coverage for OPTIMIZE TABLE ... MANIFEST with a null current snapshot and a dangling current snapshot id. Require successful no-op behavior for the former and ICEBERG_SPECIFICATION_VIOLATION for the latter. The new test exercises only plain OPTIMIZE.
Final Verdict

⚠️ Request changes. Normalize null snapshot ids and reject dangling snapshot ids consistently in manifest compaction, with focused regression coverage. Both findings already have inline threads; no duplicate inline comments were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 22, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov you have to review this

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 582f15950 with master 4e3df38e8 (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4a7b802

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, and it passed on
this head, so every red line below carries a fixing-PR link.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 3/6) dashboard-verdict gate: 5 too long; 1 confirmed regression(s) on the performance dashboard. The shard's own report called no query slower, so the red comes from the dashboard gate alone #121090 (ours, open)
Mergeable Check aggregator mirroring the row above #121090 (ours, open)
PR aggregator mirroring the row above #121090 (ours, open)

No functional, integration, sanitizer, fuzzer or build check failed on this head: a CIDB scan scoped
to 4a7b802082e7 returns zero FAIL/ERROR rows, and the 176 check-runs are 132 success, 41 skipped,
3 failure (the three rows above).

Why #121090 is the fix for this line and not a coincidental same-area PR: it changes the master_head
gate to fail a shard only when the shard's own report also calls the query slower. This shard reported
0 slower, so under #121090 it would not be red. The merged sibling fix #121278 (threshold keying by
query text) is already an ancestor of this head and did not prevent the flag, so it is not this line's
owner.

Session id: cron:our-pr-ci-monitor:20260922-110203

@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 22, 2026
Comment on lines +1060 to +1084
@@ -1068,8 +1079,9 @@ IcebergMetadata::IcebergHistory IcebergMetadata::getHistory(ContextPtr local_con
parents_list[snapshot_id] = 0;
}

/// For empty table we may have no snapshots
if (metadata_object->has(f_current_snapshot_id))
/// For empty table we may have no snapshots. `has` is true for a JSON null, which
/// `getValue<Int64>` cannot convert, and which means "no current snapshot" like an absent key.
if (metadata_object->has(f_current_snapshot_id) && !metadata_object->isNull(f_current_snapshot_id))

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.

This normalizes snapshotless metadata only for plain OPTIMIZE. The sibling OPTIMIZE TABLE ... MANIFEST path still treats two of the same carriers as hard errors: isCurrentManifestListAboveThreshold does getValue<Int64>(f_current_snapshot_id) and get(f_snapshots) without the new isNull / has guards (Compaction.cpp:158-165), and writeConsolidatedManifestFile repeats that at Compaction.cpp:441-457. So a table with current-snapshot-id = null or no snapshots array will still throw from the MANIFEST variant instead of taking its existing "No current snapshot found, skipping manifest consolidation" no-op path. Since this PR establishes "no current snapshot" as an ordinary empty-table state, the manifest-compaction entrypoint needs the same normalization (plus a focused test) or an explicit rejection.

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.

Checked both sites on the current head (6cebb86a).

The null half is real: has() is true for a JSON null, so getValue<Int64> throws at Compaction.cpp:160 and :446. It is not unowned, though. #121460 (the re-land of #114465, open) changes exactly those two lines to !has(...) || isNull(...), which is the guard you are asking for, so I would rather not put a second open PR on the same two lines.

The no snapshots array half does not hold as written. Reaching get(f_snapshots) at :165 / :457 needs current-snapshot-id present, non-null and >= 0. None of the states this PR normalizes get there: an absent id stops at :158 / :441, -1 at :161 / :447, an empty array at :175 / :469, and null at the isNull guard above. An absent snapshots array therefore throws only alongside a current snapshot id that names no snapshot, which is not a state this PR creates.

On scope: this diff does not touch or newly route optimizeManifestFiles. getHistory has two callers (IcebergMetadata.cpp:492 and StorageSystemIcebergHistory.cpp:121), and MANIFEST dispatches separately at InterpreterOptimizeQuery.cpp:56 and reads the metadata object itself, so its behaviour is identical before and after this PR.

If depending on #121460 landing is not wanted, the two-line guard is cheap to take here instead; your call.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6cebb86

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
Performance Comparison (arm_release, master_head, 2/6) perf gate, not reachable from this diff: the shard is red only on an external performance-dashboard confirmed_regression. Its own report calls no query slower at this head. Its job line reads 2 too long; 1 confirmed regression(s) on the performance dashboard, and all 1200 of its per-query rows are success, and 0 are slower. Control: shard 3/6 at this same head reports 3 too long and passes on a strictly larger too long count, so too long is not the gating clause. Repo-wide and not specific to this pull request: the number of distinct pull requests with a red arm_release, master_head shard rose from 1, 3 and 9 on 2026-09-15, 09-16 and 09-17 to 144, 124, 111, 98, 102 and 86 on 09-18 through 09-23, against 200 shard successes today, so the onset is a harness-side change in the verdict gate rather than anything in this diff #121090 + #121189 (mine, open; they close this case only as a pair)

Mergeable Check and PR are the praktika aggregators of the row above, not an independent failure.

Gates: (a) 0 of 176 checks queued or running (132 green, 41 skipped, 3 red); (b) Mergeable Check and the PR aggregator both completed; (c) 174 min since the last job finished at 2026-09-23T08:30:25Z; (d) 1 red rows resolved, 0 ownerless, 0 new fix tasks needed.

Session id: cron:our-pr-ci-monitor:20260923-103206

@SmitaRKulkarni SmitaRKulkarni self-assigned this Sep 28, 2026
groeneai and others added 2 commits September 28, 2026 10:40
…-current-snapshot-guard

# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp
Review asked for the "no current snapshot" check without building the
complete history through `getHistory`. `optimize` now reads the latest
metadata object and skips compaction when `current-snapshot-id` is absent,
`null` or negative, the predicate `Mutations.cpp` and `getRelevantState`
already use. The negative clause is needed: ClickHouse writes `-1` for a
table without snapshots (`Utils.cpp`), and without that clause the test's
`negative` case is compacted and its three hidden rows come back.

The Cloud arm no longer calls `getHistory` at all, so the three `getHistory`
edits the history-based check needed (the absent-`snapshots` guard, the
`isNull` guard and the removal of the `format_version` `chassert`) are
reverted and `getHistory` is the same as on master. The test keeps one case
per clause of the condition (`null`, `-1`, absent) and drops the three cases
that only covered those edits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The direct `current-snapshot-id` check compacted any table whose id is
non-negative, including one whose id is missing from `snapshots`. Such
metadata is invalid (`SELECT` fails with `ICEBERG_SPECIFICATION_VIOLATION`),
and compaction rebuilds the table from the snapshots that ARE listed, so the
missing snapshot's changes are lost: when the lost current snapshot deleted a
row, `OPTIMIZE` succeeded and `SELECT` then returned that row again
(`[1,3]` became `[1,3,4]`); when it inserted rows, they were dropped. The
history-based check this replaced skipped such tables, because `getHistory`
marks no listed snapshot a current ancestor.

`optimize` now resolves the id through `traverseMetadataAndFindNecessarySnapshotObject`,
the lookup the read path uses, and raises the same error as `SELECT` when
it is missing, before the `#if CLICKHOUSE_CLOUD` split. The `dangling` test
case drops the current snapshot's entry and expects both `OPTIMIZE` and a
later `SELECT` to fail; without the lookup `OPTIMIZE` succeeds and `SELECT`
returns 2 rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
LOG_INFO(log, "No current snapshot found, skipping compaction");
return true;
}
if (!traverseMetadataAndFindNecessarySnapshotObject(metadata_object, current_snapshot_id, persistent_components.schema_processor))

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.

Rejecting a dangling current-snapshot-id here is the right contract, but it only covers plain OPTIMIZE. The sibling OPTIMIZE TABLE ... MANIFEST path still treats the same carrier as success: isCurrentManifestListAboveThreshold and writeConsolidatedManifestFile just look for the id in snapshots, and if it is missing they fall through to the existing "No current snapshot found" / "not needed" path instead of raising the same ICEBERG_SPECIFICATION_VIOLATION that SELECT and this code now use. That leaves the two compaction entrypoints disagreeing about whether the metadata is corrupt or merely empty. Please fan the same snapshot-resolution check out to the manifest-compaction path, or explicitly reject that entrypoint on dangling current-snapshot-id.

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.

I kept OPTIMIZE ... MANIFEST out of this PR: on a dangling current-snapshot-id it returns from isCurrentManifestListAboveThreshold without writing anything, so it cannot rewrite the table from metadata that SELECT rejects, and this PR does not touch or reroute that entry point. Raising there instead of skipping would change the reported outcome but no data, so it is not part of this fix.

The snapshot guard in `IcebergMetadata::optimize` resolves and parses the
latest metadata file, and the open-source arm then called `getHistory`,
which resolved and parsed it again with the same arguments before
`getPlan` resolved it a third time. On S3 each resolution lists
`metadata/`, so a planning-only OPTIMIZE went from 2 listings on master
to 3, and `iceberg_suite_s3_write` query ClickHouse#2 regressed 4.30 -> 5.80 ms
(+34.5%) in `Performance Comparison (arm_release)`.

Split `getHistory` into the fetch and a private `getHistoryImpl` that
builds the history from a given metadata object, as `getState` and
`getStateImpl` already do, and build the compaction history from the
object the guard validated. The planning pass is back to 2 listings
(`S3ListObjects` 3 -> 2 per OPTIMIZE, metadata cache hits 68 -> 67, both
equal to a build without the guard), and the history that is compacted
is always the one the guard checked. `system.iceberg_history` is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Refuse Iceberg compaction on a table with no current snapshot Skip Iceberg compaction on a table with no current snapshot Oct 11, 2026
@groeneai

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

Review of eba566f3af5c5 (engine: codex): 0 findings.

The commit fixes the iceberg_suite_s3_write #2 regression this PR caused in Performance Comparison (arm_release, master_head, 6/6): the snapshot check and getHistory resolved the same metadata file twice. Measured on one tree, a planning-only OPTIMIZE now does 2 S3ListObjects instead of 3, the same as a build without the check, and the compacted history is built from the metadata object the check validated. system.iceberg_history output and the rows of a real rewrite are unchanged.

Session id: cron:clickhouse-review-slot-8:20261010-235200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - eba566f

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, s3 storage, DBReplicated, parallel, 1/2) / 05339_parquet_prewhere_subcolumn_read_through_column not from this PR (it changes Iceberg OPTIMIZE only): the test passes a session temporary table to IcebergLocal, which the replicated DDL worker cannot see (UNKNOWN_TABLE on iceberg_path). 65 PRs and 40 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 praktika rollups of the row above #125121 (external, merged)
Sync - CH Inc sync (private, not actionable by me)

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

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only changes IcebergMetadata::optimize: it now skips OPTIMIZE when an Iceberg table has no current snapshot, and splits history loading into getHistoryImpl. It also adds a stateless test. None of the ClickBench or TPC-H queries run OPTIMIZE or read Iceberg tables. The TPC-H improvements on Q1 (-20.3%) and Q7 (-23.1%) are downgraded to not_sure: both queries are noisy on master, and both new medians fall inside master's recent range. ClickBench Q13 (+13.8%) and Q32 (+18.1%) were already left as not_sure because they fall inside master's normal range, and that is consistent with the diff. Their higher CPU time does not come from code in this PR, and two of the PR's ClickBench runs shared a host, which may have added contention.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 13 not_sure 349 397 +13.8% <0.0001 The +13.8% delta stays inside master's recent range. This PR only changes OPTIMIZE for Iceberg tables, which this MergeTree SELECT never runs, so it cannot explain the delta.
⚠️ 32 not_sure 741 875 +18.1% <0.0001 The +18.1% delta stays inside master's recent range, and both sides were noisy. This query does not run the Iceberg OPTIMIZE path that the PR changes.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 64 51 -20.3% <0.0001 The -20.3% result sits at the bottom of master's recent range on a noisy query. The PR only changes Iceberg OPTIMIZE, which this TPC-H scan never runs.
⚠️ 7 not_sure 78 60 -23.1% <0.0001 The -23.1% result falls inside master's recent range on a query with a noisy history. This join query does not touch the Iceberg OPTIMIZE path that the PR changes.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 9c6383da-1a59-4254-904b-f629a465ba58
  • MIRAI run: 64274437-3d0c-40a3-bd39-a3e8eac36e3a
  • PR check IDs:
    • clickbench_952145_1791762338
    • clickbench_952151_1791762338
    • clickbench_952157_1791762338
    • tpch_adapted_1_official_952168_1791762338
    • tpch_adapted_1_official_952179_1791762338
    • tpch_adapted_1_official_952215_1791762338

@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Dear @SmitaRKulkarni, 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.

groeneai and others added 2 commits October 30, 2026 10:46
…ion plan

`IcebergMetadata::optimize` resolved and read the latest metadata file for
its no-current-snapshot check, and `getPlan` resolved and read it again.
Pass the metadata object and its version down through `compactIcebergTable`
instead, so a planning-only OPTIMIZE on S3 does one `ListObjects` instead of
two, and the history, the check and the plan all come from the same file.

`getPlan` resolved the file the way destructive callers do
(`ignore_metadata_pointer_overrides`), which refuses a table whose metadata
files mix the `v<N>` and `<N>-<uuid>` naming schemes. The single read now
uses that mode on the open-source build, which is the one that rewrites the
table; the Cloud arm keeps the default lookup. Without it, OPTIMIZE on such
a table is no longer refused (measured). `getPlan` still deep-copies the
object, because the metadata cache shares it and the rewrite mutates it.

ClickHouse#121500 (comment)

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 582f159

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 (amd_debug, parallel) / Logical error: 'ReadBuffer is canceled. Can't read from it.' (STID: 2508-2bbd), Server liveness check failed, 04007_remove_unused_columns_join_header_mismatch not from this PR (it changes only Iceberg compaction): the server's embedded web terminal client read its canceled input again in DB::ask (ClientBase::initOutputFormat from ClientEmbedded::run), which aborts the debug server; the liveness row and 04007 are collateral of that abort. The same abort hit master twice and other PRs since 2026-10-28 #128090 (mine, open)
Mergeable Check, PR praktika rollups of the row above #128090 (mine, open)
CH Inc sync the private sync build failed CH Inc sync (private, not actionable by me)

Because of this failure praktika dropped 72 later jobs (14 Stateless tests, 13 builds, 7 Integration tests, 6 Stress test, 6 Performance Comparison shards, the fuzzers and others), so they have no result on this head. All five flaky check runs and the targeted stateless and integration jobs are green.

Session id: cron:our-pr-ci-monitor:20261030-133005

…-current-snapshot-guard

# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp
@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-review-human PR origin: human review feedback on a groeneai PR pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants