Repository navigation
Conversation
…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]>
Internal second-model reviewAn independent cold read of the diff plus a second-model pass on every head, adjudicated against the
Verified independently rather than taken from the validation notes: |
|
Workflow [PR], commit [2bb61f2] Summary: ❌
AI ReviewSummaryReviewed head Findings
Missing context / blind spots
Tests
Final Verdict |
|
@alexey-milovidov you have to review this |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units31 translation units recompiled, 348 s compile time in total, 31 of them have a recent master baseline. |
CI finish ledger - 4a7b802Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
No functional, integration, sanitizer, fuzzer or build check failed on this head: a CIDB scan scoped Why #121090 is the fix for this line and not a coincidental same-area PR: it changes the Session id: cron:our-pr-ci-monitor:20260922-110203 |
| @@ -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)) | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - 6cebb86Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Gates: (a) 0 of 176 checks queued or running (132 green, 41 skipped, 3 red); (b) Session id: cron:our-pr-ci-monitor:20260923-103206 |
…-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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
Internal second-model review: adjudication log (click to expand)Review of The commit fixes the Session id: cron:clickhouse-review-slot-8:20261010-235200 |
CI finish ledger - eba566fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261011-080006 |
…-current-snapshot-guard
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (2 of 43)
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_officialFlagged queries (2 of 22)
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
|
…-current-snapshot-guard
|
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. |
…-current-snapshot-guard
…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]>
CI finish ledger - 582f159Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Because of this failure praktika dropped 72 later jobs (14 Session id: cron:our-pr-ci-monitor:20261030-133005 |
…-current-snapshot-guard # Conflicts: # src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp
Related: #121134
Related: #121460
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
OPTIMIZE TABLEon 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 thatSELECTreads as gone, and it now fails likeSELECTwhencurrent-snapshot-idnames a snapshot missing from the table metadata. Requiresallow_experimental_iceberg_compaction.Description
Asked for by @ alexey-milovidov on #121134: private
meta in keeperlanes aborted onLogical error: Background compaction is not initializedfromIcebergMetadata::optimize(job).
@ Algunenano reverted #114465 in #121443 over it.
Cause. Compaction never checks for a current snapshot:
getPlansetsneed_optimizefrom any historical position delete and republishes a chain from append history, so atable that
SELECTreads as empty gets its old rows back. @ tiandiwonder's check for that in #114465was
#else-only, so his tests still hit the#if CLICKHOUSE_CLOUDarm'sIcebergCompactionMetadataGeneratorassertion.Change. Before the
#if,optimizereadscurrent-snapshot-idfrom the latest metadata andskips compaction when it is absent,
nullor negative (ClickHouse writes-1for a new table), soneither 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
OPTIMIZElists
metadata/once. An id missing fromsnapshotsnow fails likeSELECT(
ICEBERG_SPECIFICATION_VIOLATION): compacting the rest would lose or resurrect its rows. A table thathas 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 anullcurrent-snapshot-id, so its test skipsOPTIMIZEon 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,
-1and absent returnafter=3andnullraises a Pococonversion error. Removing any one of the
< 0,isNullorsnapshots-lookup clauses fails its ownvariant. With it, 100 runs green and other Iceberg
OPTIMIZEtests unchanged.Workflow [PR]
Sync PR [sync-upstream/pr/121500]