Repository navigation
Do not wait for the remote drain when cancelling a remote query - #118218
Conversation
`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.
Internal second-model reviewTwo rounds over this diff. One finding was fixed (an in-diff comment gave the wrong reason for a
💡 The test proves |
|
Workflow [PR], commit [ff425fa] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict
LLVM Coverage ReportMeasured on commit ff425fa.
Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code |
|
cc @devcrafter @yariks5s, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units68 translation units recompiled, 723 s compile time in total, 68 of them have a recent master baseline. |
e3fb4a9
|
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 |
|
Confirmed: both tests are clean in the 7 days before this merged and start immediately after. The first failure is master I am investigating both and will reintroduce this with them covered, together with the regression test the revert removed. |
|
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 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. |
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)).
…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
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
Related: #116959
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed cancelling a distributed,
s3Clusteror parallel-replicasSELECTtaking up toreceive_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 aLIMITwas satisfied.Description
RemoteQueryExecutor::finishtakeswas_cancelled_mutexas its first statement and holds it across the packetdrain, whose
receivePacketis an uninterruptible socket read bounded only byreceive_timeout.cancelneeds that same mutex, and it is driven fromExecutingGraph::cancel, which callscancelon every processor in turn underprocessors_mutex. So one draining remote source stalls the wholesweep:
KILL QUERYcan take up toreceive_timeoutto return, and every remote source after it is nevercancelled at all, so other replicas keep running the cancelled query.
This publishes, lock-free, the one state in which
cancelhas nothing left to do -finishhas completed itstryCanceland is only draining - and returns on it. There theCancelpacket is already sent, a secondtryCancelearly-returns onwas_cancelled, and the external-table flagscancelwould also set have no livereader, since their only reader runs inside the external-table send, which holds this same mutex. Narrowing the
lock in
finishinstead would only move the block ontocancel_mutex, whichreceivePacketholds for the wholeread and
sendCancelneeds.The test parks a reader so one shard stays pending, parks
finishat the start of its drain, and assertsKILL QUERYreturns while it is held - an ordering assertion, not a timing threshold. Without the earlyreturn it fails there. The fix sits above
IConnections, so oneuse_hedged_requestsarm 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
cancelarriving before the flag is published still waits outfinish's owntryCancel, which can block inRemoteQueryExecutorReadContext::cancelBefore(the linked pull request is open against that wait) or on
cancel_mutexbehind a reader insidereceivePacket.No related open issue found.
Workflow [PR]
Sync PR [sync-upstream/pr/118218]
Version info
26.9.1.824(included in26.9and later)