Skip to content

TCP: replica-aware routing with a ReplicaTag setting - #724

Draft
alex-clickhouse wants to merge 7 commits into
mainfrom
alex-clickhouse/tcp-replica-routing
Draft

alex-clickhouse wants to merge 7 commits into
mainfrom
alex-clickhouse/tcp-replica-routing

Conversation

@alex-clickhouse

@alex-clickhouse alex-clickhouse commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds replica-aware routing for ClickHouse Cloud to the native TCP client, as a ReplicaTag setting.

What. A replica tag can be set in two places:

  • the client: ClickHouseTcpClientOptions.ReplicaTag, or ReplicaTag= in the connection string. Every pooled connection of the client uses it.
  • a session: the new ClickHouseTcpSessionOptions.ReplicaTag, through a new OpenSessionAsync(ClickHouseTcpSessionOptions, CancellationToken) overload on the client, the data source and their interfaces.

A session tag replaces the client tag. Null or empty means the client tag. There is no tag per operation: to run work on one replica, set the client tag or open a session with a tag.

How.

  • Cloud chooses the replica of a native connection from the TLS server name (SNI): <tag>.sticky.<host>. The client still dials Host. This is what clickhouse-client --tls-sni-override does.
  • .NET uses SslClientAuthenticationOptions.TargetHost for the SNI and for the certificate name check. A certificate for the service host does not cover the sticky name (a wildcard covers one label). So a tagged connection sets the sticky name as TargetHost and installs a validation callback that accepts the certificate when it names the sticky name, or when its only fault is that it names the normal host (X509Certificate2.MatchesHostname). Chain errors still refuse it. The pinned-CA chain policy, TlsAllowInvalidCertificates and the ConfigureTls hook work as before.
  • A tag needs UseTls and a DNS host name, and must be one DNS label (1-63 characters, A-Z a-z 0-9 -). Other values are refused with ArgumentException, so the same string reaches the same replica as with clickhouse-client. The client tag is checked at construction, a session tag before the checkout takes a permit.
  • The tag is fixed by the TLS handshake, so it belongs to a connection. Every connection in the pool's idle set has the client tag, so reuse and the top-up to MinPoolSize work as before.
  • A session with another tag takes a permit like any checkout, but it never reuses an idle connection: it opens a new one that only it uses (PooledConnection.Dedicated), and the pool never puts that connection back in the idle set. Idle connections hold no permit, so when the pool is full the session first closes the longest-idle connection, and dials only after that.
  • Return closes a connection that it does not keep before it removes it from the leased set. Otherwise the socket is in no counted set while it closes, and a session dial at that moment sees one socket too few. This also covers ordinary connections that come back expired or broken.
  • New Debug log events: 2004 (dial with a replica tag) and 3008 (idle connection closed to make room for a session's tag).

Why. Requests that must reach one replica (read your own writes before the other replicas catch up, cache reuse, data that only one replica has) had no first-class way to do it on the native protocol. A tag chooses a replica, not a connection: temporary tables and SET settings still need a session. The HTTP client can already send the X-ClickHouse-Replica-Tag header with CustomHeaders, so this PR does not change the HTTP client.

An earlier version of this PR also had a tag per operation. That needed a pool that keeps connections with many tags in one idle set, searches it by tag and counts undecided checkouts to keep MaxPoolSize. It was removed to keep the pool simple.

Tests

  • Unit, no server: tag rules and sticky name (ReplicaRoutingTests); SNI that the server receives and which certificates are accepted or refused with a tag, against an in-process TLS server (TlsParametersTests). Pool (ConnectionPoolReplicaTagTests): the client tag is used and reused; a session tag opens a new connection and leaves idle ones alone; its connection is closed on return; the longest-idle connection is closed when the pool is full; a pool full of leased connections makes the session wait; a connection that Return closes stays counted while a session dials (deterministic); 800 concurrent checkouts, half with session tags, never have more than MaxPoolSize connections open; top-up tag; invalid tags; sessions. Log event 3008.
  • Integration, local server: TlsTerminatingProxy records the SNI of each connection and, on request, the plaintext the client sent. The tests find the connection that carried each query id and check its SNI: client tag, no tag, connection string, log event 2004, the data source overload, a session with its own tag that keeps a temporary table while the client uses its tag, and a session without a tag that uses the client tag. The proxy certificate names only the normal host, as a Cloud certificate does.
  • Cloud (ReplicaRoutingCloudIntegrationTests, [Category("Cloud")], ignored outside Cloud):
    • positive: one client tag over 8 new connections reaches one replica; two sessions with that tag reach the same replica; 4 session tags through a pool of 1 (so each session closes an idle connection) each keep one replica over 3 rounds;
    • negative: 16 new connections without a tag reach more than one replica, and 16 different tags reach more than one replica. The negative tests show that the service has several replicas and that the tag chooses among them, so the positive results do not come from a service with one replica.
  • Mutation checks: removing the certificate callback fails 2 TLS tests; removing the idle close fails 3 pool tests; letting a session's connection into the idle set fails 2; removing from the leased set before the close fails the deterministic test (3 sockets with MaxPoolSize 2).
  • Local runs, ClickHouse.Driver.Tcp.Tests after merging main (TCP: report the driver version, not 0.0.0, so distributed queries work #725): net9.0 and net10.0 4254 passed, 6 skipped (the Cloud tests); net8.0 also passed before the merge. No new build warnings. No RS public API diagnostics. changelog.cs --check OK.

Checklist

  • Unit and integration tests covering the common scenarios were added
  • A human-readable description of the changes was provided to include in CHANGELOG

🤖 Generated with Claude Code


Note

Medium Risk
Touches TLS validation, connection pooling concurrency, and public API (ReplicaTag, session options); incorrect pool or cert logic could cause wrong-replica routing or connection leaks, but changes are heavily tested.

Overview
Adds replica-aware routing for the native TCP client on ClickHouse Cloud via a new ReplicaTag on ClickHouseTcpClientOptions and connection strings, plus ClickHouseTcpSessionOptions for OpenSessionAsync overloads.

Tagged TLS connections send SNI as <tag>.sticky.<host> (implemented in ReplicaRouting and TlsParameters) while still validating certificates against the normal host name. The connection pool opens and reuses connections per client tag; sessions with a different tag get dedicated connections that are closed on return, and may evict the longest-idle connection when at MaxPoolSize. Factory APIs now pass replicaTag through dial/handshake.

Includes docs, changelog, a Cloud-only example, and broad unit/integration/Cloud tests for validation, TLS, pooling, and routing behavior.

Reviewed by Cursor Bugbot for commit c911486. Bugbot is set up for automated code reviews on this repo. Configure here.

alex-clickhouse and others added 2 commits November 12, 2026 12:35
ClickHouse Cloud sends a native-protocol connection to the replica that its
TLS server name (SNI) asks for: <tag>.sticky.<host>. This adds a ReplicaTag
setting at three levels: ClickHouseTcpClientOptions (and the ReplicaTag
connection-string key), ClickHouseTcpQueryOptions for one operation, and the
new ClickHouseTcpSessionOptions for OpenSessionAsync.

- The client sends the sticky name as SNI and checks the certificate
  against the normal host name, because Cloud certificates name <host> and
  *.<host> only. The chain is checked as usual.
- A tag needs TLS and must be one DNS label; other values are refused.
- The pool reuses a connection only for the same tag. All tags share
  MaxPoolSize: a checkout that must open a connection closes the
  longest-idle connection of another tag when the pool is full.
- A session keeps the tag of its connection and refuses an operation with
  another tag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g scan

- The reuse-policy test puts the connection with another tag where each
  policy looks first, so the scan must skip it.
- Log events 2004 (tagged dial) and 3008 (connection closed for another
  tag) are asserted.
- ClickHouseTcpDataSource.OpenSessionAsync with session options is called
  through the TLS proxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

AI review gate — AI review passed

Clean review from: Cursor Bugbot.

@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.92473% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...lickHouse.Driver.Tcp/Client/ClickHouseTcpClient.cs 75.00% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@alex-clickhouse
alex-clickhouse marked this pull request as ready for review November 12, 2026 12:58
Copilot AI balanced review requested due to automatic review settings November 12, 2026 12:58

Copilot AI left a comment

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.

🟡 Changes recommended

Evicted connections are removed from pool accounting before their sockets close, allowing concurrent tagged checkouts to exceed MaxPoolSize.

2 open issues
What changed in this PR

Adds ClickHouse Cloud replica-aware routing to the native TCP client through ReplicaTag, allowing related operations and sessions to target the same replica. The HTTP client is unchanged.

Changes:

  • Adds client, connection-string, operation, and session tag options, with TLS server-name routing and certificate validation.
  • Makes connection pooling tag-aware, including eviction under the shared pool limit and new diagnostic events.
  • Adds routing tests, documentation, an opt-in Cloud example, and a changelog fragment.
File Description
examples/​Tcp/​Connection/​Tcp_005_ReplicaRouting.cs Demonstrates tagged Cloud connections and sessions.
examples/​README.md Indexes the routing example.
examples/​ExampleRunner.cs Marks the example as opt-in.
examples/​AGENTS.md Documents the example’s configuration exemptions.
docs/​tcp.mdx Explains tag options, TLS, pooling, and sessions.
ClickHouse.Driver.Tcp/​PublicAPI/​PublicAPI.Unshipped.txt Records new public options and overloads.
ClickHouse.Driver.Tcp/​Protocol/​TlsParameters.cs Adds sticky TLS names and certificate-name fallback.
ClickHouse.Driver.Tcp/​Protocol/​ReplicaRouting.cs Validates tags and constructs routing names.
ClickHouse.Driver.Tcp/​Protocol/​ClickHouseTcpConnection.cs Passes tags into TLS setup.
ClickHouse.Driver.Tcp/​Logging/​PoolLog.cs Adds tag-eviction logging.
ClickHouse.Driver.Tcp/​Logging/​ConnectionLog.cs Adds tagged-connection logging.
ClickHouse.Driver.Tcp/​Client/​PooledConnection.cs Stores each connection’s tag.
ClickHouse.Driver.Tcp/​Client/​PinnedConnectionSource.cs Rejects tag changes within sessions.
ClickHouse.Driver.Tcp/​Client/​IConnectionSource.cs Adds tags to checkout and lease contracts.
ClickHouse.Driver.Tcp/​Client/​IConnectionFactory.cs Carries tags into connection creation.
ClickHouse.Driver.Tcp/​Client/​IClickHouseTcpDataSource.cs Exposes session options through the interface.
ClickHouse.Driver.Tcp/​Client/​IClickHouseTcpClient.cs Declares the session-options overload.
ClickHouse.Driver.Tcp/​Client/​ConnectionPool.cs Implements tag-matched reuse, eviction, and defaults.
ClickHouse.Driver.Tcp/​Client/​ClickHouseTcpSessionOptions.cs Introduces session-level replica tags.
ClickHouse.Driver.Tcp/​Client/​ClickHouseTcpQueryOptions.cs Adds operation-level replica tags.
ClickHouse.Driver.Tcp/​Client/​ClickHouseTcpDataSource.cs Forwards session options to the client.
ClickHouse.Driver.Tcp/​Client/​ClickHouseTcpConnectionStringBuilder.cs Parses and exposes ReplicaTag.
ClickHouse.Driver.Tcp/​Client/​ClickHouseTcpClientOptions.cs Adds and validates the default tag.
ClickHouse.Driver.Tcp/​Client/​ClickHouseTcpClient.cs Routes operation and session tags into checkout.
ClickHouse.Driver.Tcp.Tests/​Utilities/​TlsTerminatingProxy.cs Records TLS names and optional client traffic.
ClickHouse.Driver.Tcp.Tests/​Utilities/​PoolTestDoubles.cs Records tags used to create connections.
ClickHouse.Driver.Tcp.Tests/​Utilities/​ConnectionSourceExtensions.cs Preserves untagged test checkout shorthand.
ClickHouse.Driver.Tcp.Tests/​Protocol/​TlsParametersTests.cs Tests tagged TLS names and certificate validation.
ClickHouse.Driver.Tcp.Tests/​Protocol/​ReplicaRoutingTests.cs Tests tag validation and routing-name construction.
ClickHouse.Driver.Tcp.Tests/​Integration/​TcpServerFixture.cs Adapts factory calls to accept tags.
ClickHouse.Driver.Tcp.Tests/​Integration/​ReplicaRoutingIntegrationTests.cs Tests routing across queries, inserts, and sessions.
ClickHouse.Driver.Tcp.Tests/​Integration/​ReplicaRoutingCloudIntegrationTests.cs Tests replica affinity and distribution on Cloud.
ClickHouse.Driver.Tcp.Tests/​Integration/​CompressionIntegrationTests.cs Forwards tags through the counting factory.
ClickHouse.Driver.Tcp.Tests/​Client/​TcpConnectionFactoryTests.cs Updates existing factory calls.
ClickHouse.Driver.Tcp.Tests/​Client/​PinnedConnectionSourceTests.cs Adds tag metadata to test leases.
ClickHouse.Driver.Tcp.Tests/​Client/​ConnectionPoolReplicaTagTests.cs Tests tag-aware pooling and session constraints.
ClickHouse.Driver.Tcp.Tests/​Client/​ConnectionPoolLoggingTests.cs Verifies eviction log events.
ClickHouse.Driver.Tcp.Tests/​Client/​ClickHouseTcpConnectionStringBuilderTests.cs Tests tag parsing and defaults.
ClickHouse.Driver.Tcp.Tests/​Client/​ClickHouseTcpClientOptionsTests.cs Extends default, validation, and copying tests.
changelog.d/​tcp-replica-routing.features.md Announces TCP replica-aware routing.

Review effort: Balanced

Comment on lines +858 to +861
while (idle.Count > 0 && AccountedConnections > options.MaxPoolSize)
{
(evicted ??= new List<PooledConnection>()).Add(idle[0]);
idle.RemoveAt(0);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cbc75d8, with a different approach than "make dials wait".

The cause was the count: idle + leased + pending also counted checkouts that had not yet looked at the idle set. So one checkout could take several idle connections out of the count, and other checkouts then dialed while those sockets were still open.

Now a checkout chooses between reuse and a dial, and takes the connection to close, in one lock. It compares against a count that leaves those checkouts out (CommittedConnections). That count stays within MaxPoolSize: reuse moves a connection from idle to a checkout, and a dial adds one. So a dial closes at most one idle connection. The checkout closes it before it dials, and its own slot covers that socket until it is closed. No dial has to wait.

New tests in ConnectionPoolReplicaTagTests:

  • RentAsync_ConcurrentCheckoutsOnAFullPool_ClosesOnlyTheConnectionTheNewTagNeeds: 300 rounds.
  • RentAsync_ManyConcurrentCheckoutsWithManyTags_NeverHasMoreThanMaxPoolSizeConnectionsOpen: 20 rounds of 800 checkouts over 7 tags. A connection counts as open from the start of its dial until its socket is closed.

Both pass on the new code. One limit: they did not reliably fail on the previous code either, because a checkout makes its choice in microseconds and the bad interleaving is rare. The fix rests on the count argument above, not on these tests.

Comment thread examples/ExampleRunner.cs
"CreateTableCluster",
"CreateTableCloud",
"JwtAuthentication",
"TcpReplicaRouting",

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cbc75d8: TcpReplicaRouting is now in _customEndpoint as well as _optIn. examples/AGENTS.md now says that an opt-in example with its own endpoint goes in both. Checked locally with no server on port 9000: dotnet run -- --filter TcpReplicaRouting reaches the example and prints its message about the missing Cloud variables.

@security-ai-gate-reviewer security-ai-gate-reviewer Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the approval on c911486.

Comment thread examples/ExampleRunner.cs Resolved
@polyglotAI-bot

polyglotAI-bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

This PR adds replica-aware routing to the native TCP client through client and session replica tags, with TLS hostname validation and dedicated connections for session overrides. No actionable findings remain in the current snapshot. The previously reported Cloud example preflight issue is fixed. ✅ Approve based on static review; builds, tests, and live Cloud routing were not independently run in this sandbox.

Final verdict

✅ Approve

Automated review by Polyglot AI (gpt-6-astra) of c911486. Replies on the inline threads are read on the next review. A maintainer can ask for a new review by mentioning @polyglotAI-bot or requesting a review from it.

The pool decided whether a dial must first close an idle connection of
another tag from idle + leased + pending. `pending` also counts checkouts
that have not yet looked at the idle set, so one checkout could close
connections that others were about to reuse, and the closed sockets left
the count before they were closed. A checkout now chooses between reuse and
a dial, and takes the connection to close, in one lock against a count
that leaves those checkouts out. That count stays within MaxPoolSize, so a
dial closes at most one connection, and closes it before it dials.

- Tests: concurrent checkouts on a full pool close only the connection the
  new tag needs; many concurrent checkouts over many tags never have more
  than MaxPoolSize connections open; the TLS name fallback refuses a
  mismatch without a certificate.
- Example: TcpReplicaRouting is a custom-endpoint example, so a filtered
  run does not check the local endpoint first.
- Docs: a tag chooses a replica, not a connection, so temporary tables
  need a session; MinPoolSize with other tags; certificate wording;
  ConfigureTls with a tag. Shorter changelog entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@security-ai-gate-reviewer security-ai-gate-reviewer Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the approval on c911486.

It must leave both `pending` and `undecided` and release its slot, or the
drain waits out PoolTimeout. Also name the changelog fragment after the
pull request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@security-ai-gate-reviewer security-ai-gate-reviewer Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the approval on c911486.

alex-clickhouse and others added 3 commits November 13, 2026 10:20
Remove ClickHouseTcpQueryOptions.ReplicaTag. A per-operation tag made the
pool keep connections with many tags in one idle set, search that set by
tag, and count undecided checkouts to keep MaxPoolSize.

Now every pooled connection has the client's tag. A session with another
tag gets a new connection that only it uses; the pool never puts that
connection in the idle set. When the pool is full, the session dial first
closes the longest-idle connection. A connection the pool does not keep is
closed before it leaves the leased set, so that count never misses an
open socket.

Remove the docs sections on how the client sends the tag and on pooling
with tags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eplica-routing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@workflow-authentication-public workflow-authentication-public Bot added the needs-docs PR has user-visible changes without matching docs updates label Nov 13, 2026
@workflow-authentication-public

Copy link
Copy Markdown

Docs drift check: this PR looks like it needs doc updates.

  • examples/README.md: the "Connection configuration" section is now stale — "The seven exceptions are listed below" (line 197) and "Seven examples do not rely on ExampleConfig ... Three use their own environment variables" (lines 216–222) still count seven. The new Tcp_005_ReplicaRouting reads CLICKHOUSE_CLOUD_HOST / CLICKHOUSE_CLOUD_USER / CLICKHOUSE_CLOUD_PASSWORD instead of ExampleConfig and is registered in ExampleRunner._customEndpoint, so the counts become eight and four and the example belongs in the own-environment-variables list (examples/AGENTS.md got the equivalent seven→eight update; the user-facing README did not).

@security-ai-gate-reviewer security-ai-gate-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Auto-approved by the AI review gate on c911486. Details in the approver's comment on this pull request.

@security-ai-gate-reviewer

Copy link
Copy Markdown

AI review gate — auto-approved

c911486e2e79 is approved by security-ai-gate-reviewer[bot], an automated identity, not a human. The approval stands on the required AI review: Cursor Bugbot concluded green on this commit and the AI review gate is SUCCESS (its own comment has the verdict), and the change touches no path that requires a human reviewer. It is bound to this commit: a new push dismisses it and the approver re-evaluates.

History (latest 5 heads, newest first)

  • c911486e2e79 approved — green: Cursor Bugbot

@alex-clickhouse
alex-clickhouse marked this pull request as draft November 16, 2026 05:04

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-docs PR has user-visible changes without matching docs updates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants