Skip to content

Make the owner wait of cluster_function_wait_for_replica_ms cancellable - #133412

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:cluster-function-wait-for-replica-cancellation
Nov 21, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:cluster-function-wait-for-replica-cancellation

Conversation

@groeneai

@groeneai groeneai commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125611
Related: #130812
Related: #126101

Changelog category (leave one):

  • Improvement

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

KILL QUERY, max_execution_time, an error in another part of the query and a satisfied LIMIT now end the wait of cluster_function_wait_for_replica_ms for a replica of a *Cluster table function or of parallel replicas over object storage. Before, the query and its cancellation waited for the whole interval.

Description

Stress test (arm_release) hung on an unrelated PR (report): a fuzzed icebergLocalCluster('test_cluster_two_shards', ...) SETTINGS cluster_function_wait_for_replica_ms = 9223372036854775 with max_threads = 1 ran 1484 s with is_cancelled = 1.

Once the iterator is exhausted, StorageObjectStorageStableTaskDistributor waits for a replica that has not asked for tasks yet, in the read-task callback under RemoteQueryExecutor::was_cancelled_mutex, and nothing checked the query: cancelQuery blocks in RemoteQueryExecutor::cancel on that mutex. Since #130812 such a huge value never ends.

The wait now polls QueryStatus::checkTimeLimit() every 100 ms, like other waits on behalf of a query. It throws on KILL QUERY and on max_execution_time; with timeout_overflow_mode = 'break' the replica gets no more tasks. Reverting #130812 would bring back the overflow of #126101; smaller values have waited uncancellably since #125611.

RemoteQueryExecutor::cancel and finish also set a flag, checked by the wait, before taking the mutex: the pipeline calls them without cancelQuery when another branch of the query throws or a LIMIT is satisfied.

With fewer initiator threads than replicas, an owner's request can still sit behind the wait for the whole interval, but KILL QUERY and max_execution_time end it: of 10 runs of the CI query (limit 10 s), 2 ended with TIMEOUT_EXCEEDED at 10 s and 8 returned the result; master still ran after 52 s.

The test reads 20 files with an unreachable second replica (test_unavailable_shard) and ends the 60 s wait with max_execution_time = 2, KILL QUERY ... SYNC, and a throwIf or a LIMIT in another UNION ALL branch: without the fix each takes 60 s, with it 1-2 s (50/50 randomized runs).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.12.1.140-master (included in 26.12 and later)

groeneai and others added 2 commits November 21, 2026 14:37
…able

When the file iterator is exhausted, `StorageObjectStorageStableTaskDistributor::getAnyUnprocessedFile`
waits on `replica_seen_cv` until `cluster_function_wait_for_replica_ms` passes for a replica that has not
asked for tasks yet. The wait runs inside the read-task callback, on an initiator pipeline thread that
holds `RemoteQueryExecutor::was_cancelled_mutex`, and nothing checked the query or notified the cv on
cancellation: `QueryStatus::cancelQuery` blocks in `RemoteQueryExecutor::cancel` on that same mutex.
So `KILL QUERY` and `max_execution_time` waited for the whole interval, and since the deadline saturates
for huge values (ClickHouse#130812) such a query never ended. This hung the Stress test (arm_release) on PR ClickHouse#115722
for a fuzzed `icebergLocalCluster('test_cluster_two_shards', ...)` query with `max_threads = 1`.

The wait now polls `QueryStatus::checkTimeLimit()` every 100 ms, as the other waits on a query's behalf
do (ZooKeeperWaitLimit, DatabaseReplicated, the worker side ReadTaskIterator::next). `cancelQuery` sets
`is_killed` before cancelling the executors, so the waiter sees it while the canceller is blocked, throws,
and the unwinding releases `was_cancelled_mutex`. With `timeout_overflow_mode = 'break'` the replica gets
an empty task. The query status comes from `getProcessListElementSafe()` of the query context; the
gtests construct the distributor without one and keep their behaviour.

With fewer initiator threads than replicas the owner's request can still sit behind the wait, so the
query can still wait until `cluster_function_wait_for_replica_ms`, but that wait now ends on
`KILL QUERY` and at `max_execution_time`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
⚠️ The regression test did not cover KILL QUERY, only max_execution_time (a deadline-only bound would have passed it) AGREE, the test now also kills the waiting query
💡 The fixture relies on the distributor listing a replica that the cluster read skips as unreachable noted, deterministic today
💡 The wait still covers replicas skipped as unavailable or beyond max_parallel_replicas, and an owner's request that queues behind it when the initiator has fewer threads than replicas behaviour of #125611, not changed here; KILL QUERY and max_execution_time end it in both cases

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test (unreachable second replica of test_unavailable_shard) fails on every master run: the max_execution_time = 2 queries take 60 s. The CI value (9223372036854775) hangs on master on demand: is_cancelled = 1, KILL QUERY ... SYNC does not return.
b Root cause explained? getAnyUnprocessedFile waits on replica_seen_cv for a replica that has not asked for tasks, inside the read-task callback under RemoteQueryExecutor::was_cancelled_mutex. Nothing checked the query, and cancelQuery blocks in RemoteQueryExecutor::cancel on that mutex, so cancellation waited for the whole interval (forever for saturated values since #130812).
c Fix matches root cause? Yes. The wait polls QueryStatus::checkTimeLimit() every 100 ms. cancelQuery sets is_killed before cancelling the executors, so the waiter sees it, throws, and unwinding releases the mutex. No bound widened, no setting clamped.
d Test intent preserved / new tests added? New 05839_cluster_function_wait_for_replica_ms_cancellation, with a control query that proves the fixture waits and a case that ends the wait with KILL QUERY ... SYNC. Existing RendezvousHashing* gtests unchanged, 15/15 OK.
e Both directions demonstrated? Test: master FAIL (60 s per query, the killed one included), fix OK (2 s, killed query 1 s), 50/50 randomized. CI value: master hangs, fix ends with TIMEOUT_EXCEEDED in 5.2 s; KILL QUERY SYNC returns in 0.24 s. Server build IDs checked.
f Fix is general across code paths? It is the only wait in the read-task callback whose length is a user setting. Iterator, Iceberg and bucket-splitter waits are bounded by other threads' I/O; URL/File cluster callbacks and the parallel replicas coordinator do not wait; the worker side already checks checkTimeLimit(). read and readAsync share the callee.
g Fix generalizes across inputs (params/datatypes/wrappers)? Setting 0 (no wait, unchanged), 1000, 60000 and the saturated maximum; timeout_overflow_mode throw and break; KILL QUERY; max_threads = 1 and randomized. No data types involved.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default, protocol or format change; the default 0 never reaches the wait.
i Invariants and contracts preserved? The deadline arithmetic of #130812 is unchanged. On throw both locks are released by RAII (the existing error path); on break the replica is marked finished as on the existing exit. checkTimeLimit() takes only QueryStatus::cancel_mutex and never calls cancelQuery: no lock inversion, no re-entry.

Session id: cron:clickhouse-impl-slot-6:20261121-140700

@clickhouse-gh

clickhouse-gh Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f830baa]

Summary: ✅


AI Review

Summary

The PR makes the replica-owner wait respect query cancellation, execution deadlines, sibling failures, and a satisfied LIMIT. Reviewed head f830baa7302f34a513760f03de450c35c104757c, including all prior discussion. The earlier blocker is addressed by publishing executor cancellation before acquiring was_cancelled_mutex, with regression coverage in 05839_cluster_function_wait_for_replica_ms_cancellation. No remaining findings.

Missing context / blind spots
  • ⚠️ No built ClickHouse server is available locally, so runtime tests were not rerun. Runtime evidence comes from the author's reported regression runs. The available CI report still requires the full suite to rerun after the earlier review thread was resolved; it does not establish a full-suite pass.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements can be tested Allows running workflows for external contributors comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. labels Nov 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f830baa73 with master 6886cedd2 (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

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

Job report

… finished

A read task request of a cluster function replica is served under
`RemoteQueryExecutor::was_cancelled_mutex`, so while the distributor waits
for the files of a replica that has not asked for tasks yet, `cancel` and
`finish` of the waiting executor block on that mutex. The pipeline calls
them when another branch of the query throws (`cancelWithException`) or a
`LIMIT` is satisfied (`onUpdatePorts`). Neither sets `is_killed`, so the
`checkTimeLimit` step of the previous commit kept waiting, and the error or
the end of the query came only after `cluster_function_wait_for_replica_ms`
(never with the saturated value).

`cancel` and `finish` now set an atomic flag before they take the mutex.
The task iterator receives the flag, and the sliced wait returns an empty
task once it is set.

Measured with `cluster_function_wait_for_replica_ms = 30000`: a `throwIf` in a
`UNION ALL` branch 30.11 s -> 4.62 s, a satisfied `LIMIT` 30.13 s -> 0.93 s.

Found by the AI review: ClickHouse#133412 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Nov 21, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 21, 2026
Merged via the queue into ClickHouse:master with commit 887a78e Nov 21, 2026
383 of 384 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 21, 2026
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-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. pr-improvement Pull request with some product 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.

3 participants