Skip to content

Stop S3 disk reads from holding a connection per idle stream above the soft limit - #119730

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix-s3-read-buffers-hoarding-connections
Sep 26, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix-s3-read-buffers-hoarding-connections

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 13, 2026 •

Copy link
Copy Markdown
Member

Closes: #119660

A ReadBufferFromS3 sends one GET for the whole range it has to deliver and keeps the connection until the range is consumed. A MergeTree reader opens one such buffer per substream of every part it reads and consumes them in lockstep, so a merge of parts with a JSON column (hundreds of substreams per part: typed paths, dynamic paths, and up to six streams for each of the 32 shared-data buckets) holds thousands of connections that are idle nearly all the time. A few such merges reach disk_connections_hard_limit together: none of them can open the streams it still needs, none releases what it holds, and every other user of the Disk connection group fails with HTTP_CONNECTION_LIMIT_REACHED. Bounding the connections of a single merge would not be enough, since one merge alone can hold thousands and the hard limit is shared by the whole group.

Once the connection group of the disks is at or above disk_connections_soft_limit, ReadBufferFromS3 now cuts each request to what one buffer fill consumes. The response is complete right after the fill, so the pool can reuse the connection at once, and the next fill sends a new request from the new offset. The connections held by such readers are then bounded by the fills in flight rather than by the number of open streams. Below the soft limit nothing changes, because this costs one request per fill. The soft limit already meant "economize connections" (idle ones expire sooner), and its description now says what else it does. The Storage and HTTP groups are not affected: their readers do not keep thousands of idle streams open in lockstep.

The retry loop of ReadBufferFromS3::nextImpl also drops the failed request before the back-off sleep instead of after it, so a connection that is of no further use is not kept out of the pool while the buffer waits.

HTTPConnectionPools::isSoftLimitReached exposes the state of a group, with a unit test. The integration test compares a node whose soft limit is reached at once against a node with default limits: both read the same data, and the limited node issues many more, smaller requests for the same query and for the same merge (locally, 120 GET requests of 1 MiB each for the merge instead of 8).

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Merges and queries on S3 disks no longer hold one HTTP connection per open stream for their whole duration once connections are scarce. Previously this let a few merges of tables with many substreams (for example a JSON column) saturate disk_connections_hard_limit, stall each other, and fail every other request to the disks with HTTP_CONNECTION_LIMIT_REACHED. Once the Disk connection group is at or above disk_connections_soft_limit, reads from S3 disks fetch each buffer fill with a separate request and return the connection to the pool between fills.


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

Version info

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

…e soft limit

A `ReadBufferFromS3` sends one GET for the whole range it has to deliver and keeps the
connection until the range is consumed. A MergeTree reader opens one such buffer per
substream of every part it reads and consumes them in lockstep, so a merge of parts with
a `JSON` column holds thousands of connections that are idle nearly all the time, and a
few such merges reach `disk_connections_hard_limit` together: none of them can open the
streams it still needs, none releases what it holds, and every other user of the `Disk`
connection group fails with `HTTP_CONNECTION_LIMIT_REACHED`.

Once the connection group of the disks is at or above `disk_connections_soft_limit`,
`ReadBufferFromS3` now cuts each request to what one buffer fill consumes. The response
is complete right after the fill, the connection returns to the pool at once, and the
next fill sends a new request from the new offset. The connections held by such readers
are then bounded by the fills in flight rather than by the number of open streams, at
the cost of one request per fill, which is why it is done only under pressure.

The retry loop of `nextImpl` also drops the failed request before the back-off sleep
instead of after it, so a connection that is of no further use is not kept out of the
pool while the buffer waits.

`HTTPConnectionPools::isSoftLimitReached` exposes the state of a group. The integration
test compares a node whose soft limit is reached at once against a node with default
limits: both read the same data, and the limited node issues many more, smaller requests
for the same query and for the same merge.

Closes: #119660

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [09f900d]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
read_in_reverse_order_final #0 FAIL dashboard
read_in_reverse_order_final #1 FAIL dashboard
min_max_wide_integers #6 FAIL dashboard

AI Review

Summary

This PR changes ReadBufferFromS3 so S3 disk reads stop pinning one HTTP connection per open stream once the Disk connection group reaches disk_connections_soft_limit, and it also releases failed readBigAt responses before retry backoff. I did not find a remaining correctness, lifetime, or concurrency bug in the patch itself; the implementation and the added unit/integration coverage match the intended fix.

PR Metadata
  • Changelog category is not quite aligned with the change. This fixes user-visible misbehavior on stable releases (HTTP_CONNECTION_LIMIT_REACHED and stalled merges), so Bug Fix is a better fit than Improvement.
  • Changelog entry is required for Bug Fix, and the existing entry is specific and user-readable, so it can stay as-is.
  • Exact replacement:
### Changelog category (leave one):
- Bug Fix
Missing context / blind spots
  • ⚠️ The full build/sanitizer matrix for the current head is still in progress, so this review is based on the current code, prior discussion, and the focused tests already in the PR rather than completed end-to-end CI evidence.
Final Verdict
  • Status: ✅ Approve
  • Minimum required actions: none for code correctness. If you want the changelog to land in the right bucket, switch the category to Bug Fix.

LLVM Coverage Report

Measured on commit 09f900d.

Metric Baseline Current Δ
Lines 88.10% 88.20% +0.10%
Functions 91.70% 91.80% +0.10%
Branches 79.40% 79.50% +0.10%

Changed lines: Changed C/C++ lines covered: 52/55 (94.55%) · 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 13, 2026
Comment thread src/IO/ReadBufferFromS3.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 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 09f900d53 with master 68694750f (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.

Compile time of recompiled translation units

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

Job report

alexey-milovidov and others added 2 commits September 19, 2026 06:48
`nextImpl` already drops its failed request before pausing, but `readBigAt`
kept the local `GetObjectResult` alive until the end of the loop iteration, so
a retriable mid-read failure held the pooled session for the whole back-off.
The `supportsReadAt` readers (Parquet, ORC on S3 disks) issue many such
requests in parallel, so under transient-error pressure they kept taking
connections out of the `Disk` group -- exactly what this pull request is
trying to relieve.

Reset `result` before `sleepForMilliseconds`, and add a focused gtest for the
`readBigAt` retry path: the first response body fails on its first read, and a
watcher observes that the session of the failed request is given up before the
retry request is sent. Control-proved: the test fails without the one-line
change.

Address review feedback.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119730&sha=4cd8d1fcabc28cfca05f27e07cf1b2209ca2bce8&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The single red job is Upgrade check (amd_release) with Logical error: 'Virtual row has different type for CAST(__table1.json.b, 'String'_String). Expected ... Nullable(String) ..., got ... String ...' (STID 1637-309b), thrown from setVirtualRow in src/Processors/Merges/Algorithms/MergeTreeReadInfo.cpp on the read_in_order_use_virtual_row path. This pull request only touches ReadBufferFromS3 and the HTTP connection pool, so it cannot reach that code; I could not find an existing tracking issue for this message.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. No new fix is owed: both sides of this signature are already merged, and the linked job predates the second one.

The linked job ran on 4cd8d1fc at 2026-09-13 06:21Z, about 7 hours before #119768 merged, so it still drew cast_keep_nullable = 1. And on this check the aborting process is the previous release, not this branch's build: Upgrade check runs the pre-upgrade load against the shipped 26.8 server, which has no fix available to it from master. I measured that per stage on another run of the same signature (#119224): 2 hits in clickhouse-server.stress.log under 26.8.2.7, 0 in clickhouse-server.upgrade.log under 26.9.1.1, and the uploaded core keyed to the pre-upgrade PID. 4cd8d1fc already contained #119385, so the red job is not evidence against the fix.

CIDB by day for the signature: 1 row on 09-10, 57 on 09-11, 23 on 09-12, 11 on 09-13, 1 on 09-14 at 06:27Z (219ee6ec, also pre-#119768), then 0 in the 1413 Upgrade check (amd_release) runs since that moment. This head, c69cee4a, contains both commits, so I expect the run in flight to be clean on this signature.

One loose end I am not repeating here: the engine fix is master-only and the abort stays reachable on 26.8 with cast_keep_nullable = 1, so I asked on #119224 whether you want v26.8-must-backport on #119385.

Separately, from the run in flight: Unit tests (tsan) is red on c69cee4a with a data race at src/IO/tests/gtest_readbuffer_s3.cpp:87:25 in CountedSession::~CountedSession(). The new ReadBigAtReleasesSessionBeforeRetryBackoff watcher thread polls CountedSession::OustandingObjects() while the main thread destroys sessions, and CountedSession::total is a plain int; making it std::atomic<int> should settle it. That signature has no other occurrence in CIDB in the last 14 days.

@alexey-milovidov alexey-milovidov added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 24, 2026
Comment thread src/IO/tests/gtest_readbuffer_s3.cpp Resolved
The `ReadBigAtReleasesSessionBeforeRetryBackoff` watcher thread polls
`CountedSession::OustandingObjects` while the main thread creates and
destroys sessions, so a plain `int` counter is a data race that TSan
reports in `Unit tests (tsan)`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119730&sha=8221d485dec3a1754fe25dbade16c91d150a0d9a&name_0=PR&name_1=Unit%20tests%20%28tsan%29
PR: #119730

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. Agreed on the Upgrade check signature. The Unit tests (tsan) race you and the AI review pointed out is fixed in 09f900d: CountedSession::total is now std::atomic<int>, so the ReadBigAtReleasesSessionBeforeRetryBackoff watcher thread can read it safely while the main thread creates and destroys sessions.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is good.

@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into master with commit 6f80dda Sep 26, 2026
175 of 177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-s3-read-buffers-hoarding-connections branch September 26, 2026 01:03
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
alexey-milovidov pushed a commit to fastio/ClickHouse that referenced this pull request Oct 10, 2026
…nting cut requests

Since ClickHouse#119730, `ReadBufferFromS3::initialize` cuts every request of an S3
disk to one buffer fill while the process-wide `Disk` connection group holds
at least `disk_connections_soft_limit` connections. Whether a request is cut
therefore depends on the rest of the server, and nothing recorded that it
happened.

`04812_prewhere_fragmented_ranges_s3_read_requests` asserts
`S3ReadRequestsCount < 20`. In `Stateless tests (arm_asan_ubsan, azure,
parallel)` every MergeTree table lives on the `azure` disk, which shares the
`Disk` group with `s3_disk`; bursts of Azure disk reads held the group at
5600-6000 connections for 10-15 s, and both failing runs (PR 115050 and
PR 123894) fell inside such a window: 1723-1843 GETs instead of 2-6 for the
same bytes, with 0 errors.

The new event is incremented exactly where `cut_request_end` is set, and the
test now bounds only the requests that were not cut:
`S3ReadRequestsCount < 20 + ReadBufferFromS3RequestsCut`. Under the cut, the
uncut requests are the ones the test is about (one per requested range), so a
read bound that advances per fragment still fails the test, with and without
the soft limit. Without pressure the event is 0 and the assertion is
unchanged.

Validated with `disk_connections_soft_limit = 1` on a local server: the old
test fails 5/5 with the CI diff, the new one passes 50/50; with the default
limit the new test passes 50/50 with the same request counts as before.

Related: ClickHouse#115050 (comment)
Related: ClickHouse#119730

Co-Authored-By: Claude Opus 5.5 <[email protected]>
filimonov pushed a commit to Altinity/ClickHouse that referenced this pull request Nov 21, 2026
…ion per idle stream above the soft limit

A reader that keeps many S3 streams open held one pooled connection per stream, idle between
fills. Above `disk_connections_soft_limit` each fill becomes its own ranged request whose
connection returns to the pool at once. Seen here on the CAS-S3 lanes: a horizontal merge of
`system.metric_log` (2425 columns) holds thousands of sessions, and the warning
`Too many active sessions in group Disk` fails random tests.

Upstream: ClickHouse#119730
Upstream merge commit: 6f80dda
Commits of the upstream pull request:
- 09f900d Make `CountedSession::total` atomic in `gtest_readbuffer_s3`
- 8221d48 Merge branch 'master' into fix-s3-read-buffers-hoarding-connections
- c69cee4 Release the failed request in `readBigAt` before the retry back-off
- 02a5405 Merge remote-tracking branch 'origin/master' into fix-s3-read-buffers-hoarding-connections
- 4cd8d1f Stop S3 disk reads from holding a connection per idle stream above the soft limit

Adaptation for antalya-26.8:
- None: applied as is. `ReadBufferFromS3::initialize` merged without conflict around this
  branch's response-identity check: `pending_response_etag` is still recorded after
  `sendRequest`, so every cut request is checked against `last_delivering_response_etag`.

(cherry picked from commit 6f80dda)

Signed-off-by: Mikhail Filimonov <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
filimonov pushed a commit to Altinity/ClickHouse that referenced this pull request Nov 21, 2026
… event and stop 04812 from counting cut requests

Counts the S3 disk reads cut to one buffer fill by ClickHouse#119730, so the cut is visible in
`system.events` and `query_log`. `04812_prewhere_fragmented_ranges_s3_read_requests` asserts
a request count and fails when the server is above the soft limit; it now excludes cut requests.

Upstream: ClickHouse#124701
Upstream merge commit: 35cab67
Commits of the upstream pull request:
- 743e625 Add ReadBufferFromS3RequestsCut profile event and stop 04812 from counting cut requests

Adaptation for antalya-26.8:
- None: applied as is.

(cherry picked from commit 35cab67)

Signed-off-by: Mikhail Filimonov <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[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-improvement Pull request with some product improvements 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.

Large merges on object storage deadlock each other on the disk connection limit

3 participants