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

Aperta
#784 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
38/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
csharp, postgresql
Ambito
backend, databases

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.

Lingua principale
C#
Stelle
102
Fork
31
Merge medio
2g 13h
PR unite (30g)
40

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di ClickHouse/clickhouse-cs

Tutte le issue di ClickHouse/clickhouse-cs

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.