Skip to content

Mark a query as cancelled in the process list when its TCP client cancels it - #127149

Merged
Algunenano merged 14 commits into
ClickHouse:masterfrom
groeneai:fix-04117-no-parallel-replicas
Nov 3, 2026
Merged

Algunenano merged 14 commits into
ClickHouse:masterfrom
groeneai:fix-04117-no-parallel-replicas

Conversation

@groeneai

@groeneai groeneai commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126555
Related: #127935

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

When a client cancels a query over the native protocol or disconnects, the query is now also marked as cancelled in the process list, as KILL QUERY does. Work that checks only that, such as sleep, now stops promptly, including in the remote part of a distributed, *Cluster table function or parallel replicas query whose initiator was cancelled, and in an INSERT whose client cancels it or disconnects while still sending data.

Description

04117_detach_database_kill_query fails Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) with Some queries hung since #126555 moved it to the parallel pool; the hung row is its parallel-replicas follower, is_cancelled: 0. #127935 restored its no-parallel tag meanwhile; this PR removes it.

Root cause: when the client cancels a query over TCP (a Cancel packet or a dropped connection), TCPHandler cancels the pipeline executor and waits for its threads, but never marks the query as cancelled in the process list. sleep checks only the process list entry (QueryStatus::checkTimeLimit), so a cancelled query sleeps out its whole block, here 300 s.

Change: before the executor is cancelled, TCPHandler::killQueryIfStoppedByClient cancels the process list entry with the current exception, keeping the client's error, when the client cancelled or a write to it failed. It is called in processOrdinaryQuery, in the interactive cancel callback (covering pipelines inside executeQuery, like CREATE TABLE ... AS SELECT), in the input() reader and the cluster function and parallel replicas read task callbacks, and in processInsertQuery before the pushing executor joins. A dropped connection during an INSERT now sets stop_query. AsyncInsertQueueTransform logs a killed query's exception from its fallback pipeline at debug level. Two OpenTelemetry tests drop a redundant second KILL QUERY.

Validation: the new 05452_cancel_by_client_stops_sleep (the remote part after KILL QUERY, also of a urlCluster query whose read task request receives the Cancel; INSERT SELECT, a streamed INSERT, CREATE TABLE ... AS SELECT and INSERT SELECT FROM input() cancelled by clickhouse-client; a streamed INSERT and a SELECT whose client is killed) fails without the fix (every case still running after 60 s) and passes with it. Locally under ParallelReplicas the 04117 follower is gone within 11 s in 20/20 runs (before: 0/20). 04117, 04869, 05025 and 05452 pass repeated runs with --hung-check, and 02357_query_cancellation_race passes with async_insert = 1.


Workflow [PR]
Sync PR [sync-upstream/pr/127149]

Version info

  • Merged into: 26.11.1.1264-master (included in 26.11 and later)

Since ClickHouse#126555 moved the test into the parallel pool, the ParallelReplicas
lane reports `Some queries hung` on master (2 of 21 runs). The table has
one mark; when a remote replica reads it, the whole 300 s `sleepEachRow`
block runs in a secondary query with its own query_id. The test's
`KILL QUERY WHERE query_id = ...` kills only the initial query, and
`sleep` stops only when its own query is killed, so the secondary
outlives the test and the end-of-run hung check catches it.

Parallel replicas add nothing to what the test checks (KILL QUERY
interrupting the DETACH DATABASE wait), so tag it `no-parallel-replicas`:
the lane skips it and other lanes run it with enable_parallel_replicas = 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding).

# Sev Finding Verdict Evidence / action
1 ⚠️ Drop the tag and kill the remote secondary by initial_query_id in both cleanup sites, keeping the test in the ParallelReplicas lane DISAGREE The test's only table read is the sleepEachRow holder (result discarded); what it checks is that KILL QUERY interrupts the DETACH DATABASE wait, which never goes through parallel replicas. The lane would only re-run the same check, which every other lane still runs. Same choice as the parallel-replicas owner asked for on #125892.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261021-095500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Local ParallelReplicas setup (master binary, lane settings, parallel_replicas_local_plan = 0): a secondary of the test's sleepEachRow query is still running after 20/20 runs; one run with --hung-check prints the same Found hung queries report as CI.
b Root cause explained? The table's only mark can go to a remote replica, so the 300 s sleep block runs in a secondary query with its own query_id. KILL QUERY WHERE query_id = ... kills only the initial query, and sleep stops only when its own query is killed (QueryStatus::checkTimeLimit), so the secondary outlives the test and the hung check catches it.
c Fix matches root cause? Yes. The test assumes the KILL stops the table holder, which holds only without parallel replicas. The tag skips the test in that lane and runs it with enable_parallel_replicas = 0 elsewhere.
d Test intent preserved / new tests added? Yes. The DETACH DATABASE cancellation check runs unchanged in every other lane; .reference unchanged. Test-only fix.
e Both directions demonstrated? Yes, same server and options: unmodified 20/20 runs leave a sleeping secondary (6/20 at local_plan = 1); tagged 0/20 at both values. --hung-check: unmodified fails, tagged is skipped by --no-parallel-replicas and the check is clean.
f Fix is general across code paths? Similar sleepEachRow + KILL QUERY tests were checked: their possible leftovers end within 60 s, inside the 90 s hung-check window, and none has a Some queries hung record. Not changed.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (test tag). Both parallel_replicas_local_plan values exercised.
h Backward compatible? (maintainer-approved exception only) N/A (test-only change).
i Invariants and contracts preserved? No query started by the test outlives it: 0 leftovers in 40 runs with lane settings, 50/50 with a clean hung check on a plain server.

Session id: cron:clickhouse-impl-slot-4:20261021-093100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai, could you review this and add the can be tested label so CI runs? It adds no-parallel-replicas to 04117_detach_database_kill_query: under parallel replicas its sleeping read can run in a remote secondary query that KILL QUERY by query_id does not stop, so the secondary outlives the test and trips the hung check on master.

@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [11687c0]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

The PR propagates native TCP client cancellation and connection failures to the query's process-list entry before joining pipeline workers, allowing operations such as sleepEachRow to stop promptly while preserving the original exception. No unresolved findings remain in head 11687c05c85a22d8d3e7e9a99e3a52a3f4037d1a.

Final Verdict

Status: ✅ Approve

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9ef712c

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 02317_distinct_in_order_optimization flaky, not from this PR (it only tags 04117 with no-parallel-replicas): under parallel replicas the unordered select distinct a from sorting_key_empty_tuple returns its two rows in either order (here 0, 1 instead of 1, 0); 0/47 same-settings reruns failed, and it failed the same way on master and on 20 other PRs since 2026-10-20 #127002 (mine, open)
Mergeable Check, PR praktika rollups of the row above #127002 (the owner of the row above)

The two Config Workflow / Pre Hooks failures on this head are the earlier attempts stopped at the can be tested label; the current attempt passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261021-190007

@Algunenano

Copy link
Copy Markdown
Member

@groeneai I feel we should fix the code, not the test. Also, why did this start failing recently all of a sudden? The test isn’t new

groeneai and others added 2 commits October 27, 2026 13:49
ClickHouse#127935 restored the `no-parallel` tag until this PR lands. With this PR the
parallel replicas follower of the killed `SELECT` stops sleeping, so the test
can run in the parallel pool again (requested in ClickHouse#127935).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Oct 27, 2026
Since it runs in the parallel pool, the remote part of its killed `SELECT`
keeps sleeping and the hung check reports `Some queries hung`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=127038&sha=9f841c9ae9a312abac66b6136e939dc248c3a7a3&name_0=PR
PR: ClickHouse#127038
Related: ClickHouse#127149

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Server/TCPHandler.cpp Resolved
groeneai and others added 2 commits October 27, 2026 15:24
A client that dies while it receives a result is often first noticed on a
write (`sendData`, `sendInteractiveUpdates`, `out->sync`), not by the socket
poll, and a failed write leaves `stop_query` unset. `processOrdinaryQuery`
then joined the executor with the process list entry still not cancelled,
so a `sleepEachRow` stream kept running (reported by clickhouse-gh on
ClickHouse#127149, reproduced 3/3: still in `system.processes` 12 s after SIGKILL,
`is_cancelled = 0`).

A failed write cancels `out` (`WriteBuffer::next`), so
`killQueryIfStoppedByClient` now also acts when `out` is canceled. Worker
thread callers reach it only with `stop_query` already set, so `out` is read
only on the connection thread or under `callback_mutex`. The query keeps the
network exception (`NETWORK_ERROR` in `query_log`).

05452 gains `select, client killed`: a UNION ALL whose fast stream keeps
the server writing while the other sleeps, the client SIGKILLed, and a large
`interactive_delay` so the write is what notices it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The CI test profile (`tests/config/users.d/limits.yaml`) sets
`max_rows_to_read = 20000000`, so the `select, client killed` case's
`numbers(1000000000)` stream failed at once with TOO_MANY_ROWS. The query
never appeared in `system.processes`, `wait_for_query` spent its 60 s, and
the test ran into the 60 s per-test budget of the Fast test.

The case needs a stream that is still sending when the client is killed,
so set `max_rows_to_read = 0` for this query only.

Measured with `limits.yaml` installed on the local server: the unchanged
test reproduces the CI output (`query did not start: ..._select_killed`,
76 s); the fixed test passes on the fix binary 19/19 (random settings, no
random settings, `limits_fast.yaml`) plus 20/20 under load, and still
fails on the binary without the write-side fix, only on
`select, client killed: still running` (3/3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 11687c0

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff infra, not from this PR: every readiness probe of the CI logs cluster failed, so the job ended with LogClusterNotReady: the endpoint never became ready in has_pr_data before comparing anything. 306 of 310 runs since 2026-10-26 22:00 UTC are red, on 242 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)

The Fast test timeout of 05452_cancel_by_client_stops_sleep on the previous head f564bb14b476 was caused by this PR (the new case read more rows than the CI profile's max_rows_to_read allows) and is fixed by 11687c05c85a; the test passes on this head. CIDB has no other FAIL or ERROR row on it.

Session id: cron:our-pr-ci-monitor:20261027-223005

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Most code changes are new blocks to catch exceptions, so it's quite simple even though it looks large

@Algunenano
Algunenano added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit d47efca Nov 3, 2026
177 of 179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
@Algunenano

Copy link
Copy Markdown
Member

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm investigating 05452_cancel_by_client_stops_sleep (median 17.8 s in Fast test and 17.6 s in Fast test (arm_darwin) over the last 3 days); I'll follow up here with a PR that makes it faster or moves it out of Fast test.

PedroTadim pushed a commit to hsusul/ClickHouse that referenced this pull request Nov 4, 2026
…bles_on_failure

The test filled the user's only max_concurrent_queries_for_user slot with a
long sleepEachRow query and killed its client after 5 s, relying on the
orphaned query to keep running so that the next SELECT 1 fails with
TOO_MANY_SIMULTANEOUS_QUERIES before its external tables are read.

Since ClickHouse#127149 the server cancels a query whose TCP client is gone, and sleep
stops at its next 1 s chunk, so the slot is free before SELECT 1 arrives.
Sanitizer builds lose that race every time (master red in amd_tsan, amd_msan
and amd_asan_ubsan integration tests), arm_binary usually wins it.

Hold the slot with a background request whose client stays connected, wait
until it is in system.processes, run the unchanged SELECT 1, then stop the
holder with KILL QUERY ... SYNC. The log assertions that are the purpose of
the test are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

This test was reverted together with this PR (#129310), so the speed-up went to the re-land instead: groeneai/ClickHouse@a2e73c1, offered for #129311 in #129311 (comment). It takes about 5 s instead of 18 s in Fast test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants