Skip to content

Automatically choose between the plain and the secure port in clickhouse-client - #110130

Merged
alexey-milovidov merged 38 commits into
masterfrom
auto-secure-port
Aug 14, 2026
Merged

alexey-milovidov merged 38 commits into
masterfrom
auto-secure-port

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

When neither port nor secure/no-secure is specified, clickhouse-client now probes both the default port 9000 and the secure port 9440 concurrently and uses the protocol of the port that answers first. A server that answers on one port only is connected to without waiting out the connect timeout of the other one, and a server that answers on both is connected to over either of them, since both work (TLS wins a tie, which costs no waiting).

This makes the following work out of the box:

clickhouse-client --host play.clickhouse.com --user play

On play.clickhouse.com (and many similarly firewalled servers) the plain port is silently dropped rather than refused, so probing the ports sequentially would stall for the whole connect timeout before TLS could even be attempted — hence the concurrent probe. The addresses of a port, in contrast, are attempted one at a time, the next one only after 250 milliseconds without an answer - the "Connection Attempt Delay" of RFC 8305 (Happy Eyeballs) - so a hostname that resolves to several reachable backends is not connected to on all of them at once. The connection the probe establishes to the port it chooses is then handed over to the client instead of being discarded. Together, these keep the automatic choice from leaving sessions that never send anything on the server, which it logs as Client has not sent any data. and counts against max_connections. When the secure port is the one that answered, the client connects with TLS and the interactive banner shows Connecting to play.clickhouse.com:9440 (secure) ....

Because the protocol here is chosen rather than requested, a port that turns out to be unusable is not an error: the client falls back to the other one. It matters the most for the secure port, whose common failure is a self-signed or otherwise untrusted certificate that every client not passing --accept-invalid-certificate rejects: the plain port is what the client would have connected to if there were no automatic choice at all, so nothing is taken away from the user. Pass --secure to require TLS. The fallback works in the other direction too: when the plain port is the one that answered but the connection to it then fails at the protocol level (e.g. a TLS-terminating proxy in front of the plain port), the secure port is tried.

Explicit --port, --secure, --no-secure (on the command line, in the configuration file, or in connection credentials), ClickHouse Cloud hostnames (which already default to TLS), and builds without TLS support bypass the detection entirely.

Covered by unit tests for the prober and a new integration test test_client_auto_secure_port that reproduces the firewalled-server scenario with iptables REJECT/DROP rules: it asserts that the DROP case (the play.clickhouse.com one) connects quickly instead of waiting out the connect timeout, that an untrusted certificate falls back to the plain port, and that the probe leaves no extra connection behind on the server. The functional tests now say which protocol the run uses (--no-secure for a plain run, symmetrically to the --secure a secure run already passes), because the test server listens on both ports.

Changelog category (leave one):

  • Improvement

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

When neither port nor secure is specified, clickhouse-client tries both the default port 9000 and the secure port 9440 concurrently and uses the one that answers first, so clickhouse-client --host play.clickhouse.com --user play connects over TLS without --secure, even though the plain port of that server is silently dropped rather than refused. If the port that answered turns out to be unusable — a secure port with an untrusted certificate, for example — the client falls back to the other one, because the protocol was not requested explicitly.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.1376 (included in 26.8 and later)

…use-client

When neither `port` nor `secure`/`no-secure` is specified, probe both the
default port 9000 and the secure port 9440 concurrently and choose the
protocol automatically: the plain port is preferred when it answers (for
compatibility), and TLS is enabled when only the secure port is reachable.

This makes `clickhouse-client --host play.clickhouse.com --user play` work
out of the box: the plain port there is silently firewalled, so trying the
ports sequentially would stall for the whole connect timeout before TLS
could be attempted.

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

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [23d7282]

Summary: ✅


AI Review

Summary

This PR teaches clickhouse-client to probe 9000 and 9440 concurrently, reuse the winning socket, remember the working transport and address per host, and retry across protocols for some probe-time mismatches. The reconnect and address-handling fixes are materially better than the earlier revisions, but two user-visible gaps from the prior discussion are still present in the current code, so I am not comfortable approving it as-is.

Findings

⚠️ Majors

  • [src/Client/PortsProbe.cpp:180-215] [dismissed by author -- https://github.com/Automatically choose between the plain and the secure port in clickhouse-client #110130#discussion_r3565410919] When 9000 and 9440 both become writable in the same select round, the loop keeps only one answered socket and returns immediately. The other successful connectNB is destroyed when probes unwinds, so dual-port servers still get a short-lived accepted session that never sends Hello, which is exactly the log / max_connections inflation this PR claims to avoid. The earlier dismissal relied on keeping the losing socket around for fallback, but the current PortsProbeResult no longer preserves it, so the extra session is pure overhead again.
  • [programs/client/Client.cpp:785-806] [dismissed by author -- https://github.com/Automatically choose between the plain and the secure port in clickhouse-client #110130#discussion_r3763720004] Auto-selected secure connections still treat SOCKET_TIMEOUT as fatal instead of falling back to plain. In the concrete trace “9440 accepts TCP, then never finishes the handshake; 9000 is healthy”, is_connection_error is false and the client throws even though the plain port would work. That still violates the PR’s user contract that an auto-chosen secure port “that turns out to be unusable” is not an error unless TLS was requested explicitly.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 353/404 (87.38%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 12, 2026
@mintlify

mintlify Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 12, 2026, 2:25 AM

Comment thread programs/client/Client.cpp Resolved
Comment thread src/Client/PortsProbe.cpp Resolved
alexey-milovidov and others added 3 commits July 12, 2026 05:53
The `arm_tidy` build failed with:

  programs/client/Client.cpp:673:36: error: the const qualified variable
  'secure_error' is copy-constructed from a const reference; consider making
  it a const reference [performance-unnecessary-copy-initialization,-warnings-as-errors]

`Exception::message` returns a `const std::string &`, and the caught exception
`e` outlives the inner `catch` block where `secure_error` is used, so binding a
const reference instead of copying is safe.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110130&sha=08a76d47d45d00f995c0dd7f78b18886c378c720&name_0=PR&name_1=Build%20%28arm_tidy%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`test_tcp_handler_connection_limits` runs `clickhouse client` without an
explicit `--port` or `--secure`/`--no-secure`. With the new automatic
plain/secure port detection, the client concurrently probes ports `9000`
and `9440`; the winning plain-port probe is a real accepted TCP session
that is discarded and reconnected, so the server logs a second
`Done processing connection`. The test asserts exactly one connection
closure and therefore failed (`Expected exactly 1 connection closure,
got 2`) in `Integration tests (amd_asan_ubsan, ...)` and
`Integration tests (amd_llvm_coverage, ...)`.

Pin `--port 9000` so this server-side connection-limit test makes a
single deterministic connection, matching its pre-existing intent and
the behavior before automatic detection. This does not touch the
open design questions about whether the probe socket should be reused
(`src/Client/PortsProbe.cpp`) or whether the detected transport should
be persisted into `config()` (`programs/client/Client.cpp`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/client/Client.cpp Resolved
When neither the port nor the TLS mode is specified, the client probes the
plain and secure ports and, if the plain port answers the TCP connect, tries
it first and falls back to TLS on the secure port only for connection-level
failures. The set of retriable errors listed `UNKNOWN_PACKET_FROM_SERVER`,
which is thrown by `Connection::receivePacket` during query execution and
cannot occur during the handshake.

A proxy that accepts TCP on the plain port but only serves TLS there answers
the native `Hello` with a TLS alert record, whose first byte the client reads
as an unexpected packet type, so `Connection::receiveHello` throws
`UNEXPECTED_PACKET_FROM_SERVER`. That code was not in the retriable set, so the
client gave up instead of retrying `9440`, leaving the "plain port accepts TCP
but only serves TLS" case broken. Add `UNEXPECTED_PACKET_FROM_SERVER` to the
retriable set.

The retry only happens in the auto-detection path, where a secure candidate was
appended after the plain one; the explicit-port path has a single candidate and
is unaffected.

Add an integration regression `test_secure_port_chosen_when_plain_serves_tls`
that redirects the plain port to the secure port so a native connection to the
plain port is answered by the TLS listener, reproducing the failure.
Comment thread src/Client/PortsProbe.cpp Resolved
When neither the port nor the TLS mode is specified, the client now probes
both the plain (9000) and the secure default port concurrently. When the host
is unreachable, both probes fail and the client throws
`Cannot connect to <host> on port <plain> or on the secure port <secure>: ...`,
listing each probed `host:port` and its failure, instead of the single
Poco-style `(host:port)` suffix the previous direct connection produced.

The stricter assertion added on master by `0e7c8ae4f74` ("Unskip 02550 and
03025 on Darwin by matching OS-invariant error suffix") greps for the
parenthesized `(255.255.255.255:9000)`, which the probe error does not contain,
so the test started failing once master was merged into this branch.

Match the OS-invariant `host:port` that ClickHouse always names (still present in
both the probe error and the master error message), and collapse duplicate
matches with `sort -u`, since the probe error can name the address more than
once. This keeps the test passing both with and without the probe feature.

CI: #110130

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The port and the TLS mode chosen by the automatic probe were written back into the
global `config()` after a successful connection. `Client::connect` rebuilds
`ConnectionParameters` from `config()`, so on a reconnect or a failover to another
address the choice made for one address was imposed on all of them: a session started
as `--host secure-only --host plain-only` kept connecting to the plain-only address on
the secure port with TLS after the first address had answered there, and failed even
though its plain port was healthy.

Remember the successful port and TLS mode in the corresponding `HostAndPort` entry
instead. A reconnect to the same address still avoids probing the ports again, while
every other address chooses its transport on its own.

Added the integration test
`test_client_auto_secure_port::test_automatic_choice_is_not_applied_to_the_other_addresses`,
which kills the auto-detected secure server mid-query and checks that the client fails
over to a plain-only address.
Comment thread programs/client/Client.cpp Resolved
`Connection::connect` removes the host from `DNSResolver` after every
connect-level failure, so that a later reconnect or failover resolves the
host again instead of reusing dead addresses. The automatic port probe
runs before any `Connection` is created and threw without doing that, so
a client process whose probe only reached stale cached addresses would
keep retrying the same addresses for the rest of the session.

Invalidate the cache entry for the host both when the probe reports that
neither port answered and when the probe itself throws.
Comment thread programs/client/Client.cpp Resolved
…swer

Per the review comment on the docs
(#110130 (comment),
"TLS should be preferred"), flip the automatic choice: the secure port now
wins whenever it answers, and the plain port is chosen only when the secure
port does not answer within 100 milliseconds after it (so that plain-only
servers, the most common setup, are not stalled for the whole connection
timeout of the unreachable secure port).

- `PortsProbeResult::Choice` becomes `PreferSecure`/`PlainOnly`/`Neither`,
  and the preference window is renamed from `plain_preference_window` to
  `secure_preference_window`.
- The `secure_address` field is gone: with TLS preferred, the plain port is
  only chosen when no secure probe has answered, so there is never a probed
  secure address to start the protocol-level fallback from (the fallback
  still derives it from the address that answered on the plain port).
- The unit and integration tests are flipped accordingly; the integration
  test for the secure-fallback address is removed (its scenario, a TLS
  listener behind the plain port, is now resolved by the preference itself
  and is covered by `test_secure_port_chosen_when_plain_serves_tls`), and
  `test_the_remembered_address_is_refreshed_when_the_connection_falls_through`
  pins the plain transport by rejecting the secure port, since it needs a
  transport that both servers speak.
- The docs describe the new rule.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread programs/client/Client.cpp Resolved
…e choice without TLS

Three problems with the automatic choice between the plain and the secure port, in the shape
it took after TLS became the preferred protocol.

**A server whose secure port has an untrusted certificate stopped working.** TLS was not
requested by the user, it was chosen automatically, so a secure port that turns out to be
unusable must not make the client fail: the plain port is what it would have connected to if
there were no automatic choice at all, so falling back to it takes nothing away. The common
case is a server that serves both ports with a self-signed certificate, which every client
that does not pass `--accept-invalid-certificate` rejects - `Stateless tests` and
`Integration tests` are full of such servers, and that is how this surfaced. Specify
`--secure` to require TLS. The probe now reports both ports it found rather than a single
choice, so the fallback usually reuses a connection that is already established, and a
timeout is retriable in exactly that case: it costs no connection attempt, so it cannot
double the time before the failure is reported.

**Every automatically detected connection left a stray session on the server.** The probe
established a connection and discarded it, and the real connection was opened afterwards, so
the server accepted a client that sends nothing and logged `Client has not sent any data.`
for every single connect, on top of counting it against `max_connections`. The connection to
the chosen port is now handed over to `Connection`, which takes it over instead of opening a
second one (`Connection::setAdoptedSocket`); for a secure port, `SecureStreamSocket::attach`
adopts it, and the TLS handshake stays deferred to the first read or write the same way as
for a socket `Connection` connects itself. Nothing is left behind for a server that listens
on the plain port only, which is the common case.

**A build without TLS support turned a working connection into `SUPPORT_IS_DISABLED`.**
`probePlainAndSecurePorts` raced the secure port there as well, so a server answering on both
ports made the client pick TLS and then throw `tcp_secure protocol is disabled because poco
library was built without NetSSL support.` from `Connection::connect`, for a user who never
asked for TLS. There is nothing to choose between in such a build, so the detection is
skipped entirely and the plain port stays the default.
The test server listens on both the plain and the secure port, so a client that is given
neither a port nor a TLS mode now probes both and prefers TLS: the whole suite would silently
switch over to TLS, including the tests that assert on the plain port (`02116_interactive_hello`
expects the `localhost:9000` greeting) and on `is_secure` (`02246_is_secure_query_log`), and the
tests that pass a configuration file of their own, which does not accept the self-signed
certificate of the test server.

A run that is not about TLS says so with `--no-secure`, symmetrically to the `--secure` a secure
run already passes. `CLICKHOUSE_CLIENT_SECURE` has to strip it before `--secure`, because the
pattern of the latter matches inside the former.

This also makes the two tests that were adapted to the probing unnecessary, so they go back to
what they assert on `master`: `03025_clickhouse_host_env` names the address exactly once again,
and `test_tcp_handler_connection_limits` counts the connections of a client that does not pin
its port - which is now a regression test for the probed connection being reused instead of
discarded.
The command line of a `.sql` test is assembled from both the client of the run and its client
options, and `--no-secure` cannot be given twice (`Bad arguments: option '--no-secure' cannot be
specified more than once`), so it goes into the options alone.

For the same reason `00505_secure` drops the one the run passes before adding its own: that line is
about the option itself, and it has to stay that way.
Putting it into CLICKHOUSE_CLIENT_OPT does not work: when a run does not randomize settings,
`add_effective_settings` builds the options as `base_client_options + client_options`, and both of
those already contain the whole variable, so every non-setting option in it appears twice - which for
`--no-secure` is a hard `Bad arguments: option '--no-secure' cannot be specified more than once`.
Repeated *settings* survive that concatenation only because the same branch adds
`--allow_repeated_settings`.

So the shell tests get it from `CLICKHOUSE_CLIENT_OPT0`, which `shell_config.sh` assembles from the
environment of the run, and the `.sql` tests from `args.client`. A secure run is left alone: it
already passes `--secure`, which wins over `--no-secure` in `enableSecureConnection`.
Comment thread programs/client/Client.cpp Resolved
Comment thread programs/client/Client.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failures: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110130&sha=19150594bd5f4a2a485a2ab7e7bd1d3f2fd3c780&name_0=PR — please file the issues and provide fixes in separate pull requests. If a fix is already in progress, link it here.

Two stress-test signatures, both unrelated to this pull request, which is client-side only (programs/client/Client.cpp and src/Client/*: the automatic choice between the plain and the secure port). Neither is reachable from a client that picks a port, and neither has a tracking issue that I could find:

  • Stress test (arm_debug) → Logical error: Virtual row does not cover sort column 'A'. Virtual row columns: B, sort description [C] (STID 4021-39eb), from checkVirtualRowCoversSortDescription in MergingSortedAlgorithm::initialize. Per CIDB this fires about once a day across unrelated pull requests over the last 30 days, including twice on master itself (pull_request_number = 0) on 2026-08-09 and 2026-08-05.
  • Stress test (arm_asan_ubsan, s3) → Logical error: Coordination mode mismatch for stream A: got B, expected C (STID 6117-68e9). CIDB shows 6 distinct pull requests on 2026-08-12 and 9 on 2026-08-11, going back to 2026-07-23.

Two more failures in the same run need nothing from you:

  • Stress test (amd_asan_ubsan) → Sanitizer (STID: 2064-22d0), the Settings copy leak under QueryTreeBuilder::buildSelectExpression, which the report already labels with the open issue Sanitizer (STID: 2064-22d0) #114396.
  • CH Inc sync reported tests failed for a single private stress job on UndefinedBehaviorSanitizer: undefined behavior (STID 0250-4224), which hit two other pull requests today; I have rerun that job.

… the probe chose

Two problems with the fallback between the automatically chosen ports.

**The fallback could lose the backend the probe had already reached.** When the secure port won while
the plain probe was still pending, the plain fallback candidate had no address at all, so it walked
the addresses the host resolves to from the start - and `Connection::connect` has dropped the DNS
cache entries by then - paying a whole connection timeout for every unresponsive address in front of
the working one, which is exactly the delay the probing exists to avoid. It now starts from the plain
port of the address whose secure port answered, symmetrically to the `plain -> secure` branch, which
already derived its candidate that way.

**A fallback candidate must not reuse the connection the probe left on it.** The first candidate can
spend an unbounded amount of time failing - a TLS handshake waits out `handshake_timeout_ms` - while
the server drops a connection that has not finished its handshake within
`handshake_timeout_milliseconds`, so by the time the fallback runs, a connection the probe left idle
may be gone. With the defaults (10 s against 30 s) it survives, but a longer client handshake timeout
or a shorter server one turns the advertised fallback into a failure on a dead socket. Only the
candidate the probe chose takes over its connection now; a fallback keeps the address the probe
reached, which is what makes it fast, and opens a connection of its own.

The retry rule is restated in the same terms: a timeout is retriable towards a candidate the probe
actually reached, because connecting to it cannot hang, and not towards one whose address is merely
the best guess for the same backend - so a plain port that accepts the connection and then never
answers, with the secure port refused, is still reported without a second attempt.

Two tests: `test_an_unresponsive_secure_port_falls_back_to_the_plain_port` makes the secure port
accept and never answer and requires the query to come back over the plain port, and
`test_the_fallback_keeps_the_address_the_probe_reached` puts a black hole in front of the server in
the resolver order and requires the certificate-rejection fallback to reach it well inside the
connect timeout.
@groeneai

Copy link
Copy Markdown
Collaborator

Both already have fixes in flight, so nothing new from me here.

STID 4021-39eb (Virtual row does not cover sort column) is the first and only occurrence of that STID in CIDB. The assertion is two days old: debug-only checkVirtualRowCoversSortDescription, added by e5c44e5d35ac09b in #113291 (merged 2026-08-10). The breadth you quoted (about once a day, master on 2026-08-09 and 2026-08-05) is the sibling STID 2651-3359, Virtual row boundary violated: 24 rows / 22 pull requests / 3 master rows in 30 days, master on exactly those two dates plus 2026-07-14. Same defect, new assertion site.

This hit is the widened-prefix case: Virtual row columns: CounterID, sort description [CounterID, EventDate]. The virtual row is built for the prefix ORDER BY needs, a later optimization re-requests the read with a longer prefix, and the extra sort column is default-filled. #111457 (@ vdimir, open) fixes that by comparing the virtual row only on the prefix it covers instead of requiring full coverage, and it closes the open #106630. It branched before #113291, so it needs a rebase over the strict check it replaces.

STID 6117-68e9 (Coordination mode mismatch) does have a tracking issue: #106039, auto-generated for this exact STID, closed as completed on 2026-06-03 by #106243, which is why searching for an open one comes up empty. I posted the recurrence evidence there yesterday and asked you on #112052 to reopen it, since I lack the permission.

Your counts match the whole message family: 28 rows / 28 pull requests / 0 master rows in 30 days, by STID 6117-726a 15, 6117-68e9 7, 7334-5b92 4, 7334-48d5 1.

The carrier here is test_7.testing_105153, from 04241_parameterized_view_used_twice, which is tagged no-parallel-replicas. That tag was inert under stress: stress.py injects enable_parallel_replicas=1 as a --client-option regardless of tags and never passes --no-parallel-replicas. #114279 fixes that and merged at 09:08 today, about two hours after this run, so a re-run should not reproduce this carrier. That covers 12 of the 14 hits I attributed.

The other two have a different carrier and are the coordinator defect itself: two IN subqueries reading one table in different modes collide because the coordinator map is keyed on stream_id alone. Composing that key with the mode was #106043, closed unmerged. As I said on #112052, I am not touching that without @ nickitat or @ devcrafter weighing in.

Comment thread src/Client/PortsProbe.cpp Resolved
Racing `connectNB` against every address a host resolves to left a session that sends nothing on every
reachable backend but the one that won, on every automatically detected connect. A load balancer behind
one hostname is the normal case for that, and the server logs each of those as `Client has not sent any
data.` and counts it against `max_connections` - so handing the winning connection over fixed the
single-address case only, which is all the previous test covered.

The two ports are still probed concurrently, which is the whole point of the probing: serialising them
would stall the client for the entire connection timeout on a firewalled plain port before TLS is even
attempted. Within a port, the addresses are now attempted one at a time, the next one only after 250
milliseconds without an answer, or right away when the previous attempt has already failed. That is the
"Connection Attempt Delay" of RFC 8305 (Happy Eyeballs), for the same reason and with the same default,
and it keeps the common case - the first address answers - down to a single connection per port.

The fast paths are unaffected: a plain-only server still returns as soon as the secure port is refused,
without waiting out the preference window, and a firewalled plain port still lets the secure port win at
once. A host whose first address is a black hole now costs one attempt delay before the second address is
tried, which is far below the connect timeout it replaces.

Covered by `PortsProbe.AttemptsOneAddressAtATime`, which listens on the same port in both address
families so that `localhost` has two reachable addresses and asserts that exactly one of them has a
connection queued, and by `test_the_probe_leaves_no_extra_connection_on_the_other_addresses`, which
points one hostname at both plain-only servers and requires neither to be left with such a session.
Comment thread src/Client/PortsProbe.h Outdated
///
/// TLS is preferred: the secure port is chosen as soon as it becomes reachable. The plain port is chosen
/// only when the secure port is unreachable — refused, unroutable, or not answering within
/// `secure_preference_window` after the plain port (the window gives the secure port a head start over

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.

We don't need secure_preference_window. We don't need an extra delay to decide on the port. If both ports are available, it is totally fine to connect to any of them, whichever answers first.

Remove this and simplify the code and tests.

@alexey-milovidov alexey-milovidov Aug 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.

🕵 Removed in 23d7282. There is no secure_preference_window any more: the probe returns the port that answers first, and PortsProbeResult is a single endpoint (with a secure flag) instead of a plain and a secure optional that could both be set.

Three things fell out with it, which is where most of the -267/+143 comes from:

  • Candidate::answered and the retry rule that depended on it. When only one port can answer, there is no "the other port is already known to answer", so a SOCKET_TIMEOUT is never retried on the other port now — only a protocol-level failure is (UNEXPECTED_PACKET_FROM_SERVER, ATTEMPT_TO_READ_AFTER_EOF, ...). That is what keeps test_an_unresponsive_server_is_not_waited_for_twice passing, and for a simpler reason than before.
  • test_an_unresponsive_secure_port_falls_back_to_the_plain_port tested exactly that removed special case (a secure port that accepts TCP and then never finishes the handshake, on a server whose plain port is healthy), so it is deleted rather than rewritten. The untrusted-certificate fallback, which is the common one, is a protocol-level failure and is unaffected.
  • The dual-port test no longer asserts which protocol it gets. It cannot: whichever SYN-ACK the client's select sees first wins, and the plain SYN goes out a few microseconds earlier, so over a real network the plain port usually wins. On loopback both connects complete before the first select, so the free tie-break makes it TLS — 200 of 200 in a local run — but that is an artifact of loopback, not a guarantee worth asserting.

The tie-break is the only trace of "TLS should be preferred" that is left: when both ports have answered by the time the probe looks at the poll result, the secure one is taken. It waits for nothing.

Docs, the PR description, and the changelog entry are updated to say "the one that answers first" instead of the 100 ms rule. PortsProbe unit tests pass 20x locally, and test_client_auto_secure_port passes 16/16 here (5m40s), including the two tests whose reasoning changed: test_secure_port_chosen_when_plain_serves_tls (TLS either directly or through the protocol-level fallback) and test_an_untrusted_certificate_falls_back_to_the_plain_port.

CurtizJ pushed a commit to CurtizJ/ClickHouse that referenced this pull request Aug 13, 2026
The test blocks the outgoing connections to the HDFS datanode web port
with a silent `DROP` and heals the network only after the client has
demonstrably hit a connect timeout, waiting up to 30 seconds for a fresh
`connect timed out` line in the server log.

That budget is not always enough, because the query does not necessarily
open a new connection at all: the earlier tests in the module leave
keep-alive connections to `hdfs1:50075` in the HTTP connection pool, and
a silent `DROP` kills an already established connection only by the
receive timeout - `http_receive_timeout`, 30 seconds by default - rather
than by the one-second connect timeout. The first try then dies after 30
seconds with a bare `Timeout`, and the first `connect timed out` line
appears only on the next try, about 31 seconds into the query, just past
the budget:

    16:57:35.001 executeQuery: select sum(cityHash64(id)) from url('http://hdfs1:50075/...
    16:58:05.013 ReadWriteBufferFromHTTP: ... Error: Timeout. Failed at try 2/10.
    16:58:06.115 ReadWriteBufferFromHTTP: ... Error: Timeout: connect timed out: 172.16.1.2:50075. Failed at try 3/10.

Drop the connection cache before installing the rule, so the query has
to open a fresh connection and the first try fails by the connect
timeout, as the test expects. Also raise the wait budget to 60 seconds:
the loop exits as soon as the line shows up, so a generous budget costs
nothing on a healthy run.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110130&sha=7acc19de7fb0c97f7ea0fb7c6c234930d188ac66&name_0=PR&name_1=Integration%20tests%20%28amd_msan%2C%205%2F8%29
Related: ClickHouse#110130

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The automatic choice between the plain and the secure port gave the secure port
a 100 milliseconds head start over a plain port that had already answered, so
that TLS would win whenever a server serves both. That delay bought nothing:
when both ports are reachable, connecting over either of them works, so the
port that answers first is the one to use.

`probePlainAndSecurePorts` now returns the single endpoint that answered
instead of the plain one alongside the secure one, and TLS wins only when both
answer at the same moment, which costs no waiting. The candidate the connection
falls back to when the chosen port turns out to be unusable is derived from the
address that answered, so `Candidate::answered` and the special case that let a
`SOCKET_TIMEOUT` retry a port already known to answer are gone as well: only a
protocol-level failure is retried now, never a timeout.

`test_an_unresponsive_secure_port_falls_back_to_the_plain_port` covered that
special case and is removed with it. The test of a server that listens on both
ports no longer asserts which protocol it is connected with, because either one
will do.
Comment thread src/Client/PortsProbe.cpp
@@ -0,0 +1,231 @@
#include <Client/PortsProbe.h>

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.

Why is the implementation so complex? Can't we reuse HedgedConnections that we already use to choose a replica?

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.

🕵 Reusing it would not remove the complexity, because what makes the probe non-trivial is exactly what HedgedConnections cannot do:

  • It is Linux-only. HedgedConnectionsFactory, HedgedConnections and ConnectionEstablisherAsync are all #if defined(OS_LINUX): they are built on Epoll, TimerDescriptor and fibers (AsyncTaskExecutor). clickhouse-client needs the automatic port choice on macOS and FreeBSD too, so the probe races the sockets with Poco::Net::Socket::select, which is portable.

  • It races full handshakes, not TCP connects. ConnectionEstablisher runs Connection::connect to completion — TCP, TLS, sendHello/receiveHello. Racing the two ports that way would leave a fully authenticated, then dropped, session on the losing port on every connect to a server that answers on both ports (the earlier rounds of this review were spent eliminating stray sessions much more innocent than that). And since sendHello writes the password, it would be sent over the plain port in cleartext even when the secure port wins the race. The probe races raw TCP connects and writes nothing to either socket until the port has been chosen.

  • It would still stall on the very scenario this PR is for. Inside each race participant, Connection::connect tries the resolved addresses of the host sequentially, with the full connect_timeout for each. Hedging the two ports against each other does not help a multi-address host whose plain port is firewalled with DROP (the play.clickhouse.com case): every dead address of the port would still wait out the whole timeout. Hence the 250 ms per-address attempt delay of RFC 8305 in the probe.

  • There is nothing to hedge over. HedgedConnectionsFactory takes a ConnectionPoolWithFailover and Settings and implements replica selection: shuffled pools, load balancing, error counters, stale-replica fallback. Here there is one host and two ports; we would have to synthesize two connection pools and a Settings object just to reach the race, and everything on top is dead weight (its error accounting, e.g. DistributedConnectionFailTry, would also be polluted by protocol probes).

On the size itself: the file is ~170 lines of code. The bare select race over two non-blocking connects is about half of that; the rest is the two mechanisms earlier rounds of this review demanded — handing the winning socket over instead of reconnecting (#110130 (comment)) and the per-address attempt delay (#110130 (comment)) — plus the aggregated failure report. A version built on the hedged machinery would still need all of them, on top of the ~1600-line epoll/fiber stack it drags in.

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.

That's true, we can't even try to send anything in plaintext. Nice catch!

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

Not bad.

@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into master with commit b14d724 Aug 14, 2026
182 checks passed
@alexey-milovidov
alexey-milovidov deleted the auto-secure-port branch August 14, 2026 00:26
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026

This branch was successfully deployed

1 active deployment
staging - docs — 23d72826 Deployed Aug 13, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants