UseSession: after a cancelled query or an early reader Dispose(), the next query of the session fails with SESSION_IS_LOCKED until the server query ends

Open
#784 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
38/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
csharp, postgresql
Domain
backend, databases

Research direction

Start in ClickHouse.Driver/ClickHouseClient.cs around line 1404 and ClickHouse.Driver/ADO/Readers/ClickHouseDataReader.cs around line 747, where cancellation and early disposal are handled. Compare those paths with the reproduced cases and the HTTP session behavior described in the issue. The issue leaves the fix choice to maintainers: stop the server query on cancellation and early disposal for session requests, or document the limitation in docs/http.mdx.

Written by the indexing model from the issue text.

Description

bug documentation queries
Describe the bug

With UseSession=true, the next query of the session fails with SESSION_IS_LOCKED (code 373) after the caller stops a query before its end. The error continues until the stopped query ends on the server: 5.9 s for a 6 s aggregation that was cancelled after 300 ms, and 1.3 s after Dispose() of a reader of a streaming result. The same defect was reported for clickhouse-js in https://github.com/ClickHouse/clickhouse-js/issues/1250.

These ways to stop a query show it (cases 1–4 below):

  • a CancellationToken of ClickHouseClient.ExecuteScalarAsync and ExecuteReaderAsync;
  • ClickHouseCommand.Cancel() (ADO.NET);
  • the client Timeout;
  • Dispose() of a ClickHouseDataReader before the end of a result that the server still sends, also inside ExecuteScalarAsync.

The setting cancel_http_readonly_queries_on_client_close=1 on the stopped query has no effect. Workaround: after the stop, send KILL QUERY WHERE query_id = '<id>' SYNC from a client without session; the next query of the session is then OK at once (case 5).

Steps to reproduce
  1. Run the program below with dotnet run app.cs (.NET 10 SDK or later) against a local server, or set CLICKHOUSE_CONNECTION.
  2. Each case uses a new session, stops a query, and then sends SELECT 1 in the same session.
Expected behaviour

After the caller cancels a query or disposes its reader, the next query of the session runs. The server rejects a query only while another query of the session runs (HTTP interface: "Only one query at a time can be executed within a single session"). docs/http.mdx (Session management) does not say that a stopped query keeps the session locked.

Code example
Reproduction program (C#, 53 lines)
#:package [email protected]
using ClickHouse.Driver;
using ClickHouse.Driver.ADO;

var cs = Environment.GetEnvironmentVariable("CLICKHOUSE_CONNECTION") ?? "Host=localhost;Port=8123";
// About 6 s; the server sends nothing before the query ends.
const string Slow = "SELECT sum(sipHash64(number)) FROM numbers(600000000) SETTINGS max_threads = 1";
// Streams for about 50 s.
const string Streaming = "SELECT number, randomPrintableASCII(1000) FROM numbers(100000) WHERE sleepEachRow(0.0005) = 0 SETTINGS max_block_size = 100";

ClickHouseClient Session(string extra = "") => new($"{cs};UseSession=true;SessionId={Guid.NewGuid()}{extra}");
async Task Next(string label, ClickHouseClient c) => await NextOf(label, () => c.ExecuteScalarAsync("SELECT 1"));
async Task NextOf(string label, Func<Task> select1)
{
    try { await select1(); Console.WriteLine($"{label}: next query OK"); }
    catch (ClickHouseServerException e) { Console.WriteLine($"{label}: next query failed: {e.ErrorCode} {e.Message.Split('\n')[0]}"); }
}

using (var c = Session())
{
    using var cts = new CancellationTokenSource(300);
    try { await c.ExecuteScalarAsync(Slow, cancellationToken: cts.Token); } catch (OperationCanceledException) { }
    await Next("1. CancellationToken", c);
}
using (var c = Session())
{
    await c.ExecuteScalarAsync(Streaming); // reads the first value, then disposes its reader
    await Next("2. ExecuteScalarAsync of a streaming result", c);
}
using (var conn = new ClickHouseConnection($"{cs};UseSession=true;SessionId={Guid.NewGuid()}"))
{
    using var cmd = conn.CreateCommand();
    cmd.CommandText = Slow;
    _ = Task.Delay(300).ContinueWith(_ => cmd.Cancel());
    try { await cmd.ExecuteScalarAsync(); } catch (OperationCanceledException) { }
    using var next = conn.CreateCommand();
    next.CommandText = "SELECT 1";
    await NextOf("3. ClickHouseCommand.Cancel()", () => next.ExecuteScalarAsync());
}
using (var c = Session(";Timeout=1"))
{
    try { await c.ExecuteScalarAsync(Slow); } catch (OperationCanceledException) { }
    await Next("4. Timeout=1", c);
}
using (var c = Session())
using (var admin = new ClickHouseClient(cs))
{
    var queryId = Guid.NewGuid().ToString();
    using var cts = new CancellationTokenSource(300);
    try { await c.ExecuteScalarAsync(Slow, options: new QueryOptions { QueryId = queryId }, cancellationToken: cts.Token); } catch (OperationCanceledException) { }
    await admin.ExecuteNonQueryAsync($"KILL QUERY WHERE query_id = '{queryId}' SYNC");
    await Next("5. CancellationToken, then KILL QUERY ... SYNC without session", c);
}
Error log
1. CancellationToken: next query failed: 373 Code: 373. DB::Exception: Session 61e5213f-64f8-4096-960b-8453377aec3a is locked by a concurrent client. (SESSION_IS_LOCKED)
2. ExecuteScalarAsync of a streaming result: next query failed: 373 Code: 373. DB::Exception: Session e9c36838-8025-44a7-b24e-db6a09f69ed4 is locked by a concurrent client. (SESSION_IS_LOCKED)
3. ClickHouseCommand.Cancel(): next query failed: 373 Code: 373. DB::Exception: Session c3678e28-1110-40b1-9409-03c417fee1fb is locked by a concurrent client. (SESSION_IS_LOCKED)
4. Timeout=1: next query failed: 373 Code: 373. DB::Exception: Session 49500a99-da55-46f0-8760-2f190b14fc58 is locked by a concurrent client. (SESSION_IS_LOCKED)
5. CancellationToken, then KILL QUERY ... SYNC without session: next query OK
Root cause

A cancellation goes only to HttpClient.SendAsync (ClickHouse.Driver/ClickHouseClient.cs:1404), and ClickHouseDataReader.Dispose only disposes the HTTP response (ClickHouse.Driver/ADO/Readers/ClickHouseDataReader.cs:747). So the server keeps the session locked until the query ends, or until a write to the closed connection fails. The setting cannot stop the query: the server applies it only when readonly > 0 (src/Server/HTTPHandler.cpp:1238 in ClickHouse), and the client sends each query as POST (ClickHouse.Driver/ClickHouseClient.cs:382), which does not set readonly.

The fix needs a maintainer decision: stop the server query on a cancellation and on an early Dispose() when the request has a session (for example, KILL QUERY by query ID without the session), or document the limit in docs/http.mdx. Polyglot AI can open a fix PR if a maintainer assigns this issue to @polyglotAI-bot.

Configuration
Environment
  • Client version: 1.5.0 (NuGet), and main at 63dc6d3b
  • Language version: C#, default of the .NET SDK 11.0.100
  • .NET version: .NET 11.0.0 (the program); .NET 10.0.15 for the same cases against main
  • OS: Ubuntu 26.04 (Docker)
ClickHouse server
  • ClickHouse Server version: 26.11.4.11
  • ClickHouse Server non-default settings, if any: none

Classification: impact: none · area: Queries (sessions)


Found by automated analysis (Polyglot AI) while checking clickhouse-js#1250 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.