diff --git a/ClickHouse.Driver.Tcp.Tests/Integration/ClientVersionIntegrationTests.cs b/ClickHouse.Driver.Tcp.Tests/Integration/ClientVersionIntegrationTests.cs new file mode 100644 index 000000000..046e84aab --- /dev/null +++ b/ClickHouse.Driver.Tcp.Tests/Integration/ClientVersionIntegrationTests.cs @@ -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; + +/// +/// 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. +/// +[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}")); + } +} diff --git a/ClickHouse.Driver.Tcp.Tests/Protocol/ClientVersionTests.cs b/ClickHouse.Driver.Tcp.Tests/Protocol/ClientVersionTests.cs new file mode 100644 index 000000000..fcbbdcef3 --- /dev/null +++ b/ClickHouse.Driver.Tcp.Tests/Protocol/ClientVersionTests.cs @@ -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; + } + } +} diff --git a/ClickHouse.Driver.Tcp/Protocol/ClientHandshakeParameters.cs b/ClickHouse.Driver.Tcp/Protocol/ClientHandshakeParameters.cs index e1e36decc..12677ae16 100644 --- a/ClickHouse.Driver.Tcp/Protocol/ClientHandshakeParameters.cs +++ b/ClickHouse.Driver.Tcp/Protocol/ClientHandshakeParameters.cs @@ -16,11 +16,17 @@ internal sealed class ClientHandshakeParameters /// affect negotiation. public string ClientName => DefaultClientName; - /// Informational client major version (ClientHello field 2). - public int VersionMajor { get; init; } + /// Client major version (ClientHello field 2). Defaults to this driver's version. + public int VersionMajor { get; init; } = ClientVersion.Current.Major; - /// Informational client minor version (ClientHello field 3). - public int VersionMinor { get; init; } + /// Client minor version (ClientHello field 3). Defaults to this driver's version. + public int VersionMinor { get; init; } = ClientVersion.Current.Minor; + + /// + /// Client patch version. ClientHello has no field for it; every query's ClientInfo carries it. Defaults to this + /// driver's version. + /// + public int VersionPatch { get; init; } = ClientVersion.Current.Patch; /// Default database (ClientHello field 5). public string Database { get; init; } = "default"; @@ -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 = , QuotaKey = }}"); + $"{nameof(ClientHandshakeParameters)} {{ ClientName = {ClientName}, Version = {VersionMajor}.{VersionMinor}.{VersionPatch}, Database = {Database}, Username = {Username}, Password = , QuotaKey = }}"); } diff --git a/ClickHouse.Driver.Tcp/Protocol/ClientInfo.cs b/ClickHouse.Driver.Tcp/Protocol/ClientInfo.cs index a2cb29209..657784101 100644 --- a/ClickHouse.Driver.Tcp/Protocol/ClientInfo.cs +++ b/ClickHouse.Driver.Tcp/Protocol/ClientInfo.cs @@ -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)) diff --git a/ClickHouse.Driver.Tcp/Protocol/ClientMetadata.cs b/ClickHouse.Driver.Tcp/Protocol/ClientMetadata.cs index 2e63be9b1..56fa078b8 100644 --- a/ClickHouse.Driver.Tcp/Protocol/ClientMetadata.cs +++ b/ClickHouse.Driver.Tcp/Protocol/ClientMetadata.cs @@ -12,12 +12,15 @@ internal sealed class ClientMetadata /// Informational client identifier, pinned to the same value the handshake reports. public string ClientName => ClientHandshakeParameters.DefaultClientName; - /// Informational client major version. + /// Client major version, as the handshake reported it. public int VersionMajor { get; init; } - /// Informational client minor version. + /// Client minor version, as the handshake reported it. public int VersionMinor { get; init; } + /// Client patch version. + public int VersionPatch { get; init; } + /// Username, echoed as the initiating user in ClientInfo. required public string Username { get; init; } @@ -31,6 +34,7 @@ internal sealed class ClientMetadata { VersionMajor = parameters.VersionMajor, VersionMinor = parameters.VersionMinor, + VersionPatch = parameters.VersionPatch, Username = parameters.Username, QuotaKey = parameters.QuotaKey, }; diff --git a/ClickHouse.Driver.Tcp/Protocol/ClientVersion.cs b/ClickHouse.Driver.Tcp/Protocol/ClientVersion.cs new file mode 100644 index 000000000..acd794902 --- /dev/null +++ b/ClickHouse.Driver.Tcp/Protocol/ClientVersion.cs @@ -0,0 +1,48 @@ +using System; +using System.Reflection; + +namespace ClickHouse.Driver.Tcp.Protocol; + +/// +/// 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. +/// +/// +/// A server refuses to send a distributed query (clusterAllReplicas, remote, a Distributed +/// 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 instead. +/// +internal static class ClientVersion +{ + /// The version reported when the build carries no usable one. + /// A property rather than a field, so can read it whatever the field order. + internal static (int Major, int Minor, int Patch) Fallback => (1, 0, 0); + + /// The version of this build, read once from its informational version. + internal static (int Major, int Minor, int Patch) Current { get; } = Parse( + typeof(ClientVersion).Assembly.GetCustomAttribute()?.InformationalVersion); + + /// Reads major, minor and patch from an informational version such as 1.5.0+3f2a1c. + /// The informational version, or null. + /// The version, or when there is no usable one. + 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 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); + } +} diff --git a/changelog.d/725-tcp-client-version.fixes.md b/changelog.d/725-tcp-client-version.fixes.md new file mode 100644 index 000000000..88284c415 --- /dev/null +++ b/changelog.d/725-tcp-client-version.fixes.md @@ -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. diff --git a/docs/tcp.mdx b/docs/tcp.mdx index 1240c97a4..2dfd73163 100644 --- a/docs/tcp.mdx +++ b/docs/tcp.mdx @@ -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.