Skip to content

Honour connection_pool_max_wait_ms and make a pool wait cancellable - #113979

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/poolbase-honour-connection-pool-max-wait-ms
Sep 3, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/poolbase-honour-connection-pool-max-wait-ms

Conversation

@groeneai

@groeneai groeneai commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112053
Related: #112380
Related: #106961

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

A query queued on a full distributed connection pool now responds to KILL QUERY, and to max_execution_time at the default timeout_overflow_mode = 'throw', instead of waiting until another query happens to release a connection, and a positive connection_pool_max_wait_ms now actually expires. Previously the wait ended only on success at every value of the setting, so the configured timeout was ignored, max_execution_time was 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 reports ALL_CONNECTION_TRIES_FAILED.

Description

PoolBase::get had no exit other than success: after available.wait_for returned there was no deadline re-check and no throw, so an expired finite wait re-scanned and waited again. available is 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 throws NO_FREE_CONNECTION when a finite deadline expires. That is the shape FileSegment::wait already uses, and mysqlxx::Pool::get already throws on an absolute deadline. Both branches are sliced: the default 0 is translated to the infinite branch, so touching only the finite branch would leave the hang in place for every default deployment.

NO_FREE_CONNECTION is added to the failover allowlist in ConnectionEstablisher::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 saturatedMilliseconds so it cannot wrap. PoolBase is now templated on its waiter type, and Silk::FiberCondVarAdapter provides only the two-argument wait_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 buildId asserted equal to the binary under test. Timings: pool of size 1 held by a concurrent query.

SQL arm before after
connection_pool_max_wait_ms = 2000 succeeds after 24.9 s fails at 6.1 s (3 attempts x 2000 ms)
KILL QUERY ... SYNC, default 0 36.8 s, holder had died 1.03 s, holder still alive
max_execution_time = 5, default 0 TIMEOUT_EXCEEDED at 39.8 s TIMEOUT_EXCEEDED at 6.1 s
no contention (control) succeeds succeeds, unchanged
  • 04659_connection_pool_zero_wait_blocks.sh: 50/50 pass after, 0/50 before, one deterministic signature. Its zero arm is unchanged; the finite arm'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 default 0 and one at a positive timeout.
  • 5 new unit arms, 6 in total. Two fail before the change; the other four pass on both.
  • Failover with one replica's pool saturated: the query is answered from the other replica at both values of use_hedged_requests; omitting the allowlist entry makes the same query fail.
  • 45 tests around connection pools, distributed reads and failover, A/B: zero regressions; the only difference is 04659, which the change fixes.
  • Ten mutants, each reverting one part: seven redden exactly the arms they target and nothing else. Unslicing only the infinite branch and unclamping only the finite branch redden disjoint arms, so each branch is pinned by a mutant the other is blind to. Three redden nothing, reported rather than papered over: the wait returns with the lock held and the outer scan tests the same conditions, so the outer loop never re-iterates after a wait, leaving a predicate-false wakeup and a per-iteration deadline unconstructible.

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

Version info

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

groeneai and others added 4 commits August 8, 2026 12:52
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.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds, 0 open blockers)

An independent reviewer read the resulting tree cold, without the implementation notes, and a
second model re-reviewed the full scope. Four review rounds; the last returned no findings.
Verdicts below are mine.

Round 4 (final)

Second-model pass: 0 findings. Scope confirmed against the intended change set: full diff
6 files / +417 / -33, delta 3 files / +27 / -12.

Cold pass, my own: no blockers, no majors. Two documentation defects I fixed before
publishing, and two nits I am not acting on.

finding verdict
⚠️ Two countable claims in the description were stale after the last round: "two arms are new" (there are three) and "nine mutants" (ten were built and measured). Agreed, corrected. Both were flagged by the implementation round rather than left to be found here.
⚠️ The linked issues sat inside the leading HTML comment, so they did not render. Agreed, corrected: they are now visible above the changelog category.
⚠️ #106961 is open and edits the exact line this restructures (std::chrono::milliseconds(timeout)), so a conflict on PoolBase.h is certain whichever merges second. Agreed, disclosed in the description; the two clamps agree in direction, so it is a one-file rebase, not a competing fix.
💡 #include <Common/Stopwatch.h> in PoolBase.h is now redundant. Not acting. Still needed transitively by the RAII profile-event guard instantiated in this header, so removing it would make the header depend on another header's include list to no observable effect.
💡 PoolBase.h now pulls Common/CurrentThread.h, which reaches Core/Block.h. Not acting, measured: PoolBase.h has 5 in-tree includers, and ConnectionPool.h already reaches Core/Block.h via IServerConnection.h, so at most 3 translation units gain weight. CurrentThreadHelpers.h does not expose checkIfNotCancelled, so there is no lighter forward.

Earlier rounds

round finding outcome
1 ❌ The setting's docstring promised that an infinite wait is interrupted by max_execution_time without qualification. Under timeout_overflow_mode = 'break' the query is never cancelled, so the promise is false there. Fixed: narrowed to the mode that delivers it.
1 ⚠️ The cancellation half, the more valuable half, had no committed regression guard: deleting the cancellation check left the whole suite green. Fixed: two arms added that cancel the waiter while the holder keeps the connection. Each asserts the holder is still running afterwards, which is what makes the arm measure cancellation rather than the handover.
2 ⚠️ The unit arms abandoned a waiter thread holding a reference to a pool with automatic storage, so an abandoned waiter could be left blocked on a mutex and condition variable that the returning frame destroys. Fixed: the waiter co-owns the pool by shared_ptr, and the arm that abandoned a live waiter by design now polls the same waiter twice instead.
3 ⚠️ Both cancellation arms ran at the default 0, which routes to the infinite branch. The finite branch keeps its deadline separately, so neither arm said anything about it: a mutant that waits unsliced straight to a positive deadline left the whole suite green while a deployment at connection_pool_max_wait_ms = 300000 would wait five minutes for KILL QUERY. Fixed: a third arm at a positive timeout. Unslicing only the infinite branch and unclamping only the finite branch now redden disjoint arms, so each branch is pinned by a mutant the other is blind to.
3 ⚠️ The documented worst-case total wait used connections_with_failover_max_tries as the multiplier, but at 0 the retry guard is if (max_tries && ...), so one attempt still runs. The formula predicted 0. Fixed: the multiplier is now stated as never less than one.

Three mutants redden nothing, reported rather than papered over: wait_for(lock, slice, pred)
returns with the lock held and the outer scan tests the same conditions, so the outer loop never
re-iterates after a wait, which leaves a predicate-false wakeup and a per-iteration deadline
unconstructible rather than merely untested.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
check answer
a Deterministic repro? Yes, at two levels. Unit: a pool of size 1 with its only object held, then get(300) from another thread stays blocked past 5000 ms, 3 runs out of 3 (5207/5208/5209 ms). Test: 04659_connection_pool_zero_wait_blocks.sh fails 50 times out of 50 on the parent commit, with one signature every time.
b Root cause explained? 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 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 configured timeout was a wake-up interval, not a deadline, and the wait ended only when another query happened to release a connection - which is why max_execution_time was raised by the pipeline long after its deadline rather than during the wait.
c Fix matches the root cause? The loop gains the deadline and the cancellation check it lacked, at the layer whose own contract is violated (get's comment already reads "Wait for free object in pool for 'timeout'"). No widened bound, no reduced dataset, no defensive check at a crash site. The adapter could not fix it: the retry is inside the callee, so it never regains control between retries.
d Test intent preserved, tests added? The zero arm of 04659 is byte-identical - it pins the merged 0-means-infinite fix and must not be weakened. The finite arm was rewritten because its premise, stated in its own comment, was that a positive timeout "re-enters the retry loop as soon as it expires", which is exactly what this removes; its waiter-must-succeed check is inverted for that arm only, through an explicit argument, so the blocking arm keeps it. Added: 5 unit arms (6 in total), one assertion row pinning the user-visible error, and three arms that cancel the waiter while the holder keeps the connection, which is what pins the cancellation half: two at the default 0 and one at a positive 300000 ms, because the two branches hold their deadline separately, so cancellation reaching one is no evidence about the other. Each of those asserts the holder is still running afterwards, so the arm measures cancellation rather than the handover. The unit arms hold the pool by shared_ptr and the waiter thread co-owns it, so a waiter that has to be abandoned (which infiniteTimeoutKeepsWaiting does by design) cannot outlive the mutex and condition variable it is blocked on; that arm now polls the same waiter twice instead of creating a second one, which makes its own comment's claim measured rather than inferred.
e Both directions? Yes, at three levels, with the running server's buildId asserted equal to the binary under test before any verdict. connection_pool_max_wait_ms = 2000 succeeded after 24.9 s before and fails at 6.1 s after; KILL QUERY ... SYNC took 36.8 s before (and only because the holder died inside that window) against 1.03 s after with the holder still alive; max_execution_time = 5 reported at 39.8 s before and 6.1 s after. A no-contention control succeeds identically on both, which is what makes those three mean something.
f General across code paths? All four PoolBase::get call sites enumerated and all three derived classes checked (ConnectionPool, ThriftHiveMetastoreClientPool, WasmCompartmentPool). PoolBase.h now uses the predicate overload, like 13 of the other 14 condvar wait_for sites in src/Common that already did; the single remaining predicate-less one, QueryProfiler.cpp:457, is a sleep-until-next-deadline interval wait and is left alone. The structurally identical sibling mysqlxx::Pool::get already computes an absolute deadline once and throws when it is exceeded, so this converges on the in-tree precedent instead of inventing a rule. FileSegment::wait is the precedent for the sliced shape, and its comment names the same failure mode.
g Generalizes across inputs? No data types here - this is a generic container in src/Common - so boundary values are the axis: -1 (infinite, unchanged), 0 (routed to the infinite branch by the setting adapter, unchanged apart from becoming cancellable), a sub-slice positive (300 ms), a multi-slice positive (1010 ms, which is what pins the last slice being clamped to the remaining time), and the largest value a Poco::Timespan can express. That last one is a real hazard, not a formality: unclamped, now() + milliseconds(INT64_MAX/1000) wraps and the comparison deadline > now reads false, so the wait would expire immediately.
h Backward compatible? No setting default and no serialized format changes, so no SettingsChangesHistory.cpp entry is owed; checked by reading the repo's own check_settings_changes_history, which returns nothing unless that file is itself among the changed files. The behaviour change is deliberate and is stated in the changelog and in the setting's own documentation rather than left implicit, including that the wait is per replica and therefore does not bound the whole query.
i Invariants and contracts preserved? The three success returns are untouched and the expired deadline is the only new exit. mutex is held throughout the wait (wait_for reacquires it before returning) and the new predicate is only ever evaluated under it. The throw leaves the pool unmodified, since no object is claimed on that path. The time spent blocked is now accounted by an RAII guard instead of an increment placed after the wait, which the throw and the cancellation would both have skipped; it still reports once per wait rather than once per slice - a 6.1 s wait reports 6.0 s, not six times that.

Ten mutants were built, each reverting one part of the change. Seven redden exactly the arms they
target and nothing else: removing the deadline, applying it to the infinite branch as well, dropping
the failover allowlist entry, dropping the cancellation check, unslicing only the infinite branch,
unclamping the finite branch's last slice so it waits once straight to its deadline, and reverting the
metric guard. The last three are what the cancellation arms pin, and the two branch-specific ones form
a complementary pair: unslicing the infinite branch reddens the two default-0 arms and leaves the
positive-timeout arm green at 3.0 s, while unclamping the finite branch reddens only that arm (14.2 s,
past its own 12 s bound) and leaves all six unit arms green, including the one that pins the last
slice being clamped - an unclamped single wait still ends at the deadline, so only an unclamped last
slice overruns. Each arm is therefore pinned by a mutant the other is blind to, which is what proves
the positive-timeout arm is not a second copy of the default path. Three mutants reverting the
predicate redden nothing, and that is
reported rather than papered over: wait_for(lock, slice, pred) returns with the lock held and the
outer scan tests the same conditions, so a wakeup that leaves the caller empty-handed is not
constructible and the arm would not discriminate. The predicate is kept because it is what makes that
true.

A 45-test slice around connection pools, distributed reads and failover was run on both commits: zero
regressions, the only difference in the failing set being 04659 itself, which this change fixes.
After the mutation matrix the shipping tree rebuilt byte-exactly back to its recorded Build ID.

The unit arms' waiter lifetime was proved separately, under AddressSanitizer with
detect_stack_use_after_return, against a probe that forces the rare interleaving deterministically.
The pre-fix shape is reported as stack-use-after-scope naming the arm's own pool variable; the shipped
shape is clean. The negative control is the point: a clean sanitizer run on a fixed tree proves nothing
unless the same probe is shown to flag the defect. Reverting the change that pins the infinite branch
still fails that arm and nothing else, so the rewrite kept what the arm was pinning, and the full unit
binary passes 22 666 tests with no new failure.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @vitlibar, could you review this? PoolBase::get had no exit other than success, so a positive connection_pool_max_wait_ms was a wake-up interval rather than a deadline and the wait ignored cancellation; it now waits in slices against one absolute deadline, checks CurrentThread::checkIfNotCancelled() between them, and throws NO_FREE_CONNECTION on expiry, which ConnectionEstablisher treats as a soft per-replica failure so failover still happens. This is the second half of the setting's contract, after the 0-means-infinite fix in #112380.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4b266c4]

Summary: ✅


AI Review

Summary

This PR makes PoolBase::get honour finite connection_pool_max_wait_ms, slices full-pool waits so queued distributed queries can notice cancellation, treats NO_FREE_CONNECTION as a soft failover error for distributed reads, and adds focused unit and functional coverage. The main implementation looks sound, but one previously reported caller still violates the new cancellation contract on the sync distributed-index-analysis path.

Findings

⚠️ Majors

  • [src/Common/PoolBase.h:172; src/Interpreters/ClusterProxy/distributedIndexAnalysis.cpp:449-456] [dismissed by author -- https://github.com/Honour connection_pool_max_wait_ms and make a pool wait cancellable #113979#discussion_r3741855982] PoolBase::get can now throw QUERY_WAS_CANCELLED or TIMEOUT_EXCEEDED while waiting on a full per-replica pool, but establishConnectionsSync still catches ... and demotes every failure to "replica unavailable". With use_hedged_requests = 0, a killed or timed-out query can therefore fall back to local distributed-index analysis work instead of aborting at the connection-establish boundary. Suggested fix: before incrementing DistributedIndexAnalysisReplicaUnavailable, rethrow cancellation/time-limit exceptions (or call CurrentThread::checkIfNotCancelled() there), matching the later remote-analysis phase that already preserves QUERY_WAS_CANCELLED.
Final Verdict

Changes requested: preserve query-cancellation and time-limit exceptions in the sync distributed-index-analysis connection-establish path.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 130/134 (97.01%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 8, 2026
Comment thread src/Common/PoolBase.h
/// 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();

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.

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?

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4b266c403 with master d33f21163 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of ab19f7494; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 711.27 MiB 708.22 MiB -3.05 MiB (-0.43%)

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

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dfc10b2

CI is complete on this head with no failures: Finish Workflow is green and every
check reports success or skipped. The only non-terminal context is CH Inc sync
(private, not actionable by me).

Check / test Reason Owner / fixing PR
- no failures on this head -
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260809-033000

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to clear a conflict. Both sides of it were mine, so the resolution is a semantic
choice worth stating rather than a mechanical one: master now carries the shared
saturatedMilliseconds() clamp that #106961 added to this same line, while this branch rewrites
the wait into deadline-bounded slices.

I kept the slice loop, since taking master's plain wait_for back would restore exactly the defect
this PR fixes, and dropped this branch's own max_wait_ms constant in favour of
saturatedMilliseconds(), so the deadline uses the same overflow clamp as every other
user-controlled wait_for site. The cap goes from ~146 years to one year; both are far longer than
any caller can wait out, and timeout < 0 still means infinite because has_deadline is evaluated
before the clamp. Net change against the previous head is one include, one rewritten line, and the
deleted constant.

Verified on the merged tree: PoolBase.* and the saturated* suites pass 19/19 with timings
unchanged, and the full unit suite is 23313 passed / 0 failed. To confirm the swapped clamp is
actually covered rather than merely green, I removed it and rebuilt: PoolBase.hugeTimeoutDoesNotWrap
then fails with NO_FREE_CONNECTION, and nothing else does.

Three unit tests abort on this tree but do so identically on a build of unrelated work that contains
none of this branch's code, so they are pre-existing and not from this merge:
ReadBufferFromS3Test.IterateUsesStartAfter, ReadBufferFromS3Test.IterateUsesStartAfterOnlyForFirstPage
(both client_configuration.retryStrategy at IO/S3/Client.cpp:789) and
UniqueKeyProbeTest.NewestLiveWinsOverOlder. This PR touches no file under src/IO or src/Disks,
and PoolBase.h is not in those tests' include graph.

…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the flaky-check timeout on fa0f499 (04659, amd_asan_ubsan)

One run of the changed test timed out at 600120 ms while the other 33 runs of the same job took 69.8 to 87.2 s. It was a hang, not slowness.

Root cause. query_log shows the finite arm working correctly: its waiter gave up on its own 500 ms deadline after 1739 ms with ALL_CONNECTION_TRIES_FAILED, which is what that arm asserts. The script missed it. The overlap check polled system.processes for both queries at once, and one poll spawns a clickhouse-client, which costs about 2 s under ASan. The poll period was therefore longer than the 1.74 s window it was sampling, and once the waiter had exited the count could never reach 2 again. The loop's bound is 600 iterations rather than a duration, so at 2 s each it runs about 1200 s and the 600 s per-test timeout fired first. The zero arm was never exposed to this: its waiter blocks until something frees the connection, so the overlap is observable at any granularity.

Change (test only, no production code, no reference row weakened):

  • Polls are bounded by wall clock instead of iteration count, so a condition that can no longer hold is reported inside the budget instead of hanging.
  • The arms whose waiter ends by itself no longer sample for a transient overlap. They wait for the waiter, then assert the holder is still holding.
  • All three cancellation arms now also assert the pool wait they accumulated (ConnectionPoolIsFullMicroseconds), which stays readable after the waiter is gone. That is the new fourth reference column.

Validation. Locally a poll costs 0.08 s, so the CI condition cannot arise on its own; I injected the sanitizer's client startup cost to make it deterministic.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Master merge, head 4b266c40365a1ff

The conflict was structural rather than textual. The silk integration (#112667) moved Entry out of PoolBase into a standalone PoolEntry, added the TLocker/TWaiter template parameters, replaced the PooledObject back-reference with an on_destroy callback built by a new makeEntry, and dropped Entry::getPool. All of that is kept verbatim: the resolved src/Common/PoolBase.h differs from master by exactly this branch's change and nothing else. Master's side of the wait block could not be taken, since it is a single wait_for with no deadline re-check, which is the defect this branch fixes.

One consequence is worth flagging. TWaiter is no longer always std::condition_variable: Silk::FiberCondVarAdapter provides only a two-argument wait_for, and Silk::ConnectionPool instantiates it. The wait therefore calls the two-argument form and tests the predicate itself; restoring the three-argument form fails the build with no matching member function for call to 'wait_for' in gtest_silk_connection_pool.cpp. The clamped millisecond value is now computed once and used for the deadline, the log line and the NO_FREE_CONNECTION message, so the message states the wait that actually applied.

Verified on the merged tree with the running server's buildId asserted equal to the binary: 20 of 20 unit arms pass, including the silk fiber pool test that exercises the new instantiation, and 04659 passes 3 of 3 byte-identical to its reference. Bypassing the clamp reddens PoolBase.hugeTimeoutDoesNotWrap and nothing else. Neither test file changed in this round.

I also corrected the changelog entry, which promised interruption by max_execution_time unconditionally; the setting documentation was narrowed to the default timeout_overflow_mode = 'throw' in an earlier round and the changelog was missed.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Good change, thanks!

@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 3, 2026
Merged via the queue into ClickHouse:master with commit 95f0e9f Sep 3, 2026
354 of 355 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 3, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Verified on master and answered in #120832: the finding is real and it is this PR's. NO_FREE_CONNECTION from a full local pool is classified as an unavailable replica, so with skip_unavailable_shards = 1 a healthy shard's rows are dropped silently. Measured: two shards, only the first one's pool held, SELECT sum(number), count() returns 45 10 instead of 90 20 with exit code 0.

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 ConnectionEstablisher::run. Fix PR to follow, linked from #120832.

middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Sep 19, 2026
… 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
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 groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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