Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using ClickHouse.Driver.Tcp.Protocol;
using ClickHouse.Driver.Tcp.Tests.Utilities;

namespace ClickHouse.Driver.Tcp.Tests.Integration;

/// <summary>
/// The client version the driver reports in its handshake and in the ClientInfo of every query. A server refuses to
/// send a distributed query on when the client that started it reports version 0.0.0, so a query that reaches another
/// replica over a connection of its own is the test that matters.
/// </summary>
[TestFixture]
[Category("Integration")]
[Category("Cloud")]
public class ClientVersionIntegrationTests
{
private static readonly CancellationToken None = CancellationToken.None;

[Test]
public async Task ExecuteScalarAsync_QueryThatReadsEveryCloudReplica_Succeeds()
{
if (!TcpServerFixture.IsCloud)
{
Assert.Ignore("Only a Cloud service has replicas that a query reaches over connections of their own.");
}

await using ClickHouseTcpClient client = TcpServerFixture.CreateClient();

object replicas = await client.ExecuteScalarAsync(
"SELECT count() FROM clusterAllReplicas(default, system.one)",
cancellationToken: None);

Assert.That(replicas, Is.GreaterThanOrEqualTo(1UL));
}

[Test]
public async Task ExecuteScalarAsync_RemoteQueryToTheSameServer_Succeeds()
{
if (TcpServerFixture.IsCloud)
{
Assert.Ignore("A Cloud service does not accept remote() to its own local port.");
}

await using ClickHouseTcpClient client = TcpServerFixture.CreateClient();

// The server's own plaintext native port, which is not the port the suite dialled when a proxy or TLS is in
// between.
object port = await client.ExecuteScalarAsync("SELECT tcpPort()", cancellationToken: None);
var parameters = new ClickHouseTcpParameterCollection
{
new ClickHouseTcpParameter("address", $"localhost:{port}"),
new ClickHouseTcpParameter("user", TcpServerFixture.Username),
new ClickHouseTcpParameter("password", TcpServerFixture.Password),
};

// prefer_localhost_replica = 0 makes the server open a connection to itself instead of reading locally, so
// the query takes the same path as a query to another replica.
object rows = await client.ExecuteScalarAsync(
"SELECT count() FROM remote({address:String}, system.one, {user:String}, {password:String}) SETTINGS prefer_localhost_replica = 0",
new ClickHouseTcpQueryOptions { Parameters = parameters },
None);

Assert.That(rows, Is.EqualTo(1UL));
}

[Test]
public async Task ExecuteAsync_AnyQuery_RecordsTheDriverVersionAsTheClientVersion()
{
await using ClickHouseTcpClient client = TcpServerFixture.CreateClient();
string queryId = Guid.NewGuid().ToString();

await client.ExecuteAsync("SELECT 1", new ClickHouseTcpQueryOptions { QueryId = queryId }, None);

object reported = await QueryLog.ScalarAsync(
client,
$"SELECT format('{{}}.{{}}.{{}}', client_version_major, client_version_minor, client_version_patch) FROM {QueryLog.Table} WHERE query_id = '{queryId}' AND type = 'QueryFinish'");

(int major, int minor, int patch) = ClientVersion.Current;
Assert.That(reported, Is.EqualTo($"{major}.{minor}.{patch}"));
}
}
110 changes: 110 additions & 0 deletions ClickHouse.Driver.Tcp.Tests/Protocol/ClientVersionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ClickHouse.Driver.Tcp.Protocol;

namespace ClickHouse.Driver.Tcp.Tests.Protocol;

[TestFixture]
public class ClientVersionTests
{
[TestCase("1.5.0+3f2a1c9", 1, 5, 0)]
[TestCase("1.4.0-rc2+3f2a1c9", 1, 4, 0)]
[TestCase("2.10.3", 2, 10, 3)]
[TestCase("1.5", 1, 5, 0)]
public void Parse_InformationalVersion_ReadsMajorMinorAndPatch(string informationalVersion, int major, int minor, int patch)
{
Assert.That(ClientVersion.Parse(informationalVersion), Is.EqualTo((major, minor, patch)));
}

// 0.0.0 is what a benchmark build carries, and it is the one version a server refuses for a distributed query.
[TestCase("0.0.0-baseline")]
[TestCase("0.0.0-pr.724+3f2a1c9")]
[TestCase("not a version")]
[TestCase("1")]
[TestCase("")]
[TestCase(null)]
public void Parse_NoUsableVersion_ReturnsTheFallback(string informationalVersion)
{
Assert.That(ClientVersion.Parse(informationalVersion), Is.EqualTo(ClientVersion.Fallback));
}

[Test]
public async Task ClientInfoWrite_ClientVersion_WritesMajorMinorAndPatch()
{
// Distinct values, so a field written as a constant or in the wrong slot shows. A dev build reports 1.0.0,
// whose zero minor and patch cannot show that.
var client = new ClientMetadata { Username = "default", VersionMajor = 12, VersionMinor = 34, VersionPatch = 56 };
using var ms = new MemoryStream();
using (var writer = new ClickHouseBinaryWriter(ms))
{
ClientInfo.Write(writer, new NegotiatedProtocol(NegotiatedProtocol.ClientTcpProtocolVersion), client);
await writer.FlushAsync(CancellationToken.None);
}

var wire = new WireCursor(ms.ToArray());
Assert.That(wire.Byte(), Is.EqualTo(1), "query_kind");
wire.String(); // initial_user
wire.String(); // initial_query_id
wire.String(); // initial_address
wire.Skip(sizeof(long)); // initial_query_start_time_microseconds
Assert.That(wire.Byte(), Is.EqualTo(1), "interface");
wire.String(); // os_user
wire.String(); // client_hostname
Assert.That(wire.String(), Is.EqualTo(ClientHandshakeParameters.DefaultClientName));
ulong major = wire.VarUInt();
ulong minor = wire.VarUInt();
wire.VarUInt(); // client_tcp_protocol_version
wire.String(); // quota_key
wire.VarUInt(); // distributed_depth
ulong patch = wire.VarUInt();

Assert.That((major, minor, patch), Is.EqualTo((12UL, 34UL, 56UL)));
}

[Test]
public void ClientHandshakeParameters_Defaults_ReportTheDriverVersion()
{
var parameters = new ClientHandshakeParameters { Username = "default" };

Assert.Multiple(() =>
{
Assert.That((parameters.VersionMajor, parameters.VersionMinor, parameters.VersionPatch), Is.EqualTo(ClientVersion.Current));
Assert.That(ClientVersion.Current, Is.Not.EqualTo((0, 0, 0)));
});
}

// Reads the native protocol's primitive encodings from a byte array, in order.
private sealed class WireCursor(byte[] bytes)
{
private int position;

internal byte Byte() => bytes[position++];

internal void Skip(int count) => position += count;

internal ulong VarUInt()
{
ulong value = 0;
for (int shift = 0; ; shift += 7)
{
byte b = bytes[position++];
value |= (ulong)(b & 0x7F) << shift;
if ((b & 0x80) == 0)
{
return value;
}
}
}

internal string String()
{
int length = checked((int)VarUInt());
string value = Encoding.UTF8.GetString(bytes, position, length);
position += length;
return value;
}
}
}
16 changes: 11 additions & 5 deletions ClickHouse.Driver.Tcp/Protocol/ClientHandshakeParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,17 @@ internal sealed class ClientHandshakeParameters
/// affect negotiation.</summary>
public string ClientName => DefaultClientName;

/// <summary>Informational client major version (ClientHello field 2).</summary>
public int VersionMajor { get; init; }
/// <summary>Client major version (ClientHello field 2). Defaults to this driver's version.</summary>
public int VersionMajor { get; init; } = ClientVersion.Current.Major;

/// <summary>Informational client minor version (ClientHello field 3).</summary>
public int VersionMinor { get; init; }
/// <summary>Client minor version (ClientHello field 3). Defaults to this driver's version.</summary>
public int VersionMinor { get; init; } = ClientVersion.Current.Minor;

/// <summary>
/// Client patch version. ClientHello has no field for it; every query's ClientInfo carries it. Defaults to this
/// driver's version.
/// </summary>
public int VersionPatch { get; init; } = ClientVersion.Current.Patch;

/// <summary>Default database (ClientHello field 5).</summary>
public string Database { get; init; } = "default";
Expand All @@ -38,5 +44,5 @@ internal sealed class ClientHandshakeParameters
public override string ToString()
=> string.Create(
CultureInfo.InvariantCulture,
$"{nameof(ClientHandshakeParameters)} {{ ClientName = {ClientName}, Version = {VersionMajor}.{VersionMinor}, Database = {Database}, Username = {Username}, Password = <redacted>, QuotaKey = <redacted> }}");
$"{nameof(ClientHandshakeParameters)} {{ ClientName = {ClientName}, Version = {VersionMajor}.{VersionMinor}.{VersionPatch}, Database = {Database}, Username = {Username}, Password = <redacted>, QuotaKey = <redacted> }}");
}
2 changes: 1 addition & 1 deletion ClickHouse.Driver.Tcp/Protocol/ClientInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public static void Write(ClickHouseBinaryWriter writer, NegotiatedProtocol negot

if (negotiated.Supports(ProtocolFeature.VersionPatch))
{
writer.WriteVarUInt(0); // client_version_patch
writer.WriteVarUInt((ulong)client.VersionPatch);
}

if (negotiated.Supports(ProtocolFeature.OpenTelemetry))
Expand Down
8 changes: 6 additions & 2 deletions ClickHouse.Driver.Tcp/Protocol/ClientMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,15 @@ internal sealed class ClientMetadata
/// <summary>Informational client identifier, pinned to the same value the handshake reports.</summary>
public string ClientName => ClientHandshakeParameters.DefaultClientName;

/// <summary>Informational client major version.</summary>
/// <summary>Client major version, as the handshake reported it.</summary>
public int VersionMajor { get; init; }

/// <summary>Informational client minor version.</summary>
/// <summary>Client minor version, as the handshake reported it.</summary>
public int VersionMinor { get; init; }

/// <summary>Client patch version.</summary>
public int VersionPatch { get; init; }

/// <summary>Username, echoed as the initiating user in ClientInfo.</summary>
required public string Username { get; init; }

Expand All @@ -31,6 +34,7 @@ internal sealed class ClientMetadata
{
VersionMajor = parameters.VersionMajor,
VersionMinor = parameters.VersionMinor,
VersionPatch = parameters.VersionPatch,
Username = parameters.Username,
QuotaKey = parameters.QuotaKey,
};
Expand Down
48 changes: 48 additions & 0 deletions ClickHouse.Driver.Tcp/Protocol/ClientVersion.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using System.Reflection;

namespace ClickHouse.Driver.Tcp.Protocol;

/// <summary>
/// The client version the driver reports in its handshake and in the ClientInfo of every query: the version of this
/// package, as major, minor and patch.
Comment on lines +7 to +8

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.

Added in 04bc611: a new section "Client name and version on the server" under "Logging and diagnostics" in docs/tcp.mdx. It lists the system.query_log / system.processes columns, says the version is the ClickHouse.Driver package version, and gives the 1.0.0 fallback with its reason.

/// </summary>
/// <remarks>
/// A server refuses to send a distributed query (<c>clusterAllReplicas</c>, <c>remote</c>, a <c>Distributed</c>
/// table) on to another server when the client that started it reports 0.0.0. So a build whose version is missing,
/// cannot be read, or is 0.0.0 reports <see cref="Fallback"/> instead.
/// </remarks>
internal static class ClientVersion
{
/// <summary>The version reported when the build carries no usable one.</summary>
/// <remarks>A property rather than a field, so <see cref="Current"/> can read it whatever the field order.</remarks>
internal static (int Major, int Minor, int Patch) Fallback => (1, 0, 0);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Major: Document the reported client version and fallback

The root AGENTS.md requires public behavior changes to be documented in docs/tcp.mdx in the same PR, but that page is unchanged. Users inspecting system.query_log or system.processes now see the driver version, and a build with a missing, invalid, or zero version reports 1.0.0; the changelog does not explain that fallback. Add a short note under Logging and diagnostics describing the version fields, their package-version source, and the fallback so users can interpret these values correctly.

A reply here is read on the next review: an explanation that holds up drops the finding.

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.

Added in 04bc611: a new section "Client name and version on the server" under "Logging and diagnostics" in docs/tcp.mdx. It lists the system.query_log / system.processes columns, says the version is the ClickHouse.Driver package version, and gives the 1.0.0 fallback with its reason.


/// <summary>The version of this build, read once from its informational version.</summary>
internal static (int Major, int Minor, int Patch) Current { get; } = Parse(
typeof(ClientVersion).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion);

/// <summary>Reads major, minor and patch from an informational version such as <c>1.5.0+3f2a1c</c>.</summary>
/// <param name="informationalVersion">The informational version, or null.</param>
/// <returns>The version, or <see cref="Fallback"/> when there is no usable one.</returns>
internal static (int Major, int Minor, int Patch) Parse(string informationalVersion)
{
if (string.IsNullOrEmpty(informationalVersion))
{
return Fallback;
}

// The build metadata after '+' and a pre-release label after '-' are not part of the number.
int end = informationalVersion.AsSpan().IndexOfAny('+', '-');
ReadOnlySpan<char> number = end < 0 ? informationalVersion : informationalVersion.AsSpan(0, end);
if (!Version.TryParse(number, out Version parsed))
{
return Fallback;
}

int patch = Math.Max(parsed.Build, 0);
return parsed.Major == 0 && parsed.Minor == 0 && patch == 0
? Fallback
: (parsed.Major, parsed.Minor, patch);
}
}
1 change: 1 addition & 0 deletions changelog.d/725-tcp-client-version.fixes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Native TCP client: fixed distributed queries (`clusterAllReplicas`, `remote`, a `Distributed` table) failing on ClickHouse 26.8 and later with "Sending a distributed query with unknown (zero) client version". The client reported version 0.0.0; it now reports the driver version, which `system.query_log` and `system.processes` also show.
24 changes: 24 additions & 0 deletions docs/tcp.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1514,6 +1514,30 @@ The log block is borrowed and is released when the callback returns. Process it
copy out values that must be retained. Keep callbacks fast and do not throw; a callback exception
terminates the operation and its connection.

### Client name and version on the server {#logging-client-identity}

The client sends its name and version in the handshake and with every query. ClickHouse shows them
in `system.query_log` and `system.processes`:

| Column | Value |
|---|---|
| `client_name` | `clickhouse-cs-tcp` |
| `client_version_major`, `client_version_minor`, `client_version_patch` | The version of the `ClickHouse.Driver` package, for example `1.4.0` |

Use these columns to find the queries that this client sent:

```sql
SELECT event_time, client_version_major, client_version_minor, client_version_patch, query
FROM system.query_log
WHERE client_name = 'clickhouse-cs-tcp' AND type = 'QueryFinish'
ORDER BY event_time DESC
LIMIT 10
```

When the build has no usable version (the version is missing, cannot be read, or is 0.0.0), the
client reports `1.0.0`. ClickHouse 26.8 and later do not send a distributed query (`remote`,
`clusterAllReplicas`, a `Distributed` table) to other servers when the client version is 0.0.0.

## OpenTelemetry {#opentelemetry}

The TCP client emits distributed-tracing spans through .NET's `System.Diagnostics.Activity` API.
Expand Down
Loading