Readers allocate the declared String length or Array/Map count before the data arrives: a 17-byte response allocates 2 GiB
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
- Domain
- backend, databases, performance
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
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): aStringvalue read asbyte[](ReadStringsAsByteArrays=true) allocates the declared length, up to about 2 GiB. A 17-byte response allocates 2,147,839,760 bytes, then throwsEndOfStreamException. AnArrayorMapcount does the same with default settings: anArray(Int64)count of 2^28 allocates 2 GiB from a 21-byte response. With a GC heap limit of 1 GiB, these reads throwOutOfMemoryException; a declared length of 2^31 throwsOverflowException. - TCP client (
ClickHouseTcpClient): each protocol string (ServerHello, Exception, table, column and type names) and eachStringcolumn 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
- Put the program below in
leadrepro/app.csof a clickhouse-cs checkout. It starts a local HTTP or TCP listener that sends one short response; it needs no ClickHouse server. dotnet run leadrepro/app.cs -- bytes 2147483591: oneStringrow with a length prefix of 2^31 − 57 (Array.MaxLength) and 2 bytes of data.- The same with
array 268435456(anArray(Int64)count, no data) andtcp 1073741824(a ServerHello name length of 2^30). - Contrast:
string 2147483591(the same bytes, read asstring) andtcp 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.ReadByteArraypasses the unchecked length (ClickHouse.Driver/Types/StringType.cs:28) toExtendedBinaryReader.ReadBytes, which doesnew byte[count]before it reads (ClickHouse.Driver/Formats/ExtendedBinaryReader.cs:27).ArrayType.ReadandMapType.Readsize the result from the element count in the same way (ArrayType.cs:54,:64;MapType.cs:139,:149). - TCP:
ReadStringAsyncrents andReadStringBytesAsyncallocates the declared length before the read (ClickHouse.Driver.Tcp/Protocol/ClickHouseBinaryReader.cs:150,:174), andStringColumnCodec.ReadColumnAsyncgrows 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:
mainc58178e - .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
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from ClickHouse/clickhouse-cs
-
bug documentation queries
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
ClickHouse/clickhouse-cs#815 ·
Maintainers usually reply within 1 day
-
bug data-types native-format
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
ClickHouse/clickhouse-cs#813 ·
Maintainers usually reply within 1 day
-
bug data-types documentation
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
ClickHouse/clickhouse-cs#811 ·
Maintainers usually reply within 1 day
-
bug data-types
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
ClickHouse/clickhouse-cs#809 ·
Maintainers usually reply within 1 day
-
bug data-types
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
ClickHouse/clickhouse-cs#806 · 1 comment ·
Maintainers usually reply within 1 day
All issues in ClickHouse/clickhouse-cs
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
-
XML grammar: only the closing --> of a comment gets the scope comment.block.xmlPossibly taken @alexeyfala claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
danipen/TextMateSharp#145 · 2 comments ·
-
good first issue help wanted
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
Klyroo/klyroo-dashboard#12 ·
Maintainers usually reply within 1 day
-
CONTRIBUTING rules Node out in step 0, then tells client-side contributors to run node --test, which is what CI gates onPossibly taken @yadavraj2001 claimed this today. Opendocumentation good first issue
Difficulty 1/5 1-3 hours Newbie friendliness 82/100
juandresrodca/AdminForge#73 · 1 comment ·
Maintainers usually reply within 1 day
-
[辞書] VIVANTOpen要トリアージ 辞書
Difficulty 1/5 Under an hour Newbie friendliness 70/100
Maintainers usually reply within 1 day