Skip to content

Read and write HTTP bodies through ReadBuffer/WriteBuffer instead of std::iostream - #116222

Merged
alexey-milovidov merged 47 commits into
masterfrom
native-http-client
Oct 13, 2026
Merged

alexey-milovidov merged 47 commits into
masterfrom
native-http-client

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

The HTTP client went through std::iostream. Poco::Net::HTTPClientSession handed out a stream whose std::streambuf copies every byte through an 8 KiB buffer and talks to the socket in 8 KiB pieces. Reads had been carved out of that path earlier - ReadBufferFromIStream reached into the streambuf and called readFromDevice itself - but writes had not, so a 15 MB upload left the machine as 1817 send calls of 8200 bytes each, after two copies of every byte. The Azure transport was on the slow path in both directions.

The client now sends and receives message bodies through the ReadBuffer/WriteBuffer hierarchy, directly on the socket, the same way the HTTP server side has done for a while.

Approach

Poco::Net::HTTPClientSession keeps doing what it is good at - connections, keep-alive, proxies, TLS - and gained an iostream-free entry point for it: sendRequestHeaders writes the request line and headers and reports how the body has to be framed, onResponseHeadersReceived does the keep-alive bookkeeping and reports the framing of the response. HTTPSession exposes raw framed access (getCharRaw, readRaw, writeAllRaw) and two flags that say whether the request and the response bodies were transferred to the end, which is what the connection pool needs in place of the stream introspection it used to do.

src/IO/HTTP/HTTPClientIO.{h,cpp} implements the two ends:

  • HTTPRequestBodyWriteBuffer writes the body with Content-Length or chunked framing. For chunked encoding the chunk header and trailer go into space reserved around the buffer, so a chunk of any size still costs one send and the payload is never copied.
  • HTTPResponseReadBuffer reads the body with either framing straight into its own memory, or into the memory the caller substitutes with set(), so the external buffer mode of the remote-filesystem readers stays zero-copy. readBig reads into the caller's memory with no buffer in between.
  • The response line and the headers are parsed from the session - ports of HTTPResponse::read and MessageHeader::read with their limits, their folding of continuation lines and their exceptions, so that a keep-alive connection closed by the server still surfaces as NoMessageException and gets retried where it did before.

Everything that spoke to the old API moved over: the S3 and Azure HTTP clients, ReadWriteBufferFromHTTP, WriteBufferFromHTTP, the connection pool, and the smaller callers (JWT and Cloud JWT providers, ACME, the REST/Unity/S3Tables catalogs, HTTP and XDBC dictionary sources, BigQuery, the AI providers, the remote proxy resolver, the Avro schema registry, BuzzHouse, the stateless worker client). The request body callback of ReadWriteBufferFromHTTP takes a WriteBuffer now, which lets its callers drop the WriteBufferFromOStream wrapper they built around the stream. Poco::StreamCopier and its extra copy are gone from the S3 upload path, and ReadBufferFromIStream, SessionAwareIOStream and the friend declaration they needed inside Poco::BasicBufferedStreamBuf are deleted.

Two bugs turned up on the way and are fixed here. StdStreamBufFromReadBuffer published no get area, so reading it one character at a time - what the AWS SDK does to parse an XML response - walked off a null gptr and crashed; it now hands the buffer of the ReadBuffer over as the get area. It also threw on an output-side seek, where code that only reads from a stream, the SDK included, expects a failure.

Results

Measured with strace on a 15 MB body:

before after
INSERT INTO FUNCTION url(...), chunked 1817 sends of 8200 bytes 15 sends, 14 of them 1 MiB
S3 PutObject 1817 sends of 8192 bytes 15 sends, 14 of them 1 MiB
Azure GetBlob, 3.4 MB 436 receives, none above 8192 bytes 22 receives, 154 KB on average
SELECT FROM url(...), 22 MB 33 receives of up to 1 MiB unchanged

There is no buffer size constant left to raise: the size of a transfer now comes from the ClickHouse settings (max_read_buffer_size for reads, 1 MiB by default for request bodies), and the 8 KiB of Poco only covers the parsing of response headers and chunk headers.

Testing

05055_native_http_client_framing checks the framing of both directions against a server that speaks every variant: a response with Content-Length, a chunked response split into chunks of growing size, and a request body sent chunked, with a read buffer smaller than the chunks as well.

Beyond that, the change was run against a base build of the same commit on the same machine: 615 stateless tests matching url, http, s3, dict and azure gave 457 passed on both sides, with the difference in the failures being three flakes from memory pressure on that machine (they pass when run alone) and the rest failing identically on both sides for lack of the CI server configuration. The 28125 unit tests give two failures, one of which fails on the base build as well and the other passes in isolation. On top of that: single-part and multipart uploads, ListObjectsV2 globs, Parquet through readBigAt and a MergeTree on an S3 disk against a real MinIO, with connection reuse counters matching the base build; a write and a read of an Azure blob against Azurite; an XML error response parsed into the same message as before; a read over HTTPS; and a ReplicatedMergeTree part fetch over the interserver protocol.

Changelog category (leave one):

  • Performance Improvement

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

The HTTP client, which every integration that talks HTTP goes through - S3, Azure, the url table function and engine, dictionaries, data lake catalogs - now reads and writes message bodies through the ClickHouse buffers directly on the socket instead of std::iostream. Uploads leave the machine in 1 MiB pieces rather than 8 KiB ones, which cuts the number of system calls for a 15 MB body from 1817 to 15 and removes two copies of every uploaded byte, and reads from Azure no longer pass every byte through an 8 KiB buffer.


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

Version info

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

The HTTP client went through `std::iostream`: `Poco::Net::HTTPClientSession`
handed out a stream whose `std::streambuf` copies every byte through an 8 KiB
buffer and talks to the socket in 8 KiB pieces. Reads had already been carved
out of that path - `ReadBufferFromIStream` reached into the streambuf and called
`readFromDevice` itself - but writes had not, so a 15 MB upload left as 1817
`send` calls of 8200 bytes each, after two copies of every byte. The Azure
transport was on the slow path in both directions.

The client now sends and receives message bodies through the `ReadBuffer` and
`WriteBuffer` hierarchy, straight on the socket, the same way the HTTP server
side already does. `Poco::Net::HTTPClientSession` keeps doing what it is good at
- connections, keep-alive, proxies, TLS - and gained an iostream-free entry
point for it: `sendRequestHeaders` writes the request head and reports how the
body has to be framed, `onResponseHeadersReceived` does the keep-alive
bookkeeping and reports the framing of the response.

`src/IO/HTTP/HTTPClientIO.{h,cpp}` implements the two ends:

- `HTTPRequestBodyWriteBuffer` writes the body with `Content-Length` or chunked
  framing. For chunked encoding the chunk header and trailer go into space
  reserved around the buffer, so a chunk of any size still costs one `send` and
  the payload is never copied.
- `HTTPResponseReadBuffer` reads the body with either framing straight into its
  own memory, or into the memory the caller substitutes with `set()`, so the
  external buffer mode of the remote-filesystem readers stays zero-copy.
  `readBig` reads into the caller's memory with no buffer in between.
- Response line and headers are parsed from the session, ports of
  `HTTPResponse::read` and `MessageHeader::read` with their limits, their folding
  and their exceptions, so that a keep-alive connection closed by the server
  still surfaces as `NoMessageException` and gets retried.

Measured, on a 15 MB body: an `INSERT INTO FUNCTION url(...)` went from 1817
`sendto` calls of 8200 bytes to 14 of 1 MiB, and an S3 `PutObject` from 1817 of
8192 bytes to 14 of 1 MiB, with `Poco::StreamCopier` and its extra copy gone
from the S3 upload path. Reading 3.4 MB from Azure went from 436 `recvfrom`
calls of at most 8192 bytes to 22, and no longer copies every byte through the
streambuf.

Along the way:

- `StdStreamBufFromReadBuffer` published no get area, so reading it one
  character at a time - what the AWS SDK does to parse an XML response - walked
  off a null `gptr`. It now hands the buffer of the `ReadBuffer` over as the get
  area, and fails an output-side seek instead of throwing, which is what the SDK
  expects of a stream it only reads.
- `ReadBufferFromIStream` and `SessionAwareIOStream` have no users left and are
  deleted, together with the `friend` declaration they needed inside
  `Poco::BasicBufferedStreamBuf`.
- The request body callback of `ReadWriteBufferFromHTTP` takes a `WriteBuffer`,
  which lets its callers drop the `WriteBufferFromOStream` wrapper they built
  around the stream.
The base class does the same nothing, and the reason a body that was not
finished leaves the connection unusable now sits in the destructor.
`readBigAt` copied the body of the response out of the `std::iostream` the AWS
SDK hands over, which copies it once more. The body is a `ReadBuffer` behind
that stream; read from it, so a big read lands in the memory of the caller.
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b4a8f53]

Summary: ✅


AI Review

Summary

This PR replaces the client-side std::iostream HTTP body path with direct ReadBuffer/WriteBuffer transport, updates the connection-pool completeness bookkeeping, and migrates the HTTP-based callers and coverage around S3, Azure, and generic HTTP reads/writes. On the current head, the previously discussed transport/pool issues appear addressed, the latest Praktika report for PR #116222 is all green, and I did not find a confident new blocker or major issue in the current code.

Final Verdict

✅ No new findings on the current head.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 25, 2026
Comment thread src/IO/ReadWriteBufferFromHTTP.cpp Resolved
Comment thread src/Common/HTTPConnectionPool.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit b4a8f5362063bcb46a7eb5e4ce2fed1febaeb9c6 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "String" }, { "name…).

See the job log for details.

… in the HTTP client

Four fixes for regressions of the ReadBuffer/WriteBuffer HTTP client path, found by CI
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116222&sha=eb526032106a7bf02b5ab4e4e8ab45c96a377074&name_0=PR
and by review:

- `HTTPResponseReadBuffer::nextImpl` reads to the end of the buffer instead of returning
  after a single `recv`, the way `ReadBufferFromIStream` did. A single `recv` returns only
  the data available on the socket at the moment, which shrank the blocks handed to the
  filesystem cache and the prefetcher (`03553_prefetch_buffer_size`,
  `02963_remote_read_small_buffer_size_bug`).
- `receiveHTTPResponse` caps the buffer at the `Content-Length` of the response, so a small
  object does not allocate the full default buffer (`02496_storage_s3_profile_events`).
- Reading a response that was constructed without memory - the body of an error response in
  the external buffer mode - falls back to a scratch buffer instead of reporting a false EOF
  and leaving the error payload on the socket, where it would poison the pooled connection
  for the next request.
- A chunked response consumed up to the last payload byte is completed on teardown by reading
  the terminating chunk, the way the old iostream path did with
  `HTTPChunkedInputStream::isComplete(true)`, so such connections are reused again.
…sten backlog

`test_checking_s3_blobs_paranoid` asserts exact `S3WriteRequestsErrors` counts, but the
`broken_s3.py` mock replied with HTTP/1.0, which is never eligible for connection reuse,
so the client opened a new connection per request. A client that uploads parts at full
speed then overflows the default listen backlog of 5 and the dropped connection attempts
surface as connect timeouts and `Connection reset by peer` counted on top of the injected
errors. On this branch the faster HTTP client made that reliably visible:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116222&sha=fa7aa907b526c0c232f7107660af90984a2c8ae1&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%203%2F6%29
but a standalone reproduction of the failing scenarios against the mock shows the same
extra errors with a master binary as well.

The mock now speaks HTTP/1.1 with keep-alive, like real S3, with `Content-Length` added
to the two response paths that lacked it, and a listen backlog large enough for the
initial burst of connections. With that, both this branch and master produce exactly the
asserted error counts in every failing scenario (`at_part_upload` injected 500,
`connection_reset_by_peer` at part upload and at create multipart upload, `broken_pipe`).

Also fix `BrokenPipeAction.inject_error` reading from `self.rfile`, which does not exist
on the action object - the partial read has to happen on the request handler.

Related: #116222
Comment thread src/IO/HTTP/HTTPClientIO.cpp Resolved
Comment thread src/IO/StdStreamBufFromReadBuffer.cpp Resolved
Since the mock started speaking HTTP/1.1 keep-alive, `do_HEAD` kept writing the
10-byte `Redirected` body of `redirect`. A response to `HEAD` must carry only the
headers of the equivalent `GET`, so those bytes stayed in the socket and the client
read them as the status line of the next response on the pooled connection. With
`max_version_length = 8` that is exactly the
`Malformed message: Invalid HTTP version string` seen in
`test_checking_s3_blobs_paranoid`, and the shorter leftovers made the client block
until the query timed out instead.

Route every response body through `write_body`, which skips the write for `HEAD`,
and set `close_connection` in the actions that tear the connection down so the
keep-alive handler loop does not try to parse another request from a closed socket.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116222&sha=23bca72219a4e46895ee11ebfc8ab7fccedec629&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%203%2F6%29
Related: #116222
…, avoid UB in `seekpos`

`receiveHTTPResponseImpl` now mirrors the cleanup of the
`Poco::Net::HTTPClientSession::receiveResponse` it replaces: a half-parsed response
header leaves the socket at an unknown offset, so the session is closed and the
network exception rethrown when present. Callers that reuse a single
`HTTPClientSession` across retries, such as `HTTPAuthClient`, would otherwise send
the next request on top of the leftover bytes.

`StdStreamBufFromReadBuffer::seekpos` compared `read_buffer->position() + offset`
against the buffer bounds, which is already undefined behavior when the target is
outside the buffer, even though the seek is rejected right after. It now compares
integer distances and only moves the pointer for an in-range target.

Related: #116222
Comment thread src/Common/HTTPConnectionPool.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 4, 2026
alexey-milovidov and others added 3 commits September 9, 2026 17:34
# Conflicts:
#	src/BridgeHelper/CatBoostLibraryBridgeHelper.cpp
…` API too

`getConnection` hands out the whole `Poco::Net::HTTPClientSession` interface, so a
caller can drive a pooled connection through `sendRequest`/`receiveResponse` instead
of `sendRequestHeaders`/`receiveHTTPResponse`. That path did not maintain
`requestBodyComplete`/`responseBodyComplete`, so the flags kept the value of the
previous exchange - `true` on a fresh connection - and `atConnectionDestroy` could
put a connection with a half-sent request or an unread response body back into the
pool. The next borrower would then read the leftover bytes as the beginning of its
own response.

`isRequestBodyComplete` and `isResponseBodyComplete` now take the state from the body
stream itself while it is alive, which is what `HTTPConnectionPool` used to do on its
own before this pull request, and `flushRequest` stores it before dropping the request
stream. `sendRequest` resets both flags, so a session that sent a request and never
received a response is not reported as complete either.

`flushRequest` also flushes the request stream explicitly instead of leaving it to the
stream's destructor, which swallows the exception - again what the pool did before.

Three regression tests in `gtest_connection_pool` pin the contract for that API: a
complete exchange is preserved, while a half-read response and a half-sent request are
not. All three fail without the change (the connection is preserved) and pass with it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`test_when_s3_broken_pipe_at_upload_is_retried` failed in every integration-test shard
with `e.code() = 104, Connection reset by peer` where it expected
`e.code() = 32, I/O error: Broken pipe`.

The `broken_pipe` action of the `broken_s3` mock reads a part of the request and then
aborts the connection with `SO_LINGER` set to zero, that is with an `RST`. A client
that is blocked in `send` when the `RST` arrives gets `ECONNRESET`; one that writes
again after the reset gets `EPIPE`. The `std::iostream` request path lost the first
error (the stream only raised `badbit`, and the flush in the stream's destructor
swallowed the exception), so the failure used to surface as the `EPIPE` of a later
write. Writing the body through a `WriteBuffer` propagates the first error, which is
the accurate one: the peer did reset the connection.

Verified locally against the mock: three runs of the scenario in a row report
`e.code() = 104` with this branch. With the mock action as it is on master - where
`inject_error` raises `AttributeError` before reading anything - the same binary
reports `No message received` instead, so the errno was pinned by the iostream layer
rather than by the mock.

The retried-and-eventually-failed behaviour the test is named after stays asserted by
the multipart counters above.

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

Copy link
Copy Markdown
Member Author

🕵 Updated: merged master (the branch was 4187 commits behind; the only conflict was CatBoostLibraryBridgeHelper.cpp, which master deleted along with the CatBoost integration), addressed the AI review's Request changes verdict, and fixed the one real CI red.

Review finding (blocking) — the legacy pooled-session API did not drive the completion state. getConnection hands out the whole Poco::Net::HTTPClientSession interface, so a caller can use sendRequest/receiveResponse instead of sendRequestHeaders/receiveHTTPResponse; that path left requestBodyComplete/responseBodyComplete at the value of the previous exchange (true on a fresh connection), so atConnectionDestroy could pool a connection with a half-sent request or an unread response body. isRequestBodyComplete/isResponseBodyComplete now take the state from the body stream itself while it is alive - which is what HTTPConnectionPool computed on its own before this pull request - flushRequest stores it before dropping the request stream (and flushes explicitly instead of leaving it to the stream's destructor, which swallows the exception), and sendRequest resets both flags. This is not hypothetical: private-only JWTValidator drives a session through exactly that API.

Three regression tests in gtest_connection_pool pin the contract - LegacyStreamApiCompleteExchangeIsPreserved, LegacyStreamApiHalfReadResponseIsNotPreserved, LegacyStreamApiHalfSentRequestIsNotPreserved. They are load-bearing: with the getters returning the plain flags the last two report preserved = 1 and fail; with the fix all of ConnectionPoolTest passes (24/24, and 77/77 for the whole *HTTP* filter).

CI red — test_when_s3_broken_pipe_at_upload_is_retried in all five integration shards. It expected e.code() = 32, I/O error: Broken pipe and got e.code() = 104, Connection reset by peer. The mock's broken_pipe action aborts the connection with SO_LINGER set to zero, i.e. with an RST; a client blocked in send when the RST arrives gets ECONNRESET, one that writes again afterwards gets EPIPE. The std::iostream path lost the first error (the stream only raised badbit, and the flush in the stream's destructor swallowed the exception), so the failure used to surface as the EPIPE of a later write; writing the body through a WriteBuffer propagates the accurate first error. Reproduced locally against the mock: three runs in a row report e.code() = 104 on this branch, while the same binary against the mock action as it is on master (where inject_error raises AttributeError before reading anything) reports No message received - so the errno was pinned by the iostream layer, not by the mock. The test now accepts either errno; the retry behaviour it is named after stays asserted by the multipart counters above it.

Also verified locally: 05055_native_http_client_framing passes, and a multipart write plus read-back against a real MinIO round-trips 3M rows. Style check clean (the only two local failures are the build-directory symlinks and the settings-history check, both of which need the CI changed_files data).

The sync PR was CONFLICTING with private master and its Config Workflow failed on outdated generated workflow yamls; merged private master into sync-upstream/pr/116222 (same single CatBoost conflict), merged the new public head, confirmed the generator produces no diff and that no private-only call site needs adapting to the new API. That sync PR is MERGEABLE again.

Comment thread src/IO/HTTP/HTTPClientIO.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

This PR replaces the iostream-based HTTP client path with direct buffer I/O: new Poco session methods, connection-pool completeness tracking, and auth, JWT and proxy callers. None of that is on the local query path that ClickBench or TPC-H exercises. The only flagged query is clickbench Q28 at -5.0%, and it stays not_sure: the two tests disagree, the runs were noisy and CPU time is flat. No performance change from this PR shows up in either benchmark.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1059 1006 -5.0% <0.0001 cpu: Q28 is a CPU-bound regex query, and its CPU time is essentially unchanged (15032 vs 14998 ms). The -5.0% wall-clock shift comes from noisy runs, not from the HTTP client rewrite.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: e7b300ec-c7b3-46cd-86f0-c5024721aa43
  • MIRAI run: 803da8c5-e655-442e-98f3-20c14b9eadbb
  • PR check IDs:
    • clickbench_649894_1791599483
    • clickbench_649907_1791599483
    • clickbench_649913_1791599483
    • tpch_adapted_1_official_649919_1791599483
    • tpch_adapted_1_official_649938_1791599483
    • tpch_adapted_1_official_649964_1791599483

… must drop the connection

`HTTPClientSession::sendRequestHeaders` picks `BodyEncoding::UntilEOF` for a `PUT`, `POST` or
`PATCH` that has neither `Content-Length` nor chunked encoding - a body delimited by the end of the
connection. `HTTPRequestBodyWriteBuffer::finalizeImpl` reported every body complete, including that
one, so the pool could preserve such a connection and hand it to the next request while the server
still considered itself to be inside the body of the previous one. The `std::iostream` path it
replaces never allowed that: `HTTPOutputStream::isComplete` returns false unconditionally, and the
pool dropped the socket.

`finalizeImpl` now mirrors `HTTPStreamBuf::close`, the counterpart of this function on that path:
it half-closes the session when keep-alive is off and leaves the request incomplete either way, so
that `isCompleted` is false and the connection is reset instead of stored. Writing the last byte
cannot end this framing, so there is nothing else to report.

No caller in the server sends such a request - `WriteBufferFromHTTP` sets chunked encoding,
`ReadWriteBufferFromHTTP` sets one framing or the other, and the S3 and Azure clients set a content
length - so this restores an invariant of the transport rather than fixing an observed failure.

`RequestBodyWithoutFramingIsNotPreserved` covers the framing mode: it writes a body to a `PUT`
without either framing, asserts the session still reports the request incomplete, and asserts the
pool resets the connection rather than storing it.
Comment thread src/Common/HTTPConnectionPool.cpp Resolved
Comment thread src/IO/HTTP/HTTPClientIO.cpp Resolved
`cppcoreguidelines-init-variables` fails `Build (arm_tidy)` on the new
`char first;`.
alexey-milovidov and others added 2 commits October 10, 2026 00:03
# Conflicts:
#	src/IO/ReadBufferFromS3.cpp
…once`

Each flush of `HTTPRequestBodyWriteBuffer` goes out as a single `writeAllRaw`,
whose length `Poco` narrows to `int`. The buffer size is caller-controlled (e.g.
`max_read_buffer_size` through `ReadWriteBufferFromHTTP`), so a huge buffer could
overflow the send length. Cap it to the same bound the read side uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Updated:

  • Merged master. The only conflict was an include in src/IO/ReadBufferFromS3.cpp; I kept both includes. The clickhouse binary builds locally.
  • Build (arm_tidy, 2/4) was failing in gtest_throttler_constraint.cpp (FifoQueue was removed on master). This is unrelated to this PR, and the fix (be9cfb1 "Fix tidy build") is already on master, so the merge pulls it in.
  • Addressed the review comment: the request-body write buffer is now capped to max_transfer_at_once.

Resolve the conflict in `src/IO/S3/PocoHTTPClient.cpp` with the master change that reads
the error response a server sends before reading the whole request body. The branch writes
the body through `HTTPRequestBodyWriteBuffer` instead of `std::ostream`, so the early
response is now read with the new `receiveEarlyHTTPResponse` (built on
`HTTPClientSession::receiveEarlyResponse`), and the body is finalized inside the `try`
block so that the failure of the last write is handled the same way. When the early
response is used, the request body is left unfinalized and the connection is not reused.

The merge also brings the revert of the `aws` bump (#125030), which caused the TSan data
race on `cpuid_state` that failed the stress test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Updated: merged master.

  • Stress test (amd_tsan) failed because the server aborted on every restart with a TSan data race on cpuid_state in aws-c-common, brought in by the aws bump (Bump aws from 1.11.771 to 1.11.907 #124678). That bump was reverted on master (Revert "Bump aws from 1.11.771 to 1.11.907" #125030), and this merge pulls in the revert.
  • The only conflict was in src/IO/S3/PocoHTTPClient.cpp, against 2f86c31, which reads the error response a server sends before it has read the whole request body. I ported it to the WriteBuffer path: the new receiveEarlyHTTPResponse in src/IO/HTTP/HTTPClientIO.cpp reads the early response through HTTPClientSession::receiveEarlyResponse. The request body is now finalized inside the try block, so a failure on the last write is caught too. When the early response is used, the body is never finalized, so the connection is not returned to the pool.
  • I checked locally: clickhouse and unit_tests_dbms build, the connection-pool / ReadBufferFromS3 / HTTP gtests pass (99 tests), and test_checking_s3_blobs_paranoid::test_early_error_response_at_upload_is_not_retried and ::test_when_s3_broken_pipe_at_upload_is_retried pass.
  • 05238_pretty_squash_broken_pipe is unrelated. It fails across many PRs since 2026-10-09, and a fix is open in Throttle reading in the first subtest of 05238_pretty_squash_broken_pipe #125102.

alexey-milovidov and others added 2 commits October 11, 2026 23:42
Master moved the hex helpers from `base` to `Common` in d1a9a14, so
`HTTPClientIO.cpp` no longer compiled after merging master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Updated:

  • Merged master (clean merge). The only red check was 05339_parquet_prewhere_subcolumn_read_through_column in Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2), which is unrelated to this PR. That test was removed from master by 563bb06 (a revert of the change that added it), so this merge drops it.
  • master moved the hex helpers from base/hex.h to Common/Hex.h (d1a9a14), so HTTPClientIO.cpp now includes Common/Hex.h. The clickhouse binary builds locally and 05055_native_http_client_framing passes.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Updated: merged master (clean merge). The only red check was test_database_disk/test.py::test_copy_of_temporary_table_under_unrelated_name in Integration tests (arm_binary, 2/4). It is unrelated to this PR: it fails across many PRs and on master, and the fix (3e84b09, "Fix test_copy_of_temporary_table_under_unrelated_name after #123902") is already on master, so this merge brings it in. Translation units touched by both this PR and the merged master changes (PocoHTTPClient, ReadBufferFromS3, YTsaurusClient, XDBCDictionarySource) build locally.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check was CH Inc sync: the robot could not merge private master into the sync branch because of a conflict in src/IO/S3/PocoHTTPClient.cpp. That conflict was against 2f86c31 ("Read the error response the S3 server sends before reading the whole request body"), which this PR had already resolved when it merged master. I resolved it the same way, using the file from the PR head (private master has the same version of this file as public master), then merged the PR head b4a8f53 cleanly and pushed the sync branch. The sync PR is now MERGEABLE, and private CI is running again. Every other check on this PR is green, and no review threads are open.

: ReadBufferFromIStream(result_.GetBody(), size_), result(std::move(result_)), watch(std::move(watch_))
: BufferWithOwnMemory<ReadBuffer>(size_), result(std::move(result_)), watch(std::move(watch_))
{
/// The S3 HTTP client hands the body of a response over as a ReadBuffer wrapped into a

@alexey-milovidov alexey-milovidov Oct 13, 2026 •

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.

Probably the most interesting part. We use iostreams only as a wrapper for interface compatibility with the AWS SDK. Interesting and a good solution.

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

I found the implementation mostly straightforward. All good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 13, 2026
Merged via the queue into master with commit 4575290 Oct 13, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the native-http-client branch October 13, 2026 22:05
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 2026
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 14, 2026
…hod-62352

Master's native HTTP client (ClickHouse#116222) changed the request-body callback of
StorageURLSource from std::ostream to WriteBuffer; keep the PR's http_method_
parameter with master's callback type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@CheSema

CheSema commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

I actually like the changes. it is hard to use iostream correctly in c++, it is a real pain.

Otherwise I do not see a big rash with this changes. Even that the write path did smaller sends call, it hardly affected performance, or at least we do not have enough sensitive instruments to notice it. So, do not see why we need to skip the proper develop cycle and overload the team with reviewing already merged out of cycle PR. Sure it speeds up things but with the cost it slows down the rest team.

The change is good, I hope we will be capable to understand it fast if it breaks.

}


HTTPClientSession::BodyInfo HTTPClientSession::sendRequestHeaders(HTTPRequest& request, uint64_t * connect_time, uint64_t * first_byte_time)

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.

sendRequestHeaders seems to be heavily copying existing sendRequest
Any chance common parts can be extracted in a helper method?

Comment on lines +480 to +498
BodyInfo body;
if (!_expectResponseBody || response.getStatus() < 200 || response.getStatus() == HTTPResponse::HTTP_NO_CONTENT
|| response.getStatus() == HTTPResponse::HTTP_NOT_MODIFIED)
{
body.encoding = BodyEncoding::NoBody;
}
else if (response.getChunkedTransferEncoding())
{
body.encoding = BodyEncoding::Chunked;
}
else if (response.hasContentLength())
{
body.encoding = BodyEncoding::ContentLength;
body.content_length = static_cast<Poco::UInt64>(response.getContentLength64());
}
else
{
body.encoding = BodyEncoding::UntilEOF;
}

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.

}


int HTTPSession::readRaw(char* buffer, std::streamsize length)

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.

why not std::span?


/// Anything else leaves the get area behind; the bytes in it were counted as read.
offset -= egptr() - gptr();
setg(nullptr, nullptr, nullptr);

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.

[P2] Preserve unread data after a failed input seek. underflow advances the underlying ReadBuffer to the end of its block while unread bytes remain in the get area. After one byte is read, seekg(-1, std::ios::beg) on a non-seekable body reaches this setg and then fails; clearing the stream error and reading again starts at the next block, silently skipping the remaining bytes. Before clearing the get area, synchronize read_buffer->position() to gptr() only when gptr() != egptr() (an empty get area may point into an older block), and keep the original offset. Please cover failed-seek-then-clear-and-read. I found no current in-tree caller that continues after a failed seek.

/// because an interface demands one - the AWS SDK, for example - read from the buffer
/// directly instead of copying the data through the stream.
ReadBuffer & getReadBuffer() const { return *read_buffer; }
std::unique_ptr<ReadBuffer> extractReadBuffer() { return std::move(read_buffer); }

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.

[P2] Can we remove extractReadBuffer until there is a caller? This new public method has no uses in the PR head, and moving out read_buffer leaves the still-live streambuf with a null pointer that underflow and seekpos dereference on the next operation. Removing it keeps the API small and avoids exposing an invalid state without a lifecycle contract.


/// Waiting for `100 Continue` is only possible through `peekResponse`, which needs the request
/// body stream that this method does not create.
if (request.getExpectContinue())

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.

[P2] Preserve Expect: 100-continue for user-provided headers. The earlier discussion chose rejection because no hardcoded caller sets this header, but url and the URL engine accept headers(...): reads pass it through ReadWriteBufferFromHTTP::prepareRequest, and uploads pass it through the additional headers of WriteBufferFromHTTP. A URL read or upload with headers('Expect'='100-continue') worked before this PR and now throws NotImplementedException here. The old sendRequest sent the body without waiting and receiveResponse skipped interim 100 responses; the new receiveHTTPResponseImpl also skips them. Please keep the previous send-then-skip behavior by removing this rejection, and add a focused GET/upload regression case.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 25, 2026
Since the HTTP client writes request bodies through `HTTPRequestBodyWriteBuffer`
(ClickHouse#116222), the body leaves only when `callImpl` finalizes the buffer after the
callback returns, and the buffer's destructor cancels rather than flushes. A
throw inside the callback after the body is written therefore never reaches
the catalog; on the `std::iostream` path the stream destructor still wrote the
buffered request out while unwinding.

Measured on the merged tree: `test_catalog_commit_transport_failure_unknown_keeps_files`
and `test_catalog_commit_std_exception_unknown_keeps_files` failed with
`assert '2' == '3'`, and the REST catalog logged no commit after the injected
failure. They now inject once the response has arrived (`..._response_lost_net`,
`..._response_lost_std`), as their confirming twins already do, so the commit
lands and the unresolved read-back must keep its files. The catalog log shows
the commit applied in both arms.

`iceberg_catalog_commit_std_throw` has no user left and is removed. The comment
at `request_body_written` and the refused arm's description now state what the
new transport does; the flag itself stays where it is, which is conservative.

Mutant: the no-status handlers rethrow the original error when the read-back
cannot confirm the snapshot -> exactly the two re-pointed arms and the refused
arm fail, the other 16 commit arms pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-networking The connection layer under the protocols, on the server and on the client side: socket read / wri... and removed comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-networking The connection layer under the protocols, on the server and on the client side: socket read / wri... pr-performance Pull request with some performance 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.

5 participants