Readers allocate the declared String length or Array/Map count before the data arrives: a 17-byte response allocates 2 GiB

Open
#808 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
52/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
clickhouse, csharp

Research direction

Start with the named reader paths: ClickHouse.Driver/Types/StringType.cs, ExtendedBinaryReader.cs, ArrayType.cs, and MapType.cs for HTTP, then ClickHouse.Driver.Tcp/Protocol/ClickHouseBinaryReader.cs and StringColumnCodec.cs for TCP. Run the reproduction commands in the issue and inspect the relevant reader tests. Done means malformed short responses fail without allocating the declared size, while large valid values remain readable in both clients.

Written by the indexing model from the issue text.

Description

bug data-types native-format performance
Describe the bug

When a response declares a length or element count larger than the data that follows, the client allocates the declared size before it reads, and only then fails:

  • HTTP client (ClickHouseClient, ClickHouseConnection): a String value read as byte[] (ReadStringsAsByteArrays=true) allocates the declared length, up to about 2 GiB. A 17-byte response allocates 2,147,839,760 bytes, then throws EndOfStreamException. An Array or Map count does the same with default settings: an Array(Int64) count of 2^28 allocates 2 GiB from a 21-byte response. With a GC heap limit of 1 GiB, these reads throw OutOfMemoryException; a declared length of 2^31 throws OverflowException.
  • TCP client (ClickHouseTcpClient): each protocol string (ServerHello, Exception, table, column and type names) and each String column value allocates the declared length up to the 1 GiB limit. A 16-byte ServerHello allocates 1,073,924,808 bytes. A length above 1 GiB is rejected with no large allocation.

A String read as string (the default) is not affected: it reads in chunks.

The same defect was reported for ch-go in https://github.com/ClickHouse/ch-go/issues/1269. Only a corrupt response, or a hostile server or network, sends such a length.

Steps to reproduce
  1. Put the program below in leadrepro/app.cs of a clickhouse-cs checkout. It starts a local HTTP or TCP listener that sends one short response; it needs no ClickHouse server.
  2. dotnet run leadrepro/app.cs -- bytes 2147483591: one String row with a length prefix of 2^31 − 57 (Array.MaxLength) and 2 bytes of data.
  3. The same with array 268435456 (an Array(Int64) count, no data) and tcp 1073741824 (a ServerHello name length of 2^30).
  4. Contrast: string 2147483591 (the same bytes, read as string) and tcp 1073741825 (above the TCP limit).
Expected behaviour

An error, with memory allocated only for the bytes that arrive, as the default string read does. The server does this for the same RowBinary bytes: INSERT INTO t FORMAT RowBinary with the 7-byte row 80 80 80 80 04 61 62 (length 2^30) fails with Code: 33. DB::Exception: Cannot read all data. Bytes read: 2. Bytes expected: 1073741824 with a memory_usage of 1,081,463 bytes (system.query_log). For the counts of Dynamic and JSON, the Native format specification says that a decoder "must treat it as untrusted and must not use it to size an allocation directly".

Code example
Reproduction program (C#, 44 lines)
#:project ../ClickHouse.Driver/ClickHouse.Driver.csproj
#:project ../ClickHouse.Driver.Tcp/ClickHouse.Driver.Tcp.csproj
#:property NoWarn=CHTCP0001
using System.Net;
using System.Net.Sockets;
using System.Text;
using ClickHouse.Driver;
using ClickHouse.Driver.ADO;
using ClickHouse.Driver.Tcp;

static byte[] VarUInt(ulong v) { var b = new List<byte>(); for (; v >= 0x80; v >>= 7) b.Add((byte)(v | 0x80)); b.Add((byte)v); return b.ToArray(); }

ulong n = ulong.Parse(args[1]);
int port = 18123;
long before = GC.GetTotalAllocatedBytes(true);
try
{
    if (args[0] == "tcp") // a server that answers the client hello with a short Hello packet
    {
        byte[] reply = [0x00, .. VarUInt(n), .. "ClickHouse"u8];
        var ln = new TcpListener(IPAddress.Loopback, port); ln.Start();
        _ = Task.Run(async () => { using var c = await ln.AcceptTcpClientAsync(); await c.GetStream().ReadAsync(new byte[4096]); await c.GetStream().WriteAsync(reply); c.Client.Shutdown(SocketShutdown.Send); await Task.Delay(1000); });
        Console.WriteLine($"server reply: {Convert.ToHexString(reply)}");
        await using var client = new ClickHouseTcpClient($"Host=127.0.0.1;Port={port}");
        await client.PingAsync();
    }
    else // an HTTP response: RowBinaryWithNamesAndTypes header, then one row that is not backed by data
    {
        string type = args[0] == "array" ? "Array(Int64)" : "String";
        byte[] body = [1, 1, (byte)'s', (byte)type.Length, .. Encoding.ASCII.GetBytes(type), .. VarUInt(n), .. (type == "String" ? "ab"u8.ToArray() : [])];
        var http = new HttpListener(); http.Prefixes.Add($"http://127.0.0.1:{port}/"); http.Start();
        _ = Task.Run(async () => { while (true) { var ctx = await http.GetContextAsync(); ctx.Response.ContentLength64 = body.Length; await ctx.Response.OutputStream.WriteAsync(body); ctx.Response.Close(); } });
        Console.WriteLine($"response body: {Convert.ToHexString(body)} ({body.Length} bytes)");
        using var client = new ClickHouseClient($"Host=127.0.0.1;Port={port};ReadStringsAsByteArrays={args[0] == "bytes"}");
        using var reader = await client.ExecuteReaderAsync("SELECT s");
        reader.Read();
    }
    Console.WriteLine("no error");
}
catch (Exception e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}
Console.WriteLine($"allocated {GC.GetTotalAllocatedBytes(true) - before} bytes");
Error log
$ dotnet run leadrepro/app.cs -- bytes 2147483591
response body: 01017306537472696E67C7FFFFFF076162 (17 bytes)
EndOfStreamException: Attempted to read past the end of the stream.
allocated 2147839760 bytes
$ dotnet run leadrepro/app.cs -- array 268435456
response body: 0101730C417272617928496E743634298080808001 (21 bytes)
EndOfStreamException: Unable to read beyond the end of the stream.
allocated 2147844624 bytes
$ dotnet run leadrepro/app.cs -- tcp 1073741824
server reply: 008080808004436C69636B486F757365
ClickHouseTcpConnectionException: The ClickHouse server closed the connection before the response was complete.
allocated 1073924808 bytes
$ dotnet run leadrepro/app.cs -- string 2147483591
response body: 01017306537472696E67C7FFFFFF076162 (17 bytes)
EndOfStreamException: Unable to read beyond the end of the stream.
allocated 357704 bytes
$ dotnet run leadrepro/app.cs -- tcp 1073741825
server reply: 008180808004436C69636B486F757365
ClickHouseTcpProtocolException: String length 1073741825 exceeds the supported maximum of 1073741824 bytes (corrupt stream).
allocated 181176 bytes
Root cause
  • HTTP: StringType.ReadByteArray passes the unchecked length (ClickHouse.Driver/Types/StringType.cs:28) to ExtendedBinaryReader.ReadBytes, which does new byte[count] before it reads (ClickHouse.Driver/Formats/ExtendedBinaryReader.cs:27). ArrayType.Read and MapType.Read size the result from the element count in the same way (ArrayType.cs:54, :64; MapType.cs:139, :149).
  • TCP: ReadStringAsync rents and ReadStringBytesAsync allocates the declared length before the read (ClickHouse.Driver.Tcp/Protocol/ClickHouseBinaryReader.cs:150, :174), and StringColumnCodec.ReadColumnAsync grows its blob to the declared end before the read (ClickHouse.Driver.Tcp/Types/Codecs/StringColumnCodec.cs:125). MaxStringLength = 1 << 30 (ClickHouseBinaryReader.cs:22) bounds the allocation, but does not prevent it.

The fix is in the readers of both clients, and must keep large valid values readable.

Polyglot AI can open a fix PR if a maintainer assigns this issue to @polyglotAI-bot.

Configuration
Environment
  • Client version: main c58178e
  • .NET version: SDK 11.0.100 (the reproduction); the test suites on net10.0 show the same allocations
  • OS: Linux x64
ClickHouse server
  • ClickHouse Server version: 26.11.7.10 (only for the reference result)

Classification: impact: Performance · area: Data types & formats (String length and Array/Map count prefixes) · native: format, protocol


Found by automated analysis (Polyglot AI) while checking ch-go#1269 against the other client repos. Verified against a live server.

Dominant language
C#
Stars
102
Forks
31
Avg merge
2d 13h
Merged PRs (30d)
40

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from ClickHouse/clickhouse-cs

All issues in ClickHouse/clickhouse-cs

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.