Skip to content

Revert "Do not wait for the remote drain when cancelling a remote query" - #118525

Merged
Algunenano merged 1 commit into
masterfrom
revert-118218-groeneai/fix-remote-query-executor-cancel-blocks-on-drain
Sep 7, 2026
Merged

Algunenano merged 1 commit into
masterfrom
revert-118218-groeneai/fix-remote-query-executor-cancel-blocks-on-drain

Conversation

@Algunenano

@Algunenano Algunenano commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

Reverts #118218


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

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [29595ee]


AI Review

Summary

This PR reverts #118218 by removing the RemoteQueryExecutor::cancel fast path for the state where finish has already sent Cancel and is only draining, and by deleting the regression test for that interleaving. I do not think this is safe to merge: finish still holds was_cancelled_mutex across a blocking receivePacket drain, RemoteSource::onUpdatePorts can still enter that drain when a LIMIT closes the port, and ExecutingGraph::cancel still walks every processor under processors_mutex, so the revert reintroduces the KILL QUERY stall up to receive_timeout and can leave later remote sources uncancelled.

Findings

❌ Blockers

  • [src/QueryPipeline/RemoteQueryExecutor.cpp:1078] Removing the drain_in_progress check reopens the cancellation contract that Do not wait for the remote drain when cancelling a remote query #118218 fixed. RemoteSource::onUpdatePorts still calls finish when the output port closes, finish still takes was_cancelled_mutex at entry and holds it across connections->receivePacket, and ExecutingGraph::cancel still calls processor->cancel for the whole pipeline under processors_mutex. In that interleaving a user KILL QUERY blocks behind the draining replica until its socket read completes or times out, and processors later in the cancel sweep never receive their own cancel. Keep a lock-free "already draining after tryCancel" state here, or otherwise restructure finish so cancel never waits behind the blocking drain.
Tests
  • ⚠️ Keep a focused regression test for cancelling while RemoteQueryExecutor::finish is parked in its drain. The deleted 05076_remote_query_executor_cancel_during_drain.sh covered exactly the interleaving this revert reintroduces, and there is no replacement evidence in this PR.
Final Verdict

❌ Request changes. The revert reintroduces a query-cancellation blocker in distributed / s3Cluster / parallel-replica remote reads.

@Algunenano
Algunenano enabled auto-merge September 7, 2026 09:38
@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 7, 2026
@Algunenano
Algunenano added this pull request to the merge queue Sep 7, 2026
void RemoteQueryExecutor::cancel()
{
/// While `finish` drains it has already sent the `Cancel` packet, and the external-table flags
/// `cancelUnlocked` sets have no reader until it releases `was_cancelled_mutex`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Removing this fast path reopens the cancellation stall that #118218 fixed. RemoteSource::onUpdatePorts can still call finish when LIMIT closes the port, finish still holds was_cancelled_mutex across the blocking connections->receivePacket drain, and ExecutingGraph::cancel still iterates processor->cancel under processors_mutex. In that interleaving a user KILL QUERY waits behind the draining replica until receive_timeout, and later remote sources in the same cancel sweep never get cancelled. If the original implementation has to be reverted, we still need an equivalent non-blocking state here, or finish has to stop holding the cancellation path across the drain.

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 7, 2026
Merged via the queue into master with commit 9c0f44f Sep 7, 2026
32 of 57 checks passed
@Algunenano
Algunenano deleted the revert-118218-groeneai/fix-remote-query-executor-cancel-blocks-on-drain branch September 7, 2026 10:19
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
robinld pushed a commit to robinld/ClickHouse that referenced this pull request Oct 4, 2026
…ery"

This reverts commit 29595ee, which reverted
ClickHouse#118218 (merged as e3fb4a9).

The reverted change fixes this: RemoteQueryExecutor::finish takes
was_cancelled_mutex as its first statement and holds it across the packet
drain, whose connections->receivePacket() is an uninterruptible socket read
bounded only by receive_timeout (300 s by default). cancel() needs the same
mutex and is driven from ExecutingGraph::cancel, which walks every processor
under processors_mutex, so one draining remote source stalls the whole
cancellation sweep: KILL QUERY can take up to receive_timeout to return, and
the remote sources after the draining one are never cancelled at all, so other
replicas keep running a query the initiator has already given up on. It
surfaced as Stress test (arm_msan) / "Hung check failed, possible deadlock
found".

ClickHouse#118525 reverted it because 04340_distributed_plan_status_reenqueue_fault and
04648_distributed_plan_task_error_propagation began failing on master. Those
two tests do not run any RemoteQueryExecutor: make_distributed_plan forces
enable_parallel_replicas = 0, makeDistributed rejects ReadFromRemote, and
assertFragmentSerializable rejects the rest, so the initiator pipeline has no
RemoteSource, and neither cancel() caller tree-wide is reachable from a
distributed-plan query. The failures are also reproducible on a tree that
carries the revert and neither of the two fixes now open for them
(39281bb fails both), so the defect they expose is pre-existing.
The step change in their failure rate nevertheless tracks this change's
presence on master, and I do not claim to have identified the carrier.

This commit restores the reverted diff unchanged so the reapply is reviewable
on its own. The next commit closes a hole the first attempt left: it published
the drain flag after finish had already taken was_cancelled_mutex, so a cancel
that read the flag earlier still waited out the whole drain.

Related: ClickHouse#118218, ClickHouse#118525
robinld pushed a commit to robinld/ClickHouse that referenced this pull request Oct 4, 2026
The reverted change published its drain flag *after* `finish` had already taken
`was_cancelled_mutex` and run `tryCancel`, so this interleaving still waited out
the whole drain:

    cancel:  reads the flag as false                    -> falls through
    finish:  holds `was_cancelled_mutex`, not yet published (includes `tryCancel`)
    cancel:  takes `was_cancelled_mutex`                 -> waits out the drain

Publishing the flag earlier only shrinks that window: between `cancel` reading
the flag and acquiring the mutex a whole `finish` can publish, acquire and start
draining, which is reachable under the thread fuzzer this bug was reported from.
Closing it needs the observation and the acquisition to be atomic, so the flag
becomes `finish_in_progress`, a counter under a dedicated `finish_gate_mutex`
held for O(1) work only. `finish` increments it before asking for
`was_cancelled_mutex`; `cancel` reads it and takes `was_cancelled_mutex` while
still holding the gate, then releases the gate before `cancelUnlocked`.

Why that is atomic: a `cancel` that reaches the acquisition holds the gate and
has read zero. Any `finish` that already owns or is waiting for
`was_cancelled_mutex` incremented the counter first, so it would have been seen;
any `finish` that has not incremented yet is blocked at the gate and so cannot
own that mutex. The holder `cancel` may wait for is therefore never a draining
`finish`. `connections->receivePacket` has exactly two call sites: `read`, which
releases the mutex before it, and `finish`'s drain, so the drain is the only
place the mutex is held across a blocking read. The other holders are
`sendQuery` and `processPacket` (network writes), the async steps of
`readAsync`, which return an fd instead of blocking, `isCancelled` and the
destructor.

Deadlock freedom: the order is always `finish_gate_mutex` before
`was_cancelled_mutex`. `finish`'s `SCOPE_EXIT` is declared before its
`LockAndBlocker`, so at scope exit the mutex is released first and the gate is
taken afterwards, and `cancel` unlocks the gate explicitly. That unlock is
load-bearing rather than tidiness: `cancelUnlocked` reaches `tryCancel`, whose
`read_context->cancel` and `connections->sendCancel` are socket writes, and
holding the gate across them would make every concurrent `finish` wait for that
I/O at the gate instead. The gate covers a counter update, a comparison, or one
acquisition, never I/O.

A skipped `cancel` loses nothing. `cancelUnlocked` has three effects, and
`finish` covers all three: every path that reaches the drain has run
`tryCancel`, so the `Cancel` packet is sent and a `cancel` would early-return on
`was_cancelled`; every earlier return leaves `finished` or
`hasThrownException`, on which `cancelUnlocked` returns without acting; and the
external-table `is_cancelled` flags have no live reader, because their only
reader tree-wide is `ExternalTableSink::consume`, reached from
`sendExternalTables` inside `sendQueryUnlocked`, which requires the same mutex
`finish` is holding. A later `sendQuery` cannot make them live again either:
`sendQueryUnlocked` returns at once when `sent_query` is set, which it is on
every path that gets there. `cancel` reentering from inside `finish` on the same
executor now returns immediately where it used to self-deadlock on the
non-recursive mutex.

The cancellation the skip defers therefore lands in `finish`'s `tryCancel`,
which runs on every path that reaches the drain and is a socket write, not the
unbounded read. `QueryRunner::cancelAll`, the other `cancel` caller tree-wide,
does not need `cancel` to have acted: it sets its own `finished` flag and then
waits on its thread pool, and the executor it skipped is being terminated by the
`finish` that caused the skip. `HedgedConnections::sendCancel` retracts pending
replacement replicas inside itself, so it covers them identically whichever
caller drives it.

The one way to reintroduce the original symptom through this code would be to
hold the gate while a second `finish` waits for `was_cancelled_mutex`. It does
not: `finish` releases the gate before asking for that mutex, so a `cancel`
never queues behind a drain at the gate either.

`05076_remote_query_executor_cancel_during_drain.sh` grows a second scenario for
this ordering, on a single executor. Two failpoints make it deterministic:
one parks `finish` at the top of the function, before it announces itself, which
is the only way to make `cancel` arrive first, and one parks `cancel` holding
only the gate. Both are guarded by the same executor-local
`in_receive_packet_window` predicate the drain pause uses, because
`ExecutingGraph::cancel` calls `onCancel` on every source including already
finished siblings, and a sibling shard would otherwise consume the one-shot
park. The scenario asserts both directions: `finish` must not reach its drain
while `cancel` holds the gate, and the background `KILL QUERY` must complete
once the gate is released while the drain park is still armed. Both
observations invert under the two rejected designs, which is what the scenario
exists to measure.

Related: ClickHouse#118218, ClickHouse#118525
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). pr-not-for-changelog This PR should not be mentioned in the changelog 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.

2 participants