Skip to content

Add clickhouse-proxy application mode - #110105

Open
alexey-milovidov wants to merge 169 commits into
masterfrom
clickhouse-proxy
Open

alexey-milovidov wants to merge 169 commits into
masterfrom
clickhouse-proxy

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Implements a new application mode in the clickhouse binary, named proxy. The proxy accepts connections over end-user ClickHouse protocols, finds the upstream backend based on configurable rules (hostname from TLS SNI or HTTP header, user name, database name, and — for HTTP — query type), and forwards the traffic to it. It is built on the silk fiber framework so that many concurrent connections are handled with low RAM usage.

Start it with clickhouse proxy --config-file proxy_config.xml; a fully commented example config is in programs/proxy/proxy_config.xml, and the feature is documented at docs/guides/oss/deployment-and-scaling/clickhouse-proxy.mdx.

What it does

  • Protocol frontends for HTTP(S), native TCP, MySQL, PostgreSQL, SSH, transparent TLS-by-SNI, and opaque TCP streams. It handles only end-user protocols (not Keeper or inter-server replication). The user name and database are parsed from the first packets where the protocol allows it (HTTP headers/params/Basic auth, native Hello, PostgreSQL StartupMessage, HTTP query type). MySQL is server-speaks-first with in-band TLS: when a rule needs the user or the database, the proxy terminates the handshake and rebinds authentication to the backend with an auth-switch; otherwise it is forwarded transparently. SSH is terminated and routed by the client's public key (which must be in a rule's allowlist and proven by signature), then re-originated to the backend with a bastion key whose host key is verified against a known_hosts file.
  • TLS routing options: terminate and re-encrypt (the proxy and each backend hold their own certificates), terminate only (unwrap: TLS to clients, plaintext to backends), and transparent (route by SNI without decrypting).
  • Multi-criteria routing rules matching host / user / database / query type / protocol, by exact value or regular expression; regexp captures can be substituted into a backend address template (e.g. route users ch-<tenant> to per-tenant backends).
  • Pools with pluggable load balancing (random, round_robin, least_connections, lowest_latency, least_resources) behind a common interface; a pool may list several backends for load balancing.
  • Session stickiness by session_id (from the HTTP URL) or by peer address, using a consistent (rendezvous) hash of the backends.
  • Backend health monitoring (connect latency, consecutive failures) and optional CPU/memory polling with per-backend credentials, feeding the least_resources strategy; a JSON status endpoint, /ping, and static pages are served by the proxy itself.
  • An abstract routing table exposing hooks (unknown route, no backends available, first time a user or database is seen) that run a shell command — for example to provision a backend on demand and wait for it to become available.

Validated end to end against a live server: HTTP /ping, static pages, the status endpoint, GET/POST forwarding, the no-backend error paths, native protocol round-trips, and clean shutdown.

Related: ClickHouse/silk#120 (the splice operation this proxy relies on, sent to silk upstream)

Changelog category (leave one):

  • New Feature

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

Added a new proxy mode to the clickhouse binary: a lightweight, protocol-aware proxy that routes end-user connections (HTTP, native, MySQL, PostgreSQL, TLS-by-SNI, and raw TCP) to backend servers based on a configurable routing table, with TLS termination/passthrough, load balancing, health checks, and session stickiness.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

Implement a new `proxy` application mode in the `clickhouse` binary. The proxy
accepts connections over end-user ClickHouse protocols, chooses a backend from
a configurable routing table, and forwards the traffic to it. It runs on the
`silk` fiber framework so a large number of connections can be handled with low
memory usage.

Features:
- Frontends for HTTP(S), native TCP, MySQL, PostgreSQL, transparent TLS routing
  by SNI, and opaque TCP streams. The user name and the database are parsed from
  the first packets where the protocol allows it (HTTP headers/params, native
  `Hello`, PostgreSQL `StartupMessage`); query-type routing is supported for HTTP.
- Multi-criteria routing rules matching on host (SNI or HTTP `Host`), user,
  database, query type and protocol, by exact value or regular expression;
  regexp captures can be substituted into a backend address template.
- Pools of backends with pluggable load balancing (`random`, `round_robin`,
  `least_connections`, `lowest_latency`, `least_resources`) behind a common
  interface, and session stickiness by `session_id` or peer address using a
  consistent (rendezvous) hash.
- TLS termination and re-encryption, TLS unwrapping, or transparent SNI-based
  forwarding, with optional ACME certificate provisioning.
- Backend health monitoring (connect latency, consecutive failures) and optional
  CPU/memory polling via per-backend credentials, plus a JSON status endpoint,
  `/ping`, and static pages served by the proxy itself.
- Abstract routing table with hooks (unknown route, no backends available, first
  time a user or a database is seen) that can run a shell command to, for example,
  provision a backend on demand.

The server-side `Silk::SecureFiberStreamSocketImpl` gains a constructor that
adopts an accepted fd and performs the server-side TLS handshake over the silk
fiber BIO, so a TLS-terminating listener never blocks an OS thread.

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

mintlify Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 24, 2026, 4:53 PM

@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a19dceb]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds the standalone clickhouse proxy application with protocol-aware routing, TLS, load balancing, health checks, and provisioning hooks. Reviewed PR head a19dceb6d5206ada6b86a9c58bff7316232eff07, the current source, pinned dependency behavior, and the previous discussion. Block: SSH forwarding can discard bytes, allocation failures can cause a use-after-free or permanently stuck handlers, and PostgreSQL cancellation still exceeds its stated deadline. Three previously deferred MySQL/health limitations also remain below; they were not reposted inline.

Missing context / blind spots
  • ⚠️ No ClickHouse binary is available in this job, so runtime reproductions were not executed. The current CI report supplies passing Fast test, Style check, and tidy results, but the targeted functional report has no test results yet. The proxy tests are excluded from Fast test. Focused runtime coverage of the failure paths below would close this gap.
Findings

❌ Blockers

  • programs/proxy/SSHFrontend.cpp:262 — SSH forwarding loses bytes under backpressure. ssh_channel_read_nonblocking invokes callbacks that can fill the same pending queue after its available capacity was calculated. With one byte free and a closed destination window, a two-byte source packet queues one byte in its callback; the read removes the second byte, but forward now consumes zero and its return value is ignored. Both directions are affected. Reserve capacity across callbacks or preserve every byte removed from libssh.

  • programs/proxy/ProxyServer.cpp:387 — Startup cleanup can use a freed accept-loop future. The fiber starts before the owning state is inserted into accept_states. If vector growth throws, the local state destroys its future while Silk retains its address; completion writes through that dangling pointer, and shutdown cannot join the omitted loop. Reserve the vector before scheduling any loops, or establish durable ownership before starting them.

  • programs/proxy/Router.cpp:177 — A failed first-seen operation can permanently pin handlers. If event allocation throws after try_emplace, the cached entry retains a null event; subsequent requests for the same target/name spin without yielding. An exception while runHook formats/logs its command, before its try, instead leaves an event that is never signaled. Neither path responds to client shutdown. Construct the event before insertion and guard all subsequent exceptional exits to remove the incomplete entry and signal waiters.

  • programs/proxy/PostgreSQLFrontend.cpp:85 — The cancellation broadcast's deadline does not cover DNS or queued deliveries. resolveAddress performs blocking resolution before the timed connect. A batch of 64 hostname lookups can occupy the fixed worker pool in successive waves, continuing beyond handshake_timeout_ms and shutdown while the parent joins every delivery. For example, four workers and five-second lookups require about 80 seconds for one batch despite the default ten-second budget. Make resolution and queued work honor the shared deadline/shutdown state. Reopened the existing thread and replied once to the explicit fixed claim.

  • programs/proxy/MySQLFrontend.cpp:117 — Credential routing removes MySQL client TLS. [dismissed by author -- https://github.com/Add clickhouse-proxy application mode #110105#discussion_r3790249149] Any applicable credential rule or first-seen hook selects the terminating handshake, which omits CLIENT_SSL. TLS-required clients fail, and permissive clients can downgrade to plaintext. The documented limitation does not preserve transport security. Implement in-band TLS mediation or explicitly reject the unsupported routing mode; this remains a maintainer scope decision.

⚠️ Majors

  • programs/proxy/MySQLFrontend.cpp:120 — The greeting's connection ID does not identify the backend session. [dismissed by author -- https://github.com/Add clickhouse-proxy application mode #110105#discussion_r3735706395] Every client receives ID 1, while backend commands are relayed unchanged. Cancellation based on the driver's handshake ID can therefore miss its query or target another connection's query. Documentation does not repair driver behavior. Preserve/translate connection-ID semantics or narrow the supported contract explicitly.

  • programs/proxy/Frontend.cpp:241 — Endpoint failures disable healthy protocols on the same backend. [dismissed by author -- https://github.com/Add clickhouse-proxy application mode #110105#discussion_r3586821965] Failed HTTP connects update the shared Backend::alive state, so native routing can stop despite a healthy native port. Probing one selected port cannot establish all endpoints' health. Track health per endpoint or reject mixed-protocol entries; separate entries are the documented workaround.

Tests
  • ⚠️ Add a focused SSH backpressure regression that delivers new source data during the explicit read with the pending queue nearly full, and verifies exact bytes in both directions. The authorization test does not exercise this path.
  • ⚠️ Exercise allocation failure after accept-loop scheduling and during first-seen setup/command construction, proving clean teardown and a successful subsequent request for the same name.
  • ⚠️ Exercise cancellation with controlled delayed hostname resolution and shutdown during a batch. The reported manual check with numeric unreachable addresses does not cover the remaining deadline violation.
Final Verdict

Status: ❌ Block

Fix SSH byte preservation, accept-loop ownership, first-seen rollback/completion, and the complete cancellation deadline. Settle the three documented MySQL/health contract limitations above, and provide focused regression evidence for the corrected failure paths.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 11, 2026
SSH carries no cleartext identity (no SNI, and the user name is inside the encrypted transport), so
the proxy now terminates SSH to route it. A new `ssh` listener protocol:

- terminates SSH using the existing libssh server wrappers (`SSHBind`/`SSHSession`), presenting the
  proxy's own host key;
- reads the client's offered public key in the `auth_pubkey` callback and routes by it — a new
  `authorized_key` / `authorized_key_file` routing dimension chooses the pool from the key the client
  presents (the user name is captured too);
- re-originates a fresh SSH connection to the chosen backend as a bastion, authenticating with a
  configured `backend_key_file` that the backends trust, and splices the two sessions (pty, shell,
  exec, stdin/stdout/stderr, EOF, exit status).

Because the client's signature is bound to the client-facing session it cannot be replayed to the
backend; the proxy authorizes the client by its public key and logs in to the backend as a jump host.

Each SSH connection runs under a silk `ThreadModeScope` (libssh drives its own blocking I/O), and
routing inside the libssh callbacks uses a new pure `Router::routeStatic` that never touches fiber
primitives.

Validated end to end: a keyed `ssh` client through the proxy to a backend `sshd` runs a remote
command and returns its output; an unknown key is rejected.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 8 commits July 11, 2026 19:46
- Use angle-bracket includes for the proxy's own headers, as the style
  check requires (the program directory is on the include path).
- Add comments containing "Ok" to the six catch (...) blocks flagged by
  the catch_all style check, explaining why swallowing the exception is
  acceptable at each site.
- Avoid "--" inside an XML comment in proxy_config.xml (use the short
  option -C in the usage example), fixing the xmllint check.
- Fix clang-tidy errors from the arm_tidy build: initialize int n in
  FiberSocket::sendAll, add default member initializers to the TLS
  ClientHello Cursor and to AcceptState::params, replace an ambiguous
  supervisor_future.reset() with an assignment of nullptr, and bind the
  HTTP path to a const reference instead of copying it.

Style check report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=7e580b6789e744485cb5dbfb57dfd479bfcc503a&name_0=PR&name_1=Style%20check
Build (arm_tidy) report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=7e580b6789e744485cb5dbfb57dfd479bfcc503a&name_0=PR&name_1=Build%20%28arm_tidy%29
PR: #110105

Co-Authored-By: Claude Fable 5 <[email protected]>
The test_numbers_check style check does not allow gaps larger than 100
between consecutive stateless test numbers, and the largest number on
master is currently 04511.

Style check report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=7e580b6789e744485cb5dbfb57dfd479bfcc503a&name_0=PR&name_1=Style%20check
PR: #110105

Co-Authored-By: Claude Fable 5 <[email protected]>
…lication

The fast test builds with USE_SILK = 0, where ProxyServer.h defines
nothing and Proxy::ProxyServer stays an incomplete type. The implicit
destructor of ProxyApplication, instantiated in Proxy.cpp, then cannot
destroy the std::unique_ptr member. Compile the member only when silk
is available; all its uses were already guarded.

Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=7e580b6789e744485cb5dbfb57dfd479bfcc503a&name_0=PR&name_1=Fast%20test
PR: #110105

Co-Authored-By: Claude Fable 5 <[email protected]>
MySQL is server-speaks-first, so when a routing rule needs the user or the database the proxy now
terminates the handshake instead of forwarding blindly: it greets the client, reads the
`HandshakeResponse` (user, database), and routes on them.

Because the client's authentication response is bound to the scramble in the greeting, the proxy
connects to the chosen backend, reads the backend's scramble, and issues an auth-switch so the client
re-computes its response against the backend's scramble, which the proxy forwards verbatim. The
backend performs the real password check; the proxy never learns the password. After authentication
the connection is spliced byte for byte. When no rule needs the user or the database, MySQL is
forwarded transparently as before.

Reuses the existing MySQL packet classes (`Handshake`, `HandshakeResponse`, `AuthSwitchRequest`,
`AuthSwitchResponse`, `ERRPacket`) over `ReadBufferFromPocoSocket`/`AutoCanceledWriteBuffer` on the
fiber socket, so it stays cooperative (no OS-thread blocking).

Validated end to end with both the mariadb CLI and pymysql: routing by database and by user return
the backend's query results through the proxy; an unroutable database is rejected with a MySQL error.

Co-Authored-By: Claude Fable 5 <[email protected]>
Align MySQLFrontend.cpp with the include style used across the proxy sources.

Co-Authored-By: Claude Fable 5 <[email protected]>
Without disabling Nagle's algorithm, relaying small protocol packets (e.g. a native `SELECT 1`
request and its response) stalls on the Nagle/delayed-ACK interaction: a benchmark measured about
40 ms per round-trip through the proxy (~24 QPS) versus sub-millisecond direct. ClickHouse's own
servers set TCP_NODELAY for the same reason.

Set TCP_NODELAY on every proxy socket — accepted client connections and outgoing backend
connections, plain and TLS — and on the SSH client fd. After the fix the same benchmark relays at
roughly the same rate as a direct connection.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 2 commits July 11, 2026 20:51
A performance test showed bulk relaying is buffer-bound: with the previous 16 KiB per-direction
buffer a single HTTP result stream reached only ~0.8 GB/s versus ~4 GB/s direct. Raising the buffer
to 64 KiB reaches ~2 GB/s, and 256 KiB approaches the direct rate; the cost is roughly twice the
buffer size in resident memory per actively-transferring connection.

Make 64 KiB the default (a better throughput/memory balance) and document `relay_buffer_size` and
`fiber_stack_size` as the two knobs that trade throughput against per-connection memory.

Co-Authored-By: Claude Fable 5 <[email protected]>
Bump the silk submodule to pick up FiberScheduler::splice and use it to relay connections whose both
legs are plaintext (HTTP, native, MySQL, PostgreSQL, transparent TLS-by-SNI, opaque streams): data
is moved socket -> pipe -> socket entirely in the kernel instead of being copied through a user-space
buffer. A TLS-terminated leg still uses the copy relay, since its bytes must be decrypted/encrypted
in user space.

A benchmark relaying a large HTTP result went from ~0.8 GB/s (copy, 16 KiB buffer) to line rate
(~5 GB/s, matching a direct connection) with splice and a larger buffer, while small-query latency
is unchanged (SPLICE_F_MOVE only, so the socket is not corked). Byte-for-byte identical output was
verified against a direct connection.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Jul 11, 2026
With the splice relay a 256 KiB chunk reaches near line rate, so make it the default (was 64 KiB).
Update the tuning documentation accordingly.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Remove the unused error code `ALL_CONNECTION_TRIES_FAILED` from `Frontend.cpp`.
- Replace `std::istringstream`/`std::ostringstream` with manual token parsing,
  `fmt::format`, and `ReadBufferFromFile` + `readStringUntilEOF`; the remaining
  `std::ostringstream` in `StatusPage.cpp` feeds `Poco::JSON` `stringify` (which
  requires `std::ostream`) and is allowlisted, as in `KeeperDashboardRequestHandler.cpp`.
- Check the return value of `close` in cleanup paths via `[[maybe_unused]] int err`.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=cff9eb708df3eedf58a2fe0dae28a8cb287da1b5&name_0=PR&name_1=Style%20check
PR: #110105

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread programs/proxy/SSHFrontend.cpp Resolved
Comment thread programs/proxy/HealthMonitor.cpp Resolved
Comment thread programs/proxy/ProxyConfig.cpp Resolved
Comment thread programs/proxy/PostgreSQLFrontend.cpp Resolved
Comment thread programs/proxy/ProxyServer.cpp Resolved
The `arm_tidy` build failed with:

  programs/proxy/Relay.cpp:122:21: error: Value stored to 'remaining' is
  never read [clang-analyzer-deadcode.DeadStores,-warnings-as-errors]

The `remaining = 0;` assignment sat right before a `break` that leaves the
`while (remaining > 0)` inner loop, and `remaining` is not read after the
loop, so the store was dead. Drop it; the `in_bytes = 0;` signal and the
`break` already stop both loops.

CI: https://s3.amazonaws.com/clickhouse-test-reports/PRs/110105/83f68d302c5aa8f84077edcc0f12e807848f31d6/build_arm_tidy/build_clickhouse/build_clickhouse.log

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/proxy/SSHFrontend.cpp Resolved
Comment thread programs/proxy/PostgreSQLFrontend.cpp Resolved
Comment thread programs/proxy/Frontend.cpp Resolved
Comment thread programs/proxy/HealthMonitor.cpp Resolved
…nitizer

`04512_proxy_http_routing` failed under MemorySanitizer with a
`use-of-uninitialized-value` in `RecordingReader::readLine`, tracing back to the
receive buffer filled by `Silk::FiberStreamSocketImpl::receiveBytes`. The bytes
arrive through an `io_uring` completion, which MemorySanitizer does not intercept
the way it does the plain `read`/`recv` syscalls, so it keeps treating them as
uninitialized as soon as the proxy inspects the parsed request line.

Unpoison the received region explicitly, mirroring what the TLS path in
`SilkSecureFiberStreamSocketImpl` (`silkBioRead`) already does. The
`__msan_unpoison` macro is a no-op outside MemorySanitizer builds, so this has no
effect on release builds.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=dca035adbcd7494dd7e399f210a72fedbf5c74a3&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20flaky%20check%29
PR: #110105

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/proxy/ProxyServer.cpp Resolved
Comment thread programs/proxy/LoadBalancing.cpp Resolved
Comment thread programs/proxy/Relay.cpp Resolved
The `HealthMonitor` polled every backend's resource usage on each liveness
pass, so with the default `interval_ms` of `5000` and `resource_poll_interval_ms`
of `10000` it polled resources twice as often as configured. The
`last_resource_poll` member and the `resource_poll_interval_ms` setting were
both present but never consulted.

The supervisor fiber now decides per backend whether a resource poll is due
(comparing `last_resource_poll` against `resource_poll_interval_ms`) before
dispatching the check, and passes the decision to `checkBackend`. The
throttle bookkeeping stays confined to the single supervisor fiber, as the
`last_resource_poll` comment already promised.

Addresses review feedback from `clickhouse-gh` on `programs/proxy/HealthMonitor.cpp`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating rand #2; I'll follow up here with a PR (or my findings) shortly.

First finding: the test does not exercise the functions at all. All four rand.xml queries have the shape SELECT count() FROM (SELECT f() FROM zeros(N)), and the planner drops the unused subquery column, so rand(), rand64(), randUniform and generateUUIDv4() are never called. On current master EXPLAIN actions=1 for query #2 is only ReadFromStorage (SystemZeros) -> Aggregating count(). The test is timing count() over zeros() (6-8 ms), which explains the noise. The fix belongs in the test: make the queries consume the generated values.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #131157. The four rand.xml queries never called their functions (the unused subquery column is pruned, FunctionExecute is 0 in every CI run since #61652), so the test timed count() over zeros() at 6-8 ms. The PR disables them and adds WHERE NOT ignore(f()) variants with the same row counts.

@Algunenano

Copy link
Copy Markdown
Member

@groeneai While #131157 is good and is merged now, it doesn't explain the slowdown in this PR, it just changes the tests. Please investigate why the tests slowed down, not how to work around it (I don't know how many times I've told you something like this already)

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating why rand #2 (in effect count() over zeros(1e8), since the function is pruned) measured slower on this PR's binary than on master; I'll follow up here with my findings shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

I looked at why rand #2 measured 6.4 -> 8.1 ms on a868fcc. The two binaries execute the same instructions for this query; what differs is where that code sits, and the 09696fc1 reference build landed on the fast side of master's own range.

  • Same work. The candidate is Merge a868fcc5 into 09696fc1, the baseline is the 09696fc1 performance reference build. Across the 30+30 measured runs every counter matches (rows, allocations, page faults, ContextLock), and parse, analysis and planning take the same time. Only execution CPU time differs: UserTimeMicroseconds 5448 -> 7204 (medians).
  • Same code, moved. The 84 functions holding 99% of this job's CPU samples in the query pipeline (memory-profiler unwinding excluded; executor, MemoryTracker, jemalloc, progress and quota callbacks; 33,490 instructions) are identical instruction streams in the two aarch64 binaries, differing only in data and call addresses. The PR adds ~380 KiB to .text, which moves the executor code by 0x62d80 and MemoryTracker/ProfileEvents by 0x10380.
  • Master moves the same way. Since 2026-11-05 the per-build medians of this query range from 6.0 to 8.5 ms across master builds (CIDB). da9125b5 measured 7.0-8.2 ms (19 runs) and 09696fc1, 17 commits later, 5.7-6.5 ms (11 runs). The commits in between change wide-integer arithmetic, Decimal sums and an analyzer pass, and the same 84 functions are identical between those two builds too. This PR's next head (55f5d04f vs 0365c1d2) measured 7.9 -> 8.1 ms.
  • It depends on placement. Before Perf CI: start both servers with ASLR disabled and fail when their executable base differs #126977 the servers started with ASLR on, and two runs of the same official master build differed by 8.1% (median over 836 builds). With ASLR off they differ by 2.7% (734 builds), while per-build means still span 6.7-8.4 ms (p10-p90). So the level belongs to each build's layout, and a given pair of builds reproduces its offset on every re-run.

The query does almost no work per row (count() over zeros, the function is pruned), so its time is about 3 µs of call-heavy executor code per block, and that kind of code is sensitive to layout. The same job shows the effect in both directions on to_bool_low_cardinality (#0 1.23x faster, #1 1.15x slower), and the shard as a whole is +0.4% over 698 queries.

I could not pin down which hardware structure is responsible (instruction TLB, branch predictor or cache sets). The measured runs collect no hardware counters, and in this job's profile runs PerfInstructions is 0 in 609 of 1151 runs, so the report's instructions and cycles ratios cannot be used here.

alexey-milovidov and others added 4 commits November 14, 2026 10:02
Resolve the conflict in `src/Common/Silk/SecureFiberStreamSocketImpl.cpp`, which master
moved from `src/IO` and where master now passes the underlying socket as a
`Poco::AutoPtr` (fixing the same reference leak this PR fixed with `release`):
keep master's constructor and build the server-side `accepted_fd` constructor of the
proxy the same way. Update the includes in `programs/proxy/SocketIO.cpp` to the new paths.
…th requests by the generated query

Address review on `programs/proxy/Frontend.cpp` and `programs/proxy/HTTPFrontend.cpp` in
#110105

A `WITH` clause may contain `select` and `insert` as names, also as bare references in its
expressions (`WITH 1 AS `select`, 1 + select + 1 AS x INSERT ...`), which a keyword scan cannot
tell from the statement. A `WITH` query is now parsed with `ParserQuery`: it is an `insert` or a
`select` as the server parses it, and has no query type if it does not parse, or if only a prefix
of it was read (unless the prefix already reaches the inline data of an `INSERT`).

For a URL path with a table (`/db/table.CSV`), the server generates the query itself: a `PUT`
without a `query` parameter is an upload (`INSERT INTO table FORMAT format`, the body is data),
and a request without a query and a body is `SELECT * FROM table`. The proxy now derives the query
type from them instead of classifying the body of an upload as a query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ts after EOF

Address review on `programs/proxy/SSHFrontend.cpp` in
#110105

The data callbacks leave what exceeds the bounded pending output in the libssh channel buffer.
When the backend sends EOF, exit status and close, and then disconnects, its session enters the
error state, in which `ssh_channel_read_nonblocking` fails before copying the buffered data, so
the rest of the output was lost. Now the EOF callback moves the data still buffered by the source
channel into the pending output. No data follows EOF, so this is bounded by the receive window.
libssh sets the EOF of the channel before the callback, so these reads take only the buffered
data and do not process further packets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review on `programs/proxy/SSHFrontend.cpp` in
#110105

The test starts an `ssh` listener in front of the server's SSH port and checks with the OpenSSH
client that an allowlisted signed key gets through, that a probe of an allowlisted key without
a signature, and a signed key that is not allowlisted (with a listener default pool and with a
rule on the user name only) are denied without routing, and that a backend whose host key is not
in `known_hosts_file` is refused.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master, which brings the fix for the Stress test (arm_asan_ubsan) failure: the heap-use-after-free in DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat is unrelated to the proxy and was fixed in #131029. The merge also adapts the proxy to master moving the Silk sockets to src/Common/Silk. The server-side SecureFiberStreamSocketImpl(accepted_fd, context) constructor now takes the Poco::AutoPtr path that master added. The new commits address the open review threads on WITH classification, HTTP path uploads, SSH output after a backend disconnect, and SSH authorization coverage (05768_proxy_ssh_authorization).

Comment thread programs/proxy/Frontend.cpp Resolved
Comment thread programs/proxy/HTTPFrontend.cpp Resolved
Comment thread programs/proxy/HTTPFrontend.cpp Resolved
Comment thread programs/proxy/MySQLFrontend.cpp Resolved
alexey-milovidov and others added 2 commits November 16, 2026 06:31
`05768_proxy_ssh_authorization` printed the result of the allowlisted
query and then `denied`: `ssh` exited with 255 although the backend
returned exit status 0. After the splice the proxy closed the client
channel and called `ssh_disconnect` at once, so `SSH_MSG_DISCONNECT`
followed the exit status and the channel close immediately. When both
arrive in one read, OpenSSH dispatches the disconnect before it acts on
the closed channel and exits with 255 instead of the exit status. This
happens under load, as in the ASan job.

Wait, bounded by 5 seconds, for the client to close its side before
disconnecting, as the SSH handler of the server does. Also remove the
backend session from the event before freeing it.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110105&sha=cee0ab969d4eeda8a328e3904f2c35705e81d0e5&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted%29
#110105

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and fixed the 05768_proxy_ssh_authorization failure in the targeted ASan job (ff5c604). The allowlisted query printed 1, but ssh then exited with 255, so the test printed denied. After the splice, the proxy closed the client channel and called ssh_disconnect straight away. SSH_MSG_DISCONNECT therefore followed the exit status and the channel close immediately. If they arrive in one read (more likely under ASan load), OpenSSH dispatches the disconnect before it acts on the closed channel, and it exits with 255 instead of the exit status. The CI server log shows the same backend-side teardown for passing and failing runs, so the problem was on the client leg. The proxy now waits, for at most 5 seconds, for the client to close its side before disconnecting, as the server SSH handler does. The race does not reproduce locally: the test passed 13 runs and a loop of 300 allowlisted ssh calls passed with both the old and the fixed proxy. The three open review threads (per-protocol backend health, the MySQL handshake thread ID, MySQL CLIENT_SSL with credential routing) still need a maintainer decision, as answered there.

Comment thread programs/proxy/SSHFrontend.cpp Resolved
Comment thread programs/proxy/HTTPFrontend.cpp Resolved
Comment thread programs/proxy/PostgreSQLFrontend.cpp Outdated
Comment on lines +68 to +78
size_t delivered = 0;
for (const auto & backend : ctx.router.reachableBackends(ctx.listener))
{
/// A secure backend cannot be reached over this protocol (see `connectToBackend`). A backend that
/// is marked down still receives the request: `alive` only gates new routing, and the sessions that
/// were relayed to it before it was marked down may still be running there.
if (backend->config().secure)
continue;
try
{
const UInt16 port = backendPortFor(ListenerProtocol::PostgreSQL, backend->config(), ctx.listener.port);

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.

[Blocker] Bound and cancel the complete PostgreSQL cancellation broadcast

This unauthenticated request serially connects to every reachable backend, including all dynamic backends and those marked down, with a fresh connect_timeout_ms for each. There is no deadline for the broadcast or shutdown check. With the default 10,000 dynamic-backend limit and 3-second connect timeout, unreachable endpoints can keep one handler running for about 30,000 seconds; cancellation of an otherwise healthy session is also delayed by whichever unavailable backends precede it.

The client handshake watchdog and ConnectionRegistry::shutdownAll only shut down the client socket. This loop no longer reads that socket, and it is not registered with abortAllRelays, so ProxyServer::stop waits in connections.waitAll until the entire fanout completes even after the client disconnects.

Give the whole broadcast a bounded budget and make shutdown interrupt its backend work. Please cover cancellation and shutdown with multiple unreachable backends.

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.

🕵 Fixed in 9cb9ef4. The backends now receive the request concurrently, in batches of 64 fibers, those that are not marked down first. The whole broadcast has the budget of handshake_timeout_ms, each connection gets at most the remaining time, and no new batch starts after abortAllRelays. A batch in flight still ends within one connect timeout. I checked it by hand, without adding a test: with 100 unroutable backends before 2 live ones and a 1 s connect timeout, both live backends got the request after 1 s, and a shutdown during a broadcast took 0.7 s. I did not add a regression test, because it would depend on wall-clock timing with unroutable addresses.

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.

[Blocker] The whole-broadcast budget still excludes name resolution. At programs/proxy/PostgreSQLFrontend.cpp:85, resolveAddress runs before the timed connect; programs/proxy/SocketIO.cpp:49-50 performs a blocking hostname lookup in ThreadModeScope, with no deadline. All 64 deliveries can queue onto the fixed blocking-worker pool, retain their original connect timeout, and continue resolving/connecting after the broadcast deadline or shutdown. The join at PostgreSQLFrontend.cpp:135-137 still waits for every delivery, while shutting down the client socket and aborting relays cannot cancel those lookups.

For example, on a four-worker proxy, 64 distinct backend names whose lookups each take five seconds require about 80 seconds of resolver work despite the default ten-second broadcast budget. Please make resolution and queued deliveries obey the shared deadline/shutdown state, rather than checking it only before starting a batch.

alexey-milovidov and others added 2 commits November 19, 2026 05:40
Conflict in `SecureSocketImpl::verifyPeerCertificateImpl`: master moved the
loopback exemption after `X509_check_host` so that `isLocalHost` is only
evaluated when the certificate does not name the host; this branch lets the
caller supply `_peerIsLocalHost` instead of resolving. Keep both: the
exemption is checked late, and uses `_peerIsLocalHost` when set.
Comment thread programs/proxy/HTTPFrontend.cpp Resolved
Comment thread programs/proxy/MySQLFrontend.cpp Resolved
Comment thread programs/proxy/SSHFrontend.cpp Resolved
alexey-milovidov and others added 6 commits November 21, 2026 20:03
…H` queries off the fiber stack

Address review: the proxy and the backend could read one HTTP request differently,
so that a request was routed by one user or query type and executed with another.

- The request line must be `method SP request-target SP HTTP-version`: the server splits it
  at any whitespace and ignores what follows the version.
- A line of the request head must end with CRLF and have a name without whitespace:
  the server takes ` X-ClickHouse-User: alice` for a field without a name.
- `decompress` is the last occurrence parsed as a boolean, as `HTMLForm::getParsedLast<bool>`.
- The only accepted `Transfer-Encoding` is a single `chunked`, `Content-Length` must be a plain
  number, and a chunk header is read as `HTTPChunkedReadBuffer` reads it.
- A body without `Content-Length` and chunked encoding lasts until the end of the stream
  and is not inspected, so the query type is known only from the `query` parameter.
- The formats are registered in the proxy, so a path such as `/db/table.CSV.gz` is parsed as by the server.
- A `WITH` query is parsed on a thread of the global pool, where `checkStackSize` works:
  on the stack of a fiber, a deeply nested query of an unauthenticated client overflowed the stack.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Address review: only the `HandshakeResponse` of the client was bounded. The greeting and
the authentication result of the backend and the auth-switch response of the client were read
with the unbounded packet readers, which join continuation packets, so a faulty backend or
an unauthenticated client could make the proxy allocate memory without a limit.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…t at shutdown

Address review: the unauthenticated request was delivered to every backend one by one, each
unreachable backend costing a connect timeout, without a deadline, and shutdown waited for it.
The backends now receive it concurrently, in batches of 64, those that are not marked down first.
The whole broadcast has the time budget of a handshake and stops when the proxy shuts down.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Address review:
- When the backend closes its transport after EOF, the output already received from it is still
  delivered to a client whose window is closed: the backend leg is released and the client is polled
  until the output is written, instead of ending the session on the poll error.
- The backend channel is released, and the pointers that the callbacks of the client channel use
  are cleared, before the client is polled for the end of the session: a packet of the client
  arriving during that wait used the freed backend channel.
- libssh accepts data and repeated EOF after EOF, so the output saved in the EOF callback could grow
  without a bound. It is saved only for the first EOF, and a peer that sends data or EOF after EOF
  has its session ended.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… a PostgreSQL `CancelRequest`

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and addressed the 13 open review threads in separate commits:

  • 4961bb7: the HTTP frontend reads the request head as the backend does and rejects what the two would read differently (request line, header lines, decompress, Transfer-Encoding, Content-Length, chunk headers). A body that lasts until the end of the stream is not inspected. The formats are registered, so /db/table.CSV.gz is parsed as by the server. A WITH query is parsed on a thread of the global pool instead of the fiber stack. Test: 05842_proxy_http_strict_request_head.
  • 15d3799: every MySQL packet of the authentication phase is bounded on both legs. Test: 05843_proxy_mysql_oversized_handshake_packets.
  • 9cb9ef4: the broadcast of a PostgreSQL CancelRequest is concurrent, has a time budget and stops at shutdown. Checked by hand, no new test.
  • ab09b5a: three fixes of the end of an SSH session (output owed to the client after the backend closes its transport, a use-after-free of the backend channel in the finishing wait, unbounded output after repeated EOF). No new test: these need a custom SSH peer.

All 15 proxy stateless tests pass locally on a release build, run one at a time.

The previous CI run was red only because the review-threads gate skipped the full suite. Three threads stay open for a maintainer decision, as answered there: per-protocol backend health, the MySQL handshake thread ID, and MySQL CLIENT_SSL with credential routing. The gate stays blocked until they are resolved.

alexey-milovidov and others added 2 commits November 24, 2026 16:18
# Conflicts:
#	programs/CMakeLists.txt
…or the style check

The `catch_all` style check flagged the `catch (...)` around `parse<bool>` in `HTTPFrontend.cpp` as silently swallowing
the exception. It does not: the failure is reported to the client as a bad request. Say so in a comment.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110105&sha=3630733cba80d2d41b232d6d784b3a1758dc85c7&name_0=PR&name_1=Style%20check
#110105

Co-Authored-By: Claude Fable 5.2 <[email protected]>
static_cast<uint32_t>(std::min(sizeof(buffer), max_pending_output_bytes - out.bytes)), is_stderr);
if (read <= 0)
break;
forward(out, destination, buffer, read, is_stderr);

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.

[Blocker] Preserve bytes when the source read invokes data callbacks

ssh_channel_read_nonblocking first polls its session and can invoke onBackendData or onClientData, which mutate this same PendingOutput. For example, with a closed destination window and out.bytes == max_pending_output_bytes - 1, an arriving two-byte packet queues one byte in its callback. The read then removes the remaining byte from libssh and returns it, but the queue is now full, so forward consumes zero. Ignoring its return value silently loses that byte. The reverse direction can lose client input the same way.

Reserve capacity across the callbacks, or retain every byte removed by the read even if callbacks filled the queue. Please cover new source data arriving during this read while the destination window is closed.

AcceptState * raw = state.get();
if (silk::FiberScheduler::run(acceptLoop, AcceptParams(raw->params), &raw->future) != 0)
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Cannot start the accept loop fiber");
accept_states.push_back(std::move(state));

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.

[Blocker] Retain the accept-loop state before starting its fiber

This vector insertion can allocate after FiberScheduler::run has started the accept loop with &raw->future. If the insertion throws, the local state is destroyed, but the running fiber still holds that future's address. The pinned Silk implementation stores the raw future pointer and calls its set on completion; FiberFuture has no joining destructor. The loop also never enters accept_states, so stop cannot join it before destroying the scheduler. A startup allocation failure therefore becomes a use-after-free during cleanup.

Reserve the vector for every listener before scheduling any accept loop, or establish durable ownership before starting each fiber, with cleanup for a scheduling failure.

Comment thread programs/proxy/Router.cpp
auto [it, inserted] = seen.try_emplace(key);
if (inserted)
{
it->second.finished = std::make_shared<silk::FiberEvent>();

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.

[Blocker] Roll back first-seen state when setup or the hook throws

seen.try_emplace has already inserted an entry with done == false and a null finished. If this allocation throws, the connection handler catches the exception, but the incomplete entry stays in the router. Every later connection with the same target and name assigns the null event to wait_for, then repeats while (!finished) without waiting or yielding. Shutting down the client socket cannot interrupt this loop, so a transient allocation failure leaves permanent busy-spinning handlers and prevents proxy shutdown.

There is a second exceptional exit after the event is installed: runHook formats and logs its command before entering its try. If that throws, the entry retains an event that is never signaled, leaving subsequent connections suspended forever.

Allocate the event before publishing the entry, then guard the published state so every exceptional exit erases the unfinished entry and signals its waiters.

This branch was successfully deployed

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

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants