Repository navigation
Prove multipart completion by write token, not by object existence - #118829
Conversation
…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
|
Workflow [PR], commit [9e4e85c] Summary: ❌
AI ReviewSummaryThis 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
Final VerdictLLVM Coverage ReportMeasured on commit 9e4e85c.
Changed lines: Changed C/C++ lines covered: 402/404 (99.50%) · Uncovered code |
Build profile diff (arm_release)Comparing commit 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.
…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.
…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.
… 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.
…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.
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.
…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
left a comment
There was a problem hiding this comment.
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;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.
|
BTW it still contains verbose comments that can be trimmed (as well as PR description) |
… 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.
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]>
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]>
Changelog category (leave one):
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(...)withs3_truncate_on_insert = 1. If the multipart upload was aborted between create and complete, for example by anAbortIncompleteMultipartUploadlifecycle rule, theNoSuchUploaderror was rewritten to success whenever any object existed at the key. TheINSERTwas 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::CompleteMultipartUploadanswered 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. SoNoSuchUploadbecame success, and anINSERTwas 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:
PutObjecton a 412,CompleteMultipartUploadon a 412 orNoSuchUpload. 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_conditionalguard, a second implementation incopyS3File, theNO_SUCH_UPLOADhandling inWriteBufferFromS3— and fixes three defects in the recoveryHeadObject: missing fromS3HeadObjectandDiskS3HeadObject, running outsideExpect404ResponseScope, and sliced down to the SDK's own request type byauto, 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 recoveryHeadObjectto one accounted request.gtest_writebuffer_s3.cpp— absorb and refuse for single-partPutObject, multipart completion andcopyDataToS3File, over an object that is ours, another write's, absent, or untokened. 83 pass locally.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/118829]
Version info
26.10.1.335-master(included in26.10and later)