Repository navigation
Honour connection_pool_max_wait_ms and make a pool wait cancellable - #113979
Conversation
PoolBase::get had no exit other than success. Its only exits were the three return Entry(...), and after available.wait_for returned there was no break, no deadline re-check and no throw, so an expired finite wait simply re-scanned and waited again. available is notified from one place only, PoolEntryHelper's destructor, i.e. when an object is returned, and the loop read no cancellation flag, so the wait ended only when some other query happened to release a connection. Three consequences, all measured on a pool of size 1 held by a concurrent query. connection_pool_max_wait_ms = 2000 did not fail after 2 s: the waiter was handed the connection 24.9 s later, when the holder was killed, with ConnectionPoolIsFullMicroseconds accounting for essentially all of it. max_execution_time = 5 with timeout_overflow_mode = 'throw' reported TIMEOUT_EXCEEDED after 39.8 s, eight times its deadline, because the pipeline raises it only once the wait finally completes. KILL QUERY ... SYNC on the waiter took 36.8 s, and only because the holder died inside that window. Wait in short slices against one absolute deadline instead, checking CurrentThread::checkIfNotCancelled() between slices, and throw NO_FREE_CONNECTION when a finite deadline expires. This is the shape FileSegment::wait already uses for the same problem, and mysqlxx::Pool::get already computes an absolute deadline once and throws when it is exceeded, so this brings the sibling pool in line with both. The deadline is computed once before the loop rather than per iteration, because a caller woken without obtaining an object goes round again and a restarted timeout would leave the total wait unbounded; the last slice is clamped to the remaining time so the total cannot overrun by up to a slice. milliseconds(timeout) can exceed what a steady_clock::time_point represents and the sum wraps into the past, so the value is clamped before it is added. Both branches are sliced, which is the more valuable half: the default connection_pool_max_wait_ms = 0 is translated to the infinite branch by ConnectionPool::getUnchecked, so a change touching only the finite branch would leave the hang in place for every default deployment. At the default the wait stays unbounded, as documented, but now responds to KILL QUERY and, at the default timeout_overflow_mode = 'throw', to max_execution_time. Under timeout_overflow_mode = 'break' the query is not cancelled at all (CancellationChecker::cancelTask calls cancelQuery only for THROW, and the BREAK path returns without writing is_killed), so the wait there still ends only when a connection is released; the setting's documentation says so rather than implying otherwise. Measured after the change: the kill returns in 1.0 s with the holder still alive, and max_execution_time = 5 reports TIMEOUT_EXCEEDED after 6 s. Also add NO_FREE_CONNECTION to the failover allowlist in ConnectionEstablisher::run. Without it the new exception is rethrown past run(), and since ConnectionPoolWithFailover::tryGetEntry does not catch, one saturated replica would fail the whole distributed query with no failover at all, which is worse than the eventual success it replaces. Semantically it belongs with the other seven codes there: they all mean this replica is not usable right now. Measured on two replicas with one pool saturated: the query is answered from the other replica, with one DistributedConnectionFailTry recorded, at both values of use_hedged_requests; omitting the allowlist entry makes the same query fail with NO_FREE_CONNECTION. The time spent blocked is now accounted by an RAII guard rather than an increment after the wait, which the deadline throw and cancellation would skip; the metric is what makes this observable at all, and it still reports once per wait, not once per slice (6.0 s reported for a 6.1 s wait). Because the pool timeout is a soft per-replica failure, the user-visible error on total exhaustion is ALL_CONNECTION_TRIES_FAILED with the pool timeout as its reason, and the setting bounds one attempt rather than the whole query. Both are now stated in the setting's documentation. Behaviour changes on purpose, so it is advertised rather than implied. Hive's metastore pool passes 1000000 ms and becomes bounded at about 16.7 minutes, which is that value's evident intent. The Wasm compartment pool and ConnectionPool::get pass -1 and keep the unbounded branch. Slicing means a pool waiting a long time wakes once a second; measured against an unsliced build over 20 s, user CPU was 49-55 ms sliced against 64-66 ms unsliced, i.e. within noise. No setting default and no serialized format changes, so no SettingsChangesHistory.cpp entry is needed. Co-Authored-By: Claude Fable 5 <[email protected]>
…docs The regression guard was missing for the more valuable half of the change. Deleting the CurrentThread::checkIfNotCancelled() call from the slice loop left the whole committed suite green: 04659's only KILL QUERY targeted the connection holder, so the waiter was released by the handover notification rather than by cancellation, the test set no max_execution_time at all, and the unit arms run waiters on plain std::threads with no thread group, which makes checkIfNotCancelled a structural no-op there. The measurements that did pin it lived in an uncommitted scratch script. Add two arms that keep the holder alive for the whole arm and cancel the waiter instead, both at the default connection_pool_max_wait_ms = 0, which is the branch ConnectionPool::getUnchecked routes the default to. One kills the waiter with KILL QUERY ... SYNC, the other gives it max_execution_time = 5 and no kill. Each asserts the holder is still running once the waiter is gone, which is what makes the arm measure cancellation rather than the handover: a waiter freed by the holder releasing the connection would leave no holder to find. The exception codes are asserted alongside the timing, so an arm that starts reporting some other error is not silently accepted. Both mutants now redden. Removing the cancellation check, and separately unslicing only the infinite branch, each fails exactly these two arms and leaves every other row of the test and all six unit arms green. The second is the one that matters for scope: it touches only the timeout < 0 branch, so the arms provably exercise the default rather than a positive timeout. On the mutant that drops the check, the kill arm ends at 14.3 s instead of 3.0 s, i.e. only once the holder dies, and the soft-limit arm reports at 12.2 s rather than 6.0 s, past its own bound. The test passes 50 out of 50 on this tree and 0 out of 50 on the parent commit, with one byte-identical failure signature every time. Correct the setting's documentation on three counts. The bullet promised that an infinite wait is interrupted by max_execution_time without qualification, which is false under timeout_overflow_mode = 'break': CancellationChecker::cancelTask calls cancelQuery only for THROW, and the BREAK path reaches handleOverflowMode's return false without writing is_killed, so throwIfKilled and therefore the new cancellation check are both no-ops. The promise is narrowed to the mode that delivers it rather than the wait being taught to observe soft expiry, which would be a cross-subsystem change with no precedent for a blocking wait here. The max_execution_time link was a same-page anchor, but the docs manifest puts that setting on a different page, so it now uses the full path form as most links in this file already do. And the failover sentence was categorical although DistributedSink, distributedIndexAnalysis and StorageQueryRunner call a per-replica pool directly and never reach ConnectionEstablisher's allowlist; it is now scoped to the failover path. All three are documentation only. Co-Authored-By: Claude Fable 5 <[email protected]>
The unit arms hand pool.get() to a helper thread and abandon that thread if it has not returned within a budget, so that one failed assertion reports instead of hanging the test binary. The helper captured the pool by reference while every arm gave it automatic storage, so an abandoned waiter borrowed a stack object. Abandoning is not an error path: infiniteTimeoutKeepsWaiting asserts that its first waiter has not finished, so that arm abandoned a live waiter on every successful run. Usually the abandoned waiter wins the object and finishes first, because PoolEntryHelper notifies while still holding the pool mutex, so a second waiter cannot enter the pool until the first is done with it. Nothing enforces that order. If the second waiter is scheduled first it takes the object, the arm joins that second thread and returns, and the first waiter is left blocked on a mutex and condition variable that the returning frame destroys. Destroying either while a thread is blocked on it is undefined, so this is a stack-use-after-return reachable from any arm whose waiter has to be abandoned, including the failure path of arms that normally join. It needs a rare interleaving, so it would surface as an intermittent report under the sanitizer unit test jobs rather than as a reproducible failure. Have the waiter co-own the pool. The arms hold it by shared_ptr, matching PoolBase::Ptr, and the thread captures that pointer by value, so an abandoned waiter keeps the mutex and the condition variable alive for as long as it is blocked on them. The lifetime is then correct whichever thread wins and for any arm added later. Wrap the thread in a small holder so a caller can observe one waiter more than once, and rewrite infiniteTimeoutKeepsWaiting to poll the same waiter twice rather than creating a second one. The arm's comment claimed that releasing the object hands it to that same waiter, which polling a fresh waiter could not distinguish from a new get() finding the object free; now it is measured. That also removes the interleaving above from the one arm that entered it by design. Applying the deadline to the timeout < 0 branch still fails this arm and nothing else, so the rewrite keeps what the arm was pinning. Name the subject of the break-mode caveat in the setting's documentation. The sentence said the query is not cancelled under break, which read as if KILL QUERY stopped working there too. KILL QUERY reaches cancelQuery without consulting timeout_overflow_mode, so it interrupts the wait in both modes; only the time limit is mode dependent. Co-Authored-By: Claude Fable 5 <[email protected]>
The two arms added in the previous commit both run at the default
connection_pool_max_wait_ms = 0, which PoolBase::get routes to its infinite
branch. The finite branch keeps its deadline in a block of its own, so those
arms say nothing about it: replacing the clamp
slice = std::min(slice, deadline - now)
with a bare `slice = deadline - now` makes the finite branch perform one
unsliced wait straight to its deadline, evaluating checkIfNotCancelled() exactly
once before waiting, and the whole committed suite stays green. Under that
mutant a deployment at connection_pool_max_wait_ms = 300000 waits five minutes
for KILL QUERY to take effect, which is the defect this change removes, on the
branch its own title names. Hive's metastore pool passes a positive 1000000 ms,
so the branch is reachable from a shipped caller and not only from a setting.
cancel_waiter takes the pool timeout as an argument, defaulting to 0 so the two
existing arms are unchanged, and one new arm runs at 300000 ms. Five minutes is
far past the arm's own twelve second bound, so within it only cancellation can
end the wait; an unsliced wait to that deadline shows up as the bound firing.
The mutant that unslices only the infinite branch and the one that unclamps only
the finite branch redden disjoint arms, so each arm is pinned by a mutant the
other is blind to. Note the existing unit arm for the clamped last slice does
not catch the unclamped-finite mutant: an unclamped single wait still ends at
the deadline, and only an unclamped last slice overruns it, so the clamp and the
cancellation arms cover different properties.
Also correct the total-wait formula in the setting's documentation. It presented
connections_with_failover_max_tries as the multiplier, but at 0 the retry guard
in PoolWithFailoverBase::getMany is `if (max_tries && ...)`, so the pool is not
skipped and one attempt still runs before it is written off. The true worst case
is N x 1 where the formula predicted 0.
Internal second-model review (4 rounds, 0 open blockers)An independent reviewer read the resulting tree cold, without the implementation notes, and a Round 4 (final)Second-model pass: 0 findings. Scope confirmed against the intended change set: full diff Cold pass, my own: no blockers, no majors. Two documentation defects I fixed before
Earlier rounds
Three mutants redden nothing, reported rather than papered over: |
Pre-PR validation gate (a-i)
Ten mutants were built, each reverting one part of the change. Seven redden exactly the arms they A 45-test slice around connection pools, distributed reads and failover was run on both commits: zero The unit arms' waiter lifetime was proved separately, under AddressSanitizer with |
|
cc @azat @vitlibar, could you review this? |
|
Workflow [PR], commit [4b266c4] Summary: ✅
AI ReviewSummaryThis PR makes Findings
Final VerdictChanges requested: preserve query-cancellation and time-limit exceptions in the sync distributed-index-analysis connection-establish path. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 130/134 (97.01%) · Uncovered code |
| /// floods once per timeout per waiter. | ||
| LOG_INFO(LogFrequencyLimiter(log, 10), "No free connections in pool. Waiting {} ms.", timeout_ms.count()); | ||
| available.wait_for(lock, timeout_ms); | ||
| DB::CurrentThread::checkIfNotCancelled(); |
There was a problem hiding this comment.
Making PoolBase::get throw from the wait loop is the right mechanism for KILL QUERY and max_execution_time, but the non-failover ConnectionPool::get callers are still written under the old contract that pool acquisition itself never surfaced cancellation. In src/Storages/Distributed/DistributedSink.cpp, the catch around connection_pool->get feeds every Exception except LOGICAL_ERROR into shouldSkipShardOnInsert, so with skip_unavailable_shards_mode = unavailable_or_exception_before_processing this change will also swallow QUERY_WAS_CANCELLED / TIMEOUT_EXCEEDED and downgrade a killed or timed-out distributed INSERT into “skip this shard”. src/Interpreters/ClusterProxy/distributedIndexAnalysis.cpp:446-456 has the same swallow-and-continue pattern for replica acquisition.
Can we re-run CurrentThread::checkIfNotCancelled (or explicitly rethrow the cancellation/time-limit codes) in those callers before converting the exception into shard/replica unavailability?
There was a problem hiding this comment.
The mechanism is real and I reproduced it: the pool wait's cancellation exception does reach that
catch and is swallowed into a shard skip. What does not follow is the consequence, so I am not
changing the callers. Evidence below, at dfc10b20.
The swallow happens. Constructed the exact state (size-1 per-replica pool saturated by a
holder, distributed INSERT blocked in PoolBase::get, skip_unavailable_shards_mode = unavailable_or_exception_before_processing, then KILL QUERY on the waiter). Server log:
{p5_..._ins} <Warning> DistributedSink: Skipping shard 1 on INSERT due to
`skip_unavailable_shards_mode` setting: DB::Exception: Query was cancelled
But the user still gets the error. Same query, one system.query_log row carries both halves:
type exception_code ProfileEvents['DistributedShardsSkipped']
ExceptionWhileProcessing QUERY_WAS_CANCELLED 1
Client rc=138, Code: 394 ... Query was cancelled, 0 rows landed.
The broken link: checkIfNotCancelled can only throw when is_killed is set
(ProcessList.cpp:687), and is_killed has exactly one writer, QueryStatus::cancelQuery
(:592). That same call cancels every registered executor (:617-618), and the flag is read by
checkTimeLimitSoft (:698-701) which PipelineExecutor::checkTimeLimit
(PipelineExecutor.cpp:284-291) turns into a throw. So the precondition for the pool wait to
raise a cancellation code is the precondition that independently fails the query. The per-shard
swallow can lose one shard's attribution; it cannot manufacture a success.
The suggested guard would therefore be unreachable code: re-running checkIfNotCancelled in those
callers can only fire when the query is already failing by that independent route.
Controls, so the above is not a probe that always errors. The same catch on the same path,
given an ordinary shard error (UNKNOWN_TABLE from the RemoteSink constructor), does swallow it
and the client sees rc=0 with Skipping shard 1 ... Table ... does not exist in the log. So the
handler is genuinely capable of the silent-success outcome; it just cannot reach it for
cancellation codes. Four earlier revisions of my probe were vacuous (pool key mismatch: cluster
and max_connections are part of ConnectionPoolFactory::Key, ConnectionPool.h:147-165) and I
discarded them rather than reporting them; the tell was zero "No free connections in pool" lines,
which is now an assertion in the probe.
Also not new. On the base commit job.executor->start() is already inside that same try, and
PushingPipelineExecutor::start -> PipelineExecutor ctor -> addPipelineExecutor
(PipelineExecutor.cpp:143) -> throwProperExceptionIfNeeded (ProcessList.cpp:646) already
raises those two codes into it, as do the RemoteSink network operations. This change adds one
more site raising codes the handler already had to tolerate, so narrowing
shouldSkipShardOnInsert would be a behaviour change to a setting this PR does not own, with no
observable defect behind it.
One thing I agree is imperfect and am leaving alone: the log line attributes a cancelled shard to
skip_unavailable_shards_mode, which reads oddly. It is wording in a warning only, with no effect
on the result, so it does not belong in this PR.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units104 translation units recompiled, 1135 s compile time in total, 104 of them have a recent master baseline. |
CI finish ledger - dfc10b2CI is complete on this head with no failures:
Session id: cron:our-pr-ci-monitor:20260809-033000 |
…ax-wait-ms The only conflict is in PoolBase::get, and both sides of it are mine: master now carries the shared saturatedMilliseconds() clamp from ClickHouse#106961, while this branch restructures the same wait into deadline-bounded slices. Kept this branch's slice loop, since a plain wait_for without a deadline check is exactly the defect the branch fixes: a positive connection_pool_max_wait_ms would go back to being a wake-up interval rather than a deadline. Dropped the branch's own max_wait_ms constant in favour of saturatedMilliseconds(), so the overflow clamp on the deadline is the one shared by every other user-controlled wait_for site. The clamp is now one year instead of ~146 years; both are far beyond any timeout a caller can wait out, and negative values still mean "infinite" via has_deadline, which is evaluated before the clamp. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Merged master to clear a conflict. Both sides of it were mine, so the resolution is a semantic I kept the slice loop, since taking master's plain Verified on the merged tree: Three unit tests abort on this tree but do so identically on a build of unrelated work that contains |
…verlap The flaky check on amd_asan_ubsan timed out one run of 04659_connection_pool_zero_wait_blocks at exactly 600120 ms, against 69.8 to 87.2 s for the other 33 runs of the same job. The xtrace shows the last ten minutes spent in one loop, the second poll in contend(), reading 0 instead of 2 every time. query_log from that run explains why it could never read 2. The finite arm's waiter gave up on its own 500 ms deadline after 1739 ms with code 279, which is what the arm asserts, so it was in system.processes for 1.74 s. One poll spawns a clickhouse-client, which costs about 2 s under a sanitizer, so the poll period was longer than the whole window it sampled for and the polls straddled it. Once the waiter has exited the count can never reach 2 again, and the loop's bound is 600 iterations rather than a duration, so at 2 s an iteration it runs for about 1200 s and the per-test timeout fires first. Two changes. The polls are bounded by wall clock, so a condition that can no longer hold is reported inside the budget instead of hanging. And on the arm whose waiter gives up, the overlap is no longer sampled: the arm waits for the waiter to exit and then asserts the holder is still holding, which covers the whole of the wait rather than one instant of it. No SELECT and no reference line changes. The arm that gives up gains two assertions it did not have: that its waiter never hit its own bound, and that the holder had not released early. Verified by injecting the sanitizer's client startup cost into running() so the poll period exceeds the waiter's lifetime deterministically: the published test times out 3 of 3 under it and this one passes 3 of 3. Reverting the production deadline to the pre-fix behaviour reddens the reworked arm 2 of 2, naming both new assertions, so the oracle still fails when it should. 50 consecutive runs pass, and 5 pass through clickhouse-test.
The first commit took the overlap poll off the arm whose waiter gives up on a pool timeout, on the grounds that the remaining arms hold the connection until something takes their waiter out. That is true of the two arms ended by a kill but not of the soft limit arm, whose waiter ends on its own max_execution_time: query_log puts its lifetime at about 6 s, so a poll slower than that samples either side of the window and reports a contention failure that did not happen. Reproduced by raising the injected poll cost to 7 s. The poll now runs only on the arms a kill ends. The soft limit arm waits for its waiter, and all three cancellation arms assert the wait they accumulated on the pool, which unlike presence in system.processes is still readable once the waiter has gone. Hence the fourth column. Checked that the column can fail: giving the waiter a pool of its own so it never queues takes it from 3 to 0 and reddens the run.
Fixed the flaky-check timeout on
|
| arm | published test | this test |
|---|---|---|
| poll 2.4 s (the CI condition) | 3/3 timeout | 3/3 pass |
| poll 7 s | timeout | 2/2 pass |
Mutation checks, so the oracles are not blind: reverting the production deadline to the pre-fix behaviour reddens the arm 2/2 and names both added assertions; giving the waiter a pool of its own so it never queues takes the new column from 3 to 0 and reddens the run. Then 50 consecutive runs pass, and 5 pass through clickhouse-test.
I also looked at two review findings on the wider PR and did not act on either. The use_hedged_requests and multi-replica matrix is a fair point but it is a property of a test already reviewed on the green head, and this fix touches neither the failover path nor the topology, so folding a test redesign in here would bundle it with a CI fix. Separately, connection_pool_max_wait_ms above one year is clamped to one year by saturatedMilliseconds; that is master's shared helper, used by 20 files, documented at saturatedDuration.h:13 and asserted by gtest_saturated_duration.cpp:25, and the merge commit deliberately adopted it in place of this branch's own clamp so every user-controlled wait_for clamps the same way. A one-year and a two-year pool wait are not distinguishable in practice. Happy to do either if you want them.
Conflict carrier: src/Common/PoolBase.h. The silk integration (ClickHouse#112667) moved Entry out of PoolBase into a standalone PoolEntry<TObject>, gave PoolBase the TLocker/TWaiter template parameters, replaced PoolEntryHelper's PooledObject back-reference with an on_destroy callback built by a new makeEntry(), dropped Entry::getPool() and with it the LOGICAL_ERROR declaration and the Common/Exception.h include. All of that is kept verbatim; only the wait itself is re-applied on top, so the resolved file differs from master by exactly this branch's change. The master side of the wait block could not be taken: it is a single wait_for() with no deadline re-check, which is the defect this branch fixes. Two consequences of the refactor for this branch: - Common/Exception.h and an ErrorCodes declaration come back, now for NO_FREE_CONNECTION alone. LOGICAL_ERROR stays deleted, since getPool() was its only user. - The wait uses the two-argument wait_for() and tests the predicate itself. TWaiter is no longer always std::condition_variable: Silk::FiberCondVarAdapter (src/Client/SilkConnectionPool.h) offers wait(), notify_one(), notify_all() and a two-argument wait_for() only, and is instantiated through Silk::ConnectionPool, so the predicate overload would not compile. The clamped millisecond value is now computed once and used for the deadline, the log line and the NO_FREE_CONNECTION message. Master already logged the clamped value; this keeps that and makes the message state the wait that actually applied rather than an unclamped request.
Master merge, head
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
Good change, thanks!
95f0e9f
|
@groeneai @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
Verified on master and answered in #120832: the finding is real and it is this PR's. The soft classification is load-bearing (it is what makes a saturated replica fail over to a healthy one, measured), so the fix keeps it and stops a zero-connection shard from counting as unavailable, rather than rethrowing from |
… shard With a finite connection_pool_max_wait_ms, PoolBase::get throws NO_FREE_CONNECTION when a replica's pool has no free slot within the deadline. ConnectionEstablisher::run classifies that as a soft per-replica failure, which is load-bearing: it is what makes a saturated replica fail over to a healthy one. One layer up, though, both shard-level connection allocators translate skip_unavailable_shards into a minimum entry count of zero and accept zero entries, and RemoteQueryExecutor::needToSkipUnavailableShard sees only that count. So a shard whose only replica was never contacted, because the initiator ran out of its own connection slots, was reported as an unavailable shard and silently dropped: a two shard SELECT returned one shard's rows with exit code 0, and the parallel_distributed_insert_select path never wrote that shard's rows while reporting success. skip_unavailable_shards_mode = 'unavailable' is documented as "a shard is considered unavailable when ClickHouse cannot connect to any of its replicas"; a replica that was never attempted is neither. ConnectionEstablisher::run now records on TryResult that a try failed because the initiator's own pool was exhausted, and each of the two shard-level allocators refuses to return an empty result that such a failure contributed to, throwing ALL_CONNECTION_TRIES_FAILED. That is the same code the skip_unavailable_shards = 0 path already produces, the one connection_pool_max_wait_ms's own documentation already promises, and the one ReadFromRemote::addLazyPipe already catches in order to fall back to a local replica. The two meanings of a zero minimum entry count are separated where the difference is known. A caller that passes skip_unavailable_endpoints itself (IStorageCluster, distributedWriteFromClusterStorage, the parallel-replicas coordinator queries, DistributedIndexAnalyzer) is allocating interchangeable task-iterator workers, where an endpoint that goes unused costs nothing; only a zero defaulted from skip_unavailable_shards is about shards, which own rows. Those callers are unchanged. Both allocators are fixed: use_hedged_requests defaults to true, so HedgedConnectionsFactory is the default path, and PoolWithFailoverBase is what use_hedged_requests = 0 uses. Each guard tests the vector it is about to return rather than predicting it from counts, so it cannot pre-empt the ALL_REPLICAS_ARE_STALE verdict the same inputs produce with fallback_to_stale_replicas = false. The soft-failure allowlist is deliberately unchanged: rethrowing NO_FREE_CONNECTION from the establisher would trade the silent partial result for a query that fails while a healthy replica could serve it. The new test's arm B pins that behaviour. At the default connection_pool_max_wait_ms = 0 the wait is infinite, the new flag is never set, and every path is bit for bit unchanged. I introduced this in ClickHouse#113979, which is contained in the 26.9 branch and not in 26.8 or 26.7. Closes ClickHouse#120832
Related: #112053
Related: #112380
Related: #106961
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A query queued on a full distributed connection pool now responds to
KILL QUERY, and tomax_execution_timeat the defaulttimeout_overflow_mode = 'throw', instead of waiting until another query happens to release a connection, and a positiveconnection_pool_max_wait_msnow actually expires. Previously the wait ended only on success at every value of the setting, so the configured timeout was ignored,max_execution_timewas reported long after its deadline and the query could not be killed. The wait applies per replica, so an expired one is a soft failure that fails over to the remaining replicas and only then reportsALL_CONNECTION_TRIES_FAILED.Description
PoolBase::gethad no exit other than success: afteravailable.wait_forreturned there was no deadline re-check and no throw, so an expired finite wait re-scanned and waited again.availableis notified only when an object is returned, and the loop read no cancellation flag, so the wait ended only when another query released a connection.The wait now happens in short slices against one absolute deadline, checking
CurrentThread::checkIfNotCancelled()between slices, and throwsNO_FREE_CONNECTIONwhen a finite deadline expires. That is the shapeFileSegment::waitalready uses, andmysqlxx::Pool::getalready throws on an absolute deadline. Both branches are sliced: the default0is translated to the infinite branch, so touching only the finite branch would leave the hang in place for every default deployment.NO_FREE_CONNECTIONis added to the failover allowlist inConnectionEstablisher::run; without it one saturated replica would fail the whole distributed query instead of failing over.Behaviour changes on purpose. At the default the wait stays unbounded, as documented, but becomes cancellable. Hive's metastore pool passes 1000000 ms and becomes bounded at about 16.7 minutes, its evident intent; the other two callers pass a negative timeout and are unchanged. Slicing wakes a long wait once a second: over 20 s, user CPU was 49-55 ms sliced against 64-66 ms unsliced. No setting default and no format changes.
The deadline is clamped with master's
saturatedMillisecondsso it cannot wrap.PoolBaseis now templated on its waiter type, andSilk::FiberCondVarAdapterprovides only the two-argumentwait_for, so the predicate is tested in the loop instead of being passed in.Validation
Both directions at three levels, each with the running server's
buildIdasserted equal to the binary under test. Timings: pool of size 1 held by a concurrent query.connection_pool_max_wait_ms = 2000KILL QUERY ... SYNC, default0max_execution_time = 5, default0TIMEOUT_EXCEEDEDat 39.8 sTIMEOUT_EXCEEDEDat 6.1 s04659_connection_pool_zero_wait_blocks.sh: 50/50 pass after, 0/50 before, one deterministic signature. Itszeroarm is unchanged; thefinitearm's premise was that the wait re-enters the retry loop, which is what this removes, so its expected outcome is inverted. Three arms are new: they cancel the waiter while the holder keeps the connection, two at the default0and one at a positive timeout.use_hedged_requests; omitting the allowlist entry makes the same query fail.04659, which the change fixes.Workflow [PR]
Sync PR [sync-upstream/pr/113979]
Version info
26.9.1.639(included in26.9and later)