Skip to content

Do not clean up an Iceberg commit whose outcome is unknown - #115390

Open
groeneai wants to merge 19 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-commit-state-unknown-cleanup
Open

groeneai wants to merge 19 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-commit-state-unknown-cleanup

Conversation

@groeneai

@groeneai groeneai commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator

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 data loss on Iceberg writes when the response to the metadata.json compare-and-swap is lost after the object store already accepted it. ClickHouse read that as another writer having taken the version and deleted the manifests, manifest list and data files of the snapshot that had just become current, leaving the table unreadable. INSERT, DELETE/UPDATE, OPTIMIZE TABLE ... MANIFEST and ALTER TABLE ... DROP PARTITION were affected. The commit outcome is now established by reading the target back instead of inferred from the error, so files are deleted only when the commit is known not to have taken effect; an outcome that cannot be established reports UNKNOWN_STATUS_OF_TRANSACTION. Closes #112081.

Description

writeMetadataFileAndVersionHint returned false for every failure of the conditional
v<N>.metadata.json write except a backend refusal, and callers read false as "my commit did not
land" and clean up. That PUT is a compare-and-swap, so a response lost after the store accepted the
object is indistinguishable at the error from a lost race: the cleanup deletes the manifest list,
manifests and (on INSERT) the data files of the snapshot that write just made current, and readers
then 404. false asserts the commit did not happen; the code can only establish it is retryable. The
spec names this state CommitStateUnknown and requires no cleanup.

The outcome is now measured, not inferred. On a failed PUT the target is read back uncached and
compared byte-for-byte with what was written: identical means committed (no cleanup),
present-but-different means a lost race (cleanup, unchanged), absent or unreadable stays
unknown and throws. Absence is not proof the write will not land, since nothing cancels a failed
conditional PUT server-side. Classifying the error instead was
rejected; see below.

Six callers share this seam. The four that delete staged files while unwinding (INSERT,
DELETE/UPDATE, OPTIMIZE, DROP PARTITION) now let that exception pass through, and the INSERT sink keeps its files on it; otherwise it
reaches their cleanup and the data loss survives. ALTER and expiration delete nothing there. The
post-commit version-hint.text steps also ran outside any handler, so a blip there reached those
same cleanup handlers after the commit had landed.

A failure raised before the write reaches the store is also reported unknown, so it leaks the staged
files rather than removing them. Erring that way is deliberate.

The catalog updateMetadata implementations share the defect but need a different oracle: #115580.
#114246 touches only this function's exists() pre-check, so the hunks are disjoint.

Validation, and why error classification was rejected

Classifying the error was rejected: a 412 is a generic S3Exception with a private AWS code, each
of four backends would need its own taxonomy, and an unclassified error defaults into one bucket.

Each guard has an arm: reverting that guard's single hunk reddens it and leaves the other eight
byte-identical. An error-code oracle would be vacuous, since a guard
changes only the cleanup, never the throw; so file counts are absolute and every scan sums
a column (count() alone survives deleted Parquet). A/B
against base, failpoints in both, Build IDs asserted.

Stateless 04929_iceberg_commit_state_unknown_no_cleanup, 8 arms and a control:

Assertion base with fix
INSERT: rows, sum(c0), fresh icebergLocal() errors 9, 45, 9, 45
INSERT: manifest list, data + Avro files absent, 2 + 4 present, 3 + 6
DELETE: rows, sum(c0), manifest list errors, absent 4, 18, present
DELETE, unknown: reported, manifest list, files no, absent, 2 + 4 yes, present, 3 + 6
OPTIMIZE, both arms: manifest list, sum(c0) absent, errors present, 36
INSERT, unknown: reported, data + Avro files no, 2 + 4 yes, 3 + 6
DROP PARTITION, unknown: manifest list, Avro, sum(c0) absent, 4, errors present, 5, 7
version hint naming no version: data files kept 1 of 2 2 of 2
control, nothing armed 4, 10 4, 10

On base, reads fail with the reported signature, No such file or directory [.../metadata/snap-<id>-...avro. The version-hint row needs no failpoint.

IcebergCommitPropagation gtest: 7 new arms (committed, compressed, hint probe error, hint race,
hint creation, absent, unreadable) redden on base. Master's refusal arms share the stub; two expecting false for an
ambiguous outcome now expect UNKNOWN_STATUS_OF_TRANSACTION, and a refusal after a landed upload
commits. 100 randomized runs passed.


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

The conditional write of v<N>.metadata.json is a compare-and-swap, and
writeMetadataFileAndVersionHint reported every failure of it except a backend
refusal as false. Callers read false as "my commit did not land" and delete the
files they staged. But a response lost after the object store already accepted
the object is indistinguishable, at the error, from another writer having taken
the version, so that cleanup deletes the manifest list, the manifest entries
and (on the INSERT path) the data files belonging to the snapshot the write has
just made current. Every subsequent read then fails to resolve the manifest
list and the table is unreadable. The Iceberg specification names this state
CommitStateUnknown and requires the writer not to clean up.

false asserts that the commit did not happen; the code could only establish
that the failure was retryable. Those are different claims and only the first
licenses a cleanup.

Establish which one holds by reading the target back and comparing it to what
was written, rather than inferring it from the error: identical content means
the commit took effect, a different document means a genuinely lost race, and
an absent or unreadable target means the outcome cannot be established. The
last case throws UNKNOWN_STATUS_OF_TRANSACTION, because a failed conditional
write is not cancelled server-side and there is no ordering fence, so absence
does not prove the write will not land; a short retry bounds that window.
Reconciliation runs only when the write was actually attempted, so a failure of
the preceding existence probe keeps reporting a lost race, which is correct
there because nothing was written.

Classifying the error instead was rejected: a 412 arrives as a generic
S3Exception whose AWS code is private, the four backends that implement the
condition would each need their own taxonomy, and any error left unclassified
would silently default into one of the two buckets.

All five callers of the commit share this seam. The three that delete staged
files while unwinding now let a commit-state-unknown exception pass through
untouched, since those files may be the ones the current snapshot references.

The post-commit version-hint convergence is also brought inside a handler. Its
existence probe, hint read and version parse ran unguarded after the commit had
landed, so a transient failure or a malformed hint file propagated into the
same cleanup handlers and destroyed a snapshot that was already current,
without any lost response being involved.

Closes: ClickHouse#112081
Advancing version-hint.text runs after the metadata file is already durable, so
every failure there is logged and swallowed: escalating would send a committed
snapshot into the callers' cleanup handlers. The loop that does it inherited a
1000 attempt bound from the commit retry it used to sit next to, which is the
wrong bound now that the read and the parse of the stored hint happen inside it.
Content that names no metadata version fails identically however many times it
is re-read, so it is reported once and the loop stops; only a lost write race
and a transient read are retried, and a handful of attempts resolve both.
Measured on a hint holding unparseable content: one warning, against 1000
exceptions and 1000 stack traces for a single INSERT before this change.

Extend the test to the two paths whose guards nothing reached. Manifest
compaction commits through the same seam and unwinds through its own handler, so
it gets both a committed and an unestablished arm; reverting just the compaction
guard now reddens the second one and leaves the INSERT and DELETE arms green.
The version hint failure needs no failpoint at all, which makes the second data
loss path this fix closes reproducible from a plain corrupt hint file.

Assert the data files themselves. count() on an Iceberg table is answered from
the manifests' record_count without opening a data file, so it reported the
right number on a table whose Parquet files had all been deleted; the arms now
also sum a column and compare the stored file count against an exact expected
number rather than against the count before the operation, which a single
survivor satisfied.
The three isCommitStateUnknown guards were not symmetrically covered. Entering one
requires writeMetadataFileAndVersionHint to throw UNKNOWN_STATUS_OF_TRANSACTION,
which needs both failpoints armed: iceberg_metadata_commit_response_lost alone is
reconciled as Committed on local storage, which is what the existing INSERT and
DELETE arms assert. The pre-existing DELETE arm armed response_lost only, so the
guard in Iceberg/Mutations.cpp was reached by nothing and deleting it left every
test green while the DELETE/UPDATE data loss stayed live.

The new arm arms both failpoints, asserts the code is reported, and then asserts
survival the way the other arms do: the current snapshot's manifest list is still
stored, absolute data-file and Avro-file counts, and a forced column scan through
both the table and a fresh icebergLocal(). count() alone is answered from the
manifests' record_count and is blind to a deleted data file.

On base the arm prints NOT REPORTED AS UNKNOWN and reads fail with the reported
signature, No such file or directory [.../snap-<id>-2-<uuid>.avro. Deleting only
the eight-line catch block in writeMetadataFiles reddens this arm and leaves the
other eight byte-identical. Note the mutant still reports the error code, so an
oracle on the code alone would be vacuous here; the manifest-list probe and the
file counts carry the difference.

100 randomized runs through clickhouse-test, no source change.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (three rounds; every finding and its disposition)

An independent model reviewed this change against the frozen description before publication, once per
round. Nothing below is outstanding.

Round 3 (final): 0 findings from the second model, 2 nits from my own review.

# Finding Verdict
💡 1 The "was the write attempted" flag is set just before the conditional write, not when the request reaches the store, so a failure raised earlier (buffer construction, compression setup, a full local disk) is also reported as an unknown outcome and leaks the staged files instead of removing them Agreed, disclosed rather than changed. It errs toward leaking, never toward deleting, which is the whole point of this change; a precise gate would need the write buffer to report whether anything was sent. Stated in the description
💡 2 isCommitStateUnknown matches on the error code alone Noted. UNKNOWN_STATUS_OF_TRANSACTION has exactly one other thrower (MergeTree transactions), unreachable from this path, so it cannot be confused today. A dedicated exception type would be immune if that ever changes

Round 3 also covered the round-2 addition: the DELETE/UPDATE guard now has an arm of its own, and
deleting that guard's eight lines reddens only that arm while the other eight stay byte-identical.
Worth recording why the arm needed the earlier rounds: a guard controls only whether the cleanup runs,
never whether the exception is thrown, so an oracle grepping the error code passes against a mutant
that deletes the files. What carries the difference is the manifest-list probe plus absolute file
counts.

Round 2: 1 finding (raised independently by both the second model and my own review).

# Finding Verdict
❌ 1 Nothing reached the DELETE/UPDATE unknown-status guard: entering it needs both failpoints, and the existing DELETE arm armed only one, so reverting that hunk left every test green while the mutation data loss stayed live Agreed, fixed. Seventh arm added; reverting the guard alone now reddens exactly it

Round 1: 6 findings.

# Finding Verdict
❌ 1 SELECT count() on an Iceberg table is answered from manifest record counts, so it cannot prove the data files survived; a relative file-count assertion passes when a single staged file survives Agreed, fixed. Forced data scans and absolute file counts, each shown to redden on base
❌ 2 Nothing exercised the OPTIMIZE cleanup guard, so reverting that hunk alone left every test green Agreed, fixed. Manifest-compaction arms added; verified red when only that hunk is reverted
⚠️ 3 Pulling the version-hint convergence inside a handler made a deterministic failure retry 1000 times instead of escaping after one attempt Agreed, fixed. Deterministic failures stop immediately, transient ones are bounded. It still cannot throw: the commit is durable by then
⚠️ 4 An ADLS Gen2 target can be left zero-length by a lost Create response, which the read-back would see as another writer's document Disagreed. The unfixed code returns false and cleans up on the same input, so this is neither introduced nor worsened. The underlying defect is that this backend publishes a zero-length object before appending, i.e. its conditional create is not atomic; separate and pre-existing
⚠️ 5 The read-back could be served from the distributed cache and a stale body mistaken for another writer Disagreed. That path sits behind a Cloud-only setting defaulting to false and behind a compile flag. The harmful direction is unreachable regardless: every competing document carries a distinct random snapshot id and last-updated-ms, so a stale body cannot compare equal
💡 6 Use the Critical Bug Fix category Not applied proactively. Happy to recategorise if a maintainer asks

One correction was made to the description during round 1: it had listed ALTER and snapshot
expiration among the affected operations. Neither deletes anything while unwinding, so neither ever
lost data here; the text now names only INSERT, DELETE/UPDATE and OPTIMIZE.

Also noted and deliberately not chased: GlueCatalog::updateMetadata and RestCatalog::updateMetadata
have the same defect entered through the catalog, but need a different reconciliation oracle. Called
out in the description as a follow-up.

@clickhouse-gh clickhouse-gh Bot closed this Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro Yes, two of them. SYSTEM ENABLE FAILPOINT iceberg_metadata_commit_response_lost, then INSERT, DELETE or OPTIMIZE ... MANIFEST on an IcebergLocal table. And, with no failpoint at all, a version-hint.text holding content that names no version, then a write through icebergLocal(...). No concurrency, no object store, 100% reproducible.
b Root cause explained Yes. writeMetadataFileAndVersionHint converts every non-refusal failure of the conditional metadata.json write to false, which callers read as "the commit did not happen" and clean up; the code can only establish "retryable".
c Fix matches root cause Yes. The outcome is read back from the store and compared to what was written, so cleanup happens only on the one outcome that proves the commit did not land. Error classification (412 vs 5xx) rejected: signal is private behind S3Exception, needs a per-backend taxonomy, and is fail-open for anything unclassified.
d Test intent preserved, new tests added Yes. New stateless test with 7 arms plus a control (INSERT, DELETE, DELETE unknown, OPTIMIZE committed, OPTIMIZE unknown, unknown outcome, version hint) and 3 new gtest arms. Each arm asserts a forced data scan next to count(), which alone is answered from the manifests' record_count and is blind to a deleted data file, and an absolute stored-file count rather than a count relative to before the operation, which one survivor satisfied. The 2 pre-existing behaviours stay pinned as regression guards; the one pre-existing assertion this fix intentionally changes is replaced by outcome-specific arms, not dropped.
e Demonstrated in both directions Yes. A/B with Build IDs asserted against each running server. On base the current snapshot's manifest list is physically deleted and every read fails No such file or directory [.../snap-<id>-...avro, and the version-hint arm loses a data file; with the fix all arms pass. The control passes on both. Three single-hunk mutations on top of the fix each redden only their own arm: removing the compaction guard reddens the OPTIMIZE unknown-outcome arm in exactly 3 output positions, removing the mutation guard reddens the DELETE unknown-outcome arm and leaves the other 8 arms byte-identical, and reverting the hint-loop bound restores 1000 logged exceptions against 1 warning.
f General across code paths Yes. Fixed at the seam all five callers share (INSERT, DELETE/UPDATE, ALTER, OPTIMIZE, expire), and the three that delete staged files on the way out also got the throw-path edit. Each of those three guards is driven by its own test arm, and each arm is proven load-bearing by a targeted single-hunk revert of exactly the guard it pins.
g Generalizes across inputs Yes. Comparison is full-content, which is required because two callers create no snapshot and would share a current-snapshot-id between competing documents. The read-back passes the write's own compression method, so .snappy.metadata.json tables compare correctly. Backend-agnostic; HDFS still surfaces UNSUPPORTED_METHOD unchanged.
h Backward compatible Yes. No setting added or changed, so no SettingsChangesHistory.cpp entry; no format change. The one user-visible change is that a genuinely ambiguous outcome now reports UNKNOWN_STATUS_OF_TRANSACTION instead of silently retrying and destroying data. It is in the changelog entry.
i Invariants and contracts preserved Yes. The UNSUPPORTED_METHOD re-throw is unchanged and still pinned by a test. No Iceberg pre-commit path throws UNKNOWN_STATUS_OF_TRANSACTION, so the caller predicate cannot suppress a legitimate pre-commit cleanup. Reconciliation adds a read on the failure path only; the success path is untouched.

100 randomized runs, all passed. IcebergCommitPropagation gtest 5/5. The whole iceberg stateless selector (79 tests) was also run on both arms: the 22 that fail here fail identically on base, on absent MinIO named collections and an absent row-policy user directory.

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0d66edf]

Summary: ✅


AI Review

Summary

The PR reconciles failed Iceberg metadata writes against stored content and preserves staged files when the outcome is UNKNOWN_STATUS_OF_TRANSACTION, including during sink destruction. Two previously reported concerns remain in the current code: acknowledged writes can leave hint-based readers on an older snapshot, and ambiguous catalog commits can still trigger destructive cleanup. Both are retained below without reopening the author's resolved threads. There are no new inline findings.

Findings

❌ Blockers

  • Acknowledged writes can remain invisible after four transient hint failures. src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp:531 [dismissed by author -- https://github.com/Do not clean up an Iceberg commit whose outcome is unknown #115390#discussion_r4239265737]. With a valid hint of 1 and committed metadata version 2, four failed hint probes exhaust VERSION_HINT_CONVERGENCE_ATTEMPTS; convergeVersionHint returns and writeMetadataFileAndVersionHint reports success. Once connectivity recovers, getLatestOrExplicitMetadataFileAndVersion at line 2452 still follows the valid older hint without checking newer versions, so reads can indefinitely omit acknowledged inserts or return rows from an acknowledged deletion. Resetting the budget when another writer advances the hint does not cover this case. Preserve the previous transient-failure retry budget or provide reader/repair behavior that prevents the persistent stale result, while keeping post-commit failures out of destructive cleanup.

  • Unknown catalog outcomes still authorize deletion of potentially committed files. src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp:2061 and src/Storages/ObjectStorage/DataLakes/Iceberg/AlterDropPartitionExecutor.cpp:722 [dismissed by author -- https://github.com/Do not clean up an Iceberg commit whose outcome is unknown #115390#discussion_r3809841380] [dismissed by author -- https://github.com/Do not clean up an Iceberg commit whose outcome is unknown #115390#discussion_r4239535296]. Current RestCatalog::updateMetadata converts a received HTTP 500 into DATALAKE_DATABASE_ERROR; GlueCatalog::commitTableUpdate also throws that ordinary exception for failed transport outcomes, and UnityV2Catalog delegates to REST. If the update was accepted before its response was lost, these exceptions bypass isCommitStateUnknown, so the insert, mutation, manifest-compaction and partition-drop cleanup paths can delete files referenced by the committed snapshot. Catalog reconciliation must establish the outcome and propagate unresolved cases as UNKNOWN_STATUS_OF_TRANSACTION. The author explicitly deferred this work to Do not delete staged Iceberg files when a catalog commit outcome is unknown #115580, which remains open; this is an existing concern, not a new inline request.

Tests
  • ⚠️ Add a focused hint-recovery case with an existing valid hint and four consecutive transient failures followed by recovery. The current VersionHintAdvancesPastATransientProbeFailure case injects only one failure and cannot detect the first finding. Verify that subsequent reads include the acknowledged change.
Missing context / blind spots
  • ⚠️ The current-head Praktika workflow is still running. Fast tests passed, but targeted stateless and unit jobs are pending; the new shell regression is tagged no-fasttest. Completed results for 04929_iceberg_commit_state_unknown_no_cleanup and IcebergCommitPropagation would close this validation gap. No local tests were run, as instructed.
Final Verdict

Status: ❌ Block

Address the version-hint stale-read regression and complete the tracked catalog reconciliation for the remaining destructive commit paths. Existing dismissed findings remain summary-only; no threads were reopened or duplicated.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @arsenmuk @kssenii, could you review this? The Iceberg metadata.json compare-and-swap reported every failure except a backend refusal as a lost race, so a response lost after the store accepted the object made the callers delete the manifests, manifest list and data files of the snapshot that write had just made current. The outcome is now established by reading the target back rather than inferred from the error.

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0d66edf3f with master 500ba6536 (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

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.

Object file sizes

8 object files changed (+45.67 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp.o 1.33 MiB 1.37 MiB +40.39 KiB (+2.96%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 80ebd36

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Bugfix validation (unit tests) harness ERROR, not a test failure: the job aborts as inconclusive because submodule state differs between the merge-base and the checkout (contrib/NuRaft, contrib/chdig, contrib/rust_vendor). This branch changes no submodule, so the base branch moved those three after the split a fix task is in progress (investigating at full effort - fixing PR link to follow on this PR)

The praktika report for this head lists exactly one non-OK result, and it is the harness abort above; the whole test matrix is otherwise green. Note the GitHub check list also shows a Config Workflow stuck in queued from an abandoned duplicate workflow run (32211204881, never updated since 03:10:41Z); the run that actually executed this head is 32211212035, which completed at 07:41Z.

@PedroTadim

Copy link
Copy Markdown
Member

cc @scanhex12 @SmitaRKulkarni

groeneai and others added 6 commits September 29, 2026 11:44
…known

`ALTER TABLE ... DROP PARTITION` on Iceberg commits through
`writeMetadataFileAndVersionHint` like INSERT, DELETE/UPDATE and OPTIMIZE,
but its `SCOPE_EXIT` removed the staged manifest list whenever the commit
did not return true, including when it threw `UNKNOWN_STATUS_OF_TRANSACTION`.
When the metadata write had in fact landed, that deleted the manifest list of
the snapshot the table now points at, so every read failed with a missing
`snap-*.avro`.

On an unknown outcome the staged files are now kept, as in the other three
commit paths. The 04929 arm arms both failpoints around a DROP PARTITION;
without this change the new manifest list is gone and both reads fail with
FILE_DOESNT_EXIST, with it the drop is visible and the table stays readable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment-only change. The guard sites no longer restate the contract that
`isCommitStateUnknown` documents in `Utils.h`, and the remaining blocks keep
only the invariants the code below them cannot show: a failed conditional
write can still land, only `LostRace` licenses deleting the staged files, the
hint convergence must never throw, and both sides pin `SnappyMode::Basic`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Three properties of `writeMetadataFileAndVersionHint` had no test that fails
without them:

- a target that becomes visible only after the first read-back still resolves
  as committed (with a single probe it reports an unknown outcome);
- a compressed document this writer stored is recognised as its own, which
  needs the read-back to decode what the write path encoded (gzip, zstd, and
  snappy in its pinned block format);
- a transient failure while advancing `version-hint.text` neither leaves the
  function, since it runs after the commit landed and a throw would reach the
  callers' cleanup, nor stops the hint from advancing.

The stub now stores what the commit writes before failing the write, hides the
target from the first probes, and holds a version hint whose first probes
fail. Each new case fails on its own mutation: one read-back attempt, no
decoding, a framed snappy reader, and giving up or rethrowing in the hint
retry loop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`convergeVersionHint` gave up after four failed attempts in total, so a writer
of the highest version could lose four hint races to writers of lower
versions and stop with `version-hint.text` still naming one of theirs: readers
with `iceberg_use_version_hint = 1` then miss the latest commit until the next
one repairs the hint. A failed attempt after which the hint turns out to have
advanced was lost to another writer's progress, so it no longer counts; the
budget still bounds attempts that make no progress, and the number of resets
is bounded by the versions between the observed hint and the committed one.

The new gtest loses four hint races, each to a writer that advances the hint
by one: before this change the hint stays at 5 after version 6 committed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0ce6a73

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_llvm_coverage, 1/8) / test_storage_iceberg_no_spark/test_iceberg_inverted_manifest_bounds.py::test_iceberg_narrow_manifest_bounds master-side: since #122681 a read decodes manifest bounds only for the columns its filter uses, so the log line the assertion at line 337 waits for is never written. It failed on every true-master run from 2026-09-29 10:59Z until the fix merged, and on 66 pull requests today #122895 (mine, merged 16:58Z), absent from the tree this run built, merged master @ 1ae61ee
Integration tests (amd_asan_ubsan, db disk, targeted) / same test same cause as the row above #122895 (mine, merged), merged master @ 1ae61ee
Integration tests (amd_msan, targeted) / same test same cause as the row above #122895 (mine, merged), merged master @ 1ae61ee
Integration tests (amd_tsan, targeted) / same test same cause as the row above #122895 (mine, merged), merged master @ 1ae61ee
Integration tests (arm_binary, distributed plan, targeted) / same test same cause as the row above #122895 (mine, merged), merged master @ 1ae61ee
Mergeable Check, PR rollups, red only because of the rows above #122895 (mine, merged)
Sync - CH Inc sync (private, not actionable by me)

The targeted jobs pick this test because the PR changes the Iceberg commit code; the PR does not touch the test or the manifest bounds decoding. CIDB has no other FAIL or ERROR row on this head, and every other check passed.

Session id: cron:our-pr-ci-monitor:20260929-183205

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

No performance change can be attributed to this PR. It only changes Iceberg write commits: checking whether a metadata write landed, retrying the version-hint update, and skipping cleanup when the commit outcome is unknown. Benchmark SELECTs over MergeTree tables never run that code. The one flagged row, clickbench Q18 (+13.3%, 892 ms to 1010.5 ms), was already held at not_sure because the new median sits inside master's current range of 856-1079 ms. That ruling fits the diff, and the run's measurements were noisy.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 892 1010 +13.3% <0.0001 aggregation: This is a heavy GROUP BY over a MergeTree table and never reaches the Iceberg commit code this PR changes. The +13.3% median falls inside master's current range, so treat it as noise.

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: 8a882b40-debc-4392-96e2-3e3f80682dc8
  • MIRAI run: 363b6d65-0b1d-4d85-8387-1f1132869bf3
  • PR check IDs:
    • clickbench_2647345_1790828670
    • clickbench_2647470_1790828685
    • clickbench_2647573_1790828708
    • tpch_adapted_1_official_2647760_1790828816
    • tpch_adapted_1_official_2647862_1790828826
    • tpch_adapted_1_official_2647967_1790828836

alexey-milovidov and others added 2 commits October 10, 2026 17:27
This PR removed the constant together with its only user, the version
hint loop of `writeMetadataFileAndVersionHint`, which `convergeVersionHint`
replaced. Master has since added `tryWriteVersionHintFile`, which OPTIMIZE
uses and which loops on the same constant, so the merge of master did not
compile. Keep the constant at master's value so that function keeps
master's behaviour; `writeMetadataFileAndVersionHint` still goes through
`convergeVersionHint`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2b1946d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 1/4) / Build ClickHouse PR-caused: Utils.cpp:638 use of undeclared identifier 'MAX_TRANSACTION_RETRIES'. This PR removed the constant, and the master merge brought tryWriteVersionHintFile, which still uses it PR-caused -> fixed in this PR @ 88f5e92: the constant is restored with master's value
Finish Workflow, Mergeable Check, PR follow-on of the row above PR-caused -> fixed in this PR @ 88f5e92
Sync - CH Inc sync (private, not actionable by me)

Every other build and test job was skipped after this failure. They will run on the new head.

Session id: cron:clickhouse-maint-slot-23:20261010-201100

groeneai and others added 3 commits October 10, 2026 22:16
The read-back of a failed conditional metadata write polled up to four
times with a fixed 200 ms sleep, to catch a write that becomes visible
late. The outcome is safe without the poll: an absent or unreadable
target is already reported as an unknown commit state, which keeps the
staged files, and every probe already goes through the object storage
client's own retries. So the read-back is now a single probe and holds
no query thread in a sleep.

The unknown-state error no longer says the table is left untouched,
which contradicted its own "the commit may have taken effect": it now
says that no staged files were removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test stub returned no ETag for `version-hint.text` and accepted any
hint write, so dropping the `If-Match` condition from the hint update
left every test green, although that condition is what stops a writer
of a lower version from overwriting a newer hint. The stub now hands
out an ETag that changes on every hint write and expects each update
of an existing hint to be conditional on it. Removing the condition
from `convergeVersionHint` now fails the two hint tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…gtest

Creating `version-hint.text` uses `If-None-Match: *`, so of two writers
creating it at once only one succeeds. No test created the hint, so
dropping that condition stayed green. A new arm creates it, and the
stub expects the creating write to be exclusive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a239ef5

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05339_parquet_prewhere_subcolumn_read_through_column not from this PR (it changes Iceberg commit cleanup only): the test passes a session temporary table to IcebergLocal, which the replicated DDL worker cannot see (UNKNOWN_TABLE on iceberg_path). 50 PRs and 40 master runs show it since 2026-10-10 21:55Z #125121 (external, merged 00:36Z), the revert of my #124685 that added this test. The tested merge commit predates it, so I will merge master here to pick it up
Mergeable Check, PR praktika rollups of the row above #125121 (external, merged)
Sync - CH Inc sync (private, not actionable by me)

All 163 check runs completed and Finish Workflow is green. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261011-033004

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 24cb5da

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR (it changes Iceberg commit cleanup only; all 130 reruns with the same settings pass): with parallel replicas the reused MATERIALIZED CTE reaches a replica that does not have it (UNKNOWN_TABLE on _materialized_cte_c_...). 99 PRs and 17 master commits show it in 3 days #123121 (mine, open)
Mergeable Check, PR praktika rollups of the row above #123121 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

The same shard's Failed count also includes three NOT_FAILED rows (01513_optimize_aggregation_in_order_memory_long, 02346_non_negative_derivative, 02884_create_view_with_sql_security_option), tests that passed while still listed in parallel_replicas_blacklist.txt; those are not failures.

Session id: cron:our-pr-ci-monitor:20261011-080006

@zlareb1

zlareb1 commented Oct 12, 2026

Copy link
Copy Markdown
Member

@groeneai check test failures

@groeneai

Copy link
Copy Markdown
Collaborator Author

The finished run on 24cb5da has one failed test, and it is not related to this PR:

CH Inc sync is red with "Needs manual intervention" on every head of this PR since 2026-10-10, while it passes on my other PRs. That job is private and I cannot see its log, so it needs someone with access to check whether this diff conflicts with private code.

nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Oct 16, 2026
…write

`Iceberg::writeMetadataFile` is the single storage-side commit point (an
`If-None-Match: *` create of `vN.metadata.json`). It turned every write failure
except `UNSUPPORTED_METHOD` into `false`, and every caller (expire_snapshots,
INSERT, DELETE/UPDATE, ALTER, DROP PARTITION, OPTIMIZE) reads `false` as a lost
commit race and retries. A write the storage refused (no permission) is refused
again on every round, so the loop ended in `LIMIT_EXCEEDED` and the real error
was only logged (ClickHouse#125343).

Propagate a refused write, extending the `UNSUPPORTED_METHOD` carve-out:
`READONLY` (a read-only disk refuses every write before sending it),
`ErrnoException` with EACCES/EPERM/EROFS (local storage; the temporary file is
opened, and the target linked, before anything is published) and `S3Exception`
with the codes `S3::isAuthenticationError` recognises (ACCESS_DENIED,
INVALID_ACCESS_KEY_ID, INVALID_SIGNATURE) plus SIGNATURE_DOES_NOT_MATCH (a
403/401 is answered before the request is applied).

A refusal that comes after the write was sent, e.g. of the
`s3_check_objects_after_upload` request, may follow a PUT that landed, so it
propagates only when the file is absent; a refused pre-write existence check
propagates directly.

Every other failure stays retryable:
- S3 reports a lost race (412 PreconditionFailed) as an untyped `UNKNOWN`
  error, so "retry only on a recognised conflict" would fail the parallel sinks
  of a multi-threaded INSERT.
- A timeout or 5xx after the PUT may have committed; that case is ClickHouse#115390's.
- Azure's layer classifies 403 as retryable on purpose (RBAC propagation lag),
  so Azure is unchanged.
`S3Exception::isRetryableError` is not reused: its non-retryable set includes
NO_SUCH_KEY/NO_SUCH_UPLOAD, which can follow a PUT that landed.

The callers' exception paths clean up only this attempt's uncommitted staged
files and rethrow, which is correct for a write that did not happen.

The gtest stub now takes the error to throw and the answers of `exists`. The
`UNSUPPORTED_METHOD` test also covers READONLY. New tests cover the errno and
S3 refusals, a refusal of a write that may have landed (the file is there
afterwards, or the check fails), and a refused pre-write existence check. The
retryable control gains the local lost race (FILE_ALREADY_EXISTS), an I/O
error (EIO) and the S3 lost race (412), so a classifier that propagated every
ErrnoException or S3Exception fails it.

Closes ClickHouse#125343

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…state-unknown-cleanup

Conflicts in Iceberg/Utils.cpp and the commit-propagation gtest, both
against master's refused-write propagation (ClickHouse#125406).

Utils.cpp: keep master's `isRefusedWrite`/`isKnownAbsent` and its
`write_attempted` flag, which replaces this branch's `put_started`
(same meaning). The refusal check stays the first statement of the
catch arm, so a refused write whose target is absent still propagates
as itself; every other failure after the write was sent is reconciled.

gtest: port master's refusal cases onto the reconciling stub (the write
failure is now a thrower, and the target's existence probe can be
answered per call). Two of master's expectations encoded "an ambiguous
outcome returns false" and change with this branch: a non-refused
failure with an absent target, or a failing check after a refusal, is
now UNKNOWN_STATUS_OF_TRANSACTION; a refusal after an upload whose bytes
landed is committed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 9, 2026 13:19
…state-unknown-cleanup

Conflicts in Iceberg/Utils.h and Utils.cpp, both against master's
`isConditionalWriteConflict` (ClickHouse#125026), which logs a lost metadata
commit race at Debug instead of Error.

Utils.h: declare both `isCommitStateUnknown` and master's
`isConditionalWriteConflict`; keep this branch's `writeMetadataFile`
contract (false only for a known-lost commit).

Utils.cpp: union of the error codes and failpoints. In the catch arm
the refusal check stays first, master's Debug/Error log split follows,
and every failure after the write was sent is still reconciled against
the stored bytes instead of returning false.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master's ClickHouse#127275 made `~IcebergStorageSink` remove the written data
files and manifests whenever the insert did not commit. An
`UNKNOWN_STATUS_OF_TRANSACTION` from `initializeMetadata` leaves
`committed` false, so the destructor deleted the files of a snapshot
the table may already point at, after the commit path had deliberately
kept them. 04929's unknown-outcome INSERT case caught it after the
master merge: a data file and a manifest gone, `SELECT sum(c0)` failing
FILE_DOESNT_EXIST on the manifest.

Record the unknown outcome and skip the destructor's cleanup for it.
Inserts that fail any other way still remove their files (05441 passes).

Co-Authored-By: Claude Opus 5.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
…state-unknown-cleanup

# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/AlterDropPartitionExecutor.cpp
#	src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp

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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

4 participants