Skip to content

Fix nested S3 request retries and read the error an S3 server sends before the whole request body - #124557

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-s3-nested-retries-and-early-error-response
Oct 10, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-s3-nested-retries-and-early-error-response

Conversation

@groeneai

@groeneai groeneai commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124326
Related: #90216

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 S3 requests that keep failing with a retryable error being attempted (s3_retry_attempts + 1)^2 times instead of s3_retry_attempts + 1. Fixed an error that a plain-HTTP S3 endpoint sends before reading the whole request body (for example NoSuchUpload for an expired multipart upload) being retried as a Broken pipe network error instead of being reported. Closes #124326.

Description

On 26.9.12.8, an INSERT INTO FUNCTION s3(...) whose multipart upload the server aborts before the last part sends that part (s3_retry_attempts + 1)^2 times (251,001 with the default) and fails with a network error instead of NoSuchUpload. Two defects:

  1. Client::doRequestWithRetryNetworkErrors retries every retryable error the SDK returns, but the SDK has already retried it s3_retry_attempts times. Slow down all backup threads after S3 retryable errors, including ‘SlowDown’ #84854 added this outer retry only for s3_slow_all_threads_after_retryable_error (where the SDK gets one retry); retry network errors when s3 library parse xml response #90216 dropped that condition; this restores it. Exceptions thrown out of the SDK while it reads a response body are still retried by the outer loop.
  2. MinIO answers 404 NoSuchUpload right after the request header and resets the connection. PocoHTTPClient writes the whole body first, the write fails, and Poco rethrows that send error instead of returning the response. Now, when the body send fails over plain HTTP with response data already waiting on the socket, that response is read (new HTTPClientSession::receiveEarlyResponse) and used if its status is >= 300. Over HTTPS (OpenSSL allows no I/O after a failed write) such an error is still retried as a network error, but only s3_retry_attempts + 1 times. The Azure transport has the same shape and is not changed.

Validation with MinIO, s3_retry_attempts = 3: 26.9.12.8 and master send the dead part 16 times and read no response; with this PR it is sent once and the query fails with NoSuchUpload (the same with the default 500). Over HTTPS: 16 -> 4. test_when_error_is_retried now checks the attempt count (37 on master, 7 here); new test test_early_error_response_at_upload_is_not_retried.

Changes the same request-body block of PocoHTTPClient as #116222.

Server log, MinIO, s3_retry_attempts = 3

26.9.12.8 (16 such lines, the SDK count restarts 4 times):

2026.10.08 05:12:30.546417 [ 1647866 ] {repro_gap} <Trace> S3ClientRetryStrategy: Attempt 4/4 failed with retryable error: 18446744073709551615, Poco::Exception. Code: 1000, e.code() = 104, Connection reset by peer (version 26.9.12.8 (official build))
2026.10.08 05:12:31.115121 [ 1647866 ] {repro_gap} <Trace> S3ClientRetryStrategy: Attempt 1/4 failed with retryable error: 18446744073709551615, Poco::Exception. Code: 1000, e.code() = 104, Connection reset by peer (version 26.9.12.8 (official build))
[...]
2026.10.08 05:12:37.617989 [ 1647866 ] {repro_gap} <Trace> S3ClientRetryStrategy: Attempt 4/4 failed with retryable error: 18446744073709551615, Poco::Exception. Code: 1000, e.code() = 104, Connection reset by peer (version 26.9.12.8 (official build))
Code: 499. DB::Exception: Received from localhost:9600. DB::Exception: Poco::Exception. Code: 1000, e.code() = 104, Connection reset by peer (version 26.9.12.8 (official build)).

This PR:

2026.10.08 05:07:22.565096 [ 1526898 ] {repro_gap} <Debug> AWSClient: Failed to send the request body to http://127.0.0.1:9200/repro-bucket/data/gap.tsv?partNumber=3&uploadId=<id>, using the response the server has already sent: Poco::Exception. Code: 1000, e.code() = 104, Connection reset by peer
2026.10.08 05:07:22.565110 [ 1526898 ] {repro_gap} <Error> AWSClient: Response status: 404, Not Found
Code: 499. DB::Exception: Received from localhost:9600. DB::Exception: The specified multipart upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed..

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 3 commits October 8, 2026 04:58
`Client::doRequestWithRetryNetworkErrors` retried every retryable error
outcome returned by the AWS SDK, but the SDK's own retry loop has already
run the same `RetryStrategy` with `max_retries = s3_retry_attempts` for it,
so a persistent retryable error was attempted `(s3_retry_attempts + 1)^2`
times (251001 with the default of 500). The outer outcome retry was
introduced in ClickHouse#84854 only for `s3_slow_all_threads_after_retryable_error`,
where the SDK gets `max_retries = 1`; ClickHouse#90216 rewrote the loop and dropped
that condition.

Restore it: with the flag off, a non-success outcome is returned as is.
Exceptions thrown out of the SDK while it reads a response body (the case
ClickHouse#90216 added the loop for) are still retried by the outer loop.

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

A server may answer a request it rejects right after reading its header and
close the connection with the body unread. MinIO does this for an
`UploadPart` whose multipart upload no longer exists (`404 NoSuchUpload`,
e.g. after its stale-upload expiry). `PocoHTTPClient` writes the whole body
before reading the response, so the write fails with `Broken pipe` or
`Connection reset by peer`; Poco keeps that send error in the session and
`receiveResponse` rethrows it before reading anything, so the 404 is never
seen and the request is retried as a network error until the retry budget
is spent, then fails with the network error instead of `NoSuchUpload`.

When sending the body over plain HTTP fails with a `Poco::IOException` and
response data is already waiting on the socket (non-blocking probe
`getSocketState`), read that response with the new
`HTTPClientSession::receiveEarlyResponse` and use it if its status is an
error (>= 300). Otherwise the send error is rethrown as before. TLS is
excluded: OpenSSL allows no further I/O after a failed `SSL_write`, so over
HTTPS such an error is still retried as a network error (bounded by
`s3_retry_attempts` after the previous commit).

The `no_such_upload` action of the S3 mock gets an `early` mode that
answers without reading the body and resets the connection, as MinIO does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the receiveEarlyResponse doc to its contract and drop the expired-upload example from the PocoHTTPClient catch comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Independent model review (codex, 1 finding) plus my own cold review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test depends on the mock's fixed 0.5 s sleep before closing (broken_s3.py) DISAGREE The send fails only after the RST, and the 404 and FIN are queued ahead of it; Linux keeps the receive queue on RST. The sleep mirrors Go net/http's 500 ms rstAvoidanceDelay. New test 50/50, module 38/38.
2 💡 The Azure transport has the same write-then-read shape AGREE Stated in the PR description; Azure is not changed.
3 💡 Raw server log for the before/after AGREE Added as a collapsed block in the PR description.
4 💡 bugprone-empty-catch on the new catch (...) in Poco DISAGREE base/poco is not clang-tidy-checked in CI; Poco uses the same idiom (HTTPSession.cpp).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261008-062000

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. MinIO RELEASE.2026-08-04, INSERT INTO FUNCTION s3(...) with the upload aborted before the last part: master and 26.9.12.8 send the dead part 16 times (s3_retry_attempts = 3) and read no response, every run. The integration tests fail on master every run.
b Root cause explained? (1) Client::doRequestWithRetryNetworkErrors retries outcomes the SDK already retried N times, giving (N+1)^2; #90216 lost #84854's gate. (2) MinIO sends the 404 and resets before reading the body; Poco rethrows the stored send error, so the response is never read.
c Fix matches root cause? Yes. The gate is restored where the attempts multiply; the response already sent is read instead of the send error. No retry setting changed.
d Test intent preserved / new tests added? test_when_error_is_retried also asserts the attempt count. New test_early_error_response_at_upload_is_not_retried, with an early mode of the mock's no_such_upload action.
e Both directions demonstrated? MinIO: master 16 x 404 / 0 read, commit 1 alone 4 / 0, this PR 1 read and Code: 499 ... upload does not exist (also at N = 500). Integration: 37 vs 7 attempts, Broken pipe vs NoSuchUpload.
f Fix is general across code paths? (1) One loop shared by every doRequestWithRetryNetworkErrors request. (2) The single S3/GCS body-send site; PooledConnection is the only flushRequest override. Azure has the same shape, no reproducer, not changed. HTTPS: 16 -> 4.
g Fix generalizes across inputs (params/datatypes/wrappers)? All four retryable outcome classes (503, two 429s, connection refused), ECONNRESET and EPIPE, N = 3 and 500, HTTP and HTTPS. A status < 300 after a failed send is not accepted; TimeoutException is not caught.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change. The backup_slow_all_threads_after_retryable_s3_error mode is unchanged (test_backup_restore_s3 96/96).
i Invariants and contracts preserved? Flag off: at most N+1 attempts per retryable outcome. After receiveEarlyResponse the send error is cleared and the connection is marked incomplete, so it never returns to the pool. Every other path rethrows the original exception.

Session id: cron:clickhouse-impl-slot-7:20261008-044000

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6eb6402]

Summary: ✅


AI Review

Summary

This PR fixes two S3-specific regressions: it stops the outer ClickHouse retry loop from re-retrying retryable AWS SDK outcomes after the SDK has already exhausted its own retry budget, and it adds a plain-HTTP early-response path so an S3 server error sent before the full request body is read is surfaced as the server's HTTP error instead of as a terminal Broken pipe/connection-reset network error. I reviewed the current diff, the touched code paths, and the prior PR discussion; the retry-contract change matches the described root cause, the new receiveEarlyResponse path integrates correctly with the pooled-session completion checks, and I did not find any new blockers or majors in the current head.

Final Verdict

✅ No new review findings from me on the current diff.

LLVM Coverage Report

Measured on commit 6eb6402.

Metric Baseline Current Δ
Lines 88.30% 88.20% -0.10%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 20/20 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. labels Oct 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6eb64029f with master c0289e05c (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

10 object files changed (-12.41 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/IO/S3/Client.cpp.o 1.23 MiB 1.21 MiB -17.77 KiB (-1.42%)

719 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

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

Job report

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

Interesting.

/// Drops the unsent rest of the request, which rethrows the send error.
try
{
flushRequest();

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.

Why we ignore errors from it?

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.

flushRequest() only rethrows the send error that the caller is already handling (the stored networkException(); the body stream is already bad, so the flush itself writes nothing). The catch drops that copy, and the caller rethrows the original exception with throw; whenever no response is read. Agreed that it is not visible from the code. This goes away in the replacement: #124326 (comment)

|| !session->receiveEarlyResponse(poco_response)
|| poco_response.getStatus() < Poco::Net::HTTPResponse::HTTP_MULTIPLE_CHOICES)
throw;
LOG_DEBUG(log, "Failed to send the request body to {}, using the response the server has already sent: {}",

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.

Do not understand, we just catch an exception here and if connection is not secure just drop it / mute it? Not sure it is correct.

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.

No, it is never muted: throw; rethrows the original IOException in every case except one: plain HTTP, data already waiting on the socket, a complete response header parsed, and status >= 300. Only then the send error is replaced by that response, which goes through the normal S3 error handling (here NoSuchUpload, not retried), and the send error is logged at DEBUG. Over HTTPS it is always rethrown.

HTTPHeaderInputStream his(*this);
try
{
response.read(his);

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.

Here we lose the exception description. If something happened here we just return false.

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.

Right: a parse failure returns false, the caller then rethrows the original send error, and the parse error text is lost. The replacement does not read after a failed write at all: #124326 (comment)

/// TLS allows no I/O after a failed write.
if (session->secure()
|| DB::getSocketState(session->socket()) != DB::SocketState::DataPending
|| !session->receiveEarlyResponse(poco_response)

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.

This session already throw the exception, current one, but in receiveEarlyResponse method we try to read from that session again.

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.

Yes, on purpose: only the write failed (EPIPE / ECONNRESET). On a plain TCP socket on Linux, the bytes the server sent before closing stay in the receive queue and can still be read; that is how the 404 is read in the MinIO repro. TLS forbids any I/O after a fatal SSL_write, hence plain HTTP only. I agree this is the wrong approach and plan Expect: 100-continue instead: #124326 (comment)

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]>
robot-ch-test-poll2 added a commit that referenced this pull request Nov 11, 2026
Cherry pick #124557 to 26.9: Fix nested S3 request retries and read the error an S3 server sends before the whole request body
robot-clickhouse added a commit that referenced this pull request Nov 11, 2026
…error an S3 server sends before the whole request body
robot-clickhouse-ci-1 added a commit that referenced this pull request Nov 11, 2026
Cherry pick #124557 to 26.8: Fix nested S3 request retries and read the error an S3 server sends before the whole request body
robot-clickhouse added a commit that referenced this pull request Nov 11, 2026
…error an S3 server sends before the whole request body
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 11, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 11, 2026
Backport #124557 to 26.8: Fix nested S3 request retries and read the error an S3 server sends before the whole request body
clickhouse-gh Bot added a commit that referenced this pull request Nov 11, 2026
Backport #124557 to 26.9: Fix nested S3 request retries and read the error an S3 server sends before the whole request body
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…error an S3 server sends before the whole request body
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…error an S3 server sends before the whole request body
Blargian pushed a commit to Blargian/ClickHouse that referenced this pull request Nov 16, 2026
The tests-only part of ClickHouse#131102, unchanged: the `lingering` mode of
`NoSuchUploadAction` in the S3 mock, the early-error rows of
`test_early_error_response_at_upload_is_not_retried`, and the
`SilkFiberSocketTest.HTTPRequestBody` gtest. They pass on master, where
plain HTTP is handled by the read of ClickHouse#124557.

Related: ClickHouse#131084

Co-authored-by: Sema Checherinda <[email protected]>
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

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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ClickHouse Keeps retrying writes to Object storage(minio) even when minio throws 404 error.

7 participants