Skip to content

Add profile events for DNS requests, TLS handshakes and HTTP server errors - #116136

Merged
alexey-milovidov merged 16 commits into
masterfrom
network-observability-profile-events
Sep 18, 2026
Merged

alexey-milovidov merged 16 commits into
masterfrom
network-observability-profile-events

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

system.events could not answer three basic questions about what the server does on the network.

DNS had a single event, DNSError: an error count with no denominator and no timing, so neither a request rate nor a latency could be derived from it. TLS had nothing at all — on the client side the handshake was folded into *ConnectionsElapsedMicroseconds together with the TCP connect and was indistinguishable from it, and on the server side it was not observable anywhere, so a server spending its time on handshakes or rejecting client certificates showed up in no counter. Incoming HTTP connections had a counter for every way a connection can end normally (HTTPServerConnectionsPreserved, Expired, Closed, Reset), but none for ending with an error.

Added:

  • DNSRequests, DNSRequestMicroseconds, DNSRequestError for forward resolution, and DNSReverseRequests, DNSReverseRequestMicroseconds, DNSReverseError for the reverse (PTR) resolution used to match a client address against a host_regexp. Only attempts that reach the system resolver are counted: hits of the ClickHouse DNS cache, and host names that are already IP address literals, are not. A counted forward attempt is a getaddrinfo call, which does not necessarily send a DNS query - it can be answered from /etc/hosts or another name service. DNSRequestError and DNSReverseError have exactly the same boundary as the corresponding request counters, so a failure rate can be derived from them; the pre-existing DNSError cannot serve as that numerator, because it also counts failures that perform no resolution at all, such as a name whose addresses are all rejected by the dns_allow_resolve_names_to_ipv4/dns_allow_resolve_names_to_ipv6 filter.
  • TLSHandshakes, TLSHandshakeMicroseconds, TLSHandshakeErrors for outgoing (client) connections, and TLSServerHandshakes, TLSServerHandshakeMicroseconds, TLSServerHandshakeErrors for incoming (server) ones.
  • HTTPServerConnectionsErrors for incoming HTTP connections terminated by a network error, a malformed request, or an exception that escaped the request handler. A client that closes a kept-alive connection without sending another request is a normal end of life and is not counted.

The TLS accounting sits in Poco::Net::SecureSocketImpl, which is the single point every TLS handshake in the server goes through: the eager SSL_connect of an outgoing connection, and the deferred SSL_do_handshake that both an accepted server connection and a non-blocking client connection are completed with. That covers the native TCP protocol, HTTPS, MySQL and PostgreSQL on the server side, and the HTTP connection pools (object storage, url, remote HTTP) on the client side, in one place; protocols carrying their own TLS stack, such as gRPC, are not counted, and the event descriptions say so. _poco_net_ssl therefore links clickhouse_common_io, the way _poco_foundation already does.

A handshake on a non-blocking socket is abandoned and retried until it completes, so the time of every attempt is charged, while the handshake itself is counted only once it stops being retriable — as a success, or as an error if the handshake failed, timed out, or the peer closed the connection in the middle of it. Note that this makes TLSServerHandshakeErrors include port scanners and health checks that open a TCP connection to a secure port and close it; that is documented in the event description.

The DNS and TLS events are also added to the list Keeper exposes, next to the DNSError that was already there.

Verified locally on a server with https_port and tcp_port_secure: each counter moves on its trigger, TLSHandshakes stays flat when the client side of the handshake is in a separate process, TLSServerHandshakeErrors fires for a plain TCP connect to the secure port, and TLSHandshakeErrors fires for an HTTPS client pointed at a plain HTTP port. The existing 02265_test_dns_profile_events still passes.

Changelog category (leave one):

  • Improvement

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

New profile events for network activity: DNSRequests, DNSRequestMicroseconds and DNSRequestError (plus DNSReverseRequests, DNSReverseRequestMicroseconds and DNSReverseError for reverse resolution), TLSHandshakes, TLSHandshakeMicroseconds and TLSHandshakeErrors for outgoing connections, TLSServerHandshakes, TLSServerHandshakeMicroseconds and TLSServerHandshakeErrors for incoming ones, and HTTPServerConnectionsErrors for incoming HTTP connections that end with an error. Previously DNS exposed only an error count with no timing, and TLS handshakes were not observable at all.


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

Version info

  • Merged into: 26.10.1.90 (included in 26.10 and later)

…rrors

`system.events` could not answer three basic questions about what the server
does on the network.

DNS had a single event, `DNSError`: an error count with no denominator and no
timing, so neither a request rate nor a latency could be derived from it. TLS
had nothing at all - on the client side the handshake was folded into
`*ConnectionsElapsedMicroseconds` together with the TCP connect and was
indistinguishable from it, and on the server side it was not observable
anywhere, so a server spending its time on handshakes or rejecting client
certificates showed up in no counter. Incoming HTTP connections had a counter
for every way a connection can end normally, but none for ending with an error.

Added:

- `DNSRequests`, `DNSRequestMicroseconds` for forward resolution, and
  `DNSReverseRequests`, `DNSReverseRequestMicroseconds`, `DNSReverseError` for
  the reverse (PTR) resolution used by `host_regexp`. Only requests that reach
  the resolver are counted: cache hits and host names that are already IP
  address literals are not.
- `TLSHandshakes`, `TLSHandshakeMicroseconds`, `TLSHandshakeErrors` for
  outgoing (client) connections, and `TLSServerHandshakes`,
  `TLSServerHandshakeMicroseconds`, `TLSServerHandshakeErrors` for incoming
  (server) ones.
- `HTTPServerConnectionsErrors` for incoming HTTP connections terminated by a
  network error, a malformed request, or an exception escaping the handler.

The TLS accounting sits in `Poco::Net::SecureSocketImpl`, which is the single
point every TLS handshake in the server goes through: the eager `SSL_connect`
of an outgoing connection, and the deferred `SSL_do_handshake` that both an
accepted server connection and a non-blocking client connection are completed
with. That covers the native TCP protocol, HTTPS, MySQL and PostgreSQL on the
server side and the HTTP connection pools on the client side in one place;
protocols carrying their own TLS stack, such as gRPC, are not counted.
`_poco_net_ssl` therefore links `clickhouse_common_io`, the way
`_poco_foundation` already does.

A handshake on a non-blocking socket is abandoned and retried until it
completes, so the time of every attempt is charged while the handshake itself
is counted only once it stops being retriable - as a success, or as an error if
the peer closed the connection or the handshake failed or timed out.
`enum Time` is unscoped, so both spellings compile, but every other call site
in the tree names the enumerator directly.
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [833fa28]

Summary: ✅


AI Review

Summary

This PR adds system.events counters for forward/reverse DNS lookups, TLS handshakes, and HTTP server connection failures. The TLS/HTTP wiring and the previously reviewed DNS edge cases look addressed, but the forward-DNS event family still over-promises its surface: existing server paths that resolve names through Poco::Net::SocketAddress(host, port) bypass the new counters entirely, so the new metrics do not yet describe all forward DNS activity/errors made by the server.

Findings

⚠️ Majors

  • [src/Common/ProfileEvents.cpp:689] DNSRequests / DNSRequestMicroseconds / DNSRequestError (and DNSError as a “total”) are only incremented from DNSResolver::hostByName, but existing server paths still resolve host names through Poco::Net::SocketAddress(host, port) in src/Common/makeSocketAddress.cpp:13, src/Server/DistributedQuery/ExchangeServer.cpp:44, and src/Client/Connection.cpp:232, which goes straight to DNS::hostByName in base/poco/Net/src/SocketAddress.cpp:285. Those lookups bypass the new metrics completely, so system.events still under-reports forward DNS activity and can miss real resolution failures.
    Suggested fix: instrument the remaining SocketAddress / DNS::hostByName entrypoints used by the server, or narrow the event descriptions and PR text to state that the new counters only cover lookups routed through DNSResolver.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: either expand the instrumentation to the direct Poco::Net::SocketAddress(host, port) resolution entrypoints already used by the server, or narrow the DNS event contract so it matches the surface that is actually counted.

LLVM Coverage Report

Measured on commit 833fa28.

Metric Baseline Current Δ
Lines 88.40% 88.50% +0.10%
Functions 91.70% 91.80% +0.10%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 63/67 (94.03%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 24, 2026
The style check requires every test containing `SYSTEM DROP` to be tagged
`no-parallel`, because such commands touch server-wide shared state. The test
drops the connection cache so that the `url` request really performs a TLS
handshake instead of reusing a pooled connection.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116136&sha=95b6968db6e1263654738fce2df5db35a596c90e&name_0=PR&name_1=Style%20check
PR: #116136
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 833fa282e with master 3a3d261fd (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

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +4.1 s (+7%) in total before that adjustment.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse ProfileEvents::global_counters_storage 12.44 MiB 12.50 MiB +64.00 KiB (+0.50%)
programs/clickhouse-keeper ProfileEvents::global_counters_storage 12.44 MiB 12.50 MiB +64.00 KiB (+0.50%)

Job report

…ation failures as TLS handshake errors

`mustRetry` throws `Poco::TimeoutException` from inside the retry loop, so the
deferred handshake in `completeHandshake` missed the timeout case, and the peer
certificate was validated by the callers after the handshake had already been
counted as successful. The handshake loop and the validation now live under the
same counter, and the test checks the two error events.
Comment thread src/Common/DNSResolver.cpp Resolved
`c-ares` reports `NXDOMAIN` and other non-success statuses by leaving the answer
set empty instead of raising an error, so failed reverse lookups used to bump
`DNSReverseRequests` and `DNSReverseRequestMicroseconds` while leaving
`DNSReverseError` at zero. Count an empty PTR answer as an error, and cover both
the successful and the failing reverse lookup with a new test in
`test_host_regexp_multiple_ptr_records`.
Comment thread src/Common/ProfileEvents.cpp Resolved
…st fast

The AI review pointed out that `DNSError` and the new `DNSRequests` counter do not
share a boundary: `DNSError` is also incremented in `getResolvedIPAddressesWithFiltering`
when `dns_allow_resolve_names_to_ipv4`/`dns_allow_resolve_names_to_ipv6` reject every
resolved address, which happens without any request reaching the resolver, so no failure
rate can be derived from the two.

Add `DNSRequestError`, incremented exactly where `DNSRequests` is, so it is a numerator
for the same denominator - the forward counterpart of `DNSReverseError`. The description
of `DNSError` now says what it covers and points at the two per-request error events.

The test was also failing with `Test runs too long (> 180s)`: it triggered a forward DNS
request by resolving a host name that is absent from the zone, which costs a resolver
timeout per attempt on a machine without a reachable resolver. Now `DNSRequests` and
`DNSRequestMicroseconds` are moved by a successful lookup after `SYSTEM DROP DNS CACHE`,
and the failure case uses a name with a label longer than the 63 bytes a DNS label may
have, which `getaddrinfo` rejects locally without sending anything.

Renumbered the test to `05054` because `05038` is taken on master.
Comment thread src/Common/ProfileEvents.cpp Resolved
Comment thread src/Common/ProfileEvents.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). label Sep 4, 2026
alexey-milovidov and others added 4 commits September 9, 2026 17:06
…real total, speed up the test

Three review findings:

* `DNSRequests` was documented as "the number of requests that actually left
  the server", which is not what it counts: the counter wraps
  `Poco::Net::DNS::hostByName`, i.e. `getaddrinfo`, so names answered from
  `/etc/hosts` or another NSS source, and names the resolver rejects locally
  without sending a query, are counted too. The description now says "forward
  name resolution attempts" and spells out what is and is not counted;
  `DNSRequestMicroseconds` and `DNSRequestError` follow the same wording.

* `DNSError` was documented as the total of all resolution failures, including
  the reverse ones, but the reverse path only incremented `DNSReverseError`, so
  a PTR miss left `DNSError` flat. `reverseResolveImpl` now increments
  `DNSError` together with `DNSReverseError`, on both the exception and the
  empty-answer path, which makes the documented contract true.
  `test_reverse_dns_profile_events` asserts it.

* `05059_network_profile_events` timed out (> 180 s) in the flaky check under
  sanitizers, where starting `clickhouse-client` dominates the run time. The
  check now takes a list of events, reads them all with a single `sumIf` query
  and runs its trigger once for the whole group, and the triggers send their
  cache drop and their payload query in one client invocation. This cuts the
  number of client startups from about 40 to about 16 without changing what is
  asserted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ing TLS handshake

The TLS handshake against the plain HTTP port is performed by the `url` table
function, which retries a failed connection `http_max_tries` (10 by default)
times with an exponential backoff. Measured locally, that single query took
131 seconds, which is where almost all of the test time went and why the flaky
check reported "Test runs too long (> 180s)". With `http_max_tries = 1` the
whole test takes 1.5 seconds and still increments `TLSHandshakeErrors`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
M(RWLockWritersWaitMilliseconds, "Total time spent waiting for a write lock to be acquired (in a heavy RWLock).", ValueType::Milliseconds) \
M(DNSError, "Total count of errors in DNS resolution", ValueType::Number) \
M(DNSError, "Total count of errors in DNS resolution. It counts both the requests that failed among the ones counted by DNSRequests and DNSReverseRequests, and the failures that happen without a request, such as a host name resolving only to addresses that are then rejected by the `dns_allow_resolve_names_to_ipv4`/`dns_allow_resolve_names_to_ipv6` filter. Use DNSRequestError and DNSReverseError to get the numerators that match the corresponding request counters.", ValueType::Number) \
M(DNSRequests, "Total count of forward name resolution attempts (host name to addresses) made by the server. An attempt is counted when the name is handed to the system resolver, so names answered locally, for example from `/etc/hosts` or another NSS source, and names that the resolver rejects locally without sending a query, are counted as well. Names served from the internal DNS cache and host names that are already IP address literals are not counted.", ValueType::Number) \

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.

DNSRequests, DNSRequestMicroseconds, and DNSRequestError are still narrower than this contract. We only increment them inside DNSResolver::hostByName, but the server already resolves host names through Poco::Net::SocketAddress(host, port) in existing paths like src/Common/makeSocketAddress.cpp:13, src/Server/DistributedQuery/ExchangeServer.cpp:44, and src/Client/Connection.cpp:232. Those go straight to DNS::hostByName in base/poco/Net/src/SocketAddress.cpp:285, so they bypass the new counters completely, and a failure there also leaves DNSError flat. system.events therefore still cannot report all forward DNS activity/errors the new description promises.

Please either instrument the remaining SocketAddress / DNS::hostByName entrypoints used by the server, or narrow the DNS event descriptions to the DNSResolver-only surface.

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 left to another PR.

target_include_directories (_poco_net_ssl SYSTEM PUBLIC "include")
# `clickhouse_common_io` is needed for the TLS handshake profile events, the same way
# `_poco_foundation` depends on it. The resulting cycle is fine for static libraries.
target_link_libraries (_poco_net_ssl PRIVATE clickhouse_common_io)

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.

Funny but tolerable.

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 18, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 18, 2026
Merged via the queue into master with commit 5907047 Sep 18, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the network-observability-profile-events branch September 18, 2026 12:11
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 18, 2026
thevar1able added a commit that referenced this pull request Sep 25, 2026
Resolve conflicts caused by #116136
(TLS handshake profile events) not being present in 26.8:
- keep the inline `SSL_connect` loop in `connectSSL` and the old `completeHandshake`,
  but route them through `performSSLOperation` and the new `mustRetry`/`handleError`
  signatures; `connectSSL` now throws if the blocking handshake does not complete,
  as in the original change;
- drop `HandshakeProfileEventCounter`.

The new Silk tests use `silk::FiberScheduler::run` instead of `Silk::spawn`,
which does not exist in 26.8.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
thevar1able added a commit that referenced this pull request Sep 25, 2026
Resolve conflicts for 26.3, which lacks Silk sockets and several prerequisite changes
(e.g. #116136):
- drop the changes to Silk sockets and `SocketPeerClosed`, which do not exist in 26.3;
- drop `markFatalError`, whose only user is `SocketPeerClosed`;
- keep the inline `SSL_connect` loop in `connectSSL` and the old `completeHandshake`,
  but route them through `performSSLOperation` and the new `mustRetry`/`handleError`
  signatures; `connectSSL` now throws if the blocking handshake does not complete,
  as in the original change;
- drop `HandshakeProfileEventCounter`;
- drop the new unit tests, which depend on `SecureSocketImpl::ssl`, `setBioMethod`
  and `gtest_ephemeral_certificate.h`, missing in 26.3.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Oct 1, 2026
Resolve conflicts caused by #116136 (TLS handshake
profile events) not being present in 26.9, the same way as the 26.8 backport
(#122197): keep the inline `SSL_connect` loop and the old
`completeHandshake`, routed through `performSSLOperation`. 26.9 has `Silk::spawn`, so the new Silk tests stay.

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-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). 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 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.

2 participants