Skip to content

Prove multipart completion by write token, not by object existence - #118829

Merged
CheSema merged 22 commits into
masterfrom
s3-complete-multipart-recover-via-write-token
Sep 21, 2026
Merged

CheSema merged 22 commits into
masterfrom
s3-complete-multipart-recover-via-write-token

Conversation

@CheSema

@CheSema CheSema commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

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 silent data loss when writing to an S3 key that already holds an object, for example INSERT INTO FUNCTION s3(...) with s3_truncate_on_insert = 1. If the multipart upload was aborted between create and complete, for example by an AbortIncompleteMultipartUpload lifecycle rule, the NoSuchUpload error was rewritten to success whenever any object existed at the key. The INSERT was acknowledged while none of its rows were stored, and the previous object kept being served. Closes #114348.

Description

An unretryable write error leaves exactly one question: did an earlier attempt of this same write already land? Client::CompleteMultipartUpload answered it by asking whether any object sits at the key (#56475), which is not an answer — an upload aborted between create and complete over a pre-existing object looks identical. So NoSuchUpload became success, and an INSERT was acknowledged with none of its rows stored. MergeTree over S3 is unaffected: it writes unique random keys.

The fix marks each blob with a unique id — #113994's mechanism, until now minted only for conditional writes — and has the client compare it. One helper answers the question for both requests that can fail over an object they wrote themselves: PutObject on a 412, CompleteMultipartUpload on a 412 or NoSuchUpload. An ETag proves the payload; an id proves the writer, which is the difference from #114375.

Real proof also removes what compensated for the weak one — the is_conditional guard, a second implementation in copyS3File, the NO_SUCH_UPLOAD handling in WriteBufferFromS3 — and fixes three defects in the recovery HeadObject: missing from S3HeadObject and DiskS3HeadObject, running outside Expect404ResponseScope, and sliced down to the SDK's own request type by auto, bypassing the api mode, extra headers and region and URI overrides.

Cost: about 47 bytes of object metadata per object, x-amz-meta-clickhouse-idempotency-id.

Relationship to #119042

On ClickHouse Cloud on GCP, GCS discards custom object metadata unless it is spelled x-goog-meta-, so the id does not land on the object and the recovery is inactive there. That is fail-closed: the completion is not absorbed, the error reaches the caller, and the data loss this PR fixes stays fixed. #119042 is a separate change that makes GCS keep the metadata, so it turns the recovery on for GCP — it is not required for this PR.

Testing

  • test_complete_multi_part_upload_no_such_upload_keeps_prior_object — the reported scenario end to end. Fails on master, with a no-fault control, and pins the recovery HeadObject to one accounted request.
  • gtest_writebuffer_s3.cpp — absorb and refuse for single-part PutObject, multipart completion and copyDataToS3File, over an object that is ours, another write's, absent, or untokened. 83 pass locally.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

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

…stence

Client::CompleteMultipartUpload rewrote NoSuchUpload to success whenever a
HeadObject found any object at the key. #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 #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: #114348
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9e4e85c]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the real data-loss bug in S3 write recovery by proving authorship with a stamped id instead of treating mere object existence as success, and the new unit/integration coverage is much stronger than the original version. I did not find a new diff-local bug that needs a fresh inline comment, but one previously dismissed compatibility concern is still present in the current code.

Findings

⚠️ Majors

  • [src/IO/WriteBufferFromS3.cpp:120,421,745; src/IO/S3/copyS3File.cpp:126,155-157] [dismissed by author -- https://github.com/Prove multipart completion by write token, not by object existence #118829#discussion_r3960227883] Every WriteBufferFromS3 write now persists clickhouse-idempotency-id, and multipart copy does the same, even when the caller did not request any metadata change. s3(..., headers('x-amz-meta-*' = ...)) and IObjectStorage already let callers spend the provider's user-metadata budget, so this widens the extra 47-byte footprint from the recovery-critical cases to all buffered writes and multipart copies. The result is a real backward-compatibility regression for objects already close to the backend metadata cap: writes that used to succeed can now start failing only because this PR injected one more persisted header, and large copies also stop being metadata-neutral. Suggested fix: either move the proof out of persisted object metadata, or at least enforce the aggregate metadata budget where metadata is assembled so the failure is explicit and consistent across all writers.
Final Verdict

⚠️ Functionally the recovery fix looks sound, but I would not call this fully clear without an explicit maintainer decision on the persisted-metadata / metadata-budget regression above.

LLVM Coverage Report

Measured on commit 9e4e85c.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.70% +0.10%

Changed lines: Changed C/C++ lines covered: 402/404 (99.50%) · 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 8, 2026
Comment thread src/IO/WriteBufferFromS3.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 9e4e85c498dfeff4a6c8da93db8ea18dfa459f01 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_cou….

See the job log for details.

…e it for its purpose

The first version minted the id in the constructor for every write, so an
ordinary single-part PUT stamped it on the object and its 412 path issued a
HEAD that could never match. Nothing reads the id back there: an unconditional
PUT cannot legitimately receive a 412. The id is now minted where it is
stamped - in the constructor for a create-if-absent write, as before, and in
createMultipartUpload for every multipart upload. Single-part writes are
byte-identical to master again, which restores
SinglepartPutWithoutIfNoneMatchStillThrows.

Renamed clickhouse-write-token to clickhouse-idempotency-id, which says what
the value is for rather than what it is, and follows the clickhouse-request
naming already used for the one other ClickHouse-authored S3 header. "tag"
was rejected because multipart_tags (the part ETags) and ObjectInfo::tags (S3
object tagging) already mean other things in the code that reads the id back.

Shortened from 32 to 22 characters behind a named constant. getRandomASCIIString
draws from 26 letters, so that is about 103 bits, far past what distinguishing
the writers racing for one key needs, and it is spent from the object's
user-metadata budget.
Comment thread src/IO/WriteBufferFromS3.cpp Resolved
…e too

The idempotency id is stamped as custom object metadata, and GCS accepts the
S3 spelling of that header and silently discards it: an upload completes, the
id never lands, and the recovery can never fire. Measured against a real
bucket - `x-amz-meta-*` returns 200 and stores nothing, `x-goog-meta-*` stores
and is returned.

ClickHouse already had the translation, but only on CopyObjectRequest, where
#48981 added it in 2023 to fix GCS native copy. That fix needed
x-amz-copy-source, and collected metadata-directive, storage-class and
x-amz-meta-* alongside it because a copy that replaces metadata needs all four
to agree. Nothing extended it, because copy failed loudly while the others
fail silently.

So the rename moves out of CopyObjectRequest into translateHeadersToGCS,
applied by ExtendedRequest for every request type in ApiMode::GCS.
CopyObjectRequest keeps no override of its own. Of the four headers, only
storage-class and x-amz-meta-* can occur outside the copy path, and both were
being dropped there - so this also fixes storage_class_name, which has never
taken effect on GCS for ordinary writes.

The response needs the mirror: GCS answers with x-goog-meta-*, while the SDK
builds GetMetadata() only from x-amz-meta-* (HeadObjectResult.cpp). PocoHTTPClient
now adds the x-amz-meta- spelling alongside, which is inert on every store that
does not emit the GCS prefix.

Renaming after signing would invalidate SigV4, so note that this fires only in
ApiMode::GCS, where credentials are empty and authorization is a bearer token
set by PocoHTTPClientGCPOAuth. The signed interop path is never translated, and
does not need to be: GCS accepts and returns x-amz-meta-* there, measured.

SSE is deliberately left out. Its mapping is not a rename - S3 uses
x-amz-server-side-encryption plus a key id, GCS uses a single
x-goog-encryption-kms-key-name with a different value - so a prefix rename
would be ignored just as silently.
…omments

The response side had its own prefix rule, written at the point of use rather
than derived from what the request side renames. Both directions now read
GCS_TRANSLATED_HEADERS, so a name added to it is renamed going out and
recognised coming back, and the two cannot drift.

The mirror is slightly wider as a result: x-goog-storage-class is returned on
HEAD and is now aliased too, so GetStorageClass works on GCS. copy-source and
metadata-directive are request-only and inert on that side.

No behaviour change otherwise. Comments added earlier in this branch were
longer than what they explained; cut to the reason and no more.
Minting it only for object_storage_write_if_none_match left the single-part
If-Match path unrecoverable, while multipart already minted unconditionally.
So a CAS retry recovered or not depending on whether the file crossed the
multipart threshold - Iceberg advances version-hint.text with If-Match once the
file exists, and those payloads are far below it.

Minting for every write removes the split rather than adding a second
condition to keep in step. idempotency_id is const again,
metadataWithIdempotencyId drops its optional, and the lazy mint in
createMultipartUpload goes away with the mutable member and its thread-safety
note.

The cost is that every object ClickHouse writes now carries
x-amz-meta-clickhouse-idempotency-id, about 47 bytes of the 2 KB S3 allows for
user metadata, including on writes that never read it back.

Tests: SinglepartIfMatchPutRecoversLostResponse and its foreign-object
counterpart. SinglepartPutWithoutIfNoneMatchStillThrows keeps its intent - no
If-None-Match sent, 412 still thrown - but now what refuses the 412 is the id
at the key not matching rather than there being no id.
Comment thread src/IO/S3/copyS3File.cpp Resolved
Comment thread src/IO/S3/Requests.cpp Resolved
…mments

UploadHelper::completeMultipartUpload has its own id, its own NO_SUCH_UPLOAD
branch and its own authorship check - none of it shared with the write buffer -
and the only test driving that helper through completion injected InvalidPart.
So the branch that decides false-success versus throw, on the path backing
backups and server-side copies, had no coverage at all.

Two arms, mirroring the write-buffer pair. Verified load-bearing by mutation:
disabling the branch fails the absorb arm; dropping the authorship check, which
is the shape the bug had, fails both.

Also drops the "absent id" wording left over from when the id was minted
conditionally, and notes that the empty-id guard in isObjectWrittenWithIdempotencyId
is now unreachable from the writers.
@azat azat self-assigned this Sep 9, 2026
… fix

The table is the sole source of truth for the request rename and the response
alias, and the failure mode is a header silently lost, so a missed entry
regresses GCS writes with no CI signal.

The test is the one written for #119042, brought here so the two copies of
these files do not diverge. Writing it there caught a real defect that this
branch still carried: translateHeaderNameFromGCS lower-cased the prefix but
kept the suffix's case, so a server answering X-Goog-Meta-Foo produced the
metadata key "Foo" and no lookup found it. Fixed with the test that catches it.

Both files are now identical to #119042's, which is the copy to keep when one
of the two merges.
The earlier shape moved the recovery out of Client::CompleteMultipartUpload on
the grounds that the layer sees only the part list and so cannot tell an
aborted upload from a completion whose response was lost. That was the wrong
diagnosis: the problem was never the layer, it was the missing information.
CompleteMultipartUploadRequest is our own wrapper, so the id can simply be
handed down, and the check stops being an inference.

Client::CompleteMultipartUpload is then master's code with one added conjunct -
the object must carry the id this upload stamped - and the HEAD it already
performed carries that id in the result it was discarding, so it costs no extra
request.

What that deletes:

  - composeObjectAfterMultipartUpload and its two call sites; the outcome
    becomes success again, so the original compose block fires by itself
  - the whole recovery branch in copyS3File, which had its own error test and
    its own authorship call; it now just sets the id on the request
  - NO_SUCH_UPLOAD from WriteBufferFromS3, which keeps only PreconditionFailed
  - the is_conditional guard. It existed because the old test was mere
    existence, where an object may be the very one the condition meant to
    reject. An id proves authorship whether or not the request was conditional,
    so the guard was compensating for a weak proof and goes with it.

The four conditional-multipart tests caught that last point: they failed while
the guard was still in place.

IDEMPOTENCY_ID_METADATA_KEY and IDEMPOTENCY_ID_LENGTH move to Requests.h, next
to the request that carries the id. isObjectWrittenWithIdempotencyId stays for
the single-part 412 path, which has no HEAD of its own to read.
"Reads the id out of the HEAD it already performs" implied the client path does
no HEAD, next to a line saying the single-part one "costs its own". Both issue
exactly one, and neither adds a request master did not already send. The
distinction is only that the client has a HeadObjectResult in hand and the free
function does not, so say that and drop the cost framing.

Comment-only, no behaviour change.
… 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.
It was duplicated here so this branch could be reviewed and tested whole, and
it had grown to a third of the diff. #119042 owns it, on its own merits: GCS
discards custom object metadata under the x-amz- spelling regardless of this
change.

Requests.h keeps the idempotency id constants and the setter on
CompleteMultipartUploadRequest, which belong to this fix rather than to the
translation, so the two pull requests still touch that file for their own
reasons.

Until #119042 merges the recovery is inactive on GCS with OAuth - the id is
discarded, the completion reports its error, and the data loss stays fixed.
Fail-closed, as the description says.
Comment thread src/IO/S3/Client.cpp Resolved
…rt-recover-via-write-token

One conflict, in copyS3File.cpp: master added an upload_checksum_algorithm
member where this branch added idempotency_id. Adjacent, not overlapping - kept
both, and checked each is still wired at its call sites.
gtest_aws_s3_client asserts the exact SigV4 SignedHeaders list, and minting the
id for every write adds x-amz-meta-clickhouse-idempotency-id to it. Only the
four write cases move; reads set no metadata and are untouched.

Caught by CI: the workhost run of *WBS3* never covered this file.

@azat azat 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.

Overall looks good

Comment thread src/IO/S3/Client.cpp Resolved
Comment thread src/IO/WriteBufferFromS3.cpp Resolved
The comment justified the absence of master's is_conditional guard. A reader of
the current code has no guard to wonder about, and the rationale is already in
the commit that removed it.

Review: #118829 (comment)
…rt-recover-via-write-token

One conflict, in gtest_aws_s3_client.cpp: master removed the s3_disable_checksum
setting and with it AppendExtraSSECHeadersWriteDisableChecksum, which this branch
had edited to list the idempotency id among the signed headers. Took master's
side and dropped the test; the three surviving write tests keep that line.
Comment thread src/IO/tests/gtest_writebuffer_s3.cpp Resolved
…sends

`SinglepartIfMatchPutDoesNotMaskForeignObject` passed on a buffer that never
sent `If-Match`, because its injection failed every `PutObject` with 412 and
recorded only `If-None-Match`. The other `If-Match` arm was guarded by a
disjunction that accepted either conditional header, so it could not see a
value routed to the wrong one either.

Both single-part injections now record `If-Match` and `If-None-Match`, and
every single-part test asserts the exact pair its own mode is supposed to
send.

Review: #118829 (comment)
`CompleteMultipartUpload` sets the caller's `If-Match` the same way
`PutObject` does, and nothing reached it: all three `CompleteMPU` injections
read only `If-None-Match`, and no test paired a multipart write with the
replace mode.

Added the recovery arm and the foreign-object arm for that mode, and the
existing `If-None-Match` arms now assert `If-Match` is absent.

Review: #118829 (comment)

@azat azat 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.

One more thing, maybe make sense to fix in separate PR, we can improve regular INSERTs into s3() to avoid extra requests using If-None-Match: *

diff --git a/src/Storages/ObjectStorage/Utils.cpp b/src/Storages/ObjectStorage/Utils.cpp
index 475cddd66f6..da921921fd3 100644
--- a/src/Storages/ObjectStorage/Utils.cpp
+++ b/src/Storages/ObjectStorage/Utils.cpp
@@ -46,6 +46,7 @@ std::optional<String> checkAndGetNewFileOnInsertIfNeeded(
     size_t sequence_number)
 {
     if (settings.truncate_on_insert
+        /// FIXME: use object_storage_write_if_none_match = "*" instead
         || !object_storage.exists(StoredObject(key)))
         return std::nullopt;

Comment thread src/IO/WriteBufferFromS3.cpp Resolved
Comment thread src/IO/S3Common.h Resolved
Comment thread src/IO/WriteBufferFromS3.cpp Resolved
The rule that a failed write is a success only when the object carries this
writer's token lived in two layers, split by error code: the client resolved
NO_SUCH_UPLOAD for a multipart completion, while WriteBufferFromS3 resolved
PreconditionFailed for that same completion and for its single-part PUT, each
with a HEAD of its own.

The client now owns it for both requests. PutObjectRequest carries the token
the way CompleteMultipartUploadRequest already did, so Client::PutObject and
Client::CompleteMultipartUpload ask one private
Client::isObjectWrittenWithIdempotencyId. WriteBufferFromS3 is left stamping
the token and choosing the log level of the error it re-throws, which drops
isObjectWrittenByThisBuffer and, with it, isObjectWrittenWithIdempotencyId
from S3Common.

Behaviour and request count are unchanged; copyS3File gains the 412 arm but
sends no conditional headers, so it cannot reach it.

Review: #118829 (comment)
Review: #118829 (comment)
Review: #118829 (comment)
Three defects in the recovery HEAD, all of them older than this branch:

It incremented neither S3HeadObject nor DiskS3HeadObject, so the request was
absent from ProfileEvents and from every dashboard built on them.

It ran outside Expect404ResponseScope, so an absent object -- the normal
outcome when the write did not land -- was logged and counted as an error.

`auto check_request = HeadObjectRequest().WithBucket(...)` sliced our request
down to the SDK's, because WithBucket returns the base type. The call then
reached Aws::S3::S3Client::HeadObject and skipped the api mode, the extra
headers and the region and URI overrides this client exists to apply.

The integration test now reads ProfileEvents['S3HeadObject'] from the
query_log for the recovering INSERT and for its no-fault control: one
accounted request against none. Removing the increments fails it with 0 == 1.
Comment thread src/IO/S3/Client.cpp Resolved
Comment thread src/IO/WriteBufferFromS3.h Resolved
Comment thread src/IO/S3/Client.cpp Resolved
@azat

azat commented Sep 17, 2026

Copy link
Copy Markdown
Member

BTW it still contains verbose comments that can be trimmed (as well as PR description)

CheSema and others added 3 commits September 18, 2026 11:45
… found

Halves the comments this branch adds to src/IO, 39 lines to 17, keeping the ones
that carry a trap or a contract and dropping the ones that restated the diff:
the six-line replay rationale in `Client::CompleteMultipartUpload`, its
three-line twin in `Client::PutObject`, and the "metadata lands on the completed
object" line that sat in two files. The id-length comment now names the alphabet
it counts, `a`-`z`, rather than sending the reader to look it up.

A failed proof now logs at warning level only when the completion reported
NO_SUCH_UPLOAD, where the upload is gone and its rows were never stored. A 412
stays at info: a conditional write losing the race for a key is ordinary control
flow, and `makeSinglepartUpload` already logs that case at info rather than
error, deliberately. The parameter selecting this is named for its effect,
`warn_if_unproven`, and the reason sits at the call site that decides it.

Also drops the line that announced an unproven completion. The helper already
reports why the proof failed, and the caller logs and throws the error it gets
back, so that was the third report of one event.

Review: #118829 (comment)
Review: #118829 (comment)
The comment guarding the HeadObject request construction explained object
slicing and overload resolution in two lines. What a reader needs is the one
line that stops them writing the builder form, so it says that instead.
@CheSema
CheSema added this pull request to the merge queue Sep 21, 2026
Merged via the queue into master with commit 37a669a Sep 21, 2026
175 of 177 checks passed
@CheSema
CheSema deleted the s3-complete-multipart-recover-via-write-token branch September 21, 2026 10:04
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 21, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 3, 2026
Master (ClickHouse#118829) moved the proof of a replayed write from WriteBufferFromS3 into S3::Client::PutObject
and S3::Client::CompleteMultipartUpload, and renamed the stamped metadata key to
clickhouse-idempotency-id. Those two sites recognised the refusal by the AWS exception name only, so
the status-based recognition this branch adds for endpoints that spell the 412 code their own way
(GCS, once the fence is expressed) moves with them: isRefusedPrecondition is now S3::isRefusedPrecondition,
defined in Client.cpp and used at both client-level replay checks and at the WriteBufferFromS3
naming sites. The tests this branch added use master's metadata key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 11, 2026
Drop the early-error-response part (`HTTPClientSession` and `PocoHTTPClient` changes,
the `early` mode of the `no_such_upload` mock and its test): the mock action it extends
comes from #118829, which is not on 26.9, and
#130514 replaces this approach on master with
`Expect: 100-continue`. What remains is fe7dab9 (no outer retry of an error the SDK
has already retried), the same tree as the resolution proposed and tested by groeneai.

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

comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. 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.

S3 multipart complete: a NoSuchUpload is rewritten to success on key existence alone, silently losing an acknowledged fixed-key INSERT

4 participants