Skip to content

Fix exception when Iceberg format version is upgraded by external tool - #100407

Merged
alexey-milovidov merged 72 commits into
masterfrom
fix-iceberg-format-version-upgrade
Jun 13, 2026
Merged

alexey-milovidov merged 72 commits into
masterfrom
fix-iceberg-format-version-upgrade

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 23, 2026 •

Copy link
Copy Markdown
Member

When external tools like Spark upgrade the Iceberg format version (e.g. from v1 to v2), the format_version cached in PersistentTableComponents becomes stale. The previous chassert in getState and getHistory then triggered a logical error because the cached value no longer matched the metadata file.

Instead of mutating shared cached state from const methods (which would introduce a cross-query data race), this PR derives the parsing format version from each manifest list / manifest file's own Avro format-version metadata. A v2 table can therefore still reference v1 manifests left behind by an external upgrade, and each one is parsed correctly.

For backward compatibility with older ClickHouse releases that wrote manifests without the format-version Avro key, falls back to schema-based detection: the sequence_number field appears at the top level of v2 manifest lists / manifest entries, but is absent from their v1 counterparts. New manifests written by ClickHouse now also include the format-version Avro metadata key.

The cached format_version in PersistentTableComponents remains const (per-table value observed when the table was opened) and is no longer compared against the latest metadata file.

Fixes #86776

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

Fix logical error exception when reading Iceberg tables whose format version was upgraded by an external tool (e.g. Spark).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Changes Iceberg manifest list/file parsing and remove_orphan_files gating to stop relying on cached table format_version, which could affect compatibility across v1/v2 manifests if the new per-file detection is wrong.

Overview
Fixes failures when an Iceberg table’s format-version is upgraded externally (e.g. Spark v1→v2) by stopping reliance on the cached PersistentTableComponents::format_version for parsing and instead deriving the version from each manifest list / manifest file’s Avro metadata.

AvroForIcebergDeserializer::getFormatVersionFromManifestFileMetadata() now falls back to schema-based detection (presence of top-level sequence_number) when the format-version Avro key is missing, and writers now emit format-version metadata for new manifest lists/files. Assertions that the cached version matches the latest metadata are removed, ManifestFileIterator::create no longer takes a table-wide version, and EXECUTE remove_orphan_files re-reads the latest metadata to enforce its v2-only requirement.

Adds an integration test covering external upgrades, concurrent reads during upgrade, and the no-format-version fallback behavior.

Reviewed by Cursor Bugbot for commit 12aee57. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.741 (included in 26.6 and later)
  • Backported to: 26.5.6.96, 26.3.17.98, 25.8.29.45

When external tools like Spark upgrade the Iceberg format version (e.g.
from v1 to v2), the `format_version` cached in `PersistentTableComponents`
becomes stale. The `chassert` in `getState` and `getHistory` would then
trigger a logical error because the cached value no longer matches the
metadata file.

Replace the assertions with updates to the cached `format_version`, so
that downstream code (manifest parsing, etc.) always uses the correct
version. The field is changed from `const` to `mutable` to allow
updating it from const methods.

Fixes: #86776

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ad565d4]

Summary: ✅


AI Review

Summary

This PR fixes Iceberg reads after external format-version upgrades by keeping PersistentTableComponents::format_version immutable and deriving manifest-list / manifest-file parser mode from each Avro file, with a schema-based fallback for older ClickHouse-written manifests. I did not find remaining correctness or safety findings in the current diff; the earlier bot findings on shared mutable state, missing concurrency/fallback coverage, and stale remove_orphan_files gating are addressed in the current code.

Missing context / blind spots
  • ⚠️ The latest head ad565d4551f73d136cfb2e5ae361e1bad4ec8109 still had CI in progress when checked; the direct Praktika aggregate report had no completed test rows yet. Final CI completion would close this gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Mar 23, 2026
@alexey-milovidov alexey-milovidov added pr-bugfix Pull request with bugfix, not backported by default and removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Mar 23, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The field is changed from const to mutable to allow updating it from const methods.

Thread safety?

alexey-milovidov and others added 5 commits March 24, 2026 00:30
… `std::atomic`

The `format_version` field can be updated when external tools upgrade
the Iceberg format version, but can also be read concurrently from
multiple queries. Using `mutable Int32` without synchronization is a
data race (undefined behavior). Replace with `std::atomic<Int32>`.

Since `std::atomic` is neither copyable nor movable, add explicit
constructors for `PersistentTableComponents`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…version-upgrade

# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp
#	src/Storages/ObjectStorage/DataLakes/Iceberg/PersistentTableComponents.h
Adds an integration test that verifies ClickHouse can read an Iceberg
table after its `format-version` has been upgraded from v1 to v2 by an
external tool (simulated by directly modifying the metadata JSON).
This is a regression test for #86776

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The flaky check failure is fixed in #102148, let's update the branch.

alexey-milovidov and others added 8 commits April 9, 2026 20:49
When an external tool (e.g. Spark) upgrades the Iceberg format version
from v1 to v2, existing manifest files are left in v1 format (per the
Iceberg specification, their entries are interpreted as having
`sequence_number = 0`).  `ManifestFileIterator::create` was checking the
table's cached `format_version`, so it rejected these legacy manifests
with an `ICEBERG_SPECIFICATION_VIOLATION` exception claiming that the
required `sequence_number` column was missing.

Use the manifest file's own Avro metadata to determine how to parse it,
matching what `AvroForIcebergDeserializer::createParsedManifestFileEntry`
already does for entry-level decoding.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100407&sha=1299abf41df6d00d2744ca5a67931bf136c0aa15&name_0=PR

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address review feedback: `PersistentTableComponents` is shared across
concurrent queries, so mutating `format_version` (even via `std::atomic`)
introduced a cross-query correctness hazard — query A could observe the
`format-version` written by query B while still parsing A's own metadata
structures.

Revert the field to `const Int32` and drop the assignments in `getState`
and `getHistory`. Parsing now relies on the format version recorded in
each manifest list / manifest file's own Avro metadata, which
`getFormatVersionFromManifestFileMetadata` already returns: the previous
commit already wired this into `ManifestFileIterator::create`, and this
commit extends the same approach to `getManifestList` so that a v1
manifest list left over after a Spark v1 -> v2 upgrade is not read with
v2 rules.
The previous commits moved away from mutating the cached `format_version`
in `PersistentTableComponents` toward reading the format version from each
manifest list / manifest file's own Avro metadata. Update the test's
docstring accordingly so the intent matches the current implementation.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master into the branch again (clean, zero conflicts — commit ad565d4, the branch was ~107 commits behind). The net PR diff is unchanged (11 files, +382/−26), and all four affected Iceberg translation units (IcebergMetadata.cpp, IcebergWrites.cpp, AvroForIcebergDeserializer.cpp, RemoveOrphanFilesExecute.cpp) compile clean against the merged tree, including the two files master had touched in the meantime.

The sole red in the last run, Stateless tests (arm_asan_ubsan, azure, parallel) (6 failed tests), was a runner-wide memory exhaustion event, not related to this PR: at 01:54:24 the runner hit the total-memory ceiling (memory limit exceeded: would use 3.37 GiB ... current RSS: 53.72 GiB, maximum: 53.69 GiB on a trivial SELECT map('a', 1, 'b', 2) FROM remote('127.0.0.{1,2}') in 01787_map_remote), and the other five tests failed simultaneously with Connection reset by peer. All six passed on rerun (0/3 rerun failures), and none of them touch Iceberg code. CIDB shows this exact failure class spiked across the fleet on the same day: 544 failures in 82 PRs on 2026-06-10 and 367 in 29 PRs on 2026-06-09, versus single digits before.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100407&sha=334b728170416b5b0ce4ba250bfc2a09b149d2ac&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29 — the runner-wide total-memory exhaustion on stateless ASan runners (spiking 2026-06-09/10 across dozens of PRs) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Confirmed, and the root-cause fix is already merged.

Cited run (SHA 334b7281, Stateless tests (arm_asan_ubsan, azure, parallel)) - all 6 failures are graceful, no crash:

  • 01787_map_remote: Code 241, (total) memory limit exceeded ... current RSS: 53.72 GiB, maximum: 53.69 GiB on a trivial remote('127.0.0.{1,2}') query.
  • The other 5 (02317_distinct_in_order_optimization_explain, 02943_alter_user_modify_profiles_and_settings, 03315_query_log_privileges_backup_restore, 03815_debug_assertion_column_sizes_race, 04070_arrow_complex_types): Code 210 Connection reset by peer - the runner dropping connections at the RSS ceiling.
  • Crash-signature scan over all 6 test_context_raw: 0 SIGSEGV / 0 use-after-free / 0 allocator CHECK / 0 LOGICAL_ERROR. Genuine OOM + network cascade, not a masked crash. Unrelated to this PR's Iceberg manifest parsing.

CIDB corroborates the runner-wide spike on arm_asan_ubsan, azure, parallel (failure rows / distinct PRs per day): single digits through 06-07, then 634 / 40 PRs on 06-09 and 972 / 94 PRs on 06-10, back to 8 / 1 PR today (06-12).

Root-cause fix already merged: #106962 (Raul Marin, "ci: tag 01603_read_with_backoff_bug as no-asan to prevent cascading OOM", merged 06-11 16:38 UTC). 01603_read_with_backoff_bug was the heavy consumer driving the cascade on this lane (9 fails 06-09, 12 fails 06-10); it is now SKIPPED on the asan azure lane (76x on 06-11) and the lane's failure volume dropped 972 -> 170 -> 8. The directive's "if the fix is already in progress, link it here" is satisfied by #106962, so no separate PR is needed from my side.

This is the same azure runner-OOM family I analyzed earlier on #106187 and #101843.

@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 55/96 (57.29%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 4e6d7ec into master Jun 13, 2026
165 of 166 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-iceberg-format-version-upgrade branch June 13, 2026 12:41
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 13, 2026
@scanhex12 scanhex12 added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jul 31, 2026
@scanhex12

Copy link
Copy Markdown
Member

alexey-milovidov added a commit that referenced this pull request Jul 31, 2026
Backport #100407 to 26.5: Fix exception when Iceberg format version is upgraded by external tool
alexey-milovidov added a commit that referenced this pull request Aug 1, 2026
Resolve the cherry-pick conflicts of #100407 against 26.3.

* `ManifestFileIterator::create` has a different signature in 26.3 (it
  takes `manifest_file_name` / `common_path` instead of the master-only
  `IcebergPathFromMetadata` / `IcebergPathResolver`). The `format_version`
  parameter is dropped and the version is derived from the manifest file's
  own Avro metadata, as in the original pull request; call sites in
  `IcebergIterator.cpp` and `StatelessMetadataFileGetter.cpp` are updated
  accordingly.
* `RemoveOrphanFilesExecute.cpp` does not exist in 26.3 - the
  `remove_orphan_files` command was introduced later - so its change and
  the `test_remove_orphan_files_after_external_upgrade` integration test
  are dropped from the backport.

Original pull-request: #100407
alexey-milovidov added a commit that referenced this pull request Aug 1, 2026
Resolve the cherry-pick conflicts of #100407 ("Fix exception when Iceberg
format version is upgraded by external tool") against the 25.8 Iceberg code,
which predates the `Common/AvroForIcebergDeserializer` move, the
`ManifestFileIterator` split and the `remove_orphan_files` command.

Adaptations to 25.8:

- `AvroForIcebergDeserializer` lives under `DataLakes/Iceberg` and has no
  `getFormatVersionFromManifestFileMetadata` yet, so the whole method is added
  (metadata key first, schema-based fallback on `sequence_number` second).
- The manifest-file parser is `ManifestFileContent`, not `ManifestFileIterator`.
  Its `format_version_` constructor parameter is dropped and replaced by the
  manifest file's own version, taken from its Avro metadata.
- `IcebergMetadata::update` carries the `chassert` that master has in
  `IcebergMetadata::getState`; both it and the one in
  `IcebergMetadata::getHistory` are removed.
- `IcebergIterator` still gates the manifest-list content type check on the
  cached `persistent_components.format_version`. The gate is removed, matching
  master: v1 manifest list entries are always `DATA`, so the comparison alone is
  correct and no longer depends on a value that goes stale after an external
  upgrade.
- `remove_orphan_files` does not exist in 25.8, so that part of the change and
  its test are omitted.
- The new integration tests are appended to
  `tests/integration/test_storage_iceberg/test.py` (25.8 has no
  `test_storage_iceberg_with_spark` package and no shared `conftest.py`), use
  the `started_cluster` fixture and the `allow_experimental_insert_into_iceberg`
  setting, which is how 25.8 spells `allow_insert_into_iceberg`.

Original pull request: #100407
robot-clickhouse-ci-2 added a commit that referenced this pull request Aug 1, 2026
Cherry pick #100407 to 25.8: Fix exception when Iceberg format version is upgraded by external tool
robot-clickhouse added a commit that referenced this pull request Aug 1, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Aug 1, 2026
Cherry pick #100407 to 26.3: Fix exception when Iceberg format version is upgraded by external tool
robot-clickhouse added a commit that referenced this pull request Aug 1, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 1, 2026
alexey-milovidov added a commit that referenced this pull request Aug 1, 2026
Backport #100407 to 26.3: Fix exception when Iceberg format version is upgraded by external tool
scanhex12 added a commit that referenced this pull request Aug 3, 2026
Backport #100407 to 25.8: Fix exception when Iceberg format version is upgraded by external tool
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
@subkanthi subkanthi mentioned this pull request Sep 16, 2026
11 of 17 tasks
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 22, 2026
…story

`PersistentTableComponents::format_version` is captured when the table is
opened and is documented as allowed to go stale after an external upgrade.
`getHistory` re-reads the latest metadata file and asserted that its
`format-version` still equals the cached value, so a debug or sanitizer
server aborted when another engine upgraded an attached table and then
`system.iceberg_history` or `OPTIMIZE` (which calls `getHistory`) ran.
Seen in Stress test (amd_msan) on PR ClickHouse#125542 (STID 2508-400e), where the
AST fuzzer turned a `system.iceberg_history` query into an unfiltered scan
that reached the table 05394 had just upgraded to format version 3.

ClickHouse#100407 removed this comparison from both `getState` and `getHistory`; the
ClickHouse#108080 sync brought both back and 6520200 removed only the
`getState` one. `getHistory` computes everything from the freshly read
metadata, and release builds compile `chassert` out, so there is no
release-build behavior change.

Extend the ClickHouse#86776 regression case to compare `system.iceberg_history`
before and after the v1 -> v2 upgrade; it aborts node1 on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! 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.

Logical error: 'persistent_components.format_version == metadata_object->getValue<int>(f_format_version)''

5 participants