Skip to content

Do not wait for the remote drain when cancelling a remote query - #118218

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-remote-query-executor-cancel-blocks-on-drain
Sep 6, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-remote-query-executor-cancel-blocks-on-drain

Conversation

@groeneai

@groeneai groeneai commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116959

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed cancelling a distributed, s3Cluster or parallel-replicas SELECT taking up to receive_timeout (300 s by default) to take effect, and never reaching some of the remote sources, when one of them was draining the packets left over after a LIMIT was satisfied.

Description

RemoteQueryExecutor::finish takes was_cancelled_mutex as its first statement and holds it across the packet
drain, whose receivePacket is an uninterruptible socket read bounded only by receive_timeout.
cancel needs that same mutex, and it is driven from ExecutingGraph::cancel, which calls
cancel on every processor in turn under processors_mutex. So one draining remote source stalls the whole
sweep: KILL QUERY can take up to receive_timeout to return, and every remote source after it is never
cancelled at all, so other replicas keep running the cancelled query.

This publishes, lock-free, the one state in which cancel has nothing left to do - finish has completed its
tryCancel and is only draining - and returns on it. There the Cancel packet is already sent, a second
tryCancel early-returns on was_cancelled, and the external-table flags cancel would also set have no live
reader, since their only reader runs inside the external-table send, which holds this same mutex. Narrowing the
lock in finish instead would only move the block onto cancel_mutex, which receivePacket holds for the whole
read and sendCancel needs.

The test parks a reader so one shard stays pending, parks finish at the start of its drain, and asserts
KILL QUERY returns while it is held - an ordering assertion, not a timing threshold. Without the early
return it fails there. The fix sits above IConnections, so one use_hedged_requests arm suffices.

Observed as Hung check failed, possible deadlock found:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112359&sha=c71c9c0c46c419ef30aa8d39dcb4bf22f38d2e5b&name_0=PR&name_1=Stress%20test%20%28arm_msan%29

Deliberately not addressed: the drain's own read stays uninterruptible, so a cancelled query whose peer went
silent can still outlive a hung check; and a cancel arriving before the flag is published still waits out
finish's own tryCancel, which can block in RemoteQueryExecutorReadContext::cancelBefore
(the linked pull request is open against that wait) or on cancel_mutex behind a reader inside receivePacket.
No related open issue found.


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

Version info

  • Merged into: 26.9.1.824 (included in 26.9 and later)

`RemoteQueryExecutor::finish` takes `LockAndBlocker guard(was_cancelled_mutex)` as its first
statement and holds it across the packet drain. That drain's `connections->receivePacket` is a
synchronous, unbounded socket read: `MultiplexedConnections::receivePacket` passes an empty async
callback, so `ReadBufferFromPocoSocketBase::socketReceiveBytesImpl` takes the plain branch into
`Poco::Net::SocketImpl::receiveBytes`, which has no cancellation hook and is bounded only by
`receive_timeout`.

`RemoteQueryExecutor::cancel` needed the same mutex, and it is driven from `ExecutingGraph::cancel`,
which takes `processors_mutex` and then calls `cancel` on every processor sequentially inside that
lock. So one draining remote source stalled cancellation of the whole pipeline: `KILL QUERY` could
take up to `receive_timeout` to return, and every remote source after the draining one in the
iteration order was never cancelled at all, leaving other replicas executing a cancelled query.

Publish, lock-free, the one state in which `cancel` provably has nothing left to do, and return on
it. `drain_in_progress` is set only after `tryCancel` has returned and only for the duration of the
drain, which implies all four of:

  - `tryCancel` completed, so `was_cancelled` is set, `read_context->cancel` has run and
    `connections->sendCancel` was issued; a second `tryCancel` early-returns on `was_cancelled`, so
    `cancelUnlocked`'s own `tryCancel` is a provable no-op;
  - `sent_query` is true, since `finish` got past its `!sent_query` gate;
  - the external-table send already completed, so marking `external_tables_data` is inert:
    `sendQuery` holds `was_cancelled_mutex` across the whole send including `sendExternalTables`,
    and the only reader of `ExternalTableData::is_cancelled` is `ExternalTableSink::consume`, which
    runs only while that send is pumping;
  - no `read_context` can appear afterwards, because both creation sites test `was_cancelled` under
    the mutex first.

The predicate is therefore a strict subset of `was_cancelled`, which on its own would be too broad:
`tryCancel` sets `was_cancelled` before the genuinely blocking wait in
`RemoteQueryExecutorReadContext::cancelBefore`.

Narrowing the lock in `finish` instead does not work, it only moves the block: `receivePacket` holds
`cancel_mutex` for the whole read, and both `sendCancel` and `disconnect` need that mutex, in
`MultiplexedConnections` and in `HedgedConnections` alike.

`cancelUnlocked` is byte-identical, `was_cancelled` keeps its `TSA_GUARDED_BY` and its writer set is
unchanged, and `SCOPE_EXIT` clears the new flag on all five exits from the drain loop, including the
`rethrow` and the `SYSTEM_ERROR` throw. `drain_in_progress` follows the same unguarded
`std::atomic_bool` pattern this class already uses for `announcement_received`, `drain_was_skipped`
and `in_receive_packet_window`, so it introduces no new concurrency idiom.

The new stateless test replaces timing with two failpoints: `remote_query_executor_receive_packet_pause`
parks one shard's reader before it consumes a packet, so that shard is still pending when `LIMIT 1`
closes the output ports, and the new `remote_query_executor_finish_drain_hold` parks `finish` at the
start of its drain while it holds the mutex. `KILL QUERY` must then return while the park is still
held. That is an ordering assertion rather than a duration one, because the unfixed latency while
parked is unbounded. It fails on a tree without the early return and passes 50 out of 50 randomized
runs with it.
The comment on the early return in `cancel` claimed the `tryCancel` that precedes the drain has
already done everything `cancel` would do. It has not: `cancelUnlocked` also marks
`external_tables_data`, which `tryCancel` never touches. Skipping that is still correct, but because
the only reader of `ExternalTableData::is_cancelled` is `ExternalTableDataSink::consume`, reached only
from the external-table send that holds `was_cancelled_mutex` for its whole duration - so it cannot
overlap the drain. State that invariant instead, and move the `ExecutingGraph` reasoning out of the
source, where the previous commit message already carries it.

Also drop the narration of the drain flag's own `SCOPE_EXIT`, whose "the two that throw" undercounts
the loop's throwing exits.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two rounds over this diff. One finding was fixed (an in-diff comment gave the wrong reason for a
correct skip). Three were disagreed with; these two are worth stating, since a reader is likely to
reach both independently.

⚠️ A hedged replacement replica started during the drain is left uncancelled - but not by this
change.
HedgedConnections::sendCancel leaves each replica's change_replica_timeout armed, and an
expiry inside the drain's own receivePacket can start a replacement without checking cancelled. The
gap is real and pre-existing: without the early return, cancel reaches tryCancel, which returns at
its was_cancelled guard, and the drain is entered only after finish's own tryCancel set that
flag - so no Cancel packet is removed here, and HedgedConnections::sendCancel would in fact throw on
a second call. The delta for that replica is zero, in a file this PR does not touch.

⚠️ Pinning max_threads >= 2 in the new test, on the theory that a randomized max_threads = 1
leaves the parked reader holding the only pipeline thread.
clickhouse-test draws 1 about a third of
the time, yet 50 randomized runs pass in ~3 s each, and the merged
04512_distributed_limit_no_more_packets_race has the same two-shard fixture and interleaving with no
pin. Pinning it would document a mechanism that does not hold.

💡 The test proves KILL QUERY returns while the drain is parked, which is the sweep reaching every
later processor. It does not discriminate the exact moment the flag is published; that rests on the
source argument, as the description says.

@clickhouse-gh clickhouse-gh Bot closed this Sep 5, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ff425fa]

Summary: ✅


AI Review

Summary

This PR makes RemoteQueryExecutor::cancel stop waiting for finish()'s post-LIMIT drain once tryCancel has already completed, so ExecutingGraph::cancel can continue cancelling the rest of the pipeline instead of stalling on one remote source. I did not find any actionable findings in the current diff: the new fast path is only published after the Cancel packet has been sent for the draining executor, the existing disconnect-on-unsynchronised-path logic is preserved, the added failpoint test exercises the intended ordering, and the linked Praktika run for ff425fa39407d1f9adb7dc506c0c4d20a100e039 is all green.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit ff425fa.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @yariks5s, could you review this? RemoteQueryExecutor::finish holds was_cancelled_mutex across its packet drain, whose receivePacket is an uninterruptible socket read, and ExecutingGraph::cancel calls cancel on every processor in turn, so one draining remote source stalls the whole sweep: KILL QUERY can take up to receive_timeout to return and the remote sources after it are never cancelled at all.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ff425fa39 with master d1adb9f9f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

68 translation units recompiled, 723 s compile time in total, 68 of them have a recent master baseline.

Job report

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@alexey-milovidov alexey-milovidov self-assigned this Sep 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 5, 2026
Merged via the queue into ClickHouse:master with commit e3fb4a9 Sep 6, 2026
174 of 344 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 2026
@Algunenano

Copy link
Copy Markdown
Member

04340_distributed_plan_status_reenqueue_fault and 04648_distributed_plan_task_error_propagation are failing in CI after this PR. Reverting. Please investigate and reintroduce

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed: both tests are clean in the 7 days before this merged and start immediately after. The first failure is master f0346e63c at 2026-09-06 01:34:45Z (Stateless tests (arm_asan_ubsan, azure, sequential), both tests in the same run), which contains e3fb4a9 and not the revert, and CIDB has 67 failures over 36 commits, 19 of them on master, in the 34 hours since. The only earlier hits in 30 days are 7 rows on 13-18 August, so it is a step change and not the old background rate.

I am investigating both and will reintroduce this with them covered, together with the regression test the revert removed.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Reintroduced in #118696, with the cancel/finish race the first version left open now closed.

On the two tests: the step change I reported is real, but the revert did not stop them. In Stateless tests (arm_asan_ubsan, azure, sequential), which carries most of their failures, they failed 38 times in 414 PR runs after the revert against 40 in 466 while this was on master, on 19 distinct heads. Five of those heads have the revert as an ancestor and carry neither this PR's flag nor its test file: 39281bbd8cfeae30 (#116647), d566ff4c5d1711c1 (#118569), 8beed835fbfbda86 (#118628), 6384a606bec90a85 (#118620), b17c035435d1522b (#118629). Master looks clean only because it ran that check 42 times in the same window.

So they are not this change's doing, and I have not found what is. #118390 and #118417 are the open fixes for them; whether #118696 lands before or after those is your call.

alexey-milovidov added a commit that referenced this pull request Sep 13, 2026
Edited by hand following .claude/skills/edit-changelog/SKILL.md, consolidating
the nine raw blocks generated between 2026-09-06 and 2026-09-13. The
NightlyChangelog job rejected its own edits every night in that period: the
verifier did not know that #116566 (reverted by #116586) had itself reverted
#109710, so it demanded that no trace of #116586 remain while the rules put
its link on the CatBoost entry. Fixed in the job by
#119866; this edit passes the
patched verifier, and the trailers below give the ledger the missing chain.

Failed runs: https://github.com/ClickHouse/ClickHouse/actions/runs/34006912773
through https://github.com/ClickHouse/ClickHouse/actions/runs/34668133756

Changelog-revert: 116566 109710 Revert "Remove CatBoost integration"
Changelog-revert: 116586 116566 Revert "Revert "Remove CatBoost integration""
Changelog-revert: 117629 117295 Revert "Skip Darwin fast test in PRs unless labeled ci-macos"
Changelog-revert: 118525 118218 Revert "Do not wait for the remote drain when cancelling a remote query"
Changelog-revert: 119043 117866 Revert "Add `ci-coverage` label to force LLVM coverage jobs on tests-only PRs"
Changelog-revert: 119269 118239 Revert "Require agents to run the style check locally before pushing"
Changelog-revert: 119270 115343 Revert "Resume a NATS JetStream subscription after a reconnect"
Changelog-revert: 119274 118919 Revert "Carry the mutation version onto a rewritten lightweight `DELETE`"
Changelog-revert: 119275 114817 Revert "Convert OUTER join to INNER join by null-rejecting join conditions"
Changelog-revert: 119276 110939 Revert "Support real hard links for plain_rewritable metadata."
Changelog-revert: 119279 117449 Revert "Print file offsets in the bare fatal stack traces and build the release binary as PIE"
Changelog-revert: 119281 116629 Revert "Check access rights in the TimeSeries table functions"
Changelog-revert: 119298 118606 Revert "Proper partition pruning with dates"
Changelog-revert: 119323 117768 Revert "Docs: Skip private sync for documentation-only pull requests"
Changelog-revert: 119334 117356 Revert "Unify the spill trigger for hash joins"
Changelog-revert: 119429 114562 Revert "Fix NO_SUCH_COLUMN_IN_TABLE naming a column absent from the table when a part's columns were all renamed or all dropped"
Changelog-deleted-entry: 110939 [New Feature] [raw] * Disks with the `plain_rewritable` metadata (`s3_plain_rewritable`, and `azure`/`local` object storages with `metadata_type = plain_rewritable`) support hard links if configured with the new `enable_hard_links` setting, which enables `ALTER` operations and mutations on `MergeTree` tables stored on them. Mutations and partition operations share the unchanged blobs between parts instead of copying them. The setting is off by default, because a disk that has hard links cannot be read by older servers. [#110939](#110939) ([yanglongwei](https://github.com/ylw510)).
Changelog-deleted-entry: 114562 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed `NO_SUCH_COLUMN_IN_TABLE` naming a column that is not in the table, when reading or merging a part whose columns had all been renamed or all dropped by a mutation that was not applied yet. The merge kept being retried, so the table stopped compacting. Also fixed the columns of a `MergeTree` part produced by such a merge reading as their default values until the mutation was applied. [#114562](#114562) ([Shaohua Wang](https://github.com/tiandiwonder)).
Changelog-deleted-entry: 114817 [Performance Improvement] [raw] * Convert `OUTER JOIN` to `INNER JOIN` when a later JOIN condition filters out its NULL-extended rows, and filter NULL join keys directly at the table scan when column statistics show it is selective. Only conditions of the form `expr1` OP `expr2` are considered, where OP is one of `=`, `<`, `<=`, `>`, `>=`. Each side can be a column or an expression that propagates NULLs. Controlled by the new settings `query_plan_derive_not_null_filters_from_joins` (enabled by default), `query_plan_allow_derived_not_null_filters_execution` (enabled by default) and `query_plan_max_selectivity_for_not_null_filters_execution` (0.7 by default). [#114817](#114817) ([Hechem Selmi](https://github.com/m-selmi)).
Changelog-deleted-entry: 115343 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed a `NATS` engine table reading from a JetStream stream (`nats_stream`) silently stopping to consume messages after the NATS server restarted or the connection was re-established. [#115343](#115343) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 116629 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * The table functions reading a `TimeSeries` table (`timeSeriesSamples`, `timeSeriesTags`, `timeSeriesMetrics`, `timeSeriesSelector`, `prometheusQuery`, `prometheusQueryRange`) checked no privilege on it: a user holding only `CREATE TEMPORARY TABLE` could read its target tables' column definitions and rows, and write into them. Each now requires the corresponding privilege on the `TimeSeries` table and on the target table, following an `Alias` target through to the table it points at. `timeSeriesSamples`, `timeSeriesTags` and `timeSeriesMetrics` check the target at table level, since they return it whole and cannot restrict the columns, so a column-scoped grant on the target is not enough; the other three run ordinary target queries, which the planner still checks per column. An external target is authorized before it is looked up, so its existence is not disclosed either. A read fails with `ACCESS_DENIED` when the user's effective `SELECT` row-policy filter on the `TimeSeries` table is not always true, since such a policy cannot be enforced on the target's rows, and the three target functions can no longer back a `CREATE TABLE ... AS` (`BAD_ARGUMENTS`). PromQL over the Prometheus HTTP and remote-read endpoints reaches `timeSeriesSelector` whenever it selects series, so those requests now need these privileges for the user the endpoint authenticated. [#116629](#116629) ([Groene AI](https://github.com/groeneai)).
Changelog-deleted-entry: 117356 [Backward Incompatible Change] [raw] * `max_bytes_before_external_join` and `max_bytes_ratio_before_external_join` are now the spill threshold for every hash-based `join_algorithm`, including `grace_hash`, which previously ignored them and spilled on `max_rows_in_join` / `max_bytes_in_join` instead. Those two are a hard cap again for every algorithm: they no longer cause spilling, and a join that spills no longer exceeds them. All join algorithms remain available; `join_algorithm = 'grace_hash'` now needs a non-zero spill threshold, and is skipped in favour of the next algorithm in the list when it has none. Set `legacy_join_size_limits_trigger_spilling = 1` (or `compatibility` to 26.8 or older) to restore the previous behavior. [#117356](#117356) ([Yarik Briukhovetskyi](https://github.com/yariks5s)).
Changelog-deleted-entry: 117449 [Build/Testing/Packaging Improvement] [raw] * ClickHouse is now built as a position independent executable on Linux amd64 and aarch64 with glibc, including the release builds, so the text segment is subject to ASLR. Addresses in the bare stack trace of a fatal log are now file offsets relative to the object that contains them, annotated with that object for frames outside the main executable, so they can be resolved with `addr2line -e <object> <hex>` regardless of where the binary was loaded. For the same reason `system.errors.last_error_trace`, `system.error_log.last_error_trace` and `system.crash_log.trace` now store a frame of the main executable as its file offset, keeping runtime addresses for frames in other objects. [#117449](#117449) ([Groene AI](https://github.com/groeneai)).
Changelog-deleted-entry: 117768 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Not applicable. [#117768](#117768) ([Dominic Tran](https://github.com/dhtclk)).
Changelog-deleted-entry: 118218 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed cancelling a distributed, `s3Cluster` or parallel-replicas `SELECT` taking up to `receive_timeout` (300 s by default) to take effect, and never reaching some of the remote sources, when one of them was draining the packets left over after a `LIMIT` was satisfied. [#118218](#118218) ([Groene AI](https://github.com/groeneai)).
Changelog-deleted-entry: 118239 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Require agents to run the style check locally before pushing. [#118239](#118239) ([Nikita Fomichev](https://github.com/fm4v)).
Changelog-deleted-entry: 118606 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Proper partition pruning with dates. Closes [#103433](#103433). [#118606](#118606) ([Konstantin Vedernikov](https://github.com/scanhex12)).
Changelog-deleted-entry: 118919 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed a pending lightweight `DELETE` read with `apply_mutations_on_fly = 1` evaluating its predicate over patch parts created after it, which made rows disappear from the result and reappear after the mutation materialized. [#118919](#118919) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
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

can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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.

5 participants