Skip to content

Fix spurious PreconditionFailed on a retried Iceberg metadata write - #113994

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:iceberg-conditional-put-write-token
Aug 28, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:iceberg-conditional-put-write-token

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #96121

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

Fixes a spurious PreconditionFailed (Code: 499) error when creating or committing to an Iceberg table. If the object store drops the response to the metadata write after the object was written, the retry of that conditional write hits its own object and the query fails even though the write succeeded. Also stops a conditional multipart completion from reporting success over an object it did not write, silently losing the write it was meant to reject.

Description

CREATE TABLE ... ENGINE = IcebergS3(...) and Iceberg commits intermittently fail with
Code: 499 ... PreconditionFailed ... (S3_ERROR) for a write that landed: 6 occurrences over 6
unrelated PRs and 4 tests in 120 days of public CI, 0 on master
(latest report).

Root cause: Iceberg writes its metadata with If-None-Match: *, so the write is not idempotent.
When the response to a successful attempt is lost, or MinIO returns the bogus NO_SUCH_KEY that
WriteBufferFromS3 already retries, the request is re-sent, finds its own object, and gets 412.
IcebergMetadata::createInitial swallows that only under IF NOT EXISTS.

Fix: a conditional create-if-absent write now carries a random per-buffer token in S3 custom
metadata, and reports success on a replay only when one HeadObject finds that exact token.
Token absent, token different, object absent, or a failed HeadObject all throw the original
error, so a genuinely pre-existing table still fails. Three sites are covered: the single-part
PUT; the conditional CompleteMultipartUpload, reachable from an ordinary
SET s3_max_single_part_upload_size = 0; and the NoSuchUpload recovery in S3::Client, which
rewrote a failure into a success whenever a bare HeadObject found any object at the key, so a
conditional create could report success over a foreign object. It is now gated on the request
being unconditional.

Comparing content instead would not be sound: version-hint.text is the literal "1", so two
writers produce identical bytes. Custom metadata is not object content, so the JSON other engines
read is unchanged; token and recovery are guarded on object_storage_write_if_none_match, whose
only non-test producer is Iceberg.

Validated by thirteen deterministic unit tests on the existing mock S3 client (no S3, no network)
and thirteen mutations that each redden exactly the expected tests.

Version info

  • Merged into: 26.9.1.303 (included in 26.9 and later)

groeneai and others added 3 commits August 8, 2026 18:53
Iceberg writes its metadata with If-None-Match: *, which makes the PUT
non-idempotent. If the object store drops the response after the object has
already been written, or MinIO answers the bogus NO_SUCH_KEY that
WriteBufferFromS3 already retries, the request is re-sent, the precondition
now fails against the object this very request wrote, and the query fails
with Code: 499 PreconditionFailed even though the write succeeded.
IcebergMetadata::createInitial swallows that only under IF NOT EXISTS, so a
plain CREATE TABLE surfaces it. Public CI shows 6 occurrences over 6
unrelated PRs and 4 tests in 120 days, none on master.

A conditional create-if-absent PUT now carries a random per-buffer token in
S3 custom metadata. On a 412 the buffer issues one HeadObject and reports
success only if the stored object carries that exact token, so only a replay
of this request is accepted. Token absent, token different, object absent,
or a failed HeadObject all throw the original error, keeping a genuinely
pre-existing table failing as before.

Comparing content instead would not be sound: version-hint.text is written
as the literal "1", so two independent writers produce identical bytes and a
comparison would accept a foreign object, weakening the compare-and-swap. A
single-part ETag is not usable either, because server-side encryption is
plumbed into this request, so the ETag is not the body MD5. Custom metadata
is not object content, so the JSON other Iceberg engines read is unchanged.

Both the token and the recovery are guarded on
object_storage_write_if_none_match, whose only non-test producer is the
Iceberg write path, so ordinary S3 writes send byte-identical requests and
issue no extra request. CompleteMultipartUpload accepts the same header, but
Iceberg metadata files are kilobytes against a 32 MiB
max_single_part_upload_size, so that path is never taken here. The
version-hint update uses If-Match, and its caller already catches and
retries without reporting hint-write failures, so a 412 there costs a retry
rather than a failed query.

Co-Authored-By: Claude Fable 5 <[email protected]>
The write token added in the previous commit only guarded the single-part
conditional PUT. CompleteMultipartUpload sets the same If-None-Match header,
throws on 412, and is retried by the SDK on a network error, so it carries the
identical defect: a completion whose response is lost is replayed, sees the
object it just wrote, and fails a query whose write had succeeded.

That path was previously dispositioned as unreachable because Iceberg metadata
is kilobytes against a 32 MiB single-part threshold. That reasoning was wrong:
32 MiB is the default of s3_max_single_part_upload_size, an ordinary session
setting that validateUploadSettings does not constrain, so 0 is accepted and
reaches the Iceberg write through S3ObjectStorage::writeObject. With it at 0 a
plain CREATE TABLE ... ENGINE = IcebergS3(...) takes the multipart path. A
reachability bound that rests on a configurable default is not a reachability
proof.

The token is now stamped by createMultipartUpload, whose custom metadata lands
on the completed object, so the same HeadObject check recognises a replayed
completion. Both senders of the conditional header share one helper for the
metadata merge rather than duplicating it. isTransientCompleteMultipartUploadError
is untouched: a 412 is recognised, never retried.

Three further arms pin the guard's remaining false paths, which previously had
no test at all, so fail-open weakenings of it survived the whole suite: an
object carrying no token, no object present, and a failed HeadObject each still
throw the original error. Every conditional injection now also asserts its
request really carried If-None-Match.

Verified against real MinIO as well as the mock: with the threshold at 0 the
stored metadata object's ETag carries S3's -N multipart suffix and the write
token, and on a tree without the stamp the same multipart object carries no
metadata at all. Nine mutations of the guard each redden exactly their
predicted arms.
…eign object

DB::S3::Client::CompleteMultipartUpload rewrites a NO_SUCH_UPLOAD failure into a
synthetic success whenever a bare HeadObject finds any object at bucket+key. The
intent is to recover a completion whose response was lost after the upload had
already finished, and for an unconditional write mere existence is adequate proof.

For a conditional completion it is not. If-None-Match: * means "create only if
absent", so the object found at that key may be exactly the object the condition
was meant to reject. The write is then reported as successful while the caller's
payload was never stored, which is worse than the spurious PreconditionFailed this
branch already handles, because 412 at least surfaced an error. NO_SUCH_UPLOAD is
not only the lost-response case either: per the AWS CompleteMultipartUpload
documentation it also covers an upload id that is invalid, aborted or already
consumed, and WriteBufferFromS3 aborts uploads on its cancel and destructor paths.

Gate the existence-only recovery on the request being unconditional, and recover
the conditional case in WriteBufferFromS3 against the write token instead, next to
the PreconditionFailed guard. An If-Match write mints no token, so it can never
recover; that is deliberate and now has its own test. NO_SUCH_UPLOAD is recognised
but never made retryable: a consumed upload id cannot succeed on a retry.

Unconditional completions keep the previous behaviour byte for byte, which is what
copyS3File and the disk write paths rely on; a test asserts it, and a mutation that
removes the new recovery reddens only the conditional arm.
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, click to expand)

Each round is an independent cold review of the resulting code plus a second-model gate, adjudicated
against the code rather than against my own earlier reasoning. Round 3 is clean: my cold review found
no blockers or majors, and the gate returned no findings.

# Round Finding Verdict
❌ 1 The conditional multipart carrier is user-reachable, so the fix covered only one of two senders. The "Iceberg metadata is KB against a 32 MiB threshold" bound is about the default of s3_max_single_part_upload_size, an ordinary session setting that accepts 0. AGREE, fixed. SET s3_max_single_part_upload_size = 0; CREATE TABLE ... ENGINE = IcebergS3(...) reproduced it, then confirmed against real MinIO by the -N multipart marker on the stored object's ETag.
⚠️ 1 Three of the guard's four false paths (token key absent, object absent, HeadObject failure) were unpinned, so fail-open mutations of the PR's own core guard survived every arm. AGREE, fixed: one arm each, and every conditional injection now asserts the header was really sent.
💡 1 New test comments restated the incident and the mutation behaviour. AGREE, trimmed; motivation belongs in the commit message.
❌ 2 The NoSuchUpload recovery in S3::Client rewrote a failure into a synthetic success whenever a bare HeadObject found any object at the key, so a conditional create reported success over a foreign object. Worse than the 412 it replaced, and reached through a different error code. AGREE, fixed: the rewrite is now gated on the request being unconditional, and the conditional case recovers only against the write token. Pinned by four arms including an unconditional no-regression control.
💡 2 Related: needed a full GitHub URL and the changelog entry needed present tense. AGREE, fixed (body only).
💡 3 Recovering a conditional completion inside WriteBufferFromS3 leaves the S3::Client outcome a failure, so the GCS gcs_issue_compose_request block is skipped for that one write. Noted, not blocking: by that block's own comment a compose failure only affects later native-copy performance, and the same property already held for the 412 recovery.

Two findings of my own were disagreed on measurement rather than acted on: the round-1 mutation
snapshot predates a comment trim, so its restored Build ID differs from shipping while diff shows
the delta is two comment lines with the header identical; and S3's 2 KB user-metadata limit is
unreachable here because Iceberg passes no caller attributes.

Worth recording from round 2: a "NOT in scope" line written in one round becomes a fail-open licence
in the next if the gate keeps naming the same gap. That blocker was mine to fix, not a missed
instruction — the gate raised it in both rounds and my own round-1 plan had deferred it.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. taskset -c 0-15 ./build/src/unit_tests_dbms --gtest_filter='*Conditional*:*NoSuchUpload*:*IfMatchComplete*' fails on demand on unmodified src/. No S3, no network, no fault-injection infrastructure: the whole replay sequence is in-tree logic driven through the mock S3 client's existing InjectionModel.
b Root cause explained? Yes. Iceberg writes metadata with If-None-Match: *, so the write is not idempotent. Attempt 1 lands the object but its response is lost (or MinIO answers the bogus NO_SUCH_KEY that WriteBufferFromS3 already retries); the replay finds the object it just wrote and gets 412; 412 is not NO_SUCH_KEY, so the else branch throws S3Exception as Code: 499; IcebergMetadata::createInitial swallows it only under if_not_exists, so plain CREATE TABLE surfaces it. The multipart completion has the same shape, and can additionally come back as NO_SUCH_UPLOAD for an upload id the server already consumed.
c Fix matches root cause? Yes. The non-idempotency is a property of a conditional write plus its retry, and the request identity is available only in the buffer that issues it. The write token makes the replay recognisable at every site that sends the conditional header; nothing is widened, swallowed on retry, or tagged away, and no error is made retryable.
d Test intent preserved / new tests added? Yes. Thirteen new arms, no existing test weakened or removed; WBS3* passes 55/56 with one pre-existing skip (PrefinalizeCalledMultipleTimes), and the neighbouring Iceberg, LocalObjectStorage and HDFS conditional-write suites are 90/90. The mock gained capability (per-object custom metadata, carry-through of CreateMultipartUpload metadata onto the completed object as real S3 does, and a NoSuchUpload injection) and lost none.
e Both directions demonstrated? Yes, on Build-ID-distinct binaries, for every carrier. Single-part: base a1f3d4b99d94a48045f1e63a09ff811d6aa7b84c fails the witness arms with the production signature and the fix passes them. Conditional multipart 412: reverting only those hunks (dad4eb9b4f734355115eeda3f53355531e71c7f7) reddens exactly the four multipart instances. NoSuchUpload: reverting only the two hunks for it (649bdad458b75e1757d64dcd46a7f9fe8bea7312) reddens exactly the foreign-object arm, with Actual: it throws nothing, while the unconditional control arm passes on both trees. Shipping tree 3acde9435cb0e4cc2111972e0daca4aede893496 is green; 50 repeats over the conditional, multipart and NoSuchUpload arms in both sync and async gave 1600 instances, 0 failures.
f Fix is general across code paths? Yes, carriers enumerated and each dispositioned. Every sender of the conditional header is fixed: the single-part PUT (the carrier for all 6 CI rows) and CompleteMultipartUpload. So is the one place that consumed a completion outcome and could report success without proof: the NoSuchUpload recovery in DB::S3::Client::CompleteMultipartUpload, which rewrote a failure into a synthetic success whenever a bare HeadObject found any object at the key. For a conditional create that reported success on a foreign object, which is worse than the 412 it replaced, so it is now gated on the request being unconditional and the conditional case is recovered only against the write token. An earlier revision called the multipart path unreachable because Iceberg metadata is kilobytes against a 32 MiB threshold; that was wrong, because 32 MiB is the default of the ordinary session setting s3_max_single_part_upload_size, which accepts 0 and reaches this write. With it at 0 a plain Iceberg CREATE TABLE takes the multipart path, confirmed against real MinIO by the -N multipart suffix on the stored object's ETag. version-hint.text is covered by the same PUT. The If-Match sibling at the version-hint update is not a user-visible carrier: its caller catches and retries in a loop, and its documented contract is not to report hint-write failures, so a failure there costs a retry rather than a failed query. copyS3File never sets these headers and its recovery is left byte-identical, pinned by an unconditional control arm; LocalObjectStorage uses a temp file plus conditional rename with no request replay; HDFS refuses conditional writes. Azure has the same pattern behind a different SDK but retries neither 412 nor this case, so a landed conditional write is never replayed there; 0 occurrences in 120 days, disclosed and out of scope.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The input space here is the request and metadata shape rather than a type matrix, and every axis now has its own arm. Guard outcomes: token different, token key absent, object absent, and a failed HeadObject each throw the original error, fail closed. Error code: PreconditionFailed and NoSuchUpload each have an own-object arm and a foreign-object arm. Condition kind: If-None-Match mints a token so recovery is possible, while If-Match mints none and is therefore provably fail-closed, pinned by its own arm. Caller-supplied metadata present versus absent is covered by a dedicated arm plus the value_or path; conditional versus unconditional by two control arms; single-part versus multipart by the multipart arms.
h Backward compatible? Yes. No setting is added or changed, so no SettingsChangesHistory.cpp entry is needed. Object bytes are unchanged, verified against real MinIO: the metadata JSON other Iceberg engines read still parses and contains no token, which rides in x-amz-meta-clickhouse-write-token where an older server simply ignores it. Unconditional writes are byte-identical in behaviour and carry no token at all, also verified end to end. No format version to bump.
i Invariants and contracts preserved? The invariant at risk is the compare-and-swap: an object this request did not write must still fail the write. It is strengthened, not relaxed, and pinned by six arms (foreign and untokened and absent and HEAD-failure for the single-part guard, plus foreign-object arms for both multipart error codes) and by a thirteen-mutant matrix in which every fail-open weakening reddens its predicted arm, each redness checked for the right reason rather than for mere redness. write_token is const and set once in the constructor, so all retries of one buffer share one identity and no two buffers share one. Recovery takes the same return as an ordinary success, so finalizeImpl's check_objects_after_upload and the task-tracker accounting are reached exactly as before, and a recovered completion leaves no abort behind. The catch (...) cannot leak: it logs and returns false, so the original error is thrown and the user-visible message keeps its shape. No error is made retryable: a consumed upload id cannot succeed on a retry, so it is recognised, never retried.

Session id: cron:clickhouse-impl-slot-40:20260808-225000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @kssenii, could you review this? A conditional Iceberg metadata write is not idempotent, so a retry after a lost response hits its own object and fails with 412; the fix stamps a per-buffer token in S3 custom metadata and accepts a replay only against that token, and it also stops the NoSuchUpload recovery in S3::Client from reporting success over a foreign object on a conditional completion.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6e97697]

Summary: ✅


AI Review

Summary

This PR makes conditional Iceberg metadata writes on S3 fail closed but recover correctly when a successful write is replayed after a lost response, by tagging If-None-Match writes with per-buffer metadata and checking that token before accepting PreconditionFailed or conditional NO_SUCH_UPLOAD outcomes. After reviewing the current diff, the touched S3 write paths, the unchanged callers around Iceberg commits and CompleteMultipartUpload, the added unit coverage, and the current all-green CI, I did not find a blocker or major issue worth posting inline.

Final Verdict

No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 397/398 (99.75%) · 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 9, 2026
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6e97697

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.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks build-profile telemetry INSERT to the CI logs cluster; NON-GATING, the check itself concluded success #113409 (ours, merged)

No test-level failure on this head: all 32 executed checks concluded success (0 running, Finish Workflow success).

Session id: cron:our-pr-ci-monitor:20260809-230000

@alexey-milovidov alexey-milovidov left a comment

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.

That's nice.

@alexey-milovidov alexey-milovidov self-assigned this Aug 28, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 28, 2026
Merged via the queue into ClickHouse:master with commit 003d95f Aug 28, 2026
182 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
CheSema added a commit that referenced this pull request Sep 9, 2026
… went

Three pairs of multipart NO_SUCH_UPLOAD arms - If-None-Match, If-Match and
unconditional - existed to prove the is_conditional guard behaved for each. The
guard is gone: Client::CompleteMultipartUpload no longer reads IfMatchHasBeenSet
or IfNoneMatchHasBeenSet, so all three drove identical code and differed only in
a setting nothing looks at.

Dropped the pair this branch added rather than the one #113994 did. The
remaining If-None-Match pair still fails if the guard is ever reintroduced,
which is what caught it during the restructure.
PedroTadim pushed a commit to groeneai/ClickHouse that referenced this pull request Sep 21, 2026
…stence

Client::CompleteMultipartUpload rewrote NoSuchUpload to success whenever a
HeadObject found any object at the key. ClickHouse#56475 added that for a completion
whose response was lost, but existence at a key is not evidence of a replay:
an upload aborted between create and complete, against a key that already
held an object, was acknowledged with none of its rows stored.

This layer cannot tell the two apart. It sees only the part list, while
everything that identifies the write - metadata, storage class, encryption,
conditional headers - is set on CreateMultipartUpload one request earlier.
So the inference is removed, and NoSuchUpload is reported as it is.

Authorship is proven where it is known instead. Every multipart create now
carries the write token introduced by ClickHouse#113994, so the recovery that already
existed for conditional writes covers all of them. copyS3File gains the same
token and check. isObjectWrittenWithToken is shared by both. An unconditional
single-part PUT still carries no token: it cannot receive the 412 that would
read one back.

The GCS compose request moves out of the completion outcome into
Client::composeObjectAfterMultipartUpload, so a recovery that reports success
without a successful outcome still composes the object.

Closes: ClickHouse#114348
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 groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet 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.

3 participants