Repository navigation
Record the HTTP connection behind each blob storage request - #116361
Conversation
Add five columns to system.blob_storage_log describing the connection that
carried the operation: connection_id, connection_local_port,
connection_socket_inode, connection_requests and
connection_idle_microseconds.
The motivation is that a keep-alive connection to object storage is not
equally fast over its whole life. Two GETs of the same size, issued from
the same node at the same moment, routinely differ several-fold in time to
first byte, and the existing counters cannot tell them apart:
DiskConnectionsReused says a session came out of the pool, not how long it
had been sitting idle there. With these columns the two populations can be
separated directly:
SELECT
connection_idle_microseconds < 20000 AS warm,
count(), quantile(0.5)(elapsed_microseconds)
FROM system.blob_storage_log WHERE event_type = 'Read'
GROUP BY warm
Everything is scoped to the socket rather than to the session object that
wraps it, so a row cannot claim a connection is new but has been idle for a
minute. connection_id is process-unique and assigned when the socket is
established; group by it rather than by the port or the inode, since the OS
recycles both as soon as a socket closes, promptly enough that consecutive
connections to one endpoint often come back with the same pair.
Identity is derived from the socket itself, in notifySocketInode(), rather
than from the connect call sites: Poco reaches a connected socket by several
routes (handed out by the pool, connected lazily inside sendRequest, copied
in by assign()), and hooking each one separately means whichever route gets
forgotten silently reports id 0 - which is what an earlier version of this
patch did.
The values travel from the pool to the log through a thread-local, read in
BlobStorageLogWriter::addEvent, the single funnel for every blob storage
event. Poco's HTTP client is synchronous, so a request and the log entry
describing it are adjacent on one thread. Reading clears the slot, so an
event that made no request of its own reports zeros instead of inheriting
stale numbers; the cost is that a batched delete attributes the connection
to the first event of the batch only.
Only the Poco connection pool is instrumented, so this covers S3 and the
other HTTP-backed disks. Azure Blob uses its own SDK stack and will report
zeros until that client gets the same hook.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [57a517d] Summary: ✅
AI ReviewSummaryAdds HTTP connection identity, reuse count, age, and idle time to Final Verdict✅ Approve |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes38 object files changed (+47.85 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units99 translation units recompiled, 891 s compile time in total, 98 of them have a recent master baseline. |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
Four findings from the review, all of them real. The socket-scoped state lived on the `PooledConnection` wrapper, but the wrapper is not what survives a keep-alive round trip. Both of the pool's reuse paths move the socket to a fresh wrapper with `Poco::Net::HTTPClientSession::assign`: `EndpointConnectionPool::atConnectionDestroy` clones a returning connection into a new `PooledConnection` before storing it, and `PooledConnection::reconnect` swaps in a borrowed one. The fresh wrapper started with `socket_fd = -1` and `socket_inode = 0`, so `notifySocketInode` saw a socket it did not recognise and minted a new `connection_id`, restarted `established_at` and zeroed `requests_on_socket` - for the very same live socket. Grouping `system.blob_storage_log` by `connection_id` therefore did not follow a reused connection, and `connection_requests` was always 0. The fields describe the socket, so they now travel with it: `assignFrom` carries them across the handoff, and both call sites use it. `getPooledConnection` exists so `reconnect` keeps the concrete type it needs for that. `BlobStorageLogWriter::addEvent` took the thread-local after its `!log` and `shouldIgnorePath` early returns, so an event that was not logged left the slot populated and the next event on that worker thread inherited an unrelated socket - including events that should report zeros. It is taken first now, on every path. The test asserted only self-consistency, which a broken implementation that mints an id per borrow satisfies just as well. It now requires `max(connection_requests) > 0`: three sequential queries against the same endpoint, so a socket must be handed back out at least once. The `blob_storage_log.mdx` hunk was inside the `AUTOGENERATED` region and failed the docs check; the `ColumnsDescription` in `BlobStorageLog.cpp` is the source of truth for those descriptions, so the hunk is dropped. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…le idle time Two gaps remained on the `PooledConnection::reconnect` path. `last_idle_time` was copied by `assignFrom` together with the rest of the socket state, but it is a sample taken for the *previous* request, not a property of the socket. A connection borrowed from the pool here may have been sitting idle far longer than that sample says, so re-sample it before publishing. The cached `socket_fd` / `socket_inode` pair was never cleared when the session dropped its socket, so a reconnect that came back with the same fd number and the same inode - which the kernel does hand out promptly after a close - inherited the old `connection_id`, `established_at` and `requests_on_socket`. `forgetSocketIdentity` is now called on every path that drops the socket, so `notifySocketInode` must mint a new id for the new TCP connection. Covered by two new cases in `gtest_connection_pool`, both going through `reconnect`: one asserts a fresh id and a zeroed request count after an abort, the other that reusing an idle stored connection reports the time it really spent in the pool.
`Poco::Net::HTTPClientSession::assign` ends with `session.reset()`, which reaches the `PooledConnection::reset` override and now clears the source's cached socket identity. Reading those fields after `assign` therefore returned an unidentified socket, so every handoff minted a fresh `connection_id` and restarted the request count - the exact thing `assignFrom` exists to prevent. Take the copies first. Caught by `ConnectionPoolTest.ConnectionInfoIdleTimeAfterReconnect`; all 23 cases of `gtest_connection_pool` pass.
`setCurrentHTTPConnectionInfo` used to run for every consumer of `HTTPConnectionPool`, while the only reader is `BlobStorageLogWriter::addEvent`. A `StorageURL` read, a dictionary source or a proxy-configuration fetch on a worker thread left its connection in the slot, and the next blob storage event on that thread took it - so a row for local or HDFS object storage, which uses no HTTP connection at all, could report a socket it never used. Publishing is now opt-in: `HTTPConnectionInfoScope`, opened by the S3 and Azure HTTP clients around each request they issue, and nothing is recorded outside of one. Entering the scope also drops whatever was left over, so a request that fails before reaching the wire reports no connection rather than the previous one. Regression: `ConnectionPoolTest.ConnectionInfoIsNotPublishedOutsideScope`.
…he row The `HTTPConnectionInfoScope` was opened by the S3 and Azure HTTP clients around every request they sent, but not every such request is followed by a `system.blob_storage_log` row: the `HeadObject` issued by `s3_check_objects_after_upload` after the `Upload` row, the `GetProperties` issued by `azure_check_objects_after_upload`, the credential refreshes made by the SDKs through the same transport. Any of them repopulated the thread-local slot after the real row had taken it, and the next `BlobStorageLogWriter::addEvent` on that thread - possibly for a request that never reached the wire, or for local object storage - inherited an unrelated socket. The scope now belongs to the code that writes the row: it is opened right before the request is issued and lives until `addEvent` has been called, at every S3/Azure site that logs (`WriteBufferFromS3`, `copyS3File`, `deleteFileFromS3`, `ReadBufferFromS3`, `WriteBufferFromAzureBlobStorage`, `copyAzureBlobStorageFile`, `AzureObjectStorage`, `ReadBufferFromAzureBlobStorage`, `WriteBufferFromAzureDataLakeStorage`). Its destructor now clears the slot, so it is empty whenever no scope is open, by construction: a request the HTTP client sends outside of a scope publishes nothing, and one sent inside a scope whose row is never written leaves nothing behind. The two `PocoHTTPClient` transports no longer know about the slot at all. `ConnectionPoolTest.ConnectionInfoIsClearedWhenScopeEnds` covers the stale-slot case (published, not taken, scope ends, slot empty), and `04106_blob_storage_log_connection_info` now runs its upload with `s3_check_objects_after_upload = 1` so the unlogged `HeadObject` path is exercised. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116361&sha=aabb17debf1c5956548f3b8f21fb45df6c641f76&name_0=PR&name_1=Integration%20tests%20(amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6) and provide a fix in a separate PR. If the fix is already in progress, link it here. The job hit |
|
🕵 Both reds are one event, and the tree that produced them predates two of the three fixes for it. The job's own head is pre-fix
The job ran 09:47:01 to 11:37:26Z, so #117412 reached master while it was still running, about six minutes before it finished. The job's own environment says the same thing without any ancestry math: Your current head The two reds are one kill, one second apartThree kernel records, all
#117564's mechanism is visible inside this job, not merely absent from the treeBoth modules it changes ran in this shard: Class statusTrees carrying the guard row over trees run, on
Each of the eight trees that has fired since #117564 merged is individually So there is no separate PR to writeThe fixes are #117412 and #117564, both merged, and your current head has both. |
`PooledConnection::sendRequest` publishes the connection it is about to use before handing the request to Poco, so that a request which fails on the wire is still attributed to the socket that carried it. Poco can reconnect from inside `sendRequest` when the borrowed keep-alive connection turns out to be dead, and the `reconnect` override re-publishes the replacement - but only on success. When the reconnect itself threw - `HTTP_CONNECTION_LIMIT_REACHED` at the group hard limit, a connect failure, an exhausted ephemeral port range - the pre-send publish survived inside the still-open `HTTPConnectionInfoScope`, and the error row the caller then wrote claimed the `connection_id`, `connection_requests` and `connection_age_microseconds` of a socket that never carried the request. That broke the contract of these columns exactly on failed requests. `reconnect` now drops the published socket right after closing it, before anything that can throw; on success the publish at the end of `reconnect` puts the replacement in its place. `clearCurrentHTTPConnectionInfo` is the read-free counterpart of `takeCurrentHTTPConnectionInfo` that this needs. `ConnectionInfoClearedWhenReconnectFails` pins the behaviour: a group hard limit of one, already reached by the connection under test, makes the reconnect inside `sendRequest` throw before any connect attempt, and the info taken where the caller would log the failure has to be empty.
|
🕵 Merged master ( Thanks @groeneai for confirming that #118234 tracks None of the three failures on the previous head
|
|
🕵 Merged master ( The only failure on the previous head |
|
🕵 Merged master ( The only failure on the previous head |
|
🕵 Merged master ( The only failures on the previous head
|
# Conflicts: # src/IO/S3/PocoHTTPClient.cpp
|
🕵 Merged master ( |
|
🕵 Merged master ( The only failure on the previous head |
|
🕵 |
|
🕵 |
|
🕵 Merged master ( The only failure on the previous head |
Master armed an `HTTPConnectionInfoScope` around every request that writes a `system.blob_storage_log` row (ClickHouse#116361), including this writer's `runWithRetries`. This branch sends the guarded flush and the publishing rename through `runOnceRetryingForbidden` instead, which had no scope, so after the merge those two rows always reported no connection. Arm it there too, on the same `blob_log != nullptr` condition. The cleanup delete writes no row, as on master, so it needs none. The new test records, in the fake transport, whether each request went out inside an armed scope: with a blob log the Flush and the Rename were uncaptured before this change (Create and Append were), and with `scope(true)` the no-blob-log arm fails instead. `getAdlsGen2Url` (ClickHouse#124721) is what a query-created disk's host is checked against; its comment now names `makeAdlsGen2FileSystemClient` too, since the writer's requests come from that builder here. Checked with a throwaway probe: for token, SAS and connection-string auth (including a `DfsEndpoint` on another host) every Create, Append, Flush and Rename goes to the host `getAdlsGen2Url` returns. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added six columns to
system.blob_storage_logdescribing the HTTP connection that carried each object storage request:connection_id,connection_local_port,connection_socket_inode,connection_requests,connection_age_microsecondsandconnection_idle_microseconds. This makes it possible to see whether a slow request landed on a freshly opened socket or on a keep-alive connection that had been sitting idle in the pool.Documentation entry for user-facing changes
docs/reference/system-tables/blob_storage_log.mdxis generated fromColumnsDescriptioninsrc/Interpreters/BlobStorageLog.cpp, which is where the new columns are described.Why
A keep-alive connection to object storage is not equally fast over its whole life. Two GETs of the same size, issued from the same node at the same instant, routinely differ several-fold in time to first byte — and nothing the server currently exposes distinguishes them.
DiskConnectionsReusedsays a session came out of the pool; it does not say how long it had been sitting there, or even which socket it ended up on.This came out of chasing a bimodal read-latency distribution on ClickHouse Cloud: two sharp, stable populations at ~23 ms and ~92 ms, present simultaneously within a single query on different threads, with the mixture weight tracking recent request volume (73% fast at 50 GET/s, 0.5% fast once the node went quiet). Read size, code path, request type, retries, throttling, object age, connection creation and CPU were all ruled out. Per-connection freshness is the obvious remaining suspect and the one thing that could not be measured. Now it can:
Design notes
Everything is scoped to the socket, not to the session object wrapping it, so a row can never claim a connection is new while reporting a minute of idle time.
connection_requests = 0if and only ifconnection_idle_microseconds = 0, and idle never exceeds age.Group by
connection_id, not by the port or the inode. The id is process-unique and assigned when the socket is established. The OS recycles both ports and socket inodes as soon as a socket closes, and promptly enough that consecutive connections to one endpoint routinely come back with the same pair — measured, not assumed: reading one Parquet file from S3 produced four distinct connections that all reported local port 41602 and inode 74685781. The port and inode are still there, because they are what joins against a packet capture or a/proc/net/tcprow taken at the time.Identity is derived from the socket in
notifySocketInode()rather than from the connect call sites. Poco reaches a connected socket by several routes — handed out by the pool, connected lazily insidesendRequest, copied in byassign()from another session — and hooking each separately means whichever route is forgotten silently reportsconnection_id = 0. An earlier version of this patch did exactly that, on 3 of 7 requests. The cost is onefstatper HTTP request, against a network round trip.The values reach the log through a thread-local, published by the pooled session and read in
BlobStorageLogWriter::addEvent. Poco's HTTP client is synchronous, so a request and the log entry describing it are adjacent on one thread. Publishing is opt-in: the code that writes a row opens anHTTPConnectionInfoScopearound issuing the request and logging it, and the scope clears the slot both on entry and on exit. The pool is shared withStorageURL, dictionary sources, the proxy resolver, the REST catalogs, the SDKs' credential refreshes and the post-upload existence checks (s3_check_objects_after_upload), none of which produce a row - and since none of them opens a scope, none of them can leave a socket behind for the next row on that thread to inherit. Taking clears the slot too, so a batched delete attributes the connection to the first event of the batch only. Both properties are documented inHTTPConnectionInfo.h.Scope: S3 and Azure Blob Storage, both of which send their requests through the Poco connection pool. Local and HDFS object storage use no HTTP connection and report zeros.
Testing
tests/queries/0_stateless/04106_blob_storage_log_connection_info.sqlasserts the invariants that must hold regardless of workload: every HTTP-backed request has a non-zero id, port and inode; oneconnection_idnever shows two different ports or inodes; a socket's first request has no idle time; and idle never exceeds age.Verified by hand against real S3 (public bucket, no credentials) with a locally built server: all six columns populate, all of the above invariants hold, and the recycled port/inode case above is correctly split into separate ids.
ConnectionPoolTest.ConnectionInfoNewIdAfterReconnectandConnectionPoolTest.ConnectionInfoIdleTimeAfterReconnectingtest_connection_poolcover thePooledConnection::reconnectpath, where the socket - and all the bookkeeping that goes with it - is swapped out from under a session in the middle of a request: a reconnect onto a new socket must report a new id and a zeroed request count, and a reconnect onto an idle connection taken from the pool must report the time that socket really spent waiting there.ConnectionInfoIsNotPublishedOutsideScopeandConnectionInfoIsClearedWhenScopeEndscover the handoff itself: a request outside a scope publishes nothing, and a request inside a scope that is never taken is gone once the scope ends.Against a local MinIO the stateless test shows all three requests sharing one
connection_idand one port, withconnection_requestsgoing 0 → 4 → 6: the unloggedHeadObjectchecks in between advance the socket's counter but leave no row and no stale state.Workflow [PR]
Sync PR [sync-upstream/pr/116361]
Version info
26.11.1.1093-master(included in26.11and later)