Repository navigation
Fail Iceberg writes when the parent snapshot is missing from snapshots - #109739
tiandiwonder wants to merge 11 commits into
Conversation
A live `current-snapshot-id` whose entry is absent from `snapshots` (array missing, empty, or the entry pruned) would commit a snapshot that orphans all previously visible data and restarts the summary totals from zero. Throw `ICEBERG_SPECIFICATION_VIOLATION` on an unresolvable parent instead of only when the whole array is absent. Compaction opts out via the new `tolerate_missing_parent_snapshot` parameter: it replays a filtered history, so a record's parent may be a legitimately skipped snapshot. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [36febdb] Summary: ✅
AI ReviewSummaryThis PR hardens Iceberg writes and both compaction entrypoints against metadata whose live Missing context / blind spots
Findings
|
| Metric | Baseline | Current | Δ |
|---|---|---|---|
| Lines | 87.30% | 87.30% | +0.00% |
| Functions | 91.90% | 91.90% | +0.00% |
| Branches | 79.40% | 79.40% | +0.00% |
Changed lines: Changed C/C++ lines covered: 132/142 (92.96%) · Uncovered code
| history_record.made_current_at.value, | ||
| /// The replayed history is filtered (non-append records are skipped), so a | ||
| /// record's parent may be legitimately absent from the rebuilt `snapshots`. | ||
| /* tolerate_missing_parent_snapshot */ true); |
There was a problem hiding this comment.
tolerate_missing_parent_snapshot = true is too broad here. In a history like APPEND -> delete-only OVERWRITE -> APPEND, the second append now replays with a parent id that is absent from rebuilt snapshots, so generateNextMetadata falls back to 0 for all inherited totals. That leaves the rebuilt current snapshot with total-records / total-files-size describing only the last append, even though its manifest list still includes the older compacted data.
That is user-visible: IcebergMetadata::totalRows trusts the current snapshot summary for the trivial-count optimization, so after compaction SELECT count() can under-report rows on exactly this history shape. Please either rewire replayed appends to the last retained snapshot, or carry forward the skipped snapshot's totals into the next retained one, instead of opting out of the parent lookup entirely.
There was a problem hiding this comment.
The mechanism is real but not introduced by this PR — master's compaction replay already hits the prev_value = 0 fallback on exactly this history shape, and passing false here would make OPTIMIZE throw on such histories, which is strictly worse. Rewiring replayed appends to the last retained snapshot (or carrying totals forward) is a good follow-up to compaction replay itself; I'd track it separately from this cherry-pick.
There was a problem hiding this comment.
Verified this is pre-existing master behavior, not introduced by this PR: setSnapshotTotals's base-total fallback and the persisted parent-snapshot-id predate it, and the PR's tolerate_missing_parent_snapshot = true only preserves compaction's existing ability to replay a filtered history (the new throw never fired for compaction before). Correct catch though — the replayed dangling parent does restart totals and can mis-drive expire_snapshots/is_current_ancestor. Tracked as a follow-up to re-parent the replayed chain to the nearest retained ancestor, fix the added_files/added_files_size provenance, and then remove tolerate_missing_parent_snapshot.
There was a problem hiding this comment.
I could not reproduce the under-reported totals on this history shape: after INSERT / DELETE / INSERT / OPTIMIZE TABLE, the rebuilt head carries total-records = 4, which is the true count, and SELECT count() returns 4 both before and after compaction, with and without the trivial-count optimization. The reason the totals survive is the same defect you raise in the other thread — the parent is unresolvable, so the inheritance restarts at 0, and compaction happens to pass the cumulative row count as added_records (a manifest list enumerates all live data files, so plan.snapshot_id_to_data_files[id] is not a delta). The two errors cancel.
So the summary accounting is indeed wrong, but not in the direction of under-reporting: rewiring the parent without also making the three data totals real deltas produces total-records = 6 against 4 real rows. Both threads therefore need the same combined fix, which I am tracking separately — this pull request leaves compaction byte-identical to master, which has neither the validation nor any parent rewiring.
…ith a test Follow the code-comment convention: parameter semantics live in the /// block above generateNextMetadata rather than inside the parameter list, and the Compaction.cpp call site keeps only the /* param */ name comment. The new ToleratesUnresolvableParentWhenRequested case pins the opt-out contract: with the flag set an unresolvable live parent still commits, with the summary totals restarting from the appended deltas. Co-Authored-By: Claude Fable 5 <[email protected]>
| history_record.snapshot_id, | ||
| history_record.made_current_at.value); | ||
| history_record.made_current_at.value, | ||
| /* tolerate_missing_parent_snapshot */ true); |
There was a problem hiding this comment.
Persisting a parent-snapshot-id that is absent from snapshots breaks more than the summary totals. expire_snapshots follows parent-snapshot-id in SnapshotGraph::walkBranchAncestors (ExpireSnapshotsExecute.cpp:240-255), so after a replayed history like APPEND -> delete-only OVERWRITE -> APPEND, retain_last = 2 can keep only the head and expire the surviving older append snapshot immediately. IcebergMetadata::getHistory truncates the same way at IcebergMetadata.cpp:892-897, so system.iceberg_history.is_current_ancestor becomes wrong too.
Please rewire replayed appends to the last retained snapshot instead of preserving a missing parent id. The current opt-out leaves the rebuilt metadata internally inconsistent even when the manifest list itself is correct.
There was a problem hiding this comment.
These downstream effects on expire_snapshots and system.iceberg_history are real, but they stem from the dangling parent-snapshot-id that compaction replay already persists on master today — this PR preserves that status quo for compaction and makes every other write path fail-close, so it strictly shrinks the exposure. Rewiring replayed appends to the last retained snapshot is the right fix for the replay itself; I'd track it as a follow-up together with the totals issue from the earlier thread.
There was a problem hiding this comment.
Verified this is pre-existing master behavior, not introduced by this PR: setSnapshotTotals's base-total fallback and the persisted parent-snapshot-id predate it, and the PR's tolerate_missing_parent_snapshot = true only preserves compaction's existing ability to replay a filtered history (the new throw never fired for compaction before). Correct catch though — the replayed dangling parent does restart totals and can mis-drive expire_snapshots/is_current_ancestor. Tracked as a follow-up to re-parent the replayed chain to the nearest retained ancestor, fix the added_files/added_files_size provenance, and then remove tolerate_missing_parent_snapshot.
There was a problem hiding this comment.
You are right that the dangling parent-snapshot-id is real, and I reproduced both symptoms it causes (INSERT / DELETE / INSERT / OPTIMIZE TABLE): the surviving append comes back with is_current_ancestor = 0, and expire_snapshots(retain_last = N) expires its manifest list. But this is pre-existing and unchanged by this pull request — master passes the same history_record.parent_id in writeMetadataFiles and has no validateParentSnapshotResolvable at all, so the opt-out reproduces master byte for byte rather than introducing anything.
Rewiring replayed appends to the last retained snapshot is not sufficient on its own: I tried it, and total-records went from 4 to 6 with the server logging claims 6 total rows, but its manifest files describe 4 rows. The reason is that a manifest list enumerates all live data files, so plan.snapshot_id_to_data_files[id] is cumulative, and compaction passes that cumulative count as added_records while setSnapshotTotals adds it to the parent total — the broken chain was zeroing the inheritance and cancelling that error out. A correct fix has to rewire the chain and turn all three data totals into real deltas, which is a rework of compaction's summary accounting. Tracking it separately so this pull request stays on the write-path validation.
|
📊 Cloud Performance Report ✅ AI verdict: This sync PR changes only Iceberg data-lake metadata generation and compaction (adding a tolerate_missing_parent_snapshot fail-close path); it does not touch the server's query-execution hot path. The two flagged ClickBench queries (Q4 -11.0%, Q15 -10.2%) both landed as no_change within master's current variance band, which is the right call since neither query exercises Iceberg code and the deltas are consistent with normal run-to-run noise. No genuine performance impact expected from this change. clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
`generateNextMetadata` already fails a commit whose live parent snapshot is absent from `snapshots`, but it does so only at commit time — after the write has already uploaded its data (and delete) files. On that failure path the callers have not yet armed their object-cleanup lambdas (`IcebergWrites.cpp` `initializeMetadata`, `Mutations.cpp` `writeMetadataFiles`), so the exception unwinds past them and the uploaded objects are orphaned. Extract the invariant into `MetadataGenerator::validateParentSnapshotResolvable` and call it up front in both write paths — the `IcebergStorageSink` constructor and the mutation loop, right after the metadata is loaded and before any data is written — so a self-contradictory table fails fast without leaving objects behind. `generateNextMetadata` keeps the same check (now via the helper) as the authoritative commit-time guard and for the retry path that re-reads metadata. Also harden the pruned-parent regression test: set `current-snapshot-id` to a fixed id absent from `snapshots` and pass the same id (instead of `first_snapshot_id + 1`, which can signed-overflow), so the metadata is genuinely self-contradictory and matches the real caller contract; add a direct test for the new helper. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… a snapshot The constructor validates the initial metadata before any data is written, but the metadata-conflict retry in initializeMetadata reloads `metadata` (cleanup path) and loops back to generateNextMetadata without re-validating. If the reloaded table has a current-snapshot-id missing from `snapshots`, the throw fires before the cleanup lambda is armed, orphaning the data files already finalized during consume(). Re-validate at the top of initializeMetadata (so every attempt, including a reloaded one, is covered) and clear the finalized data files if it fails, before rethrowing. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…issing-parent-snapshot
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 112/115 (97.39%) · Uncovered code |
|
Dear @kssenii, 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. |
…t unresolvable current snapshots in manifest compaction
Conflicts in `MetadataGenerator.{h,cpp}`: master added a trailing default
parameter `SnapshotOperation operation`, this branch added
`tolerate_missing_parent_snapshot`. Both are kept, master's first, and
master's `operation_name` selection for the snapshot summary is preserved.
Two call sites passed the flag positionally and had to be updated:
`Compaction.cpp` in `writeMetadataFiles`, and the `appendSnapshot` helper
in `gtest_iceberg_metadata_generator.cpp` — the latter merged cleanly as
text but did not compile.
`OPTIMIZE TABLE ... MANIFEST` silently reported success on metadata whose
live `current-snapshot-id` is absent from `snapshots`, the same
self-contradictory state inserts and mutations already reject.
`isCurrentManifestListAboveThreshold` and `writeConsolidatedManifestFile`
both read that as "no current snapshot" and return early, so validate once
in `compactIcebergManifests` on the freshly-fetched metadata, ahead of both.
`current-snapshot-id` has three spellings for "none": absent, JSON null,
and negative. `Poco::JSON::Object::has` is true for a null value and
`getValue<Int64>` then throws a conversion error, so route all three reads
in `Compaction.cpp` through `getCurrentSnapshotIdOrNegative`.
Add `04838_iceberg_optimize_manifest_unresolvable_current_snapshot`,
covering both the pruned-snapshot case and the JSON-null case. Verified
load-bearing: rebuilt without the validation and the test fails.
Co-Authored-By: Claude Opus 5 <[email protected]>
| Int64 current_snapshot_id = -1; | ||
| if (metadata->has(Iceberg::f_current_snapshot_id) && !metadata->isNull(Iceberg::f_current_snapshot_id)) | ||
| current_snapshot_id = metadata->getValue<Int64>(Iceberg::f_current_snapshot_id); | ||
| MetadataGenerator::validateParentSnapshotResolvable(metadata, current_snapshot_id); |
There was a problem hiding this comment.
This normalizes current-snapshot-id = null only for the new helper. The same mutate() iteration still does if (metadata->has(f_current_snapshot_id)) metadata->getValue<Int64>(...) at src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp:734-738, so an external empty table that uses the spec's JSON null encoding still fails with a conversion exception before we even discover that there is no snapshot to mutate.
Since the read path and the new compaction code already treat null as "no current snapshot", mutations need the same normalization when populating current_iceberg_snapshot (and any later reads of f_current_snapshot_id in this loop).
There was a problem hiding this comment.
Fixed separately in #114465, which adds the isNull check to exactly this current_iceberg_snapshot population, plus the two other same-class sites in IcebergMetadata.cpp and ExpireSnapshotsExecute.cpp.
There was a problem hiding this comment.
This is still present in the current PR. src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp:734-736 still reads current-snapshot-id with getValue<Int64>(...) whenever the key exists, without an isNull guard, so \"current-snapshot-id\": null still raises the same conversion exception before the mutation path discovers that there is no current snapshot.
There was a problem hiding this comment.
Correct, it is still present here — the fix for this exact read is in #114465 (the Mutations.cpp hunk at line 721, alongside IcebergMetadata.cpp and ExpireSnapshotsExecute.cpp), which is open and not yet merged. This pull request deliberately stays on the write-path validation, so the read-side null encoding is out of scope here.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units10 translation units recompiled, 52 s compile time in total, 10 of them have a recent master baseline. |
`getHistory` drops a live `current-snapshot-id` that is absent from `snapshots` without complaining, so full `OPTIMIZE TABLE` planned the rewrite from a partial history. `compactIcebergTable` lists every object under `metadata/` and `data/` before rewriting and deletes all of them afterwards through `clearOldFiles`, so the files only the missing head still referenced were lost and the statement reported success. Validate the head in `getPlan`, next to the existing `format_version` pre-check. That is the object the rewrite is based on, and it runs before the listing, so the check covers the metadata actually used rather than a separate load. The `OPTIMIZE ... MANIFEST` path already rejects the same metadata. The check cannot live in `getHistory` itself: `system.iceberg_history` reads through it and must stay non-throwing. Also fix the test's two `ATTACH TABLE` invocations: `shell_config.sh` bakes `--send_logs_level=warning` into `CLICKHOUSE_CLIENT`, so a bare `--send_logs_level=fatal` makes the client refuse to start with `option '--send_logs_level' cannot be specified more than once`. Pass `--allow_repeated_settings`, as `01600_quota_by_prefix_forwarded_ip.sh` does. Co-Authored-By: Claude Opus 5 <[email protected]>
| /// The rewrite is based on this object, so validate it here rather than at the caller: a live | ||
| /// `current-snapshot-id` missing from `snapshots` yields a partial history, and `clearOldFiles` | ||
| /// then deletes every listed object - losing the files only that head still referenced. | ||
| MetadataGenerator::validateParentSnapshotResolvable( |
There was a problem hiding this comment.
validateParentSnapshotResolvable here only runs after IcebergMetadata::optimize has already built snapshots_info via getHistory. That helper still does if (metadata_object->has(f_current_snapshot_id)) metadata_object->getValue<Int64>(...) at src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:943-945, so a spec-compliant external table with "current-snapshot-id": null still makes plain OPTIMIZE TABLE fail with a conversion exception before this guard is reached.
The new stateless test covers only OPTIMIZE TABLE ... MANIFEST. Please normalize absent / null / negative current-snapshot-id before getHistory walks ancestors (or bypass getHistory for the no-snapshot case), and add plain OPTIMIZE TABLE coverage for the JSON-null metadata shape.
There was a problem hiding this comment.
The normalization you ask for is in #114465, which guards the getHistory read at IcebergMetadata.cpp:939; that pull request is open and not yet merged. The plain OPTIMIZE TABLE coverage for the JSON-null shape is genuinely still missing in both pull requests — its natural home is the new 04838_iceberg_optimize_full_compaction_unresolvable_current_snapshot, because that command only reaches getHistory and getPlan in the open-source build.
There was a problem hiding this comment.
Correcting my previous reply on where that coverage belongs: it cannot live in this pull request. I reproduced it on this branch — a JSON-null current-snapshot-id makes plain OPTIMIZE TABLE fail with Code: 1000 ... Invalid access: Can not convert empty value. (POCO_EXCEPTION), from exactly the unguarded getHistory read you point at. The case therefore has to ship with the normalization in #114465, alongside its 04846_iceberg_null_current_snapshot_id, rather than here where it would simply fail.
| /// Cheap pre-check for `compactIcebergManifests`: read just the current manifest list and report whether its entry count exceeds `threshold`. | ||
| /// A table with no current snapshot spells it three ways: the key absent, the key present but JSON null, | ||
| /// or a negative id. `getValue<Int64>` throws on a null Var, so normalize all three to -1 in one place. | ||
| static Int64 getCurrentSnapshotIdOrNegative(const Poco::JSON::Object::Ptr & metadata_object) |
There was a problem hiding this comment.
This helper makes JSON null a first-class "no current snapshot" encoding for compaction, but the sibling expire_snapshots path still does if (!has) ...; getValue<Int64>(...) at src/Storages/ObjectStorage/DataLakes/Iceberg/ExpireSnapshotsExecute.cpp:711-718. A spec-compliant external table that spells "no current snapshot" as \"current-snapshot-id\": null will still make ALTER TABLE ... EXPIRE SNAPSHOTS throw a conversion exception instead of taking the existing no-op path.
Please route that reader through the same absent / null / negative normalization, ideally via a shared helper rather than a compaction-local one.
There was a problem hiding this comment.
ExpireSnapshotsExecute.cpp is the third site normalized by #114465 (hunk at line 708), whose test 04846_iceberg_null_current_snapshot_id exercises ALTER TABLE ... EXECUTE expire_snapshots on the JSON-null shape. That pull request is open and not yet merged, so this reader stays out of scope here.
…issing-parent-snapshot
`04838_iceberg_optimize_manifest_unresolvable_current_snapshot` asserted that both `OPTIMIZE TABLE ... MANIFEST` and a plain `OPTIMIZE TABLE` reject metadata whose `current-snapshot-id` is live but absent from `snapshots`. Only the first of the two holds in every build. In a `CLICKHOUSE_CLOUD` build `IcebergMetadata::optimize` does not call `compactIcebergTable`: it waits on a cloud-only background compactor and returns. So it never reaches `getPlan`, where `MetadataGenerator::validateParentSnapshotResolvable` is called, and the plain `OPTIMIZE TABLE` completes without raising `ICEBERG_SPECIFICATION_VIOLATION`. `optimizeManifestFiles` has no such branch - it always calls `compactIcebergManifests` - so the manifest assertion is build-independent. Move the full-compaction assertion into `04838_iceberg_optimize_full_compaction_unresolvable_current_snapshot`, so the build-independent assertions keep running everywhere and only the one that needs the open-source code path is listed in `tests/queries-no-private-tests.txt` downstream. This mirrors how the masking-policy tests are handled: seven of them run in both builds and only `04489_masking_policies_introspection`, whose expectations are open-source-only, is skipped in the private build. Verified locally against a build of this branch and against a control binary without the fix (`56624e8f745`, confirmed by content to lack the guard's message): both tests pass with the fix and both fail without it, each missing exactly its own `ICEBERG_SPECIFICATION_VIOLATION` line.
| # Tags: no-fasttest | ||
| # - no-fasttest: requires `IcebergLocal` (USE_AVRO build option) | ||
| # | ||
| # Split out of `04838_iceberg_optimize_manifest_unresolvable_current_snapshot` because this |
There was a problem hiding this comment.
OPTIMIZE TABLE is still inconsistent across builds here. In CLICKHOUSE_CLOUD, IcebergMetadata::optimize returns at src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:455-465 after waitUntilUpdated() and never reaches getPlan(), so the new validateParentSnapshotResolvable() guard is skipped entirely for plain full compaction.
Splitting the test to stop asserting this in private builds just hides the gap: the same malformed metadata that OSS now rejects still reports success from OPTIMIZE TABLE in Cloud. Please move the validation to a point common to both OPTIMIZE implementations, or add the equivalent check before the Cloud early return.
The review thread was right and my earlier reply was not: pointing at ClickHouse#109739 does not make this branch correct against `master`, because ClickHouse#109739 is still open. On this branch `OPTIMIZE TABLE ... MANIFEST` over the very metadata this pull request's test writes still throws `Poco::InvalidAccessException` - `Poco::JSON::Object::has` is true for a JSON null and `getValue<Int64>` cannot convert one. A census of every `f_current_snapshot_id` read site found three unguarded, not the two the thread named: - `Compaction.cpp:158` `isCurrentManifestListAboveThreshold` - `Compaction.cpp:437` `writeConsolidatedManifestFile` - `Mutations.cpp:381` `writeMetadataFiles` - not named in the thread The other five (`IcebergMetadata.cpp:581` / `:974`, `Mutations.cpp:601` / `:724`, `ExpireSnapshotsExecute.cpp:712`, `IcebergWrites.cpp:1120`) already normalize null. Leaving three behind made this change inconsistent with itself, since it swept the same pattern elsewhere. Each site gets the `isNull` check next to its existing `has` check, the idiom this pull request already uses. No shared helper is introduced, so the overlap with ClickHouse#109739 stays at three lines. Closed loop, same machine and branch. Reverting only these three guards and rebuilding: OPTIMIZE TABLE t -> rc=0, quiet no-op (covered by the guards already on this branch) OPTIMIZE TABLE t MANIFEST -> Code: 1000. Invalid access: Can not convert empty value. (POCO_EXCEPTION) and the test reads `0 0` / `232 3` / `0`. With the guards restored it reads `0 0` / `0 0` / `0`, matching the reference on 3 of 3 runs. So the new `MANIFEST` assertion is load-bearing. Co-Authored-By: Claude Opus 5 <[email protected]>
Follow-up to #107473 (review escalation: #107473 (comment)).
If Iceberg metadata carries a live
current-snapshot-idwhose entry cannot be resolved insnapshots(the array is missing, empty, or the matching entry was pruned — malformed external metadata or an over-aggressive catalog),MetadataGenerator::getParentSnapshotreturnednullptrand the write still committed: the summary totals restarted from zero and the manifest-list copy loop found no parent, so the new snapshot silently orphaned all previously visible data.generateNextMetadatanow throwsICEBERG_SPECIFICATION_VIOLATIONon an unresolvable live parent, matching the read path's handling of a missing snapshot set. Compaction opts out via the newtolerate_missing_parent_snapshotparameter: it replays a filtered history onto rebuilt metadata (non-append records are skipped), so a record's parent may be legitimately absent there.Covered by
gtest_iceberg_metadata_generator(suite extended to 9 cases: positive parent-chain append, empty-array, and pruned-entry rejections).Related: #107473
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Iceberg writes now fail with an
ICEBERG_SPECIFICATION_VIOLATIONerror instead of silently orphaning previously committed data when the metadata's current snapshot cannot be found in itssnapshotslist.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/109739]