Skip to content

Observe query cancellation in the distributed connection retry loop - #112689

Merged
PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-cancellation-in-distributed-connect-retry
Aug 7, 2026
Merged

PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-cancellation-in-distributed-connect-retry

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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):

Fixes max_execution_time and KILL QUERY being silently ineffective for a distributed query that is establishing connections to replicas. Such a query now stops at the next connection attempt instead of working through every remaining replica and retry.

Description

Found on master by Stress test (arm_release), reported as a hung check (CI report). The hung system.processes row had elapsed = 909.94, is_cancelled = 1, max_execution_time = 60 and DistributedConnectionFailAtAll = 149. 149 unreachable addresses x 3 tries x a 2 s connect timeout accounts for 894 s of that: no lock, the query just keeps dialing.

Root cause: nothing on the connection-establishment path observes cancellation, so once PoolWithFailoverBase::getMany is entered it performs nested_pools.size() x connections_with_failover_max_tries blocking connects regardless of is_killed.

The fix adds CurrentThread::checkIfNotCancelled to ConnectionEstablisher::run, the single place every distributed connection attempt passes through, so the synchronous pool, hedged requests and parallel replicas are all covered. Two call sites are needed. One at the top of the retry loop stops the query before the next blocking connect. One on the soft-failure return covers the final attempt, which the loop top can never reach; without it a query cancelled while the last connect is in flight is still reported as ALL_CONNECTION_TRIES_FAILED, which the caller turns into a next-shard retry.

Measured with 40 addresses from the reserved 198.51.100.0/24 range and max_execution_time = 3: 240 s and ALL_CONNECTION_TRIES_FAILED before, ~4.1 s and TIMEOUT_EXCEEDED after. Under KILL QUERY the query kept dialing a further 234 s before and now stops in ~2 s with QUERY_WAS_CANCELLED. The test runs four cases, pinning use_hedged_requests at both values to cover the synchronous pool and the asynchronous establisher, and asserts elapsed time, the reported code, and the attempt count read back from system.query_log. Removing either call site reddens it. One residue is deliberate: on the asynchronous path the final attempt completes outside the fiber, so its reported code is unchanged, bounded by one connect timeout rather than the full grind. The parallel-replicas path builds the same establisher and is covered by construction, not separately reproduced.

groeneai and others added 6 commits July 29, 2026 21:15
A cancelled or timed-out distributed query kept dialing unreachable
replicas until every pool and every retry was exhausted. Found on master
by Stress test (arm_release) as a hung check: the query had
elapsed = 909.94, is_cancelled = 1 and max_execution_time = 60, with
DistributedConnectionFailAtAll = 149. That is 149 unreachable addresses
times 3 tries times a 2 s connect timeout, so the wall clock was fully
explained by serialized blocking connects with no lock and no deadlock.

Nothing on the connection-establishment path observed cancellation, so
PoolWithFailoverBase::getMany ran to completion regardless of is_killed.
The cancellation itself was already available: it is armed when the query
enters the process list, long before the analyzer resolves the table
function and reaches this loop, so this was purely a missing observation
point.

Check for cancellation at the top of the retry loop in
ConnectionEstablisher::run. That is the single place every distributed
connection attempt passes through, so it covers the synchronous pool
(and therefore every public pool entry point and every PoolMode), hedged
requests via ConnectionEstablisherAsync, and the parallel-replicas path
that constructs the establisher directly without touching the pool. It
also covers the establisher's own pooled-connection reconnect-retry.

The check is a sibling of the surrounding try rather than a statement
inside it, so the throw cannot be absorbed by that block's network-error
allowlist and converted into a soft failure. It throws a plain Exception,
not a NetException, which matters because the caller swallows
NetException and advances to the next shard.

Measured with 40 non-routable addresses and max_execution_time = 3:
240.29 s and ALL_CONNECTION_TRIES_FAILED before, 4.11 s and
TIMEOUT_EXCEEDED after. Under KILL QUERY the query kept dialing for a
further 234.12 s before, and stops after 2.02 s now, reporting
QUERY_WAS_CANCELLED.

No setting, default or serialized format changes, so no
SettingsChangesHistory.cpp entry is needed. The cost is one thread-local
load per connection attempt, beside a multi-millisecond network
operation.

Co-Authored-By: Claude Fable 5 <[email protected]>
Use an RFC 5737 reserved address range instead of an actively allocated one,
pin use_hedged_requests and assert both branches, and tighten the elapsed
bound so it pins the claim that the query stops at the next attempt.

128.1.2.0/24 is an active ARIN allocation, so its routing and latency were
externally mutable even though the test called it non-routable, and the whole
240 s timing budget rested on every dial blocking for the full connect
timeout. 198.51.100.0/24 is TEST-NET-2, reserved and guaranteed never routed;
it was measured to time out after the same 2.5 s per connect.

use_hedged_requests selects a different IConnections implementation and is
randomized by the test runner, so which of the two code paths the test
exercised was a coin flip and the serialized-timeout arithmetic only holds on
the synchronous one. Both values are now pinned on the client command line and
run as separate labelled cases. The pin wins over the runner's injected value
because the runner appends --allow_repeated_settings, under which the last
occurrence takes effect.

The elapsed bound moves from 60 s to 15 s. The post-fix window is the 3 s
deadline plus at most one connect already in flight, and each extra attempt
costs 2 s, so 60 s tolerated about 28 extra attempts and could not distinguish
stopping at the next attempt from stopping within 28 more. 15 s admits at most
6 while keeping a 3.3x margin over the slowest of 50 randomized runs.

Removing the checkpoint from ConnectionEstablisher::run reddens both cases at
240 s with ALL_CONNECTION_TRIES_FAILED, so both assertions are load-bearing on
both code paths.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The check at the top of the attempt loop in ConnectionEstablisher::run cannot
cover the last attempt, because there is no next iteration to reach it. A query
cancelled while the final connect was in flight therefore left the establisher
reporting an ordinary soft failure, and the caller reported
ALL_CONNECTION_TRIES_FAILED instead of the cancellation. Since that is a
NetException, getStructureOfRemoteTable then treated it as a reason to move on
to the next shard, which is what this fix exists to prevent.

Add a second checkpoint on the soft-failure return path in the catch block, the
single exit through which every non-retried attempt failure leaves the
establisher. The two checkpoints are complementary rather than redundant, and
they split by carrier: the one in the catch covers the synchronous path, and the
one at the loop top is the only cover for the asynchronous path, which finishes
a terminal attempt outside the fiber in ConnectionEstablisherAsync::checkTimeout
and so never re-enters the catch. Removing either one reddens a different case
of the test.

Extend the test with three assertions. An attempt-count oracle read from
system.query_log ProfileEvents pins "stops at the next attempt" (2 attempts with
the fix, 120 without), which an elapsed-time bound cannot do. A one-address case
with a deadline shorter than the connect timeout covers the terminal window. A
KILL QUERY case covers the cancellation reason that yields QUERY_WAS_CANCELLED
rather than TIMEOUT_EXCEEDED; that behaviour was previously only measured by
hand.

Also verify at runtime that the reserved address range actually blocks. RFC 5737
recommends filtering such traffic but does not mandate dropping it, and on a
host that refuses instead every assertion would fail with a misleading error
rather than naming the unusable fixture.

Co-Authored-By: Claude Fable 5 <[email protected]>
The precondition probe timed the connect with $SECONDS, which counts tick
boundaries crossed rather than time elapsed, so a sub-second refusal that
straddled a tick read as 1 second and was accepted as a genuine block. On such
a host every case then failed with a misleading "wrong error" instead of the
probe's own message. Measured over 40 refusals on a rejecting endpoint, the
integer clock accepted the useless fixture 4 times; the millisecond clock
accepted it 0 times, with the refusal at ~0.1 s against a ~2.1 s real block.

The deadline cases admitted up to 4 connection attempts where the fixture only
permits 2: each connect takes the full 2 s timeout, so against the 3 s deadline
only the attempts starting at t~0 and t~2 can begin before cancellation. The
measured value is 2 for both use_hedged_requests values, so the old ceiling left
room for two further replicas to be dialed after cancellation and still pass.

The KILL case asserted only elapsed time and the error code, and its 15 s bound
tolerates about six further dials. It now reads the attempt counter before the
kill and after it and requires the difference to be at most one, the attempt
already in flight. A fixed ceiling is not derivable there because the kill is
sent only once the query is visible in system.processes, so the poll latency
decides how many attempts precede it; the delta measures what the fix is about.
Without the fix that delta is 119.

Also record why the terminal case's 1 s deadline against a 5 s connect is
reliable rather than lucky, and state that on the asynchronous path the
establisher's catch is structurally unreachable, not merely prevented from
throwing.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ceiling

The test asserts that a cancelled distributed query starts at most two
connection attempts. That ceiling is only sound if each attempt lasts long
enough that a third cannot begin before cancellation is observed. Attempts are
sequential, so with a per-attempt duration D they start at t = 0, D, 2D, ...,
and cancellation for the three second deadline lands no later than 3099 ms
because CancellationChecker rounds the deadline up to the next 100 ms grid
boundary and never down. At most two attempts start iff 2 * D >= 3099, that is
D >= 1550 ms.

The precondition probe accepted any D >= 1000 ms, leaving a 1000-1549 ms band
in which a correct implementation may legitimately begin a third attempt and
redden the assertion. That band is reachable: the probe exists precisely because
RFC 5737 only recommends filtering the reserved range, so a host that answers
after roughly a second passes the probe and then fails the test with a
misleading attempt count.

Raise the bound to 1550 and derive it in the comment instead of asserting it.
The separation from the fixture's two real behaviours stays wide in both
directions: a refusal takes 64-96 ms on the test host, 16x below the bound, and
a genuine block 2073-2120 ms against the 2000 ms connect timeout, 1.34x above
it. No source file, test setting or reference line changes, and the two-attempt
ceiling is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two test-only oracle corrections. No source file changes.

The fixture probe checked whether the reserved address range blocks by timing
the whole clickhouse-client invocation, but the two-attempt ceiling it feeds is
derived from the per-attempt connect duration D. The client figure exceeds D by
startup, local connection, exception propagation and output handling, measured
here at 78 to 90 ms, so a true D as low as about 1460 ms measured above the
1550 ms bound, was accepted, and then permitted a third attempt on a correct
implementation. The probe now reads the server-side query_duration_ms of its own
one-address one-try query from system.query_log, which starts inside
executeQueryImpl and therefore excludes all of that. Its only residual is the
analysis remainder, measured against a refusing endpoint (where D is about zero)
at no more than 1 ms over 40 trials, 20 idle and 20 at load average 110. Since
accepting on figure >= threshold accepts D >= threshold - residual, and the
inequality needs D >= 1549.5 ms, the bound becomes 1551. An exhaustive sweep of
D over 1000 to 2100 ms at 0.1 ms resolution confirms nothing permitting more
than two attempts is admitted, and that the smallest accepted D is 1550.0 ms.
Separation in practice is three orders of magnitude either side: a refusal
measures 0 to 1 ms, a genuine block 2001 to 2052 ms.

The KILL QUERY case allowed the attempt count to grow by one after cancellation,
justified as the attempt already in flight. DistributedConnectionTries is
incremented as the first statement of try_establish, before the connect, so it
counts attempts that start: the in-flight attempt is already inside the before
sample and its completion adds nothing, which made a delta of one mean a
brand-new attempt begun on a cancelled query. The kill is now issued ASYNC, so
is_killed is set when the statement returns, and the before count is read from a
system.processes row that already shows is_cancelled, with both fields taken
from one snapshot per row. The delta must now be exactly zero, and the case says
so loudly if is_cancelled is never observed rather than passing.

Measured: 50 of 50 runs green on the shipped content, all 50 kill rows reading
exactly one attempt. With both cancellation checkpoints removed the same block
reads "kill went from 1 to 120 attempts", so the tightened line reddens as a
non-zero delta rather than a missing counter. A synthetic delta of one passes
the old oracle and fails the new one.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 6 rounds, 20 findings adjudicated, 18 fixed, 2 disagreed with evidence in the final round

An independent model reviewed this change against the diff and the source in six rounds, and I ran
my own cold review of the resulting code each round before reading the accumulated evidence. Every
finding was adjudicated by verifying it in the code, not by accepting or rejecting it on assertion.
Cumulative gate findings: 17 (3 blocker, 14 major) across six rounds; 18 items fixed in total.

❌ Fixed in this PR (selected)

Finding Action
Two nested cancellation checkpoints on the terminal path could report a cancelled query as NETWORK_ERROR rather than the cancellation. Reduced to one checkpoint on the soft-failure return, placed after the stale-connection retry continue so a legitimate reconnect is not aborted.
The test dialled 128.1.2.0/24, described as non-routable, but ARIN RDAP reports it as an ACTIVE allocation whose routing and latency are externally mutable. Switched to 198.51.100.0/24 (RFC 5737 TEST-NET-2, reserved and never routed), and added a precondition probe that verifies the range actually blocks rather than assuming it.
use_hedged_requests is randomized by the stateless runner and selects a different IConnections implementation, so the test picked the synchronous or hedged path by coin flip. Pinned on the client command line and exercised at both values as two labelled cases.
The elapsed assertion < 60 s could not distinguish "stops at the next attempt" from "stops within ~28 attempts". Tightened to 15 s and, more importantly, added an attempt-count oracle read back from system.query_log: <= 2, against 120 pre-fix, a 60x separation.
KILL QUERY was uncovered, so an implementation observing only the deadline would pass every case. Added an explicit kill case asserting QUERY_WAS_CANCELLED, a different cancel reason and error code from the three deadline cases.
The kill case allowed the attempt count to grow by one after cancellation. Since DistributedConnectionTries is incremented as the first statement of try_establish, before the connect, the in-flight attempt is already inside the baseline, so a delta of one meant a brand-new attempt on a cancelled query. Delta tightened to exactly zero, the kill issued ASYNC so is_killed is set when the statement returns, and the baseline read from a system.processes row that already shows is_cancelled. Proven non-vacuous by extracting both predicates verbatim and driving them over synthetic pairs: a delta of one passes the old oracle and fails the new one.
The precondition probe timed the whole clickhouse-client invocation, which exceeds the per-attempt connect duration by 78 to 90 ms of startup and output handling, so a true per-attempt duration around 1460 ms measured above the bound and then permitted a third attempt on a correct implementation. The probe now reads the server-side query_duration_ms of its own one-address one-try query. Its residual is the analysis remainder, measured at no more than 1 ms over 40 trials, 20 idle and 20 at load average 110. The bound is derived rather than picked: 2 * D >= 3099 gives D >= 1549.5, plus the residual, so 1551.

⚠️ Disagreed, with evidence (final round)

"The two-attempt ceiling relies on timing upper bounds the implementation does not guarantee, so
correct code can fail under load."
The necessary step is that cancellation is delayed past 4000 ms
so a third attempt begins on a correct implementation. The assertion is not a deadline assertion: an
attempt can only start by passing the checkpoint this PR adds, which throws once is_killed is set,
so a late wake-up does not let the query pass, it just moves which attempt terminates. The cited
delay is also not unbounded in the cited code: CancellationChecker::workerFunction is a dedicated
thread whose wait_for is armed on the earliest deadline with an explicit re-arm guard so an earlier
deadline cannot be swallowed, and its batch loop drains all expired tasks per wake-up rather than
one. Measured: 2 attempts on 20 of 20 arms, and the one quantity called an empirical observation is
the one that was stressed, at load average 110 with 8 concurrent CPU burners, giving a p99 of 1 ms.
Residual disclosed: fully removing the timing dependence needs a failpoint that pauses the
establisher at a known attempt boundary, which is a src/ change and belongs in its own PR.

"The kill baseline is sampled after cancellation, so a post-kill attempt that starts before the
sample is hidden."
The necessary step is that an attempt starts inside the window between KILL
setting is_killed and the baseline SELECT. The kill is issued within one 0.1 s poll of the first
attempt starting, and each attempt blocks for the full 2000 ms connect, so at kill time the query is
roughly 1.8 s from its next attempt boundary while the baseline SELECT completes in milliseconds.
Measured kill-to-exit is 1776 to 1978 ms, consistent with the kill landing early in the first
attempt. Independently, on correct code no attempt can start after the kill at all, and a broken fix
produces 120 attempts, which no one-attempt window can absorb. is_cancelled and the counters come
from a single getInfo(true, true, true) call per row, so the pair cannot straddle a boundary the
2 s connect guarantees is absent. Same residual and same reason as above.

💡 Noted, not blocking

Connection::connect loops over the DNS-resolved addresses of a single host, each iteration up to
the full connect timeout, with no checkpoint. The checkpoints added here sit one level out, per host
and try, so a cancelled query can still spend the address count times the connect timeout inside one
attempt. That is bounded by the A and AAAA records of one host, typically one or two, against the
outer loop's 149 addresses times 3 tries which is what produced the reported 910 s. Closing it needs
a layering decision between Common/ and Client/, so it is left for its own change.

Session id: cron:clickhouse-review-slot-8:20260730-233600

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

a-i validation checklist (click to expand)
# Criterion Answer
a Deterministic repro? YES. SELECT count() FROM remote('198.51.100.{1..40}', system.one) FORMAT Null with --connections_with_failover_max_tries 3 --connect_timeout_with_failover_ms 2000 --max_execution_time 3. Pre-fix: 240.29 s, code 519/279. Exactly the predicted 40 x 3 x 2 s, matching the CI artifact's own 149 x 3 x 2 = 894 s vs 909.94 s. I measured first that the address range really blocks rather than assuming it: a raw TCP connect to 198.51.100.1 / .20 / .40 on port 9000 returns TIMEOUT after 2.503 s each, so the 240 s budget is real. The range is RFC 5737 TEST-NET-2, reserved and guaranteed never routed, so the budget cannot be invalidated by an external routing change.
b Root cause explained? YES. PoolWithFailoverBase::getMany retries every pool without ever observing cancellation or the time limit (isCancelled/checkTimeLimit/CancellationChecker/QueryStatus have 0 hits in the three files on the stack), so once entered it performs nested_pools.size() x connections_with_failover_max_tries blocking connects regardless of is_killed. The cancellation is armed when the query enters the process list, long before the analyzer resolves the table function and reaches this loop.
c Fix matches root cause? YES. Adds the missing interruption point, one CurrentThread::checkIfNotCancelled() at the retry-loop head. Not a timeout tweak, not a settings cap, not a test tag: those would leave max_execution_time unenforced on this path.
d Test intent preserved / new test added? YES. New 04652_distributed_connect_retry_cancellation.sh asserts, per case, an elapsed bound, the reported error code, and the number of connection attempts read back from the counters, so it distinguishes "stops at the next attempt" from "merely finished sooner" rather than resting on timing alone. Each ceiling is derived from what the fixture permits, not rounded up: at most 2 attempts for the deadline cases, and, after a KILL QUERY, no further attempt at all. The kill case is an exact zero rather than a tolerance because DistributedConnectionTries is incremented before the connect, so the attempt already in flight when the kill lands is inside the "before" sample and any increase is a new attempt begun on a cancelled query; that sample is taken from a system.processes row already showing is_cancelled, so the delta spans only post-cancellation attempts. A precondition probe verifies that the reserved address range really blocks, measuring the server-side query_duration_ms of its own one-address one-try query rather than client wall clock, so the figure compared against the bound is the per-attempt duration the 2-attempt ceiling is derived from and not that duration plus ~80-105 ms of client overhead; on a host that refuses instead the test says so explicitly rather than failing with a misleading wrong-error message. Every assertion line is proven load-bearing individually. No existing test weakened or retagged.
e Both directions demonstrated? YES. Timeout arm 240.29 s / 519 -> 4.11 s / 159. KILL QUERY arm: kept dialing 234.12 s after the kill -> 2.02 s, code 394. Attempt counters over the same two arms: 120 -> 2 for the deadline cases, and for the kill case the shipped oracle now reads the post-cancellation delta, measured 119 -> 0 (pre-fix kill went from 1 to 120 attempts; post-fix 50 of 50 kill rows read exactly 1 attempt, so the is_cancelled-visible sample and the final count agree). The whole shipped test was also run against an unmodified master build, where all 10 of its 10 reference lines redden. Every arm was a real rebuild with a moved Build ID, or in the unmodified-master case a binary whose source was md5-verified against origin/master, and the server's SELECT buildId() was checked against readelf -n before each verdict.
f General across CODE paths? YES. Anchored on ConnectionEstablisher::run, the one abstraction all three carriers pass through: the synchronous pool (covering all five public pool entry points and every PoolMode), hedged requests (via ConnectionEstablisherAsync::Task::run), and parallel replicas, which constructs the establisher directly and never touches the pool. That last one is exactly what a tryGetEntry-anchored fix would have missed. IConnectionPool is the only PoolWithFailoverBase instantiation, so no other pool type is left unfixed. Two of the three carriers are now measured in both directions: the test pins use_hedged_requests and runs the synchronous and hedged branches as separate labelled cases, and the mutant reddens both (240.18 s and 240.15 s). The parallel-replicas carrier remains covered by construction only.
g Generalizes across INPUTS? YES. The guard is input-independent: it fires once per connection attempt regardless of address count, settings or replica topology, and covers both the timeout and KILL QUERY sources of cancellation. It also guards the establisher's own pooled-connection reconnect-retry continue, not just the first attempt. The one input that selects a different code path, use_hedged_requests, is randomized by the test runner, so the test pins it on the client command line and asserts both values; the pin is proven to win over the runner's injected value, since the runner appends --allow_repeated_settings under which the last occurrence takes effect. Verified as a no-op where there is no query thread group, so background async-INSERT flushing is unaffected.
h Backward compatible? YES. No setting, default or serialized format touched, no header modified (one TU recompiles), so no SettingsChangesHistory.cpp entry is required. The only behaviour change is that a cancelled or timed-out distributed query fails fast with 159/394 instead of returning 279/519 after the full grind, which is the documented meaning of max_execution_time and KILL QUERY.
i Invariants and contracts preserved? YES. The call sits outside the sole try, so it cannot be absorbed by that block's 7-code network allowlist and the soft fail_message contract for genuine network failures is untouched. It throws a plain Exception, not a NetException, which is load-bearing: the caller's catch (const NetException &) { continue; } would otherwise swallow it and advance to the next shard. Fiber safety on the hedged path is measured in both directions with the setting pinned (mutant 240.15 s / code 519, fixed 4.08-4.11 s / code 159), with no abort, the server alive afterwards and 0 fatal or sanitizer lines. Cost is one thread-local load per multi-millisecond network operation.

Mutation testing. Removing the call reddens the new test: 240.95 s initially, and re-run against the two pinned cases it reddens both of them (240.18 s synchronous, 240.15 s hedged, code 519, no TIMEOUT_EXCEEDED; the runner reports FAIL 480.85 sec). Restoring the call returns the test to green. Restoration is evidenced by an identical source md5, an empty src/ diff, the symbol present in the binary and both cases measuring 4.17 s / 4.11 s with code 159 again; the Build ID does not return to its earlier value because the relink is not bit-reproducible, so behaviour is the proof rather than the hash. Independently of the mutants, the shipped test was run against the nightly pristine-master snapshot binary (its ConnectionEstablisher.cpp md5-identical to origin/master and to this branch's merge base, and containing none of the guard), where all 10 of 10 reference lines redden and the run needs 728 s. Deleting only the new KILL QUERY counter assertion leaves the test green, so that line carries exactly one property. A second mutation moving the call inside the try still passes today, since 159/394 are not in that allowlist, so the outside-try placement is a robustness margin rather than a correctness requirement. Stating that rather than overclaiming it.

50/50 randomized run: 50 OK / 0 FAIL, per run 19.93-21.59 s against the 600 s per-test limit. Elapsed is asserted per case with a 15 s bound; each extra connection attempt costs 2 s, so that bound admits at most 6 of them, and it is backed by a counter rather than left to timing: the two deadline cases assert the attempt count is at most 2, which is what the fixture permits (a 2 s connect against a 3 s deadline lets only the attempts starting at t0 and t2 begin), and the measured value is 2 in 20 of 20 observations against 120 without the fix. The KILL QUERY case reads the counter from a row that already shows is_cancelled and again after the query ends, and requires the difference to be zero; measured 0 in 50 of 50 runs against 119 without the fix. A fixed ceiling is not derivable there because the kill is sent only once the query is visible in system.processes, so the poll latency decides how many connects precede it, which is why the assertion is a delta.

No-regression A/B. 20 cancel/timeout/hedged/skip-unavailable distributed tests, same environment, one binary swap: merge-base 15 OK / 6 FAIL, fixed 15 OK / 6 FAIL, failure sets identical in both directions. The 6 shared failures are pre-existing sandbox artifacts. Separately, 10 distributed-async-INSERT tests: 8 OK / 2 FAIL on both arms, identical sets. The 15 passing include 01361_fover_remote_num_tries, 01514_distributed_cancel_query_on_error, 01521_distributed_query_hang, 01563_distributed_query_finish, 00613_shard_distributed_max_execution_time, 02805_distributed_queries_timeouts and 01851_hedged_connections_external_tables.

Deliberately out of scope, one concern per PR: ConnectionEstablisherAsync::checkBeforeTaskResume checks only the socket timeout between fiber resumes, and Connection::connect's per-address loop can perform several blocking dials within a single attempt. Neither is needed to explain the measured 149 x 6 s, and both are filed separately.

Round 2 update (rows a, c, d, f, i).

  • (a) deterministic repro: a fourth deterministic window was added: one address, one try, and a
    deadline shorter than the connect timeout, so cancellation necessarily lands during the single
    attempt. Reproduces on demand; no randomization involved.
  • (c) fix matches root cause: a second checkpoint now covers the terminal attempt, which the
    loop-top check structurally cannot reach (there is no next iteration). Mutation testing shows the
    two calls are complementary, not redundant: removing only the terminal call reddens only the new
    case, removing only the loop-top call reddens the hedged 40-address case at 120 attempts.
  • (d) test intent / new assertions: the test grew from 2 to 4 labelled cases plus a runtime
    precondition probe: an attempt-count oracle read from system.query_log ProfileEvents
    (post-fix 2 attempts, pre-fix 120), a terminal-window case, and an automated KILL QUERY case
    (previously only measured by hand). Each new line was mutation-tested to confirm it carries its own
    property.
  • (f) general across code paths: the establisher remains the single anchor. One scope limit is
    disclosed rather than papered over: the asynchronous (hedged) terminal attempt finishes outside the
    fiber in ConnectionEstablisherAsync::checkTimeout, which cannot throw by design, so it does not
    reach the establisher's catch. The hedged path is fully covered for non-terminal attempts, which is
    the hang itself; the residue is the reported error code on the final attempt, bounded by one connect
    timeout. Measured with DistributedConnectionFailTry, which increments only inside that catch.
  • (i) invariants: the new call sits outside any nested try, on the single exit through which
    every non-retried attempt failure leaves the establisher. It is a no-op unless a live query thread
    group with a killed process-list element exists. 50/50 randomized run green (50 OK / 0 FAIL) and an
    A/B regression sweep over 10 neighbouring distributed tests shows identical failure sets.

Follow-up update (row d). The precondition probe's lower bound is now derived from the
attempt ceiling rather than chosen for its order of magnitude. Attempts are sequential, so with
a per-attempt duration D the deadline cases can only start attempts at t = 0, D, 2D, ...,
and cancellation for the 3 s deadline lands no later than 3099 ms because the deadline is
rounded up to the next 100 ms grid boundary and never down. At most 2 attempts therefore start
iff 2 * D >= 3099, i.e. D >= 1549.5 ms. The previous 1000 ms bound admitted a 1000-1549 ms
band in which a correct implementation may legitimately begin a third attempt and redden the
two-attempt assertion.

Round 5 update (rows d and e). Two oracles were tightened; no source file, test setting or
address range changed, and src/ is byte-identical.

  • (d) the probe now bounds the quantity the ceiling needs. It previously timed the whole
    clickhouse-client invocation, which includes client startup, local connection, exception
    propagation and output handling. Measured on this host that overhead is 78-90 ms, so a true D
    as low as ~1460 ms measured above the bound, was accepted, and then permitted a third attempt --
    the bad band was narrowed by the earlier bound but not closed. The probe now reads the
    server-side query_duration_ms of its own query from system.query_log, which starts inside
    executeQueryImpl and therefore excludes all of that. The residual (the analysis remainder) was
    measured against a refusing endpoint, where D is ~0 and the figure is the residual alone: at
    most 1 ms over 40 trials, 20 idle and 20 at load average 110. The bound is therefore
    1549.5 + 1, rounded up to 1551. An exhaustive sweep of D over 1000-2100 ms at 0.1 ms
    resolution confirms the shipped comparison now admits no D that permits more than 2
    attempts, and that its smallest accepted D is 1550.0 ms, above the required 1549.5. Separation
    in practice: a refusal measures 0-1 ms (1551x below) and a genuine block 2001-2052 ms (1.29x
    above), accepted 50 of 50 times through the real runner. The fixture-detection path was
    re-measured at the new bound rather than inherited: with the probe alone pointed at a refusing
    endpoint the test prints one line and fails loudly on the nine missing reference lines.
  • (e) the KILL QUERY delta oracle now requires zero. DistributedConnectionTries is
    incremented as the first statement of try_establish, before the connect, so it counts attempts
    that start. The attempt already in flight when the kill landed is therefore already inside the
    "before" sample and its completion adds nothing, which made the previous "at most 1 further
    attempt" one unit looser than the fix's own contract: a delta of exactly 1 meant a brand-new
    attempt had begun on a cancelled query. The kill is now issued ASYNC (its branch calls
    sendCancelToQuery inline before returning, so is_killed is set when the statement completes)
    and the "before" count is read from a system.processes row that already shows is_cancelled,
    with both fields coming from a single snapshot per row. The assertion requires a delta of exactly
    0, and the reference line reads kill started no further attempts. If is_cancelled is never
    observed the case now says so loudly instead of passing. Measured: delta 0 in 50 of 50 runs
    through the runner and 8 of 8 direct runs (is_cancelled observed on the first poll iteration
    every time, 136-162 ms after the kill); pre-fix the same block reads
    kill went from 1 to 120 attempts, i.e. it reddens as a non-zero delta with both endpoints
    populated rather than as a missing counter. A synthetic delta of 1 passes the old oracle and
    fails the new one; deleting only this assertion leaves the other nine lines green.

Session id: cron:clickhouse-review-slot-8:20260730-233600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @devcrafter, could you review this? Nothing on the connection-establishment path observed cancellation, so once PoolWithFailoverBase::getMany was entered a cancelled or timed-out distributed query performed every remaining replica times connections_with_failover_max_tries blocking connects regardless of is_killed; this adds CurrentThread::checkIfNotCancelled to ConnectionEstablisher::run, the one place all three carriers pass through.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [97ee790]

Summary: ✅


AI Review

Summary

This PR adds cancellation checkpoints to ConnectionEstablisher::run and a stateless regression test for slow distributed connects. The main retry-loop hang is improved, but the fix is still incomplete on the success path: if cancellation lands during a final connection that then resolves as missing table, stale replica, or read-only, the query still escapes with the ordinary replica outcome, and in the stale-fallback case it can still proceed to sendQuery on a replica after it has already been cancelled. I would not merge it as-is.

Findings

❌ Blockers

  • [src/Client/ConnectionEstablisher.cpp:167-168] CurrentThread::checkIfNotCancelled() only runs before a new connect and on the exception-based soft-failure exit. If try_establish returns a connected entry that is then rejected or downgraded (!is_usable, !is_up_to_date, or is_readonly), run returns success without re-checking cancellation. The unchanged callers still treat that as a normal result: PoolWithFailoverBase::getMany can throw ALL_CONNECTION_TRIES_FAILED / ALL_REPLICAS_ARE_STALE instead of the cancellation, fallback_to_stale_replicas_for_distributed_queries can still hand a stale connection to RemoteQueryExecutor, and HedgedConnectionsFactory::setBestUsableReplica can still pick a stale replica after the query was already killed. Suggested fix: add a post-try_establish cancellation checkpoint on the success path (outside the network-error allowlist), then cover the checked-result carriers with focused tests (missing table, stale replica, and read-only / insert).
Tests
  • ⚠️ The new 04652_distributed_connect_retry_cancellation.sh only covers timeout / KILL QUERY during outright connection failure. It never exercises the surviving checked-result path above, so the suite can stay green while cancellation is still lost on missing table, stale, or read-only outcomes.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 31, 2026
{
/// Every distributed connection attempt passes through here, so this is the one place where a
/// cancelled or timed out query can be stopped before it blocks on another connect.
CurrentThread::checkIfNotCancelled();

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.

This still misses the path where PoolWithFailoverBase::getMany() advances to the next pool after a successful but unusable result. try_establish() can return a connected entry that is filtered out later (!is_usable for a missing table, !is_up_to_date for a stale replica, or is_readonly in getManyCheckedForInsert). In that case we jump straight to the return below, and PoolWithFailoverBase::getMany() immediately keeps iterating replicas without any further cancellation check. A timed-out or KILL QUERY-ed request can therefore still walk the rest of the checked replicas in those modes. We need another CurrentThread::checkIfNotCancelled() after try_establish() (before returning), or an equivalent guard between pool attempts in PoolWithFailoverBase::getMany().

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and I am fixing it, but the blast radius is narrower than described.

getMany does not keep iterating replicas without a further cancellation check. Its loop calls
try_get_entry (PoolWithFailoverBase.h:310), which constructs a fresh ConnectionEstablisher and
enters run, whose first statement is the loop-top CurrentThread::checkIfNotCancelled at
ConnectionEstablisher.cpp:163. The next pool attempt therefore throws before doing any DNS or
connect work, so a cancelled request cannot walk the remaining checked replicas.

The real residual is the terminal attempt. When the completed-but-unusable result is the last one the
loop takes, there is no next try_get_entry to reach :163, the loop exits, and
usable_count < min_entries reports ALL_CONNECTION_TRIES_FAILED (PoolWithFailoverBase.h:346) or
ALL_REPLICAS_ARE_STALE (:377) instead of the cancellation. That is the same error-code masking
this PR fixes for the throwing path at :206, now on the non-throwing path. All three outcomes you
list qualify, since none of them increments usable_count: missing table, stale replica, and
is_readonly under getManyCheckedForInsert.

I am carrying the recheck as a separate change rather than extending this PR, to keep it to one
concern, and because two decisions are not settled yet.

Whether it belongs before the return for every outcome or only when is_usable is false. I lean to
every outcome: :163 already throws unconditionally at the top of the loop, so gating the new check
on is_usable would make the two checkpoints disagree.

Whether ConnectionEstablisherAsync needs separate handling. It appears not to. The terminal timeout
is processed outside the fiber in checkTimeout, which returns false and never resumes it
(AsyncTaskExecutor.cpp:22-23), but a normal return from try_establish happens inside the fiber
body, so a throw there propagates through the fiber's exception path.

I will post the fixing PR link here when it opens.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correcting the plan I stated above: I am folding this recheck into this PR rather than carrying it as
a separate change.

The reason is that my earlier framing assumed the two checkpoints already existed on master and
that only the third was missing. They do not. master currently has no cancellation checkpoint in
ConnectionEstablisher::run at all - both of the ones I referred to are added by this PR, so a
follow-up carrying only the third would sit inside the try and cover neither the per-attempt case
nor the throwing terminal case, and it could not stand on its own. Basing it on this branch instead
would be a stacked pull request. So it belongs here, as one concern with one changelog entry.

Both design questions I left open are now settled.

The check must be unconditional rather than gated on is_usable being false. is_readonly is a soft
outcome that carries is_usable == true: PoolWithFailoverBase.h:320 skips the ++usable_count at
:324 for a readonly replica under getManyCheckedForInsert
(ConnectionPoolWithFailover.cpp:183-186), so that outcome reaches the aggregate throw with
is_usable set. Gating on is_usable would miss it. That is a stronger reason than the symmetry
argument I gave earlier.

ConnectionEstablisherAsync needs no separate handling, as suspected. AsyncTaskExecutor::resume
calls processException at AsyncTaskExecutor.cpp:36-37, and a normal return from try_establish
happens inside the fiber body, so a throw there propagates through the fiber's exception path.

On test coverage: all five queries in 04652_distributed_connect_retry_cancellation.sh use
remote(...), which passes table_to_check = nullptr, so getTablesStatus is never entered and the
soft outcomes that need it are not reachable from the current cases. Covering them needs a real
Distributed table; there is no failpoint in the getTablesStatus path, and
replicated_merge_tree_all_replicas_stale looks like the usable hook for the stale-replica variant.

…hrinking window

The kill case sampled the attempt counter from system.processes while requiring the row to
already show is_cancelled. That state is readable only while the query is still running, and
this PR's fix deliberately shortens that window to the single connect already in flight when
the kill landed: measured 1836-2063 ms with a 2 s connect timeout. The poll therefore raced a
window that gets tighter the better the fix works, and on a miss the case printed its own
"unusable" line, which the reference cannot match. CI saw the resulting mixed pass/fail within
single jobs (msan 8 OK / 5 FAIL, tsan 46 / 4, asan_ubsan 0 / 5) while amd_debug was 50 / 0.

Read the total attempt count from query_log after the query has ended instead. That row is
written once and stays readable, so the assertion has no deadline. The connect timeout goes to
8 s so the kill, which completes in 147-333 ms, lands inside the first attempt with more than
20x margin; a total of 1 then means no attempt was ever begun on a query already known to be
cancelled. The reference is unchanged.

Four further robustness fixes:

- Wait for the first attempt to have STARTED, not merely for the query to exist. A query is
  registered in system.processes (executeQuery.cpp:1574) before analysis builds the remote
  table, so there was an interval in which a kill is handled correctly yet records zero
  attempts rather than the one asserted. This also lets the presence check reject an empty
  result instead of accepting it.
- Stop the query server-side on the guard path. Signalling the background client does not stop
  what it started: the client installs no SIGTERM handler (ClientBase.cpp:728-730 covers only
  SIGPIPE and SIGQUIT), so it dies without sending a Cancel packet, and while the server is
  synchronously inside executeQuery during analysis it does not notice the closed socket.
  Measured: 17 s after signalling and reaping the client the query was still in
  system.processes with is_cancelled = 0.
- Verify the 8 s connect timeout this case relies on. The shared precondition probe measures
  2 s, so a fixture erroring after ~2.5 s cleared it while truncating the nominal 8 s attempt,
  letting a correct query begin attempt 2 before the kill landed.
- Dial 5 addresses rather than 40. With 40 the kill case alone needed 40 x 3 x 8 s = 960 s
  without the fix and the whole test about 1455 s, past the runner's 600 s per-test timeout, so
  a revert was caught by the shell being killed rather than by the assertions. Five addresses
  keep every oracle discriminating: without the fix the deadline cases perform 15 attempts
  against an asserted bound of 2, and the kill case 15 against an asserted 1.

Also correct the max_execution_time note in Settings.cpp: it said the timeout cannot stop a
query during query analysis, which the checkpoint in the connection-establishment retry loop
makes partly untrue. Doc text only, no setting name, type or default change.

Verified: 50 of 50 runs pass with zero fixture-guard hits, at ~34 s per run against the 600 s
cap. On a build with both cancellation checkpoints removed the whole test fails in 198.54 s
with semantic diffs, including "kill used 15 attempts", so every assertion is load-bearing.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b382dfb

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 04611_join_runtime_filters_index_analysis_skip_index flaky under join_runtime_filter_min_probe_rows randomization #111691 (external, merged) - this build predates it (the test carries no pin at this commit)
Stateless tests (arm_binary, parallel) / 04612_join_runtime_filters_index_analysis_multi_key_anti same randomization #111691 (external, merged) - this build predates it
Fast test (arm_darwin) job-level macOS runner failure: the job was killed mid-Run at 29m30s (05:40:43Z to 06:10:14Z) and produced no artifacts and no test rows; 31 of 1828 builds in 7 days across 30 unrelated PRs, 0 on master #112267 (external, merged) - this build predates it (base/darwin-compatibility absent at this commit, 953 commits behind the fix)

The 7 failures on the previous commit a61770e3e3b53b were PR-caused (this PR's own new
04652 test racing on is_cancelled) and are fixed in this PR: that test is green here.

Session id: cron:our-pr-ci-monitor:20260801-063000

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 97ee790

CI is fully finished on this head and there is nothing to own: 174/174 check-runs completed, 156 success, 18 skipped, 0 failures. Finish Workflow completed successfully, and no check reported a failed test.

Check / test Reason Owner / fixing PR
(none) no failing check on this commit not applicable

Verified from the paginated check-runs API rather than the status rollup, which truncates on this repo. I am not re-pinging reviewers.

Session id: cron:our-pr-ci-monitor:20260803-163000

@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit 66bf3d5 Aug 7, 2026
179 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 Aug 7, 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 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.

4 participants