Skip to content

Fix an error reading an Iceberg table whose current-snapshot-id is JSON null - #114465

Merged
tiandiwonder merged 6 commits into
ClickHouse:masterfrom
tiandiwonder:fix-iceberg-null-current-snapshot-id
Sep 21, 2026
Merged

tiandiwonder merged 6 commits into
ClickHouse:masterfrom
tiandiwonder:fix-iceberg-null-current-snapshot-id

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Related: #109739

Problem

The Iceberg spec lets current-snapshot-id be absent, -1, or JSON null, and all three mean the same
thing: the table has no current snapshot. External writers do emit "current-snapshot-id": null.

Reading such a table, several commands fail with an unrelated Poco conversion error instead of taking the
no-snapshot path:

  • SELECT ... FROM system.iceberg_history reports the table as broken and skips it, so its history is
    silently missing from the result:
    Ignoring broken table <db>.<t>: Poco::Exception. Code: 1000, Invalid access: Can not convert empty value.
  • ALTER TABLE ... EXECUTE expire_snapshots(...) fails.
  • DELETE / UPDATE fail.

Root cause

Poco::JSON::Object::has returns true for a key whose value is JSON null — the key is present, the value
is an empty Poco::Dynamic::Var. A reader guarded only by has therefore proceeds to
getValue<Int64>, and Var::convert<Int64> throws Poco::InvalidAccessException:

Poco::Dynamic::Var::convert<long>()
DB::IcebergMetadata::getHistory(std::shared_ptr<DB::Context const>) const
DB::StorageSystemIcebergHistory::fillData(...)

Each affected site is immediately followed by a < 0 / >= 0 test, so treating null like a negative id
is what the surrounding code already intends; it simply never handled that spelling.

Fix

Three reads now also check isNull, matching the idiom already used by their neighbours in the same
files (IcebergMetadata.cpp:581, Mutations.cpp:601, IcebergWrites.cpp:1120):

Site Reached by
IcebergMetadata::getHistory system.iceberg_history
expireSnapshots ALTER TABLE ... EXECUTE expire_snapshots(...)
mutate DELETE / UPDATE

Regression test: tests/queries/0_stateless/04846_iceberg_null_current_snapshot_id.sh, which rewrites
current-snapshot-id to JSON null and exercises all three. Verified closed-loop — with the three guards
reverted and rebuilt, the test fails with the error above; with them restored it passes. Each guard was
attributed individually rather than only as a group.

Two related reads are deliberately not changed here:

  • writeMetadataFiles (Mutations.cpp) has the same pattern, but no repro could be constructed: it runs
    only after a mutation has matched rows, and a null current-snapshot-id makes the table read as empty,
    so the two conditions are mutually exclusive. Reverting only that line leaves the new test green.
  • The two reads in Compaction.cpp are fixed by Fail Iceberg writes when the parent snapshot is missing from snapshots #109739, which also adds the manifest-compaction
    validation and null coverage there. Both pull requests target master independently; their changes are
    complementary and can merge in either order.

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

Fixed an error when reading an Iceberg table whose current-snapshot-id is JSON null, which some writers emit for a table with no current snapshot.


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

Version info

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

…ceberg

The Iceberg spec lets `current-snapshot-id` be absent, `-1`, or JSON null, and
external writers do emit null for a table with no current snapshot.
`Poco::JSON::Object::has` returns true for a null value, so a reader guarded
only by `has` before `getValue<Int64>` raises
`Poco::InvalidAccessException: Can not convert empty value` instead of taking
the no-snapshot path. Each site fixed here is immediately followed by a
`< 0` / `>= 0` test, so treating null like a negative id is what the
surrounding code already intends, and other readers in the same files
(`IcebergMetadata.cpp`, `Mutations.cpp`, `IcebergWrites.cpp`) already do it.

Affected: `IcebergMetadata::getHistory` (reached by `system.iceberg_history`),
`expireSnapshots` (`ALTER TABLE ... EXECUTE expire_snapshots`), and `mutate`
(`DELETE` / `UPDATE`).

`writeMetadataFiles` in `Mutations.cpp` has the same unguarded read and is left
alone: it runs only once a mutation has matched rows, and a null
`current-snapshot-id` makes the table read as empty, so no repro could be
constructed. Reverting only that line leaves the new test green.

The remaining reads in `Compaction.cpp` are fixed separately, by the pull
request that also adds the manifest-compaction validation there.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9d8dc73]

Summary: ✅


AI Review

Summary

This PR fixes the JSON null spelling of Iceberg's current-snapshot-id across several readers and adds focused regression coverage, but the new OPTIMIZE guard still leaves the compaction rewrite free to replay abandoned snapshots after a rollback. As written, it only skips the degenerate case where there is no current ancestor at all; it does not make the compaction plan respect the current-ancestor chain.

Findings

❌ Blockers

  • src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp:489 has_current_ancestor only proves that some current lineage exists. compactIcebergTable still receives the full retained history, and writeMetadataFiles replays every append snapshot in order while MetadataGenerator::generateNextMetadata updates current-snapshot-id / refs.main on each one. After a rollback, OPTIMIZE can therefore republish an abandoned branch and silently move the table back to the wrong snapshot. Filter compaction to is_current_ancestor snapshots (or reject histories with retained non-current snapshots), and add a regression that rolls current-snapshot-id back to an earlier snapshot after creating a stale append+position-delete branch.
Tests
  • ⚠️ Add a regression that creates a rollbacked Iceberg history with a stale append branch plus a later position-delete snapshot, then asserts OPTIMIZE TABLE leaves the rollbacked current snapshot in place instead of republishing the abandoned branch.
Final Verdict

Request changes. The JSON null handling is improved, but OPTIMIZE still does not preserve rollbacked histories because the rewrite path ignores is_current_ancestor once at least one current ancestor exists.

LLVM Coverage Report

Measured on commit 9d8dc73.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.20% +0.10%

Changed lines: Changed C/C++ lines covered: 36/38 (94.74%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9d8dc7371 with master d6eead06e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of f0310cf12; 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

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

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -3.5 s (-6%) in total before that adjustment.

Job report

`IcebergMetadata::optimize` walks the snapshot ancestry through `getHistory`, the reader
this pull request normalizes, so a spec-legal `"current-snapshot-id": null` used to make
plain `OPTIMIZE TABLE` fail with `Code: 1000 ... Invalid access: Can not convert empty
value. (POCO_EXCEPTION)` instead of taking the no-snapshot path. The existing test
covered `system.iceberg_history`, `ALTER TABLE ... EXECUTE expire_snapshots`, `DELETE`
and `SELECT`, but not this command.

It goes in its own file rather than into
`04846_iceberg_null_current_snapshot_id` because only this command is build-dependent:
`optimize` reaches `getHistory` only when `CLICKHOUSE_CLOUD` is off, and a cloud build
instead waits on `IcebergCompactionMetadataGenerator`, which the background scheduler
creates lazily. Keeping it separate lets the sibling test - whose four readers behave the
same in both builds - stay enabled everywhere.

Verified locally on this branch: with the `getHistory` guard both tests pass; with only
that guard reverted the new test fails with `232 3` against its `0 0` reference, so the
case is load-bearing.
@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 4, 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]>
tiandiwonder and others added 2 commits September 7, 2026 07:31
The review's second point was right, and the private CI proves it: this test fails on the cloud build,
and it already did before the previous commit. On `Stateless tests (amd_asan_ubsan, distributed cache,
meta in keeper, s3 storage, parallel, 1/2)` of the sync pull request the diff is

    -0 0        <- expected from plain `OPTIMIZE TABLE`
    +36 7
     0 0        <- `OPTIMIZE TABLE ... MANIFEST`, unaffected
     0

so the line that fails is the pre-existing plain-`OPTIMIZE` assertion. The file's own header already
said the command is build-dependent - `IcebergMetadata::optimize` reaches `getHistory` only when
`CLICKHOUSE_CLOUD` is off, and a cloud build gates it on `IcebergCompactionMetadataGenerator` - and
then asserted a single exit code anyway.

What this change guarantees is narrower than "`OPTIMIZE` is a quiet no-op": a JSON-null
`current-snapshot-id` must never reach `getValue<Int64>`, i.e. never produce
`Invalid access: Can not convert empty value`. State that instead, and hold only the open-source build
to the no-op, classifying the outcome the way `04513_iceberg_optimize_orc_position_delete_88123`
already does for the same command. That keeps both builds meaningful rather than skipping one.

Closed loop on the open-source build, with only the two `Compaction.cpp` guards reverted:

    OPTIMIZE: no conversion error
    FAIL: OPTIMIZE MANIFEST hit the JSON-null conversion error
    0

With them restored both tests match their references on 3 of 3 runs each. So relaxing the exit-code
assertion did not cost the test its teeth - it now names the regression instead of a number.

Co-Authored-By: Claude Opus 5 <[email protected]>
A table whose `current-snapshot-id` says "no current snapshot" reads as empty, but plain
`OPTIMIZE TABLE` brought its historical rows back. `getHistory` marks no record as a current ancestor
when there is no current snapshot; compaction never looked at 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.

Refuse the rewrite when no record is a current ancestor. Deriving the condition from `getHistory`
rather than re-reading `current-snapshot-id` keeps the three spellings of "no current snapshot"
(`null`, negative, absent) covered by one check instead of a fourth copy of the `has` / `isNull` /
negative triple. A `current-snapshot-id` that names a snapshot missing from `snapshots` reaches the
same branch - that metadata is corrupt, and refusing the rewrite is the fail-close answer for it too -
so both the log message and the comment state what was observed, that no snapshot is a current
ancestor, rather than claiming anything about `current-snapshot-id`.

Measured on this branch, `04846_iceberg_optimize_snapshotless_position_delete`:

    without the guard:  null before=0 after=3   negative before=0 after=3   absent before=0 after=3
    with the guard:     null before=0 after=0   negative before=0 after=0   absent before=0 after=0

so all three encodings resurrect without it, and the test is load-bearing for each. The counts alone
would also stay at zero if `OPTIMIZE` failed before reaching the guard, so on an open-source build the
test additionally requires `OPTIMIZE` to succeed, discriminating on the client's exit status rather
than on stderr being empty - server logs reach stderr at the harness' log level and an unrelated
warning must not read as a failure. Verified by dropping `allow_experimental_iceberg_compaction`, which
makes `OPTIMIZE` throw: all three variants then report the failure instead of a green count.

The defect predates this pull request - negative and absent are the spellings master always normalized -
but for `null` this pull request is what turns a loud `Invalid access: Can not convert empty value` into
this silent wrong result, so the guard belongs here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
if (!has_current_ancestor)
{
LOG_INFO(log, "No snapshot is a current ancestor, skipping compaction");
return 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.

has_current_ancestor only fixes the zero-ancestor case. snapshots_info still passes every retained snapshot into compactIcebergTable, and the rewrite path never filters on history_record.is_current_ancestor: writeMetadataFiles replays plan.history in order, while MetadataGenerator::generateNextMetadata resets both current-snapshot-id and refs.main on every regenerated append snapshot.

That means a valid rollback history is still wrong here. A concrete trace is s1 append, s2 append, s3 position-delete on s2 (so need_optimize becomes true), then rollback current-snapshot-id to s1. getHistory marks only s1 as a current ancestor, so this new guard passes, but compaction still regenerates s2 and finishes with s2 current again, silently undoing the rollback. The fix needs to compact only the current-ancestor chain (or reject histories that retain non-current snapshots), and it needs a regression that rewrites current-snapshot-id back to an older snapshot after creating an abandoned append+delete branch.

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.

Confirmed and reproduced, but fixed separately in #118951 rather than here: after a rollback plain OPTIMIZE does republish the abandoned branch (SELECT goes from 1,2,3 back to 1,3,4, with current-snapshot-id and refs.main moving with it), yet that needs only a rollbacked history — no null, -1 or absent current-snapshot-id — and it reproduces on master without any of this pull request's changes. 118951 refuses such a history in checkIfIcebergHistorySupported instead of filtering it, because the abandoned snapshots' data files can still be referenced by a branch or tag that compaction would then delete, and it has since grown to cover the references and the retention floor the rewrite cannot reproduce either. The guard in this pull request stays scoped to the degenerate case it is about: a table where no snapshot is a current ancestor at all, which is what a JSON-null current-snapshot-id produces.

@tiandiwonder

Copy link
Copy Markdown
Contributor Author

Confirmed and reproduced: after a rollback, plain OPTIMIZE does republish the abandoned branch (SELECT goes from 1,2,3 back to 1,3,4, and current-snapshot-id/refs.main move with it), but that defect is independent of this pull request — it needs only a rollbacked history, not a null, -1 or absent current-snapshot-id, and it reproduces on master unchanged. It is fixed separately in #118951, which refuses such a history in checkIfIcebergHistorySupported rather than filtering it, because the abandoned snapshots' data files can still be referenced from a branch or tag that compaction would then delete; the guard here covers the degenerate case where no snapshot is a current ancestor at all.

@tiandiwonder
tiandiwonder added this pull request to the merge queue Sep 21, 2026
Merged via the queue into ClickHouse:master with commit de0734d Sep 21, 2026
175 checks passed
@tiandiwonder
tiandiwonder deleted the fix-iceberg-null-current-snapshot-id branch September 21, 2026 05:30
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 21, 2026
@Algunenano

Copy link
Copy Markdown
Member

This completely wrecked the private CI. Reverting

clickhouse-gh Bot pushed a commit that referenced this pull request Sep 25, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 119274 118919 Revert "Carry the mutation version onto a rewritten lightweight `DELETE`"
Changelog-revert: 119306 119274 Revert "Revert "Carry the mutation version onto a rewritten lightweight `DELETE`""
Changelog-revert: 119334 117356 Revert "Unify the spill trigger for hash joins"
Changelog-revert: 119335 119334 Revert "Revert "Unify the spill trigger for hash joins""
Changelog-revert: 121135 118279 Revert "Test the ESCAPE route into the ngram LIKE-pattern tokenizer"
Changelog-revert: 121136 121135 Revert "Revert "Test the ESCAPE route into the ngram LIKE-pattern tokenizer""
Changelog-revert: 121258 118216 Revert "Do not invert an ordered comparison that can see a `NaN` in the CNF form"
Changelog-revert: 121298 117578 Revert "Bound the docker buildx retry ladder by wall clock, not by the timeout divisor"
Changelog-revert: 121443 114465 Revert "Fix an error reading an Iceberg table whose `current-snapshot-id` is JSON null"
Changelog-revert: 121477 121096 Revert "Trim `test_max_bytes_ratio_before_external_distinct` to fit the client timeout"
Changelog-revert: 121901 121869 Revert "docs(managed-postgres): updated Private Service Connect"
Changelog-revert: 122110 118223 Revert "Correct nightly coverage selection and share PR test manifests"
Changelog-revert: 122140 120312 Revert "Refuse a `Set` table on the right side of `IN` when a row policy applies to it"
Changelog-deleted-entry: 114465 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed an error when reading an Iceberg table whose `current-snapshot-id` is JSON null, which some writers emit for a table with no current snapshot. [#114465](#114465) ([Shaohua Wang](https://github.com/tiandiwonder)).
Changelog-deleted-entry: 118216 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed `convert_query_to_cnf = 1` silently dropping rows with a `NaN` in a floating point column: the conversion rewrote `NOT (x < c)` into `x >= c`, which is not an equivalent condition for `NaN`. [#118216](#118216) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 118223 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Correct nightly coverage selection and share PR test manifests. [#118223](#118223) ([Nikita Fomichev](https://github.com/fm4v)).
Changelog-deleted-entry: 120312 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * A row policy on a `Set`-engine table was accepted but never applied: the right side of `IN` read the prebuilt set directly and returned the rows the policy hides. Such a query now fails with `ACCESS_DENIED`, because the `Set` engine has no read path that could filter the rows. Queries that used a `Set` table covered by a database-wide row policy ran unfiltered before and now throw. [#120312](#120312) ([Harikrishnan Prabakaran](https://github.com/harikrishnan94)).
Changelog-deleted-entry: 121096 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Sized `test_max_bytes_ratio_before_external_distinct` to fit the integration harness's 600 second per-query timeout. [#121096](#121096) ([Groene AI](https://github.com/groeneai)).
@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants