Skip to content

Fail Iceberg writes when the parent snapshot is missing from snapshots - #109739

Open
tiandiwonder wants to merge 11 commits into
ClickHouse:masterfrom
tiandiwonder:fix-iceberg-write-missing-parent-snapshot
Open

tiandiwonder wants to merge 11 commits into
ClickHouse:masterfrom
tiandiwonder:fix-iceberg-write-missing-parent-snapshot

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #107473 (review escalation: #107473 (comment)).

If Iceberg metadata carries a live current-snapshot-id whose entry cannot be resolved in snapshots (the array is missing, empty, or the matching entry was pruned — malformed external metadata or an over-aggressive catalog), MetadataGenerator::getParentSnapshot returned nullptr and 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.

generateNextMetadata now throws ICEBERG_SPECIFICATION_VIOLATION on an unresolvable live parent, matching the read path's handling of a missing snapshot set. Compaction opts out via the new tolerate_missing_parent_snapshot parameter: 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):

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

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

Iceberg writes now fail with an ICEBERG_SPECIFICATION_VIOLATION error instead of silently orphaning previously committed data when the metadata's current snapshot cannot be found in its snapshots list.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [36febdb]

Summary: ✅


AI Review

Summary

This PR hardens Iceberg writes and both compaction entrypoints against metadata whose live current-snapshot-id cannot be resolved in snapshots, and the write-path cleanup fix itself looks sound. The branch is still not ready as-is, though: plain OPTIMIZE TABLE still skips that validation in CLICKHOUSE_CLOUD, and several previously discussed Iceberg metadata-shape bugs remain real in the current code even though the author deliberately scoped them into follow-up work.

Missing context / blind spots
  • ⚠️ The private CLICKHOUSE_CLOUD background compactor implementation is not in this checkout. I could verify that the front-door IcebergMetadata::optimize path returns success without running the new guard, but proving whether the deferred compactor later rejects or mishandles the same metadata would require the private-side code.
Findings
⚠️ Majors
  • [tests/queries/0_stateless/04838_iceberg_optimize_full_compaction_unresolvable_current_snapshot.sh:5-10] The test split weakens the contract instead of fixing the remaining build. In CLICKHOUSE_CLOUD, IcebergMetadata::optimize returns at src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:455-465 before Compaction.cpp:getPlan runs, so plain OPTIMIZE TABLE still reports success on the same unresolvable live snapshot that OSS now rejects. Move validateParentSnapshotResolvable to a pre-dispatch point common to both OPTIMIZE implementations, or add the equivalent check before the Cloud early return.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1062-1072] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109739#discussion_r3549061033] Full compaction still rewrites append snapshots with tolerate_missing_parent_snapshot = true, so a replayed snapshot can persist a parent-snapshot-id that is absent from snapshots. IcebergMetadata::getHistory then truncates the ancestor walk at src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:973-981, which keeps system.iceberg_history.is_current_ancestor wrong and lets expire_snapshots(retain_last = N) drop surviving history earlier than requested.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp:734-736] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109739#discussion_r3764119984] Mutations still treat JSON null current-snapshot-id as a hard conversion exception. The new validation normalizes null only for the up-front helper, but the same loop immediately does has() + getValue<Int64>(), so a spec-compliant external empty table still throws before the no-current-snapshot path is reached.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:973-975] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109739#discussion_r3782718497] Plain OPTIMIZE TABLE in OSS still reads current-snapshot-id with getValue<Int64>() inside getHistory, so the spec's JSON-null encoding raises a conversion exception before the new full-compaction guard at src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:231-232 can run.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/ExpireSnapshotsExecute.cpp:711-718] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109739#discussion_r3810619807] ALTER TABLE ... EXECUTE expire_snapshots still has the same has() + getValue<Int64>() read, so the JSON-null spelling of "no current snapshot" throws an unrelated conversion exception instead of taking the existing no-op path.
Final Verdict

⚠️ Needs changes before merge. The new write-path validation is worthwhile, but OPTIMIZE TABLE still behaves differently in CLICKHOUSE_CLOUD, and the remaining dismissed Iceberg metadata-shape bugs are still present in the current code.

LLVM Coverage Report

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 8, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Jul 8, 2026
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);

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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]>
@tiandiwonder
tiandiwonder requested a review from kssenii July 9, 2026 05:08
history_record.snapshot_id,
history_record.made_current_at.value);
history_record.made_current_at.value,
/* tolerate_missing_parent_snapshot */ true);

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@kssenii kssenii self-assigned this Jul 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: 31a16c34-2c8e-4aba-924f-7fbc3f9da683
  • MIRAI run: a3703d59-96e5-4532-87a5-cf330a8a067c
  • PR check IDs:
    • clickbench_498948_1784004003
    • clickbench_498961_1784004005
    • clickbench_498968_1784004003
    • tpch_adapted_1_official_498973_1784004003
    • tpch_adapted_1_official_498979_1784004006
    • tpch_adapted_1_official_498986_1784004006

tiandiwonder and others added 4 commits July 22, 2026 03:53
`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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 112/115 (97.39%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

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);

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 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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

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 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 36febdb81 with master 3eb72756a (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
Binary Master PR Δ
programs/clickhouse-stripped 711.97 MiB 708.93 MiB -3.03 MiB (-0.43%)

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 units

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

Job report

`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(

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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)

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 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

`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

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.

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.

@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 4, 2026
tiandiwonder added a commit to tiandiwonder/ClickHouse that referenced this pull request Sep 7, 2026
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]>
@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... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants