Skip to content

Do not treat an existing object as proof that a multipart upload completed - #114375

Closed
groeneai wants to merge 25 commits into
ClickHouse:masterfrom
groeneai:s3-complete-mpu-verify-etag-before-absorbing-nosuchupload
Closed

groeneai wants to merge 25 commits into
ClickHouse:masterfrom
groeneai:s3-complete-mpu-verify-etag-before-absorbing-nosuchupload

Conversation

@groeneai

@groeneai groeneai commented Aug 11, 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 silent data loss when writing to a fixed 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, CompleteMultipartUpload correctly returned NoSuchUpload, but the error was rewritten to success whenever any object existed at the key, so the INSERT was acknowledged while none of its rows were stored and the previous object kept being served. The error is now only absorbed when the object at the key is the one the upload would have produced. Closes #114348.

Description

Requested by @ zlareb1 in #114348 (comment).

Client::CompleteMultipartUpload absorbs NoSuchUpload if a HeadObject finds any object at the key.
That check is from #56475, whose premise is a completion that succeeded and whose response was lost -
i.e. the completion was replayed and the object is this upload's. Key existence tests neither, so a
genuinely aborted upload against a key holding an unrelated object also passes, and the INSERT is
acknowledged with none of its rows stored. NO_SUCH_UPLOAD is unretryable and excluded from
isTransientCompleteMultipartUploadError, so this rewrite is the only thing between the abort and a
silent success. MergeTree over S3 is unaffected: it writes random unique keys.

The rewrite now requires the object to carry the ETag implied by the request's own part list,
md5(concat(binary md5 of each part))-<N>. No extra request, no new state, and both callers
(WriteBufferFromS3, copyS3File) are fixed at once. It fails closed: when the ETag does not match or
is not derivable - SSE-KMS, a non-default checksum algorithm, S3 Express, a provider that computes it
differently - the original error is returned, so a replay that used to be absorbed now errors. A failed
INSERT is recoverable; a silently discarded one is not.

A matching ETag proves the payload, not the create-time attributes: a completion may also carry
If-Match / If-None-Match, and CreateMultipartUpload may carry metadata or a storage class, which
this layer cannot observe. That residual is pre-existing, strictly less reachable here, and unset on the
in-tree S3 multipart paths. #113994 addresses it in WriteBufferFromS3, which knows the writer identity.

A new integration test fails on master (INSERT acknowledged, old object survives) and passes here, with a
no-fault control. Two unit tests keep #56475 honest: a matching object is absorbed, a foreign one errors.

cc @ scanhex12 @ kssenii @ CheSema


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

…leted

Client::CompleteMultipartUpload absorbed a NoSuchUpload error whenever a
HeadObject found any object at the target key. That recheck comes from ClickHouse#56475,
whose premise is a completion that already succeeded and whose response was
lost. The premise has two conjuncts: the completion was replayed, and the
object at the key is the one this upload produced. Key existence tests neither,
so it also admits a genuinely aborted upload against a key that already holds
an unrelated object, for example an s3() INSERT with s3_truncate_on_insert=1
whose upload an AbortIncompleteMultipartUpload lifecycle rule cancelled. The
INSERT was then acknowledged with none of its rows stored and the prior object
kept being served. NO_SUCH_UPLOAD is unretryable and excluded from
isTransientCompleteMultipartUploadError, so this rewrite was the only thing
standing between the abort and a silent success. MergeTree over S3 was
unaffected because it writes random unique keys.

Require the object at the key to carry the ETag implied by the part list in the
request itself, md5(concat(binary md5 of each part))-N. That needs no extra
request and no new state, and fixing it in the client covers both callers
(WriteBufferFromS3 and copyS3File) without touching either. It fails closed:
when the ETag does not match, or is not derivable, the original error is
returned so the INSERT fails and can be retried. The ETag is a sufficient but
not a necessary proof, since SSE-KMS and non-default checksum algorithms change
its shape, so in those setups a benign replay now returns a retryable error
instead of silently accepting a possibly foreign object. A failed INSERT is
recoverable; a silently discarded one is not.

Both operands need unquoting: the SDK stores the etag header verbatim for the
HEAD result and for each uploaded part, so the quotes are present on both sides,
and HashingUtils::HexDecode asserts on non-hex input.

The integration test injects an unforwarded NoSuchUpload on the completion via a
new inert-by-default broken_s3 hook, and asserts the INSERT fails and the prior
object survives; a no-fault control arm proves the fixture really does perform a
multipart upload. Two unit tests keep ClickHouse#56475 honest in both directions: a
matching object is still absorbed, a foreign one still errors. The gtest mock
had to be taught real MD5 ETags first, otherwise both would have passed through
the fail-closed branch and proved nothing.

Closes: ClickHouse#114348
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 findings, all disagreed with evidence)

A second model reviewed this diff cold. All three findings are answered below; none changed the code.

⚠️ NoSuchUpload can still be absorbed for a conditional completion if a foreign object happens to have byte-identical content — disagreed. This change is condition-agnostic and only adds conjuncts to the absorb predicate, so its absorb set is a strict subset of master's: for any request it can only turn an absorb into an error, never the reverse. The residual is pre-existing and strictly less reachable after this PR. The conditional half is #113994, which adds the is_conditional skip and a per-upload authorship token on these same lines; duplicating it here would conflict with it. The only in-tree setter of these conditions is Iceberg writeMessageToFile, whose payloads (a metadata JSON, a version number) are far below the 32 MiB single-part threshold, so the multipart path is not reached there.

⚠️ The unit arms use one part, so they would pass a first-digest-only or hardcoded -1 implementation — disagreed. The formula was verified against a real MinIO server at N=2 before the helper was written: two unequal parts produced 37bd1b728bc3436623f0eb643525a6da-2, matching the derived value, which a first-digest-only or hardcoded-suffix implementation contradicts. The requested opaque-part-ETag arm is the mock's own pre-change state: it minted non-MD5 part ETags, and both new arms were measured to fall through the fail-closed path, which is why the mock had to be taught real MD5 ETags. The absorb arm's non-vacuity is measured separately (corrupting the stored composite turns it red in both sync and async modes).

💡 Use Critical Bug Fix and move the relationship lines out of the template comment — disagreed. Critical Bug Fix is reserved for cases a senior maintainer explicitly asks for. The relationship lines sit inside the leading comment block because that is where the upstream PULL_REQUEST_TEMPLATE.md puts them; the issue link renders separately in the changelog entry and in the description.

One reviewer nit was applied to this description: the not-derivable cases now also name S3 Express and providers that compute the ETag differently, not just SSE-KMS and non-default checksum algorithms.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. test_checking_s3_blobs_paranoid/test.py::test_complete_multi_part_upload_no_such_upload_keeps_prior_object fails 100% on unpatched master and passes 10/10 with the fix (--count 10 --random-order). Not probabilistic.
b Root cause explained? #56475's premise is a replayed completion whose response was lost, which requires both that the completion was replayed and that the object at the key is this upload's. The implemented test checks only "some object exists", which is also true of an unrelated prior object, so a genuinely aborted upload is accepted. NO_SUCH_UPLOAD is unretryable and excluded from isTransientCompleteMultipartUploadError, so this rewrite is the only guard on that path.
c Fix matches root cause? Yes: it supplies the missing conjunct at the site that makes the wrong inference, proving via the request's own part list that the object is this upload's. Not a widened bound, not a guard at a downstream site, and not a revert of #56475 (see d/e).
d Test intent preserved / new tests added? No existing assertion weakened. Three new tests: one integration (the reported scenario) and two unit tests that pin #56475's benign-replay behaviour in both directions. The gtest mock now mints real MD5 ETags instead of synthetic ids; nothing asserted on the old values.
e Both directions demonstrated? Yes, at both levels, on Build-ID-verified binaries (base 30c190fc…, fix 2c40e0ae…). Integration: unpatched → Client expected to be failed but succeeded! (the data loss), patched → INSERT errors and the key still reads 0 NEW / 100 OLD. Unit: …ForForeignObject throws nothing on master, throws with the fix. Plus a no-fault control landing 900 NEW / 0 OLD, so the faulted assertion is not vacuous.
f Fix is general across code paths? Fixed in S3::Client, so both callers (WriteBufferFromS3::completeMultipartUpload, copyS3File) are covered without touching either; both already build the full part list. Ten carriers swept: Azure's analogue correctly throws and is not the anti-pattern; the GCS compose block is success-gated so a fail-closed outcome skips it; NO_SUCH_UPLOAD deliberately not added to the transient set, since retrying an aborted upload cannot succeed.
g Fix generalizes across inputs (params/datatypes/wrappers)? Part counts N=1 and N=2 verified against a real server before writing the helper. Empty part list, a non-MD5 part ETag (SSE-KMS, non-default checksum algorithms), and quoted vs unquoted ETags on either operand are all handled; every unprovable case fails closed. S3-Express attaches CRC32 to parts without changing the part ETag field, so the proof still applies there.
h Backward compatible? (maintainer-approved exception only) No new or changed setting, no serialization or format change, so no SettingsChangesHistory.cpp entry. One intended behaviour change, stated in the PR description: where the ETag is not derivable, a replay that used to be absorbed now returns a retryable error instead of silently accepting a possibly foreign object.
i Invariants and contracts preserved? The contract is unchanged on every path except the NoSuchUpload branch. No new state, no lock, no allocation held across the request, and the HeadObject was already there. On the fail-closed path the original outcome is returned untouched, and GetResult() is only read after IsSuccess().

Session id: cron:clickhouse-impl-slot-7:20260811-175500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @CheSema, could you review this? Client::CompleteMultipartUpload absorbed NoSuchUpload whenever a HeadObject found any object at the key, but #56475's premise is a replayed completion, which also requires the object to be the one that upload produced; on a fixed key holding a prior object an aborted upload was therefore acknowledged with none of its rows stored. It now absorbs only when the object carries the ETag the request's own part list implies, and fails closed otherwise.

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

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b70db34]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR hardens CompleteMultipartUpload recovery so NoSuchUpload is only absorbed when the key can be proven to hold this upload's object, and the current head fixes the earlier ETag, Content-Type, and mixed-case header gaps. One new exemption in hasExtraHeadersRequiringFullWriteIdentity is still too broad, though: it treats every non-x-amz-* access_header as auth-only, which can reopen the same false-success path for supported conditional header names.

Findings

❌ Blockers

  • [src/IO/S3/Client.cpp:286] The new access_header exemption is carrier-based instead of semantics-based. access_header is documented and accepted as an arbitrary HTTP header, so non-x-amz-* names like If-Match / If-None-Match still go out on the wire, but they no longer trip either requiresFullWriteIdentity() or the is_conditional guard. A lost CompleteMultipartUpload response can therefore still be rewritten to success on an ETag / Content-Type match even though the write was conditional and the object may belong to a different write.
    Suggested fix: do not exempt the whole non-x-amz-* access_header namespace. Either whitelist only headers proven auth/transport-only, or keep fail-closed behavior for standard conditional/object-attribute names carried through access_header.
Tests
  • ⚠️ Add a focused multipart regression with an access_header carrying If-None-Match: * or If-Match. The current suite only proves custom-auth-token and x-amz-tagging, so it does not cover the supported non-x-amz-* conditional-header case that this exemption changes.
Final Verdict

❌ Changes requested. The main multipart-recovery fix is solid, but the new non-x-amz-* access_header exemption is still broad enough to reopen false-success on a supported header surface.

LLVM Coverage Report

Measured on commit b70db34.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 407/416 (97.84%) · 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 12, 2026
Comment thread src/IO/S3/Client.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 46977830461eeb48f2ce38a4e64a1e13ee9ba0d5

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.

CI finished with no failing checks on this head (155 success, 20 skipped, praktika top-level OK,
0 dropped jobs), so there is nothing to own.

Check / test Reason Owner / fixing PR
(none) - -
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260812-050000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for 4697783

CI is fully finished on this head (175 leaves, praktika top-level OK, 0 dropped jobs). No failures to own.

Check / test Reason Owner / fixing PR
— no failing check —

The 73 CIDB FAIL rows on this head are all on Bugfix validation (integration tests, amd64/aarch64) for test_checking_s3_blobs_paranoid, plus one Build (arm_release) / Post Hooks row. Every one of those jobs concluded success - the Bugfix-validation rows are the expected "must fail on master HEAD" half of the contract, and the Post Hooks row is bookkeeping on a passing check.

This supersedes my 05:17Z ledger comment on this PR, whose heading carried a 40-char SHA that does not exist (a 16-char prefix of this head padded out instead of read from headRefOid). The head itself was and is green; only that heading was wrong.

Session id: cron:our-pr-ci-monitor:20260812-163000

@alexey-milovidov alexey-milovidov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 17, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Fantastic finding! Thank you!

Comment thread src/IO/tests/gtest_writebuffer_s3.cpp Resolved

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

Everything else LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
Renames the two injection models, the two test cases and the object keys
introduced here so they do not abbreviate MultipartUpload. Test identifiers
only; no behaviour change.

Requested by alexey-milovidov in review of ClickHouse#114375.
@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2cbcab437 with master 60f0a24d7 (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

21 object files changed (+34.55 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/IO/S3/Client.cpp.o 1.24 MiB 1.27 MiB +26.44 KiB (+2.08%)

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

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

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +47.0 s (+7%) in total before that adjustment.

Job report

@CheSema CheSema self-assigned this Aug 17, 2026
@groeneai

groeneai commented Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 555331e

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 abstention: submodule state differs between the merge-base and the checkout a fix task owns the harness gap (fixing PR link to follow on this PR)

That job reports ERROR while its own message says the result is "inconclusive - NOT a
reproduction or a refutation": it must build a before-binary at the merge-base, but the
before-worktree can only be populated with the primary checkout's submodule content. This diff
touches 4 files, 0 submodules and 0 .gitmodules, so the second arm of the job's own explanation
applies - the base branch moved a submodule after the branch split (.gitmodules, contrib/AMQP-CPP,
contrib/llvm-project, contrib/musl, contrib/orc, contrib/silk, contrib/simdjson). Base rate
is 58 rows across 31 distinct PRs in 7 days, so it is harness-wide rather than specific to this branch.

Both Bugfix validation (integration tests, *) jobs are green (check_status = success,
praktika info = Failures: 36/37): for that job class the failing rows are the proof the bug
reproduces on the pre-fix binary, which is its success condition. The four skipped checks are
legitimate no-ops ("No relevant tests found for targeted AST fuzzer", "No failed tests found from
previous runs"), each with Post Hooks OK.

Session id: cron:our-pr-ci-monitor:20260817-113000

Comment thread src/IO/S3/Client.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0aba0e7

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
AST fuzzer (amd_debug) / STID 2467-2c2d Reading from materialized CTE before its materialization completed - DelayedPortsProcessor gate is missing in the query plan pre-existing trunk defect, not caused by this diff (11 failures on the true master line in 90 days; this PR touches only S3 multipart upload code, no planner or CTE code) #113489 (mine, open)

Session id: cron:our-pr-ci-monitor:20260818-200000

Comment thread src/IO/S3/Client.cpp Resolved
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Build (arm_tidy) is red at 27a5654b and it is gating the rest of the run: 27 of the 29 Build* nodes were skipped, so 165 checks never ran. The 3.4 MB log has exactly one diagnostic:

src/IO/tests/gtest_writebuffer_s3.cpp:1227:13: error: passing result of std::move() as a const
reference argument; no move will actually happen [performance-move-const-arg,-warnings-as-errors]

copyDataToS3File takes const std::optional<ObjectAttributes> & (copyS3File.h:94), so the move at that call site cannot happen and -Werror rejects it. Dropping the std::move on that one line clears it. The failing translation unit is 17574 of 17612 and nothing else in the log fails, so the rest of the build had already succeeded.

I have not pushed, since you own every commit at head. I can push just that one-token change if you want it.

Comment thread src/IO/S3/Client.cpp Resolved
…identity gate

The AI review flagged that treating every configured extra header as write
identity regressed benign replay recovery on requester-pays buckets:
`headers('x-amz-request-payer' = 'requester')` must be sent on every request
but does not change which object a successful completion produces, yet it made
every lost completion response surface `NoSuchUpload`.

`hasExtraHeadersRequiringFullWriteIdentity` now exempts `x-amz-request-payer`
and `x-amz-expected-bucket-owner` (case-insensitive); any other extra header
still fails closed. New regression arms prove the replay is absorbed with
those headers configured, on both the `WriteBufferFromS3` path and the
`copyS3File` path, while the foreign-header arm keeps throwing.
…ify-etag-before-absorbing-nosuchupload

# Conflicts:
#	src/IO/S3/Client.cpp
#	src/IO/tests/gtest_writebuffer_s3.cpp
…gning

`PocoHTTPClient` replays `client_configuration.extra_headers` onto the Poco request after the SDK has
signed it, skipping anything that starts with `x-amz-` because those are already in the canonical
header list. That test was literal, while every surface that accepts the header name keeps its case:
`headers(...)` stores it verbatim and `HTTPHeaderFilter::checkAndNormalizeHeaders` does not lowercase
it. `CompleteMultipartUploadRequest` / `UploadPartRequest` drop create-only headers case-insensitively
in `SetAdditionalCustomHeaderValue`, so a spelling such as `X-Amz-Meta-Write-Id` was dropped from the
request and then added back on the wire, unsigned, by this loop.

Use the same case-insensitive comparison the classifier and the canonical header selection already
use, and cover it with a regression that goes through the real `PocoHTTPClient` against a capturing
endpoint rather than through `MockS3::Client`.

Reverting the one-line change turns `DoesNotReplayMixedCaseAmzHeaderAfterSigning` red; the other three
arms (lowercase spelling, an already signed header, a non `x-amz-` header) stay green either way.
…a-headers test

`Build (arm_tidy)` failed on `head.find("\r\n\r\n") == std::string::npos`;
use `head.contains` instead.
@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Sep 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (6683afc6a939, clean, no conflicts) to pull in the fixes for the two unrelated reds on 15ada7378164: the Bugfix validation master-build lookup (#117580) and the toYYYYMM docs example that rolled over on 2026-09-01. unit_tests_dbms builds and 77/77 of the S3 completion-recovery / PocoHTTPClient tests pass locally after the merge.

The remaining red, Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6), was Container memory budget exceeded (/docker), a fleet-wide resource guard rather than a test failure. @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114375&sha=15ada737816472a19402079bc996696ecc0e6e67&name_0=PR&name_1=Integration%20tests%20(amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/IO/S3/Client.cpp Resolved
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

🕵 Investigated that Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) red on 15ada7378164. It is already fixed in master: the two PRs that close it merged after that job ran, and your 6683afc6a939 merge is what picks them up. No separate PR from me is needed.

What the job reported. All 1261 test rows are OK or SKIPPED, and the only failure is the job-level guard row, so the /docker cgroup leaf was breached rather than a test failing. dmesg carries six CONSTRAINT_MEMCG kills on oom_memcg=.../docker, with the leaf peaking at 40.78 GiB of its 40.78 GiB cap:

time (UTC) victim anon-rss
07:31:35 gdb 3.78 GiB
07:31:44 gdb 2.57 GiB
07:31:52 gdb 3.19 GiB
07:33:09 clickhouse 2.56 GiB
07:34:04 clickhouse 2.43 GiB
07:34:43 clickhouse 2.06 GiB

This is not the gdb attach fan-out. oom_reaper reaped 260447 at 07:31:38 and 261206 at 07:31:46, each before the next victim was chosen, 9 s and 8 s apart, so the attaches did not overlap. #117202 was already in this tree (7fc3004ed25a is an ancestor of 15ada7378164) and its job-wide flock on the repository mount held. No single 2 to 4 GiB victim explains a 40.78 GiB breach either: the leaf was already full of resident containers and the kernel just picked the largest task in it. peak == cap is also the steady state on green runs of this shard, so that line alone is not a signal.

Fix presence in the tested tree. It was missing exactly the two changes that size and depopulate that leaf:

owner merged in 15ada7378164 in 6683afc6a939
#117202, shutdown gdb serialization 2026-08-31 11:05Z yes yes
#117412, nested container budget 2026-09-01 11:31Z no yes
#117564, module-scoped cluster teardown 2026-09-03 13:07Z no yes

The job started 2026-09-01 06:38Z, roughly 5 h before #117412 merged and 2 days before #117564.

Fleet-wide incidence confirms those two are the fix, counting distinct trees carrying the guard row on this shard:

day trees tested trees with the guard row
08-31 543 311
09-01 492 214
09-02 469 76
09-03 545 52
09-04 503 0
09-05 364 1
09-06 91 0

The step down on 09-02 follows #117412 and the drop to zero on 09-04 follows #117564. The one row since is e52b2c3845a8, whose base predates both, so it is a pre-fix tail rather than a live occurrence. The guard row itself only starts being reported on 08-30 (6 trees fleet-wide that day), so earlier days are not comparable.

So: #117412 and #117564, both merged, both now on this branch through your merge. The re-run on 6683afc6a939 is the check.

…e-identity gate

`hasExtraHeadersRequiringFullWriteIdentity` treated every `client_configuration.extra_headers`
entry except `x-amz-request-payer` / `x-amz-expected-bucket-owner` as object identity, and
`S3AuthSettings::getHeaders` merges the documented `access_header` entries into that same vector.
On a header-authenticated endpoint that turned off the `NoSuchUpload` replay recovery entirely, so
a merely lost completion response reported `NoSuchUpload` for an object that was in fact stored.

`access_header` provenance is now preserved: `S3AuthSettings::getMergedAccessHeaders` reports the
entries `getHeaders` actually merged, `getClient` puts them in the new
`PocoHTTPClientConfiguration::access_headers` (the wire path still sends the merged
`extra_headers`, unchanged), and the gate exempts a header carried by that list. The exemption
stops at the `x-amz-` namespace: an `access_header` may name any header, and `x-amz-` is where S3
puts the ones that do change the stored object (metadata, tagging, storage class, encryption,
checksums), so those still fail closed.

Adds `CompleteMultipartUploadAbsorbsNoSuchUploadWithAccessHeader`,
`CompleteMultipartUploadReportsNoSuchUploadWhenAccessHeaderIsAMZHeader` and
`CopyS3FileCompletionRecoveryTest.AbsorbsNoSuchUploadWithAccessHeader`.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the AI review's "Changes requested" Major on hasExtraHeadersRequiringFullWriteIdentity — the access_header carrier is now told apart from generic header / headers(...) entries and exempted from the full-write-identity gate (except inside the x-amz- namespace, where a header can change the stored object). Details and the three new regression arms are on the thread. Merged master on top (clean, no conflicts, no submodule gitlink drift) and pushed 2cbcab437418. unit_tests_dbms builds; 82/82 of *CopyS3FileCompletionRecovery*:*WBS3*:*PocoHTTPClient* pass locally, and the new absorb arms were verified non-vacuous by deleting the exemption line.

CI on 6683afc6a939 had one red, Stateless tests (arm_asan_ubsan, azure, sequential), with two failures, both unrelated to this diff (it touches only S3 multipart upload code) and both labelled flaky by the harness after failing 0 out of 3 reruns:

Test Reason
04648_distributed_plan_task_error_propagation CANNOT_SCHEDULE_TASK not raised on the expected query
04340_distributed_plan_status_reenqueue_fault reenqueue fault handled: 0 — the injected fault was not observed in system.text_log

Neither has a tracking issue. #118417 ("Report a distributed plan's root cause, not its exchange teardown error") is open and touches the first area but is not a fix for the flakiness.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114375&sha=6683afc6a93947314062824c0c764dbffdb3c318&name_0=PR&name_1=Stateless%20tests%20(arm_asan_ubsan%2C%20azure%2C%20sequential) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Investigated. The two rows are one cascade, and it recurred on the new head: in Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, selected tests) on 2cbcab437418, 04648 failed with Expected server error code: 439 but got: 1000 ... Failed to receive final_result__0_0 from 127.0.0.1:9223, peer closed connection, and 04340 with reenqueue fault handled: 0 instead of 1. Fleet-wide over the last 48 hours: 38 failures of 04648, 11 of them on master, across 25 PRs and 6 lanes; 29 of 04340, 8 on master, across 20 PRs and 3 lanes.

The chain, within one job:

  1. ReadFromDistributedPlanSource::tryGenerate runs cleanupLocked before it rethrows. The cleanup closes this query's own exchange sockets, and PipelineExecutor reports the first node in graph order that holds an exception, so Code: 1000 ... peer closed connection replaces the recorded CANNOT_SCHEDULE_TASK. That is 04648.
  2. tests/clickhouse-test:3904 runs the .sql with --multiquery and no --ignore-error, and ClientBase.cpp:3722 stops the file at the unexpected error, so the next line, SYSTEM DISABLE FAILPOINT distributed_plan_record_failure_while_starting_tasks, never runs. That fail point is REGULAR on master (src/Common/FailPoint.cpp:360), i.e. armed process-wide until disabled.
  3. It then fires inside for (const auto & task : stage.tasks) in DistributedPlanExecutor::startStage (:1765), before any task of 04340's query is dispatched, so checkCancelled throws with no status poll and no TaskTracker::recordFailure line. That is 04340's 0.

The fix is in progress and does not need a new PR. Three are open, any one of which clears both rows, and none is merged, so 2cbcab437418 carries none:

PR What it removes
#118417 (yours) both halves: the rethrow ordering, and ONCE(distributed_plan_record_failure_while_starting_tasks) disarms the fail point after its single trigger, so an aborted file cannot leak it
#118390 (mine, open) the same 439 to 1000 substitution at the exchange source: rethrowIfFailed surfaces the plan's recorded failure before the socket error is rethrown
#105942 (@ Diskein, approved 2026-06-01) the class: the runner resets enabled fail points after each no-parallel test

On the harness labels: 04340 is the victim, and --diagnose-random-settings replays it without 04648 in front of it, so it cannot redden alone (4 of 4 reruns passed). 04648 does reproduce alone, at 2 of 35 reruns on this head.

Same two rows came up on #115528 seventeen minutes later, so that thread has the same answer rather than a second investigation.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master on top (clean, no conflicts, no submodule gitlink drift) and pushed b70db34b8262. unit_tests_dbms builds incrementally and 82/82 of *CopyS3FileCompletionRecovery*:*WBS3*:*CompleteMultipartUpload*:*PocoHTTPClient* pass locally after the merge. No code change was needed: 0 unresolved review threads, the AI review's final verdict on 2cbcab43 is "✅ No further findings on the current head", and the pull request is approved.

CI on 2cbcab437418 had one real red, Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, selected tests), with the same two distributed-plan tests as the previous run — this time on amd rather than arm, which is what prompted a closer look. They are failing fleet-wide, on master itself (pull_request_number = 0) and on dozens of unrelated pull requests, in bulk since 2026-09-06:

Test Failures (30 days, master + PRs based on master) Distinct PRs Rerun verdict
04648_distributed_plan_task_error_propagation 49 31 flaky, 2/35 reruns failed
04340_distributed_plan_status_reenqueue_fault 44 25 not reproducible, 0/4 reruns failed

04648 expects CANNOT_SCHEDULE_TASK but the exchange teardown wins the race and the client sees Net Exception: Failed to receive final_result__0_0 ..., peer closed connection. (POCO_EXCEPTION); 04340 reports reenqueue fault handled: 0 because the injected fault is not observed in system.text_log. This diff only touches S3 multipart-upload code, so neither can be caused by it.

There was no tracking issue for either, so I filed one with the evidence: #118626

Finish Workflow / new_tests_check.py was pure collateral — the stateless red dropped both Bugfix validation (integration tests, *) jobs, so no per-arch validation could report OK:

Bugfix validation (integration tests, amd64): DROPPED (Dropped due to previous failure [Stateless tests (amd_asan_ubsan, ...)])
Bugfix validation (integration tests, aarch64): DROPPED (...)
A bug fix is validated when at least one per-arch Bugfix validation job reports OK or XFAIL; none did.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114375&sha=2cbcab437418d395ea30d9be5dc25d1ea4199679&name_0=PR&name_1=Stateless%20tests%20(amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20sequential%2C%20selected%20tests) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/IO/S3/Client.cpp
/// namespace, though -- that is where S3 puts the headers which do change the stored
/// object (metadata, tagging, storage class, encryption, checksums), and an
/// `access_header` is free to name any header at all.
if (!isAMZHeader(header.name) && isAccessHeader(header.name))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

access_header is still an arbitrary header carrier here, not a typed auth-only field: registerStorageObjectStorage documents it as "adds specified HTTP header", and HTTPHeaderFilter does not constrain the header name. Exempting every non-x-amz-* access_header therefore reopens the same hole for standard conditional headers like If-Match / If-None-Match.

Those headers still go out on the wire through PocoHTTPClient (src/IO/S3/PocoHTTPClient.cpp:602-615), but they never set request.IfMatchHasBeenSet() / IfNoneMatchHasBeenSet() in CompleteMultipartUpload (src/IO/S3/Client.cpp:640-647). So a header-authenticated endpoint configured with access_header = If-None-Match: * can still rewrite NoSuchUpload to success on an ETag / Content-Type match, even though the completion was conditional and the object may belong to a different write. I think this exemption needs to stay fail-closed for standard conditional/object-attribute names, or be tightened to a whitelist of headers proven auth/transport-only.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Measured on b70db34b8262, and the mechanism holds: not blocking in my reading, hardening at most.

Three arms in gtest_writebuffer_s3.cpp (whole suite 77 passed, 1 pre-existing skip):

  1. access_header: If-None-Match: *, so it lands in both extra_headers and access_headers: the absorb fires, headObject == 1. HTTPHeaderFilter constrains no name by default, so a conditional header does reach the exempt branch.
  2. The same header spelled as a generic header: fail-closed, headObject == 0. The access_header classification is the only cause.
  3. The same exempt conditional header with a foreign object at the key: still refused, Expected ETag: 8f28f2e7231860115d2a8cacba019dbe-1, ETag at key: "90f0f2aff752d90f2bf7eba27e07e874".

Arm 3 is why I would not call this the same hole. At origin/master (16723d7e43a2, Client.cpp:563-575) the absorb is if (check_outcome.IsSuccess()) with no ETag and no Content-Type check, and master's is_conditional reads the same typed fields, so this exact configuration absorbs whatever object sits at the key today. Behind the exemption it absorbs only an object whose multipart ETag and Content-Type match the part list: narrower than what ships, not wider.

What does survive is the authorship half, one step further than stated: for a conditional completion an ETag match is not authorship, because a byte-identical object from another writer carries the same ETag. That is what the write token exists for on the typed path, where object_storage_write_if_none_match mints it and the recovery checks it. A conditional header arriving through access_header mints no token and trips neither guard.

I could not get from there to a user-visible consequence. access_header is documented as a credential carrier ("in cases where there are no other credentials from another source", added for user authentication in #71011), the only in-tree use is an auth token, and being per-endpoint it would condition every read from that endpoint as well.

If you want it closed regardless, the cheap form is two names refused ahead of the exemption: if-match and if-none-match are the only conditional fields on the SDK's CompleteMultipartUploadRequest, so a deny-list there is complete rather than open-ended. Your branch and your design call; I pushed nothing.

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Same cascade as the run I answered at 11:29Z (#114375 (comment)): the job you link is the one I measured there, so I will not repeat the chain. What is new since then:

Nothing has merged, so b70db34b8262 carries no fix either. On master right now src/Common/FailPoint.cpp:361 is still REGULAR(distributed_plan_record_failure_while_starting_tasks), ReadFromDistributedPlanSource.cpp has not moved since b0701704afe8 (2026-08-26), and neither test has changed since before the onset (04648 .sql at bb7062ed8712, 2026-07-30; 04340 .sh at 75cfc34cbe46, 2026-08-26). CI on the new head started at 17:38:08Z and no stateless lane has reported yet, so the same two rows are likely on it.

Fleet-wide in the 6.5 hours since that reply, on top of the 30-day counts in #118626: 04648 +10 failures over 9 pull requests, 04340 +8 over 7. The three fixes are unchanged and all still open, so there is nothing new for me to author here: #118417 (yours, removes both halves), #118390 (mine), #105942 (@ Diskein, approved 2026-06-01).

One thing worth flagging, because it is the only test-level red left on #118417 and it is not caused by that diff: Integration tests (amd_tsan, 2/6) fails at test_storage_nats/test_nats_jet_stream.py:1590, assert consumer_seq >= 3 ... 2 deliveries for two messages. That oracle is a flake of its own (9 failures over 5 pull requests, 3 of them on master, across 4 lanes in the last 7 days, onset 2026-09-06 00:59Z), and it is exactly the assertion #118521 (mine) rewrites, which you approved at 17:07Z today. The remaining reds there are Finish Workflow (the new_tests_check.py post hook, "No new tests have been added"), the Mergeable Check and PR aggregates, and CH Inc sync.

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

Need a pause to understand why it become so big change.
Simple and right idea takes too much code and too much discussion here.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Measured on the current head b70db34b8262, against the point where you approved it.

At your approval (2026-08-17): 4 files, +259 -5, of which the behaviour change was 61 lines in src/IO/S3/Client.cpp and 198 lines were tests.
Now: 15 files, +860 -17 (src/ +182, tests +678); Client.cpp is +107 -5.

The 601 added lines in between are 11 non-merge commits (plus 12 master merges) authored by @ alexey-milovidov after he took the head over on 08-18: 8 titled "Address review:", 2 clang-tidy follow-ups, 1 the mixed-case x-amz- replay fix. Each closes one review-bot round, and there have been 9 of those since your approval. They widened the guard from "verify the ETag before absorbing NoSuchUpload" to "fail closed whenever the request carries a header that could change the stored object", which is where isAMZHeader, hasExtraHeadersRequiringFullWriteIdentity, isAccessHeader and the transport/billing exemption list come from. Tests are 79% of the diff (gtest_writebuffer_s3.cpp +408, the new gtest_poco_http_client_extra_headers.cpp +184, integration +86).

So the original idea did not grow much: Client.cpp went from 61 to 107 lines. The header-carrier classification and its tests did, one round at a time.

I agree it should be smaller, and I am not pushing anything here since the head has been @ alexey-milovidov's since 08-18. If you want it split, I can open a fresh PR off master with only the NoSuchUpload ETag verification and its test arms, which is the shape you approved, and leave the header classification to be decided separately. The defect is still live on master: a completion whose response was lost is accepted on key existence alone, so an acknowledged fixed-key INSERT can be absorbed by a different object at that key.

@CheSema

CheSema commented Sep 9, 2026

Copy link
Copy Markdown
Member

I close it in favour. #118829

@CheSema CheSema closed this Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed, and yours is the better branch. Deleting the inference is the fix. Keeping it inside S3::Client meant enumerating by hand every header that could make the stored object differ from what the part list implies, and that enumeration is most of what this PR grew into after you approved it.

One measurement worth having on the record, since the obvious question about your approach is whether moving the recovery out of the client leaves a caller behind: at master 10bec7b88102, DB::S3::Client::CompleteMultipartUpload has exactly two call sites in the tree, src/IO/WriteBufferFromS3.cpp:677 and src/IO/S3/copyS3File.cpp:214, and the base overload is re-declared under private: at Client.h:280, so no caller can reach the SDK method around the wrapper. #118829 re-adds the recovery at both, so the removal is complete rather than relocated.

Checked against what this PR carried, every case is covered there: the integration arm with its no-fault control, own-object recovery and foreign-object refusal on an unconditional completion, and the copyS3File path. Leaving composeObjectAfterMultipartUpload unpinned reads right to me too, since a failed compose has only ever cost native-copy performance.

Nothing further from me here.

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-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care!

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

3 participants