Skip to content

Watch the connection for an early response while sending an HTTP request body - #130858

Closed
CheSema wants to merge 15 commits into
masterfrom
s3-monitor-response
Closed

CheSema wants to merge 15 commits into
masterfrom
s3-monitor-response

Conversation

@CheSema

@CheSema CheSema commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Related: #124326
Related: #124557
Related: #130514

A server can answer a request it rejects before reading the whole body and then close the connection: MinIO does this for NoSuchUpload on an expired multipart upload, and AWS S3 answers a rejected upload after reading about 10 MB. ClickHouse wrote the whole body first, so the write failed with Broken pipe and the error was retried as a network error. #124557 read that early answer for S3, but only over plain HTTP, because OpenSSL allows no read after a failed write.

The change:

  1. While an HTTP request body is sent, the client now watches the connection for a response (RFC 9112, section 9.5), and it sends with non-blocking writes. So no write can fail before the answer is read: a failed write makes a TLS answer unreadable.
  2. The response is parsed as it arrives by a new incremental parser, Poco::Net::HTTPResponseParser. For the same bytes, it gives the same result and the same exceptions as Poco::Net::HTTPResponse::read, and it checks the header limits as the data arrives. An error status stops the body at once. A 2xx is finished after the body. A 100 Continue is skipped. The blocking read of a response uses the same parser.
  3. This applies to every sendHTTPRequest caller (S3, Azure, the url engine, and others) with no caller change. The header limits are now given to sendHTTPRequest, because the response is parsed while the body is sent; S3 and Azure pass theirs there. This replaces the plain-HTTP-only workaround of Fix nested S3 request retries and read the error an S3 server sends before the whole request body #124557.

Known limitation: Silk fiber sockets have no non-blocking mode, so they keep the blocking writes without the watching, and an early response on them is read only after the body. Over plain HTTP they also lose the read after a failed write that #124557 added. A follow-up can add a fiber-aware wait for reading or writing to these sockets.

A reading guide with diagrams: #130858 (comment)

Changelog category (leave one):

  • Improvement

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

While sending the body of an HTTP request (S3, Azure, the url engine and other HTTP clients), ClickHouse now watches the connection for an early response, so an error that the server sends before it reads the whole body, such as NoSuchUpload for an expired multipart upload, is reported instead of being retried as a network error, also over TLS.

🤖 Generated with Claude Code


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

While the body is sent, the connection is watched for a response
(RFC 9112, 9.5) with non-blocking writes, so an early error such as
`NoSuchUpload` is reported instead of `Broken pipe`, also over TLS.
Replaces the plain-HTTP-only early-response read of #124557.
Setting `s3_monitor_response_while_sending`.
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a7d93f6]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_ytsaurus/test_dictionaries.py::test_yt_lookups_throttler_proxy_failover FAIL cidb
test_ytsaurus/test_dictionaries.py::test_yt_lookups_default_chunk_size_is_unlimited FAIL cidb
test_ytsaurus/test_dictionaries.py::test_yt_lookups_unlimited_chunk_size FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (amd_illumos) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

The PR monitors responses while sending HTTP request bodies, using nonblocking writes and an incremental response parser to report early server errors over HTTP and HTTPS. Static review of a7d93f6e2cd03c7c6ccd4fdb8eac0293bca94614, including all previous discussion, found no outstanding actionable findings. No new inline comments or existing-thread updates were needed.

Missing context / blind spots
  • ⚠️ Focused unit and integration CI results for this head were still pending. No configured local ClickHouse build was available, so the added regression tests were reviewed but not executed locally.
Final Verdict

Status: ✅ Approve. No code changes requested; runtime validation remains subject to the pending CI checks.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 11, 2026
Comment thread base/poco/Net/src/HTTPSession.cpp Resolved
Comment thread src/IO/HTTP/HTTPClientIO.cpp Resolved
Comment thread src/IO/HTTP/HTTPClientIO.cpp Resolved
`HTTPRequestBodyWriteBuffer` always watches the connection while it sends
the body; an early final response is kept in the session and returned by
`receiveHTTPResponse`, which fails closed for a success status. No setting.
The non-blocking switch around the send uses `ScopedNonBlocking`, moved
out of `SocketPeerClosed.cpp`.
@CheSema CheSema changed the title Watch the S3 connection for an early response while sending the request body Watch the connection for an early response while sending an HTTP request body Nov 11, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Nov 11, 2026
The response is parsed into the session between body chunks: an error
status stops the body, a success is finished after it, so an early `200`
or streamed headers no longer fail or block the request. The blocking
throttle wait goes to the socket that TLS charges, so
`max_remote_write_network_bandwidth` holds over HTTPS. Also a deadline
across `EINTR`, and no completed chunked request after an early stop.
Comment thread src/IO/HTTP/HTTPClientIO.cpp Resolved
Comment thread src/IO/HTTP/HTTPClientIO.cpp Resolved
Comment thread src/IO/ScopedNonBlocking.cpp Resolved
@CheSema

CheSema commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

How to read this PR

Review the whole diff, not commit by commit: the early commits contain intermediate designs that the later commits replace. The order below puts the most important parts first.

# Where What to look at
1 HTTPRequestBodyWriteBuffer::writeBody in src/IO/HTTP/HTTPClientIO.cpp The core loop. The exception for Silk fiber sockets (isFiberSocket, blocking writes); poll for readable and writable events; the send timeout as one deadline, also across EINTR; the readable event is handled first; fillBuffer under ScopedNonBlocking; peer_closed; the send under ScopedNonBlocking
2 HTTPRequestBodyWriteBuffer::checkResponse, feedHTTPResponseParser, finalResponseComplete The decision. The buffered bytes go to the parser of the session. A status of 300 or more stops the body; any other complete response stops the watching; a complete 100 Continue is dropped, and the next response is parsed
3 Poco::Net::HTTPResponseParser in base/poco/Net The parser. A state machine with one state per position in the grammar of HTTPResponse::read and MessageHeader::read. feed takes all bytes until the header ends and none after it; feedEof gives the end-of-stream behavior of HTTPResponse::read; the limits are checked at every field and every line as they arrive, also in a 1xx
4 readHTTPResponseHeader, receiveHTTPResponseImpl The blocking path. It continues the same parser with blocking fillBuffer calls, copies the result into the HTTPResponse of the caller, and resets the session on an error. The end of the data after a 100 Continue gives NoMessageException, as before
5 HTTPClientSession::responseParser; sendHTTPRequest The parser lives in the session. sendRequest and sendRequestHeaders reset it with the default limits, and sendHTTPRequest sets the limits of the caller. Contract change: the limits come from sendHTTPRequest, and the limits set on the HTTPResponse given to receiveHTTPResponse are not used. S3 and Azure, the only callers with other limits, pass theirs to sendHTTPRequest
6 HTTPRequestBodyWriteBuffer::finalizeImpl After an error stop, nothing more is sent, and the body is not marked complete, so the pool drops the connection. The same is true when the error arrives while the chunked terminator is sent
7 HTTPSession::fillBuffer, HTTPSession::writeRawNonBlocking in base/poco/Net The Poco primitives. fillBuffer appends to the read buffer and consumes nothing (it moves the unread bytes to the front first). writeRawNonBlocking does one non-blocking send; "would block" gives 0 and calls the data hooks with atFail; the blocking throttle wait comes before the send
8 SocketImpl::throttleSendBlocking, SecureStreamSocketImpl::throttleSendBlocking TLS throttling. throttleSendBlocking is virtual, and the TLS socket forwards it to the inner socket, which SSL_write charges
9 src/IO/ScopedNonBlocking.{h,cpp}, src/IO/SocketPeerClosed.cpp The guard moved out of SocketPeerClosed.cpp without a change, and now has two users
10 src/IO/S3/PocoHTTPClient.cpp, HTTPClientSession.{h,cpp}, HTTPClientIO.cpp Removals: the catch (Poco::IOException) block of #124557, receiveEarlyResponse, receiveEarlyHTTPResponse, and the two character-by-character ports of the Poco reader (readHTTPMessageHeader, the old readHTTPResponseHeader)
11 Tests gtest_http_response_parser.cpp: each input, split at every byte, gives what HTTPResponse::read gives for it, with three sets of limits. gtest_http_early_response.cpp: an early error with a field longer than 8 KiB, and one with too many fields that never ends its header. gtest_silk_fiber_stream_socket.cpp: a body on plain and TLS fiber sockets. Integration test_checking_s3_blobs_paranoid: early-error rows for HTTP and HTTPS with a MinIO-like server and with lingering close (like AWS S3), and test_tls_upload_is_throttled; the TLS listener (--tls-port) and the lingering mode of the mock

How it works

A rejected upload over TLS, before and after

BEFORE (blocking send)                       AFTER (watched send)

client              server                   client                       server
  | headers ------->  |                        | headers ----------------->  |
  | body chunk ---->  | 404 + close (early)    | body chunk -------------->  | 404 + close (early)
  | body chunk ---->  |<----                   | poll: readable  <-----------|
  | body chunk -->X   | RST                    | fillBuffer, parser: status 404
  | send() fails:     |                        | stop sending, drop the rest
  |  "Broken pipe"    |                        | receiveHTTPResponse -> 404 NoSuchUpload
  | TLS: answer lost  |                        |   (also over TLS: no write ever failed)
  | -> retried as a network error             | -> reported, not retried

The writeBody loop

          stopped? --yes--> drop the data, return
              | no
          fiber socket? --yes--> writeAllRaw (blocking), return
              | no
              v
          +--------------------------------------------------------------+
          | poll(fd, watch ? POLLIN|POLLOUT : POLLOUT, remaining time)   |
          |   EINTR -> recompute the remaining time from the deadline    |
          |   time over -> TimeoutException      error -> NetException   |
          +-------------------+------------------------------+-----------+
                              |                              |
           readable (watching)|                   writable (or peer_closed)
                              v                              v
      +--------------------------------------+   +------------------------------+
      | ScopedNonBlocking + fillBuffer()     |   | ScopedNonBlocking +          |
      |   TLS: SSL_read, a ticket gives 0    |   | writeRawNonBlocking(data)    |
      |   -1 -> peer_closed (next write      |   |   throttle wait first        |
      |         reports the real error)      |   |   would block -> 0, retry    |
      | checkResponse():                     |   |   with the same buffer       |
      |   feed the parser (may throw)        |   | data += sent, size -= sent   |
      |   status >= 300 -> stopped, return   |   +------------------------------+
      |   complete      -> stop watching     |
      +--------------------------------------+
            watch = !peer_closed && !response_header_complete

Data path of the response

 socket --(fillBuffer: append)--> session read buffer (8 KiB)
                                          |  feed(): all bytes up to the end of the header
                                          v
                       session.responseParser()      limits from sendHTTPRequest
                       (HTTPResponseParser)          partial name/value kept across refills
                                          |
                       body bytes stay in the buffer
                                          |
 during the body:  writeBody  -> fillBuffer non-blocking -> feed -> decide
 after the body:   receiveHTTPResponse -> fillBuffer blocking -> feed -> until complete
                                          |
                                          v
                   copy into the HTTPResponse of the caller
                   --> HTTPResponseReadBuffer (the body starts in the buffer)

The parser states

Start -> LeadingSpace -> Version -> SpaceBeforeStatus -> Status -> SpaceBeforeReason -> Reason
                                                                                         |
                                                    StatusLineCR <-- '\r' ---------------+
                                                         | '\n'                          | '\n'
                                                         v                               v
   +------------------------------------------------> LineStart <------------------------+
   |                                                  |  '\r' -> FinalLine -> '\n' -> Done
   |                                                  |  '\n' -> Done
   |                                                  |  other: field limit check
   |                                                  v
   |      Name -- ':' --> SpaceBeforeValue --> Value -- '\r' --> ValueCR
   |        '\n' (line without a colon) -> LineStart   | '\n'      | '\n'
   |                                                   v           v
   +-- other: add the field <-------------------- AfterLine <------+
                                                  ' ' or '\t' -> FoldValue (-> FoldCR) -> AfterLine

What happens for each status

status line parsed during the body
 ├── >= 300           -> stop sending now; finish the header in receiveHTTPResponse, return at once
 │                       (request incomplete -> pool drops the connection)
 ├── 100 Continue     -> dropped when complete; the next response is parsed
 └── other (2xx, 1xx) -> keep sending; keep parsing until the header is complete, then stop watching;
                         receiveHTTPResponse returns it after the body
                         (streamed X-ClickHouse-Progress lines never block the upload)

TLS throttling of the non-blocking send

SecureStreamSocketImpl (outer)          StreamSocketImpl (inner, used by SSL_write)
  _sndThrottler, budget A                 _sndThrottler, budget B

without the forward:
  throttleSendBlocking -> outer budget A (sleeps once, then never charged)
  SSL_write -> inner throttleSend(non-blocking) -> books budget B, never sleeps
  => no throttling over TLS (test: 80,991 us slept for 8 MiB at 1 MB/s)

with the forward:
  throttleSendBlocking -> forwarded -> inner budget B (sleeps as needed)
  SSL_write -> inner throttleSend -> budget B already granted, no extra wait

What to check while reading

  1. OpenSSL: an SSL_read while an SSL_write is pending after WANT_WRITE. A retry must pass the same buffer, and writeBody does that.
  2. The parser against Poco: the gtest compares with HTTPResponse::read for every split. One deliberate difference: the status is checked at the end of the status line, so a non-numeric status throws before the rest of the header is read.
  3. Exceptions: a response that breaks the syntax or the limits during the body makes the write throw; after the body, receiveHTTPResponse throws, and resets the session as before.
  4. Connection reuse: after an error stop, the request stays incomplete. Check _requestBodyComplete and the path of the chunked terminator.
  5. Known gaps, for small follow-up commits in this PR:
    • a stale writable event after the throttle wait in writeRawNonBlocking: the response that arrives during the wait is not checked before the send;
    • a busy loop on a TLS WANT_READ during a write;
    • no SSL_write after a fatal TLS error;
    • a forced reconnect after an early stop;
    • the dead if (!response_body) in the S3 client;
    • unused includes in SocketPeerClosed.cpp.

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

clickhouse-gh Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a7d93f6e2 with master 6618395f5 (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

59 object files changed (+57.01 KiB total), 2 added.

Object file Master PR Δ
base/poco/Net/CMakeFiles/_poco_net.dir/src/HTTPResponseParser.cpp.o new 43.64 KiB +43.64 KiB
src/CMakeFiles/clickhouse_common_io.dir/IO/ScopedNonBlocking.cpp.o new 16.37 KiB +16.37 KiB

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.63, programs/clickhouse-keeper ×0.67 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.6 s 13.5 s +9.9 s (+281%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.3 s 7.2 s +5.1 s (+246%)
Compile time of recompiled translation units

417 translation units recompiled, 2775 s compile time in total, 415 of them have a recent master baseline.

Job report

Comment thread src/IO/HTTP/HTTPClientIO.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Nov 13, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Nov 13, 2026
@CheSema

CheSema commented Nov 19, 2026

Copy link
Copy Markdown
Member Author

Superseded by the split of #131084: #132376 (socket primitives) and #131102 (watching).

@CheSema CheSema closed this Nov 19, 2026
@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-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant