Repository navigation
Observe query cancellation in the distributed connection retry loop - #112689
PedroTadim merged 8 commits into
Conversation
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]>
Internal second-model review: 6 rounds, 20 findings adjudicated, 18 fixed, 2 disagreed with evidence in the final roundAn independent model reviewed this change against the diff and the source in six rounds, and I ran ❌ Fixed in this PR (selected)
|
Pre-PR validation gatea-i validation checklist (click to expand)
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 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 t 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 Deliberately out of scope, one concern per PR: Round 2 update (rows a, c, d, f, i).
Follow-up update (row d). The precondition probe's lower bound is now derived from the Round 5 update (rows d and e). Two oracles were tightened; no source file, test setting or
Session id: cron:clickhouse-review-slot-8:20260730-233600 |
|
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. |
|
Workflow [PR], commit [97ee790] Summary: ✅
AI ReviewSummaryThis PR adds cancellation checkpoints to Findings❌ Blockers
Tests
Final VerdictChanges requested. |
| { | ||
| /// 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(); |
There was a problem hiding this comment.
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().
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - b382dfbEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The 7 failures on the previous commit Session id: cron:our-pr-ci-monitor:20260801-063000 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code |
CI finish ledger - 97ee790CI is fully finished on this head and there is nothing to own: 174/174 check-runs completed, 156 success, 18 skipped, 0 failures.
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 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
max_execution_timeandKILL QUERYbeing 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 hungsystem.processesrow hadelapsed = 909.94,is_cancelled = 1,max_execution_time = 60andDistributedConnectionFailAtAll = 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::getManyis entered it performsnested_pools.size() x connections_with_failover_max_triesblocking connects regardless ofis_killed.The fix adds
CurrentThread::checkIfNotCancelledtoConnectionEstablisher::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 asALL_CONNECTION_TRIES_FAILED, which the caller turns into a next-shard retry.Measured with 40 addresses from the reserved
198.51.100.0/24range andmax_execution_time = 3: 240 s andALL_CONNECTION_TRIES_FAILEDbefore, ~4.1 s andTIMEOUT_EXCEEDEDafter. UnderKILL QUERYthe query kept dialing a further 234 s before and now stops in ~2 s withQUERY_WAS_CANCELLED. The test runs four cases, pinninguse_hedged_requestsat both values to cover the synchronous pool and the asynchronous establisher, and asserts elapsed time, the reported code, and the attempt count read back fromsystem.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.