Repository navigation
Do not send a remote query after the executor was marked finished - #113551
Merged
Merged
Conversation
`RemoteQueryExecutor::finish` marks an executor `finished` when its output port is closed before the query has been sent, but it did not mark it cancelled. Both `sendQuery` and `sendQueryAsync` gate only on `was_cancelled`, never on `finished`, so a `RemoteSource::work()` that was already scheduled went on to send the query afterwards. From that point nothing could release it: `finish` returns early for the rest of the query's life, and the destructor's `if (established || (isQueryPending() && connections))` is false because `finished` is set, so the connection went back to the pool without a `Cancel` packet and without a disconnect. For parallel replicas this stranded a follower. In `SELECT ... LIMIT 1` where the initiator's local replica takes the only mark, the coordinator never reaches `Finish: true`, so the callback that cancels unused replicas never runs and teardown is the only thing that can release the followers. A follower left this way stays blocked in `TCPHandler::receivePartitionMergeTreeReadTaskResponse` for the whole `receive_timeout` (300 s by default) holding the table's shared lock, which is what stalled the `DROP TABLE` at the end of `02764_parallel_replicas_plain_merge_tree`. `KILL QUERY ... SYNC` on such a replica hangs too, since it is inside a blocking socket read. Mark the executor cancelled as well, so the query is never sent. The comment claiming that only the synchronous, non-Linux send path could reach this branch was wrong: `async_query_sending_for_remote = 0` takes the synchronous path on Linux too, and makes the window deterministic. The new test reproduces the stranded replica 6/6 without this change and passes 15/15 with it, plus 16/16 with `max_threads`, `prefer_localhost_replica`, `use_hedged_requests` and `async_socket_for_remote` randomized. Closes: #109265 CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105737&sha=5c92e2a6f0071014848b95c9c78201fa6642f45a&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20parallel%2C%201%2F2%29 Related: #105737 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017fTDZRiWPsEFAQnjTrFTiQ
Contributor
|
Workflow [PR], commit [bb3da54] Summary: ✅
AI ReviewSummaryThis PR fixes two sides of the same early-finish teardown bug. In Final Verdict✅ No blocking issues found. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 26/26 (100.00%) · Uncovered code |
nickitat
marked this pull request as ready for review
August 6, 2026 11:27
nickitat
marked this pull request as draft
August 6, 2026 13:29
…shed The previous commit stopped `RemoteQueryExecutor` from sending a query for an executor that `finish` had already marked `finished`. That is not specific to parallel replicas: any pipeline where a local source satisfies the consumer before the remote sources have sent their queries hits it. Instrumenting the branch showed it is taken on essentially every `UNION ALL remote(...)` with a `LIMIT` - three times per query, once per remote source - and that every such entry went on to send the query. Outside parallel replicas the consequence is quieter than the 300 s stall of `02764_parallel_replicas_plain_merge_tree`, because a plain remote query never waits for anything from the initiator: the abandoned connection is simply returned to the pool without a `Cancel` packet and without a disconnect, while the remote query may still be running. That is the state `RemoteQueryExecutor::finish` already warns about for cancelled connections. Assert that a `LIMIT` satisfied by a local source starts no remote read. The count is 3 without the fix and 0 with it; `remote()` also issues an unconditional `DESC TABLE` to infer the structure, which is not a read and is filtered out. `async_query_sending_for_remote = 0` sends from `work()` synchronously, which is what makes the window deterministic. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017fTDZRiWPsEFAQnjTrFTiQ
The parallel replicas coordinator discovered that reading was complete only when some replica asked for work and was told `finish = true`. That is a request-driven check, so it never fires when the initiator stops pulling first: with `SELECT ... LIMIT 1` where the local replica takes the only mark, the local pool never asks again and the followers' requests are never read, so nobody is ever told `finish`. The replicas that got nothing were then left waiting on a read task that never comes, released only by pipeline teardown - and only if teardown reaches them. Completion is a property of the coordinator's own state, not of the protocol: `isReadingCompleted` just asks whether any ranges are left. Evaluate it in the `finish = false` branch as well, so unused replicas are released as soon as there is provably nothing left to assign. `replicas_used` already contains the replica the response is for, so it is excluded from cancellation and still gets the `finish = true` round-trip the protocol owes it. On the run in the issue this fires at the moment the local replica takes the mark, 5 ms before the follower queries were sent at all, so the followers never reach the read-task wait. Without it that query produced no cancellation whatsoever. Checked on a 200k row / 25k mark table across randomized `max_parallel_replicas`, `max_threads` and `async_query_sending_for_remote`, including the early terminating `LIMIT` shape: results unchanged. Closes: #109265 CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105737&sha=5c92e2a6f0071014848b95c9c78201fa6642f45a&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20parallel%2C%201%2F2%29 Related: #105737 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017fTDZRiWPsEFAQnjTrFTiQ
`isReadingCompleted` walks every part and every range, and the previous commit made it run on responses that hand out ranges, not only on the final one. Gate it on an O(1) hint. `DefaultCoordinator` now tracks how many marks the working set had and how many have been handed out, next to the existing per-replica `sum_marks` accounting, and reports whether anything may be left. `isReadingCompleted` remains the authority, so neither answer of the hint can be unsafe: a spurious `false` costs one exact scan, a spurious `true` misses an early release and falls back to the behaviour from before the previous commit. Nothing can cancel a replica that still has work. The base implementation returns `true`, so `InOrderCoordinator` keeps the old behaviour rather than relying on a counter that was not written for it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017fTDZRiWPsEFAQnjTrFTiQ
Style check requires a query to `system.query_log` to be scoped to the test's own database. `current_database = currentDatabase()` is not usable here: a remote query runs with `default` as its current database, so that condition matches none of the rows the test counts and would have made it report 0 unconditionally - green in CI while detecting nothing. `databases` does hold the test's database for those rows, and is one of the forms the check accepts. It is empty for the `DESC TABLE` that `remote()` issues to infer the structure, so that row drops out on its own and the explicit filter on `SELECT` is no longer needed. Scoping is still primarily by `initial_query_id`, which is unique to the run. Checked on one binary with the fix switched on and off: 3 remote reads started without it, 0 with it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017fTDZRiWPsEFAQnjTrFTiQ
nickitat
marked this pull request as ready for review
August 7, 2026 19:45
This was referenced Aug 8, 2026
alexey-milovidov
approved these changes
Aug 9, 2026
This was referenced Aug 12, 2026
pull Bot
pushed a commit
to Haofei/ClickHouse
that referenced
this pull request
Sep 24, 2026
04604_parallel_replicas_unsent_query_not_cancelled fails only on the amd_llvm_coverage lanes: 29 times on master over 30 days, every one of them on a coverage lane (22/1174 = 1.87% on the plain 3/3 lane, 4/1179 on AsyncInsert+s3, 3/390 on s3+DBReplicated), against 0 of ~15000 runs on every non-coverage lane. 28 of the 29 are currently hidden as OK because the diagnostics rerun relabels them flaky. The discriminator is the instrumented binary, not the Replicated database and not s3: 22 of the 29 ran with no Replicated database at all. It is not a cancellation bug. Measured from the failing job's own artifacts, the follower receives and honours the Cancel 11 ms after its query starts, at its first cancellation checkpoint, and throws QUERY_WAS_CANCELLED_BY_CLIENT. It then spends 4.17 more seconds resolving that exception's text stack trace in logExceptionBeforeStart, and its system.processes row is released only when that finishes; trace_log caught the thread 8 of 8 times in the gap on a byte-identical 17-frame DWARF lookup stack, with both the real and the CPU timer firing at full rate. Since code 735 sets log_error = false, the only thing that can demand the trace is query_log_will_read, and log_queries is forced to 1 by the CI config, so the whole 4.17 s exists to populate system.query_log.stack_trace for a query that was cancelled on purpose. The cost is intermittent because StackTrace::toString is cached per process on the frame triple: over all 4510 ExceptionBeforeStart rows of that job the post-throw cost is p50 1 ms, p90 72 ms, p99 2202 ms, max 4533 ms. The test polls system.processes for ~3.4 s, so it reports a parked replica that was in fact cancelled 4.1 s earlier. Turn the symbolization off for the measured query. calculate_text_stack_trace is the documented lever for exactly this cost and is already used this way by five tests in the suite, so no new setting appears. The poll budget, receive_timeout, the assertion and the reference are all untouched, which keeps the test's discriminating power intact and leaves a ~300x margin over the 11 ms the cancellation actually needs. Raising the timeout was rejected because it widens a margin instead of removing the cause and would make a genuine regression cost ~60 s; a retry was rejected because it can mask a real cancellation gap; and no-replicated-database was rejected because it would claim a mechanism the measurements refute. The setting reaches the follower through the per-replica context copy (updateContextForParallelReplicas -> Context::createCopy) and is not in initiator_only_setting_names, so nothing strips it. Verified on one binary: the follower's query_log row carries a 7199-byte stack_trace without this change and an empty one with it, while recording calculate_text_stack_trace = 0 on its own row. Sensitivity was checked against a genuinely parked follower using the parallel_replicas_delay_announcement failpoint, where the changed test still reports "FAIL: 1 replica(s) still running" 16 times out of 20 versus 14 out of 20 for the unchanged test. 100 of 100 local runs green, 50 randomized and 50 not. One consequence worth knowing: system.query_log.stack_trace is now empty for this test's queries. No assertion depends on it, and a regression is still identified by the reference diff and the server log. Related: ClickHouse#113551 CI report: https://github.com/ClickHouse/ClickHouse/actions/runs/35917766208/job/107380811116 Co-Authored-By: Claude Opus 5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix possible query hanging (for the
receive_timeoutseconds) in case it very quickly finishes on the initiator.Closes: #109265