Skip to content

Don't wait for a replica's announcement to cancel it - #114862

Merged
nickitat merged 12 commits into
masterfrom
fix-parallel-replicas-cancel-unannounced
Aug 26, 2026
Merged

nickitat merged 12 commits into
masterfrom
fix-parallel-replicas-cancel-unannounced

Conversation

@nickitat

@nickitat nickitat commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Reduce cancellation latency for distributed queries that use parallel replicas by not waiting for a replica's initial announcement after the query is already cancelled.


Screenshot 2026-08-15 at 21 18 28

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

Version info

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

Cancelling a parallel-replicas query waits for whatever packet is already in
flight on each replica's connection, so that the socket is left on a packet
boundary. For a replica that has not announced yet, the only packet it owes is
its `MergeTreeAllRangesAnnouncement` - and it sends that only once it has built
and optimized its own plan. So the initiator, having finished reading, blocks for
the whole of that replica's planning phase to receive a message whose only
purpose is to let the coordinator assign ranges it is no longer going to assign.

Traced on TPC-H q22: the drain ends on `MergeTreeAllRangesAnnouncement` every
time, one iteration, zero rows. Sending the `Cancel` packet costs 0.04 ms and the
replica acts on it 0.3 ms later, so none of the cost is the wire; the replicas are
drained one after another, 16 ms each at sf=1. At sf=100 on a three-node cluster
the same wait is ~290 ms against a 576 ms query, which is the whole of that
query's parallel-replicas regression, and q04 and q20 lose 604 ms and 353 ms the
same way.

Skip the drain for a replica that has not announced. Nothing is lost: `tryCancel`
does not mark the executor finished, so `~RemoteQueryExecutor` disconnects that
connection instead of returning it to the pool, and it cannot be left
unsynchronised for anyone else. Replicas that already announced are drained as
before - they may be part-way through a block - so the change is confined to the
case that is provably pointless.

On its own that leaves the replica writing an announcement into a closed socket
and failing with `Broken pipe`. So look for a pending `Cancel` right before
sending the announcement, rather than at the next `interactive_delay` tick: the
replica then stops with `QUERY_WAS_CANCELLED_BY_CLIENT`, which is what it is.

TPC-H q22 at sf=1 goes from 42 ms to 29 ms against 23 ms without parallel
replicas, and `ParallelReplicasReadRequestMicroseconds` from 14 ms to zero, as it
does on q04 and q20. All 22 adapted TPC-H queries return identical results with
parallel replicas off, on, and automatic.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCjBRRshJunXWy6z6FwvUd
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8e1474f]

Summary: ✅


AI Review

Summary

This PR short-circuits cancellation of parallel-replicas followers that have not yet announced, adds a forced cancel probe on the follower before it sends the initial announcement, and covers the behavior with a focused stateless regression test. I did not find a remaining correctness or protocol-safety defect in the current head; the earlier review regressions around ordinary distributed queries, partial_result_on_first_cancel, and missing targeted coverage appear addressed.

Missing context / blind spots
  • ⚠️ Most of the build/test matrix was still pending at review time; Fast test and Style check had finished, but the broader cross-platform/runtime validation had not. A fully green matrix would close that remaining blind spot.
Final Verdict

✅ No new findings to post inline. From code review perspective, the current diff looks acceptable pending CI.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.30% +0.10%

Changed lines: Changed C/C++ lines covered: 47/49 (95.92%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 14, 2026
nickitat and others added 2 commits August 16, 2026 11:26
…licas

The skip added in "Do not wait out a replica's planning to cancel it" was gated on
`announcement_received`, which is only ever set by
`processMergeTreeInitialReadAnnouncement` - a path that requires a parallel reading
coordinator. An ordinary distributed query (`Distributed`, `remote()`, a `*Cluster`
function) never announces, so the flag stayed false and the drain was skipped on
every cancel, including the normal completion path: `finish()` calls `tryCancel`
when enough data has been read, e.g. under `LIMIT`.

That left the socket part-way through a packet. The commit argued this was safe
because `~RemoteQueryExecutor` disconnects instead of pooling the connection, but
that only holds while the query is still pending, and `finish()` marks it finished
immediately after - so the connection went back to the pool unsynchronised. It
surfaced as `Connection to ... terminated` out of `Connection::sendCancel`, and as
a pooled connection destroyed with an unfinalized buffer (`WriteBuffer is neither
finalized nor canceled in destructor`), killing the server. Around forty
distributed tests failed, none of which fail on master.

Gate the skip on the query actually reading with parallel replicas, so an ordinary
distributed query drains exactly as it did before. And when the drain is skipped,
record it and disconnect from the destructor regardless of `finished`, rather than
inferring from `isQueryPending()` that nobody can reuse the connection - a
parallel-replicas query can reach `finish()` before its replicas announce too.

Reported in review of the CI run. The named regressions -
`02466_distributed_query_profiler`, `01814_distributed_push_down_limit`,
`00154_shard_distributed_with_distinct`, `04659_connection_pool_zero_wait_blocks` -
pass again, along with 38 distributed/shard tests locally (the rest need the
stateful dataset). TPC-H q22 at sf=1 keeps the change's benefit:
`ParallelReplicasReadRequestMicroseconds` is still zero.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCjBRRshJunXWy6z6FwvUd
`finish` cancels the query and then runs its own drain loop over the same
connections, to collect the `Log`, `ProfileEvents` and `Progress` packets the
replica sent before it saw the cancel. When the cancel skipped the read-context
drain, the fiber is torn down part-way through a packet and the read side is
canceled, so that loop reads from a canceled buffer and aborts with "ReadBuffer is
canceled. Can't read from it.".

The previous commit only taught the destructor to disconnect such a connection,
which is too late: `finish` reads from it first.

Disconnect instead of draining, which is what the branch a few lines above already
does when the query was cancelled from elsewhere - for the same two reasons it
gives: the read side may already be gone (#95466), and an out-of-sync connection
must not be returned to the pool (#93018). That path is not reached here because
`finish` is itself the canceller, so `was_cancelled` is still false on entry.

Reported in review of the CI run. `02466_distributed_query_profiler`,
`01814_distributed_push_down_limit`, `00154_shard_distributed_with_distinct` and
`04659_connection_pool_zero_wait_blocks` pass, as do
`02784_parallel_replicas_automatic_decision{,_join}`, `04836` and `04839`. All 22
adapted TPC-H queries return identical results with parallel replicas off, on and
automatic, and q22 keeps the change's benefit:
`ParallelReplicasReadRequestMicroseconds` is zero.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCjBRRshJunXWy6z6FwvUd
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8e1474f2e with master 581c15c46 (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
Binary Master PR Δ
programs/clickhouse-stripped 702.08 MiB 699.05 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -49.3 s (-6%) in total before that adjustment.

Job report

@nickitat nickitat changed the title Do not wait out a replica's planning to cancel it Don't wait for a replica's announcement when cancelling it Aug 18, 2026
@nickitat nickitat changed the title Don't wait for a replica's announcement when cancelling it Don't wait for a replica's announcement while cancelling it Aug 18, 2026
@nickitat nickitat changed the title Don't wait for a replica's announcement while cancelling it Don't wait for a replica's announcement to cancel it Aug 18, 2026
Comment thread src/Server/TCPHandler.cpp Resolved
nickitat and others added 5 commits August 18, 2026 18:52
Stands in for a follower that is still planning when the initiator gives up on
it, so the cancel path can be tested without racing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Covers the contract of the three preceding commits: an initiator that finishes
before a replica has announced does not wait for that announcement, and the
replica does not write one into a socket that nobody reads any more.

`parallel_replicas_delay_announcement` holds every follower just short of
announcing, so the initiator - which satisfies `LIMIT 1` from its local plan -
always cancels them mid-planning. Its delay is shortened to 3s here, which is
still three orders of magnitude above the few milliseconds the initiator needs
when it does not wait.

All four `async_socket_for_remote` / `async_query_sending_for_remote`
combinations are exercised, because they leave the cancel by different routes.
The timing assertion covers `async_socket_for_remote = 1` only: with `0` the
reading thread sits in a blocking socket read that cancellation cannot
interrupt, so the initiator still waits out the replica (3s, and 6s when the
query is also sent synchronously and the waits serialize). Those combinations
are still run, to show that skipping the drain neither corrupts the pooled
connections nor takes the server down - both of which broke earlier revisions.

How many followers get far enough to run depends on how quickly the cancel
overtakes the query being sent, so nothing asserts their number; the assertion
is that none of them announced.

Co-Authored-By: Claude Opus 5 <[email protected]>
Without `slowdown_parallel_replicas_local_plan_read` the local plan can answer
`LIMIT 1` before the query has even been sent to the followers. There is then
nothing to cancel and nothing to wait for, and an unfixed server passes the
test as easily as a fixed one: reverting the three fixes left 1 run in 3
passing, and the `async_query_sending_for_remote = 0` combination never caught
the regression at all.

With the local read slowed down, the sends always land first. Reverting the
fixes now fails 5 runs out of 5, on all three assertions and both asynchronous
combinations. 22 runs pass with the fixes in place (10 without settings
randomization, 12 with).

Co-Authored-By: Claude Opus 5 <[email protected]>
…ext`

`tryCancel` calls it unconditionally, but the class only had it in the
`OS_LINUX || OS_DARWIN` implementation, so every other target failed to build:

    RemoteQueryExecutor.cpp:1185:27: error: no member named 'skipDrainOnCancel'
    in 'DB::RemoteQueryExecutorReadContext'

Seen in CI on `Build (amd_freebsd)` and `Build (wasm64)`.

A no-op matches the stub's existing `cancel` and `setTimer`, and is correct
here: skipping the drain only avoids waiting for a packet that the epoll-driven
read context would otherwise sit on, and the connection is disconnected rather
than pooled either way. `cancel` and `skipDrainOnCancel` are the only two calls
outside the platform guards, so the stub is complete again.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Server/TCPHandler.cpp Resolved
nickitat and others added 4 commits August 18, 2026 21:41
…nnounced' into fix-parallel-replicas-cancel-unannounced
On the first `Cancel`, `processCancel` returns without setting `stop_query`
when `allow_partial_result_on_first_cancel` is set - "return what you have"
rather than stop. Secondary queries inherit `partial_result_on_first_cancel`
from the initiator (it is applied in `receiveQuery` with no check for an
initial query), so the forced probe added by `Do not wait out a replica's
planning to cancel it` could see the `Cancel`, leave `stop_query` unset, and
let `checkIfQueryCanceled` pass. The replica then went on to announce to an
initiator that had already skipped the drain and disconnected, which is the
`Broken pipe` this branch exists to remove:

    DB::NetException: I/O error: Broken pipe, while writing to socket
    (127.0.0.3:9377 -> 127.0.0.1:33468). (NETWORK_ERROR)

With `partial_result_on_first_cancel = 1` both followers announced and died
that way; with it unset neither announced. A replica that has not announced
yet has no partial result to return, so the setting is turned off for the whole
exchange - the probe, the announcement, and the response, which calls
`processCancel` again - the same way `readTemporaryTables` does it. Both
followers now end in `ExceptionBeforeStart` without announcing, as they do
without the setting.

Only the asynchronous socket is affected: with `async_socket_for_remote = 0`
the initiator is still blocked reading the announcement, so the write lands.
The test covers that combination and asserts no follower announced and none saw
a broken pipe. Removing the guard again fails it 5 runs out of 5; 20 runs pass
with it (10 without settings randomization, 10 with).

Co-Authored-By: Claude Opus 5 <[email protected]>
Merging master moved this block into the external tables initializer. Both it
and the announcement callback contain the same two lines

    std::lock_guard lock(*callback_mutex);
    checkIfQueryCanceled(*query_state);

and master rewrote `TCPHandler.cpp` around them, so the hunk applied cleanly to
the wrong one. It compiles, and it breaks every query: the forced
`receivePacketsExpectCancel` runs before `readTemporaryTables` and eats the
empty `Data` block the client sends to end its external tables, so the server
answers `Unknown packet from client 2` on every connection.

That is what the `Fast test` failure was - `select 1` failed ~60 times in a row
and the server was never considered started. It reproduced on a rerun because
the merge result is deterministic, and only in CI because CI builds the merge
ref (`GIT_HASH 063a246`, `Merge 5e30e29 into 18fcc60`), not the branch head.

Co-Authored-By: Claude Opus 5 <[email protected]>
@nickitat
nickitat marked this pull request as ready for review August 19, 2026 18:26
@nickitat
nickitat requested a review from devcrafter August 19, 2026 18:26
@devcrafter devcrafter self-assigned this Aug 25, 2026
@devcrafter
devcrafter requested a balanced review from Copilot August 25, 2026 10:08

Copilot AI left a comment

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.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Reduces distributed query cancellation latency for parallel replicas by allowing the initiator to stop waiting for a follower’s initial announcement after cancellation, and adds coverage to prevent regressions.

Changes:

  • Add a new stateless test including failpoints to reproduce “cancel before announcement” and validate latency/connection safety.
  • Introduce a new failpoint to delay follower announcements and make the follower check for Cancel immediately during announcement exchange.
  • Allow RemoteQueryExecutor to skip draining an in-flight packet on cancel (pre-announcement) and force-disconnect such connections to avoid pool reuse.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tests/queries/0_stateless/04839_parallel_replicas_cancel_before_announcement.sh New regression test exercising cancellation before initial announcement across socket/sending modes.
tests/queries/0_stateless/04839_parallel_replicas_cancel_before_announcement.reference Expected output for the new stateless test.
src/Server/TCPHandler.h Adds a force flag to bypass interactive-delay when checking for Cancel.
src/Server/TCPHandler.cpp Adds announcement-delay failpoint and forces immediate Cancel check during announcement exchange; disables partial-result-on-cancel for this stage.
src/QueryPipeline/RemoteQueryExecutorReadContext.h Adds skipDrainOnCancel() flag to allow cancellation without draining in-flight packet.
src/QueryPipeline/RemoteQueryExecutorReadContext.cpp Implements conditional drain-wait skipping during cancel.
src/QueryPipeline/RemoteQueryExecutor.h Tracks whether announcement was received and whether drain was skipped.
src/QueryPipeline/RemoteQueryExecutor.cpp Skips drain on cancel before announcement and disconnects (instead of pooling) when drain was skipped.
src/Common/FailPoint.cpp Registers the new parallel_replicas_delay_announcement failpoint.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

[[ $running -eq 0 ]] && break
sleep 0.25
done

Comment thread src/Server/TCPHandler.cpp
CurrentMetrics::Increment callback_metric_increment(CurrentMetrics::MergeTreeAllRangesAnnouncementsSent);

/// Stands in for a follower that is still planning while the initiator gives up on it.
fiu_do_on(FailPoints::parallel_replicas_delay_announcement, { sleepForMilliseconds(3000); });
Comment thread src/Server/TCPHandler.cpp
/// disconnected (`Broken pipe`). Secondary queries inherit
/// `partial_result_on_first_cancel` from the initiator, so this has to be turned off
/// explicitly, the same way `readTemporaryTables` does it.
auto off_setting_guard = TurnOffBoolSettingTemporary(query_state->allow_partial_result_on_first_cancel);
#if defined(OS_LINUX) || defined(OS_DARWIN)

#include <QueryPipeline/RemoteQueryExecutorReadContext.h>
#include <Common/OpenTelemetryTraceContext.h>

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.

it seems unnecessary

@nickitat
nickitat added this pull request to the merge queue Aug 26, 2026
Merged via the queue into master with commit a4311d3 Aug 26, 2026
176 checks passed
@nickitat
nickitat deleted the fix-parallel-replicas-cancel-unannounced branch August 26, 2026 10:39
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
fm4v pushed a commit to BoloniniD/ClickHouse that referenced this pull request Oct 1, 2026
The test failed on master in `Stateless tests (amd_tsan, s3 storage,
sequential, 2/2)`: `partial_result_on_first_cancel did_not_wait` became 0
because the timed query took 1652 ms against the 1500 ms bound.

On the s3 lanes the test table lived on the object-storage disk. Opening a
part there takes `MetadataStorageFromDisk::metadata_mutex` shared, and every
metadata commit on that disk (`MetadataStorageFromDiskTransaction::commit`)
holds it exclusively. In the failing job a `system.metric_log` merge with
2184 columns held it for about 1.6 s and the one-granule read waited for it;
commits in the same job took up to 2.6 s, so no bound below the 3 s
`parallel_replicas_delay_announcement` delay is safe. The table now uses
`storage_policy = 'default'`, the local disk, which has no disk-wide
metadata lock. Nothing the test guards is storage-specific.

The failing run had also drawn `automatic_parallel_replicas_mode = 2`
(p = 0.25 in the runner), which only collects statistics and runs the
single-node plan: no follower was contacted, so such a run cannot catch the
regression the test exists for. `automatic_parallel_replicas_mode = 0` is
added to the test's own parallel-replicas settings, which every timed query
uses. A `Random settings limits` clamp is not used, because the runner
applies the mode-2 bundle (client-level `enable_parallel_replicas = 1` and
friends) before the clamp, which would turn every auxiliary query of the
test into a parallel-replicas query while the delay failpoint is enabled.

Validated on a debug build: a one-granule read of an s3 table waits up to
337 ms in `readMetadata` during concurrent 2000-column inserts while the same
read of a `default`-policy table takes at most 7 ms; with a forced client-level
mode 2 the old test runs no parallel replicas and the new one uses them in
every timed query; with the initiator fix of ClickHouse#114862 reverted the new test
fails 10/10 randomized and 5/5 in mode 2, while the old one passes in mode 2;
50/50 randomized runs pass on a local-disk and on an s3-backed server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance 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