Skip to content

Fix Iceberg OPTIMIZE deleting version-hint - #122833

Merged
arsenmuk merged 6 commits into
masterfrom
arsenmuk/optmize-deletes-version-hint
Oct 9, 2026
Merged

arsenmuk merged 6 commits into
masterfrom
arsenmuk/optmize-deletes-version-hint

Conversation

@arsenmuk

@arsenmuk arsenmuk commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

Problem

OPTIMIZE TABLE on OSS Iceberg tables could delete metadata/version-hint.text, leaving hint-based readers unable to open the table.

Changes

Advance compaction metadata output to the next metadata version instead of rewriting v0.metadata.json.

Publish compacted metadata via the existing metadata-and-version-hint helper so version-hint.text stays in sync.

Restrict old metadata cleanup to .metadata.json files so version-hint.text is not treated as obsolete metadata.

Add a stateless regression test covering OPTIMIZE TABLE on an Iceberg table with iceberg_use_version_hint = 1.

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 OPTIMIZE TABLE for OSS Iceberg tables so compaction no longer removes version-hint.text and breaks hint-based reads.

Closes: #120164


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

Version info

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

@arsenmuk arsenmuk changed the title Fix OPTIMIZE <iceberg> deleting version-hint Fix OPTIMIZE on Iceberg table deleting version-hint Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [18bd573]

Summary: ✅


AI Review

Summary

This PR fixes the happy path for OSS Iceberg OPTIMIZE: it now chooses the next metadata version from the latest listed metadata, keeps metadata/version-hint.text out of stale-file cleanup, and adds a regression test that checks the hint survives and advances. I do not think the commit path is merge-ready yet, though, because two failure modes still violate the promised contract: full compaction can report success after the compacted snapshot was not fully published, and retryable metadata-write failures are still surfaced as a bogus version-conflict.

Findings
  • ❌ Blockers
    • [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1522] OPTIMIZE still returns success when tryWriteVersionHintFile(..., assert_version_exactly = true) fails. By this point the rewritten data files, manifests, and vN.metadata.json already exist, but version-hint.text still names the old snapshot. That leaves listing-based readers able to pick up the compacted metadata while hint-based readers stay on the old state, so the same table can diverge immediately after a reported-success compaction. Suggested fix: treat a false return here as an uncommitted compaction—either clean up the just-written snapshot tree and throw/retry, or keep retrying until the hint is confirmed before returning success.
  • ⚠️ Majors
    • [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1362] writeMetadataFile returns false both for a genuine compare-and-swap loss and for retryable storage/write failures, but this branch maps every false to FILE_ALREADY_EXISTS. A transient object-storage failure during the metadata write will therefore be reported to the user as a bogus version conflict, which hides the real incident and prevents the caller from applying the right retry/cleanup policy. Suggested fix: return a richer commit result (committed / conflict / write_not_confirmed) or let non-conflict failures propagate and only translate a proven metadata-path race into FILE_ALREADY_EXISTS.
Tests
  • ⚠️ Add one focused failure-path regression for full compaction where the metadata file is created but hint confirmation fails, and assert that OPTIMIZE does not return success or leave readers split between listing-based and hint-based state.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Make full compaction fail or retry when hint confirmation is not exact instead of logging success.
    • Preserve the distinction between a real metadata-path conflict and an unconfirmed metadata write failure.

LLVM Coverage Report

Measured on commit 18bd573.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 92.20% +0.40%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 88/94 (93.62%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 29, 2026
@arsenmuk arsenmuk changed the title Fix OPTIMIZE on Iceberg table deleting version-hint Fix Iceberg OPTIMIZE deleting version-hint Sep 29, 2026
@arsenmuk
arsenmuk force-pushed the arsenmuk/optmize-deletes-version-hint branch from 3949eee to b57bb12 Compare September 29, 2026 10:40
@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 18bd5739c83d3dcaec3c97be799cb9519a3f8ce1 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

@arsenmuk
arsenmuk force-pushed the arsenmuk/optmize-deletes-version-hint branch from 3c294a3 to 9f3168f Compare September 30, 2026 10:58
@arsenmuk
arsenmuk force-pushed the arsenmuk/optmize-deletes-version-hint branch from 9f3168f to 0e6d533 Compare October 1, 2026 13:39
@scanhex12 scanhex12 self-assigned this Oct 1, 2026
DB::ContextPtr context,
bool try_write_version_hint);
bool try_write_version_hint,
bool * version_hint_confirmed = nullptr);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

bool * seems weird)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's remove this flag and logical error related to it

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You're right 100% - I've missed that spaghetti logic. The general problem is that for regular updates it's okay to succeed writing metadata, but to fail updating the hint file. For optimize operations, this is more complicated. I made it explicit, as well as the contract for optimize in general.

{
const auto sample_block = std::make_shared<const Block>(metadata_snapshot->getSampleBlock());
auto snapshots_info = getHistory(context);
auto snapshots_info = getHistory(context, /* ignore_metadata_pointer_overrides */ true);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why true here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

absolute slop, used to cover the gap in ambiguous logic. I removed this one and the change in getHistory as well.

/// writer that does not have the setting enabled advances the table.
size_t i = 0;
while (i < MAX_TRANSACTION_RETRIES)
for (size_t attempt=0; attempt < MAX_TRANSACTION_RETRIES; ++attempt)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Cosmetic: attempt = 0

return true;
}

bool tryWriteVersionHintFile(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think that when an INSERT and a compaction (OPTIMIZE) run concurrently, they can corrupt the metadata.json file. In this case, both operations write metadata.json at the same time, and we only detect the conflict later, at the step where we write the version hint file.

I think OPTIMIZE should fail correctly (without breaking metadata of insert operation) in this case.

We can fix it in the following PR, but we need to keep it in mind

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 32 queries analysed

This PR only changes how Iceberg compaction and metadata writes handle the version-hint file, plus one new stateless test. Neither ClickBench nor TPC-H runs that code. No query has a directional verdict. ClickBench Q31 (-13.9%) is inside master's normal range with almost no change in CPU time, so leaving it as no change fits the diff. ClickBench Q34 (-11.2%) shows a matching CPU drop, but master's history for this query shifted mid-window, so the old numbers don't give a reliable comparison. The diff also cannot explain the drop, so not_sure is the right call.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 34 not_sure 1092 969 -11.2% <0.0001 The -11.2% comes with a similar CPU drop, but master's history for this query shifted mid-window. This MergeTree SELECT does not touch the Iceberg metadata-write paths in the diff.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: b13bd6d5-5e3c-468d-81dc-f2f7e8afe161
  • MIRAI run: 22ca1a20-df96-4fa5-b266-9fd239bb09ce
  • PR check IDs:
    • clickbench_437630_1791494594
    • clickbench_437643_1791494594
    • clickbench_437649_1791494594
    • tpch_adapted_1_official_437656_1791494593
    • tpch_adapted_1_official_437686_1791494594
    • tpch_adapted_1_official_437701_1791494594

@arsenmuk
arsenmuk force-pushed the arsenmuk/optmize-deletes-version-hint branch from 866b862 to 0d5d8fd Compare October 7, 2026 14:49
json_representation,
object_storage,
context))
throw Exception(ErrorCodes::FILE_ALREADY_EXISTS, "Metadata file {} already exists", generated_metadata_info.path.serialize());

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.

writeMetadataFile does not mean only “the path already exists”: it also returns false for retryable storage failures after logging them (see the new helper in Utils.cpp). Mapping every false to FILE_ALREADY_EXISTS here turns a transient metadata-write failure into a bogus version-conflict, which is what the user will see from OPTIMIZE.

Can we preserve the original failure here (or at least distinguish “already exists” from “write was not confirmed”) instead of always throwing FILE_ALREADY_EXISTS?

if (writeMetadataFiles(plan, persistent_table_components.path_resolver, object_storage_, context_, sample_block_, write_format, persistent_table_components.table_path))
clearOldFiles(object_storage_, old_files);
else
LOG_WARNING(getLogger("IcebergCompaction"), "Compacted metadata was written but its version hint was not confirmed; old files were retained");

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.

If writeMetadataFiles returns false, the rewritten data files / manifests / vN.metadata.json have already been created, but the compaction was not published through version-hint.text. This branch only logs a warning and still lets OPTIMIZE return success, so a transient hint-update failure or a writer race leaves the whole rewritten snapshot tree orphaned while the command appears to have worked.

I think this needs to surface a retryable commit-conflict/failure (or clean up the just-written files) rather than quietly succeeding.

@arsenmuk
arsenmuk force-pushed the arsenmuk/optmize-deletes-version-hint branch from 0d5d8fd to 18bd573 Compare October 8, 2026 15:07
zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Oct 9, 2026
A task of a distributed plan runs a deserialized plan, and plan headers
carry names and types only, so a receive step's header has a full column
where the producing stage emits a `ColumnConst`. The Persisted and
Streaming exchanges write through `NativeWriter`, which materializes
constants, but `SinkFromInMemoryExchange` (used by
`distributed_plan_execute_locally`) forwarded the chunk unchanged.

With a constant `ORDER BY` key, `PartialSortingTransform` kept its LIMIT
threshold as a `ColumnConst`, and the next zero-row scheduling tick of
`SourceFromInMemoryExchange`, built from the header, made
`ColumnVector<UInt8>::compareColumn` read the `ColumnConst` threshold as
a `ColumnVector`, which aborted debug and sanitizer builds with the
`PODArray` bounds assertion (STID 2508-1e49).

Materialize constants in `SinkFromInMemoryExchange::consume`, the only
caller of `InMemoryExchange::appendChunk`, so all in-memory exchanges
deliver what the serialized ones do.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122833&sha=866b862fc9f521847ee9acac63978be11ba19e3c&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
PR: ClickHouse#122833

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@arsenmuk
arsenmuk added this pull request to the merge queue Oct 9, 2026
Merged via the queue into master with commit 5859e03 Oct 9, 2026
152 checks passed
@arsenmuk
arsenmuk deleted the arsenmuk/optmize-deletes-version-hint branch October 9, 2026 06:55
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
@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

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.

OPTIMIZE TABLE deletes metadata/version-hint.text, leaving the table unreadable

3 participants